feat: simplify asset serving and enhance bootstrap response handling

This commit is contained in:
shuaiplus
2026-03-19 00:52:58 +08:00
parent facd0ea5f7
commit 5ff322d809
5 changed files with 43 additions and 43 deletions
+1 -30
View File
@@ -4,7 +4,6 @@ import { handleRequest } from './router';
import { StorageService } from './services/storage';
import { applyCors, jsonResponse } from './utils/response';
import { runScheduledBackupIfDue } from './handlers/backup';
import { buildWebBootstrapResponse } from './router-public';
let dbInitialized = false;
let dbInitError: string | null = null;
@@ -23,41 +22,13 @@ function isWorkerHandledPath(path: string): boolean {
);
}
function injectBootstrapIntoHtml(html: string, env: Env): string {
const payload = JSON.stringify(buildWebBootstrapResponse(env)).replace(/</g, '\\u003c');
const script = `<script>window.__NW_BOOT__=${payload};</script>`;
if (html.includes('</head>')) {
return html.replace('</head>', `${script}</head>`);
}
return `${script}${html}`;
}
function responseStatusCannotHaveBody(status: number): boolean {
return status === 101 || status === 204 || status === 205 || status === 304;
}
async function maybeServeAsset(request: Request, env: Env): Promise<Response | null> {
if (!env.ASSETS) return null;
if (request.method !== 'GET' && request.method !== 'HEAD') return null;
const url = new URL(request.url);
if (isWorkerHandledPath(url.pathname)) return null;
const assetResponse = await env.ASSETS.fetch(request);
const contentType = String(assetResponse.headers.get('Content-Type') || '').toLowerCase();
if (
request.method === 'GET' &&
contentType.includes('text/html') &&
!responseStatusCannotHaveBody(assetResponse.status)
) {
const html = await assetResponse.text();
const injected = injectBootstrapIntoHtml(html, env);
return new Response(injected, {
status: assetResponse.status,
statusText: assetResponse.statusText,
headers: assetResponse.headers,
});
}
return assetResponse;
return env.ASSETS.fetch(request);
}
async function ensureDatabaseInitialized(env: Env): Promise<void> {
+6
View File
@@ -175,6 +175,12 @@ export async function handlePublicRoute(
});
}
if ((path === '/api/web-bootstrap' || path === '/web-bootstrap') && method === 'GET') {
const blocked = await enforcePublicRateLimit('public-read', LIMITS.rateLimit.publicReadRequestsPerMinute);
if (blocked) return blocked;
return jsonResponse(buildWebBootstrapResponse(env));
}
const iconMatch = path.match(/^\/icons\/([^/]+)\/icon\.png$/i);
if (iconMatch && method === 'GET') {
return handleWebsiteIcon(iconMatch[1]);