diff --git a/lib/api/category/one.test.ts b/lib/api/category/one.test.ts index e865a889e..4ed00ee1f 100644 --- a/lib/api/category/one.test.ts +++ b/lib/api/category/one.test.ts @@ -1,8 +1,11 @@ +import type { Next } from 'hono'; import { describe, expect, it } from 'vitest'; import { handler, route } from '@/api/category/one'; import { namespaces } from '@/registry'; +const noopNext: Next = () => Promise.resolve(); + const createCtx = (param: Record, query: Record = {}) => ({ req: { @@ -27,11 +30,11 @@ const findCategory = (requireLang = false) => { }; describe('api/category/one', () => { - it('returns namespaces that match a category', () => { + it('returns namespaces that match a category', async () => { const { categories } = findCategory(); const category = categories[0]; - const result = handler(createCtx({ category }, {})); + const result = await handler(createCtx({ category }, {}), noopNext); expect(Object.keys(result)).not.toHaveLength(0); for (const namespace of Object.values(result)) { @@ -41,19 +44,20 @@ describe('api/category/one', () => { } }); - it('intersects categories and filters by lang', () => { + it('intersects categories and filters by lang', async () => { const { namespace, categories, lang } = findCategory(true); const [primary, secondary] = categories.length > 1 ? categories : [categories[0], categories[0]]; const selectedLang = lang || namespaces[namespace].lang; - const result = handler( + const result = await handler( createCtx( { category: primary }, { categories: [secondary], lang: selectedLang, } - ) + ), + noopNext ); expect(Object.keys(result)).toContain(namespace); @@ -68,8 +72,8 @@ describe('api/category/one', () => { expect(parsed?.lang).toBe('en'); }); - it('returns empty result for unknown categories', () => { - const result = handler(createCtx({ category: 'rsshub-unknown-category' }, {})); + it('returns empty result for unknown categories', async () => { + const result = await handler(createCtx({ category: 'rsshub-unknown-category' }, {}), noopNext); expect(result).toEqual({}); }); }); diff --git a/lib/api/category/one.ts b/lib/api/category/one.ts index 60fb290c3..b47456e50 100644 --- a/lib/api/category/one.ts +++ b/lib/api/category/one.ts @@ -1,30 +1,40 @@ import type { RouteHandler } from '@hono/zod-openapi'; import { createRoute, z } from '@hono/zod-openapi'; -import { namespaces } from '@/registry'; +import { ensureAllLoaded, namespaces } from '@/registry'; -const categoryList: Record = {}; +let cachedCategoryList: Record | undefined; -for (const namespace in namespaces) { - for (const path in namespaces[namespace].routes) { - if (!namespaces[namespace].routes[path].categories?.length) { - continue; - } - const categories = namespaces[namespace].routes[path].categories!; - for (const category of categories) { - if (!Object.hasOwn(categoryList, category)) { - categoryList[category] = {}; +const getCategoryList = async (): Promise> => { + if (cachedCategoryList) { + return cachedCategoryList; + } + await ensureAllLoaded(); + + const list: Record = {}; + for (const namespace in namespaces) { + for (const path in namespaces[namespace].routes) { + if (!namespaces[namespace].routes[path].categories?.length) { + continue; } - if (!Object.hasOwn(categoryList[category], namespace)) { - categoryList[category][namespace] = { - ...namespaces[namespace], - routes: {}, - }; + const categories = namespaces[namespace].routes[path].categories!; + for (const category of categories) { + if (!Object.hasOwn(list, category)) { + list[category] = {}; + } + if (!Object.hasOwn(list[category], namespace)) { + list[category][namespace] = { + ...namespaces[namespace], + routes: {}, + }; + } + list[category][namespace].routes[path] = namespaces[namespace].routes[path]; } - categoryList[category][namespace].routes[path] = namespaces[namespace].routes[path]; } } -} + cachedCategoryList = list; + return cachedCategoryList; +}; const ParamsSchema = z.object({ category: z.string().openapi({ @@ -60,7 +70,8 @@ const route = createRoute({ }, }); -const handler: RouteHandler = (ctx) => { +const handler: RouteHandler = async (ctx) => { + const categoryList = await getCategoryList(); const { categories, lang } = ctx.req.valid('query'); const { category } = ctx.req.valid('param'); diff --git a/lib/api/namespace.test.ts b/lib/api/namespace.test.ts index d1d318ab2..fd586ac1d 100644 --- a/lib/api/namespace.test.ts +++ b/lib/api/namespace.test.ts @@ -1,3 +1,4 @@ +import type { Next } from 'hono'; import { describe, expect, it } from 'vitest'; import api from '@/api'; @@ -5,6 +6,8 @@ import { handler as allHandler } from '@/api/namespace/all'; import { handler as oneHandler } from '@/api/namespace/one'; import { namespaces } from '@/registry'; +const noopNext: Next = () => Promise.resolve(); + const createCtx = (param: Record = {}) => ({ req: { @@ -16,20 +19,20 @@ const createCtx = (param: Record = {}) => describe('api/namespace', () => { const nestedKey = Object.keys(namespaces).find((key) => key.includes('/')) as string; - it('returns all namespaces', () => { - const result = allHandler(createCtx()); + it('returns all namespaces', async () => { + const result = await allHandler(createCtx(), noopNext); expect(result).toBe(namespaces); }); - it('returns a single namespace', () => { - const result = oneHandler(createCtx({ namespace: 'test' })); + it('returns a single namespace', async () => { + const result = await oneHandler(createCtx({ namespace: 'test' }), noopNext); expect(result).toBe(namespaces.test); }); - it('returns a nested namespace', () => { + it('returns a nested namespace', async () => { expect(nestedKey).toBeDefined(); const [namespace, sub] = nestedKey.split('/'); - const result = oneHandler(createCtx({ namespace, sub })); + const result = await oneHandler(createCtx({ namespace, sub }), noopNext); expect(result).toBe(namespaces[nestedKey]); }); diff --git a/lib/api/namespace/all.ts b/lib/api/namespace/all.ts index ac104b3f5..6fe43203b 100644 --- a/lib/api/namespace/all.ts +++ b/lib/api/namespace/all.ts @@ -1,7 +1,7 @@ import type { RouteHandler } from '@hono/zod-openapi'; import { createRoute } from '@hono/zod-openapi'; -import { namespaces } from '@/registry'; +import { ensureAllLoaded, namespaces } from '@/registry'; const route = createRoute({ method: 'get', @@ -15,6 +15,9 @@ const route = createRoute({ }, }); -const handler: RouteHandler = (ctx) => ctx.json(namespaces); +const handler: RouteHandler = async (ctx) => { + await ensureAllLoaded(); + return ctx.json(namespaces); +}; export { handler, route }; diff --git a/lib/api/namespace/one.ts b/lib/api/namespace/one.ts index 9c9252a97..2db466f12 100644 --- a/lib/api/namespace/one.ts +++ b/lib/api/namespace/one.ts @@ -1,7 +1,7 @@ import type { RouteHandler } from '@hono/zod-openapi'; import { createRoute, z } from '@hono/zod-openapi'; -import { namespaces } from '@/registry'; +import { ensureAllLoaded, namespaces } from '@/registry'; const pathParam = (name: string, example: string) => z.string().openapi({ @@ -46,7 +46,8 @@ const routeNested = createRoute({ }, }); -const handler: RouteHandler = (ctx) => { +const handler: RouteHandler = async (ctx) => { + await ensureAllLoaded(); const { namespace, sub } = ctx.req.valid('param') as { namespace: string; sub?: string }; return ctx.json(namespaces[[namespace, sub].filter(Boolean).join('/')]); }; diff --git a/lib/api/radar/rules/all.ts b/lib/api/radar/rules/all.ts index e8136063a..dba4185dd 100644 --- a/lib/api/radar/rules/all.ts +++ b/lib/api/radar/rules/all.ts @@ -1,46 +1,7 @@ import type { RouteHandler } from '@hono/zod-openapi'; import { createRoute } from '@hono/zod-openapi'; -import { parse } from 'tldts'; -import { namespaces } from '@/registry'; -import type { RadarDomain } from '@/types'; - -const radar: { - [domain: string]: RadarDomain; -} = {}; - -for (const namespace in namespaces) { - for (const path in namespaces[namespace].routes) { - const realPath = `/${namespace}${path}`; - const data = namespaces[namespace].routes[path]; - if (data.radar?.length) { - for (const radarItem of data.radar) { - const parsedDomain = parse(new URL('https://' + radarItem.source[0]).hostname); - const subdomain = parsedDomain.subdomain || '.'; - const domain = parsedDomain.domain; - if (domain) { - if (!Object.hasOwn(radar, domain)) { - radar[domain] = { - _name: namespaces[namespace].name, - } as RadarDomain; - } - if (!Object.hasOwn(radar[domain], subdomain)) { - radar[domain][subdomain] = []; - } - radar[domain][subdomain].push({ - title: radarItem.title || data.name, - docs: `https://docs.rsshub.app/routes/${data.categories?.[0] || 'other'}`, - source: radarItem.source.map((source) => { - const sourceURL = new URL('https://' + source); - return sourceURL.pathname + sourceURL.search + sourceURL.hash; - }), - target: radarItem.target ? `/${namespace}${radarItem.target}` : realPath, - }); - } - } - } - } -} +import { getRadarRules } from './utils'; const route = createRoute({ method: 'get', @@ -54,6 +15,9 @@ const route = createRoute({ }, }); -const handler: RouteHandler = (ctx) => ctx.json(radar); +const handler: RouteHandler = async (ctx) => { + const rules = await getRadarRules(); + return ctx.json(rules); +}; export { handler, route }; diff --git a/lib/api/radar/rules/one.test.ts b/lib/api/radar/rules/one.test.ts index dee4403c0..e5afe4abb 100644 --- a/lib/api/radar/rules/one.test.ts +++ b/lib/api/radar/rules/one.test.ts @@ -1,9 +1,12 @@ +import type { Next } from 'hono'; import { describe, expect, it, vi } from 'vitest'; import { handler } from '@/api/radar/rules/one'; +const noopNext: Next = () => Promise.resolve(); + describe('api/radar/rules/one', () => { - it('returns radar data for a domain param', () => { + it('returns radar data for a domain param', async () => { const ctx = { req: { valid: vi.fn(() => ({ domain: 'unknown.invalid' })), @@ -11,7 +14,7 @@ describe('api/radar/rules/one', () => { json: vi.fn((value) => value), }; - const result = handler(ctx as any); + const result = await handler(ctx as any, noopNext); expect(ctx.req.valid).toHaveBeenCalledWith('param'); expect(ctx.json).toHaveBeenCalledWith(undefined); diff --git a/lib/api/radar/rules/one.ts b/lib/api/radar/rules/one.ts index 1a28f117b..3e2f75c04 100644 --- a/lib/api/radar/rules/one.ts +++ b/lib/api/radar/rules/one.ts @@ -1,46 +1,7 @@ import type { RouteHandler } from '@hono/zod-openapi'; import { createRoute, z } from '@hono/zod-openapi'; -import { parse } from 'tldts'; -import { namespaces } from '@/registry'; -import type { RadarDomain } from '@/types'; - -const radar: { - [domain: string]: RadarDomain; -} = {}; - -for (const namespace in namespaces) { - for (const path in namespaces[namespace].routes) { - const realPath = `/${namespace}${path}`; - const data = namespaces[namespace].routes[path]; - if (data.radar?.length) { - for (const radarItem of data.radar) { - const parsedDomain = parse(new URL('https://' + radarItem.source[0]).hostname); - const subdomain = parsedDomain.subdomain || '.'; - const domain = parsedDomain.domain; - if (domain) { - if (!Object.hasOwn(radar, domain)) { - radar[domain] = { - _name: namespaces[namespace].name, - } as RadarDomain; - } - if (!Object.hasOwn(radar[domain], subdomain)) { - radar[domain][subdomain] = []; - } - radar[domain][subdomain].push({ - title: radarItem.title || data.name, - docs: `https://docs.rsshub.app/routes/${data.categories?.[0] || 'other'}`, - source: radarItem.source.map((source) => { - const sourceURL = new URL('https://' + source); - return sourceURL.pathname + sourceURL.search + sourceURL.hash; - }), - target: radarItem.target ? `/${namespace}${radarItem.target}` : realPath, - }); - } - } - } - } -} +import { getRadarRules } from './utils'; const ParamsSchema = z.object({ domain: z.string().openapi({ @@ -67,9 +28,10 @@ const route = createRoute({ }, }); -const handler: RouteHandler = (ctx) => { +const handler: RouteHandler = async (ctx) => { const { domain } = ctx.req.valid('param'); - return ctx.json(radar[domain]); + const rules = await getRadarRules(); + return ctx.json(rules[domain]); }; export { handler, route }; diff --git a/lib/api/radar/rules/utils.ts b/lib/api/radar/rules/utils.ts new file mode 100644 index 000000000..7291c2816 --- /dev/null +++ b/lib/api/radar/rules/utils.ts @@ -0,0 +1,49 @@ +import { parse } from 'tldts'; + +import { ensureAllLoaded, namespaces } from '@/registry'; +import type { RadarDomain } from '@/types'; + +let radar: Record | undefined; + +export const getRadarRules = async (): Promise> => { + if (radar) { + return radar; + } + await ensureAllLoaded(); + + const rules: Record = {}; + for (const namespace in namespaces) { + for (const path in namespaces[namespace].routes) { + const realPath = `/${namespace}${path}`; + const data = namespaces[namespace].routes[path]; + if (data.radar?.length) { + for (const radarItem of data.radar) { + const parsedDomain = parse(new URL('https://' + radarItem.source[0]).hostname); + const subdomain = parsedDomain.subdomain || '.'; + const domain = parsedDomain.domain; + if (domain) { + if (!Object.hasOwn(rules, domain)) { + rules[domain] = { + _name: namespaces[namespace].name, + } as RadarDomain; + } + if (!Object.hasOwn(rules[domain], subdomain)) { + rules[domain][subdomain] = []; + } + rules[domain][subdomain].push({ + title: radarItem.title || data.name, + docs: `https://docs.rsshub.app/routes/${data.categories?.[0] || 'other'}`, + source: radarItem.source.map((source) => { + const sourceURL = new URL('https://' + source); + return sourceURL.pathname + sourceURL.search + sourceURL.hash; + }), + target: radarItem.target ? `/${namespace}${radarItem.target}` : realPath, + }); + } + } + } + } + } + radar = rules; + return radar; +}; diff --git a/lib/api/route/status.ts b/lib/api/route/status.ts index f7b2e1ca0..bcc44f563 100644 --- a/lib/api/route/status.ts +++ b/lib/api/route/status.ts @@ -4,6 +4,8 @@ import xxhash from 'xxhash-wasm'; import cacheModule from '@/utils/cache/index'; +const { h64ToString } = await xxhash(); + const QuerySchema = z.object({ requestPath: z.string().openapi({ param: { @@ -62,7 +64,6 @@ const handler: RouteHandler = async (ctx) => { } const { requestPath } = ctx.req.valid('query'); - const { h64ToString } = await xxhash(); const key = 'rsshub:koa-redis-cache:' + h64ToString(requestPath + ':rss'); const cached = await cacheModule.globalCache.has(key); diff --git a/lib/errors/index.tsx b/lib/errors/index.tsx index 5ad01a336..cd79d2ce7 100644 --- a/lib/errors/index.tsx +++ b/lib/errors/index.tsx @@ -54,7 +54,7 @@ export const errorHandler: ErrorHandler = (error, ctx) => { } let errorMessage = (process.env.NODE_ENV || process.env.VERCEL_ENV) === 'production' ? error.message : error.stack || error.message; - switch (error.constructor.name) { + switch (error.name) { case 'HTTPError': case 'RequestError': case 'FetchError': diff --git a/lib/middleware/cache-error.test.ts b/lib/middleware/cache-error.test.ts index bd852af32..3d7e80406 100644 --- a/lib/middleware/cache-error.test.ts +++ b/lib/middleware/cache-error.test.ts @@ -16,6 +16,7 @@ vi.mock('@/utils/cache/index', () => ({ globalCache: { get: getSpy, set: setSpy, + claim: vi.fn(() => true), }, }, })); diff --git a/lib/middleware/cache.ts b/lib/middleware/cache.ts index 3deaa14da..fe5acf34d 100644 --- a/lib/middleware/cache.ts +++ b/lib/middleware/cache.ts @@ -7,6 +7,8 @@ import type { Data } from '@/types'; import cacheModule from '@/utils/cache/index'; const bypassList = new Set(['/', '/robots.txt', '/logo.png', '/favicon.ico']); + +const { h64ToString } = await xxhash(); // only give cache string, as the `!` condition tricky // XXH64 is used to shrink key size // plz, write these tips in comments! @@ -19,13 +21,18 @@ const middleware: MiddlewareHandler = async (ctx, next) => { const requestPath = ctx.req.path; const format = `:${ctx.req.query('format') || 'rss'}`; const limit = ctx.req.query('limit') ? `:${ctx.req.query('limit')}` : ''; - const { h64ToString } = await xxhash(); const key = 'rsshub:koa-redis-cache:' + h64ToString(requestPath + format + limit); const controlKey = 'rsshub:path-requested:' + h64ToString(requestPath + format + limit); - const isRequesting = await cacheModule.globalCache.get(controlKey); + let value = await cacheModule.globalCache.get(key); - if (isRequesting === '1') { + // Doesn't hit the cache? Try to become the fetcher and let others know! + let isRequesting = false; + if (!value) { + isRequesting = !(await cacheModule.globalCache.claim(controlKey, config.cache.requestTimeout)); + } + + if (isRequesting) { let retryTimes = process.env.NODE_ENV === 'test' ? 1 : 10; let bypass = false; while (retryTimes > 0) { @@ -41,10 +48,9 @@ const middleware: MiddlewareHandler = async (ctx, next) => { if (!bypass) { throw new RequestInProgressError('This path is currently fetching, please come back later!'); } + value = await cacheModule.globalCache.get(key); } - const value = await cacheModule.globalCache.get(key); - if (value) { ctx.status(200); ctx.header('RSSHub-Cache-Status', 'HIT'); @@ -53,8 +59,10 @@ const middleware: MiddlewareHandler = async (ctx, next) => { return; } - // Doesn't hit the cache? We need to let others know! - await cacheModule.globalCache.set(controlKey, '1', config.cache.requestTimeout); + if (isRequesting) { + // waited out a stale claim without finding a cache entry, take over the fetch + await cacheModule.globalCache.set(controlKey, '1', config.cache.requestTimeout); + } // let routers control cache ctx.set('cacheKey', key); diff --git a/lib/middleware/parameter.ts b/lib/middleware/parameter.ts index ce7780cf2..5dbad3d65 100644 --- a/lib/middleware/parameter.ts +++ b/lib/middleware/parameter.ts @@ -1,4 +1,3 @@ -import Parser from '@jocmp/mercury-parser'; import type { CheerioAPI } from 'cheerio'; import { load } from 'cheerio'; import type { Element } from 'domhandler'; @@ -309,6 +308,7 @@ const middleware: MiddlewareHandler = async (ctx, next) => { if (link) { // if parser failed, return default description and not report error try { + const { default: Parser } = await import('@jocmp/mercury-parser'); const res = await ofetch(link); const $ = load(res); const result = await Parser.parse(link, { diff --git a/lib/registry-dev.test.ts b/lib/registry-dev.test.ts new file mode 100644 index 000000000..ec589f284 --- /dev/null +++ b/lib/registry-dev.test.ts @@ -0,0 +1,217 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { Hono } from 'hono'; +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createDevRegistry } from '@/registry-dev'; +import type { NamespacesType } from '@/registry-helpers'; + +const directoryImportMock = vi.hoisted(() => vi.fn()); + +vi.mock('@/utils/directory-import', () => ({ + directoryImport: directoryImportMock, +})); + +// Fake route modules keyed by top-level directory; inner keys are relative to that directory, +// matching what directoryImport returns for a scoped import. +const fakeDirectories: Record> = { + flat: { + '/single.ts': { + route: { + path: '/single', + name: 'Single', + handler: () => ({ title: 'flat-single', link: 'https://example.com', item: [], allowEmpty: true }), + }, + }, + '/param.ts': { + route: { + path: '/:id', + name: 'Param', + handler: (ctx) => ({ title: `param-${ctx.req.param('id')}`, link: 'https://example.com', item: [], allowEmpty: true }), + }, + }, + '/outer.ts': { + route: { + path: '/outer', + name: 'Outer', + handler: (ctx) => ({ title: String(ctx.get('fromOuter')), link: 'https://example.com', item: [], allowEmpty: true }), + }, + }, + '/boom.ts': { + route: { + path: '/boom', + name: 'Boom', + handler: () => { + throw new Error('handler-boom'); + }, + }, + }, + }, + github: { + '/namespace.ts': { namespace: { name: 'GitHub' } }, + '/enterprise/namespace.ts': { namespace: { name: 'GitHub Enterprise' } }, + '/enterprise/news.ts': { + route: { + path: '/news', + name: 'News', + handler: () => ({ title: 'github-enterprise-news', link: 'https://example.com', item: [], allowEmpty: true }), + }, + }, + }, + withapi: { + '/api.ts': { + apiRoute: { + path: '/ping', + name: 'Ping', + handler: () => ({ ok: true }), + }, + }, + }, +}; + +const mockImplementation = ({ targetDirectoryPath }: { targetDirectoryPath: string }) => { + const name = targetDirectoryPath.split(/[/\\]/).findLast(Boolean) as string; + return Promise.resolve(fakeDirectories[name]); +}; + +// The registry lists real directories at startup; module contents come from the mocked importer +const routesDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'rsshub-dev-registry-')); +for (const name of Object.keys(fakeDirectories)) { + fs.mkdirSync(path.join(routesDirectory, name)); +} +afterAll(() => { + fs.rmSync(routesDirectory, { recursive: true, force: true }); +}); + +const buildApp = () => { + const namespaces: NamespacesType = {}; + const dev = createDevRegistry({ routesDirectory, namespaces }); + const app = new Hono(); + app.use(async (ctx, next) => { + ctx.set('fromOuter', 'bridged'); + await next(); + const apiData = ctx.get('apiData'); + if (apiData) { + return ctx.json(apiData); + } + const data = ctx.get('data'); + if (data) { + return ctx.json(data); + } + }); + app.use('*', dev.middleware); + app.get('/static', (ctx) => ctx.text('static-ok')); + return { app, dev, namespaces }; +}; + +describe('createDevRegistry', () => { + beforeEach(() => { + directoryImportMock.mockReset().mockImplementation(mockImplementation); + }); + + it('imports nothing at startup', () => { + buildApp(); + expect(directoryImportMock).not.toHaveBeenCalled(); + }); + + it('loads a namespace on first request and serves its routes', async () => { + const { app } = buildApp(); + const response = await app.request('/flat/single'); + expect(response.status).toBe(200); + const body = await response.json(); + expect(body.title).toBe('flat-single'); + expect(directoryImportMock).toHaveBeenCalledTimes(1); + }); + + it('imports each top directory at most once', async () => { + const { app } = buildApp(); + await app.request('/flat/single'); + const second = await app.request('/flat/abc'); + const body = await second.json(); + expect(body.title).toBe('param-abc'); + expect(directoryImportMock).toHaveBeenCalledTimes(1); + }); + + it('bridges outer context vars into route handlers', async () => { + const { app } = buildApp(); + const response = await app.request('/flat/outer'); + const body = await response.json(); + expect(body.title).toBe('bridged'); + }); + + it('serves nested namespaces', async () => { + const { app } = buildApp(); + const response = await app.request('/github/enterprise/news'); + const body = await response.json(); + expect(body.title).toBe('github-enterprise-news'); + }); + + it('serves api routes under /api', async () => { + const { app } = buildApp(); + const response = await app.request('/api/withapi/ping'); + const body = await response.json(); + expect(body).toEqual({ ok: true }); + }); + + it('falls through for unknown directories without touching the importer', async () => { + const { app } = buildApp(); + const first = await app.request('/static'); + const body = await first.text(); + expect(body).toBe('static-ok'); + await app.request('/static'); + expect(directoryImportMock).not.toHaveBeenCalled(); + }); + + it('returns 404 for unmatched paths inside a loaded namespace', async () => { + const { app } = buildApp(); + const response = await app.request('/withapi/nope'); + expect(response.status).toBe(404); + }); + + it('populates the shared namespaces object', async () => { + const { app, namespaces } = buildApp(); + await app.request('/github/enterprise/news'); + expect(namespaces['github/enterprise'].routes['/news']).toBeDefined(); + }); + + it('propagates route handler errors to the outer error handler', async () => { + const { app } = buildApp(); + let seen: unknown = null; + app.onError((error, ctx) => { + seen = error; + return ctx.text('outer-handled', 503); + }); + const response = await app.request('/flat/boom'); + expect((seen as Error)?.message).toBe('handler-boom'); + expect(response.status).toBe(503); + const body = await response.text(); + expect(body).toBe('outer-handled'); + }); + + it('retries a directory whose import failed', async () => { + const { app } = buildApp(); + directoryImportMock.mockRejectedValueOnce(new Error('boom')); + const first = await app.request('/flat/single'); + expect(first.status).toBe(500); + const second = await app.request('/flat/single'); + expect(second.status).toBe(200); + }); + + it('ensureAllLoaded imports every top-level directory', async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'rsshub-dev-registry-')); + try { + fs.mkdirSync(path.join(tmp, 'flat')); + fs.mkdirSync(path.join(tmp, 'github')); + fs.writeFileSync(path.join(tmp, 'not-a-dir.ts'), ''); + const namespaces: NamespacesType = {}; + const dev = createDevRegistry({ routesDirectory: tmp, namespaces }); + await dev.ensureAllLoaded(); + expect(directoryImportMock).toHaveBeenCalledTimes(2); + expect(Object.keys(namespaces).toSorted((a, b) => a.localeCompare(b))).toEqual(['flat', 'github', 'github/enterprise']); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/lib/registry-dev.ts b/lib/registry-dev.ts new file mode 100644 index 000000000..98cf818a6 --- /dev/null +++ b/lib/registry-dev.ts @@ -0,0 +1,126 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import type { Context, MiddlewareHandler } from 'hono'; +import { Hono } from 'hono'; + +import type { ModulesType, NamespacesType } from '@/registry-helpers'; +import { applyModulesToNamespaces, registerApiRoutes, registerRssRoutes } from '@/registry-helpers'; +import { directoryImport } from '@/utils/directory-import'; + +export type DevRegistry = { + middleware: MiddlewareHandler; + ensureAllLoaded: () => Promise; +}; + +/** + * Dev-only lazy route loading. Hono routers reject new routes once an app has matched a request + * ("matcher is already built"), so each top-level routes directory gets its own self-contained + * sub-app, built on first request and dispatched from the middleware. + */ +export function createDevRegistry({ routesDirectory, namespaces }: { routesDirectory: string; namespaces: NamespacesType }): DevRegistry { + const subApps = new Map>(); + const outerContexts = new WeakMap(); + + // One readdir at startup replaces per-request fs probing (and doubles as the path-safety check); + // a top-level directory added at runtime needs a restart, which tsx watch does on any save anyway. + const topDirectories = new Set( + fs + .readdirSync(routesDirectory, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + ); + + // Sub-apps run on a fresh context; copy the outer vars in so handlers see middleware state + // (e.g. parameters), and copy back out so ctx.set('data') reaches the upstream template middleware. + const bridge: MiddlewareHandler = async (ctx, next) => { + const outer = outerContexts.get(ctx.req.raw); + if (outer) { + for (const [key, value] of Object.entries(outer.var)) { + ctx.set(key as never, value as never); + } + } + await next(); + if (outer) { + for (const [key, value] of Object.entries(ctx.var)) { + outer.set(key as never, value as never); + } + } + const vars = ctx.var as Record; + if (!ctx.finalized && (vars.data || vars.apiData)) { + // Data-producing handlers return undefined (the outer template middleware renders the + // bridged vars); finalize so Hono does not raise "Context is not finalized". + ctx.res = new Response(null, { status: 204 }); + } + }; + + const loadTopDirectory = async (name: string): Promise => { + const modules = (await directoryImport({ + targetDirectoryPath: path.join(routesDirectory, name), + importPattern: /\.tsx?$/, + })) as ModulesType; + + // directoryImport keys are relative to the imported directory; restore the lib/routes-relative form + const prefixed: ModulesType = {}; + for (const key in modules) { + prefixed[`/${name}${key}`] = modules[key]; + } + applyModulesToNamespaces(prefixed, namespaces); + + const subApp = new Hono(); + // Rethrow so subApp.fetch rejects and handler errors reach the outer app's error handler + // instead of Hono's bare text-500 default. + subApp.onError((error) => { + throw error; + }); + subApp.use('*', bridge); + const subset = Object.fromEntries(Object.entries(namespaces).filter(([key]) => key === name || key.startsWith(`${name}/`))); + registerRssRoutes(subApp, subset); + registerApiRoutes(subApp, subset); + return subApp; + }; + + const ensureTopDirectory = async (name: string): Promise => { + let promise = subApps.get(name); + if (!promise) { + promise = loadTopDirectory(name); + subApps.set(name, promise); + } + try { + return await promise; + } catch (error) { + // Import errors are not memoized so a fixed file works on the next request + subApps.delete(name); + throw error; + } + }; + + const middleware: MiddlewareHandler = async (ctx, next) => { + const segments = ctx.req.path.split('/').filter(Boolean); + const candidate = segments[0] === 'api' ? segments[1] : segments[0]; + if (!candidate || !topDirectories.has(candidate)) { + return next(); + } + const subApp = await ensureTopDirectory(candidate); + outerContexts.set(ctx.req.raw, ctx); + try { + const response = await subApp.fetch(ctx.req.raw); + if (ctx.get('data') || ctx.get('apiData')) { + // The upstream template middleware renders from the bridged vars + return; + } + if (response.status === 404) { + return next(); + } + return response; + } finally { + outerContexts.delete(ctx.req.raw); + } + }; + + const ensureAllLoaded = async (): Promise => { + await Promise.all([...topDirectories].map((name) => ensureTopDirectory(name))); + }; + + return { middleware, ensureAllLoaded }; +} diff --git a/lib/registry-helpers.ts b/lib/registry-helpers.ts new file mode 100644 index 000000000..a4c4b81ee --- /dev/null +++ b/lib/registry-helpers.ts @@ -0,0 +1,237 @@ +import type { Handler, Hono } from 'hono'; +import { routePath } from 'hono/route'; + +import type { APIRoute, Namespace, Route } from '@/types'; +import logger from '@/utils/logger'; + +const SEPARATOR = /[/\\]/; + +export type RoutesType = Record< + string, + Route & { + location: string; + } +>; + +export type NamespacesType = Record< + string, + Namespace & { + routes: RoutesType; + apiRoutes: Record< + string, + APIRoute & { + location: string; + } + >; + } +>; + +export type ModulesType = Record; + +/** + * A directory under lib/routes that contains a `namespace.ts` is a "namespace root". Roots are keyed by their path + * relative to lib/routes, joined with `/` (e.g. `github/enterprise`). + */ +export function collectNamespaceRoots(moduleKeys: string[]): Set { + const roots = new Set(); + for (const key of moduleKeys) { + const segments = key.split(SEPARATOR).filter(Boolean); + if (segments.at(-1) === 'namespace.ts') { + roots.add(segments.slice(0, -1).join('/')); + } + } + return roots; +} + +/** + * A module belongs to its longest matching namespace root; modules with no matching root fall back to their first + * path segment (flat namespaces). `location` is the module path relative to the resolved namespace root. + */ +export function resolveModuleNamespace(moduleKey: string, roots: Set): { namespace: string; location: string } { + const segments = moduleKey.split(SEPARATOR).filter(Boolean); + for (let i = segments.length - 1; i >= 1; i--) { + const candidate = segments.slice(0, i).join('/'); + if (roots.has(candidate)) { + return { namespace: candidate, location: segments.slice(i).join('/') }; + } + } + return { namespace: segments[0], location: segments.slice(1).join('/') }; +} + +/** + * Merge directory-imported modules into `namespaces` (mutated in place). Module keys must be relative to + * lib/routes (e.g. `/github/enterprise/news.ts`). + */ +export function applyModulesToNamespaces(modules: ModulesType, namespaces: NamespacesType): void { + const namespaceRoots = collectNamespaceRoots(Object.keys(modules)); + for (const module in modules) { + const content = modules[module]; + const { namespace, location } = resolveModuleNamespace(module, namespaceRoots); + if ('namespace' in content) { + namespaces[namespace] = Object.assign( + { + routes: {}, + apiRoutes: {}, + }, + namespaces[namespace], + content.namespace + ); + } else if ('route' in content) { + if (!Object.hasOwn(namespaces, namespace)) { + namespaces[namespace] = { + name: namespace, + routes: {}, + apiRoutes: {}, + }; + } + if (Array.isArray(content.route.path)) { + for (const path of content.route.path) { + namespaces[namespace].routes[path] = { + ...content.route, + location, + }; + } + } else { + namespaces[namespace].routes[content.route.path] = { + ...content.route, + location, + }; + } + } else if ('apiRoute' in content) { + if (!Object.hasOwn(namespaces, namespace)) { + namespaces[namespace] = { + name: namespace, + routes: {}, + apiRoutes: {}, + }; + } + if (Array.isArray(content.apiRoute.path)) { + for (const path of content.apiRoute.path) { + namespaces[namespace].apiRoutes[path] = { + ...content.apiRoute, + location, + }; + } + } else { + namespaces[namespace].apiRoutes[content.apiRoute.path] = { + ...content.apiRoute, + location, + }; + } + } + } +} + +export const sortRoutes = ( + routes: Record< + string, + Route & { + location: string; + module?: () => Promise<{ route: Route }>; + } + > +) => + Object.entries(routes).toSorted(([pathA], [pathB]) => { + const segmentsA = pathA.split('/'); + const segmentsB = pathB.split('/'); + const lenA = segmentsA.length; + const lenB = segmentsB.length; + const minLen = Math.min(lenA, lenB); + + for (let i = 0; i < minLen; i++) { + const segmentA = segmentsA[i]; + const segmentB = segmentsB[i]; + + // Literal segments have priority over parameter segments + if (segmentA.startsWith(':') !== segmentB.startsWith(':')) { + return segmentA.startsWith(':') ? 1 : -1; + } + + // Regex-constrained parameters have priority over plain parameters + if (segmentA.startsWith(':') && segmentA.includes('{') !== segmentB.includes('{')) { + return segmentA.includes('{') ? -1 : 1; + } + } + + return 0; + }); + +// Deeper namespaces register first so a parent's param routes cannot shadow them +const sortNamespacesByDepth = (namespaces: NamespacesType) => Object.keys(namespaces).toSorted((a, b) => b.split('/').length - a.split('/').length); + +export function registerRssRoutes(app: Hono, namespaces: NamespacesType): void { + for (const namespace of sortNamespacesByDepth(namespaces)) { + const subApp = app.basePath(`/${namespace}`); + + const namespaceData = namespaces[namespace]; + if (!namespaceData || !namespaceData.routes) { + continue; + } + + const sortedRoutes = sortRoutes(namespaceData.routes); + + for (const [path, routeData] of sortedRoutes) { + const wrappedHandler: Handler = async (ctx) => { + logger.debug(`Matched route: ${routePath(ctx)}`); + if (!ctx.get('data')) { + if (typeof routeData.handler !== 'function') { + if (process.env.NODE_ENV === 'test') { + const { route } = await import(`./routes/${namespace}/${routeData.location}`); + routeData.handler = route.handler; + } else if (routeData.module) { + const { route } = await routeData.module(); + routeData.handler = route.handler; + } + } + const response = await routeData.handler(ctx); + if (response instanceof Response) { + return response; + } + ctx.set('data', response); + } + }; + subApp.get(path, wrappedHandler); + } + } +} + +export function registerApiRoutes(app: Hono, namespaces: NamespacesType): void { + for (const namespace of sortNamespacesByDepth(namespaces)) { + const subApp = app.basePath(`/api/${namespace}`); + + const namespaceData = namespaces[namespace]; + if (!namespaceData || !namespaceData.apiRoutes) { + continue; + } + + const sortedRoutes = Object.entries(namespaceData.apiRoutes) as Array< + [ + string, + APIRoute & { + location: string; + module?: () => Promise<{ apiRoute: APIRoute }>; + }, + ] + >; + + for (const [path, routeData] of sortedRoutes) { + const wrappedHandler: Handler = async (ctx) => { + if (ctx.get('apiData')) { + return; + } + if (typeof routeData.handler !== 'function') { + if (process.env.NODE_ENV === 'test') { + const { apiRoute } = await import(`./routes/${namespace}/${routeData.location}`); + routeData.handler = apiRoute.handler; + } else if (routeData.module) { + const { apiRoute } = await routeData.module(); + routeData.handler = apiRoute.handler; + } + } + const data = await routeData.handler(ctx); + ctx.set('apiData', data); + }; + subApp.get(path, wrappedHandler); + } + } +} diff --git a/lib/registry.dynamic.test.ts b/lib/registry.dynamic.test.ts index 81ca7f748..0d2b4e090 100644 --- a/lib/registry.dynamic.test.ts +++ b/lib/registry.dynamic.test.ts @@ -1,6 +1,49 @@ +import type fs from 'node:fs'; +import path from 'node:path'; + import { Hono } from 'hono'; import { describe, expect, it, vi } from 'vitest'; +// The dev registry lists lib/routes at startup; expose the fixture directory names there +const fakeTopDirectories = vi.hoisted(() => ({ names: [] as string[] })); + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + const readdirSync = ((target: unknown, options: unknown) => { + if (fakeTopDirectories.names.length > 0 && String(target).endsWith(path.join('lib', 'routes'))) { + return fakeTopDirectories.names.map((name) => ({ name, isDirectory: () => true })); + } + return actual.readdirSync(target as never, options as never); + }) as typeof actual.readdirSync; + return { ...actual, readdirSync, default: { ...actual, readdirSync } }; +}); + +const perDirectoryMock = (fakeDirectories: Record>) => { + fakeTopDirectories.names = Object.keys(fakeDirectories); + return vi.fn(({ targetDirectoryPath }: { targetDirectoryPath: string }) => { + const name = targetDirectoryPath.split(/[/\\]/).findLast(Boolean) as string; + return Promise.resolve(fakeDirectories[name]); + }); +}; + +const wrap = (registry: Hono) => { + const app = new Hono(); + app.use(async (ctx, next) => { + const response = await next(); + const apiData = ctx.get('apiData'); + if (apiData) { + return ctx.json(apiData); + } + const data = ctx.get('data'); + if (data) { + return ctx.json(data); + } + return response; + }); + app.route('/', registry); + return app; +}; + describe('registry dynamic loading', () => { it('loads production namespaces from build', async () => { const originalEnv = process.env.NODE_ENV; @@ -13,116 +56,104 @@ describe('registry dynamic loading', () => { process.env.NODE_ENV = originalEnv; }); - it('builds namespaces from directory import and resolves module handlers', async () => { + it('lazily builds namespaces from directory import on first request', async () => { const originalEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; - const modules = { - '/nsEmpty/namespace.ts': { - namespace: { - name: 'Empty', - routes: null, + const directoryImportMock = perDirectoryMock({ + nsRoute: { + '/route-array.ts': { + route: { + path: ['/a', '/b'], + name: 'Array', + handler: () => ({ title: 'array', link: 'https://example.com', item: [], allowEmpty: true }), + }, + }, + '/route-single.ts': { + route: { + path: '/single', + name: 'Single', + handler: () => ({ title: 'ok', link: 'https://example.com', item: [], allowEmpty: true }), + }, }, }, - '/nsRoute/route-array.ts': { - route: { - path: ['/a', '/b'], - name: 'Array', + nsModule: { + '/route-module.ts': { + route: { + path: '/module', + name: 'Module', + module: () => + Promise.resolve({ + route: { + handler: () => new Response('module'), + }, + }), + }, }, }, - '/nsRoute/route-single.ts': { - route: { - path: '/single', - name: 'Single', - handler: () => ({ - title: 'ok', - link: 'https://example.com', - item: [], - allowEmpty: true, - }), + nsApi: { + '/api-single.ts': { + apiRoute: { + path: '/single', + name: 'ApiSingle', + handler: () => ({ ok: true }), + }, + }, + '/api-module.ts': { + apiRoute: { + path: '/module', + name: 'ApiModule', + module: () => + Promise.resolve({ + apiRoute: { + handler: () => ({ ok: true }), + }, + }), + }, }, }, - '/nsModule/route-module.ts': { - route: { - path: '/module', - name: 'Module', - module: () => - Promise.resolve({ - route: { - handler: () => new Response('module'), - }, - }), + test: { + '/api-index.ts': { + apiRoute: { + path: '/', + name: 'ApiIndex', + }, }, }, - '/nsApi/api-array.ts': { - apiRoute: { - path: ['/a1', '/a2'], - name: 'ApiArray', - handler: () => ({ ok: true }), - }, - }, - '/nsApi/api-single.ts': { - apiRoute: { - path: '/single', - name: 'ApiSingle', - handler: () => ({ ok: true }), - }, - }, - '/nsApi/api-module.ts': { - apiRoute: { - path: '/module', - name: 'ApiModule', - module: () => - Promise.resolve({ - apiRoute: { - handler: () => ({ ok: true }), - }, - }), - }, - }, - '/test/api-index.ts': { - apiRoute: { - path: '/', - name: 'ApiIndex', - }, - }, - }; - - const directoryImportMock = vi.fn(() => modules); + }); vi.doMock('@/utils/directory-import', () => ({ directoryImport: directoryImportMock, })); vi.resetModules(); const { namespaces, default: registry } = await import('@/registry'); - expect(directoryImportMock).toHaveBeenCalled(); - expect(namespaces.nsRoute.routes['/single']).toBeDefined(); - expect(namespaces.nsApi.apiRoutes['/single']).toBeDefined(); + // The cold-start guarantee: importing the registry imports no route modules + expect(directoryImportMock).not.toHaveBeenCalled(); - const app = new Hono(); - app.use(async (ctx, next) => { - const response = await next(); - const apiData = ctx.get('apiData'); - if (apiData) { - return ctx.json(apiData); - } - const data = ctx.get('data'); - if (data) { - return ctx.json(data); - } - return response; - }); - app.route('/', registry); + const app = wrap(registry); const routeResponse = await app.request('/nsModule/module'); expect(await routeResponse.text()).toBe('module'); - await app.request('/api/nsApi/module'); + expect(directoryImportMock).toHaveBeenCalledTimes(1); + const singleResponse = await app.request('/nsRoute/single'); + const singleBody = await singleResponse.json(); + expect(singleBody.title).toBe('ok'); + expect(namespaces.nsRoute.routes['/single']).toBeDefined(); + expect(namespaces.nsRoute.routes['/a']).toBeDefined(); + + const apiResponse = await app.request('/api/nsApi/module'); + const apiBody = await apiResponse.json(); + expect(apiBody).toEqual({ ok: true }); + expect(namespaces.nsApi.apiRoutes['/single']).toBeDefined(); + + // Handler resolution from disk in test env (real file lib/routes/test/api-index.ts) process.env.NODE_ENV = 'test'; const apiTestResponse = await app.request('/api/test'); expect(await apiTestResponse.json()).toEqual({ code: 0 }); process.env.NODE_ENV = originalEnv; + vi.doUnmock('@/utils/directory-import'); }); // https://github.com/DIYgod/RSSHub/pull/18002 @@ -130,61 +161,38 @@ describe('registry dynamic loading', () => { const originalEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; - const modules = { - '/specificity/param-route.ts': { - route: { - path: '/:category', - name: 'ParamRoute', - handler: () => ({ - title: 'param', - link: 'https://example.com', - item: [], - allowEmpty: true, - }), + const directoryImportMock = perDirectoryMock({ + specificity: { + '/param-route.ts': { + route: { + path: '/:category', + name: 'ParamRoute', + handler: () => ({ title: 'param', link: 'https://example.com', item: [], allowEmpty: true }), + }, + }, + '/literal-route.ts': { + route: { + path: '/news/:channel', + name: 'LiteralRoute', + handler: () => ({ title: 'literal', link: 'https://example.com', item: [], allowEmpty: true }), + }, + }, + '/news-route.ts': { + route: { + path: '/news', + name: 'NewsRoute', + handler: () => ({ title: 'news', link: 'https://example.com', item: [], allowEmpty: true }), + }, }, }, - '/specificity/literal-route.ts': { - route: { - path: '/news/:channel', - name: 'LiteralRoute', - handler: () => ({ - title: 'literal', - link: 'https://example.com', - item: [], - allowEmpty: true, - }), - }, - }, - '/specificity/news-route.ts': { - route: { - path: '/news', - name: 'NewsRoute', - handler: () => ({ - title: 'news', - link: 'https://example.com', - item: [], - allowEmpty: true, - }), - }, - }, - }; - - const directoryImportMock = vi.fn(() => modules); + }); vi.doMock('@/utils/directory-import', () => ({ directoryImport: directoryImportMock, })); vi.resetModules(); const { default: registry } = await import('@/registry'); - const app = new Hono(); - app.use(async (ctx, next) => { - await next(); - const data = ctx.get('data'); - if (data) { - return ctx.json(data); - } - }); - app.route('/', registry); + const app = wrap(registry); // /news/sports should match /news/:channel (literal "news" wins over :category) const literalResponse = await app.request('/specificity/news/sports'); @@ -199,5 +207,6 @@ describe('registry dynamic loading', () => { expect((await paramResponse.json()).title).toBe('param'); process.env.NODE_ENV = originalEnv; + vi.doUnmock('@/utils/directory-import'); }); }); diff --git a/lib/registry.ts b/lib/registry.ts index ec12e10a4..d559b57ec 100644 --- a/lib/registry.ts +++ b/lib/registry.ts @@ -1,54 +1,24 @@ import path from 'node:path'; import { serveStatic } from '@hono/node-server/serve-static'; -import type { Handler } from 'hono'; import { Hono } from 'hono'; -import { routePath } from 'hono/route'; import { config } from '@/config'; +import type { DevRegistry } from '@/registry-dev'; +import type { NamespacesType, RoutesType } from '@/registry-helpers'; +import { registerApiRoutes, registerRssRoutes } from '@/registry-helpers'; import healthz from '@/routes/healthz'; import index from '@/routes/index'; import metrics from '@/routes/metrics'; import robotstxt from '@/routes/robots.txt'; -import type { APIRoute, Namespace, Route } from '@/types'; -import { directoryImport } from '@/utils/directory-import'; +import type { Route } from '@/types'; import { isWorker } from '@/utils/is-worker'; -import logger from '@/utils/logger'; + +export type { NamespacesType } from '@/registry-helpers'; +export { collectNamespaceRoots, resolveModuleNamespace, sortRoutes } from '@/registry-helpers'; const __dirname = import.meta.dirname; -const SEPARATOR = /[/\\]/; - -/** - * A directory under lib/routes that contains a `namespace.ts` is a "namespace root". Roots are keyed by their path - * relative to lib/routes, joined with `/` (e.g. `gov/cn`). - */ -export function collectNamespaceRoots(moduleKeys: string[]): Set { - const roots = new Set(); - for (const key of moduleKeys) { - const segments = key.split(SEPARATOR).filter(Boolean); - if (segments.at(-1) === 'namespace.ts') { - roots.add(segments.slice(0, -1).join('/')); - } - } - return roots; -} - -/** - * A module belongs to its longest matching namespace root; modules with no matching root fall back to their first - * path segment (flat namespaces). `location` is the module path relative to the resolved namespace root. - */ -export function resolveModuleNamespace(moduleKey: string, roots: Set): { namespace: string; location: string } { - const segments = moduleKey.split(SEPARATOR).filter(Boolean); - for (let i = segments.length - 1; i >= 1; i--) { - const candidate = segments.slice(0, i).join('/'); - if (roots.has(candidate)) { - return { namespace: candidate, location: segments.slice(i).join('/') }; - } - } - return { namespace: segments[0], location: segments.slice(1).join('/') }; -} - function isSafeRoutes(routes: RoutesType): boolean { return Object.values(routes).every((route: Route) => !route.features?.nsfw); } @@ -64,29 +34,8 @@ function safeNamespaces(namespaces: NamespacesType): NamespacesType { return safe; } -let modules: Record = {}; - -type RoutesType = Record< - string, - Route & { - location: string; - } ->; - -export type NamespacesType = Record< - string, - Namespace & { - routes: RoutesType; - apiRoutes: Record< - string, - APIRoute & { - location: string; - } - >; - } ->; - let namespaces: NamespacesType = {}; +let devRegistry: DevRegistry | undefined; if (config.isPackage) { namespaces = (await import('../assets/build/routes.js')).default; @@ -103,198 +52,30 @@ if (config.isPackage) { namespaces = namespaces.default; } break; - default: - modules = (await directoryImport({ - targetDirectoryPath: path.join(__dirname, './routes'), - importPattern: /\.tsx?$/, - })) as typeof modules; - } -} - -if (config.feature.disable_nsfw) { - namespaces = safeNamespaces(namespaces); -} - -if (Object.keys(modules).length) { - const namespaceRoots = collectNamespaceRoots(Object.keys(modules)); - for (const module in modules) { - const content = modules[module] as - | { - route: Route; - } - | { - namespace: Namespace; - } - | { - apiRoute: APIRoute; - }; - const { namespace, location } = resolveModuleNamespace(module, namespaceRoots); - if ('namespace' in content) { - namespaces[namespace] = Object.assign( - { - routes: {}, - apiRoutes: {}, - }, - namespaces[namespace], - content.namespace - ); - } else if ('route' in content) { - if (!Object.hasOwn(namespaces, namespace)) { - namespaces[namespace] = { - name: namespace, - routes: {}, - apiRoutes: {}, - }; - } - if (Array.isArray(content.route.path)) { - for (const path of content.route.path) { - namespaces[namespace].routes[path] = { - ...content.route, - location, - }; - } - } else { - namespaces[namespace].routes[content.route.path] = { - ...content.route, - location, - }; - } - } else if ('apiRoute' in content) { - if (!Object.hasOwn(namespaces, namespace)) { - namespaces[namespace] = { - name: namespace, - routes: {}, - apiRoutes: {}, - }; - } - if (Array.isArray(content.apiRoute.path)) { - for (const path of content.apiRoute.path) { - namespaces[namespace].apiRoutes[path] = { - ...content.apiRoute, - location, - }; - } - } else { - namespaces[namespace].apiRoutes[content.apiRoute.path] = { - ...content.apiRoute, - location, - }; - } + default: { + // lazy load dev namespaces + const { createDevRegistry } = await import('@/registry-dev'); + devRegistry = createDevRegistry({ + routesDirectory: path.join(__dirname, './routes'), + namespaces, + }); } } } +if (config.feature.disable_nsfw && !devRegistry) { + namespaces = safeNamespaces(namespaces); +} + +export const ensureAllLoaded: () => Promise = devRegistry?.ensureAllLoaded ?? (() => Promise.resolve()); + export { namespaces }; const app = new Hono(); -export const sortRoutes = ( - routes: Record< - string, - Route & { - location: string; - module?: () => Promise<{ route: Route }>; - } - > -) => - Object.entries(routes).toSorted(([pathA], [pathB]) => { - const segmentsA = pathA.split('/'); - const segmentsB = pathB.split('/'); - const lenA = segmentsA.length; - const lenB = segmentsB.length; - const minLen = Math.min(lenA, lenB); - for (let i = 0; i < minLen; i++) { - const segmentA = segmentsA[i]; - const segmentB = segmentsB[i]; - - // Literal segments have priority over parameter segments - if (segmentA.startsWith(':') !== segmentB.startsWith(':')) { - return segmentA.startsWith(':') ? 1 : -1; - } - - // Regex-constrained parameters have priority over plain parameters - if (segmentA.startsWith(':') && segmentA.includes('{') !== segmentB.includes('{')) { - return segmentA.includes('{') ? -1 : 1; - } - } - - return 0; - }); - -// Deeper namespaces register first so a parent's param routes cannot shadow them -const namespacesByDepth = Object.keys(namespaces).toSorted((a, b) => b.split('/').length - a.split('/').length); - -for (const namespace of namespacesByDepth) { - const subApp = app.basePath(`/${namespace}`); - - const namespaceData = namespaces[namespace]; - if (!namespaceData || !namespaceData.routes) { - continue; - } - - const sortedRoutes = sortRoutes(namespaceData.routes); - - for (const [path, routeData] of sortedRoutes) { - const wrappedHandler: Handler = async (ctx) => { - logger.debug(`Matched route: ${routePath(ctx)}`); - if (!ctx.get('data')) { - if (typeof routeData.handler !== 'function') { - if (process.env.NODE_ENV === 'test') { - const { route } = await import(`./routes/${namespace}/${routeData.location}`); - routeData.handler = route.handler; - } else if (routeData.module) { - const { route } = await routeData.module(); - routeData.handler = route.handler; - } - } - const response = await routeData.handler(ctx); - if (response instanceof Response) { - return response; - } - ctx.set('data', response); - } - }; - subApp.get(path, wrappedHandler); - } -} - -for (const namespace of namespacesByDepth) { - const subApp = app.basePath(`/api/${namespace}`); - - const namespaceData = namespaces[namespace]; - if (!namespaceData || !namespaceData.apiRoutes) { - continue; - } - - const sortedRoutes = Object.entries(namespaceData.apiRoutes) as Array< - [ - string, - APIRoute & { - location: string; - module?: () => Promise<{ apiRoute: APIRoute }>; - }, - ] - >; - - for (const [path, routeData] of sortedRoutes) { - const wrappedHandler: Handler = async (ctx) => { - if (ctx.get('apiData')) { - return; - } - if (typeof routeData.handler !== 'function') { - if (process.env.NODE_ENV === 'test') { - const { apiRoute } = await import(`./routes/${namespace}/${routeData.location}`); - routeData.handler = apiRoute.handler; - } else if (routeData.module) { - const { apiRoute } = await routeData.module(); - routeData.handler = apiRoute.handler; - } - } - const data = await routeData.handler(ctx); - ctx.set('apiData', data); - }; - subApp.get(path, wrappedHandler); - } +if (!devRegistry) { + registerRssRoutes(app, namespaces); + registerApiRoutes(app, namespaces); } app.get('/', index); @@ -304,6 +85,11 @@ if (config.debugInfo !== 'false') { // Only enable tracing in debug mode app.get('/metrics', metrics); } + +if (devRegistry) { + app.use('*', devRegistry.middleware); +} + if (!config.isPackage && !process.env.VERCEL_ENV && !isWorker) { app.use( '/*', diff --git a/lib/routes/economist/espresso.ts b/lib/routes/economist/espresso.ts index bce577e32..56addc313 100644 --- a/lib/routes/economist/espresso.ts +++ b/lib/routes/economist/espresso.ts @@ -11,6 +11,8 @@ import { parseDate } from '@/utils/parse-date'; const link = 'https://www.economist.com/the-world-in-brief'; +const { h64ToString } = await xxhash(); + export const route: Route = { path: '/espresso', categories: ['traditional-media'], @@ -37,7 +39,6 @@ export const route: Route = { }; async function handler() { - const { h64ToString } = await xxhash(); const nextData = await cache.tryGet( link, async () => { diff --git a/lib/routes/tophub/list.tsx b/lib/routes/tophub/list.tsx index 8a4c60db6..8d6975e05 100644 --- a/lib/routes/tophub/list.tsx +++ b/lib/routes/tophub/list.tsx @@ -6,6 +6,8 @@ import { config } from '@/config'; import type { Route } from '@/types'; import ofetch from '@/utils/ofetch'; +const { h64ToString } = await xxhash(); + export const route: Route = { path: '/list/:id', categories: ['new-media'], @@ -39,7 +41,6 @@ export const route: Route = { }; async function handler(ctx) { - const { h64ToString } = await xxhash(); const id = ctx.req.param('id'); const link = `https://tophub.today/n/${id}`; const response = await ofetch(link, { diff --git a/lib/routes/youtube/api/google.ts b/lib/routes/youtube/api/google.ts index 568f404c8..60be15514 100644 --- a/lib/routes/youtube/api/google.ts +++ b/lib/routes/youtube/api/google.ts @@ -1,7 +1,7 @@ +import { auth as googleAuth, youtube as googleYoutube } from '@googleapis/youtube'; import { load } from 'cheerio'; import dayjs from 'dayjs'; import duration from 'dayjs/plugin/duration.js'; -import { google } from 'googleapis'; import { config } from '@/config'; import NotFoundError from '@/errors/types/not-found'; @@ -13,7 +13,7 @@ import { parseDate } from '@/utils/parse-date'; import utils, { getVideoUrl } from '../utils'; import { getSrtAttachmentBatch } from './subtitles'; -const { OAuth2 } = google.auth; +const { OAuth2 } = googleAuth; dayjs.extend(duration); @@ -27,7 +27,7 @@ if (config.youtube && config.youtube.key) { continue; } - youtube[index] = google.youtube({ + youtube[index] = googleYoutube({ version: 'v3', auth: key, }); diff --git a/lib/routes/youtube/utils.tsx b/lib/routes/youtube/utils.tsx index 706acf5a4..2ccb28d06 100644 --- a/lib/routes/youtube/utils.tsx +++ b/lib/routes/youtube/utils.tsx @@ -1,4 +1,4 @@ -import { google } from 'googleapis'; +import { youtube as googleYoutube } from '@googleapis/youtube'; import { raw } from 'hono/html'; import { renderToString } from 'hono/jsx/dom/server'; @@ -99,7 +99,7 @@ export const getSubscriptions = async (part, cache) => { return cache.tryGet('youtube:getSubscriptions', () => getSubscriptionsRecusive(part), config.cache.routeExpire, false); }; export async function getSubscriptionsRecusive(part, nextPageToken?) { - const res = await google.youtube('v3').subscriptions.list({ + const res = await googleYoutube('v3').subscriptions.list({ auth: youtubeOAuth2Client, part, mine: true, diff --git a/lib/utils/cache/index.ts b/lib/utils/cache/index.ts index f1a05e3b3..6d32b34de 100644 --- a/lib/utils/cache/index.ts +++ b/lib/utils/cache/index.ts @@ -11,10 +11,16 @@ const globalCache: { get: (key: string) => Promise | string | null | undefined; has: (key: string) => Promise | boolean; set: (key: string, value?: string | Record, maxAge?: number) => any; + /** + * Atomically set `key` to '1' and return true, unless it is already '1' (return false). + * A get-then-set in the caller races: two same-tick requests would both read "not '1'". + */ + claim: (key: string, maxAge: number) => Promise | boolean; } = { get: () => null, has: () => false, set: () => null, + claim: () => true, }; const noopCacheModule: CacheModule = { @@ -54,6 +60,13 @@ if (isWorker) { return false; }; globalCache.set = cacheModule.set; + globalCache.claim = async (key, maxAge) => { + if (!key || !cacheModule.status.available || !redisClient) { + return true; + } + const result = await redisClient.eval("if redis.call('GET', KEYS[1]) == '1' then return 0 end redis.call('SET', KEYS[1], '1', 'EX', ARGV[1]) return 1", 1, key, maxAge); + return result === 1; + }; break; } case 'http': @@ -75,6 +88,17 @@ if (isWorker) { return cacheModule.set(key, value, maxAge); } }; + globalCache.claim = async (key, maxAge) => { + if (!key || !cacheModule.status.available) { + return true; + } + // best effort: the HTTP cache protocol has no atomic operation + if ((await cacheModule.get(key, false)) === '1') { + return false; + } + await cacheModule.set(key, '1', maxAge); + return true; + }; break; case 'memory': { cacheModule = memory; @@ -102,6 +126,17 @@ if (isWorker) { return memoryCache.set(key, value, { ttl: maxAge * 1000 }); } }; + // fully synchronous, so nothing can interleave between the read and the write + globalCache.claim = (key, maxAge) => { + if (!key || !cacheModule.status.available || !memoryCache) { + return true; + } + if (memoryCache.get(key, { updateAgeOnGet: false }) === '1') { + return false; + } + memoryCache.set(key, '1', { ttl: maxAge * 1000 }); + return true; + }; break; } default: diff --git a/lib/utils/cache/index.worker.ts b/lib/utils/cache/index.worker.ts index b634464f6..b956a8ac9 100644 --- a/lib/utils/cache/index.worker.ts +++ b/lib/utils/cache/index.worker.ts @@ -11,6 +11,11 @@ import kv, { getKVNamespace } from './kv'; const globalCache: { get: (key: string) => Promise | string | null | undefined; set: (key: string, value?: string | Record, maxAge?: number) => any; + /** + * Atomically set `key` to '1' and return true, unless it is already '1' (return false). + * A get-then-set in the caller races: two same-tick requests would both read "not '1'". + */ + claim: (key: string, maxAge: number) => Promise | boolean; } = { get: async (key) => { if (key && kv.status.available && getKVNamespace()) { @@ -33,6 +38,14 @@ const globalCache: { await getKVNamespace()!.put(key, value, { expirationTtl: maxAge }); } }, + claim: async (key, maxAge) => { + // best effort: KV has no atomic operation + if ((await globalCache.get(key)) === '1') { + return false; + } + await globalCache.set(key, '1', maxAge); + return true; + }, }; // Use KV cache module for Worker diff --git a/lib/utils/playwright.test.ts b/lib/utils/playwright.test.ts index b069b3515..2d6adf680 100644 --- a/lib/utils/playwright.test.ts +++ b/lib/utils/playwright.test.ts @@ -143,37 +143,45 @@ describe('playwright', () => { describe('getPlaywrightPage (mocked)', () => { it('connects via ws endpoint and runs onBeforeLoad', async () => { - resetMocks(); - connect.mockResolvedValue(mockBrowser); - connectOverCDP.mockResolvedValue(mockBrowser); - launch.mockResolvedValue(mockBrowser); - mockPage.goto.mockResolvedValue(undefined); - mockBrowser.close.mockResolvedValue(undefined); - process.env.PLAYWRIGHT_WS_ENDPOINT = 'ws://localhost:3000/?token=abc'; - proxyMock.getCurrentProxy.mockReturnValue(null); + vi.useFakeTimers(); + try { + resetMocks(); + connect.mockResolvedValue(mockBrowser); + connectOverCDP.mockResolvedValue(mockBrowser); + launch.mockResolvedValue(mockBrowser); + mockPage.goto.mockResolvedValue(undefined); + mockBrowser.close.mockResolvedValue(undefined); + process.env.PLAYWRIGHT_WS_ENDPOINT = 'ws://localhost:3000/?token=abc'; + proxyMock.getCurrentProxy.mockReturnValue(null); - const getPlaywrightPage = await loadPlaywright(); - const onBeforeLoad = vi.fn(); - const contextClose = mockContext.close; - const result = await getPlaywrightPage('https://example.com', { - noGoto: true, - onBeforeLoad, - }); + const getPlaywrightPage = await loadPlaywright(); + const onBeforeLoad = vi.fn(); + const browserClose = mockBrowser.close; + const result = await getPlaywrightPage('https://example.com', { + noGoto: true, + onBeforeLoad, + }); - const endpoint = connect.mock.calls[0][0] as string; - expect(connectOverCDP).not.toHaveBeenCalled(); - expect(endpoint).toContain('launch='); - expect(endpoint).not.toContain('launch-options='); - const launchOptions = JSON.parse(new URL(endpoint).searchParams.get('launch') || '{}'); - expect(launchOptions.args).not.toContainEqual(expect.stringContaining('--user-agent=')); - expect(launchOptions.executablePath).toBeUndefined(); - expect(launchOptions.ignoreHTTPSErrors).toBeUndefined(); - expect(launchOptions.stealth).toBeUndefined(); - expect(launchOptions.headless).toBe(true); - expect(onBeforeLoad).toHaveBeenCalled(); + const endpoint = connect.mock.calls[0][0] as string; + expect(connectOverCDP).not.toHaveBeenCalled(); + expect(endpoint).toContain('launch='); + expect(endpoint).not.toContain('launch-options='); + const launchOptions = JSON.parse(new URL(endpoint).searchParams.get('launch') || '{}'); + expect(launchOptions.args).not.toContainEqual(expect.stringContaining('--user-agent=')); + expect(launchOptions.executablePath).toBeUndefined(); + expect(launchOptions.ignoreHTTPSErrors).toBeUndefined(); + expect(launchOptions.stealth).toBeUndefined(); + expect(launchOptions.headless).toBe(true); + expect(onBeforeLoad).toHaveBeenCalled(); - await result.destroy(); - expect(contextClose).toHaveBeenCalled(); + await result.destroy(); + expect(browserClose).toHaveBeenCalledTimes(1); + + await vi.advanceTimersByTimeAsync(30000); + expect(browserClose).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } }); it('overrides an existing ws endpoint launch param, dropping invalid keys like stealth', async () => { @@ -342,6 +350,7 @@ describe('getPlaywrightPage (mocked)', () => { it('marks proxy failed when navigation throws with multi-proxy', async () => { resetMocks(); launch.mockResolvedValue(mockBrowser); + mockBrowser.close.mockResolvedValue(undefined); mockPage.goto.mockRejectedValueOnce(new Error('fail')); const currentProxy = { @@ -355,5 +364,6 @@ describe('getPlaywrightPage (mocked)', () => { await expect(getPlaywrightPage('https://example.com')).rejects.toThrow('fail'); expect(proxyMock.markProxyFailed).toHaveBeenCalledWith(currentProxy.uri); + expect(mockBrowser.close).toHaveBeenCalledTimes(1); }); }); diff --git a/lib/utils/playwright.ts b/lib/utils/playwright.ts index d5cf4e25d..372060ba0 100644 --- a/lib/utils/playwright.ts +++ b/lib/utils/playwright.ts @@ -108,11 +108,10 @@ const getBrowserlessEndpoint = (endpoint: string, launchOptions: BrowserlessLaun return endpointURL.href; }; -const scheduleClose = (browser: Browser, timeout = 30000) => { +const scheduleClose = (browser: Browser, timeout = 30000) => setTimeout(() => { void browser.close(); }, timeout); -}; /** * @returns Playwright browser context (native `newPage()` shares state across calls) @@ -156,7 +155,12 @@ export const getPlaywrightPage = async ( const currentProxyState = currentProxy && allowProxy ? currentProxy : null; const hasProxy = Boolean(getProxyOptions(currentProxyState).proxy); const { browser, context } = await launchBrowser(currentProxyState); - scheduleClose(browser, instanceOptions.closeTimeout); + const closeTimer = scheduleClose(browser, instanceOptions.closeTimeout); + const destroy = async () => { + clearTimeout(closeTimer); + await browser.close(); + }; + const page = await context.newPage(); if (hasProxy && currentProxyState) { @@ -174,17 +178,15 @@ export const getPlaywrightPage = async ( if (hasProxy && currentProxyState && proxy.multiProxy) { logger.warn(`Playwright navigation failed with proxy ${currentProxyState.uri}, marking as failed: ${error}`); proxy.markProxyFailed(currentProxyState.uri); - throw error; } + await destroy(); throw error; } } return { context, - destroy: async () => { - await context.close(); - }, + destroy, page, }; }; diff --git a/package.json b/package.json index 374f805a5..8780d2d6e 100644 --- a/package.json +++ b/package.json @@ -60,6 +60,7 @@ "@bbob/html": "4.3.1", "@bbob/plugin-helper": "4.3.1", "@bbob/preset-html5": "4.3.1", + "@googleapis/youtube": "33.0.0", "@honeybadger-io/js": "6.14.0", "@hono/node-server": "2.0.8", "@hono/zod-openapi": "1.4.0", @@ -87,7 +88,6 @@ "etag": "1.8.1", "fanfou-sdk": "6.0.0", "google-play-scraper": "10.1.3", - "googleapis": "173.0.0", "header-generator": "2.1.82", "hono": "4.12.28", "html-to-text": "10.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 88a223fe4..7666a237a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -40,6 +40,9 @@ importers: '@bbob/preset-html5': specifier: 4.3.1 version: 4.3.1 + '@googleapis/youtube': + specifier: 33.0.0 + version: 33.0.0 '@honeybadger-io/js': specifier: 6.14.0 version: 6.14.0 @@ -121,9 +124,6 @@ importers: google-play-scraper: specifier: 10.1.3 version: 10.1.3 - googleapis: - specifier: 173.0.0 - version: 173.0.0 header-generator: specifier: 2.1.82 version: 2.1.82 @@ -1077,6 +1077,10 @@ packages: '@noble/hashes': optional: true + '@googleapis/youtube@33.0.0': + resolution: {integrity: sha512-PW3SdoZ8ULzW0We0lgplyZHjuXJtOdRvU5RL6ErNUlcTeSqjoHtk1pWdHKTwk3brPuIiqUB26K7fX84VroDqRg==} + engines: {node: '>=12.0.0'} + '@honeybadger-io/core@6.9.0': resolution: {integrity: sha512-nHkTigMgqABQ6XuhZ4/2cVIArwImctdWfmu/ckWLoF5E4JlATe9WUL3hMRL8UZPmu/ThmbojxkLwDgHts1LyUA==} engines: {node: '>=14'} @@ -2976,8 +2980,8 @@ packages: brace-expansion@1.1.15: resolution: {integrity: sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==} - brace-expansion@2.1.1: - resolution: {integrity: sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA==} + brace-expansion@2.1.2: + resolution: {integrity: sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==} brace-expansion@5.0.7: resolution: {integrity: sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==} @@ -3470,10 +3474,6 @@ packages: error-stack-parser-es@1.0.5: resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} - es-define-property@1.0.1: - resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} - engines: {node: '>= 0.4'} - es-module-lexer@2.3.0: resolution: {integrity: sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==} @@ -3787,14 +3787,6 @@ packages: resolution: {integrity: sha512-YGGyuEdVIjqxkxVH1pUTMY/XtmmsApXrCVv5EU25iX6inEPbV+VakJfLealkBtJN69AQmh1eGOdCl9Sm1UP6XQ==} engines: {node: '>=18'} - gaxios@7.1.5: - resolution: {integrity: sha512-5FZy72Rh8LhtjmvDrKkI+lVhrsQrVKVsItxMoDm5mNQE+xR0WVIIs+jzPSJgBvKVsLi24fZhXJIsNI0bihDzFg==} - engines: {node: '>=18'} - - gcp-metadata@8.1.2: - resolution: {integrity: sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==} - engines: {node: '>=18'} - gcp-metadata@8.1.3: resolution: {integrity: sha512-ziTrzUhhpL9Zk5k0HHzgP/KIpWDJT0VMBC/ynt/QIBvTW+UUcSivQRl6VlwTf/EilDxtSWklHoRsKy1c4k+59w==} engines: {node: '>=18'} @@ -3864,10 +3856,6 @@ packages: resolution: {integrity: sha512-7ABviyMOlX5hIVD60YOfHw4/CxOfBhyduaYB+wbFWCWoni4N7SLcV46hrVRktuBbZjFC9ONyqamZITN7q3n32w==} engines: {node: '>=18'} - google-auth-library@10.9.0: - resolution: {integrity: sha512-xtvUqvINPhTaBm7nXqlYPcrMHJPm1lCNdSovxnKKhTm+4JsvQ+KGVYJViLoH9Yxu8w+T0Qv5HubzYT9BLrppJg==} - engines: {node: '>=18'} - google-logging-utils@1.1.3: resolution: {integrity: sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==} engines: {node: '>=14'} @@ -3879,10 +3867,6 @@ packages: resolution: {integrity: sha512-5MXeQzIZaqCH7B+HJWqhQm946VARpZep6acbWSr/fcgF2cQANq7allgX+i/G0EqF0WyUxB277gtWMzRYHMl9tg==} engines: {node: '>=18.0.0'} - googleapis@173.0.0: - resolution: {integrity: sha512-xEJJYLZ4qeenVyfzispNfRjCe9bsv7CzBv5zYFLvScOze9snJ8S9W6hjQ729CWPQt5mvn/JrcRaCHzQiukt0ng==} - engines: {node: '>=18'} - got@14.6.6: resolution: {integrity: sha512-QLV1qeYSo5l13mQzWgP/y0LbMr5Plr5fJilgAIwgnwseproEbtNym8xpLsDzeZ6MWXgNE6kdWGBjdh3zT/Qerg==} engines: {node: '>=20'} @@ -5009,10 +4993,6 @@ packages: resolution: {integrity: sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==} engines: {node: '>=0.6'} - qs@6.15.3: - resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==} - engines: {node: '>=0.6'} - qs@6.5.5: resolution: {integrity: sha512-mzR4sElr1bfCaPJe7m8ilJ6ZXdDaGoObcYR0ZHSsktM/Lt21MVHj5De30GQH2eiZ1qGRTO7LCAzQsUeXTNexWQ==} engines: {node: '>=0.6'} @@ -6602,6 +6582,12 @@ snapshots: optionalDependencies: '@noble/hashes': 2.2.0 + '@googleapis/youtube@33.0.0': + dependencies: + googleapis-common: 8.0.2 + transitivePeerDependencies: + - supports-color + '@honeybadger-io/core@6.9.0': dependencies: json-nd: 1.0.0 @@ -8159,7 +8145,7 @@ snapshots: balanced-match: 1.0.2 concat-map: 0.0.1 - brace-expansion@2.1.1: + brace-expansion@2.1.2: dependencies: balanced-match: 1.0.2 @@ -8597,8 +8583,6 @@ snapshots: error-stack-parser-es@1.0.5: {} - es-define-property@1.0.1: {} - es-module-lexer@2.3.0: {} es5-ext@0.10.64: @@ -9028,22 +9012,6 @@ snapshots: transitivePeerDependencies: - supports-color - gaxios@7.1.5: - dependencies: - extend: 3.0.2 - https-proxy-agent: 7.0.6 - node-fetch: 3.3.2 - transitivePeerDependencies: - - supports-color - - gcp-metadata@8.1.2: - dependencies: - gaxios: 7.1.5 - google-logging-utils: 1.1.3 - json-bigint: 1.0.0 - transitivePeerDependencies: - - supports-color - gcp-metadata@8.1.3: dependencies: gaxios: 7.1.3 @@ -9119,7 +9087,7 @@ snapshots: dependencies: base64-js: 1.5.1 ecdsa-sig-formatter: 1.0.11 - gaxios: 7.1.5 + gaxios: 7.1.3 gcp-metadata: 8.1.3 google-logging-utils: 1.1.3 gtoken: 8.0.0 @@ -9127,17 +9095,6 @@ snapshots: transitivePeerDependencies: - supports-color - google-auth-library@10.9.0: - dependencies: - base64-js: 1.5.1 - ecdsa-sig-formatter: 1.0.11 - gaxios: 7.1.5 - gcp-metadata: 8.1.2 - google-logging-utils: 1.1.3 - jws: 4.0.1 - transitivePeerDependencies: - - supports-color - google-logging-utils@1.1.3: {} google-play-scraper@10.1.3: @@ -9157,18 +9114,11 @@ snapshots: gaxios: 7.1.3 google-auth-library: 10.5.0 google-logging-utils: 1.1.3 - qs: 6.15.3 + qs: 6.14.2 url-template: 2.0.8 transitivePeerDependencies: - supports-color - googleapis@173.0.0: - dependencies: - google-auth-library: 10.9.0 - googleapis-common: 8.0.2 - transitivePeerDependencies: - - supports-color - got@14.6.6: dependencies: '@sindresorhus/is': 7.2.0 @@ -9205,7 +9155,7 @@ snapshots: gtoken@8.0.0: dependencies: - gaxios: 7.1.5 + gaxios: 7.1.3 jws: 4.0.1 transitivePeerDependencies: - supports-color @@ -10128,7 +10078,7 @@ snapshots: minimatch@9.0.9: dependencies: - brace-expansion: 2.1.1 + brace-expansion: 2.1.2 minipass@7.1.3: {} @@ -10581,11 +10531,6 @@ snapshots: dependencies: side-channel: '@nolyfill/side-channel@1.0.44' - qs@6.15.3: - dependencies: - es-define-property: 1.0.1 - side-channel: '@nolyfill/side-channel@1.0.44' - qs@6.5.5: {} quansync@1.0.0: {} diff --git a/scripts/workflow/build-routes.ts b/scripts/workflow/build-routes.ts index 52a9ec09a..b6b8d860c 100644 --- a/scripts/workflow/build-routes.ts +++ b/scripts/workflow/build-routes.ts @@ -17,7 +17,8 @@ process.env.REDIS_URL = ''; process.env.CACHE_TYPE = ''; process.env.REMOTE_CONFIG = ''; -const { namespaces } = await import('../../lib/registry'); +const { ensureAllLoaded, namespaces } = await import('../../lib/registry'); +await ensureAllLoaded(); const maintainers: Record = {}; const radar: { diff --git a/tsdown.config.ts b/tsdown.config.ts index a7a6c724d..d0a3134d7 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -1,5 +1,7 @@ import { defineConfig } from 'tsdown'; +const namespaceOf = (id: string) => id.match(/[\\/]lib[\\/]routes[\\/]([^\\/]+)[\\/]/)?.[1]; + export default defineConfig({ entry: ['./lib/index.ts'], minify: true, @@ -9,4 +11,16 @@ export default defineConfig({ deps: { onlyBundle: false, }, + outputOptions: { + chunkFileNames(chunk) { + let namespace = chunk.facadeModuleId ? namespaceOf(chunk.facadeModuleId) : undefined; + if (!namespace) { + const namespaces = new Set(chunk.moduleIds.map((id) => namespaceOf(id))); + if (namespaces.size === 1) { + namespace = [...namespaces][0]; + } + } + return namespace && namespace !== chunk.name ? `${namespace}-[name]-[hash].mjs` : '[name]-[hash].mjs'; + }, + }, });