Files
RSSHub/lib/registry.ts
T
DIYgodandClaude Opus 4.5 1131350b5f feat: deploy RSSHub to Cloudflare Workers (#20804)
* feat: deploy RSSHub to Cloudflare Workers

- Create Worker entry point (lib/worker.ts) with polyfills
- Implement Worker-specific app configuration (lib/app.worker.tsx)
- Add automatic .worker.ts resolution plugin for cleaner config
- Simplify build configuration with only 3 essential shims
- Enable static asset serving via Cloudflare Static Assets feature
- Support dynamic route loading with proper module aliasing

🤖 Generated with Claude Code

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* feat(worker): add puppeteer and request-rewriter support

- Add @cloudflare/puppeteer for Browser Rendering API support
- Create puppeteer.worker.ts with Cloudflare Browser binding
- Add request-rewriter Worker version with static browser headers
- Add vm module shim to node-module.ts for JSDOM compatibility
- Configure __dirname/__filename in tsdown for CommonJS compat
- Update wrangler.toml with BROWSER binding configuration
- Dynamically extract namespaces from foloAnalysisTop100 for routes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(cache): restore synchronous initialization for tests

The async initialization caused cache tests to fail because the cache
module wasn't ready when tests ran. Restored synchronous imports while
keeping Worker-specific no-op behavior.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test(worker): add automated Worker integration tests

- Add miniflare for Worker environment simulation
- Create lib/worker.worker.test.ts with integration tests
- Test basic routes (/test/1, /, unknown routes)
- Test RSS feed routes (hackernews, v2ex)
- Test error handling for puppeteer routes without BROWSER binding
- Add worker-test npm script

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(worker): use test routes for Worker integration tests

- Replace third-party routes (hackernews, v2ex, weibo) with /test/* routes
- Remove miniflare dependency (wrangler includes it internally)
- Simplify test setup using wrangler's unstable_dev API

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(test): make header-generator test less flaky

The header-generator library may return different platform values due to
internal randomness. Update test to check for valid format instead of
exact value.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(test): exclude worker tests from vitest coverage run

Worker tests require the dist-worker bundle to be built first,
which is not part of the regular CI test workflow. These tests
should be run separately using 'pnpm worker-test'.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test(worker): add automated Worker integration tests

- Add worker-build step to CI workflow before running tests
- Revert exclusion of worker tests from vitest coverage run
- Worker tests now run as part of the regular test suite

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(worker): fix routes.js alias path in worker build config

Change alias key from absolute path to relative import path to match
how it's imported in lib/registry.ts. This fixes the worker build
failing with "Could not resolve '../assets/build/routes.js'" error.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* ci: trigger CI re-run

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(ci): build worker routes before worker-build

The worker build requires routes-worker.js which is generated by
running build:routes with WORKER_BUILD=true. This was missing in CI,
causing the worker build to fail with "Could not resolve routes.js".

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(test): increase timeout for Worker integration tests

Worker tests need more time in CI environments. Increase individual
test timeouts from default 10s to 30s for each test case.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-01-04 09:22:05 +08:00

275 lines
8.5 KiB
TypeScript

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 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 { isWorker } from '@/utils/is-worker';
import logger from '@/utils/logger';
const __dirname = import.meta.dirname;
function isSafeRoutes(routes: RoutesType): boolean {
return Object.values(routes).every((route: Route) => !route.features?.nsfw);
}
function safeNamespaces(namespaces: NamespacesType): NamespacesType {
const safe: NamespacesType = {};
for (const [key, value] of Object.entries(namespaces)) {
if (value.routes === null || value.routes === undefined || isSafeRoutes(value.routes)) {
safe[key] = value;
}
}
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 = {};
if (config.isPackage) {
namespaces = (await import('../assets/build/routes.js')).default;
} else {
switch (process.env.NODE_ENV || process.env.VERCEL_ENV) {
case 'production':
namespaces = (await import('../assets/build/routes.js')).default;
break;
case 'test':
// @ts-expect-error
namespaces = await import('../assets/build/routes.json');
if (namespaces.default) {
// @ts-ignore
namespaces = namespaces.default;
}
break;
default:
modules = directoryImport({
targetDirectoryPath: path.join(__dirname, './routes'),
importPattern: /\.tsx?$/,
}) as typeof modules;
}
}
if (config.feature.disable_nsfw) {
namespaces = safeNamespaces(namespaces);
}
if (Object.keys(modules).length) {
for (const module in modules) {
const content = modules[module] as
| {
route: Route;
}
| {
namespace: Namespace;
}
| {
apiRoute: APIRoute;
};
const namespace = module.split(/[/\\]/)[1];
if ('namespace' in content) {
namespaces[namespace] = Object.assign(
{
routes: {},
},
namespaces[namespace],
content.namespace
);
} else if ('route' in content) {
if (!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: module.split(/[/\\]/).slice(2).join('/'),
};
}
} else {
namespaces[namespace].routes[content.route.path] = {
...content.route,
location: module.split(/[/\\]/).slice(2).join('/'),
};
}
} else if ('apiRoute' in content) {
if (!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: module.split(/[/\\]/).slice(2).join('/'),
};
}
} else {
namespaces[namespace].apiRoutes[content.apiRoute.path] = {
...content.apiRoute,
location: module.split(/[/\\]/).slice(2).join('/'),
};
}
}
}
}
export { namespaces };
const app = new Hono();
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;
}
}
return 0;
});
for (const namespace in 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);
}
}
for (const namespace in 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')) {
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);
}
}
app.get('/', index);
app.get('/healthz', healthz);
app.get('/robots.txt', robotstxt);
if (config.debugInfo) {
// Only enable tracing in debug mode
app.get('/metrics', metrics);
}
if (!config.isPackage && !process.env.VERCEL_ENV && !isWorker) {
app.use(
'/*',
serveStatic({
root: path.join(__dirname, 'assets'),
rewriteRequestPath: (path) => (path === '/favicon.ico' ? '/favicon.png' : path),
})
);
}
export default app;