import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import type { H3Event } from 'h3' /** 是否为需要回退到 admin/index.html 的 SPA 路由(非静态资源) */ export function isAdminSpaRoute(pathname: string): boolean { if (!pathname.startsWith('/admin')) return false const rest = pathname.slice('/admin'.length) if (!rest || rest === '/') return true const last = rest.split('/').pop() || '' // 带扩展名的路径交给 Nitro 静态资源处理,如 /admin/assets/*.js if (/\.[a-z0-9]+$/i.test(last)) return false return true } /** 解析 admin 构建产物目录(兼容 dev / preview / production 多种 cwd) */ function resolveAdminIndexPath(): string | null { const candidates = [ join(process.cwd(), 'public', 'admin', 'index.html'), join(process.cwd(), '.output', 'public', 'admin', 'index.html'), ] for (const filePath of candidates) { if (existsSync(filePath)) return filePath } return null } export async function serveAdminSpa(event: H3Event) { const indexPath = resolveAdminIndexPath() if (!indexPath) { throw createError({ statusCode: 404, statusMessage: 'Admin not built. Run: cd admin && npm run build-only', }) } const html = readFileSync(indexPath, 'utf-8') setHeader(event, 'Content-Type', 'text/html; charset=utf-8') setHeader(event, 'Cache-Control', 'no-cache') return html }