http-utils.ts 2.68 KB
import { readFileSync, existsSync, statSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { ServerResponse } from 'node:http';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_INDEX = path.join(__dirname, '..', 'public', 'index.html');
// Phase 2 前端工程构建产物:apps/web/dist。存在时优先托管它(支持 SPA 路由)。
export const WEB_DIST = path.join(__dirname, '..', '..', 'web', 'dist');

const MIME: Record<string, string> = {
    '.html': 'text/html; charset=utf-8',
    '.js': 'text/javascript; charset=utf-8',
    '.mjs': 'text/javascript; charset=utf-8',
    '.css': 'text/css; charset=utf-8',
    '.json': 'application/json; charset=utf-8',
    '.svg': 'image/svg+xml',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.ico': 'image/x-icon',
    '.woff': 'font/woff',
    '.woff2': 'font/woff2',
    '.ttf': 'font/ttf',
    '.map': 'application/json',
};

/** 目录选择器中隐藏的“噪音”目录,保持文件树可读。 */
export const FS_NOISE = new Set([
    'node_modules',
    '.git',
    '.next',
    '.nuxt',
    '.turbo',
    '.cache',
    'dist',
    'build',
    'out',
    'coverage',
    '.svelte-kit',
    '.output',
    '.workbuddy',
    '.trash',
    '.trash-win',
]);

/** 目录选择器的初始顶层根视图。 */
export function listRoots(): string[] {
    if (process.platform === 'win32') {
        const drives: string[] = [];
        for (const c of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
            try {
                if (existsSync(`${c}:\\`)) drives.push(`${c}:\\`);
            } catch {
                /* 不可访问的盘符,跳过 */
            }
        }
        return drives.length ? drives : ['C:\\'];
    }
    return ['/'];
}

/** 以正确的 MIME 类型读取并返回静态文件;失败返回 404。 */
export function serveStaticFile(res: ServerResponse, filePath: string): void {
    try {
        const data = readFileSync(filePath);
        const ext = path.extname(filePath).toLowerCase();
        res.writeHead(200, {
            'Content-Type': MIME[ext] ?? 'application/octet-stream',
            'Cache-Control': 'no-cache',
        });
        res.end(data);
    } catch {
        res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end('Not Found');
    }
}

/** 解析要返回的 index.html:优先 Phase 2 构建产物,否则回退到 public 内置页。 */
export function resolveIndexHtml(): string {
    if (WEB_DIST && existsSync(path.join(WEB_DIST, 'index.html'))) {
        return path.join(WEB_DIST, 'index.html');
    }
    return PUBLIC_INDEX;
}