soma-core 2.1.5 → 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/build/compiler/soma-precompile.js +11 -1
- package/core/client/base/SomaHttpClient.ts +85 -12
- package/core/client/data/data-object-resolver.ts +12 -1
- package/core/client/engine/event-engine.ts +3 -3
- package/core/client/engine/soma-bootstrap.ts +30 -30
- package/core/client/host-bridge/load-host-domain-class.ts +74 -20
- package/core/client/host-bridge/resolve-host-bootstrap.ts +125 -23
- package/core/client/infra/http/IHttpClient.ts +3 -1
- package/core/client/infra/http/SomaHttpService.ts +15 -6
- package/core/client/parser/data-config-parser.ts +6 -1
- 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/core/shared/registry-generated/error-codes.ts +5 -0
- package/core/shared/registry-generated/limits.ts +5 -0
- package/core/shared/types/data-config.types.ts +2 -0
- package/dist/browser/soma-runtime.js +197 -49
- package/dist/cli/soma.js +68 -14
- package/dist/core/index.cjs +284 -64
- package/dist/host-native/aot-builder.cjs +850 -0
- package/dist/host-native/native-server.cjs +15338 -0
- package/dist/lsp/component-tree.cjs +11 -1
- package/dist/types/client/base/SomaHttpClient.d.ts +1 -8
- package/dist/types/client/data/data-object-resolver.d.ts +1 -0
- package/dist/types/client/engine/event-engine.d.ts +2 -2
- package/dist/types/client/engine/soma-bootstrap.d.ts +3 -2
- package/dist/types/client/host-bridge/load-host-domain-class.d.ts +1 -0
- package/dist/types/client/host-bridge/resolve-host-bootstrap.d.ts +20 -0
- package/dist/types/client/infra/http/IHttpClient.d.ts +2 -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/dist/types/shared/registry-generated/error-codes.d.ts +4 -0
- package/dist/types/shared/registry-generated/limits.d.ts +4 -0
- package/dist/types/shared/types/data-config.types.d.ts +2 -0
- 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 +13 -32
- 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
|
@@ -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);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path, { join, normalize, resolve } from "node:path";
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* 将 kebab-case / snake_case 转为 PascalCase
|
|
@@ -8,32 +9,95 @@ export function toPascalCase(str: string): string {
|
|
|
8
9
|
return str
|
|
9
10
|
.split(/[-_]/)
|
|
10
11
|
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
|
11
|
-
.join(
|
|
12
|
+
.join("");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 校验服务路由片段的安全与合法性,并将末段解析为 PascalCase 类名。
|
|
17
|
+
* 拒收:空片段、"." / ".."、以 "_" 起头的私有模块、含 "/" / "\\" / "\0" 的穿越字符。
|
|
18
|
+
*/
|
|
19
|
+
export function validateServiceSegments(segments: readonly string[]): { dirSegments: string[]; className: string } | null {
|
|
20
|
+
if (!segments || segments.length === 0) return null;
|
|
21
|
+
|
|
22
|
+
for (const segment of segments) {
|
|
23
|
+
if (!segment || typeof segment !== "string" || segment.startsWith("_")) return null;
|
|
24
|
+
if (segment === "." || segment === "..") return null;
|
|
25
|
+
if (segment.includes("/") || segment.includes("\\") || segment.includes("\0")) return null;
|
|
26
|
+
const normalized = normalize(segment);
|
|
27
|
+
if (normalized === "." || normalized.startsWith("..") || normalized.includes("\0")) return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const last = segments[segments.length - 1];
|
|
31
|
+
const className = toPascalCase(last);
|
|
32
|
+
if (!className) return null;
|
|
33
|
+
const dirSegments = segments.slice(0, -1);
|
|
34
|
+
return { dirSegments, className };
|
|
12
35
|
}
|
|
13
36
|
|
|
14
37
|
/**
|
|
15
38
|
* 从 /api/{...path} 片段解析宿主服务文件绝对路径。
|
|
16
39
|
*
|
|
17
40
|
* 规则(与文档 12.4 一致):
|
|
18
|
-
* - ["
|
|
41
|
+
* - ["products"] → {host}/api/service/Products.ts
|
|
19
42
|
* - ["user", "profile"] → {host}/api/service/user/Profile.ts
|
|
20
43
|
*/
|
|
21
44
|
export function resolveServiceFilePath(hostDir: string, segments: string[]): string | null {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
for (const segment of segments) {
|
|
25
|
-
if (!segment || segment.startsWith('_')) return null;
|
|
26
|
-
const normalized = normalize(segment);
|
|
27
|
-
if (normalized.startsWith('..') || normalized.includes('\0')) return null;
|
|
28
|
-
}
|
|
45
|
+
const validated = validateServiceSegments(segments);
|
|
46
|
+
if (!validated) return null;
|
|
29
47
|
|
|
30
|
-
const fileName = `${
|
|
31
|
-
const
|
|
32
|
-
const filePath = join(hostDir, 'api', 'service', ...dirs, fileName);
|
|
48
|
+
const fileName = `${validated.className}.ts`;
|
|
49
|
+
const filePath = join(hostDir, "api", "service", ...validated.dirSegments, fileName);
|
|
33
50
|
|
|
34
51
|
const resolved = resolve(filePath);
|
|
35
|
-
const serviceRoot = resolve(hostDir,
|
|
52
|
+
const serviceRoot = resolve(hostDir, "api", "service");
|
|
36
53
|
if (!resolved.startsWith(serviceRoot)) return null;
|
|
37
54
|
|
|
38
55
|
return resolved;
|
|
39
56
|
}
|
|
57
|
+
|
|
58
|
+
export interface ResolveHostServiceCandidateOptions {
|
|
59
|
+
readonly allowDirectRoot?: boolean;
|
|
60
|
+
readonly extensions?: readonly string[];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const DEFAULT_SERVICE_EXTENSIONS: readonly string[] = [".ts", ".js", ".mjs", ".cjs"];
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 在给定后端根 apiRoot 下按顺序探测真实存在的服务文件(默认后缀顺序 [".ts", ".js", ".mjs", ".cjs"]):
|
|
67
|
+
* 1) <apiRoot>/api/service/<...dirSegments>/<ClassName><ext>
|
|
68
|
+
* 2) <apiRoot>/service/<...dirSegments>/<ClassName><ext>
|
|
69
|
+
* 3) 当 options?.allowDirectRoot === true 时额外探测 <apiRoot>/<...dirSegments>/<ClassName><ext>
|
|
70
|
+
* 每一步都必须校验 resolved.startsWith(normalizedAllowedBase + path.sep) 且 fs.statSync(resolved, { throwIfNoEntry: false })?.isFile() === true
|
|
71
|
+
*/
|
|
72
|
+
export function resolveHostServiceCandidate(
|
|
73
|
+
apiRoot: string,
|
|
74
|
+
segments: string[],
|
|
75
|
+
options?: ResolveHostServiceCandidateOptions,
|
|
76
|
+
): string | null {
|
|
77
|
+
const validated = validateServiceSegments(segments);
|
|
78
|
+
if (!validated) return null;
|
|
79
|
+
|
|
80
|
+
const normalizedApiRoot = resolve(apiRoot);
|
|
81
|
+
const extensions = options?.extensions ?? DEFAULT_SERVICE_EXTENSIONS;
|
|
82
|
+
const { dirSegments, className } = validated;
|
|
83
|
+
|
|
84
|
+
const candidateBases = [
|
|
85
|
+
join(normalizedApiRoot, "api", "service"),
|
|
86
|
+
join(normalizedApiRoot, "service"),
|
|
87
|
+
...(options?.allowDirectRoot ? [normalizedApiRoot] : []),
|
|
88
|
+
];
|
|
89
|
+
|
|
90
|
+
for (const base of candidateBases) {
|
|
91
|
+
const normalizedAllowedBase = resolve(base);
|
|
92
|
+
for (const ext of extensions) {
|
|
93
|
+
const fileName = `${className}${ext}`;
|
|
94
|
+
const resolved = resolve(normalizedAllowedBase, ...dirSegments, fileName);
|
|
95
|
+
if (resolved.startsWith(normalizedAllowedBase + path.sep)) {
|
|
96
|
+
const stat = fs.statSync(resolved, { throwIfNoEntry: false });
|
|
97
|
+
if (stat?.isFile()) return resolved;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
@@ -57,3 +57,60 @@ export function hasRuleForCandidate(css: string, candidate: string): boolean {
|
|
|
57
57
|
from = at + needle.length;
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
|
+
|
|
61
|
+
function decodeCssEscape(escaped: string): string {
|
|
62
|
+
return escaped.replace(/\\(?:([0-9a-fA-F]{1,6})[ \t\r\n\f]?|([\s\S]))/g, (_match, hex, char) => {
|
|
63
|
+
if (hex !== undefined) {
|
|
64
|
+
const code = parseInt(hex, 16);
|
|
65
|
+
return code === 0 ? '�' : String.fromCodePoint(code);
|
|
66
|
+
}
|
|
67
|
+
return char;
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const CLASS_SELECTOR_RE = /\.((?:[a-zA-Z_]|[^\x00-\x7f]|-(?![0-9])|\\(?:[0-9a-fA-F]{1,6}[ \t\r\n\f]?|[\s\S]))(?:[a-zA-Z0-9_-]|[^\x00-\x7f]|\\(?:[0-9a-fA-F]{1,6}[ \t\r\n\f]?|[\s\S]))*)/g;
|
|
72
|
+
|
|
73
|
+
/** 从 CSS 选择器片段单遍提取所有类名(已解码转义) */
|
|
74
|
+
export function extractClassesFromCss(css: string): Set<string> {
|
|
75
|
+
const classes = new Set<string>();
|
|
76
|
+
const clean = css.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
77
|
+
let segStart = 0;
|
|
78
|
+
for (let i = 0; i < clean.length; i++) {
|
|
79
|
+
const ch = clean[i];
|
|
80
|
+
if (ch === '{') {
|
|
81
|
+
const seg = clean.slice(segStart, i);
|
|
82
|
+
CLASS_SELECTOR_RE.lastIndex = 0;
|
|
83
|
+
let m: RegExpExecArray | null;
|
|
84
|
+
while ((m = CLASS_SELECTOR_RE.exec(seg)) !== null) {
|
|
85
|
+
classes.add(decodeCssEscape(m[1]));
|
|
86
|
+
}
|
|
87
|
+
segStart = i + 1;
|
|
88
|
+
} else if (ch === '}' || ch === ';') {
|
|
89
|
+
segStart = i + 1;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return classes;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 批量判定编译产物中是否包含指定候选类的规则。
|
|
97
|
+
* O(1) 查表命中 99.9% 候选类,未命中时回退 hasRuleForCandidate 兜底复杂选择器,结果逐字等价。
|
|
98
|
+
*/
|
|
99
|
+
export function partitionCompiledCandidates(
|
|
100
|
+
css: string,
|
|
101
|
+
candidates: readonly string[],
|
|
102
|
+
): { matched: string[]; unmatched: string[] } {
|
|
103
|
+
const classSet = extractClassesFromCss(css);
|
|
104
|
+
const matched: string[] = [];
|
|
105
|
+
const unmatched: string[] = [];
|
|
106
|
+
for (const candidate of candidates) {
|
|
107
|
+
if (classSet.has(candidate)) {
|
|
108
|
+
matched.push(candidate);
|
|
109
|
+
} else if (hasRuleForCandidate(css, candidate)) {
|
|
110
|
+
matched.push(candidate);
|
|
111
|
+
} else {
|
|
112
|
+
unmatched.push(candidate);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { matched, unmatched };
|
|
116
|
+
}
|
|
@@ -22,7 +22,7 @@ export type {
|
|
|
22
22
|
} from '../../../shared/engines/style/style-engine.types';
|
|
23
23
|
export { assertStyleEngineAdapter, assertThemeCss } from './port';
|
|
24
24
|
export { guardCandidates } from './candidate-guard';
|
|
25
|
-
export { createTailwindAdapter } from './tailwind-adapter';
|
|
25
|
+
export { createTailwindAdapter, clearTailwindCompilerCache } from './tailwind-adapter';
|
|
26
26
|
|
|
27
27
|
export interface StyleEnginePortOptions { readonly telemetry?: EngineLoadTelemetry }
|
|
28
28
|
|
|
@@ -12,15 +12,31 @@ import type {
|
|
|
12
12
|
StyleCompileResult,
|
|
13
13
|
} from '../../../shared/engines/style/style-engine.types';
|
|
14
14
|
import { loadEngineModule, type EngineLoadTelemetry } from '../../../client/engines/load';
|
|
15
|
-
import { guardCandidates,
|
|
15
|
+
import { guardCandidates, partitionCompiledCandidates } from './candidate-guard';
|
|
16
16
|
import { assertThemeCss } from './port';
|
|
17
17
|
|
|
18
|
-
interface TailwindCompiler { build(candidates: string[]): string }
|
|
19
|
-
interface TailwindModule { compile(css: string): Promise<TailwindCompiler> }
|
|
18
|
+
export interface TailwindCompiler { build(candidates: string[]): string }
|
|
19
|
+
export interface TailwindModule { compile(css: string, options?: { base?: string }): Promise<TailwindCompiler> }
|
|
20
20
|
|
|
21
|
-
export interface TailwindAdapterOptions {
|
|
21
|
+
export interface TailwindAdapterOptions {
|
|
22
|
+
readonly telemetry?: EngineLoadTelemetry;
|
|
23
|
+
readonly base?: string;
|
|
24
|
+
readonly loadTailwind?: () => Promise<TailwindModule>;
|
|
25
|
+
}
|
|
22
26
|
|
|
23
27
|
const UTILITIES_DIRECTIVE = /@tailwind\s+utilities\b/;
|
|
28
|
+
const MAX_COMPILER_CACHE = 16;
|
|
29
|
+
|
|
30
|
+
const defaultCompilerCache = new Map<string, Promise<TailwindCompiler>>();
|
|
31
|
+
let defaultTailwindModulePromise: Promise<TailwindModule> | null = null;
|
|
32
|
+
let customCompilerCaches = new WeakMap<object, Map<string, Promise<TailwindCompiler>>>();
|
|
33
|
+
|
|
34
|
+
/** 清除 Tailwind 编译器与模块缓存(供内部测试重置) */
|
|
35
|
+
export function clearTailwindCompilerCache(): void {
|
|
36
|
+
defaultCompilerCache.clear();
|
|
37
|
+
defaultTailwindModulePromise = null;
|
|
38
|
+
customCompilerCaches = new WeakMap();
|
|
39
|
+
}
|
|
24
40
|
|
|
25
41
|
function withUtilities(themeCss: string): string {
|
|
26
42
|
return UTILITIES_DIRECTIVE.test(themeCss) ? themeCss : `${themeCss}\n@tailwind utilities;\n`;
|
|
@@ -31,24 +47,74 @@ function digestOf(css: string): string {
|
|
|
31
47
|
}
|
|
32
48
|
|
|
33
49
|
export function createTailwindAdapter(adapterOptions: TailwindAdapterOptions = {}): SomaStyleEngine {
|
|
34
|
-
const load = (): Promise<TailwindModule> =>
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
50
|
+
const load = (): Promise<TailwindModule> => {
|
|
51
|
+
if (adapterOptions.loadTailwind !== undefined) {
|
|
52
|
+
return adapterOptions.loadTailwind();
|
|
53
|
+
}
|
|
54
|
+
if (!defaultTailwindModulePromise) {
|
|
55
|
+
defaultTailwindModulePromise = loadEngineModule<TailwindModule>(
|
|
56
|
+
'tailwindcss',
|
|
57
|
+
() => import('tailwindcss') as unknown as Promise<TailwindModule>,
|
|
58
|
+
{ telemetry: adapterOptions.telemetry },
|
|
59
|
+
).catch((cause) => {
|
|
60
|
+
defaultTailwindModulePromise = null;
|
|
61
|
+
throw cause;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return defaultTailwindModulePromise;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const getCompilerCache = (): Map<string, Promise<TailwindCompiler>> => {
|
|
68
|
+
if (adapterOptions.loadTailwind !== undefined) {
|
|
69
|
+
let m = customCompilerCaches.get(adapterOptions.loadTailwind);
|
|
70
|
+
if (!m) {
|
|
71
|
+
m = new Map<string, Promise<TailwindCompiler>>();
|
|
72
|
+
customCompilerCaches.set(adapterOptions.loadTailwind, m);
|
|
73
|
+
}
|
|
74
|
+
return m;
|
|
75
|
+
}
|
|
76
|
+
return defaultCompilerCache;
|
|
77
|
+
};
|
|
38
78
|
|
|
39
79
|
return {
|
|
40
80
|
id: 'tailwind',
|
|
41
81
|
async compile(input: StyleCompileInput): Promise<StyleCompileResult> {
|
|
42
82
|
assertThemeCss(input.themeCss);
|
|
43
83
|
const guarded = guardCandidates(input.candidates, input.allow);
|
|
44
|
-
const
|
|
84
|
+
const cssWithUtils = withUtilities(input.themeCss);
|
|
85
|
+
const cacheKey = createHash('sha256')
|
|
86
|
+
.update(cssWithUtils + '\0' + (adapterOptions.base ?? ''))
|
|
87
|
+
.digest('hex');
|
|
88
|
+
|
|
89
|
+
const compilerCache = getCompilerCache();
|
|
90
|
+
let compilerPromise = compilerCache.get(cacheKey);
|
|
91
|
+
if (compilerPromise !== undefined) {
|
|
92
|
+
compilerCache.delete(cacheKey);
|
|
93
|
+
compilerCache.set(cacheKey, compilerPromise);
|
|
94
|
+
} else {
|
|
95
|
+
while (compilerCache.size >= MAX_COMPILER_CACHE) {
|
|
96
|
+
const oldest = compilerCache.keys().next().value;
|
|
97
|
+
if (oldest !== undefined) compilerCache.delete(oldest);
|
|
98
|
+
else break;
|
|
99
|
+
}
|
|
100
|
+
compilerPromise = (async () => {
|
|
101
|
+
const lib = await load();
|
|
102
|
+
const compileOptions = adapterOptions.base !== undefined ? { base: adapterOptions.base } : undefined;
|
|
103
|
+
return compileOptions ? lib.compile(cssWithUtils, compileOptions) : lib.compile(cssWithUtils);
|
|
104
|
+
})().catch((cause) => {
|
|
105
|
+
compilerCache.delete(cacheKey);
|
|
106
|
+
throw cause;
|
|
107
|
+
});
|
|
108
|
+
compilerCache.set(cacheKey, compilerPromise);
|
|
109
|
+
}
|
|
45
110
|
|
|
46
111
|
let compiler: TailwindCompiler;
|
|
47
112
|
try {
|
|
48
|
-
compiler = await
|
|
113
|
+
compiler = await compilerPromise;
|
|
49
114
|
} catch (cause) {
|
|
50
115
|
throw new SomaEngineError('CORE-STYLE-ENGINE-THEME', 'style', '主题 CSS 编译失败', { cause });
|
|
51
116
|
}
|
|
117
|
+
|
|
52
118
|
let css: string;
|
|
53
119
|
try {
|
|
54
120
|
css = compiler.build([...guarded.accepted]);
|
|
@@ -56,12 +122,13 @@ export function createTailwindAdapter(adapterOptions: TailwindAdapterOptions = {
|
|
|
56
122
|
throw new SomaEngineError('CORE-STYLE-ENGINE-COMPILE', 'style', '样式表编译失败', { cause });
|
|
57
123
|
}
|
|
58
124
|
|
|
59
|
-
const
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
125
|
+
const { matched, unmatched } = partitionCompiledCandidates(css, guarded.accepted);
|
|
126
|
+
const accepted: string[] = matched;
|
|
127
|
+
const rejected: StyleCompileRejection[] = [
|
|
128
|
+
...guarded.rejected,
|
|
129
|
+
...unmatched.map((candidate) => ({ candidate, reason: 'no-rule' as const })),
|
|
130
|
+
];
|
|
131
|
+
|
|
65
132
|
return { css, accepted, rejected, digest: digestOf(css) };
|
|
66
133
|
},
|
|
67
134
|
};
|