soma-core 2.1.6 → 2.2.1
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 +79 -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 +98 -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 +852 -0
- package/dist/host-native/native-server.cjs +15341 -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
package/README.md
CHANGED
|
@@ -28,8 +28,8 @@ Host 文件页优先,Registry 页面在 Host 404 时兜底;存量 `/pages/<n
|
|
|
28
28
|
Temporal 值语义(`temporal`)、图表(`chart`)、拖放(`dnd`)、文本差异(`diff`)、二维码(`qrcode`)各一个子路径;
|
|
29
29
|
引擎库只在 `adapter-*.ts` 里动态 import,可经 `SomaBootstrapOptions.engines` 逐槽替换。
|
|
30
30
|
- **渲染端口**:`render-ports` 的 notify / regionFallback 由 UI 体系注入,缺省无头(只记录 / 只打标记)。
|
|
31
|
-
- **宿主与 CLI**:core
|
|
32
|
-
(`dev/build/start` 转调包内 host-
|
|
31
|
+
- **宿主与 CLI**:core 运行时与宿主壳均零 Next / React 依赖;原生极速单进程宿主壳在包内 `host-native/`(含客户端分片与后端服务预先静态编译,支持 `--web-dir` / `--api-dir` 前后端分目录同进程运行),`soma dev/build/start` 以子进程转调它;`soma` CLI
|
|
32
|
+
(`dev/build/start` 转调包内 host-native、`codegen`、`sync`、`lsp`、`component eject|diff|upgrade` 与 `pack init` 转调 soma-ui,见 `bin/` 与 `soma help`)。
|
|
33
33
|
mock 服务器与 `soma-mock` 已迁 soma-testkit;`verify` 在 soma-testkit。
|
|
34
34
|
|
|
35
35
|
## 文档索引
|
package/bin/soma.cjs
CHANGED
|
@@ -158,7 +158,7 @@ function printHelp() {
|
|
|
158
158
|
console.log([
|
|
159
159
|
'Usage: soma <命令> [...参数]',
|
|
160
160
|
'',
|
|
161
|
-
' dev | build | start 在 Host
|
|
161
|
+
' dev | build | start 在 Host 根启动原生开发 / AOT 预编译 / 启动产物(转调包内 host-native)',
|
|
162
162
|
' codegen [service] ... Domain Class 装饰器 → 页面声明;service 分支生成 IService 骨架',
|
|
163
163
|
' sync [--from <目录>] [--to <目录>] 把包内预构建的浏览器运行包拷到 <runtime 根>/static/(--to 可改)',
|
|
164
164
|
' lsp [--check <文件或目录>] stdio JSON-RPC 语言服务(同 soma-lsp);--check 单次诊断,有错退出码 1',
|
package/bin/soma.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
|
|
@@ -134,9 +134,9 @@ if (command === 'check') {
|
|
|
134
134
|
process.exit(1);
|
|
135
135
|
});
|
|
136
136
|
}
|
|
137
|
-
/**
|
|
138
|
-
function
|
|
139
|
-
const candidate = path.join(packageRoot, 'host-
|
|
137
|
+
/** 原生宿主壳命令行:随 soma-core 包发布的 host-native/bin/host-native.cjs(包内相对定位,不去 node_modules 找外部包) */
|
|
138
|
+
function locateHostNativeCli(): string | null {
|
|
139
|
+
const candidate = path.join(packageRoot, 'host-native', 'bin', 'host-native.cjs');
|
|
140
140
|
return fs.existsSync(candidate) ? candidate : null;
|
|
141
141
|
}
|
|
142
142
|
|
|
@@ -149,23 +149,72 @@ if (command !== 'check') {
|
|
|
149
149
|
process.exit(1);
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
// `soma dev|build|start
|
|
153
|
-
// core 运行时(core/**)不 import
|
|
152
|
+
// `soma dev|build|start`:原生宿主壳(AOT 预编译 + 原生单进程内核)在包内 host-native/ 目录,
|
|
153
|
+
// core 运行时(core/**)不 import 它;这里以子进程转调它的命令行,参数、环境变量与退出码透传。
|
|
154
154
|
// Host 目录取当前目录,覆盖外部陈旧的 SOMA_HOST_DIR。
|
|
155
155
|
const hostDir = path.resolve(process.cwd());
|
|
156
156
|
process.env.SOMA_HOST_DIR = hostDir;
|
|
157
|
-
|
|
158
|
-
|
|
157
|
+
|
|
158
|
+
const restArgs = args.slice(1);
|
|
159
|
+
for (let i = 0; i < restArgs.length; i++) {
|
|
160
|
+
const arg = restArgs[i];
|
|
161
|
+
if (arg === '--web-dir' && i + 1 < restArgs.length) {
|
|
162
|
+
process.env.SOMA_WEB_DIR = path.resolve(process.cwd(), restArgs[i + 1]);
|
|
163
|
+
} else if (arg.startsWith('--web-dir=')) {
|
|
164
|
+
process.env.SOMA_WEB_DIR = path.resolve(process.cwd(), arg.slice('--web-dir='.length));
|
|
165
|
+
} else if (arg === '--api-dir' && i + 1 < restArgs.length) {
|
|
166
|
+
process.env.SOMA_API_DIR = path.resolve(process.cwd(), restArgs[i + 1]);
|
|
167
|
+
} else if (arg.startsWith('--api-dir=')) {
|
|
168
|
+
process.env.SOMA_API_DIR = path.resolve(process.cwd(), arg.slice('--api-dir='.length));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const hostNativeCli = locateHostNativeCli();
|
|
173
|
+
if (!hostNativeCli) {
|
|
159
174
|
console.error(
|
|
160
|
-
`[soma ${command}]
|
|
175
|
+
`[soma ${command}] 找不到原生宿主壳入口 host-native/bin/host-native.cjs:soma-core 包不完整,请重新安装。`,
|
|
161
176
|
);
|
|
162
177
|
process.exit(1);
|
|
163
178
|
}
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
179
|
+
const hasHeapArg = process.execArgv.some((a) => a.includes('--max-old-space-size'))
|
|
180
|
+
|| (process.env.NODE_OPTIONS || '').includes('--max-old-space-size');
|
|
181
|
+
const nodeArgs: string[] = [];
|
|
182
|
+
if (!hasHeapArg && !process.env.SOMA_DISABLE_HEAP_CAP) {
|
|
183
|
+
const defaultCap = command === 'dev' ? 1024 : 512;
|
|
184
|
+
const cap = process.env.SOMA_MAX_OLD_SPACE_MB
|
|
185
|
+
? parseInt(process.env.SOMA_MAX_OLD_SPACE_MB, 10)
|
|
186
|
+
: defaultCap;
|
|
187
|
+
if (Number.isFinite(cap) && cap > 0) {
|
|
188
|
+
nodeArgs.push(`--max-old-space-size=${cap}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
nodeArgs.push(hostNativeCli, command, ...args.slice(1));
|
|
192
|
+
const childEnv = {
|
|
193
|
+
...process.env,
|
|
194
|
+
SOMA_HOST_DIR: hostDir,
|
|
195
|
+
SOMA_NATIVE_HEAP_APPLIED: '1',
|
|
196
|
+
};
|
|
169
197
|
|
|
170
|
-
|
|
198
|
+
if (command === 'build') {
|
|
199
|
+
const child = spawnSync(process.execPath, nodeArgs, {
|
|
200
|
+
cwd: process.cwd(),
|
|
201
|
+
stdio: 'inherit',
|
|
202
|
+
env: childEnv,
|
|
203
|
+
});
|
|
204
|
+
process.exit(child.status === null ? 1 : child.status);
|
|
205
|
+
} else {
|
|
206
|
+
const child = spawn(process.execPath, nodeArgs, {
|
|
207
|
+
cwd: process.cwd(),
|
|
208
|
+
stdio: 'inherit',
|
|
209
|
+
env: childEnv,
|
|
210
|
+
});
|
|
211
|
+
const forward = (sig: NodeJS.Signals) => {
|
|
212
|
+
try { child.kill(sig); } catch {}
|
|
213
|
+
};
|
|
214
|
+
process.on('SIGINT', () => forward('SIGINT'));
|
|
215
|
+
process.on('SIGTERM', () => forward('SIGTERM'));
|
|
216
|
+
child.on('exit', (code, signal) => {
|
|
217
|
+
process.exit(code ?? (signal ? 0 : 0));
|
|
218
|
+
});
|
|
219
|
+
}
|
|
171
220
|
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import type { IService } from "./IService";
|
|
2
|
+
import {
|
|
3
|
+
getAotServiceResolver,
|
|
4
|
+
loadHostService,
|
|
5
|
+
resolveServiceExport,
|
|
6
|
+
} from "./load-host-service";
|
|
7
|
+
import { invokeHostRequestHook } from "../host/invoke-host-request-hook";
|
|
8
|
+
import { withHostResponseHeaders } from "../host/host-response-headers";
|
|
9
|
+
|
|
10
|
+
export interface RequestCookie {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly value: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface RequestCookiesAdapter {
|
|
16
|
+
get(name: string): RequestCookie | undefined;
|
|
17
|
+
getAll(name?: string): RequestCookie[];
|
|
18
|
+
has(name: string): boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface DispatchHostServiceApiOptions {
|
|
22
|
+
readonly segments?: readonly string[];
|
|
23
|
+
readonly hostDir?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function parseCookieHeader(headerValue: string | null): RequestCookiesAdapter {
|
|
27
|
+
const parsed: RequestCookie[] = [];
|
|
28
|
+
const map = new Map<string, string>();
|
|
29
|
+
if (headerValue) {
|
|
30
|
+
const pairs = headerValue.split(";");
|
|
31
|
+
for (const pair of pairs) {
|
|
32
|
+
const trimmed = pair.trim();
|
|
33
|
+
if (!trimmed) continue;
|
|
34
|
+
const eqIndex = trimmed.indexOf("=");
|
|
35
|
+
if (eqIndex === -1) {
|
|
36
|
+
const name = trimmed;
|
|
37
|
+
parsed.push({ name, value: "" });
|
|
38
|
+
if (!map.has(name)) map.set(name, "");
|
|
39
|
+
} else {
|
|
40
|
+
const name = trimmed.slice(0, eqIndex).trim();
|
|
41
|
+
const rawValue = trimmed.slice(eqIndex + 1).trim();
|
|
42
|
+
const value = rawValue.startsWith(`"`) && rawValue.endsWith(`"`)
|
|
43
|
+
? rawValue.slice(1, -1)
|
|
44
|
+
: rawValue;
|
|
45
|
+
parsed.push({ name, value });
|
|
46
|
+
if (!map.has(name)) map.set(name, value);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
get(name: string): RequestCookie | undefined {
|
|
53
|
+
const value = map.get(name);
|
|
54
|
+
return value !== undefined ? { name, value } : undefined;
|
|
55
|
+
},
|
|
56
|
+
getAll(name?: string): RequestCookie[] {
|
|
57
|
+
if (name !== undefined) {
|
|
58
|
+
return parsed.filter((c) => c.name === name);
|
|
59
|
+
}
|
|
60
|
+
return [...parsed];
|
|
61
|
+
},
|
|
62
|
+
has(name: string): boolean {
|
|
63
|
+
return map.has(name);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function polyfillServiceRequest<T extends Request>(request: T): T & { nextUrl: URL; cookies: RequestCookiesAdapter } {
|
|
69
|
+
const req = request as unknown as { nextUrl?: URL; cookies?: RequestCookiesAdapter; url: string; headers: Headers };
|
|
70
|
+
if (!("nextUrl" in req) || !req.nextUrl) {
|
|
71
|
+
let nextUrlCache: URL | undefined;
|
|
72
|
+
Object.defineProperty(req, "nextUrl", {
|
|
73
|
+
get() {
|
|
74
|
+
if (!nextUrlCache) {
|
|
75
|
+
nextUrlCache = new URL(request.url, "http://soma.local");
|
|
76
|
+
}
|
|
77
|
+
return nextUrlCache;
|
|
78
|
+
},
|
|
79
|
+
configurable: true,
|
|
80
|
+
enumerable: true,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
if (!("cookies" in req) || !req.cookies) {
|
|
84
|
+
let cookiesCache: RequestCookiesAdapter | undefined;
|
|
85
|
+
Object.defineProperty(req, "cookies", {
|
|
86
|
+
get() {
|
|
87
|
+
if (!cookiesCache) {
|
|
88
|
+
cookiesCache = parseCookieHeader(request.headers.get("cookie"));
|
|
89
|
+
}
|
|
90
|
+
return cookiesCache;
|
|
91
|
+
},
|
|
92
|
+
configurable: true,
|
|
93
|
+
enumerable: true,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return request as T & { nextUrl: URL; cookies: RequestCookiesAdapter };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function getAllowHeader(service: IService): string {
|
|
100
|
+
const methods: string[] = [];
|
|
101
|
+
if (typeof service.get === "function") methods.push("GET");
|
|
102
|
+
if (typeof service.post === "function") methods.push("POST");
|
|
103
|
+
if (typeof service.put === "function") methods.push("PUT");
|
|
104
|
+
if (typeof service.patch === "function") methods.push("PATCH");
|
|
105
|
+
if (typeof service.delete === "function") methods.push("DELETE");
|
|
106
|
+
return methods.join(", ");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function dispatchHostServiceApiRequest(
|
|
110
|
+
request: Request,
|
|
111
|
+
segmentsOrOptions?: readonly string[] | DispatchHostServiceApiOptions,
|
|
112
|
+
): Promise<Response> {
|
|
113
|
+
const polyfilledReq = polyfillServiceRequest(request);
|
|
114
|
+
const options: DispatchHostServiceApiOptions | undefined =
|
|
115
|
+
Array.isArray(segmentsOrOptions)
|
|
116
|
+
? { segments: segmentsOrOptions }
|
|
117
|
+
: (segmentsOrOptions as DispatchHostServiceApiOptions | undefined);
|
|
118
|
+
|
|
119
|
+
const hostDir = options?.hostDir ?? process.env.SOMA_HOST_DIR;
|
|
120
|
+
|
|
121
|
+
let segments: string[];
|
|
122
|
+
if (options?.segments && options.segments.length > 0) {
|
|
123
|
+
segments = [...options.segments];
|
|
124
|
+
} else {
|
|
125
|
+
const pathname = polyfilledReq.nextUrl.pathname;
|
|
126
|
+
const pathParts = pathname.split("/").filter(Boolean);
|
|
127
|
+
if (pathParts[0] === "api") {
|
|
128
|
+
segments = pathParts.slice(1);
|
|
129
|
+
} else {
|
|
130
|
+
segments = pathParts;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const pathname = polyfilledReq.nextUrl.pathname;
|
|
135
|
+
const rejected = await invokeHostRequestHook(polyfilledReq, {
|
|
136
|
+
kind: "api",
|
|
137
|
+
path: pathname,
|
|
138
|
+
});
|
|
139
|
+
if (rejected) {
|
|
140
|
+
return withHostResponseHeaders(rejected, {
|
|
141
|
+
method: request.method,
|
|
142
|
+
pathname,
|
|
143
|
+
}, hostDir);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (segments.length === 0) {
|
|
147
|
+
const res = Response.json(
|
|
148
|
+
{ error: "Missing API path. Expected: /api/{module}/{action}" },
|
|
149
|
+
{ status: 400 },
|
|
150
|
+
);
|
|
151
|
+
return withHostResponseHeaders(res, { method: request.method, pathname }, hostDir);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let service: IService | null = null;
|
|
155
|
+
if (hostDir) {
|
|
156
|
+
const prevHostDir = process.env.SOMA_HOST_DIR;
|
|
157
|
+
try {
|
|
158
|
+
process.env.SOMA_HOST_DIR = hostDir;
|
|
159
|
+
service = loadHostService(segments);
|
|
160
|
+
if (!service) {
|
|
161
|
+
const aotResolver = getAotServiceResolver(hostDir);
|
|
162
|
+
if (aotResolver) {
|
|
163
|
+
const routeKey = segments.join("/");
|
|
164
|
+
const resolved = await aotResolver(routeKey, segments);
|
|
165
|
+
if (resolved) {
|
|
166
|
+
service = resolveServiceExport(resolved, `[aot:${routeKey}]`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
} finally {
|
|
171
|
+
if (prevHostDir === undefined) {
|
|
172
|
+
delete process.env.SOMA_HOST_DIR;
|
|
173
|
+
} else {
|
|
174
|
+
process.env.SOMA_HOST_DIR = prevHostDir;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
} else {
|
|
178
|
+
service = loadHostService(segments);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (!service) {
|
|
182
|
+
const res = Response.json(
|
|
183
|
+
{ error: `API not found: /api/${segments.join("/")}` },
|
|
184
|
+
{ status: 404 },
|
|
185
|
+
);
|
|
186
|
+
return withHostResponseHeaders(res, { method: request.method, pathname }, hostDir);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const method = request.method.toUpperCase();
|
|
190
|
+
const methodKey = method.toLowerCase() as keyof IService;
|
|
191
|
+
const handlerFn = service[methodKey];
|
|
192
|
+
if (typeof handlerFn !== "function") {
|
|
193
|
+
const res = Response.json(
|
|
194
|
+
{ error: `Method ${method} not allowed: /api/${segments.join("/")}` },
|
|
195
|
+
{ status: 405, headers: { Allow: getAllowHeader(service) } },
|
|
196
|
+
);
|
|
197
|
+
return withHostResponseHeaders(res, { method: request.method, pathname }, hostDir);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
const response = await handlerFn.call(service, polyfilledReq);
|
|
202
|
+
return withHostResponseHeaders(response, { method: request.method, pathname }, hostDir);
|
|
203
|
+
} catch (e: unknown) {
|
|
204
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
205
|
+
console.error(`[soma-core][接口] ${method} /api/${segments.join("/")}:`, message);
|
|
206
|
+
const res = Response.json(
|
|
207
|
+
{ error: message || "Internal server error" },
|
|
208
|
+
{ status: 500 },
|
|
209
|
+
);
|
|
210
|
+
return withHostResponseHeaders(res, { method: request.method, pathname }, hostDir);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
@@ -1,82 +1,256 @@
|
|
|
1
|
-
import fs from
|
|
2
|
-
import path from
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import type { IService } from "./IService";
|
|
5
|
+
import { resolveHostServiceCandidate } from "./service-path";
|
|
6
|
+
import {
|
|
7
|
+
getSomaAssetSources,
|
|
8
|
+
getSomaHostApiRoot,
|
|
9
|
+
getSomaHostSourceRoot,
|
|
10
|
+
} from "../host/source-packages";
|
|
11
|
+
import { ensureNodeServerOnlyInterop, getJitiFactory } from "../host/host-assembly";
|
|
12
|
+
|
|
13
|
+
export type AotServiceResolver = (routeKey: string, segments: readonly string[]) => unknown | Promise<unknown>;
|
|
7
14
|
|
|
8
15
|
function isService(obj: unknown): obj is IService {
|
|
9
|
-
if (!obj || typeof obj !==
|
|
10
|
-
const methods = [
|
|
11
|
-
return methods.some((m) => typeof (obj as IService)[m] ===
|
|
16
|
+
if (!obj || typeof obj !== "object") return false;
|
|
17
|
+
const methods = ["get", "post", "put", "patch", "delete"] as const;
|
|
18
|
+
return methods.some((m) => typeof (obj as IService)[m] === "function");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function resolveServiceExport(loaded: unknown, filePath?: string): IService | null {
|
|
22
|
+
if (isService(loaded)) return loaded;
|
|
23
|
+
const ServiceClass = typeof loaded === "function"
|
|
24
|
+
? (loaded as new () => IService)
|
|
25
|
+
: (loaded as { default?: new () => IService } | null)?.default;
|
|
26
|
+
if (!ServiceClass || typeof ServiceClass !== "function") {
|
|
27
|
+
if (filePath) console.warn(`[soma-core][接口] ${filePath} missing default export`);
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const instance = new ServiceClass();
|
|
32
|
+
if (!isService(instance)) {
|
|
33
|
+
if (filePath) console.warn(`[soma-core][接口] ${filePath} does not implement IService`);
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return instance;
|
|
12
38
|
}
|
|
13
39
|
|
|
14
40
|
function getCoreDir(): string {
|
|
15
|
-
|
|
16
|
-
|
|
41
|
+
try {
|
|
42
|
+
if (typeof import.meta.url === "string" && import.meta.url.startsWith("file:")) {
|
|
43
|
+
const candidate = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../");
|
|
44
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
45
|
+
}
|
|
46
|
+
} catch {}
|
|
47
|
+
return path.resolve(process.cwd(), "core");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface CachedServiceEntry {
|
|
51
|
+
readonly instance: IService;
|
|
52
|
+
readonly mtimeToken: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const MAX_HOST_SERVICE_CACHE = 512;
|
|
56
|
+
const MAX_ROUTE_PATH_CACHE = 512;
|
|
57
|
+
|
|
58
|
+
const instanceCache = new Map<string, CachedServiceEntry>();
|
|
59
|
+
const routePathCache = new Map<string, string | null>();
|
|
60
|
+
const jitiLoaders = new Map<string, (file: string) => unknown>();
|
|
61
|
+
const aotResolvers = new Map<string, AotServiceResolver>();
|
|
62
|
+
|
|
63
|
+
export function registerAotServiceResolver(hostDir: string, resolver: AotServiceResolver | null): void {
|
|
64
|
+
const normalized = path.resolve(hostDir);
|
|
65
|
+
if (!resolver) {
|
|
66
|
+
aotResolvers.delete(normalized);
|
|
67
|
+
} else {
|
|
68
|
+
aotResolvers.set(normalized, resolver);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function getAotServiceResolver(hostDir: string): AotServiceResolver | undefined {
|
|
73
|
+
return aotResolvers.get(path.resolve(hostDir));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
export function clearHostServiceCache(hostDir?: string): void {
|
|
78
|
+
if (!hostDir) {
|
|
79
|
+
instanceCache.clear();
|
|
80
|
+
routePathCache.clear();
|
|
81
|
+
jitiLoaders.clear();
|
|
82
|
+
} else {
|
|
83
|
+
const normalized = path.resolve(hostDir);
|
|
84
|
+
for (const [key] of instanceCache) {
|
|
85
|
+
if (key.startsWith(normalized) || key.includes(normalized)) {
|
|
86
|
+
instanceCache.delete(key);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
for (const [key] of routePathCache) {
|
|
90
|
+
if (key.startsWith(normalized) || key.includes(normalized)) {
|
|
91
|
+
routePathCache.delete(key);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for (const [key] of jitiLoaders) {
|
|
95
|
+
if (key.startsWith(normalized) || key.includes(normalized)) {
|
|
96
|
+
jitiLoaders.delete(key);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
17
100
|
}
|
|
18
101
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
102
|
+
function getJitiLoader(
|
|
103
|
+
hostDir: string,
|
|
104
|
+
apiRoot: string,
|
|
105
|
+
webRoot: string,
|
|
106
|
+
reload = false,
|
|
107
|
+
): (file: string) => unknown {
|
|
108
|
+
const normalizedHostDir = path.resolve(hostDir);
|
|
109
|
+
const normalizedApiRoot = path.resolve(apiRoot);
|
|
110
|
+
const normalizedWebRoot = path.resolve(webRoot);
|
|
111
|
+
|
|
112
|
+
const anchor = fs.existsSync(path.join(normalizedApiRoot, "package.json"))
|
|
113
|
+
? path.join(normalizedApiRoot, "package.json")
|
|
114
|
+
: path.resolve(normalizedHostDir, "package.json");
|
|
115
|
+
|
|
116
|
+
const serverOnlyEmpty = ensureNodeServerOnlyInterop(normalizedHostDir);
|
|
117
|
+
const createJiti = getJitiFactory(normalizedHostDir);
|
|
118
|
+
const options = {
|
|
119
|
+
interopDefault: true,
|
|
120
|
+
moduleCache: !reload,
|
|
121
|
+
requireCache: !reload,
|
|
122
|
+
alias: {
|
|
123
|
+
"@core": getCoreDir(),
|
|
124
|
+
"@soma-host": normalizedWebRoot,
|
|
125
|
+
"@soma-api": normalizedApiRoot,
|
|
126
|
+
...(serverOnlyEmpty !== undefined ? { "server-only": serverOnlyEmpty } : {}),
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
if (reload) {
|
|
131
|
+
return createJiti(anchor, options);
|
|
37
132
|
}
|
|
38
|
-
|
|
133
|
+
|
|
134
|
+
const cacheKey = `${normalizedHostDir}\0${normalizedApiRoot}\0${normalizedWebRoot}`;
|
|
135
|
+
let loader = jitiLoaders.get(cacheKey);
|
|
136
|
+
if (!loader) {
|
|
137
|
+
loader = createJiti(anchor, options);
|
|
138
|
+
jitiLoaders.set(cacheKey, loader);
|
|
139
|
+
}
|
|
140
|
+
return loader;
|
|
39
141
|
}
|
|
40
142
|
|
|
41
143
|
/**
|
|
42
|
-
* 按约定从宿主
|
|
144
|
+
* 按约定从宿主 apiRoot 加载 IService 实例(运行时按需加载,零手动 registry)。
|
|
43
145
|
*/
|
|
44
146
|
export function loadHostService(segments: string[]): IService | null {
|
|
45
|
-
if (typeof process !==
|
|
147
|
+
if (typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge") return null;
|
|
46
148
|
const hostDir = process.env.SOMA_HOST_DIR;
|
|
47
149
|
if (!hostDir) return null;
|
|
48
150
|
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
.find((candidate): candidate is string => Boolean(candidate && fs.existsSync(candidate)));
|
|
52
|
-
if (!filePath) return null;
|
|
151
|
+
const normalizedHostDir = path.resolve(hostDir);
|
|
152
|
+
const routeKey = segments.join("/");
|
|
53
153
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
154
|
+
// 1. AOT 预编译服务快速命中(零磁盘、零 jiti)
|
|
155
|
+
const aotResolver = aotResolvers.get(normalizedHostDir);
|
|
156
|
+
if (aotResolver) {
|
|
157
|
+
const aotCacheKey = `${normalizedHostDir}::aot::${routeKey}`;
|
|
158
|
+
const cachedAot = instanceCache.get(aotCacheKey);
|
|
159
|
+
if (cachedAot) {
|
|
160
|
+
return cachedAot.instance;
|
|
161
|
+
}
|
|
162
|
+
const resolved = aotResolver(routeKey, segments);
|
|
163
|
+
if (resolved && typeof (resolved as Promise<unknown>).then !== "function") {
|
|
164
|
+
const service = resolveServiceExport(resolved, `[aot:${routeKey}]`);
|
|
165
|
+
if (service) {
|
|
166
|
+
if (instanceCache.size >= MAX_HOST_SERVICE_CACHE) {
|
|
167
|
+
const firstKey = instanceCache.keys().next().value;
|
|
168
|
+
if (firstKey) instanceCache.delete(firstKey);
|
|
169
|
+
}
|
|
170
|
+
instanceCache.set(aotCacheKey, { instance: service, mtimeToken: "aot" });
|
|
171
|
+
return service;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
57
174
|
}
|
|
58
175
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
176
|
+
// 2. 路由路径定位(生产态 O(1) 缓存)
|
|
177
|
+
const isDev = process.env.NODE_ENV !== "production";
|
|
178
|
+
const routeCacheKey = `${normalizedHostDir}::${routeKey}`;
|
|
179
|
+
|
|
180
|
+
let filePath: string | null | undefined;
|
|
181
|
+
if (!isDev) {
|
|
182
|
+
filePath = routePathCache.get(routeCacheKey);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const webRoot = getSomaHostSourceRoot(normalizedHostDir);
|
|
186
|
+
const apiRoot = getSomaHostApiRoot(normalizedHostDir);
|
|
187
|
+
|
|
188
|
+
if (filePath === undefined) {
|
|
189
|
+
filePath = resolveHostServiceCandidate(apiRoot, segments, { allowDirectRoot: apiRoot !== webRoot });
|
|
190
|
+
if (!filePath) {
|
|
191
|
+
const sources = getSomaAssetSources(normalizedHostDir);
|
|
192
|
+
for (const source of sources) {
|
|
193
|
+
if (source.type === "package") {
|
|
194
|
+
const candidateRoot = source.apiRoot || source.codeRoot;
|
|
195
|
+
const candidate = resolveHostServiceCandidate(candidateRoot, segments, { allowDirectRoot: false });
|
|
196
|
+
if (candidate) {
|
|
197
|
+
filePath = candidate;
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (!isDev) {
|
|
204
|
+
if (routePathCache.size >= MAX_ROUTE_PATH_CACHE) {
|
|
205
|
+
const firstKey = routePathCache.keys().next().value;
|
|
206
|
+
if (firstKey) routePathCache.delete(firstKey);
|
|
207
|
+
}
|
|
208
|
+
routePathCache.set(routeCacheKey, filePath ?? null);
|
|
71
209
|
}
|
|
210
|
+
}
|
|
72
211
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
212
|
+
if (!filePath) return null;
|
|
213
|
+
|
|
214
|
+
// 3. 实例缓存与热替换(开发态依据 mtimeToken 判定;若源码变更触发 dispose 并重新加载)
|
|
215
|
+
if (!isDev) {
|
|
216
|
+
const cached = instanceCache.get(filePath);
|
|
217
|
+
if (cached) return cached.instance;
|
|
218
|
+
} else {
|
|
219
|
+
const stat = fs.statSync(filePath, { throwIfNoEntry: false });
|
|
220
|
+
const mtimeToken = stat ? `${stat.mtimeMs}:${stat.size}` : "none";
|
|
221
|
+
const cached = instanceCache.get(filePath);
|
|
222
|
+
|
|
223
|
+
if (cached && cached.mtimeToken === mtimeToken) {
|
|
224
|
+
return cached.instance;
|
|
77
225
|
}
|
|
78
226
|
|
|
79
|
-
if (
|
|
227
|
+
if (cached && cached.mtimeToken !== mtimeToken) {
|
|
228
|
+
const oldInstance = cached.instance as { dispose?: () => unknown; close?: () => unknown };
|
|
229
|
+
if (typeof oldInstance.dispose === "function") {
|
|
230
|
+
Promise.resolve().then(() => oldInstance.dispose?.()).catch(() => {});
|
|
231
|
+
} else if (typeof oldInstance.close === "function") {
|
|
232
|
+
Promise.resolve().then(() => oldInstance.close?.()).catch(() => {});
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// 4. Jiti 加载并解析服务
|
|
238
|
+
const cachedForReload = instanceCache.get(filePath);
|
|
239
|
+
const isReload = Boolean(isDev && cachedForReload);
|
|
240
|
+
try {
|
|
241
|
+
const loader = getJitiLoader(normalizedHostDir, apiRoot, webRoot, isReload);
|
|
242
|
+
const loaded = loader(filePath) as unknown;
|
|
243
|
+
const instance = resolveServiceExport(loaded, filePath);
|
|
244
|
+
if (!instance) return null;
|
|
245
|
+
|
|
246
|
+
const currentStat = isDev ? fs.statSync(filePath, { throwIfNoEntry: false }) : null;
|
|
247
|
+
const token = currentStat ? `${currentStat.mtimeMs}:${currentStat.size}` : "production";
|
|
248
|
+
|
|
249
|
+
if (instanceCache.size >= MAX_HOST_SERVICE_CACHE) {
|
|
250
|
+
const firstKey = instanceCache.keys().next().value;
|
|
251
|
+
if (firstKey) instanceCache.delete(firstKey);
|
|
252
|
+
}
|
|
253
|
+
instanceCache.set(filePath, { instance, mtimeToken: token });
|
|
80
254
|
return instance;
|
|
81
255
|
} catch (e: unknown) {
|
|
82
256
|
const message = e instanceof Error ? e.message : String(e);
|