soma-core 1.5.1 → 1.6.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 (131) hide show
  1. package/app/SomaPageClient.tsx +28 -9
  2. package/app/soma/manifest/route.ts +3 -0
  3. package/bin/migrate.cjs +71 -1
  4. package/bin/soma-lsp.cjs +8 -1
  5. package/core/build/blocks/block-compile.ts +23 -5
  6. package/core/build/compiler/full-manifest-builder.ts +15 -0
  7. package/core/build/compiler/page-assets.ts +17 -1
  8. package/core/build/compiler/page-declaration-compiler.ts +67 -11
  9. package/core/build/compiler/precompiled-manifest-loader.ts +7 -0
  10. package/core/build/compiler/soma-manifest-webpack-plugin.js +7 -0
  11. package/core/build/compiler/soma-precompile.js +30 -6
  12. package/core/build/component/package-loader.ts +35 -4
  13. package/core/build/component-tree/artifact-codec.ts +192 -0
  14. package/core/build/component-tree/binding-bridge.ts +272 -0
  15. package/core/build/component-tree/collection-binding-lowerer.ts +65 -0
  16. package/core/build/component-tree/definition-preparation.ts +320 -0
  17. package/core/build/component-tree/migration-files.ts +214 -0
  18. package/core/build/component-tree/migration.ts +170 -0
  19. package/core/build/component-tree/parser.ts +362 -0
  20. package/core/build/component-tree/registry-snapshot.ts +317 -0
  21. package/core/build/component-tree/source-preflight.ts +132 -0
  22. package/core/build/component-tree/structure-topology.ts +63 -0
  23. package/core/build/component-tree/validator.ts +318 -0
  24. package/core/build/lsp/component-tree-service.ts +79 -0
  25. package/core/build/lsp/component-tree.cjs +42 -0
  26. package/core/build/lsp/cross-file-diagnostics.cjs +15 -3
  27. package/core/build/lsp/extra-completion.cjs +7 -0
  28. package/core/client/compiler/manifest-compiler.ts +2 -0
  29. package/core/client/component/ai-catalog.ts +41 -3
  30. package/core/client/component/catalog-examples.ts +60 -0
  31. package/core/client/component/component-definition.types.ts +9 -0
  32. package/core/client/component/component-expander.ts +21 -5
  33. package/core/client/component/component-manager.ts +103 -16
  34. package/core/client/component/component-registry.ts +10 -1
  35. package/core/client/component/scoped-adapter.ts +29 -2
  36. package/core/client/component/structure-adapter.ts +207 -0
  37. package/core/client/component/verify-pack.ts +21 -1
  38. package/core/client/engine/asset-resolver.ts +1 -1
  39. package/core/client/engine/dom-renderer.ts +283 -0
  40. package/core/client/engine/event-engine.ts +28 -9
  41. package/core/client/engine/render-engine.ts +2 -0
  42. package/core/client/engine/row-range.ts +62 -0
  43. package/core/client/engine/row-scope.ts +77 -0
  44. package/core/client/engine/runtime-builder.ts +2 -0
  45. package/core/client/engine/soma-bootstrap.ts +146 -1
  46. package/core/client/parser/blocks/page-parser.ts +9 -2
  47. package/core/client/parser/ui-config-parser.ts +38 -6
  48. package/core/client/registry/declaration-renderer.ts +32 -24
  49. package/core/client/registry/remote-page.ts +1 -1
  50. package/core/client/validation/contract-validator.ts +1 -1
  51. package/core/index.ts +3 -0
  52. package/core/server/host/page-markup-config.ts +42 -0
  53. package/core/server/host/published-page-artifact-cache.ts +36 -4
  54. package/core/server/host/published-page-assets.ts +13 -7
  55. package/core/server/host/resolve-host-tree-context.ts +43 -0
  56. package/core/server/host/server-page-assets.ts +23 -4
  57. package/core/server/host/soma-page-compile.ts +10 -0
  58. package/core/server/page-declaration.ts +7 -0
  59. package/core/server/registry/declaration-precompiler.ts +35 -3
  60. package/core/server/registry/page-registry-repository.ts +31 -3
  61. package/core/server/registry/page-registry-store.ts +64 -7
  62. package/core/server/registry/publish-asset-pin.ts +6 -1
  63. package/core/server/registry/services/pages/Get.ts +11 -6
  64. package/core/server/registry/validation/compile-gate.ts +10 -1
  65. package/core/shared/component-tree-artifact.ts +237 -0
  66. package/core/shared/component-tree-errors.ts +52 -0
  67. package/core/shared/types/component-contract.types.ts +51 -0
  68. package/core/shared/types/component-tree-artifact.types.ts +121 -0
  69. package/core/shared/types/component-tree.types.ts +170 -0
  70. package/core/shared/types/engine.types.ts +5 -0
  71. package/core/shared/types/manifest.types.ts +4 -0
  72. package/core/shared/types/ui-config.types.ts +8 -0
  73. package/dist/cli/soma.js +1 -1
  74. package/dist/core/index.cjs +1757 -511
  75. package/dist/lsp/component-tree.cjs +20807 -0
  76. package/dist/types/build/blocks/block-compile.d.ts +10 -1
  77. package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
  78. package/dist/types/build/compiler/page-assets.d.ts +6 -1
  79. package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
  80. package/dist/types/build/component/package-loader.d.ts +4 -1
  81. package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
  82. package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
  83. package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
  84. package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
  85. package/dist/types/build/component-tree/migration-files.d.ts +35 -0
  86. package/dist/types/build/component-tree/migration.d.ts +28 -0
  87. package/dist/types/build/component-tree/parser.d.ts +13 -0
  88. package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
  89. package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
  90. package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
  91. package/dist/types/build/component-tree/validator.d.ts +9 -0
  92. package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
  93. package/dist/types/client/component/ai-catalog.d.ts +18 -1
  94. package/dist/types/client/component/catalog-examples.d.ts +18 -0
  95. package/dist/types/client/component/component-definition.types.d.ts +9 -0
  96. package/dist/types/client/component/component-expander.d.ts +2 -1
  97. package/dist/types/client/component/component-manager.d.ts +11 -0
  98. package/dist/types/client/component/scoped-adapter.d.ts +1 -0
  99. package/dist/types/client/component/structure-adapter.d.ts +17 -0
  100. package/dist/types/client/engine/dom-renderer.d.ts +15 -0
  101. package/dist/types/client/engine/event-engine.d.ts +1 -0
  102. package/dist/types/client/engine/render-engine.d.ts +1 -0
  103. package/dist/types/client/engine/row-range.d.ts +13 -0
  104. package/dist/types/client/engine/row-scope.d.ts +20 -0
  105. package/dist/types/client/engine/runtime-builder.d.ts +1 -0
  106. package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
  107. package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
  108. package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
  109. package/dist/types/client/registry/remote-page.d.ts +1 -1
  110. package/dist/types/index.d.ts +3 -1
  111. package/dist/types/server/host/page-markup-config.d.ts +6 -0
  112. package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
  113. package/dist/types/server/host/published-page-assets.d.ts +5 -3
  114. package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
  115. package/dist/types/server/host/server-page-assets.d.ts +6 -0
  116. package/dist/types/server/host/soma-page-compile.d.ts +10 -1
  117. package/dist/types/server/page-declaration.d.ts +6 -0
  118. package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
  119. package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
  120. package/dist/types/server/registry/page-registry-store.d.ts +11 -1
  121. package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
  122. package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
  123. package/dist/types/shared/component-tree-artifact.d.ts +5 -0
  124. package/dist/types/shared/component-tree-errors.d.ts +22 -0
  125. package/dist/types/shared/types/component-contract.types.d.ts +42 -0
  126. package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
  127. package/dist/types/shared/types/component-tree.types.d.ts +149 -0
  128. package/dist/types/shared/types/engine.types.d.ts +5 -0
  129. package/dist/types/shared/types/manifest.types.d.ts +4 -0
  130. package/dist/types/shared/types/ui-config.types.d.ts +8 -0
  131. package/package.json +2 -1
@@ -1,5 +1,6 @@
1
1
  import { recordMetric } from '../diagnostics/telemetry-context';
2
2
  import type { IContainerAdapter } from '../container/IContainerAdapter';
3
+ import { SomaRowScope, readRowPath } from './row-scope';
3
4
  import { SOMA_KEY_MODIFIERS } from '../../shared/types/keyboard.types';
4
5
  import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
5
6
  import { SomaMiddlewareChain } from '../middleware/SomaMiddlewareChain';
@@ -75,6 +76,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
75
76
  originalEvent: Event,
76
77
  ) => TContext;
77
78
  private readonly pendingSet = new Set<string>();
79
+ private pendingRows = new WeakSet<HTMLElement>();
78
80
  private readonly abortController = new AbortController();
79
81
 
80
82
  constructor(options: SomaEventEngineOptions<TContext>) {
@@ -139,7 +141,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
139
141
  // 沿 parentElement 向上找锚点对任何 Element 都成立;交给下游仍按 HTMLElement 类型传,
140
142
  // 下游只用 getAttribute / parentElement / tagName / focus / dataset,SVGElement 同样具备。
141
143
  let el: Element | null = start instanceof Element ? start : null;
142
- while (el && el !== this.container) {
144
+ while (el) {
143
145
  const somaId = this.adapter.getAnchorId(el as HTMLElement);
144
146
  if (somaId) {
145
147
  const indexed = this.manifest.eventIndex.get(`${eventType}:${somaId}`);
@@ -150,6 +152,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
150
152
  return { element: el as HTMLElement, config };
151
153
  }
152
154
  }
155
+ if (el === this.container) break;
153
156
  el = el.parentElement;
154
157
  }
155
158
  return null;
@@ -188,6 +191,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
188
191
  destroy(): void {
189
192
  this.abortController.abort();
190
193
  this.pendingSet.clear();
194
+ this.pendingRows = new WeakSet();
191
195
  }
192
196
 
193
197
  private async executeNow(
@@ -196,7 +200,9 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
196
200
  originalEvent: Event,
197
201
  ): Promise<void> {
198
202
  const startedAt = this.adapter.now();
199
- const currentVar = this.getContext(element);
203
+ const rowContext = this.getContext(element);
204
+ if (rowContext instanceof SomaRowScope && !rowContext.active) return;
205
+ const currentVar = rowContext instanceof SomaRowScope ? rowContext.data : rowContext;
200
206
  const context = {
201
207
  config,
202
208
  element,
@@ -208,7 +214,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
208
214
  };
209
215
 
210
216
  const terminal = async (runtime: SomaEventMiddlewareContext & TContext): Promise<void> => {
211
- if (!this.preCheck(config, config.somaId)) {
217
+ if (!this.preCheck(config, config.somaId, element)) {
212
218
  runtime.status = 'blocked';
213
219
  runtime.message = 'pre-check rejected';
214
220
  return;
@@ -262,18 +268,21 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
262
268
  try {
263
269
  if (runsHandler) {
264
270
  try {
265
- this.pendingSet.add(config.somaId);
271
+ if (rowContext instanceof SomaRowScope) this.pendingRows.add(element);
272
+ else this.pendingSet.add(config.somaId);
266
273
  this.callbacks.onSyncModels?.();
267
- const fn = this.resolveFunction(config.funcPath!, currentVar);
274
+ const fn = this.resolveFunction(config.funcPath!, rowContext);
268
275
  // emit 路由:第二实参为契约 payload;DOM 路由保持 originalEvent
269
276
  const handlerArg = isSomaEmitEvent(originalEvent) ? originalEvent.payload : originalEvent;
270
277
  result = await fn(currentVar, handlerArg);
278
+ if (rowContext instanceof SomaRowScope && !rowContext.active) return;
271
279
  } catch (error) {
272
280
  runtime.status = 'error';
273
281
  runtime.message = error instanceof Error ? error.message : String(error);
274
282
  result = false;
275
283
  } finally {
276
- this.pendingSet.delete(config.somaId);
284
+ if (rowContext instanceof SomaRowScope) this.pendingRows.delete(element);
285
+ else this.pendingSet.delete(config.somaId);
277
286
  }
278
287
  }
279
288
 
@@ -341,8 +350,10 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
341
350
  let value: unknown;
342
351
  if (pipeline.funcPath && pipeline.type !== 'NAV_STATIC') {
343
352
  const currentVar = this.getContext(element);
353
+ if (currentVar instanceof SomaRowScope && !currentVar.active) return undefined;
344
354
  const fn = this.resolveFunction(pipeline.funcPath, currentVar);
345
- value = await fn(currentVar, undefined);
355
+ value = await fn(currentVar instanceof SomaRowScope ? currentVar.data : currentVar, undefined);
356
+ if (currentVar instanceof SomaRowScope && !currentVar.active) return undefined;
346
357
  // 一步之内就 commit:后面的步骤(和它们的 when)要看得见这一步的效果
347
358
  await this.callbacks.onCommit();
348
359
  }
@@ -371,8 +382,8 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
371
382
  return undefined;
372
383
  }
373
384
 
374
- private preCheck(config: SomaCompiledEvent, somaId: string): boolean {
375
- if (this.pendingSet.has(somaId)) {
385
+ private preCheck(config: SomaCompiledEvent, somaId: string, element: HTMLElement): boolean {
386
+ if (this.getContext(element) instanceof SomaRowScope ? this.pendingRows.has(element) : this.pendingSet.has(somaId)) {
376
387
  return false;
377
388
  }
378
389
 
@@ -461,6 +472,14 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
461
472
  private resolveFunction(funcPath: string, currentVar: any): Function {
462
473
  const segments = funcPath.split('.');
463
474
  const rootToken = segments[0];
475
+ if (currentVar instanceof SomaRowScope) {
476
+ if (!currentVar.has(rootToken)) return this.resolver.resolveFunction(funcPath);
477
+ const ownerPath = segments.slice(0, -1).join('.');
478
+ const owner = currentVar.read(ownerPath, () => undefined);
479
+ const fn = readRowPath(owner, segments.slice(-1));
480
+ if (typeof fn !== 'function') throw new Error('[SomaEventEngine] Row handler is not a function');
481
+ return fn.bind(owner);
482
+ }
464
483
 
465
484
  // When the root token refers to a list-item var alias and we have a
466
485
  // concrete item context, resolve the function directly on that item rather
@@ -10,6 +10,7 @@ import { SomaPropertyWatcher } from './property-watcher';
10
10
  import type { WatchCallback, WatcherOptions } from '../../shared/types/watcher.types';
11
11
 
12
12
  export interface SomaRenderEngineOptions {
13
+ repeatPlans?: readonly import('../../shared/types/component-tree-artifact.types').RepeatPlan[];
13
14
  container: HTMLElement;
14
15
  adapter: IContainerAdapter;
15
16
  manifest: SomaRuntimeManifest;
@@ -64,6 +65,7 @@ export class SomaRenderEngine {
64
65
 
65
66
  this.renderer = new SomaDomRenderer();
66
67
  this.renderer.init(this.adapter, this.resolver, this.scopeTracker, options.pipeRegistry);
68
+ this.renderer.setRepeatPlans(options.repeatPlans ?? []);
67
69
  this.renderer.setModelWriteBack((path, value) => this.writeToProxy(path, value));
68
70
 
69
71
  this.bindingTable = options.manifest.bindings
@@ -0,0 +1,62 @@
1
+ import type { SomaRowScope } from './row-scope';
2
+
3
+ /** One keyed row is a complete DOM range, not an assumed first element. */
4
+ export class SomaRowRange {
5
+ readonly start: Comment;
6
+ readonly end: Comment;
7
+ readonly roots: readonly HTMLElement[];
8
+ private released = false;
9
+
10
+ constructor(fragment: DocumentFragment, readonly scope: SomaRowScope, readonly variant = '') {
11
+ this.start = fragment.ownerDocument.createComment('soma-row');
12
+ this.end = fragment.ownerDocument.createComment('/soma-row');
13
+ this.roots = Array.from(fragment.children) as HTMLElement[];
14
+ fragment.prepend(this.start);
15
+ fragment.append(this.end);
16
+ }
17
+
18
+ moveBefore(parent: Node, before: Node | null): void {
19
+ if (this.released) return;
20
+ if (this.start.parentNode === parent && this.end.nextSibling === before) return;
21
+ const doc = this.start.ownerDocument;
22
+ const active = doc.activeElement;
23
+ const focused = active?.namespaceURI === 'http://www.w3.org/1999/xhtml'
24
+ && typeof (active as HTMLElement).focus === 'function' ? active as HTMLElement : null;
25
+ const ownedFocus = focused && this.roots.some(root => root === focused || root.contains(focused));
26
+ const textControl = focused && ['input', 'textarea'].includes(focused.localName)
27
+ ? focused as HTMLInputElement | HTMLTextAreaElement : null;
28
+ const selection = ownedFocus && textControl
29
+ ? { start: textControl.selectionStart, end: textControl.selectionEnd, direction: textControl.selectionDirection }
30
+ : undefined;
31
+ const moved = doc.createDocumentFragment();
32
+ for (let node: Node | null = this.start; node;) {
33
+ const next: Node | null = node.nextSibling;
34
+ moved.appendChild(node);
35
+ if (node === this.end) break;
36
+ node = next;
37
+ }
38
+ parent.insertBefore(moved, before);
39
+ if (ownedFocus && focused.isConnected && doc.activeElement !== focused
40
+ && (!doc.activeElement || doc.activeElement === doc.body)) {
41
+ focused.focus({ preventScroll: true });
42
+ if (selection && selection.start !== null && selection.end !== null) {
43
+ (focused as HTMLInputElement | HTMLTextAreaElement).setSelectionRange(
44
+ selection.start, selection.end, selection.direction ?? undefined,
45
+ );
46
+ }
47
+ }
48
+ }
49
+
50
+ release(releaseRoot: (root: HTMLElement) => void): void {
51
+ if (this.released) return;
52
+ this.released = true;
53
+ this.scope.dispose();
54
+ for (const root of this.roots) releaseRoot(root);
55
+ for (let node: Node | null = this.start; node;) {
56
+ const next: Node | null = node.nextSibling;
57
+ node.parentNode?.removeChild(node);
58
+ if (node === this.end) break;
59
+ node = next;
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,77 @@
1
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
2
+
3
+ export type SomaTypedRowKey = string | number;
4
+
5
+ /** Lexical row identity is in memory only: no raw business keys in DOM attributes. */
6
+ export class SomaRowScope {
7
+ active = true;
8
+ generation = 0;
9
+
10
+ constructor(
11
+ readonly alias: string,
12
+ readonly key: SomaTypedRowKey,
13
+ public data: unknown,
14
+ readonly parent?: SomaRowScope,
15
+ ) {}
16
+
17
+ has(alias: string): boolean {
18
+ return this.alias === alias || (this.parent?.has(alias) ?? false);
19
+ }
20
+
21
+ read(path: string, fallback: (path: string) => unknown): unknown {
22
+ const parts = path.split('.');
23
+ for (let scope: SomaRowScope | undefined = this; scope; scope = scope.parent) {
24
+ if (scope.alias === parts[0]) return readRowPath(scope.data, parts.slice(1));
25
+ }
26
+ return fallback(path);
27
+ }
28
+
29
+ update(data: unknown): void {
30
+ if (!this.active) return;
31
+ this.data = data;
32
+ this.generation++;
33
+ }
34
+
35
+ dispose(): void {
36
+ this.active = false;
37
+ this.generation++;
38
+ }
39
+ }
40
+
41
+ export function readRowPath(value: unknown, parts: readonly string[]): unknown {
42
+ let current = value;
43
+ for (const part of parts) {
44
+ if (['__proto__', 'prototype', 'constructor'].includes(part)) return undefined;
45
+ if (current == null || (typeof current !== 'object' && typeof current !== 'function')) return undefined;
46
+ current = (current as Record<string, unknown>)[part];
47
+ }
48
+ return current;
49
+ }
50
+
51
+ export function validateRowKeys(rows: unknown, keyPath: string, alias: string, limits?: { maxRows?: number; maxKeyLength?: number }): SomaTypedRowKey[] {
52
+ if (!Array.isArray(rows)) rowError('CT-REPEAT-SOURCE', '集合 ready 状态的数据必须是数组');
53
+ if (rows.length > (limits?.maxRows ?? 1000)) rowError('CT-LIMIT', '集合行数超过受信预算');
54
+ const parts = keyPath.split('.');
55
+ if (parts.shift() !== alias || parts.length === 0
56
+ || parts.some(part => !/^[$A-Z_a-z][$\w]*$/.test(part)
57
+ || ['__proto__', 'prototype', 'constructor'].includes(part))) {
58
+ rowError('CT-REPEAT-KEY', '显式行键必须来自当前行的安全字段路径');
59
+ }
60
+ const seen = new Set<SomaTypedRowKey>();
61
+ return rows.map(row => {
62
+ const key = readRowPath(row, parts);
63
+ if (!((typeof key === 'string' && key.length > 0 && key.length <= (limits?.maxKeyLength ?? 256))
64
+ || (typeof key === 'number' && Number.isFinite(key)))) {
65
+ rowError('CT-REPEAT-KEY', '行键必须是非空有界字符串或有限数字');
66
+ }
67
+ if (seen.has(key)) rowError('CT-REPEAT-KEY', '同一集合中存在重复行键');
68
+ seen.add(key);
69
+ return key;
70
+ });
71
+ }
72
+
73
+ function rowError(code: 'CT-REPEAT-KEY' | 'CT-REPEAT-SOURCE' | 'CT-LIMIT', hint: string): never {
74
+ throw new SomaComponentTreeError({
75
+ code, phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat', fixHint: hint,
76
+ });
77
+ }
@@ -27,6 +27,7 @@ import { SomaTriggerEngine } from './trigger-engine';
27
27
  import { SomaTimerEngine } from './timer-engine';
28
28
 
29
29
  export interface RuntimeBuildInput {
30
+ repeatPlans?: readonly import('../../shared/types/component-tree-artifact.types').RepeatPlan[];
30
31
  container: HTMLElement;
31
32
  adapter: IContainerAdapter;
32
33
  uiConfig: UiConfig;
@@ -99,6 +100,7 @@ export class SomaRuntimeBuilder {
99
100
  propertyWatcher.setRoot(input.proxiedInstance);
100
101
 
101
102
  const renderEngine = new SomaRenderEngine({
103
+ repeatPlans: input.repeatPlans,
102
104
  container: input.container,
103
105
  adapter: input.adapter,
104
106
  manifest,
@@ -60,8 +60,11 @@ import {
60
60
  } from '../observability/error-reporter';
61
61
 
62
62
  // ─── 类型定义 ──────────────────────────────────────────
63
+ import { assertRuntimeArtifact } from '../../shared/component-tree-artifact';
64
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
65
+ import type { ComponentTreeRuntimeEnvelope } from '../../shared/types/component-tree-artifact.types';
63
66
 
64
- export interface SomaPageAssets {
67
+ export interface SomaPageAssets extends ComponentTreeRuntimeEnvelope {
65
68
  html: string;
66
69
  includes?: Record<string, string>;
67
70
  DomainClass: new () => SomaPageRoot;
@@ -104,6 +107,123 @@ export interface SomaPageAssets {
104
107
  components?: Record<string, SomaComponentDefinition>;
105
108
  }
106
109
 
110
+ /** Validate before mutating the current DOM or instantiating any business Domain. */
111
+ export function assertPageRuntimeAssets(assets: SomaPageAssets, hostComponents: Record<string, SomaComponentDefinition>): void {
112
+ assertRuntimeArtifact(assets);
113
+ if (assets.uiYaml && isSomaDeclarationSource(assets.uiYaml)) {
114
+ throw new Error('[SomaBootstrap] 收到未编译的 SOMA DSL 源声明,请先在服务端编译。');
115
+ }
116
+ if (assets.sourceMarkup === 'component-tree') {
117
+ for (const ref of assets.artifact!.componentRefs) {
118
+ const definition = assets.components?.[ref.name] ?? hostComponents[ref.name];
119
+ if (!definition || definition.contractDigest !== ref.contractDigest || definition.structureDigest !== ref.structureDigest) {
120
+ throw new SomaComponentTreeError({
121
+ code: 'CT-ARTIFACT-CAPABILITY', phase: 'artifact', sourceId: '<runtime-assets>', nodePath: 'componentRefs',
122
+ fixHint: '客户端组件供货缺失或契约/结构摘要与资产不一致;请同步部署服务端与客户端供货。',
123
+ });
124
+ }
125
+ }
126
+ const objectConfig = assets.uiConfig !== undefined && assets.eventConfig !== undefined;
127
+ const yamlConfig = typeof assets.uiYaml === 'string' && assets.uiYaml.trim() !== ''
128
+ && typeof assets.eventYaml === 'string';
129
+ if ((!objectConfig && !yamlConfig) || (assets.styleConfig && Object.keys(assets.styleConfig).length > 0)
130
+ || Boolean(assets.styleYaml?.trim()) || Object.keys(assets.includes ?? {}).length > 0) {
131
+ throw new SomaComponentTreeError({
132
+ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'artifact', sourceId: '<runtime-assets>', nodePath: 'config',
133
+ fixHint: '树页面必须携带完整编译配置;不能附带独立样式或待展开 includes。',
134
+ });
135
+ }
136
+ }
137
+ // Browser parsing is used only for leak detection, never as the source tree parser.
138
+ const probe = document.createElement('template');
139
+ probe.innerHTML = assets.html;
140
+ const pending: ParentNode[] = [probe.content];
141
+ const treeHosts = new Map<string, Element>();
142
+ const treeTemplates = new Map<string, Element>();
143
+ const templateParents = new Map<Node, HTMLTemplateElement>();
144
+ const invalidPlan = (): never => {
145
+ throw new SomaComponentTreeError({
146
+ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'artifact', sourceId: '<runtime-assets>', nodePath: 'html.plans',
147
+ fixHint: '兼容 HTML 的组件/行模板与结构计划不是同一编译批次;旧页面不会被替换。',
148
+ });
149
+ };
150
+ while (pending.length > 0) {
151
+ for (const element of pending.pop()!.querySelectorAll('*')) {
152
+ if (element.localName.toLowerCase().startsWith('soma-')) {
153
+ throw new SomaComponentTreeError({
154
+ code: 'CT-SYNTAX-LEAK', phase: 'artifact', sourceId: '<runtime-assets>', nodePath: 'html',
155
+ fixHint: '运行时 HTML 仍包含组件树源码标签;请检查完整资产出口。',
156
+ });
157
+ }
158
+ if (assets.sourceMarkup === 'component-tree') {
159
+ if (element.hasAttribute('data-soma-component')) {
160
+ const symbol = element.getAttribute('data-soma-id') ?? '';
161
+ if (!symbol || treeHosts.has(symbol)) invalidPlan();
162
+ treeHosts.set(symbol, element);
163
+ }
164
+ if (element.hasAttribute('data-soma-repeat-template')) {
165
+ const symbol = element.getAttribute('data-soma-repeat-template') ?? '';
166
+ if (!symbol || !isHtmlTemplateElement(element) || treeTemplates.has(symbol)) invalidPlan();
167
+ treeTemplates.set(symbol, element);
168
+ }
169
+ }
170
+ if (isHtmlTemplateElement(element)) {
171
+ templateParents.set(element.content, element);
172
+ pending.push(element.content);
173
+ }
174
+ }
175
+ }
176
+ if (assets.sourceMarkup === 'component-tree') {
177
+ if (treeHosts.size !== assets.artifact!.structurePlan.length || treeTemplates.size !== assets.artifact!.repeatPlans.length
178
+ || probe.content.children.length !== 1 || !probe.content.firstElementChild?.hasAttribute('data-soma-host')) invalidPlan();
179
+ for (const plan of assets.artifact!.structurePlan) {
180
+ const host = treeHosts.get(plan.instanceSymbol);
181
+ if (!host || host.getAttribute('data-soma-component') !== plan.componentName
182
+ || host.localName !== plan.hostTag || host.namespaceURI !== 'http://www.w3.org/1999/xhtml') invalidPlan();
183
+ }
184
+ const repeats = assets.artifact!.repeatPlans;
185
+ const lexicalTemplate = (element: Element): string | undefined => {
186
+ let parent: Node | null = element.parentNode;
187
+ while (parent) {
188
+ const template = templateParents.get(parent);
189
+ if (template?.hasAttribute('data-soma-repeat-template')) return template.getAttribute('data-soma-repeat-template')!;
190
+ parent = template ? template.parentNode : parent.parentNode;
191
+ }
192
+ return undefined;
193
+ };
194
+ const symbolScopes = new Map<string, string>();
195
+ for (const plan of repeats) {
196
+ const template = treeTemplates.get(plan.rowTemplateId);
197
+ const slot = template?.parentNode ? templateParents.get(template.parentNode) : undefined;
198
+ const owner = treeHosts.get(plan.consumerOwner.instanceSymbol);
199
+ const ownerPlan = assets.artifact!.structurePlan.find(item => item.instanceSymbol === plan.consumerOwner.instanceSymbol);
200
+ const slotPlan = ownerPlan?.slotPlans.find(item => item.name === plan.consumerOwner.slotName);
201
+ if (!template || !slot || !owner || slot.parentElement !== owner
202
+ || slot.getAttribute('data-soma-slot') !== plan.consumerOwner.slotName
203
+ || template.getAttribute('data-soma-role') !== 'item'
204
+ || slot.content.children.length !== 1 || slot.content.firstElementChild !== template
205
+ || slotPlan?.kind !== 'collection' || slotPlan.layoutRootKey !== plan.consumerOwner.layoutRootKey
206
+ || slotPlan.rowContainer !== plan.consumerOwner.rowContainer
207
+ || ownerPlan?.componentName !== plan.consumerOwner.componentName) invalidPlan();
208
+ const parentPlan = plan.parentPlanId ? repeats.find(item => item.planId === plan.parentPlanId) : undefined;
209
+ if (lexicalTemplate(owner!) !== parentPlan?.rowTemplateId) invalidPlan();
210
+ for (const symbol of Object.values(plan.localSymbols)) {
211
+ if (symbolScopes.has(symbol) || !treeHosts.has(symbol)) invalidPlan();
212
+ symbolScopes.set(symbol, plan.rowTemplateId);
213
+ }
214
+ }
215
+ for (const [symbol, host] of treeHosts) {
216
+ if (lexicalTemplate(host) !== symbolScopes.get(symbol)) invalidPlan();
217
+ }
218
+ }
219
+ }
220
+
221
+ /** Template contents use an inert ownerDocument; its defaultView can be null in real DOM/JSDOM. */
222
+ function isHtmlTemplateElement(element: Element): element is HTMLTemplateElement {
223
+ return element.localName === 'template' && element.namespaceURI === 'http://www.w3.org/1999/xhtml'
224
+ && 'content' in element && (element as HTMLTemplateElement).content?.nodeType === 11;
225
+ }
226
+
107
227
  /** 浏览器只用于拒绝源声明;不存在旧/新两套执行分派。 */
108
228
  function isSomaDeclarationSource(value: string): boolean {
109
229
  return value.split('\n').some((line) => {
@@ -395,6 +515,7 @@ export class SomaBootstrap {
395
515
  this.scheduler.setDiagnostics(this.diagnostics);
396
516
  }
397
517
  this.container = container;
518
+ assertPageRuntimeAssets(assets, this.hostComponents);
398
519
  // 源声明只允许在构建/服务端编译;浏览器 mount 只消费运行时资产。
399
520
  if (assets.uiYaml && isSomaDeclarationSource(assets.uiYaml)) {
400
521
  throw new Error(
@@ -482,6 +603,28 @@ export class SomaBootstrap {
482
603
  ...overrides,
483
604
  DomainClass: overrides.DomainClass ?? this.assets.DomainClass,
484
605
  };
606
+ if (this.assets.sourceMarkup === 'component-tree' || merged.sourceMarkup === 'component-tree') {
607
+ const compilationFields = ['html', 'uiConfig', 'eventConfig', 'triggerConfig', 'timerConfig',
608
+ 'dataConfig', 'uiYaml', 'eventYaml', 'dataYaml', 'sourceMarkup', 'artifact'] as const;
609
+ const updatesCompilation = compilationFields.some((key) => Object.hasOwn(overrides, key));
610
+ if (updatesCompilation && (overrides.html === undefined || overrides.sourceMarkup === undefined
611
+ || (merged.sourceMarkup === 'component-tree' && overrides.artifact === undefined)
612
+ || !((overrides.uiConfig !== undefined && overrides.eventConfig !== undefined)
613
+ || (overrides.uiYaml !== undefined && overrides.eventYaml !== undefined)))) {
614
+ throw new SomaComponentTreeError({
615
+ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'artifact', sourceId: '<runtime-assets>', nodePath: 'hotSwap',
616
+ fixHint: '树页面热替换必须整体提供 HTML、格式、配置与 artifact,不能混用新旧编译批次。',
617
+ });
618
+ }
619
+ if (updatesCompilation) {
620
+ // Remove alternate representations from the previous compile batch.
621
+ for (const key of ['uiConfig', 'eventConfig', 'triggerConfig', 'timerConfig', 'dataConfig',
622
+ 'uiYaml', 'eventYaml', 'dataYaml', 'artifact'] as const) {
623
+ if (!Object.hasOwn(overrides, key)) delete merged[key];
624
+ }
625
+ }
626
+ }
627
+ assertPageRuntimeAssets(merged, this.hostComponents);
485
628
 
486
629
  if (options?.resetDiagnostics) {
487
630
  this.diagnostics = new SomaDiagnostics();
@@ -1240,6 +1383,7 @@ export class SomaBootstrap {
1240
1383
  pipeRegistry: this.pipeRegistry,
1241
1384
  componentDefaults: this.componentDefaults,
1242
1385
  styleOptions: { nonce: this.componentStyleNonce ?? null },
1386
+ treeArtifact: assets.artifact,
1243
1387
  });
1244
1388
  this.componentManager.prepare(container, uiConfig);
1245
1389
  }
@@ -1270,6 +1414,7 @@ export class SomaBootstrap {
1270
1414
  eventMiddleware: this.eventMiddleware,
1271
1415
  pipeRegistry: this.pipeRegistry,
1272
1416
  adaptiveVocabulary: this.adaptiveVocabulary,
1417
+ repeatPlans: this.assets?.artifact?.repeatPlans,
1273
1418
  });
1274
1419
 
1275
1420
  this.parsedTimers = parsed.timers;
@@ -285,17 +285,24 @@ function parseEachBlock(
285
285
  throw new SomaBlockParseError(message, 'page');
286
286
  };
287
287
  const raw = String(block.each);
288
- const match = /^(\S+)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s+by\s+(\S+))?(?:\s+key\s+(\S+))?$/.exec(raw.trim());
288
+ const match = /^(\S+)\s+as\s+([$A-Z_a-z][$\w]*)(?:\s+by\s+(\S+))?(?:\s+key\s+(\S+))?$/.exec(raw.trim());
289
289
  if (!match) {
290
290
  fail(`each 语法错误: "${raw}"(应为 each: 路径 as 变量 [by 路径] [key 字段])`);
291
291
  }
292
- const [, sourcePath, rowVar, byPath] = match!;
292
+ const [, sourcePath, rowVar, byPath, keyPath] = match!;
293
293
 
294
294
  const bind: BindDeclaration = {
295
295
  obj: expandPath(sourcePath, scope),
296
296
  var: rowVar,
297
297
  };
298
298
  if (byPath) bind.role_by = byPath;
299
+ if (keyPath) {
300
+ bind.key = keyPath.includes('.') ? keyPath : `${rowVar}.${keyPath}`;
301
+ if (!bind.key.startsWith(`${rowVar}.`) || !/^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)+$/.test(bind.key)
302
+ || bind.key.split('.').some(part => ['__proto__', 'prototype', 'constructor'].includes(part))) {
303
+ fail('each key 必须是当前行变量的安全字段路径');
304
+ }
305
+ }
299
306
 
300
307
  // 行作用域:行变量加入可见名
301
308
  const rowScope: BlockScope = {
@@ -52,6 +52,8 @@ export class SomaUiConfigError extends Error {
52
52
  // ─── 解析选项 ─────────────────────────────────────────────────────────────────
53
53
 
54
54
  export interface SomaUiConfigParseOptions {
55
+ /** Raw collectionSlot is trusted package source only; runtimes consume plan references. */
56
+ collectionBindingStage?: 'definition-source' | 'runtime';
55
57
  /**
56
58
  * 阶梯词汇表(F-09)。core 不内置任何级语义,词汇由宿主 bootstrap 注入;
57
59
  * 不传而页面声明了 `adaptive.ladder` 时,按"词汇未知"快速失败。
@@ -110,6 +112,20 @@ function validateBind(bind: any, path: string): asserts bind is BindDeclaration
110
112
  if ('onChange' in bind && bind.onChange !== undefined) {
111
113
  parseOnChangeRules(bind.onChange, `${path}.onChange`);
112
114
  }
115
+ if (bind.key !== undefined && (typeof bind.key !== 'string'
116
+ || !bind.key.startsWith(`${bind.var}.`)
117
+ || !/^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)+$/.test(bind.key)
118
+ || bind.key.split('.').some((part: string) => ['__proto__', 'prototype', 'constructor'].includes(part)))) {
119
+ throw new SomaUiConfigError('bind.key 必须是当前行变量的安全字段路径', path);
120
+ }
121
+ if (bind.repeatPlanId !== undefined && (typeof bind.repeatPlanId !== 'string' || !bind.repeatPlanId.trim()
122
+ || bind.key !== undefined || bind.collectionSlot !== undefined)) {
123
+ throw new SomaUiConfigError('repeatPlanId 必须是非空引用且不能与 key/collectionSlot 双写', path);
124
+ }
125
+ if (bind.collectionSlot !== undefined && (typeof bind.collectionSlot !== 'string' || !bind.collectionSlot.trim()
126
+ || bind.key === undefined)) {
127
+ throw new SomaUiConfigError('collectionSlot 必须具名并提供唯一显式 key', path);
128
+ }
113
129
  }
114
130
 
115
131
  function parseOnChangeRules(raw: unknown, path: string): OnChangeRule[] {
@@ -172,7 +188,7 @@ function parseInitProps(raw: unknown, path: string): Record<string, unknown> {
172
188
  /**
173
189
  * 判断一个对象值是否为嵌套绑定(含 bind + show)
174
190
  */
175
- function isNestedShowMapping(value: any): value is { bind: any; show: any; when?: unknown } {
191
+ function isNestedShowMapping(value: any): value is { bind: any; show: any; when?: unknown; props?: unknown } {
176
192
  return (
177
193
  typeof value === 'object' &&
178
194
  value !== null &&
@@ -205,7 +221,7 @@ function isExtendedShowValue(value: any): boolean {
205
221
  * @returns 类型安全的 ShowMapping
206
222
  * @throws SomaUiConfigError 格式不合法时抛出
207
223
  */
208
- function parseShowMapping(rawShow: any, path: string): ShowMapping {
224
+ function parseShowMapping(rawShow: any, path: string, options?: SomaUiConfigParseOptions): ShowMapping {
209
225
  if (!rawShow || typeof rawShow !== 'object') {
210
226
  throw new SomaUiConfigError(`show 必须是对象`, path);
211
227
  }
@@ -225,23 +241,36 @@ function parseShowMapping(rawShow: any, path: string): ShowMapping {
225
241
  } else if (/^item:.+/.test(key) && typeof value === 'object' && value !== null
226
242
  && !isNestedShowMapping(value) && !isExtendedShowValue(value)) {
227
243
  // 异构列表分组键:item:变体 → 仅该变体行生效的子映射(DSL 扩展规范 2.1)
228
- result[key] = { show: parseShowMapping(value, currentPath) };
244
+ result[key] = { show: parseShowMapping(value, currentPath, options) };
229
245
  } else if (isNestedShowMapping(value)) {
230
246
  // 嵌套绑定:含 bind + show
231
247
  const nestedPath = `${currentPath}.bind`;
232
248
  validateBind(value.bind, nestedPath);
249
+ if (value.bind.collectionSlot !== undefined && options?.collectionBindingStage !== 'definition-source') {
250
+ throw new SomaUiConfigError('collectionSlot 仅允许受信组件定义源;运行时必须使用准备计划', nestedPath);
251
+ }
233
252
 
234
253
  const nested: NestedShowMapping = {
235
254
  bind: {
236
255
  obj: value.bind.obj,
237
256
  var: value.bind.var,
238
257
  ...(typeof value.bind.role_by === 'string' ? { role_by: value.bind.role_by } : {}),
258
+ ...(value.bind.key !== undefined ? { key: value.bind.key } : {}),
259
+ ...(value.bind.repeatPlanId !== undefined ? { repeatPlanId: value.bind.repeatPlanId } : {}),
260
+ ...(value.bind.collectionSlot !== undefined ? { collectionSlot: value.bind.collectionSlot } : {}),
239
261
  },
240
- show: parseShowMapping(value.show, `${currentPath}.show`),
262
+ show: parseShowMapping(value.show, `${currentPath}.show`, options),
241
263
  // when 与 bind 同处一层:整块显隐(列表在错误/加载态整体隐藏靠它)
242
264
  ...(typeof value.when === 'string' ? { when: value.when } : {}),
243
265
  };
244
266
 
267
+ if (value.props !== undefined) {
268
+ if (!value.props || typeof value.props !== 'object' || Array.isArray(value.props)) {
269
+ throw new SomaUiConfigError('props 必须是对象', currentPath);
270
+ }
271
+ nested.props = { ...value.props };
272
+ }
273
+
245
274
  result[key] = nested;
246
275
  } else if (typeof value === 'object' && value !== null && isExtendedShowValue(value)) {
247
276
  // 扩展绑定:含 text / model / when / class / show
@@ -299,7 +328,7 @@ function parseShowMapping(rawShow: any, path: string): ShowMapping {
299
328
  }
300
329
 
301
330
  if ('show' in value && value.show !== undefined) {
302
- extended.show = parseShowMapping(value.show, `${currentPath}.show`);
331
+ extended.show = parseShowMapping(value.show, `${currentPath}.show`, options);
303
332
  }
304
333
 
305
334
  if ('props' in value && value.props !== undefined) {
@@ -389,7 +418,10 @@ export function parseUiConfig(raw: any, options?: SomaUiConfigParseOptions): UiC
389
418
  bind.onChange = parseOnChangeRules(raw.bind.onChange, 'bind.onChange');
390
419
  }
391
420
 
392
- const show = parseShowMapping(raw.show, 'show');
421
+ if (raw.bind.key !== undefined || raw.bind.repeatPlanId !== undefined || raw.bind.collectionSlot !== undefined) {
422
+ throw new SomaUiConfigError('顶层 bind 不接受集合行字段', 'bind');
423
+ }
424
+ const show = parseShowMapping(raw.show, 'show', options);
393
425
 
394
426
  const config: UiConfig = { bind, show };
395
427