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.
Files changed (96) hide show
  1. package/README.md +2 -2
  2. package/bin/soma.cjs +1 -1
  3. package/bin/soma.ts +64 -15
  4. package/core/build/compiler/soma-precompile.js +11 -1
  5. package/core/client/base/SomaHttpClient.ts +85 -12
  6. package/core/client/data/data-object-resolver.ts +12 -1
  7. package/core/client/engine/event-engine.ts +3 -3
  8. package/core/client/engine/soma-bootstrap.ts +30 -30
  9. package/core/client/host-bridge/load-host-domain-class.ts +74 -20
  10. package/core/client/host-bridge/resolve-host-bootstrap.ts +125 -23
  11. package/core/client/infra/http/IHttpClient.ts +3 -1
  12. package/core/client/infra/http/SomaHttpService.ts +15 -6
  13. package/core/client/parser/data-config-parser.ts +6 -1
  14. package/core/server/api/dispatch-service-api.ts +212 -0
  15. package/core/server/api/load-host-service.ts +230 -56
  16. package/core/server/api/service-path.ts +78 -14
  17. package/core/server/engines/style/candidate-guard.ts +57 -0
  18. package/core/server/engines/style/index.ts +1 -1
  19. package/core/server/engines/style/tailwind-adapter.ts +83 -16
  20. package/core/server/host/source-packages.cjs +96 -30
  21. package/core/server/host/source-packages.ts +12 -5
  22. package/core/server/index.ts +39 -17
  23. package/core/server/infra/cache/ServerFileCache.ts +138 -25
  24. package/core/server/node.ts +32 -8
  25. package/core/shared/registry-generated/error-codes.ts +5 -0
  26. package/core/shared/registry-generated/limits.ts +5 -0
  27. package/core/shared/types/data-config.types.ts +2 -0
  28. package/dist/browser/soma-runtime.js +197 -49
  29. package/dist/cli/soma.js +68 -14
  30. package/dist/core/index.cjs +284 -64
  31. package/dist/host-native/aot-builder.cjs +850 -0
  32. package/dist/host-native/native-server.cjs +15338 -0
  33. package/dist/lsp/component-tree.cjs +11 -1
  34. package/dist/types/client/base/SomaHttpClient.d.ts +1 -8
  35. package/dist/types/client/data/data-object-resolver.d.ts +1 -0
  36. package/dist/types/client/engine/event-engine.d.ts +2 -2
  37. package/dist/types/client/engine/soma-bootstrap.d.ts +3 -2
  38. package/dist/types/client/host-bridge/load-host-domain-class.d.ts +1 -0
  39. package/dist/types/client/host-bridge/resolve-host-bootstrap.d.ts +20 -0
  40. package/dist/types/client/infra/http/IHttpClient.d.ts +2 -0
  41. package/dist/types/server/api/dispatch-service-api.d.ts +18 -0
  42. package/dist/types/server/api/load-host-service.d.ts +7 -2
  43. package/dist/types/server/api/service-path.d.ts +21 -1
  44. package/dist/types/server/engines/style/candidate-guard.d.ts +10 -0
  45. package/dist/types/server/engines/style/index.d.ts +1 -1
  46. package/dist/types/server/engines/style/tailwind-adapter.d.ts +12 -0
  47. package/dist/types/server/host/source-packages.d.cts +13 -1
  48. package/dist/types/server/host/source-packages.d.ts +7 -4
  49. package/dist/types/server/index.d.ts +18 -17
  50. package/dist/types/server/infra/cache/ServerFileCache.d.ts +28 -5
  51. package/dist/types/server/node.d.ts +10 -7
  52. package/dist/types/shared/registry-generated/error-codes.d.ts +4 -0
  53. package/dist/types/shared/registry-generated/limits.d.ts +4 -0
  54. package/dist/types/shared/types/data-config.types.d.ts +2 -0
  55. package/host-native/bin/host-native.cjs +204 -0
  56. package/host-native/client/browser-entry.ts +499 -0
  57. package/{host-next/app → host-native/client}/page-access.ts +12 -0
  58. package/host-native/client/router-bridge.ts +120 -0
  59. package/host-native/src/aot-builder.ts +486 -0
  60. package/host-native/src/csp-headers.ts +75 -0
  61. package/host-native/src/host-prepare.ts +123 -0
  62. package/{host-next/app/soma/manifest/route.ts → host-native/src/manifest-http.ts} +10 -10
  63. package/host-native/src/native-server.ts +691 -0
  64. package/host-native/src/page-http.ts +223 -0
  65. package/host-native/src/public-packages.cjs +167 -0
  66. package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts} +17 -19
  67. package/{host-next → host-native}/src/shell-routes.cjs +23 -13
  68. package/host-native/src/static-file.ts +172 -0
  69. package/host-native/src/workspace.ts +185 -0
  70. package/{host-next/app → host-native/styles}/globals.css +2 -2
  71. package/package.json +13 -32
  72. package/tsconfig.json +1 -1
  73. package/host-next/app/SomaPageClient.tsx +0 -359
  74. package/host-next/app/[...path]/page.tsx +0 -22
  75. package/host-next/app/api/[...path]/route.ts +0 -98
  76. package/host-next/app/components/SomaHostPage.tsx +0 -128
  77. package/host-next/app/components/SomaHydrationShell.tsx +0 -20
  78. package/host-next/app/components/SomaPageClientBoundary.tsx +0 -13
  79. package/host-next/app/components/SomaPageForbidden.tsx +0 -19
  80. package/host-next/app/favicon.ico/route.ts +0 -13
  81. package/host-next/app/layout.tsx +0 -27
  82. package/host-next/app/page.tsx +0 -9
  83. package/host-next/app/router-bridge.ts +0 -42
  84. package/host-next/app/soma/[...path]/route.ts +0 -9
  85. package/host-next/app/soma/_shared/host-prepare.ts +0 -33
  86. package/host-next/app/soma/_shared/page-http.ts +0 -86
  87. package/host-next/app/soma/page/route.ts +0 -36
  88. package/host-next/app/soma/route.ts +0 -9
  89. package/host-next/app/soma-runtime/[...file]/route.ts +0 -21
  90. package/host-next/app/soma-runtime/_shared/static-file.ts +0 -89
  91. package/host-next/bin/host-next.cjs +0 -60
  92. package/host-next/instrumentation.ts +0 -18
  93. package/host-next/next-env.d.ts +0 -7
  94. package/host-next/next.config.js +0 -410
  95. package/host-next/proxy.ts +0 -43
  96. package/host-next/src/workspace.ts +0 -543
@@ -1,82 +1,256 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import type { IService } from './IService';
4
- import { resolveServiceFilePath } from './service-path';
5
- import { getSomaAssetSources, getSomaHostSourceRoot } from '../host/source-packages';
6
- import { ensureNodeServerOnlyInterop, getJitiFactory } from '../host/host-assembly';
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 !== 'object') return false;
10
- const methods = ['get', 'post', 'put', 'patch', 'delete'] as const;
11
- return methods.some((m) => typeof (obj as IService)[m] === 'function');
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
- // soma-core 根目录(route 运行于 next dev/build,cwd 即工作区,其下有 core)
16
- return path.resolve(process.cwd(), 'core');
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
- let jitiLoader: ((file: string) => unknown) | null = null;
20
- let jitiHostDir: string | null = null;
21
- const instanceCache = new Map<string, IService>();
22
-
23
- function getJiti(hostDir: string): (file: string) => unknown {
24
- if (!jitiLoader || jitiHostDir !== hostDir) {
25
- const serverOnlyEmpty = ensureNodeServerOnlyInterop(hostDir);
26
- const createJiti = getJitiFactory(hostDir);
27
- const hostSourceRoot = getSomaHostSourceRoot(hostDir);
28
- jitiLoader = createJiti(path.resolve(hostDir, 'package.json'), {
29
- interopDefault: true,
30
- alias: {
31
- '@core': getCoreDir(),
32
- '@soma-host': hostSourceRoot,
33
- ...(serverOnlyEmpty !== undefined ? { 'server-only': serverOnlyEmpty } : {}),
34
- },
35
- });
36
- jitiHostDir = hostDir;
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
- return jitiLoader;
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
- * 按约定从宿主 api/service/ 加载 IService 实例(运行时读盘,无需手写 registry)。
144
+ * 按约定从宿主 apiRoot 加载 IService 实例(运行时按需加载,零手动 registry)。
43
145
  */
44
146
  export function loadHostService(segments: string[]): IService | null {
45
- if (typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge') return null;
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 filePath = getSomaAssetSources(hostDir)
50
- .map((source) => resolveServiceFilePath(source.codeRoot, segments))
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
- const isDev = process.env.NODE_ENV !== 'production';
55
- if (!isDev && instanceCache.has(filePath)) {
56
- return instanceCache.get(filePath)!;
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
- try {
60
- const loaded = getJiti(hostDir)(filePath) as unknown;
61
- // Jiti with `interopDefault: true` returns a lone default export directly.
62
- // A default class that extends another default-exported class can inherit a
63
- // static `.default` from its base, so reading `loaded.default` first would
64
- // instantiate the base service and silently drop the Host subclass setup.
65
- const ServiceClass = typeof loaded === 'function'
66
- ? loaded as new () => IService
67
- : (loaded as { default?: new () => IService } | null)?.default;
68
- if (!ServiceClass || typeof ServiceClass !== 'function') {
69
- console.warn(`[soma-core][接口] ${filePath} missing default export`);
70
- return null;
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
- const instance = new ServiceClass();
74
- if (!isService(instance)) {
75
- console.warn(`[soma-core][接口] ${filePath} does not implement IService`);
76
- return null;
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 (!isDev) instanceCache.set(filePath, instance);
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 { join, normalize, resolve } from 'node:path';
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
- * - ["login"] → {host}/api/service/Login.ts
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
- if (segments.length === 0) return null;
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 = `${toPascalCase(segments[segments.length - 1])}.ts`;
31
- const dirs = segments.slice(0, -1);
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, 'api', 'service');
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, hasRuleForCandidate } from './candidate-guard';
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 { readonly telemetry?: EngineLoadTelemetry }
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
- loadEngineModule<TailwindModule>('tailwindcss', () => import('tailwindcss') as unknown as Promise<TailwindModule>, {
36
- telemetry: adapterOptions.telemetry,
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 lib = await load();
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 lib.compile(withUtilities(input.themeCss));
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 accepted: string[] = [];
60
- const rejected: StyleCompileRejection[] = [...guarded.rejected];
61
- for (const candidate of guarded.accepted) {
62
- if (hasRuleForCandidate(css, candidate)) accepted.push(candidate);
63
- else rejected.push({ candidate, reason: 'no-rule' });
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
  };