soma-core 2.1.6 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/bin/soma.cjs +1 -1
- package/bin/soma.ts +64 -15
- package/core/server/api/dispatch-service-api.ts +212 -0
- package/core/server/api/load-host-service.ts +230 -56
- package/core/server/api/service-path.ts +78 -14
- package/core/server/engines/style/candidate-guard.ts +57 -0
- package/core/server/engines/style/index.ts +1 -1
- package/core/server/engines/style/tailwind-adapter.ts +83 -16
- package/core/server/host/source-packages.cjs +96 -30
- package/core/server/host/source-packages.ts +12 -5
- package/core/server/index.ts +39 -17
- package/core/server/infra/cache/ServerFileCache.ts +138 -25
- package/core/server/node.ts +32 -8
- package/dist/cli/soma.js +68 -14
- package/dist/host-native/aot-builder.cjs +850 -0
- package/dist/host-native/native-server.cjs +15338 -0
- package/dist/types/server/api/dispatch-service-api.d.ts +18 -0
- package/dist/types/server/api/load-host-service.d.ts +7 -2
- package/dist/types/server/api/service-path.d.ts +21 -1
- package/dist/types/server/engines/style/candidate-guard.d.ts +10 -0
- package/dist/types/server/engines/style/index.d.ts +1 -1
- package/dist/types/server/engines/style/tailwind-adapter.d.ts +12 -0
- package/dist/types/server/host/source-packages.d.cts +13 -1
- package/dist/types/server/host/source-packages.d.ts +7 -4
- package/dist/types/server/index.d.ts +18 -17
- package/dist/types/server/infra/cache/ServerFileCache.d.ts +28 -5
- package/dist/types/server/node.d.ts +10 -7
- package/host-native/bin/host-native.cjs +204 -0
- package/host-native/client/browser-entry.ts +499 -0
- package/{host-next/app → host-native/client}/page-access.ts +12 -0
- package/host-native/client/router-bridge.ts +120 -0
- package/host-native/src/aot-builder.ts +486 -0
- package/host-native/src/csp-headers.ts +75 -0
- package/host-native/src/host-prepare.ts +123 -0
- package/{host-next/app/soma/manifest/route.ts → host-native/src/manifest-http.ts} +10 -10
- package/host-native/src/native-server.ts +691 -0
- package/host-native/src/page-http.ts +223 -0
- package/host-native/src/public-packages.cjs +167 -0
- package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts} +17 -19
- package/{host-next → host-native}/src/shell-routes.cjs +23 -13
- package/host-native/src/static-file.ts +172 -0
- package/host-native/src/workspace.ts +185 -0
- package/{host-next/app → host-native/styles}/globals.css +2 -2
- package/package.json +12 -31
- package/tsconfig.json +1 -1
- package/host-next/app/SomaPageClient.tsx +0 -359
- package/host-next/app/[...path]/page.tsx +0 -22
- package/host-next/app/api/[...path]/route.ts +0 -98
- package/host-next/app/components/SomaHostPage.tsx +0 -128
- package/host-next/app/components/SomaHydrationShell.tsx +0 -20
- package/host-next/app/components/SomaPageClientBoundary.tsx +0 -13
- package/host-next/app/components/SomaPageForbidden.tsx +0 -19
- package/host-next/app/favicon.ico/route.ts +0 -13
- package/host-next/app/layout.tsx +0 -27
- package/host-next/app/page.tsx +0 -9
- package/host-next/app/router-bridge.ts +0 -42
- package/host-next/app/soma/[...path]/route.ts +0 -9
- package/host-next/app/soma/_shared/host-prepare.ts +0 -33
- package/host-next/app/soma/_shared/page-http.ts +0 -86
- package/host-next/app/soma/page/route.ts +0 -36
- package/host-next/app/soma/route.ts +0 -9
- package/host-next/app/soma-runtime/[...file]/route.ts +0 -21
- package/host-next/app/soma-runtime/_shared/static-file.ts +0 -89
- package/host-next/bin/host-next.cjs +0 -60
- package/host-next/instrumentation.ts +0 -18
- package/host-next/next-env.d.ts +0 -7
- package/host-next/next.config.js +0 -410
- package/host-next/proxy.ts +0 -43
- package/host-next/src/workspace.ts +0 -543
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import zlib from 'node:zlib';
|
|
6
|
+
import { getSomaHostSourceRoot, getSomaHostApiRoot } from '../../core/server/host/source-packages.cjs';
|
|
7
|
+
import { resolveSomaRuntimeLayout } from '../../core/server/runtime-space/root';
|
|
8
|
+
import { loadPageByAddress } from '../../core/server/runtime-space';
|
|
9
|
+
import { readHostAppDisplayName } from '../../core/server/host/app-config-composer';
|
|
10
|
+
import { invokeHostRequestHook } from '../../core/server/host/invoke-host-request-hook';
|
|
11
|
+
import { dispatchHostServiceApiRequest } from '../../core/server/api/dispatch-service-api';
|
|
12
|
+
import { registerAotServiceResolver } from '../../core/server/api/load-host-service';
|
|
13
|
+
import { toPascalCase } from '../../core/server/api/service-path';
|
|
14
|
+
import { runHostStartup } from 'soma-core/server/host-assembly';
|
|
15
|
+
import { clearTailwindCompilerCache } from 'soma-core/server/style-engine';
|
|
16
|
+
import { resolveHostResponseHeaders } from '../../core/server/host/host-response-headers';
|
|
17
|
+
import type { BrowserClientBuildResult, ServerAotManifest } from './aot-builder';
|
|
18
|
+
import { pageSuccessResponse, pageErrorResponse } from './page-http';
|
|
19
|
+
import { handleManifestGet } from './manifest-http';
|
|
20
|
+
import { prepareHostAssembly } from './host-prepare';
|
|
21
|
+
import { staticResponse } from './static-file';
|
|
22
|
+
import {
|
|
23
|
+
applyHostAndCspHeaders,
|
|
24
|
+
createSomaCspHeader,
|
|
25
|
+
readCspNonceMeta,
|
|
26
|
+
resolveSomaCspOptionsFromEnv,
|
|
27
|
+
} from './csp-headers';
|
|
28
|
+
|
|
29
|
+
export interface CreateNativeServerOptions {
|
|
30
|
+
readonly hostDir: string;
|
|
31
|
+
readonly webRoot?: string;
|
|
32
|
+
readonly apiRoot?: string;
|
|
33
|
+
readonly port?: number;
|
|
34
|
+
readonly hostname?: string;
|
|
35
|
+
readonly dev?: boolean;
|
|
36
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface NativeServerInstance {
|
|
40
|
+
readonly server: http.Server;
|
|
41
|
+
readonly port: number;
|
|
42
|
+
readonly url: string;
|
|
43
|
+
start(): Promise<{ url: string; port: number }>;
|
|
44
|
+
close(): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function escapeHtml(str: string): string {
|
|
48
|
+
return str
|
|
49
|
+
.replace(/&/g, '&')
|
|
50
|
+
.replace(/</g, '<')
|
|
51
|
+
.replace(/>/g, '>')
|
|
52
|
+
.replace(/"/g, '"')
|
|
53
|
+
.replace(/'/g, ''');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function extractHtmlBodyInner(html: string): string {
|
|
57
|
+
const match = html.match(/<body\b[^>]*>([\s\S]*)<\/body>/i);
|
|
58
|
+
return (match?.[1] ?? html).trim();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function readRejectedMessage(response: Response): Promise<string> {
|
|
62
|
+
try {
|
|
63
|
+
const payload = (await response.clone().json()) as { error?: unknown; message?: unknown };
|
|
64
|
+
const msg = payload.error ?? payload.message;
|
|
65
|
+
if (typeof msg === 'string' && msg.trim()) return msg.trim();
|
|
66
|
+
} catch {}
|
|
67
|
+
try {
|
|
68
|
+
const txt = await response.clone().text();
|
|
69
|
+
if (txt.trim()) return txt.trim();
|
|
70
|
+
} catch {}
|
|
71
|
+
return response.statusText || 'Request rejected';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function installAotManifest(manifestPath: string, hostDir: string): void {
|
|
75
|
+
if (!fs.existsSync(manifestPath)) return;
|
|
76
|
+
try {
|
|
77
|
+
const raw = fs.readFileSync(manifestPath, 'utf8');
|
|
78
|
+
const manifest: ServerAotManifest = JSON.parse(raw);
|
|
79
|
+
const baseDir = path.dirname(manifestPath);
|
|
80
|
+
|
|
81
|
+
registerAotServiceResolver(hostDir, (routeKey, segments) => {
|
|
82
|
+
const pascalRouteKey = segments.length > 0
|
|
83
|
+
? segments.slice(0, -1).concat(toPascalCase(segments[segments.length - 1])).join('/')
|
|
84
|
+
: routeKey;
|
|
85
|
+
const targetRel = manifest.routes[routeKey] || manifest.routes[pascalRouteKey] || manifest.routes[routeKey.toLowerCase()];
|
|
86
|
+
if (targetRel) {
|
|
87
|
+
const absFile = path.resolve(baseDir, targetRel);
|
|
88
|
+
if (fs.existsSync(absFile)) {
|
|
89
|
+
return require(absFile);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
});
|
|
94
|
+
} catch (err) {
|
|
95
|
+
console.warn('[soma-native] Failed to register AOT manifest resolver:', err);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 将 Node IncomingMessage 转换为标准 Request 对象
|
|
101
|
+
*/
|
|
102
|
+
async function toWebRequest(req: http.IncomingMessage, origin: string): Promise<Request> {
|
|
103
|
+
const url = new URL(req.url || '/', origin);
|
|
104
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
105
|
+
const headers = new Headers();
|
|
106
|
+
|
|
107
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
108
|
+
if (value === undefined) continue;
|
|
109
|
+
if (Array.isArray(value)) {
|
|
110
|
+
for (const v of value) headers.append(key, v);
|
|
111
|
+
} else {
|
|
112
|
+
headers.set(key, value);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let body: Uint8Array | null = null;
|
|
117
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
118
|
+
const chunks: Buffer[] = [];
|
|
119
|
+
let totalLength = 0;
|
|
120
|
+
const MAX_BODY_BYTES = 32 * 1024 * 1024; // 32MB 防内存攻击
|
|
121
|
+
|
|
122
|
+
for await (const chunk of req) {
|
|
123
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
124
|
+
totalLength += buf.length;
|
|
125
|
+
if (totalLength > MAX_BODY_BYTES) {
|
|
126
|
+
throw new Error('Request body payload too large (max 32MB)');
|
|
127
|
+
}
|
|
128
|
+
chunks.push(buf);
|
|
129
|
+
}
|
|
130
|
+
body = Buffer.concat(chunks);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return new Request(url.toString(), {
|
|
134
|
+
method,
|
|
135
|
+
headers,
|
|
136
|
+
...(body ? { body: body as unknown as BodyInit, duplex: 'half' as any } : {}),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 将标准 Web Response 写入 Node ServerResponse
|
|
142
|
+
*/
|
|
143
|
+
async function sendWebResponse(webRes: Response, res: http.ServerResponse): Promise<void> {
|
|
144
|
+
res.statusCode = webRes.status;
|
|
145
|
+
|
|
146
|
+
if (typeof (webRes.headers as any).getSetCookie === 'function') {
|
|
147
|
+
const cookies = (webRes.headers as any).getSetCookie();
|
|
148
|
+
if (Array.isArray(cookies) && cookies.length > 0) {
|
|
149
|
+
res.setHeader('set-cookie', cookies);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
for (const [key, value] of webRes.headers.entries()) {
|
|
154
|
+
if (key.toLowerCase() === 'set-cookie') continue;
|
|
155
|
+
res.setHeader(key, value);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (webRes.body) {
|
|
159
|
+
const arrayBuffer = await webRes.arrayBuffer();
|
|
160
|
+
res.end(Buffer.from(arrayBuffer));
|
|
161
|
+
} else {
|
|
162
|
+
res.end();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function createNativeServer(
|
|
167
|
+
options: CreateNativeServerOptions,
|
|
168
|
+
): Promise<NativeServerInstance> {
|
|
169
|
+
const hostDir = path.resolve(options.hostDir);
|
|
170
|
+
const prevWebDir = process.env.SOMA_WEB_DIR;
|
|
171
|
+
const prevApiDir = process.env.SOMA_API_DIR;
|
|
172
|
+
if (options.webRoot) {
|
|
173
|
+
process.env.SOMA_WEB_DIR = path.resolve(options.webRoot);
|
|
174
|
+
}
|
|
175
|
+
if (options.apiRoot) {
|
|
176
|
+
process.env.SOMA_API_DIR = path.resolve(options.apiRoot);
|
|
177
|
+
}
|
|
178
|
+
const env = options.env ?? process.env;
|
|
179
|
+
const webRoot = path.resolve(options.webRoot || getSomaHostSourceRoot(hostDir, env));
|
|
180
|
+
const apiRoot = path.resolve(options.apiRoot || getSomaHostApiRoot(hostDir, env));
|
|
181
|
+
const dev = Boolean(options.dev);
|
|
182
|
+
const runtimeLayout = resolveSomaRuntimeLayout(hostDir, env);
|
|
183
|
+
|
|
184
|
+
// 1. 若存在 AOT 服务清单,立即登记 AOT 解析器
|
|
185
|
+
const aotManifestPath = path.join(runtimeLayout.dirs.root, 'aot-server/aot-manifest.json');
|
|
186
|
+
installAotManifest(aotManifestPath, hostDir);
|
|
187
|
+
|
|
188
|
+
await runHostStartup(hostDir);
|
|
189
|
+
|
|
190
|
+
// 2. 准备客户端产物(生产态优先直接读取预编译清单,零 esbuild 驻留)
|
|
191
|
+
const clientManifestPath = path.join(runtimeLayout.dirs.static, 'client', 'client-manifest.json');
|
|
192
|
+
let clientBuild: BrowserClientBuildResult;
|
|
193
|
+
if (!dev && fs.existsSync(clientManifestPath)) {
|
|
194
|
+
const parsed = JSON.parse(fs.readFileSync(clientManifestPath, 'utf8')) as {
|
|
195
|
+
entryUrl: string;
|
|
196
|
+
cssUrl: string;
|
|
197
|
+
cssText: string;
|
|
198
|
+
};
|
|
199
|
+
clientBuild = {
|
|
200
|
+
entryUrl: parsed.entryUrl,
|
|
201
|
+
cssUrl: parsed.cssUrl,
|
|
202
|
+
cssText: parsed.cssText,
|
|
203
|
+
rebuild: async () => {},
|
|
204
|
+
dispose: async () => {},
|
|
205
|
+
};
|
|
206
|
+
} else {
|
|
207
|
+
const { buildBrowserClient } = await import('./aot-builder');
|
|
208
|
+
clientBuild = await buildBrowserClient({
|
|
209
|
+
hostDir,
|
|
210
|
+
webRoot,
|
|
211
|
+
outDir: runtimeLayout.dirs.static,
|
|
212
|
+
dev,
|
|
213
|
+
env,
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// 预构建静态 HTML 外壳缓冲(CSP 关闭时零字符串拼接、零实时压缩直出)
|
|
218
|
+
let cachedStaticShell: { key: string; utf8: Buffer; gzip: Buffer } | null = null;
|
|
219
|
+
function getStaticShellBuffers(titleText: string): { utf8: Buffer; gzip: Buffer } {
|
|
220
|
+
const key = `${titleText}\0${clientBuild.entryUrl}\0${clientBuild.cssText.length}\0${dev ? '1' : '0'}`;
|
|
221
|
+
if (cachedStaticShell && cachedStaticShell.key === key) return cachedStaticShell;
|
|
222
|
+
const devSse = dev ? '<script>window.__SOMA_DEV_SSE__ = true;</script>\n ' : '';
|
|
223
|
+
const html = `<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>${escapeHtml(titleText)}</title>\n <style>${clientBuild.cssText}</style>\n <script>\n try {\n const theme = localStorage.getItem('soma-theme');\n if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {\n document.documentElement.setAttribute('data-theme', 'dark');\n }\n } catch (_) {}\n </script>\n ${devSse}</head>\n<body>\n <div id="soma-app-root">\n <div class="soma-hydration-shell">\n <div class="soma-hydration-shell__bar"></div>\n </div>\n </div>\n <script type="module" src="${clientBuild.entryUrl}"></script>\n</body>\n</html>`;
|
|
224
|
+
const utf8 = Buffer.from(html, 'utf8');
|
|
225
|
+
const gzip = zlib.gzipSync(utf8);
|
|
226
|
+
cachedStaticShell = { key, utf8, gzip };
|
|
227
|
+
return cachedStaticShell;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// 3. SSE 热更新客户端集合
|
|
231
|
+
const sseClients = new Set<http.ServerResponse>();
|
|
232
|
+
let hmrHeartbeatTimer: NodeJS.Timeout | null = null;
|
|
233
|
+
if (dev) {
|
|
234
|
+
hmrHeartbeatTimer = setInterval(() => {
|
|
235
|
+
for (const client of sseClients) {
|
|
236
|
+
try {
|
|
237
|
+
client.write(': heartbeat\n\n');
|
|
238
|
+
} catch {
|
|
239
|
+
sseClients.delete(client);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}, 15000);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function broadcastHmr(event: string, data?: string) {
|
|
246
|
+
for (const client of sseClients) {
|
|
247
|
+
try {
|
|
248
|
+
client.write(`event: ${event}\ndata: ${data || ''}\n\n`);
|
|
249
|
+
} catch {
|
|
250
|
+
sseClients.delete(client);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// 4. 开发态仅监听前端目录文件变动
|
|
256
|
+
let fsWatcher: fs.FSWatcher | null = null;
|
|
257
|
+
if (dev) {
|
|
258
|
+
try {
|
|
259
|
+
let debounceTimer: NodeJS.Timeout | null = null;
|
|
260
|
+
fsWatcher = fs.watch(webRoot, { recursive: true }, (event, filename) => {
|
|
261
|
+
if (!filename) return;
|
|
262
|
+
const norm = filename.replace(/\\/g, '/');
|
|
263
|
+
if (
|
|
264
|
+
norm.startsWith('.') ||
|
|
265
|
+
norm.startsWith('node_modules') ||
|
|
266
|
+
norm.startsWith('.soma') ||
|
|
267
|
+
norm.startsWith('dist')
|
|
268
|
+
) {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
// 如果 apiRoot 位于 webRoot 之下,跳过后端文件变动
|
|
272
|
+
const full = path.join(webRoot, filename);
|
|
273
|
+
if (full.startsWith(apiRoot + path.sep)) return;
|
|
274
|
+
|
|
275
|
+
if (debounceTimer) clearTimeout(debounceTimer);
|
|
276
|
+
debounceTimer = setTimeout(async () => {
|
|
277
|
+
try {
|
|
278
|
+
if (/\.(?:css|ya?ml)$/i.test(norm)) {
|
|
279
|
+
clearTailwindCompilerCache();
|
|
280
|
+
}
|
|
281
|
+
await clientBuild.rebuild();
|
|
282
|
+
broadcastHmr('reload');
|
|
283
|
+
} catch (e) {
|
|
284
|
+
console.error('[soma-native][dev-rebuild-error]', e);
|
|
285
|
+
}
|
|
286
|
+
}, 100);
|
|
287
|
+
});
|
|
288
|
+
} catch {
|
|
289
|
+
// 平台不支持 recursive watch 时降级
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// 5. 纯 node:http 服务器主调度
|
|
294
|
+
const server = http.createServer(async (req, res) => {
|
|
295
|
+
try {
|
|
296
|
+
const origin = `http://${req.headers.host || 'localhost'}`;
|
|
297
|
+
const url = new URL(req.url || '/', origin);
|
|
298
|
+
const pathname = url.pathname;
|
|
299
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
300
|
+
|
|
301
|
+
// ==========================================
|
|
302
|
+
// 分支 A: 静态极速通道
|
|
303
|
+
// ==========================================
|
|
304
|
+
|
|
305
|
+
// A.1: SSE 热更新通道
|
|
306
|
+
if (dev && pathname === '/_soma/hmr') {
|
|
307
|
+
res.writeHead(200, {
|
|
308
|
+
'Content-Type': 'text/event-stream',
|
|
309
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
310
|
+
'Connection': 'keep-alive',
|
|
311
|
+
'Access-Control-Allow-Origin': '*',
|
|
312
|
+
});
|
|
313
|
+
res.write(': heartbeat\n\n');
|
|
314
|
+
sseClients.add(res);
|
|
315
|
+
req.on('close', () => {
|
|
316
|
+
sseClients.delete(res);
|
|
317
|
+
});
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// A.2: 客户端 JS/CSS 分片直出
|
|
322
|
+
if (pathname.startsWith('/_soma/client/')) {
|
|
323
|
+
const subfile = pathname.slice('/_soma/client/'.length);
|
|
324
|
+
const diskFile = path.resolve(runtimeLayout.dirs.static, 'client', subfile);
|
|
325
|
+
const rootReal = fs.realpathSync(path.resolve(runtimeLayout.dirs.static, 'client'));
|
|
326
|
+
let realFile = '';
|
|
327
|
+
try {
|
|
328
|
+
realFile = fs.realpathSync(diskFile);
|
|
329
|
+
} catch {
|
|
330
|
+
res.statusCode = 404;
|
|
331
|
+
res.end('File not found');
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (!realFile.startsWith(rootReal + path.sep) && realFile !== rootReal) {
|
|
336
|
+
res.statusCode = 404;
|
|
337
|
+
res.end('Forbidden');
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const stat = fs.statSync(realFile);
|
|
342
|
+
if (!stat.isFile()) {
|
|
343
|
+
res.statusCode = 404;
|
|
344
|
+
res.end('Not found');
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const isHashed = /[-.][0-9a-f]{8,}\.[a-z0-9]+$/i.test(subfile);
|
|
349
|
+
const etag = `W/"${createHash('sha1').update(`${stat.size}:${stat.mtimeMs}`).digest('hex').slice(0, 20)}"`;
|
|
350
|
+
const ifNoneMatch = req.headers['if-none-match'];
|
|
351
|
+
|
|
352
|
+
if (ifNoneMatch && ifNoneMatch.includes(etag)) {
|
|
353
|
+
res.statusCode = 304;
|
|
354
|
+
res.end();
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const ext = path.extname(realFile).toLowerCase();
|
|
359
|
+
let contentType = 'application/octet-stream';
|
|
360
|
+
if (ext === '.js' || ext === '.mjs') contentType = 'text/javascript; charset=utf-8';
|
|
361
|
+
else if (ext === '.css') contentType = 'text/css; charset=utf-8';
|
|
362
|
+
else if (ext === '.json' || ext === '.map') contentType = 'application/json; charset=utf-8';
|
|
363
|
+
|
|
364
|
+
res.setHeader('Content-Type', contentType);
|
|
365
|
+
res.setHeader(
|
|
366
|
+
'Cache-Control',
|
|
367
|
+
isHashed ? 'public, max-age=31536000, immutable' : 'public, max-age=300, must-revalidate',
|
|
368
|
+
);
|
|
369
|
+
res.setHeader('ETag', etag);
|
|
370
|
+
|
|
371
|
+
if (method === 'HEAD') {
|
|
372
|
+
res.statusCode = 200;
|
|
373
|
+
res.end();
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const content = fs.readFileSync(realFile);
|
|
378
|
+
res.statusCode = 200;
|
|
379
|
+
res.end(content);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// A.3: /soma-runtime/* 核心静态资源
|
|
384
|
+
if (pathname.startsWith('/soma-runtime/')) {
|
|
385
|
+
const segments = pathname.slice('/soma-runtime/'.length).split('/').filter(Boolean);
|
|
386
|
+
const standardReq = {
|
|
387
|
+
method,
|
|
388
|
+
headers: {
|
|
389
|
+
get(name: string) {
|
|
390
|
+
const v = req.headers[name.toLowerCase()];
|
|
391
|
+
return Array.isArray(v) ? v.join(', ') : v || null;
|
|
392
|
+
},
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
const staticRes = staticResponse(segments, standardReq, env);
|
|
396
|
+
await sendWebResponse(staticRes, res);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// A.4: public/* 宿主静态文件直出
|
|
401
|
+
const publicDir = path.resolve(webRoot, 'public');
|
|
402
|
+
if (fs.existsSync(publicDir)) {
|
|
403
|
+
const targetPath = path.resolve(publicDir, pathname.replace(/^\//, ''));
|
|
404
|
+
try {
|
|
405
|
+
const realTarget = fs.realpathSync(targetPath);
|
|
406
|
+
const realPublic = fs.realpathSync(publicDir);
|
|
407
|
+
if (realTarget.startsWith(realPublic + path.sep) && fs.statSync(realTarget).isFile()) {
|
|
408
|
+
const stat = fs.statSync(realTarget);
|
|
409
|
+
const ext = path.extname(realTarget).toLowerCase();
|
|
410
|
+
let ctype = 'application/octet-stream';
|
|
411
|
+
if (ext === '.ico') ctype = 'image/x-icon';
|
|
412
|
+
else if (ext === '.svg') ctype = 'image/svg+xml';
|
|
413
|
+
else if (ext === '.png') ctype = 'image/png';
|
|
414
|
+
else if (ext === '.jpg' || ext === '.jpeg') ctype = 'image/jpeg';
|
|
415
|
+
else if (ext === '.txt') ctype = 'text/plain; charset=utf-8';
|
|
416
|
+
|
|
417
|
+
res.statusCode = 200;
|
|
418
|
+
res.setHeader('Content-Type', ctype);
|
|
419
|
+
res.setHeader('Content-Length', stat.size);
|
|
420
|
+
if (method === 'HEAD') {
|
|
421
|
+
res.end();
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
res.end(fs.readFileSync(realTarget));
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
} catch {}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// ==========================================
|
|
431
|
+
// 分支 B: SOMA 内部数据接口 (/soma/*)
|
|
432
|
+
// ==========================================
|
|
433
|
+
if (pathname.startsWith('/soma/') || pathname === '/soma') {
|
|
434
|
+
const webReq = await toWebRequest(req, origin);
|
|
435
|
+
|
|
436
|
+
// B.1: GET /soma/page
|
|
437
|
+
if (pathname === '/soma/page' && method === 'GET') {
|
|
438
|
+
const pagePath = url.searchParams.get('path') || '/';
|
|
439
|
+
let assembly: any = null;
|
|
440
|
+
try {
|
|
441
|
+
assembly = await prepareHostAssembly(hostDir);
|
|
442
|
+
const hookRejected = await invokeHostRequestHook(webReq, {
|
|
443
|
+
kind: 'page',
|
|
444
|
+
path: pagePath,
|
|
445
|
+
pageHref: pagePath,
|
|
446
|
+
});
|
|
447
|
+
if (hookRejected) {
|
|
448
|
+
const hooked = await applyHostAndCspHeaders(hookRejected, { method: 'GET', pathname }, env);
|
|
449
|
+
await sendWebResponse(hooked, res);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
const page = await loadPageByAddress(pagePath, webReq, { hostDir });
|
|
453
|
+
const pageRecord = page as unknown as {
|
|
454
|
+
binding?: { digest?: string; generation?: number };
|
|
455
|
+
nav?: unknown;
|
|
456
|
+
params?: unknown;
|
|
457
|
+
query?: unknown;
|
|
458
|
+
};
|
|
459
|
+
const cacheKey = `page:${hostDir}:${pagePath}:${pageRecord.binding?.digest ?? ''}:${pageRecord.binding?.generation ?? 0}:${JSON.stringify([pageRecord.nav ?? null, pageRecord.params ?? null, pageRecord.query ?? null])}`;
|
|
460
|
+
let response = pageSuccessResponse(page, page, webReq, cacheKey);
|
|
461
|
+
response = await applyHostAndCspHeaders(response, { method: 'GET', pathname }, env);
|
|
462
|
+
await sendWebResponse(response, res);
|
|
463
|
+
return;
|
|
464
|
+
} catch (error) {
|
|
465
|
+
let response = pageErrorResponse(error, assembly);
|
|
466
|
+
response = await applyHostAndCspHeaders(response, { method: 'GET', pathname }, env);
|
|
467
|
+
await sendWebResponse(response, res);
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// B.2: GET /soma/manifest
|
|
473
|
+
if (pathname === '/soma/manifest' && method === 'GET') {
|
|
474
|
+
let response = await handleManifestGet(webReq);
|
|
475
|
+
response = await applyHostAndCspHeaders(response, { method: 'GET', pathname }, env);
|
|
476
|
+
await sendWebResponse(response, res);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// B.3: 未知内部端点 404
|
|
481
|
+
let notFoundRes = Response.json({ error: 'SOMA internal endpoint not found' }, { status: 404 });
|
|
482
|
+
notFoundRes = await applyHostAndCspHeaders(notFoundRes, { method, pathname }, env);
|
|
483
|
+
await sendWebResponse(notFoundRes, res);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// ==========================================
|
|
488
|
+
// 分支 C: 后端业务接口 (/api/*)
|
|
489
|
+
// ==========================================
|
|
490
|
+
if (pathname.startsWith('/api/') || pathname === '/api') {
|
|
491
|
+
const webReq = await toWebRequest(req, origin);
|
|
492
|
+
const segments = pathname.slice('/api'.length).split('/').filter(Boolean);
|
|
493
|
+
let apiRes = await dispatchHostServiceApiRequest(webReq, { segments, hostDir });
|
|
494
|
+
apiRes = await applyHostAndCspHeaders(apiRes, { method, pathname }, env);
|
|
495
|
+
await sendWebResponse(apiRes, res);
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// ==========================================
|
|
500
|
+
// 分支 D: 前端页面 HTML 极速外壳 (GET / HEAD)
|
|
501
|
+
// ==========================================
|
|
502
|
+
const webReq = await toWebRequest(req, origin);
|
|
503
|
+
const csp = createSomaCspHeader(resolveSomaCspOptionsFromEnv(env));
|
|
504
|
+
const verifiedNonce = await readCspNonceMeta(csp?.nonce, env as Record<string, string | undefined>);
|
|
505
|
+
const nonceAttr = verifiedNonce ? ` nonce="${escapeHtml(verifiedNonce)}"` : '';
|
|
506
|
+
const cspMeta = verifiedNonce ? `<meta name="csp-nonce" content="${escapeHtml(verifiedNonce)}">\n` : '';
|
|
507
|
+
const extraHeaders = await resolveHostResponseHeaders({ method, pathname });
|
|
508
|
+
const applyExtraResHeaders = () => {
|
|
509
|
+
if (extraHeaders) {
|
|
510
|
+
for (const [hName, hVal] of Object.entries(extraHeaders)) res.setHeader(hName, hVal);
|
|
511
|
+
}
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
// 跑 Host 请求钩子
|
|
515
|
+
const rejected = await invokeHostRequestHook(webReq, {
|
|
516
|
+
kind: 'page',
|
|
517
|
+
path: pathname,
|
|
518
|
+
pageHref: pathname,
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
if (rejected) {
|
|
522
|
+
// 重定向
|
|
523
|
+
if (rejected.status >= 300 && rejected.status < 400 && rejected.headers.get('location')) {
|
|
524
|
+
res.statusCode = rejected.status;
|
|
525
|
+
res.setHeader('Location', rejected.headers.get('location')!);
|
|
526
|
+
res.end();
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// HTML 拒绝
|
|
531
|
+
if ((rejected.headers.get('content-type') || '').toLowerCase().includes('text/html')) {
|
|
532
|
+
const rawHtml = await rejected.text();
|
|
533
|
+
const inner = extractHtmlBodyInner(rawHtml);
|
|
534
|
+
const html = `<!DOCTYPE html><html><head><meta charset="utf-8">${cspMeta}</head><body><div data-soma-request-rejected="${rejected.status}" data-soma-rejection-html="1">${inner}</div></body></html>`;
|
|
535
|
+
res.statusCode = rejected.status;
|
|
536
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
537
|
+
if (csp) res.setHeader(csp.name, csp.value);
|
|
538
|
+
res.end(html);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// JSON/文本拒绝
|
|
543
|
+
const message = await readRejectedMessage(rejected);
|
|
544
|
+
const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Request Rejected</title>${cspMeta}<style${nonceAttr}>${clientBuild.cssText}</style></head><body><main class="soma-request-rejected" data-soma-request-rejected="${rejected.status}"><section class="soma-request-rejected__panel"><p class="soma-request-rejected__eyebrow">HTTP ${rejected.status}</p><h1 class="soma-request-rejected__title">Request rejected</h1><p class="soma-request-rejected__message">${escapeHtml(message)}</p></section></main></body></html>`;
|
|
545
|
+
res.statusCode = rejected.status;
|
|
546
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
547
|
+
if (csp) res.setHeader(csp.name, csp.value);
|
|
548
|
+
res.end(html);
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
applyExtraResHeaders();
|
|
553
|
+
// 正常 HTML 外壳(CSP 关闭时直接走预压缩内存 Buffer 快速通道)
|
|
554
|
+
const title = readHostAppDisplayName() || 'SOMA';
|
|
555
|
+
if (!csp) {
|
|
556
|
+
const prebuilt = getStaticShellBuffers(title);
|
|
557
|
+
res.statusCode = 200;
|
|
558
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
559
|
+
const ae = req.headers['accept-encoding'];
|
|
560
|
+
if (ae && (ae.includes('gzip') || ae.includes('*')) && prebuilt.utf8.length >= 1024) {
|
|
561
|
+
res.setHeader('Content-Encoding', 'gzip');
|
|
562
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
563
|
+
res.setHeader('Content-Length', prebuilt.gzip.length);
|
|
564
|
+
if (method === 'HEAD') { res.end(); return; }
|
|
565
|
+
res.end(prebuilt.gzip);
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
res.setHeader('Content-Length', prebuilt.utf8.length);
|
|
569
|
+
if (method === 'HEAD') { res.end(); return; }
|
|
570
|
+
res.end(prebuilt.utf8);
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
const devSseScript = dev
|
|
574
|
+
? `<script${nonceAttr}>window.__SOMA_DEV_SSE__ = true;</script>\n`
|
|
575
|
+
: '';
|
|
576
|
+
|
|
577
|
+
const htmlDocument = `<!DOCTYPE html>
|
|
578
|
+
<html lang="en">
|
|
579
|
+
<head>
|
|
580
|
+
<meta charset="utf-8">
|
|
581
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
582
|
+
${cspMeta} <title>${escapeHtml(title)}</title>
|
|
583
|
+
<style${nonceAttr}>${clientBuild.cssText}</style>
|
|
584
|
+
<script${nonceAttr}>
|
|
585
|
+
try {
|
|
586
|
+
const theme = localStorage.getItem('soma-theme');
|
|
587
|
+
if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
|
|
588
|
+
document.documentElement.setAttribute('data-theme', 'dark');
|
|
589
|
+
}
|
|
590
|
+
} catch (_) {}
|
|
591
|
+
</script>
|
|
592
|
+
${devSseScript}</head>
|
|
593
|
+
<body>
|
|
594
|
+
<div id="soma-app-root">
|
|
595
|
+
<div class="soma-hydration-shell">
|
|
596
|
+
<div class="soma-hydration-shell__bar"></div>
|
|
597
|
+
</div>
|
|
598
|
+
</div>
|
|
599
|
+
<script type="module" src="${clientBuild.entryUrl}"${nonceAttr}></script>
|
|
600
|
+
</body>
|
|
601
|
+
</html>`;
|
|
602
|
+
|
|
603
|
+
res.statusCode = 200;
|
|
604
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
605
|
+
if (csp) res.setHeader(csp.name, csp.value);
|
|
606
|
+
|
|
607
|
+
const acceptEncoding = req.headers['accept-encoding'];
|
|
608
|
+
if (
|
|
609
|
+
acceptEncoding &&
|
|
610
|
+
(acceptEncoding.includes('gzip') || acceptEncoding.includes('*')) &&
|
|
611
|
+
htmlDocument.length >= 1024
|
|
612
|
+
) {
|
|
613
|
+
try {
|
|
614
|
+
const gzipped = zlib.gzipSync(Buffer.from(htmlDocument, 'utf8'));
|
|
615
|
+
res.setHeader('Content-Encoding', 'gzip');
|
|
616
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
617
|
+
res.setHeader('Content-Length', gzipped.length);
|
|
618
|
+
if (method === 'HEAD') {
|
|
619
|
+
res.end();
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
res.end(gzipped);
|
|
623
|
+
return;
|
|
624
|
+
} catch {}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
const htmlBuf = Buffer.from(htmlDocument, 'utf8');
|
|
628
|
+
res.setHeader('Content-Length', htmlBuf.length);
|
|
629
|
+
if (method === 'HEAD') {
|
|
630
|
+
res.end();
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
res.end(htmlBuf);
|
|
634
|
+
} catch (err: unknown) {
|
|
635
|
+
const message = err instanceof Error ? err.stack || err.message : String(err);
|
|
636
|
+
console.error('[soma-native][server-error]', message);
|
|
637
|
+
if (!res.headersSent) {
|
|
638
|
+
res.statusCode = 500;
|
|
639
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
640
|
+
res.end('Internal Server Error');
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
server.keepAliveTimeout = 65_000;
|
|
646
|
+
server.headersTimeout = 66_000;
|
|
647
|
+
|
|
648
|
+
const port = options.port ?? (process.env.PORT ? parseInt(process.env.PORT, 10) : 3000);
|
|
649
|
+
const hostname = options.hostname ?? process.env.HOSTNAME ?? '0.0.0.0';
|
|
650
|
+
|
|
651
|
+
return {
|
|
652
|
+
server,
|
|
653
|
+
port,
|
|
654
|
+
url: `http://${hostname === '0.0.0.0' ? 'localhost' : hostname}:${port}`,
|
|
655
|
+
start() {
|
|
656
|
+
return new Promise((resolve, reject) => {
|
|
657
|
+
server.listen(port, hostname, () => {
|
|
658
|
+
const addr = server.address();
|
|
659
|
+
const actualPort = typeof addr === 'object' && addr ? addr.port : port;
|
|
660
|
+
const url = `http://${hostname === '0.0.0.0' ? 'localhost' : hostname}:${actualPort}`;
|
|
661
|
+
resolve({ url, port: actualPort });
|
|
662
|
+
});
|
|
663
|
+
server.once('error', reject);
|
|
664
|
+
});
|
|
665
|
+
},
|
|
666
|
+
async close() {
|
|
667
|
+
if (hmrHeartbeatTimer) clearInterval(hmrHeartbeatTimer);
|
|
668
|
+
for (const client of sseClients) {
|
|
669
|
+
try {
|
|
670
|
+
client.end();
|
|
671
|
+
} catch {}
|
|
672
|
+
}
|
|
673
|
+
sseClients.clear();
|
|
674
|
+
if (fsWatcher) {
|
|
675
|
+
try {
|
|
676
|
+
fsWatcher.close();
|
|
677
|
+
} catch {}
|
|
678
|
+
}
|
|
679
|
+
await clientBuild.dispose();
|
|
680
|
+
if (prevWebDir !== undefined) process.env.SOMA_WEB_DIR = prevWebDir;
|
|
681
|
+
else delete process.env.SOMA_WEB_DIR;
|
|
682
|
+
if (prevApiDir !== undefined) process.env.SOMA_API_DIR = prevApiDir;
|
|
683
|
+
else delete process.env.SOMA_API_DIR;
|
|
684
|
+
if (typeof server.closeIdleConnections === 'function') server.closeIdleConnections();
|
|
685
|
+
if (typeof server.closeAllConnections === 'function') server.closeAllConnections();
|
|
686
|
+
await new Promise<void>((resolve) => {
|
|
687
|
+
server.close(() => resolve());
|
|
688
|
+
});
|
|
689
|
+
},
|
|
690
|
+
};
|
|
691
|
+
}
|