* perf: use only one WASM alloc for xxhash

* perf(deps): lazy load mercury-parser and use googleapis/youtube instead of heavy googleapis

* perf(dx): lazy load dev registry

speed up npm dev script

* perf: close playwright browser on destroy

* fix: show exception msg in prod

* revert: "perf: use only one WASM alloc for xxhash"

This reverts commit 01ecdd48d09a046dce05f440814dcbec0323a7de.

* perf: use only one WASM alloc for xxhash

* test: add claim for worker

* fix: missing piece from 8dd9c9a

* feat: add namespace to the chunkfilename

* fix: keep var naming
This commit is contained in:
Tony
2026-07-09 02:37:41 +08:00
committed by GitHub
parent 12a75059dd
commit cb0791cb41
31 changed files with 1030 additions and 623 deletions
+11 -7
View File
@@ -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<string, string>, query: Record<string, any> = {}) =>
({
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({});
});
});
+30 -19
View File
@@ -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<string, typeof namespaces> = {};
let cachedCategoryList: Record<string, typeof namespaces> | 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<Record<string, typeof namespaces>> => {
if (cachedCategoryList) {
return cachedCategoryList;
}
await ensureAllLoaded();
const list: Record<string, typeof namespaces> = {};
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<typeof route> = (ctx) => {
const handler: RouteHandler<typeof route> = async (ctx) => {
const categoryList = await getCategoryList();
const { categories, lang } = ctx.req.valid('query');
const { category } = ctx.req.valid('param');
+9 -6
View File
@@ -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<string, string> = {}) =>
({
req: {
@@ -16,20 +19,20 @@ const createCtx = (param: Record<string, string> = {}) =>
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]);
});
+5 -2
View File
@@ -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<typeof route> = (ctx) => ctx.json(namespaces);
const handler: RouteHandler<typeof route> = async (ctx) => {
await ensureAllLoaded();
return ctx.json(namespaces);
};
export { handler, route };
+3 -2
View File
@@ -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<typeof route> = (ctx) => {
const handler: RouteHandler<typeof route> = 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('/')]);
};
+5 -41
View File
@@ -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<typeof route> = (ctx) => ctx.json(radar);
const handler: RouteHandler<typeof route> = async (ctx) => {
const rules = await getRadarRules();
return ctx.json(rules);
};
export { handler, route };
+5 -2
View File
@@ -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);
+4 -42
View File
@@ -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<typeof route> = (ctx) => {
const handler: RouteHandler<typeof route> = 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 };
+49
View File
@@ -0,0 +1,49 @@
import { parse } from 'tldts';
import { ensureAllLoaded, namespaces } from '@/registry';
import type { RadarDomain } from '@/types';
let radar: Record<string, RadarDomain> | undefined;
export const getRadarRules = async (): Promise<Record<string, RadarDomain>> => {
if (radar) {
return radar;
}
await ensureAllLoaded();
const rules: Record<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(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;
};
+2 -1
View File
@@ -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<typeof route> = 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);
+1 -1
View File
@@ -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':
+1
View File
@@ -16,6 +16,7 @@ vi.mock('@/utils/cache/index', () => ({
globalCache: {
get: getSpy,
set: setSpy,
claim: vi.fn(() => true),
},
},
}));
+15 -7
View File
@@ -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);
+1 -1
View File
@@ -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, {
+217
View File
@@ -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<string, Record<string, unknown>> = {
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 });
}
});
});
+126
View File
@@ -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<void>;
};
/**
* 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<string, Promise<Hono>>();
const outerContexts = new WeakMap<Request, Context>();
// 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<string, unknown>;
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<Hono> => {
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<Hono> => {
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<void> => {
await Promise.all([...topDirectories].map((name) => ensureTopDirectory(name)));
};
return { middleware, ensureAllLoaded };
}
+237
View File
@@ -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<string, { route: Route } | { namespace: Namespace } | { apiRoute: APIRoute }>;
/**
* 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<string> {
const roots = new Set<string>();
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<string>): { 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);
}
}
}
+139 -130
View File
@@ -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<typeof fs>();
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<string, Record<string, unknown>>) => {
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');
});
});
+29 -243
View File
@@ -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<string> {
const roots = new Set<string>();
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<string>): { 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<string, { route: Route } | { namespace: Namespace }> = {};
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<void> = 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(
'/*',
+2 -1
View File
@@ -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 () => {
+2 -1
View File
@@ -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, {
+3 -3
View File
@@ -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,
});
+2 -2
View File
@@ -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,
+35
View File
@@ -11,10 +11,16 @@ const globalCache: {
get: (key: string) => Promise<string | null | undefined> | string | null | undefined;
has: (key: string) => Promise<boolean> | boolean;
set: (key: string, value?: string | Record<string, any>, 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> | 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:
+13
View File
@@ -11,6 +11,11 @@ import kv, { getKVNamespace } from './kv';
const globalCache: {
get: (key: string) => Promise<string | null | undefined> | string | null | undefined;
set: (key: string, value?: string | Record<string, any>, 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> | 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
+38 -28
View File
@@ -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);
});
});
+9 -7
View File
@@ -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,
};
};
+1 -1
View File
@@ -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",
+20 -75
View File
@@ -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: {}
+2 -1
View File
@@ -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<string, string[]> = {};
const radar: {
+14
View File
@@ -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';
},
},
});