http-utils.ts
2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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;
}