static-server.mjs
6.31 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/**
* 内置静态服务 —— 把产物目录当成真实站点来访问。
*
* 它同时服务两个场景,所以必须只有一份实现:
* - release-verify 用它做自检(起在随机端口,跑完即退)
* - release-all 用它做本地预览(起在固定端口,占住终端)
*
* 两份实现会漂移成「预览能开、自检说没事、上线却挂」,所以刻意不复写。
*
* 行为刻意对齐 DEPLOY.md 里的 nginx 配置,好在本地就复现线上的坑:
* /mfe/** 找不到就是 404,绝不回落(线上 `location ^~ /mfe/ { try_files $uri $uri/ =404; }`)
* 其它 目录取 index.html,缺文件回落主壳(线上 `location / { try_files $uri $uri/ /index.html; }`)
*/
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { pathToFileURL } from 'node:url';
const MIME = {
'.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',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.map': 'application/json; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
};
/**
* @param {string} dir 站点根(产物目录)
* @param {{ port?: number, host?: string }} [opts] port=0 时由系统分配
* @returns {Promise<{ server: import('node:http').Server, port: number, url: string }>}
*/
export function startStaticServer(dir, opts = {}) {
const rootDir = path.resolve(dir);
const port = opts.port ?? 0;
const host = opts.host ?? '127.0.0.1';
return new Promise((resolve, reject) => {
const server = http.createServer((req, res) => {
let pathname;
try {
pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname);
} catch {
res.writeHead(400).end('bad request');
return;
}
const send404 = () => {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.end('404 not found');
};
const resolveFile = (p) => {
const abs = path.join(rootDir, p);
if (!abs.startsWith(rootDir)) return null; // 防目录穿越
if (!fs.existsSync(abs)) return null;
const st = fs.statSync(abs);
if (st.isDirectory()) {
const idx = path.join(abs, 'index.html');
return fs.existsSync(idx) ? idx : null;
}
return st.isFile() ? abs : null;
};
const withHeaders = (file, status = 200) => {
const ext = path.extname(file).toLowerCase();
const base = path.basename(file);
const headers = { 'content-type': MIME[ext] ?? 'application/octet-stream' };
// 与 DEPLOY.md 的缓存约定一致:入口类 no-cache,带 hash 的资源长缓存
headers['cache-control'] =
base === 'index.html' || base === 'manifest.json'
? 'no-cache'
: 'public, max-age=31536000, immutable';
res.writeHead(status, headers);
fs.createReadStream(file).pipe(res);
};
if (pathname.startsWith('/mfe/')) {
const file = resolveFile(pathname);
if (file) withHeaders(file);
else send404();
return;
}
// 主壳侧:真实文件优先,目录取 index.html,其余回落到根 index.html(SPA)
const direct = resolveFile(pathname);
if (direct) {
withHeaders(direct);
return;
}
const fallback = path.join(rootDir, 'index.html');
if (fs.existsSync(fallback)) {
withHeaders(fallback);
return;
}
send404();
});
server.on('error', reject);
server.listen(port, host, () => {
const actual = server.address().port;
resolve({ server, port: actual, url: `http://${host}:${actual}` });
});
});
}
export { MIME };
// ---------------------------------------------------------------------------
// CLI:pnpm release:preview [--dir dist] [--port 4180]
//
// 存在的理由:产物里的资源是绝对路径(/mfe/host/<ver>/assets/...),
// 只有「站点根 = 产物目录」时才解析得对。任何以仓库根为根的服务器
// (最典型是 VS Code Live Server 默认行为)都会把 /mfe/... 找成 <仓库>/mfe/...,
// 404 又被返回成 HTML,浏览器报 MIME 错误 + 资源 404,看起来像产物坏了。
// ---------------------------------------------------------------------------
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const argv = process.argv.slice(2);
// 取最后一次出现,这样 `pnpm release:preview -- --port 5180` 的追加参数能覆盖默认值
const getArg = (name) => {
const i = argv.lastIndexOf(`--${name}`);
return i >= 0 ? argv[i + 1] : undefined;
};
if (argv.includes('--help') || argv.includes('-h')) {
console.log(`用法: node scripts/release/static-server.mjs [--dir <产物目录>] [--port <n>] [--host <h>]
--dir 站点根,默认 dist(= 部署根镜像)
--port 端口,默认 4180;被占用时自动往后找 10 个
--host 监听地址,默认 127.0.0.1`);
process.exit(0);
}
const dir = path.resolve(getArg('dir') ?? 'dist');
if (!fs.existsSync(path.join(dir, 'index.html'))) {
console.error(`\n ✗ ${dir} 下没有 index.html,不是有效的站点根。`);
console.error(' 先跑 pnpm release:all(或 pnpm release --app <name>)生成产物。\n');
process.exit(1);
}
const basePort = Number(getArg('port') ?? 4180);
const host = getArg('host') ?? '127.0.0.1';
let started;
for (let p = basePort; p < basePort + 10 && !started; p += 1) {
try {
started = await startStaticServer(dir, { port: p, host });
} catch (err) {
if (err.code !== 'EADDRINUSE') throw err;
}
}
if (!started) {
console.error(` ✗ 端口 ${basePort}-${basePort + 9} 全被占用,用 --port 换一个。`);
process.exit(1);
}
console.log(`\n 站点根 ${dir}`);
console.log(` 预览 ${started.url}\n`);
console.log(' 行为对齐线上 nginx:/mfe/** 缺失即 404(不回落),其它路径回落到主壳。');
console.log(' Ctrl+C 停止。\n');
}