soma-core 2.2.10 → 2.2.11

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 (41) hide show
  1. package/README.md +8 -19
  2. package/bin/service-codegen.cjs +2 -3
  3. package/bin/soma.cjs +2 -2
  4. package/core/build/compiler/soma-precompile.js +13 -4
  5. package/core/client/data/region-scope-port.ts +8 -3
  6. package/core/client/engine/event-engine.ts +1 -1
  7. package/core/client/engine/soma-bootstrap.ts +9 -0
  8. package/core/client/parser/confirm-spec.ts +10 -4
  9. package/core/client/parser/ui-config-parser.ts +14 -2
  10. package/core/index.ts +1 -1
  11. package/core/server/api/load-host-service.ts +0 -1
  12. package/core/shared/registry-generated/diagnostic-registry-index.ts +16 -0
  13. package/core/shared/registry-generated/diagnostic-registry.ts +130 -0
  14. package/core/shared/registry-generated/std-grammar-views.ts +1 -1
  15. package/core/shared/registry-generated/std-grammar.ts +1 -1
  16. package/core/shared/types/region-scope.types.ts +6 -0
  17. package/dist/browser/runtime-bundle.manifest.json +11 -12
  18. package/dist/browser/soma-runtime.js +127 -112
  19. package/dist/core/index.cjs +127 -112
  20. package/dist/host-native/aot-builder.cjs +22 -5
  21. package/dist/host-native/native-server.cjs +122 -54
  22. package/dist/lsp/component-tree.cjs +17 -8
  23. package/dist/types/client/data/region-scope-port.d.ts +1 -1
  24. package/dist/types/client/engine/soma-bootstrap.d.ts +5 -0
  25. package/dist/types/client/parser/confirm-spec.d.ts +1 -1
  26. package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +113 -1
  27. package/dist/types/shared/registry-generated/std-grammar-views.d.ts +1 -1
  28. package/dist/types/shared/registry-generated/std-grammar.d.ts +1 -1
  29. package/dist/types/shared/types/region-scope.types.d.ts +6 -0
  30. package/host-native/bin/host-native.cjs +1 -1
  31. package/host-native/client/browser-entry.ts +12 -1
  32. package/host-native/client/first-frame.ts +8 -0
  33. package/host-native/client/router-bridge.ts +8 -2
  34. package/host-native/src/aot-builder.ts +26 -2
  35. package/host-native/src/native-server.ts +131 -25
  36. package/host-native/src/public-packages.cjs +11 -2
  37. package/host-native/styles/globals.css +28 -2
  38. package/package.json +2 -2
  39. package/dist/core/adaptive-pure.cjs +0 -41
  40. package/dist/core/theme-pure.cjs +0 -38
  41. package/dist/preview-export.cjs +0 -3401
@@ -37,7 +37,7 @@ export interface SomaConfirmContext {
37
37
  export declare function listConfirmPlaceholders(text: string): string[];
38
38
  /** 代入一段确认文案里的占位;`onMissing` 收到每个缺失的占位名(引擎用它记开发期告警) */
39
39
  export declare function substituteConfirmText(text: string, context: SomaConfirmContext, onMissing?: (name: string) => void): string;
40
- /** 把确认规格的 text / impact 代入占位;无花括号时返回原规格(同一引用) */
40
+ /** 把确认规格的 text / impact / phrase 代入占位;无花括号时返回原规格(同一引用)。phrase 缺任一占位值 → 空串(确认钮恒不可用) */
41
41
  export declare function resolveConfirmSpec(spec: SomaConfirmSpec, context: SomaConfirmContext, onMissing?: (name: string) => void): SomaConfirmSpec;
42
42
  /** 开发期告警(按占位名去重;生产构建不输出) */
43
43
  export declare function warnConfirmMissing(name: string, where: string): void;
@@ -13,7 +13,7 @@ export declare const SOMA_PIPELINE_DIAGNOSTIC_REGISTRY: {
13
13
  readonly warn: "none";
14
14
  readonly advice: "none";
15
15
  };
16
- readonly closedFamilies: readonly ["BDL-ALIAS", "CORE", "CT", "ERR-ADAPT", "ERR-AI", "ERR-APP", "ERR-BIZ", "ERR-CAP", "ERR-CAT", "ERR-COMPOSE", "ERR-CONTRACT", "ERR-DSN", "ERR-EXPAND", "ERR-GEN", "ERR-LAYOUT", "ERR-LOCALE", "ERR-PACK", "ERR-PAGE", "ERR-PUB", "ERR-RUN", "ERR-TYPE", "ERR-UNIT", "FND-DEFECT", "FND-GUARD", "FND-INTR", "FND-LAYOUT", "FND-PROOF", "FND-STYLE", "FND-THEME", "OOUI-ART", "OOUI-ASM", "OOUI-SEM", "OOUI-SPA", "THM-CMP", "THM-COORD", "THM-DSL", "THM-MAN", "THM-OUT", "THM-PRESET", "THM-REC", "THM-ROLE", "THM-RULE", "THM-STYLE", "THM-VF"];
16
+ readonly closedFamilies: readonly ["BDL-ALIAS", "CORE", "CT", "ERR-ADAPT", "ERR-AI", "ERR-APP", "ERR-BIZ", "ERR-CAP", "ERR-CAT", "ERR-COMPOSE", "ERR-CONTRACT", "ERR-DSN", "ERR-EXPAND", "ERR-GEN", "ERR-LAYOUT", "ERR-LOCALE", "ERR-PACK", "ERR-PAGE", "ERR-PUB", "ERR-RUN", "ERR-TYPE", "ERR-UNIT", "FND-DEFECT", "FND-GUARD", "FND-INTR", "FND-LAYOUT", "FND-PROOF", "FND-STYLE", "FND-THEME", "KIT-PAGE-GATE", "KIT-THEME-GATE", "OOUI-ART", "OOUI-ASM", "OOUI-SEM", "OOUI-SPA", "THM-CMP", "THM-COORD", "THM-DSL", "THM-MAN", "THM-OUT", "THM-PRESET", "THM-REC", "THM-ROLE", "THM-RULE", "THM-STYLE", "THM-VF"];
17
17
  readonly codes: readonly [{
18
18
  readonly code: "BDL-ALIAS-COMPAT";
19
19
  readonly family: "BDL-ALIAS";
@@ -3729,6 +3729,118 @@ export declare const SOMA_PIPELINE_DIAGNOSTIC_REGISTRY: {
3729
3729
  readonly stage: "foundation";
3730
3730
  readonly severity: "error";
3731
3731
  readonly owner: "soma-foundation/src/primitives/diag.ts";
3732
+ }, {
3733
+ readonly code: "KIT-PAGE-GATE-001";
3734
+ readonly family: "KIT-PAGE-GATE";
3735
+ readonly stage: "page";
3736
+ readonly severity: "error";
3737
+ readonly owner: "soma-kit/src/spatial/emit.ts";
3738
+ readonly negative: "soma-kit/tests/spatial/emit-gates.test.ts";
3739
+ }, {
3740
+ readonly code: "KIT-PAGE-GATE-002";
3741
+ readonly family: "KIT-PAGE-GATE";
3742
+ readonly stage: "page";
3743
+ readonly severity: "error";
3744
+ readonly owner: "soma-kit/src/spatial/emit.ts";
3745
+ readonly negative: "soma-kit/tests/spatial/emit-gates.test.ts";
3746
+ }, {
3747
+ readonly code: "KIT-PAGE-GATE-003";
3748
+ readonly family: "KIT-PAGE-GATE";
3749
+ readonly stage: "page";
3750
+ readonly severity: "error";
3751
+ readonly owner: "soma-kit/src/spatial/emit.ts";
3752
+ readonly negative: "soma-kit/tests/spatial/emit-gates.test.ts";
3753
+ }, {
3754
+ readonly code: "KIT-PAGE-GATE-004";
3755
+ readonly family: "KIT-PAGE-GATE";
3756
+ readonly stage: "page";
3757
+ readonly severity: "error";
3758
+ readonly owner: "soma-kit/src/spatial/emit.ts";
3759
+ readonly negative: "soma-kit/tests/spatial/emit-gates.test.ts";
3760
+ }, {
3761
+ readonly code: "KIT-PAGE-GATE-005";
3762
+ readonly family: "KIT-PAGE-GATE";
3763
+ readonly stage: "page";
3764
+ readonly severity: "error";
3765
+ readonly owner: "soma-kit/src/spatial/emit.ts";
3766
+ readonly negative: "soma-kit/tests/spatial/emit-gates.test.ts";
3767
+ }, {
3768
+ readonly code: "KIT-PAGE-GATE-006";
3769
+ readonly family: "KIT-PAGE-GATE";
3770
+ readonly stage: "page";
3771
+ readonly severity: "warn";
3772
+ readonly owner: "soma-kit/src/spatial/emit.ts";
3773
+ readonly negative: "soma-kit/tests/spatial/emit-gates.test.ts";
3774
+ }, {
3775
+ readonly code: "KIT-PAGE-GATE-900";
3776
+ readonly family: "KIT-PAGE-GATE";
3777
+ readonly stage: "page";
3778
+ readonly severity: "warn";
3779
+ readonly owner: "soma-kit/src/compile/page-pipeline.ts";
3780
+ readonly negative: "soma-kit/tests/compile/page-pipeline-wiring.test.ts";
3781
+ }, {
3782
+ readonly code: "KIT-PAGE-GATE-901";
3783
+ readonly family: "KIT-PAGE-GATE";
3784
+ readonly stage: "page";
3785
+ readonly severity: "error";
3786
+ readonly owner: "soma-kit/src/compile/compile-page.ts";
3787
+ readonly negative: "soma-kit/tests/compile/page-pipeline-wiring.test.ts";
3788
+ }, {
3789
+ readonly code: "KIT-THEME-GATE-001";
3790
+ readonly family: "KIT-THEME-GATE";
3791
+ readonly stage: "theme";
3792
+ readonly severity: "error";
3793
+ readonly owner: "soma-kit/src/theme/value-table.ts";
3794
+ readonly negative: "soma-kit/tests/theme/value-table.test.ts";
3795
+ }, {
3796
+ readonly code: "KIT-THEME-GATE-002";
3797
+ readonly family: "KIT-THEME-GATE";
3798
+ readonly stage: "theme";
3799
+ readonly severity: "error";
3800
+ readonly owner: "soma-kit/src/theme/value-table.ts";
3801
+ readonly negative: "soma-kit/tests/theme/value-table.test.ts";
3802
+ }, {
3803
+ readonly code: "KIT-THEME-GATE-003";
3804
+ readonly family: "KIT-THEME-GATE";
3805
+ readonly stage: "theme";
3806
+ readonly severity: "warn";
3807
+ readonly owner: "soma-kit/src/theme/value-table.ts";
3808
+ readonly negative: "soma-kit/tests/theme/value-table.test.ts";
3809
+ }, {
3810
+ readonly code: "KIT-THEME-GATE-010";
3811
+ readonly family: "KIT-THEME-GATE";
3812
+ readonly stage: "theme";
3813
+ readonly severity: "error";
3814
+ readonly owner: "soma-kit/src/app/tier-compat.ts";
3815
+ readonly negative: "soma-kit/tests/app/tier-compat.test.ts";
3816
+ }, {
3817
+ readonly code: "KIT-THEME-GATE-011";
3818
+ readonly family: "KIT-THEME-GATE";
3819
+ readonly stage: "theme";
3820
+ readonly severity: "warn";
3821
+ readonly owner: "soma-kit/src/app/tier-compat.ts";
3822
+ readonly negative: "soma-kit/tests/app/tier-compat.test.ts";
3823
+ }, {
3824
+ readonly code: "KIT-THEME-GATE-012";
3825
+ readonly family: "KIT-THEME-GATE";
3826
+ readonly stage: "theme";
3827
+ readonly severity: "warn";
3828
+ readonly owner: "soma-kit/src/app/server.ts";
3829
+ readonly negative: "soma-kit/tests/app/tier-compat.test.ts";
3830
+ }, {
3831
+ readonly code: "KIT-THEME-GATE-013";
3832
+ readonly family: "KIT-THEME-GATE";
3833
+ readonly stage: "theme";
3834
+ readonly severity: "warn";
3835
+ readonly owner: "soma-kit/src/app/tier-compat.ts";
3836
+ readonly negative: "soma-kit/tests/app/tier-compat.test.ts";
3837
+ }, {
3838
+ readonly code: "KIT-THEME-GATE-014";
3839
+ readonly family: "KIT-THEME-GATE";
3840
+ readonly stage: "theme";
3841
+ readonly severity: "warn";
3842
+ readonly owner: "soma-kit/src/theme/value-table.ts";
3843
+ readonly negative: "soma-kit/tests/theme/value-table.test.ts";
3732
3844
  }, {
3733
3845
  readonly code: "OOUI-ART-ANCHOR-DUPLICATE";
3734
3846
  readonly family: "OOUI-ART";
@@ -270,7 +270,7 @@ export declare const SOMA_STD_PAGE_FORBIDDEN_LOGIC_KEYS: {
270
270
  };
271
271
  };
272
272
  readonly exemptContexts: readonly ["diagnostics", "diagnosticExamples", "rejected", "title", "basis", "was", "summary", "docSummary"];
273
- readonly exampleRoots: readonly ["soma-kit-demo/pages", "soma-kit/examples", "soma-ui/tests/fixtures/hosts", "soma-core-demo/ui", "soma-core-demo/pages"];
273
+ readonly exampleRoots: readonly ["soma-kit-demo/pages", "soma-kit/examples", "soma-ui/tests/fixtures/hosts"];
274
274
  readonly exampleFilePatterns: readonly ["_ui.yaml", ".kit.yaml", "_style.yaml"];
275
275
  readonly exampleSkipDirs: readonly ["node_modules", "negative", "__negative__"];
276
276
  readonly note: "forbiddenShape: 'object' = 只禁对象 / 列表形,值为字符串(纯路径绑定)放行;scope: 'standard' = 只在 core 标准格式(四件套 / 注入口)判定,不进 G83 的跨方言语法源与示例页扫描(方言同名键含义不同,如 steps 页面模式)";
@@ -3302,7 +3302,7 @@ export declare const SOMA_PIPELINE_STD_GRAMMAR: {
3302
3302
  };
3303
3303
  };
3304
3304
  readonly exemptContexts: readonly ["diagnostics", "diagnosticExamples", "rejected", "title", "basis", "was", "summary", "docSummary"];
3305
- readonly exampleRoots: readonly ["soma-kit-demo/pages", "soma-kit/examples", "soma-ui/tests/fixtures/hosts", "soma-core-demo/ui", "soma-core-demo/pages"];
3305
+ readonly exampleRoots: readonly ["soma-kit-demo/pages", "soma-kit/examples", "soma-ui/tests/fixtures/hosts"];
3306
3306
  readonly exampleFilePatterns: readonly ["_ui.yaml", ".kit.yaml", "_style.yaml"];
3307
3307
  readonly exampleSkipDirs: readonly ["node_modules", "negative", "__negative__"];
3308
3308
  readonly note: "forbiddenShape: 'object' = 只禁对象 / 列表形,值为字符串(纯路径绑定)放行;scope: 'standard' = 只在 core 标准格式(四件套 / 注入口)判定,不进 G83 的跨方言语法源与示例页扫描(方言同名键含义不同,如 steps 页面模式)";
@@ -66,6 +66,12 @@ export interface SomaScopeSliceDecl {
66
66
  readonly readers?: readonly string[];
67
67
  /** 带 ready 位:初值未就绪,owner 调 `markReady()` 置位 */
68
68
  readonly ready?: boolean;
69
+ /**
70
+ * 切片初值(纯 JSON 值):装入与重置(`reset`)时切片取它的副本而不是空;不写 = 空(读作 undefined)。
71
+ * 用途:读接口参数经镜像绑切片子路径时,首个请求就带上初值(例:列表视图切片 `{ page: 1, size: <每页缺省> }`),
72
+ * 不必等 owner 第一次写入后再重取。初值不经写权核对(它是声明的一部分,不是某个部件的写入)。
73
+ */
74
+ readonly initial?: unknown;
69
75
  }
70
76
  /**
71
77
  * 切片镜像:把切片值(或其子路径的值)镜像进页面状态,供宿主片段里的 `ui.show` prop 绑定读取。
@@ -199,7 +199,7 @@ async function run() {
199
199
  const { url, port: actualPort } = await instance.start();
200
200
  // 只警告不退出:纯四件套原生工程没有 soma.app.ts 是合法的。装配代码只认文件名 soma.app.ts(应用根或源码根下,见 host-assembly.ts)。
201
201
  if (![hostDir, webRoot].some((dir) => fs.existsSync(path.join(dir, 'soma.app.ts')))) {
202
- console.warn(`[soma-native] 未找到 soma.app.ts,当前目录:${hostDir};若这是 soma-kit / 应用工程,请确认在工程根目录运行`);
202
+ console.warn(`[soma-native] 未找到 soma.app.ts,当前目录:${hostDir};若这是应用工程,请确认在工程根目录运行`);
203
203
  }
204
204
  const modeText = isDev ? '开发态 (增量热更新)' : '生产态 (极速 AOT)';
205
205
 
@@ -1,5 +1,6 @@
1
1
  // 纯原生 DOM 极速客户端入口:零 React,零 Next,体积小、性能快
2
2
  import { PageAccessError, readPageAccessError, loginRedirectTarget } from './page-access';
3
+ import { declaresLoadingState } from './first-frame';
3
4
  import {
4
5
  createBrowserNavigate,
5
6
  pendingNavigateInfo,
@@ -149,6 +150,8 @@ class NativePageClient {
149
150
  private containerEl: HTMLElement;
150
151
  private statusEl: HTMLElement;
151
152
  private navigate: SomaShellNavigate;
153
+ /** 最近一次渲染(或开始渲染)的页面地址:pathname + search + hash;popstate 落到同一地址时不重渲染 */
154
+ private renderedUrl = '';
152
155
 
153
156
  constructor(appRoot: HTMLElement) {
154
157
  this.appRoot = appRoot;
@@ -190,9 +193,10 @@ class NativePageClient {
190
193
  void this.renderPage(url);
191
194
  });
192
195
 
196
+ // 同一地址的历史项(页面内组件压的浏览状态)不重渲染页面:只有地址变了才是换页
193
197
  setupPopstateListener((url) => {
194
198
  void this.renderPage(url);
195
- });
199
+ }, () => this.renderedUrl);
196
200
 
197
201
  this.setupDevHmr();
198
202
  }
@@ -281,6 +285,7 @@ class NativePageClient {
281
285
  const runId = ++this.currentRunId;
282
286
 
283
287
  const parsed = new URL(targetUrl, window.location.href);
288
+ this.renderedUrl = parsed.pathname + parsed.search + parsed.hash;
284
289
  const pagePath = parsed.pathname;
285
290
  const routerPath = parsed.search ? `${pagePath}${parsed.search}` : pagePath;
286
291
 
@@ -461,6 +466,12 @@ class NativePageClient {
461
466
  ...assets,
462
467
  });
463
468
 
469
+ // 首帧:首轮渲染画出了页面自己声明的加载态(aria-busy,如骨架)就先显示容器,不等数据落定;
470
+ // 没声明加载态的页面仍在落定后才显示(判据见 first-frame.ts)。
471
+ await bs.whenRendered();
472
+ if (runId !== this.currentRunId) return;
473
+ if (declaresLoadingState(this.containerEl)) this.showContainer();
474
+
464
475
  await bs.whenSettled();
465
476
  if (runId !== this.currentRunId) return;
466
477
 
@@ -0,0 +1,8 @@
1
+ // 首帧显示判据(与方言无关):首轮渲染后,页面在容器里自己声明了加载态——标准 ARIA `aria-busy="true"`
2
+ // (骨架、加载面板等)——宿主就不等数据落定、先显示容器,让页头与骨架先被看见;数据到位仍走原来的落定流程。
3
+ // 没有声明加载态的页面(如未写加载态的原生四件套页)保持原行为:数据落定后再显示,不闪未就绪内容。
4
+
5
+ /** 容器内是否有元素声明「正在加载」(aria-busy="true")。 */
6
+ export function declaresLoadingState(container: ParentNode): boolean {
7
+ return container.querySelector('[aria-busy="true"]') !== null;
8
+ }
@@ -104,12 +104,18 @@ export function setupLinkInterceptor(navigate: SomaShellNavigate): () => void {
104
104
  };
105
105
  }
106
106
 
107
- /** 监听浏览器前进后退事件并触发路由回调 */
108
- export function setupPopstateListener(onPop: (url: string) => void): () => void {
107
+ /**
108
+ * 监听浏览器前进后退事件并触发路由回调。
109
+ * renderedUrl 给出当前已渲染页面的地址(pathname + search + hash):后退 / 前进落到同一地址时不是换页,
110
+ * 而是页面里的组件自己压的浏览历史项(例如整页表单视图「浏览器后退 = 取消」),交给压它的组件处理,壳不重渲染页面
111
+ * (重渲染会卸掉整页、丢掉未保存的编辑)。
112
+ */
113
+ export function setupPopstateListener(onPop: (url: string) => void, renderedUrl?: () => string): () => void {
109
114
  if (typeof window === 'undefined') return () => undefined;
110
115
 
111
116
  const handlePopstate = () => {
112
117
  const current = window.location.pathname + window.location.search + window.location.hash;
118
+ if (renderedUrl !== undefined && renderedUrl() === current) return;
113
119
  onPop(current);
114
120
  };
115
121
 
@@ -39,9 +39,27 @@ export interface BrowserClientBuildResult {
39
39
  readonly cssUrl: string;
40
40
  readonly cssText: string;
41
41
  rebuild(): Promise<void>;
42
+ /**
43
+ * 开发态:这批改动(绝对路径)会不会改变客户端包(clientBuildAffectedBy)。缺省(生产清单、首轮构建前)视为会。
44
+ * 宿主刷新队列据此跳过只改页面资产(html / yaml 等,不进客户端包)时的整包重建。
45
+ */
46
+ affectedBy?(changedFiles: readonly string[]): boolean;
42
47
  dispose(): Promise<void>;
43
48
  }
44
49
 
50
+ /** esbuild 能当模块加载的扩展名:新增 / 删除这类文件可能改变插件的解析结果(bootstrap、domain/ui/*Class.ts、@soma-host/* 的存在性判断),即使它还不在上次的输入里 */
51
+ const CLIENT_MODULE_EXT = /\.(?:[cm]?[jt]sx?|json|css)$/i;
52
+
53
+ /**
54
+ * 开发态按需重建的判据(纯函数):inputs = 上次构建 metafile 的输入(绝对路径;null = 还不知道)。
55
+ * 改动里有任一文件是上次的输入、或是可当模块加载的扩展名 → 需要重建;改动集为空(来源不明)也重建。
56
+ * 只改页面资产(四件套 html / yaml、kit 页面 yaml、文档、图片)且它们不在输入里 → 不重建:页面由预热与 Registry 出,客户端包不变。
57
+ */
58
+ export function clientBuildAffectedBy(inputs: ReadonlySet<string> | null, changedFiles: readonly string[]): boolean {
59
+ if (inputs === null || changedFiles.length === 0) return true;
60
+ return changedFiles.some((file) => inputs.has(path.resolve(file)) || CLIENT_MODULE_EXT.test(file));
61
+ }
62
+
45
63
  export interface BuildServerAotOptions {
46
64
  readonly hostDir: string;
47
65
  readonly webRoot?: string;
@@ -320,11 +338,16 @@ export async function buildBrowserClient(
320
338
  let ctx: BuildContext | null = null;
321
339
  let entryUrl = '/_soma/client/browser-entry.js';
322
340
 
323
- // 开发态每次构建后按进程登记回收旧分片(dev-chunk-gc.ts):旧实现从不清理,chunks/ 会无限增长
341
+ // 开发态每次构建后按进程登记回收旧分片(dev-chunk-gc.ts):旧实现从不清理,chunks/ 会无限增长;
342
+ // 同一份 metafile 的输入集记下来,供按需重建判据(clientBuildAffectedBy)用
343
+ let devInputs: Set<string> | null = null;
324
344
  const devRebuild = async (): Promise<void> => {
325
345
  if (!ctx) return;
326
346
  const result = await ctx.rebuild();
327
- if (result.metafile) collectDevChunks(clientOutDir, outputsRelativeTo(clientOutDir, Object.keys(result.metafile.outputs)));
347
+ if (result.metafile) {
348
+ collectDevChunks(clientOutDir, outputsRelativeTo(clientOutDir, Object.keys(result.metafile.outputs)));
349
+ devInputs = new Set(Object.keys(result.metafile.inputs).map((file) => path.resolve(file)));
350
+ }
328
351
  };
329
352
 
330
353
  if (options.dev) {
@@ -366,6 +389,7 @@ export async function buildBrowserClient(
366
389
  rebuild: async () => {
367
390
  await devRebuild();
368
391
  },
392
+ affectedBy: (changedFiles) => clientBuildAffectedBy(devInputs, changedFiles),
369
393
  dispose: async () => {
370
394
  if (ctx) {
371
395
  await ctx.dispose();
@@ -527,12 +527,17 @@ async function sendEarlyResponseAndClose(
527
527
  await sendWebResponse(webRes, res, method);
528
528
  }
529
529
 
530
- /** 装配可选字段 `documentHead` 的形状:静态片段,或按请求上下文(CSP nonce)生成片段的函数 */
530
+ /**
531
+ * 装配可选字段 `documentHead` 的形状:静态片段,或按请求上下文(CSP nonce)生成片段的函数。
532
+ * 契约:`documentHead` 函数须为无副作用纯函数,相同输入返回稳定字符串以便命中静态壳缓存;
533
+ * 启动期与开发态重载期会以 `{}` 预求值一次,返回非字符串或抛错时立即快失败。
534
+ */
531
535
  export type DocumentHeadSource = string | ((ctx: { readonly nonce?: string }) => string);
532
536
 
533
537
  /**
534
538
  * 按形状从已加载的 Host 装配读取可选 `documentHead`(类型契约之外的方言中性扩展口)。
535
539
  * 无装配或未写该字段 → undefined;写了但不是字符串 / 函数 → 当场抛错,避免静默吞掉装配错误。
540
+ * `documentHead` 函数须为无副作用纯函数,相同输入返回稳定字符串以便命中静态壳缓存。
536
541
  */
537
542
  export function readDocumentHeadSource(assembly: unknown): DocumentHeadSource | undefined {
538
543
  if (assembly === null || typeof assembly !== 'object') return undefined;
@@ -542,16 +547,98 @@ export function readDocumentHeadSource(assembly: unknown): DocumentHeadSource |
542
547
  throw new Error('soma.app.ts 的 Host 装配的 documentHead 必须是字符串或返回字符串的函数');
543
548
  }
544
549
 
545
- /** 求出要插入 `<head>` 的片段:原样插入(片段自身负责转义与 nonce),末尾补换行缩进;无片段返回空串 */
546
- export function renderDocumentHead(source: DocumentHeadSource | undefined, nonce: string | undefined): string {
550
+ function evalDocumentHeadSnippet(source: DocumentHeadSource | undefined, nonce: string | undefined): string {
547
551
  if (source === undefined) return '';
548
552
  const snippet = typeof source === 'function' ? source(nonce === undefined ? {} : { nonce }) : source;
549
553
  if (typeof snippet !== 'string') {
550
554
  throw new Error('soma.app.ts 的 Host 装配的 documentHead() 必须返回字符串');
551
555
  }
556
+ return snippet;
557
+ }
558
+
559
+ /** 求出要插入 `<head>` 的片段:原样插入(片段自身负责转义与 nonce),末尾补换行缩进;无片段返回空串 */
560
+ export function renderDocumentHead(source: DocumentHeadSource | undefined, nonce: string | undefined): string {
561
+ const snippet = evalDocumentHeadSnippet(source, nonce);
552
562
  return snippet === '' ? '' : `${snippet}\n `;
553
563
  }
554
564
 
565
+ export interface StaticShellInputs {
566
+ readonly title: string;
567
+ readonly entryUrl: string;
568
+ readonly cssText: string;
569
+ readonly dev: boolean;
570
+ readonly documentHeadSource: DocumentHeadSource | undefined;
571
+ }
572
+
573
+ export interface StaticShellCacheEntry {
574
+ readonly head: string;
575
+ readonly title: string;
576
+ readonly entryUrl: string;
577
+ readonly cssText: string;
578
+ readonly dev: boolean;
579
+ readonly html: string;
580
+ readonly utf8: Buffer;
581
+ readonly gzip: Buffer;
582
+ }
583
+
584
+ export interface StaticShellCache {
585
+ get(inputs: StaticShellInputs): StaticShellCacheEntry;
586
+ clear(): void;
587
+ }
588
+
589
+ const LAYER_ORDER_STYLE_RE = /<style\b[^>]*\bdata-soma-kit-layer-order\b[^>]*>[\s\S]*?<\/style>/gi;
590
+
591
+ /** V4-L1-6:将 documentHead 中携带 data-soma-kit-layer-order 的首行层序声明提前至 <style>${cssText}</style> 之前,确保 CSSOM 全局层序在任何样式表之前生效;其余脚本/样式仍留原位 */
592
+ export function splitLayerOrderHead(head: string): { readonly layerOrder: string; readonly rest: string } {
593
+ if (!head.includes('data-soma-kit-layer-order')) return { layerOrder: '', rest: head };
594
+ const extracted: string[] = [];
595
+ const rest = head
596
+ .replace(LAYER_ORDER_STYLE_RE, (m) => {
597
+ extracted.push(m.trim());
598
+ return '';
599
+ })
600
+ .replace(/\n{2,}/g, '\n')
601
+ .trim();
602
+ return { layerOrder: extracted.join('\n '), rest };
603
+ }
604
+
605
+ /**
606
+ * 预构建静态 HTML 外壳缓冲缓存(仅用于无 CSP 场景;CSP 开启时每次必须按请求 nonce 新鲜生成)。
607
+ * 每次读取都会实时求值 `documentHead` 片段,并与全部注入外壳的字段逐项比对:
608
+ * 全部一致时零重建、零压缩直接复用缓存;任一项变化时立即重建并刷新缓存。
609
+ */
610
+ export function createStaticShellCache(): StaticShellCache {
611
+ let cachedStaticShell: StaticShellCacheEntry | null = null;
612
+ return {
613
+ get(inputs: StaticShellInputs): StaticShellCacheEntry {
614
+ const { title, entryUrl, cssText, dev, documentHeadSource } = inputs;
615
+ const head = evalDocumentHeadSnippet(documentHeadSource, undefined);
616
+ if (
617
+ cachedStaticShell !== null
618
+ && cachedStaticShell.head === head
619
+ && cachedStaticShell.title === title
620
+ && cachedStaticShell.entryUrl === entryUrl
621
+ && cachedStaticShell.cssText === cssText
622
+ && cachedStaticShell.dev === dev
623
+ ) {
624
+ return cachedStaticShell;
625
+ }
626
+ const { layerOrder, rest } = splitLayerOrderHead(head);
627
+ const layerOrderHead = layerOrder === '' ? '' : `${layerOrder}\n `;
628
+ const devSse = dev ? '<script>window.__SOMA_DEV_SSE__ = true;</script>\n ' : '';
629
+ const extraHead = rest === '' ? '' : `${rest}\n `;
630
+ const html = `<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>${escapeHtml(title)}</title>\n ${layerOrderHead}<style>${cssText}</style>\n <script>\n try {\n const theme = localStorage.getItem('soma-theme');\n if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {\n document.documentElement.setAttribute('data-theme', 'dark');\n }\n } catch (_) {}\n </script>\n ${extraHead}${devSse}</head>\n<body>\n <div id="soma-app-root">\n <div class="soma-hydration-shell">\n <div class="soma-hydration-shell__bar"></div>\n </div>\n </div>\n <script type="module" src="${entryUrl}"></script>\n</body>\n</html>`;
631
+ const utf8 = Buffer.from(html, 'utf8');
632
+ const gzip = zlib.gzipSync(utf8);
633
+ cachedStaticShell = { head, title, entryUrl, cssText, dev, html, utf8, gzip };
634
+ return cachedStaticShell;
635
+ },
636
+ clear(): void {
637
+ cachedStaticShell = null;
638
+ },
639
+ };
640
+ }
641
+
555
642
  export async function createNativeServer(
556
643
  options: CreateNativeServerOptions,
557
644
  ): Promise<NativeServerInstance> {
@@ -576,8 +663,9 @@ export async function createNativeServer(
576
663
  installAotManifest(aotManifestPath, hostDir);
577
664
 
578
665
  await runHostStartup(hostDir);
579
- // 装配的可选文档头片段(方言中性):按形状读取,插到外壳 <head> 末尾
666
+ // 装配的可选文档头片段(方言中性):按形状读取并做启动期快失败预求值,插到外壳 <head> 末尾
580
667
  let documentHeadSource = readDocumentHeadSource(await loadHostAssembly(hostDir));
668
+ evalDocumentHeadSnippet(documentHeadSource, undefined);
581
669
 
582
670
  // 2. 准备客户端产物(生产态优先直接读取预编译清单,零 esbuild 驻留)
583
671
  const clientManifestPath = path.join(runtimeLayout.dirs.static, 'client', 'client-manifest.json');
@@ -606,18 +694,19 @@ export async function createNativeServer(
606
694
  });
607
695
  }
608
696
 
609
- // 预构建静态 HTML 外壳缓冲(CSP 关闭时零字符串拼接、零实时压缩直出)
610
- let cachedStaticShell: { key: string; utf8: Buffer; gzip: Buffer } | null = null;
611
- function getStaticShellBuffers(titleText: string): { utf8: Buffer; gzip: Buffer } {
612
- const key = `${titleText}\0${clientBuild.entryUrl}\0${clientBuild.cssText.length}\0${dev ? '1' : '0'}`;
613
- if (cachedStaticShell && cachedStaticShell.key === key) return cachedStaticShell;
614
- const devSse = dev ? '<script>window.__SOMA_DEV_SSE__ = true;</script>\n ' : '';
615
- const extraHead = renderDocumentHead(documentHeadSource, undefined);
616
- const html = `<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>${escapeHtml(titleText)}</title>\n <style>${clientBuild.cssText}</style>\n <script>\n try {\n const theme = localStorage.getItem('soma-theme');\n if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {\n document.documentElement.setAttribute('data-theme', 'dark');\n }\n } catch (_) {}\n </script>\n ${extraHead}${devSse}</head>\n<body>\n <div id="soma-app-root">\n <div class="soma-hydration-shell">\n <div class="soma-hydration-shell__bar"></div>\n </div>\n </div>\n <script type="module" src="${clientBuild.entryUrl}"></script>\n</body>\n</html>`;
617
- const utf8 = Buffer.from(html, 'utf8');
618
- const gzip = zlib.gzipSync(utf8);
619
- cachedStaticShell = { key, utf8, gzip };
620
- return cachedStaticShell;
697
+ // 预构建静态 HTML 外壳缓冲(CSP 关闭时零字符串拼接、零实时压缩直出;每次校验 documentHead 与全部外壳输入)
698
+ const staticShellCache = createStaticShellCache();
699
+ function getStaticShellBuffers(
700
+ titleText: string,
701
+ headSource: DocumentHeadSource | undefined = documentHeadSource,
702
+ ): StaticShellCacheEntry {
703
+ return staticShellCache.get({
704
+ title: titleText,
705
+ entryUrl: clientBuild.entryUrl,
706
+ cssText: clientBuild.cssText,
707
+ dev,
708
+ documentHeadSource: headSource,
709
+ });
621
710
  }
622
711
 
623
712
  // 3. SSE 热更新客户端集合
@@ -651,6 +740,8 @@ export async function createNativeServer(
651
740
  let debounceTimer: NodeJS.Timeout | null = null;
652
741
  let refreshPending = false;
653
742
  let refreshNeedsTailwindClear = false;
743
+ /** 自上一轮成功刷新以来改过的文件(绝对路径):决定这一轮要不要重建客户端包(clientBuild.affectedBy);本轮失败时并回下一轮 */
744
+ const refreshChanged = new Set<string>();
654
745
  let refreshTask: Promise<void> | null = null;
655
746
 
656
747
  const drainDevRefreshQueue = (): Promise<void> => {
@@ -659,6 +750,8 @@ export async function createNativeServer(
659
750
  const task = (async () => {
660
751
  while (refreshPending && !watcherClosed) {
661
752
  const clearTailwind = refreshNeedsTailwindClear;
753
+ const changed = [...refreshChanged];
754
+ refreshChanged.clear();
662
755
  refreshPending = false;
663
756
  refreshNeedsTailwindClear = false;
664
757
  try {
@@ -667,13 +760,17 @@ export async function createNativeServer(
667
760
  if (watcherClosed) break;
668
761
  await prewarmHostPages(hostDir, env);
669
762
  if (watcherClosed) break;
670
- documentHeadSource = readDocumentHeadSource(await loadHostAssembly(hostDir));
671
- cachedStaticShell = null;
672
- await clientBuild.rebuild();
763
+ const nextDocumentHeadSource = readDocumentHeadSource(await loadHostAssembly(hostDir));
764
+ evalDocumentHeadSnippet(nextDocumentHeadSource, undefined);
765
+ documentHeadSource = nextDocumentHeadSource;
766
+ staticShellCache.clear();
767
+ // 只改页面资产(不在客户端包输入里的 html / yaml 等)时不重建客户端包:页面由上面的预热出,整包重建只会拖慢 reload
768
+ if (clientBuild.affectedBy?.(changed) !== false) await clientBuild.rebuild();
673
769
  // 有更新排队或仍在 debounce 时不向浏览器发送中间代通知。
674
770
  if (!watcherClosed && !refreshPending && debounceTimer === null) broadcastHmr('reload');
675
771
  } catch (error) {
676
- // 单轮失败只记录本轮;队列仍会继续执行合并后的下一代。
772
+ // 单轮失败只记录本轮;队列仍会继续执行合并后的下一代(本轮的改动并回去,下一轮照样据此判要不要重建)。
773
+ for (const file of changed) refreshChanged.add(file);
677
774
  console.error('[soma-native][dev-rebuild-error]', error);
678
775
  }
679
776
  }
@@ -712,6 +809,7 @@ export async function createNativeServer(
712
809
  if (apiRoot !== webRoot && full.startsWith(apiRoot + path.sep)) return;
713
810
 
714
811
  refreshNeedsTailwindClear ||= /\.(?:css|ya?ml)$/i.test(norm);
812
+ refreshChanged.add(full);
715
813
  if (debounceTimer) clearTimeout(debounceTimer);
716
814
  debounceTimer = setTimeout(() => {
717
815
  debounceTimer = null;
@@ -1073,7 +1171,7 @@ export async function createNativeServer(
1073
1171
  }
1074
1172
  };
1075
1173
 
1076
- await prepareHostAssembly(hostDir);
1174
+ const assembly = await prepareHostAssembly(hostDir);
1077
1175
  // 跑 Host 请求钩子
1078
1176
  const rejected = await invokeHostRequestHook(
1079
1177
  guardHookRequestBody(headerReq, req, dev, warnedHookBodyMembers),
@@ -1140,10 +1238,15 @@ export async function createNativeServer(
1140
1238
  }
1141
1239
 
1142
1240
  applyExtraResHeaders();
1241
+ const currentDocumentHeadSource = readDocumentHeadSource(assembly);
1242
+ if (currentDocumentHeadSource !== documentHeadSource) {
1243
+ evalDocumentHeadSnippet(currentDocumentHeadSource, undefined);
1244
+ documentHeadSource = currentDocumentHeadSource;
1245
+ }
1143
1246
  // 正常 HTML 外壳(CSP 关闭时直接走预压缩内存 Buffer 快速通道)
1144
1247
  const title = readHostAppDisplayName() || 'SOMA';
1145
1248
  if (!csp) {
1146
- const prebuilt = getStaticShellBuffers(title);
1249
+ const prebuilt = getStaticShellBuffers(title, currentDocumentHeadSource);
1147
1250
  res.statusCode = 200;
1148
1251
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
1149
1252
  const ae = req.headers['accept-encoding'];
@@ -1163,7 +1266,10 @@ export async function createNativeServer(
1163
1266
  const devSseScript = dev
1164
1267
  ? `<script${nonceAttr}>window.__SOMA_DEV_SSE__ = true;</script>\n`
1165
1268
  : '';
1166
- const extraHeadSnippet = renderDocumentHead(documentHeadSource, verifiedNonce || undefined);
1269
+ const extraHeadSnippet = renderDocumentHead(currentDocumentHeadSource, verifiedNonce || undefined);
1270
+ const { layerOrder: cspLayerOrder, rest: cspRestHead } = splitLayerOrderHead(extraHeadSnippet);
1271
+ const cspLayerOrderHead = cspLayerOrder === '' ? '' : `${cspLayerOrder}\n `;
1272
+ const cspExtraHead = cspRestHead === '' ? '' : `${cspRestHead}\n `;
1167
1273
 
1168
1274
  const htmlDocument = `<!DOCTYPE html>
1169
1275
  <html lang="en">
@@ -1171,7 +1277,7 @@ export async function createNativeServer(
1171
1277
  <meta charset="utf-8">
1172
1278
  <meta name="viewport" content="width=device-width, initial-scale=1">
1173
1279
  ${cspMeta} <title>${escapeHtml(title)}</title>
1174
- <style${nonceAttr}>${clientBuild.cssText}</style>
1280
+ ${cspLayerOrderHead}<style${nonceAttr}>${clientBuild.cssText}</style>
1175
1281
  <script${nonceAttr}>
1176
1282
  try {
1177
1283
  const theme = localStorage.getItem('soma-theme');
@@ -1180,7 +1286,7 @@ export async function createNativeServer(
1180
1286
  }
1181
1287
  } catch (_) {}
1182
1288
  </script>
1183
- ${extraHeadSnippet}${devSseScript}</head>
1289
+ ${cspExtraHead}${devSseScript}</head>
1184
1290
  <body>
1185
1291
  <div id="soma-app-root">
1186
1292
  <div class="soma-hydration-shell">
@@ -159,8 +159,17 @@ function readAllSomaPublicAliases(hostDir, repoRoot, extraRoots = [], env = proc
159
159
  const shouldIncludePackage = (pkgName, pkgRoot) =>
160
160
  Boolean(pkgName) && (pkgName.startsWith('soma-') || isSomaSourcePackage(pkgRoot, explicitPackages.has(pkgName)));
161
161
 
162
- const registerPackage = (pkgName, pkgRoot) => {
163
- if (!pkgName || seenPackages.has(pkgName) || !fs.existsSync(pkgRoot)) return;
162
+ const registerPackage = (pkgName, linkedRoot) => {
163
+ if (!pkgName || seenPackages.has(pkgName) || !fs.existsSync(linkedRoot)) return;
164
+ // 别名一律落到包的真实路径:esbuild 对插件返回的路径不再做 realpath,若保留软链路径(如宿主
165
+ // node_modules/soma-ai -> ../../soma/soma-ai),包内的三方依赖(如 soma-ai 的 `ai`)会从宿主的
166
+ // node_modules 起找而解析失败,同一个包也会经不同软链路径各装一份(单例分裂)。
167
+ let pkgRoot = linkedRoot;
168
+ try {
169
+ pkgRoot = fs.realpathSync(linkedRoot);
170
+ } catch {
171
+ /* keep linked path */
172
+ }
164
173
  if (!shouldIncludePackage(pkgName, pkgRoot)) return;
165
174
  seenPackages.add(pkgName);
166
175
  Object.assign(aliases, readPublicPackageAliases(pkgName, pkgRoot));