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.
Files changed (70) 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/server/api/dispatch-service-api.ts +212 -0
  5. package/core/server/api/load-host-service.ts +230 -56
  6. package/core/server/api/service-path.ts +79 -14
  7. package/core/server/engines/style/candidate-guard.ts +57 -0
  8. package/core/server/engines/style/index.ts +1 -1
  9. package/core/server/engines/style/tailwind-adapter.ts +83 -16
  10. package/core/server/host/source-packages.cjs +98 -30
  11. package/core/server/host/source-packages.ts +12 -5
  12. package/core/server/index.ts +39 -17
  13. package/core/server/infra/cache/ServerFileCache.ts +138 -25
  14. package/core/server/node.ts +32 -8
  15. package/dist/cli/soma.js +68 -14
  16. package/dist/host-native/aot-builder.cjs +852 -0
  17. package/dist/host-native/native-server.cjs +15341 -0
  18. package/dist/types/server/api/dispatch-service-api.d.ts +18 -0
  19. package/dist/types/server/api/load-host-service.d.ts +7 -2
  20. package/dist/types/server/api/service-path.d.ts +21 -1
  21. package/dist/types/server/engines/style/candidate-guard.d.ts +10 -0
  22. package/dist/types/server/engines/style/index.d.ts +1 -1
  23. package/dist/types/server/engines/style/tailwind-adapter.d.ts +12 -0
  24. package/dist/types/server/host/source-packages.d.cts +13 -1
  25. package/dist/types/server/host/source-packages.d.ts +7 -4
  26. package/dist/types/server/index.d.ts +18 -17
  27. package/dist/types/server/infra/cache/ServerFileCache.d.ts +28 -5
  28. package/dist/types/server/node.d.ts +10 -7
  29. package/host-native/bin/host-native.cjs +204 -0
  30. package/host-native/client/browser-entry.ts +499 -0
  31. package/{host-next/app → host-native/client}/page-access.ts +12 -0
  32. package/host-native/client/router-bridge.ts +120 -0
  33. package/host-native/src/aot-builder.ts +486 -0
  34. package/host-native/src/csp-headers.ts +75 -0
  35. package/host-native/src/host-prepare.ts +123 -0
  36. package/{host-next/app/soma/manifest/route.ts → host-native/src/manifest-http.ts} +10 -10
  37. package/host-native/src/native-server.ts +691 -0
  38. package/host-native/src/page-http.ts +223 -0
  39. package/host-native/src/public-packages.cjs +167 -0
  40. package/{host-next/app/api/soma-registry/[...path]/route.ts → host-native/src/registry-handler.ts} +17 -19
  41. package/{host-next → host-native}/src/shell-routes.cjs +23 -13
  42. package/host-native/src/static-file.ts +172 -0
  43. package/host-native/src/workspace.ts +185 -0
  44. package/{host-next/app → host-native/styles}/globals.css +2 -2
  45. package/package.json +12 -31
  46. package/tsconfig.json +1 -1
  47. package/host-next/app/SomaPageClient.tsx +0 -359
  48. package/host-next/app/[...path]/page.tsx +0 -22
  49. package/host-next/app/api/[...path]/route.ts +0 -98
  50. package/host-next/app/components/SomaHostPage.tsx +0 -128
  51. package/host-next/app/components/SomaHydrationShell.tsx +0 -20
  52. package/host-next/app/components/SomaPageClientBoundary.tsx +0 -13
  53. package/host-next/app/components/SomaPageForbidden.tsx +0 -19
  54. package/host-next/app/favicon.ico/route.ts +0 -13
  55. package/host-next/app/layout.tsx +0 -27
  56. package/host-next/app/page.tsx +0 -9
  57. package/host-next/app/router-bridge.ts +0 -42
  58. package/host-next/app/soma/[...path]/route.ts +0 -9
  59. package/host-next/app/soma/_shared/host-prepare.ts +0 -33
  60. package/host-next/app/soma/_shared/page-http.ts +0 -86
  61. package/host-next/app/soma/page/route.ts +0 -36
  62. package/host-next/app/soma/route.ts +0 -9
  63. package/host-next/app/soma-runtime/[...file]/route.ts +0 -21
  64. package/host-next/app/soma-runtime/_shared/static-file.ts +0 -89
  65. package/host-next/bin/host-next.cjs +0 -60
  66. package/host-next/instrumentation.ts +0 -18
  67. package/host-next/next-env.d.ts +0 -7
  68. package/host-next/next.config.js +0 -410
  69. package/host-next/proxy.ts +0 -43
  70. package/host-next/src/workspace.ts +0 -543
@@ -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,96 @@ 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, "..", "api", "service"),
87
+ join(normalizedApiRoot, "service"),
88
+ ...(options?.allowDirectRoot ? [normalizedApiRoot] : []),
89
+ ];
90
+
91
+ for (const base of candidateBases) {
92
+ const normalizedAllowedBase = resolve(base);
93
+ for (const ext of extensions) {
94
+ const fileName = `${className}${ext}`;
95
+ const resolved = resolve(normalizedAllowedBase, ...dirSegments, fileName);
96
+ if (resolved.startsWith(normalizedAllowedBase + path.sep)) {
97
+ const stat = fs.statSync(resolved, { throwIfNoEntry: false });
98
+ if (stat?.isFile()) return resolved;
99
+ }
100
+ }
101
+ }
102
+
103
+ return null;
104
+ }
@@ -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
  };
@@ -5,33 +5,42 @@
5
5
  // `scripts/verify-single-impl.mjs` 的 S1-d 对「别处再写一份源包判定」报红。
6
6
  //
7
7
  // 纪律(AD-34):这里只有 Host 与源包两种来源类别,不出现任何产生方的名字。
8
- const fs = require('node:fs');
9
- const path = require('node:path');
8
+ const fs = require("node:fs");
9
+ const path = require("node:path");
10
10
 
11
11
  /** @typedef {Readonly<Record<string, string | undefined>>} SomaEnv */
12
- const { getSomaHostConfigRoot } = require('./host-config-paths.cjs');
12
+ const { getSomaHostConfigRoot } = require("./host-config-paths.cjs");
13
13
 
14
14
  /** 环境变量:显式声明的源包名(逗号分隔),不论其 package.json 怎么写都当源包 */
15
- const SOMA_SOURCE_PACKAGES_ENV = 'SOMA_SOURCE_PACKAGES';
15
+ const SOMA_SOURCE_PACKAGES_ENV = "SOMA_SOURCE_PACKAGES";
16
+
17
+ const MAX_ASSET_SOURCE_CACHE = 64;
18
+ /** @typedef {{ type: "host" | "package"; name: string; assetRoot: string; codeRoot: string; apiRoot: string; configRoot: string; packageName?: string }} SomaAssetSourceItem */
19
+ /** @type {Map<string, SomaAssetSourceItem[]>} */
20
+ const assetSourcesCache = new Map();
21
+
22
+ function clearSomaAssetSourcesCache() {
23
+ assetSourcesCache.clear();
24
+ }
16
25
 
17
26
  function readJson(filePath) {
18
27
  try {
19
28
  if (!fs.existsSync(filePath)) return null;
20
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
29
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
21
30
  } catch {
22
31
  return null;
23
32
  }
24
33
  }
25
34
 
26
35
  function packagePathInNodeModules(hostDir, packageName) {
27
- return path.join(hostDir, 'node_modules', ...packageName.split('/'));
36
+ return path.join(hostDir, "node_modules", ...packageName.split("/"));
28
37
  }
29
38
 
30
39
  function resolvePackageRoot(hostDir, packageName, version) {
31
40
  const nodeModulesPath = packagePathInNodeModules(hostDir, packageName);
32
41
  if (fs.existsSync(nodeModulesPath)) return nodeModulesPath;
33
- if (typeof version === 'string' && version.startsWith('file:')) {
34
- const fileRoot = path.resolve(hostDir, version.slice('file:'.length));
42
+ if (typeof version === "string" && version.startsWith("file:")) {
43
+ const fileRoot = path.resolve(hostDir, version.slice("file:".length));
35
44
  if (fs.existsSync(fileRoot)) return fileRoot;
36
45
  }
37
46
  return null;
@@ -39,14 +48,14 @@ function resolvePackageRoot(hostDir, packageName, version) {
39
48
 
40
49
  /** @param {SomaEnv} [env] */
41
50
  function readExplicitSourcePackages(env = process.env) {
42
- return String(env[SOMA_SOURCE_PACKAGES_ENV] ?? '')
43
- .split(',')
51
+ return String(env?.[SOMA_SOURCE_PACKAGES_ENV] ?? "")
52
+ .split(",")
44
53
  .map((item) => item.trim())
45
54
  .filter(Boolean);
46
55
  }
47
56
 
48
57
  function readHostDependencies(hostDir) {
49
- const packageJson = readJson(path.join(hostDir, 'package.json'));
58
+ const packageJson = readJson(path.join(hostDir, "package.json"));
50
59
  return {
51
60
  ...(packageJson?.dependencies ?? {}),
52
61
  ...(packageJson?.devDependencies ?? {}),
@@ -56,7 +65,7 @@ function readHostDependencies(hostDir) {
56
65
  /** 子路径必须落在 parent 内且存在,否则回落 parent(越界不报错、不跟随) */
57
66
  function resolveSafeChildRoot(parent, relativePath) {
58
67
  const normalizedParent = path.resolve(parent);
59
- const trimmed = typeof relativePath === 'string' ? relativePath.trim() : '';
68
+ const trimmed = typeof relativePath === "string" ? relativePath.trim() : "";
60
69
  if (!trimmed) return normalizedParent;
61
70
  const resolved = path.resolve(normalizedParent, trimmed);
62
71
  if (resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`)) {
@@ -65,29 +74,68 @@ function resolveSafeChildRoot(parent, relativePath) {
65
74
  return normalizedParent;
66
75
  }
67
76
 
68
- function getSomaHostSourceRoot(hostDir) {
77
+ /** 解析显式外部/同级/子目录路径(仅用于宿主自身 hostDir,第三方包不走此函数) */
78
+ function resolveExplicitHostPath(baseDir, rawPath, options = {}) {
79
+ if (typeof rawPath !== "string") return null;
80
+ const trimmed = rawPath.trim();
81
+ if (!trimmed || trimmed.includes("\0")) return null;
82
+ const resolved = path.resolve(baseDir, trimmed);
83
+ if (resolved === path.parse(resolved).root) return null;
84
+ if (options.requireExists && !fs.existsSync(resolved)) return null;
85
+ return resolved;
86
+ }
87
+
88
+ function getSomaHostSourceRoot(hostDir, env = process.env) {
69
89
  const normalizedHostDir = path.resolve(hostDir);
70
- const packageJson = readJson(path.join(normalizedHostDir, 'package.json'));
90
+ if (env && typeof env.SOMA_WEB_DIR === "string" && env.SOMA_WEB_DIR.trim()) {
91
+ const explicit = resolveExplicitHostPath(normalizedHostDir, env.SOMA_WEB_DIR, { requireExists: false });
92
+ if (explicit) return explicit;
93
+ }
94
+ const packageJson = readJson(path.join(normalizedHostDir, "package.json"));
95
+ if (typeof packageJson?.soma?.webRoot === "string" && packageJson.soma.webRoot.trim()) {
96
+ const explicit = resolveExplicitHostPath(normalizedHostDir, packageJson.soma.webRoot, { requireExists: true });
97
+ if (explicit) return explicit;
98
+ }
71
99
  return resolveSafeChildRoot(normalizedHostDir, packageJson?.soma?.hostRoot);
72
100
  }
73
101
 
102
+ function getSomaHostApiRoot(hostDir, env = process.env) {
103
+ const normalizedHostDir = path.resolve(hostDir);
104
+ if (env && typeof env.SOMA_API_DIR === "string" && env.SOMA_API_DIR.trim()) {
105
+ const explicit = resolveExplicitHostPath(normalizedHostDir, env.SOMA_API_DIR, { requireExists: false });
106
+ if (explicit) return explicit;
107
+ }
108
+ const packageJson = readJson(path.join(normalizedHostDir, "package.json"));
109
+ const candidate = typeof packageJson?.soma?.apiRoot === "string" && packageJson.soma.apiRoot.trim()
110
+ ? packageJson.soma.apiRoot
111
+ : (typeof packageJson?.soma?.serviceRoot === "string" && packageJson.soma.serviceRoot.trim() ? packageJson.soma.serviceRoot : null);
112
+ if (candidate) {
113
+ const explicit = resolveExplicitHostPath(normalizedHostDir, candidate, { requireExists: true });
114
+ if (explicit) return explicit;
115
+ }
116
+ return getSomaHostSourceRoot(normalizedHostDir, env);
117
+ }
118
+
74
119
  /** 源包判定:显式声明(环境变量)或 `package.json` 的 `soma.source === true` */
75
120
  function isSomaSourcePackage(packageRoot, explicit) {
76
121
  if (explicit) return true;
77
- const packageJson = readJson(path.join(packageRoot, 'package.json'));
122
+ const packageJson = readJson(path.join(packageRoot, "package.json"));
78
123
  return packageJson?.soma?.source === true;
79
124
  }
80
125
 
81
126
  function toPackageSource(packageName, packageRoot) {
82
- const packageJson = readJson(path.join(packageRoot, 'package.json'));
127
+ const packageJson = readJson(path.join(packageRoot, "package.json"));
83
128
  const codeRoot = resolveSafeChildRoot(packageRoot, packageJson?.soma?.hostRoot);
84
129
  const configRoot = resolveSafeChildRoot(packageRoot, packageJson?.soma?.configRoot);
130
+ const hasRootApiService = fs.existsSync(path.join(packageRoot, "api", "service"));
131
+ const apiRoot = hasRootApiService ? packageRoot : codeRoot;
85
132
  return {
86
- type: 'package',
133
+ type: "package",
87
134
  name: packageName,
88
135
  packageName,
89
136
  assetRoot: codeRoot,
90
137
  codeRoot,
138
+ apiRoot,
91
139
  configRoot,
92
140
  };
93
141
  }
@@ -96,17 +144,29 @@ function toPackageSource(packageName, packageRoot) {
96
144
  /** @param {SomaEnv} [env] */
97
145
  function getSomaAssetSources(hostDir, env = process.env) {
98
146
  const normalizedHostDir = path.resolve(hostDir);
99
- const hostSourceRoot = getSomaHostSourceRoot(normalizedHostDir);
147
+
148
+ const pkgStat = fs.statSync(path.join(normalizedHostDir, "package.json"), { throwIfNoEntry: false });
149
+ const pkgStatKey = pkgStat ? `${pkgStat.mtimeMs}:${pkgStat.size}` : "none";
150
+ const cacheKey = `${normalizedHostDir}\0${env?.[SOMA_SOURCE_PACKAGES_ENV] ?? ""}\0${env?.SOMA_WEB_DIR ?? ""}\0${env?.SOMA_API_DIR ?? ""}\0${pkgStatKey}`;
151
+
152
+ const cached = assetSourcesCache.get(cacheKey);
153
+ if (cached) {
154
+ return cached.slice();
155
+ }
156
+
157
+ const hostSourceRoot = getSomaHostSourceRoot(normalizedHostDir, env);
158
+ const hostApiRoot = getSomaHostApiRoot(normalizedHostDir, env);
100
159
  const dependencies = readHostDependencies(normalizedHostDir);
101
160
  const explicitPackages = new Set(readExplicitSourcePackages(env));
102
161
  const packageNames = new Set([...Object.keys(dependencies), ...explicitPackages]);
103
162
 
104
163
  const sources = [
105
164
  {
106
- type: 'host',
107
- name: 'host',
165
+ type: "host",
166
+ name: "host",
108
167
  assetRoot: hostSourceRoot,
109
168
  codeRoot: hostSourceRoot,
169
+ apiRoot: hostApiRoot,
110
170
  configRoot: getSomaHostConfigRoot(normalizedHostDir),
111
171
  },
112
172
  ];
@@ -116,32 +176,38 @@ function getSomaAssetSources(hostDir, env = process.env) {
116
176
  if (!packageRoot || !isSomaSourcePackage(packageRoot, explicitPackages.has(packageName))) continue;
117
177
  sources.push(toPackageSource(packageName, packageRoot));
118
178
  }
119
- return sources;
179
+
180
+ if (assetSourcesCache.size >= MAX_ASSET_SOURCE_CACHE) {
181
+ assetSourcesCache.delete(assetSourcesCache.keys().next().value);
182
+ }
183
+ assetSourcesCache.set(cacheKey, sources);
184
+
185
+ return sources.slice();
120
186
  }
121
187
 
122
188
  /** 源包名清单(next.config 的 transpilePackages 用) */
123
189
  /** @param {SomaEnv} [env] */
124
190
  function listSomaSourcePackageNames(hostDir, env = process.env) {
125
191
  return getSomaAssetSources(hostDir, env)
126
- .filter((source) => source.type === 'package')
192
+ .filter((source) => source.type === "package")
127
193
  .map((source) => source.packageName);
128
194
  }
129
195
 
130
196
  /** 覆盖顺序:源包在前、Host 在后(同名页面与片段由 Host 覆盖) */
131
197
  function orderSourcesForOverride(sources) {
132
198
  return [
133
- ...sources.filter((source) => source.type === 'package'),
134
- ...sources.filter((source) => source.type === 'host'),
199
+ ...sources.filter((source) => source.type === "package"),
200
+ ...sources.filter((source) => source.type === "host"),
135
201
  ];
136
202
  }
137
203
 
138
- function collectHtmlFiles(dir, prefix = '', acc = []) {
204
+ function collectHtmlFiles(dir, prefix = "", acc = []) {
139
205
  if (!fs.existsSync(dir)) return acc;
140
206
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
141
207
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
142
208
  const full = path.join(dir, entry.name);
143
209
  if (entry.isDirectory()) collectHtmlFiles(full, rel, acc);
144
- else if (entry.name.endsWith('.html')) acc.push(rel);
210
+ else if (entry.name.endsWith(".html")) acc.push(rel);
145
211
  }
146
212
  return acc;
147
213
  }
@@ -150,7 +216,7 @@ function collectHtmlFiles(dir, prefix = '', acc = []) {
150
216
  function collectPageEntries(sources) {
151
217
  const byHtmlFile = new Map();
152
218
  for (const source of orderSourcesForOverride(sources)) {
153
- const htmlRoot = path.join(source.assetRoot, 'html');
219
+ const htmlRoot = path.join(source.assetRoot, "html");
154
220
  for (const htmlFile of collectHtmlFiles(htmlRoot).sort()) {
155
221
  byHtmlFile.set(htmlFile, { source, htmlFile });
156
222
  }
@@ -162,11 +228,11 @@ function collectPageEntries(sources) {
162
228
  function collectIncludes(sources) {
163
229
  const includes = {};
164
230
  for (const source of orderSourcesForOverride(sources)) {
165
- const sharedDir = path.join(source.assetRoot, 'html', 'shared');
231
+ const sharedDir = path.join(source.assetRoot, "html", "shared");
166
232
  if (!fs.existsSync(sharedDir)) continue;
167
233
  for (const entry of fs.readdirSync(sharedDir, { withFileTypes: true })) {
168
- if (!entry.isFile() || !entry.name.endsWith('.html')) continue;
169
- includes[`shared/${entry.name}`] = fs.readFileSync(path.join(sharedDir, entry.name), 'utf8');
234
+ if (!entry.isFile() || !entry.name.endsWith(".html")) continue;
235
+ includes[`shared/${entry.name}`] = fs.readFileSync(path.join(sharedDir, entry.name), "utf8");
170
236
  }
171
237
  }
172
238
  return includes;
@@ -175,6 +241,8 @@ function collectIncludes(sources) {
175
241
  module.exports = {
176
242
  SOMA_SOURCE_PACKAGES_ENV,
177
243
  getSomaHostSourceRoot,
244
+ getSomaHostApiRoot,
245
+ clearSomaAssetSourcesCache,
178
246
  getSomaAssetSources,
179
247
  listSomaSourcePackageNames,
180
248
  orderSourcesForOverride,
@@ -1,10 +1,11 @@
1
- import * as impl from './source-packages.cjs';
1
+ import * as impl from "./source-packages.cjs";
2
2
 
3
3
  export interface SomaAssetSource {
4
- type: 'host' | 'package';
4
+ type: "host" | "package";
5
5
  name: string;
6
6
  assetRoot: string;
7
7
  codeRoot: string;
8
+ apiRoot: string;
8
9
  configRoot: string;
9
10
  packageName?: string;
10
11
  }
@@ -16,11 +17,17 @@ export {
16
17
  resolveAppConfigPath,
17
18
  resolveHostAppConfigPath,
18
19
  resolveHostConfigRoot,
19
- } from './host-config-paths';
20
- export type { SomaEnvName } from './host-config-paths';
20
+ } from "./host-config-paths";
21
+ export type { SomaEnvName } from "./host-config-paths";
21
22
 
22
23
  /** 实现只有 `source-packages.cjs` 一份(RT3 单实现);这里只补类型再导出,不另写第二份。 */
23
- export const getSomaHostSourceRoot: (hostDir: string) => string = impl.getSomaHostSourceRoot;
24
+ export const getSomaHostSourceRoot: (hostDir: string, env?: Readonly<Record<string, string | undefined>>) => string =
25
+ impl.getSomaHostSourceRoot;
26
+
27
+ export const getSomaHostApiRoot: (hostDir: string, env?: Readonly<Record<string, string | undefined>>) => string =
28
+ impl.getSomaHostApiRoot;
29
+
30
+ export const clearSomaAssetSourcesCache: () => void = impl.clearSomaAssetSourcesCache;
24
31
 
25
32
  /** Host 自己 + 全部源包;Host 恒在第一位 */
26
33
  export const getSomaAssetSources: (hostDir: string, env?: Readonly<Record<string, string | undefined>>) => SomaAssetSource[] =