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
@@ -0,0 +1,60 @@
1
+ import type { SomaContractExample } from '../../shared/types/component-contract.types';
2
+
3
+ export interface CatalogExampleSource {
4
+ ai?: { example?: string; examples?: readonly SomaContractExample[] };
5
+ }
6
+
7
+ export interface CatalogExampleCapabilities {
8
+ /** In preference order. Missing options intentionally means legacy-only. */
9
+ formats?: readonly SomaContractExample['format'][];
10
+ capabilities?: readonly string[];
11
+ }
12
+
13
+ /** No tree source is selected unless both its grammar format and capabilities are accepted. */
14
+ export function selectSomaCatalogExample(
15
+ entry: CatalogExampleSource,
16
+ options: CatalogExampleCapabilities = {},
17
+ ): SomaContractExample | null {
18
+ const capabilities = new Set(options.capabilities ?? []);
19
+ for (const format of options.formats ?? ['legacy-html']) {
20
+ const example = entry.ai?.examples?.find((candidate) => candidate.format === format
21
+ && (candidate.format !== 'component-tree' || candidate.grammarVersion === 1 && capabilities.has('component-tree:1'))
22
+ && (candidate.capabilities ?? []).every((capability) => capabilities.has(capability)));
23
+ if (example) return example;
24
+ }
25
+ return null;
26
+ }
27
+
28
+ /** Human-readable usage retains format metadata, rather than pretending tree tags are HTML. */
29
+ export function formatSomaCatalogExample(example: SomaContractExample): string {
30
+ return [
31
+ `markup: ${example.format}`,
32
+ ...(example.format === 'component-tree' ? [`grammarVersion: ${example.grammarVersion}`] : []),
33
+ ...(example.capabilities?.length ? [`capabilities: ${example.capabilities.join(', ')}`] : []),
34
+ '', example.html, '', example.canonicalUi,
35
+ ].join('\n');
36
+ }
37
+
38
+ /** Validate the portable example envelope without importing build-time parsers in the client. */
39
+ export function copyCatalogExamples(examples: readonly SomaContractExample[]): SomaContractExample[] {
40
+ if (!Array.isArray(examples)) throw new TypeError('[catalog] ai.examples must be an array');
41
+ return examples.map((example) => {
42
+ if (!example || typeof example !== 'object' || !['legacy-html', 'component-tree'].includes(example.format)
43
+ || typeof example.html !== 'string' || !example.html.trim()
44
+ || typeof example.canonicalUi !== 'string' || !example.canonicalUi.trim()
45
+ || !example.canonicalUi.trim().startsWith('{{') || !example.canonicalUi.trim().endsWith('}}')
46
+ || (example.format === 'component-tree' ? example.grammarVersion !== 1 : example.grammarVersion !== undefined)
47
+ || (example.capabilities !== undefined && (!Array.isArray(example.capabilities)
48
+ || example.capabilities.some((capability: unknown) => typeof capability !== 'string' || !/^[a-z][a-z-]*:\d+$/.test(capability))))) {
49
+ throw new TypeError('[catalog] invalid ai.examples format/grammar/canonical declaration/capabilities');
50
+ }
51
+ if (example.format === 'legacy-html' && /<\/?soma-(?:host|component|slot|fragment|repeat)\b/i.test(example.html)) {
52
+ throw new TypeError('[catalog] component-tree source cannot be labelled legacy-html');
53
+ }
54
+ return {
55
+ format: example.format, html: example.html, canonicalUi: example.canonicalUi,
56
+ ...(example.format === 'component-tree' ? { grammarVersion: 1 as const } : {}),
57
+ ...(example.capabilities ? { capabilities: [...example.capabilities] } : {}),
58
+ } as SomaContractExample;
59
+ });
60
+ }
@@ -6,6 +6,8 @@
6
6
  import type { UiConfig } from '../../shared/types/ui-config.types';
7
7
  import type { ParsedEvent } from '../../shared/types/event.types';
8
8
  import type { SomaComponentContract } from '../../shared/types/component-contract.types';
9
+ import type { DefinitionPreparation, DefinitionRepeatPlan, SomaStructureAdapterDefinition } from '../../shared/types/component-tree-artifact.types';
10
+ import type { TreeCollectionSource } from '../../shared/types/component-tree.types';
9
11
 
10
12
  /** 控制器工厂上下文:props 即实例作用域根(可读取最新值),emit 向页面上抛 */
11
13
  export interface SomaComponentControllerContext {
@@ -72,6 +74,13 @@ export interface SomaComponentStyleFeature {
72
74
 
73
75
  export interface SomaComponentDefinition {
74
76
  contract: SomaComponentContract;
77
+ structureAdapter?: SomaStructureAdapterDefinition;
78
+ collectionSources?: readonly TreeCollectionSource[];
79
+ definitionRepeatPlans?: DefinitionRepeatPlan[];
80
+ definitionPreparation?: DefinitionPreparation;
81
+ /** Precomputed by the trusted package build; never browser-computed with Node. */
82
+ structureDigest?: string;
83
+ contractDigest?: string;
75
84
  /**
76
85
  * 组件内部结构模板。内部锚点写 data-soma-id(与页面 DSL 一致),
77
86
  * 展开器统一改写为 data-soma-scoped-id 实现作用域隔离。
@@ -8,7 +8,9 @@
8
8
  // - 宿主元素自身的 data-soma-id / class 不变(页面继续用它做 when/样式/事件寻址)。
9
9
 
10
10
  import type { SomaComponentDefinition } from './component-definition.types';
11
- import { SOMA_SCOPED_ID_ATTR, SOMA_SCOPE_ATTR } from './scoped-adapter';
11
+ import { SOMA_SCOPED_ID_ATTR, SOMA_SCOPE_ATTR, registerSomaRootAlias } from './scoped-adapter';
12
+ import type { StructurePlan } from '../../shared/types/component-tree-artifact.types';
13
+ import { prepareStructureTemplate, commitStructureTemplate, registerPreparedStructure } from './structure-adapter';
12
14
 
13
15
  export const SOMA_COMPONENT_ATTR = 'data-soma-component';
14
16
  /**
@@ -45,12 +47,13 @@ export class SomaComponentExpander {
45
47
  }
46
48
 
47
49
  /** @returns 本次展开分配的 scopeId(宿主已展开时返回既有的那个) */
48
- expand(host: HTMLElement, def: SomaComponentDefinition): string {
50
+ expand(host: HTMLElement, def: SomaComponentDefinition, plan?: StructurePlan, staticProps?: Record<string, unknown>): string {
49
51
  const existing = this.scopeIdOf(host);
50
52
  if (existing !== null) {
51
53
  return existing;
52
54
  }
53
55
  const scopeId = `c${++scopeSeq}`;
56
+ const prepared = prepareStructureTemplate(host, def, plan, staticProps);
54
57
 
55
58
  // 1. 摘出页面提供的插槽内容(在模板注入前,DocumentFragment 引用在注入后仍有效)
56
59
  const slotContent = new Map<string, DocumentFragment>();
@@ -62,7 +65,8 @@ export class SomaComponentExpander {
62
65
  }
63
66
 
64
67
  // 2. 注入组件模板
65
- host.innerHTML = def.templateHtml;
68
+ commitStructureTemplate(host, prepared);
69
+ if (prepared.rootAlias) registerSomaRootAlias(host, scopeId, prepared.rootAlias);
66
70
 
67
71
  // 3. 内部锚点作用域化(含 <template> 内容,插槽内容尚未注入故不受影响)
68
72
  // 此刻宿主子树里的锚点,恰好就是"本组件模板写下的"全集——包括写在
@@ -82,13 +86,24 @@ export class SomaComponentExpander {
82
86
  for (const outlet of outlets) {
83
87
  const slotName = outlet.getAttribute(SOMA_SLOT_OUTLET_ATTR)!;
84
88
  const content = slotContent.get(slotName);
85
- if (!content) {
89
+ // Existing definitions require the named projection to exist, not to be
90
+ // nonempty. Meaningful-content validation belongs to the new structure
91
+ // protocol; an explicitly empty legacy Drawer body remains compatible.
92
+ const emptyStructureContent = def.contract.structure && content
93
+ && ![...content.childNodes].some(node => node.nodeType === 1 || (node.nodeType === 3 && !!node.textContent?.trim()));
94
+ if (!content || emptyStructureContent) {
95
+ slotContent.delete(slotName);
86
96
  if (def.contract.slots?.[slotName]?.required) {
87
97
  throw new SomaComponentExpandError(
88
98
  `组件 "${def.contract.name}" 的必填插槽 "${slotName}" 缺少内容(<template data-soma-slot="${slotName}">)`,
89
99
  );
90
100
  }
91
- outlet.remove();
101
+ // A collection's optional empty state is an independent semantic row;
102
+ // an absent slot removes that row, not just its now-empty outlet.
103
+ const emptyAnchor = def.structureAdapter?.layoutRoots.empty;
104
+ const parent = outlet.parentElement;
105
+ if (slotName === 'empty' && emptyAnchor && parent?.getAttribute(SOMA_SCOPED_ID_ATTR) === emptyAnchor) parent.remove();
106
+ else outlet.remove();
92
107
  continue;
93
108
  }
94
109
  outlet.replaceWith(content);
@@ -102,6 +117,7 @@ export class SomaComponentExpander {
102
117
  }
103
118
 
104
119
  host.setAttribute(SOMA_COMPONENT_READY_ATTR, scopeId);
120
+ registerPreparedStructure(host, def, scopeId, prepared.staticProps);
105
121
  return scopeId;
106
122
  }
107
123
 
@@ -14,6 +14,7 @@ import { isKnownDomEvent } from '../parser/pipeline-parser';
14
14
  import { SomaRenderEngine } from '../engine/render-engine';
15
15
  import { SomaEventEngine } from '../engine/event-engine';
16
16
  import { SomaScopeResolver } from '../engine/scope-resolver';
17
+ import { SomaRowScope } from '../engine/row-scope';
17
18
  import { SomaEmitEvent } from '../engine/emit-event';
18
19
  import type { SomaScheduler } from '../scheduler/SomaScheduler';
19
20
  import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
@@ -39,6 +40,10 @@ import { SomaScopedContainerAdapter, SOMA_SCOPE_ATTR } from './scoped-adapter';
39
40
  import type { SomaComponentDefaults } from './component-defaults';
40
41
  import { ensureStyleFeatures } from './style-features';
41
42
  import type { PackStyleOptions } from './pack-styles';
43
+ import { COMPONENT_TREE_CAPABILITIES, type TreeArtifact, type StructurePlan } from '../../shared/types/component-tree-artifact.types';
44
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
45
+ import { assertDefinitionPreparation } from '../../shared/component-tree-artifact';
46
+ import { assertPreparedStructureProps, withPreparedStructureProps } from './structure-adapter';
42
47
 
43
48
  const MAX_EXPANSION_ROUNDS = 8;
44
49
 
@@ -54,6 +59,8 @@ export interface SomaComponentPageRuntime {
54
59
  }
55
60
 
56
61
  export interface SomaComponentManagerOptions {
62
+ /** The complete artifact has already passed the bootstrap integrity gate. */
63
+ treeArtifact?: TreeArtifact;
57
64
  registry: SomaComponentRegistry;
58
65
  scheduler?: SomaScheduler;
59
66
  diagnostics?: SomaDiagnostics;
@@ -90,6 +97,8 @@ export class SomaComponentManager {
90
97
  private readonly componentDefaults?: SomaComponentDefaults;
91
98
  private readonly styleOptions?: PackStyleOptions;
92
99
  private readonly expander = new SomaComponentExpander();
100
+ private readonly treeArtifact?: TreeArtifact;
101
+ private readonly preparedDefinitions = new Map<string, SomaComponentDefinition>();
93
102
 
94
103
  private staticDecls: StaticInstanceDecl[] = [];
95
104
  private propsIndex = new Map<string, Record<string, unknown>>();
@@ -99,6 +108,7 @@ export class SomaComponentManager {
99
108
  private page: SomaComponentPageRuntime | null = null;
100
109
 
101
110
  constructor(options: SomaComponentManagerOptions) {
111
+ this.treeArtifact = options.treeArtifact;
102
112
  this.registry = options.registry;
103
113
  this.scheduler = options.scheduler;
104
114
  this.diagnostics = options.diagnostics;
@@ -138,7 +148,7 @@ export class SomaComponentManager {
138
148
  throw new SomaComponentExpandError(`组件 "${name}" 的宿主元素缺少 data-soma-id`);
139
149
  }
140
150
  const def = this.registry.get(name);
141
- this.expander.expand(host, def);
151
+ this.expandHost(host, def, this.propsIndex.get(instanceId) ?? {});
142
152
  // 组合组件的子组件也必须在页面契约校验前展开。否则子组件模板
143
153
  // 里的 data-soma-host 仍封在 template.content 中,页面会误报
144
154
  // "缺少 data-soma-host 边界";实例挂载阶段再展开已经太晚。
@@ -200,7 +210,8 @@ export class SomaComponentManager {
200
210
  dispose();
201
211
  }
202
212
  this.watchDisposers.length = 0;
203
- for (const instance of this.instances) {
213
+ const ordered = [...this.instances].sort((a, b) => a.getHost().contains(b.getHost()) ? 1 : b.getHost().contains(a.getHost()) ? -1 : 0);
214
+ for (const instance of ordered) {
204
215
  instance.destroy();
205
216
  }
206
217
  this.instances.clear();
@@ -226,12 +237,12 @@ export class SomaComponentManager {
226
237
  return;
227
238
  }
228
239
  // 被摘除的行根元素自己就可能是组件宿主(行模板根 = 组件)
229
- this.releaseHost(root);
230
240
  for (const host of Array.from(
231
241
  root.querySelectorAll<HTMLElement>(`[${SOMA_COMPONENT_ATTR}]`),
232
- )) {
242
+ ).reverse()) {
233
243
  this.releaseHost(host);
234
244
  }
245
+ this.releaseHost(root);
235
246
  }
236
247
 
237
248
  private releaseHost(host: HTMLElement): void {
@@ -263,7 +274,7 @@ export class SomaComponentManager {
263
274
  const reader = this.createRowReader(this.page, rowData);
264
275
  const existing = this.hostInstances.get(element);
265
276
  if (existing) {
266
- existing.setProps(resolveProps(propsDecl, reader, existing.def, this.defaultsFor(existing.def)));
277
+ existing.setProps(withPreparedStructureProps(element, resolveProps(propsDecl, reader, existing.def, this.defaultsFor(existing.def)), propsDecl));
267
278
  return;
268
279
  }
269
280
 
@@ -272,7 +283,7 @@ export class SomaComponentManager {
272
283
  throw new SomaComponentExpandError(`组件 "${name}" 的宿主元素缺少 data-soma-id`);
273
284
  }
274
285
  const def = this.registry.get(name);
275
- this.expander.expand(element, def);
286
+ this.expandHost(element, def, propsDecl);
276
287
  this.mountInstance(element, instanceId, def, propsDecl, reader);
277
288
  }
278
289
 
@@ -289,7 +300,7 @@ export class SomaComponentManager {
289
300
  host,
290
301
  instanceId,
291
302
  def,
292
- initialProps: resolveProps(propsDecl, reader, def, this.defaultsFor(def)),
303
+ initialProps: withPreparedStructureProps(host, resolveProps(propsDecl, reader, def, this.defaultsFor(def)), propsDecl),
293
304
  scheduler: this.scheduler,
294
305
  diagnostics: this.diagnostics,
295
306
  pipeRegistry: this.pipeRegistry,
@@ -324,17 +335,17 @@ export class SomaComponentManager {
324
335
  const reader = this.createChildReader(parent, rowData);
325
336
  const existing = this.hostInstances.get(element);
326
337
  if (existing) {
327
- existing.setProps(resolveProps(propsDecl, reader, existing.def, this.defaultsFor(existing.def)));
338
+ existing.setProps(withPreparedStructureProps(element, resolveProps(propsDecl, reader, existing.def, this.defaultsFor(existing.def)), propsDecl));
328
339
  return;
329
340
  }
330
341
 
331
342
  const def = this.registry.get(name);
332
- this.expander.expand(element, def);
343
+ this.expandHost(element, def, propsDecl);
333
344
  const child = new SomaComponentInstance({
334
345
  host: element,
335
346
  instanceId: childId,
336
347
  def,
337
- initialProps: resolveProps(propsDecl, reader, def, this.defaultsFor(def)),
348
+ initialProps: withPreparedStructureProps(element, resolveProps(propsDecl, reader, def, this.defaultsFor(def)), propsDecl),
338
349
  scheduler: this.scheduler,
339
350
  diagnostics: this.diagnostics,
340
351
  pipeRegistry: this.pipeRegistry,
@@ -384,11 +395,66 @@ export class SomaComponentManager {
384
395
  );
385
396
  }
386
397
  for (const host of pending) {
387
- this.expander.expand(host, this.registry.get(host.getAttribute(SOMA_COMPONENT_ATTR)!));
398
+ const owner = this.preparedDefinitions.get(host.getAttribute(SOMA_SCOPE_ATTR) ?? '');
399
+ const childId = host.getAttribute(SOMA_CHILD_COMPONENT_ID_ATTR)!;
400
+ const props = owner?.uiConfig ? collectPagePropsDecls(owner.uiConfig.show).get(childId) : undefined;
401
+ this.expandHost(host, this.registry.get(host.getAttribute(SOMA_COMPONENT_ATTR)!), props ?? {});
388
402
  }
389
403
  }
390
404
  }
391
405
 
406
+ private expandHost(host: HTMLElement, def: SomaComponentDefinition, props: Record<string, unknown>): void {
407
+ this.assertDefinitionPrepared(def);
408
+ let plan: StructurePlan | undefined;
409
+ const symbol = host.getAttribute('data-soma-id');
410
+ if (this.treeArtifact && symbol) {
411
+ const plans = this.treeArtifact.structurePlan.filter(item => item.instanceSymbol === symbol);
412
+ if (plans.length !== 1) this.artifactError('组件宿主没有唯一结构计划');
413
+ plan = plans[0];
414
+ const ref = this.treeArtifact.componentRefs.find(item => item.name === def.contract.name);
415
+ if (!ref || !def.structureDigest || !def.contractDigest
416
+ || ref.structureDigest !== def.structureDigest || ref.contractDigest !== def.contractDigest
417
+ || plan.structureDigest !== def.structureDigest) this.artifactError('组件供货摘要与结构资产不一致');
418
+ }
419
+ const staticProp = def.contract.structure?.semantics?.staticProp;
420
+ if (staticProp && Object.prototype.hasOwnProperty.call(this.defaultsFor(def) ?? {}, staticProp)) {
421
+ this.artifactError('Host 默认值不得覆盖结构语义属性');
422
+ }
423
+ const scope = this.expander.expand(host, def, plan, props);
424
+ this.preparedDefinitions.set(scope, def);
425
+ }
426
+
427
+ private assertDefinitionPrepared(def: SomaComponentDefinition): void {
428
+ const plans = def.definitionRepeatPlans;
429
+ const references = new Set<string>();
430
+ const hasCollectionSource = (show: ShowMapping | undefined): boolean => Object.values(show ?? {}).some(value => {
431
+ if (!value || typeof value !== 'object') return false;
432
+ if (isNested(value) && value.bind.repeatPlanId) references.add(value.bind.repeatPlanId);
433
+ return (isNested(value) && value.bind.collectionSlot !== undefined) || hasCollectionSource(value.show);
434
+ });
435
+ if (hasCollectionSource(def.uiConfig?.show)) this.artifactError('组件内部 collectionSlot 必须在构建时准备为计划');
436
+ if (references.size !== (plans?.length ?? 0) || plans?.some(plan => !references.has(plan.planId) || plan.definitionName !== def.contract.name)) {
437
+ this.artifactError('组件集合绑定与准备计划未完整一一对应');
438
+ }
439
+ if (!plans?.length && !def.definitionPreparation) return;
440
+ const prep = def.definitionPreparation;
441
+ if (prep) assertDefinitionPreparation(prep);
442
+ if (!prep || prep.schemaVersion !== 1 || !prep.definitionDigest
443
+ || (plans?.length && ['definition-repeat:1', 'repeat-range:1', 'row-bindings:1'].some(capability => !prep.requiredCapabilities.some(value => value === capability)))
444
+ || prep.requiredCapabilities.some(capability => !COMPONENT_TREE_CAPABILITIES.includes(capability))) {
445
+ this.artifactError('组件定义准备封套或运行时能力不兼容');
446
+ }
447
+ for (const [name, digest] of Object.entries(prep.dependencyDigests)) {
448
+ if (!this.registry.has(name) || !digest || this.registry.get(name).structureDigest !== digest) {
449
+ this.artifactError('组件定义准备依赖摘要失效');
450
+ }
451
+ }
452
+ }
453
+
454
+ private artifactError(fixHint: string): never {
455
+ throw new SomaComponentTreeError({ code: 'CT-ARTIFACT-CAPABILITY', phase: 'runtime', sourceId: 'runtime', nodePath: 'component', fixHint });
456
+ }
457
+
392
458
  private createChildReader(parent: SomaComponentInstance, rowData: unknown): ScopeReader {
393
459
  return {
394
460
  read: (path: string) => parent.read(path, rowData),
@@ -473,6 +539,10 @@ export class SomaComponentManager {
473
539
  }
474
540
 
475
541
  private createRowReader(page: SomaComponentPageRuntime, rowData: unknown): ScopeReader {
542
+ if (rowData instanceof SomaRowScope) return {
543
+ read: path => rowData.read(path, value => page.resolver.readFromRoot(page.resolver.resolvePath(value))),
544
+ hasVar: seg => rowData.has(seg) || page.resolver.hasVar(seg),
545
+ };
476
546
  return {
477
547
  read: (path: string) => {
478
548
  const segments = path.split('.');
@@ -503,7 +573,7 @@ export class SomaComponentManager {
503
573
  for (const path of paths) {
504
574
  const resolved = page.resolver.resolvePath(path);
505
575
  const dispose = page.renderEngine.watch(resolved, () => {
506
- instance.setProps(resolveProps(decl.propsDecl, reader, decl.def));
576
+ instance.setProps(withPreparedStructureProps(decl.host, resolveProps(decl.propsDecl, reader, decl.def), decl.propsDecl));
507
577
  });
508
578
  this.watchDisposers.push(dispose);
509
579
  }
@@ -562,8 +632,11 @@ export class SomaComponentInstance {
562
632
  }> = [];
563
633
  private readonly mountChild: SomaComponentInstanceOptions['mountChild'];
564
634
  private readonly styleOptions?: PackStyleOptions;
635
+ private readonly host: HTMLElement;
565
636
 
566
637
  constructor(options: SomaComponentInstanceOptions) {
638
+ this.host = options.host;
639
+ assertPreparedStructureProps(options.host, options.initialProps);
567
640
  this.def = options.def;
568
641
  this.mountChild = options.mountChild;
569
642
  this.styleOptions = options.styleOptions;
@@ -617,6 +690,7 @@ export class SomaComponentInstance {
617
690
  markChildEmitRoutes(options.host, this.manifest, options.registry, scopeId);
618
691
 
619
692
  this.renderEngine = new SomaRenderEngine({
693
+ repeatPlans: options.def.definitionRepeatPlans,
620
694
  container: options.host,
621
695
  adapter,
622
696
  manifest: this.manifest,
@@ -725,6 +799,7 @@ export class SomaComponentInstance {
725
799
  if (this.destroyed) {
726
800
  return;
727
801
  }
802
+ assertPreparedStructureProps(this.host, next);
728
803
  for (const [key, value] of Object.entries(next)) {
729
804
  if (key === SOMA_COMPONENT_CTRL_KEY) {
730
805
  continue;
@@ -751,8 +826,16 @@ export class SomaComponentInstance {
751
826
  return this.scopeRoot;
752
827
  }
753
828
 
829
+ /** Internal lifecycle ordering: children must release while their DOM is still attached. */
830
+ getHost(): HTMLElement {
831
+ return this.host;
832
+ }
833
+
754
834
  /** 父实例作用域读取;rowData 存在时与列表行内组件的求值语义一致。 */
755
835
  read(path: string, rowData?: unknown): unknown {
836
+ if (rowData instanceof SomaRowScope) {
837
+ return rowData.read(path, value => this.resolver.readFromRoot(this.resolver.resolvePath(value)));
838
+ }
756
839
  const segments = path.split('.');
757
840
  const first = segments[0];
758
841
  if (rowData !== undefined && this.resolver.hasVar(first) && first !== 'p' && first !== 'ctrl') {
@@ -905,7 +988,11 @@ function resolveProps(
905
988
  }
906
989
 
907
990
  for (const [propName, declValue] of Object.entries(propsDecl)) {
908
- result[propName] = resolvePropValue(declValue, reader);
991
+ const field = def.contract.props?.[propName];
992
+ // Closed enum tokens are literals even when named page/p/ctrl. A path
993
+ // remains a path only when it is not one of the declared tokens.
994
+ result[propName] = field?.type === 'enum' && field.values?.some(value => value === declValue)
995
+ ? declValue : resolvePropValue(declValue, reader);
909
996
  }
910
997
  return result;
911
998
  }
@@ -919,13 +1006,13 @@ function collectPagePropsDecls(
919
1006
  if (typeof value === 'string' || value === null || typeof value !== 'object') {
920
1007
  continue;
921
1008
  }
922
- if (isNested(value)) {
923
- continue; // 行作用域内的 props 由渲染钩子按行处理
924
- }
925
1009
  const extended = value as ExtendedShowValue;
926
1010
  if (extended.props) {
927
1011
  into.set(rawKey.split('@')[0], extended.props);
928
1012
  }
1013
+ if (isNested(value)) {
1014
+ continue; // Own props belong to the consumer; child show belongs to its rows.
1015
+ }
929
1016
  if (extended.show) {
930
1017
  collectPagePropsDecls(extended.show, into);
931
1018
  }
@@ -20,7 +20,16 @@ export class SomaComponentRegistry {
20
20
  if (!contract?.name) {
21
21
  throw new SomaComponentRegistryError('契约缺少 name');
22
22
  }
23
- if (!def.templateHtml) {
23
+ const macro = contract.structure?.kind === 'fragment-macro';
24
+ if (macro && (contract.structure?.tree_mount !== 'erase' || !contract.structure.rootless
25
+ || typeof def.templateHtml !== 'string' || def.templateHtml.trim() || def.controllerFactory || def.uiConfig || def.eventConfig?.length
26
+ || Object.keys(contract.props ?? {}).length || Object.keys(contract.emits ?? {}).length
27
+ || def.services?.length || def.definitionRepeatPlans?.length || Object.keys(def.styleFeatures ?? {}).length
28
+ || contract.keyboard || contract.overlay || contract.structure.semantics || contract.uses?.length
29
+ || !contract.slots?.content?.required || Object.keys(contract.slots).length !== 1)) {
30
+ throw new SomaComponentRegistryError(`组件 "${contract.name}" 的 fragment-macro 含运行时行为`);
31
+ }
32
+ if (!def.templateHtml && !macro) {
24
33
  throw new SomaComponentRegistryError(`组件 "${contract.name}" 缺少 templateHtml`);
25
34
  }
26
35
  if (contract.props && SOMA_COMPONENT_CTRL_KEY in contract.props) {
@@ -20,6 +20,21 @@ export const SOMA_SCOPED_ID_ATTR = 'data-soma-scoped-id';
20
20
  /** 锚点的作用域归属标记(展开器写入,值为该次展开的 scopeId) */
21
21
  export const SOMA_SCOPE_ATTR = 'data-soma-scope';
22
22
 
23
+ // A shared physical host keeps its parent/row DOM identity. Its own internal
24
+ // root is an instance-local alias, never a second set of DOM scope attributes.
25
+ const rootAliases = new WeakMap<HTMLElement, { scopeId: string; anchorId: string }>();
26
+
27
+ export function registerSomaRootAlias(host: HTMLElement, scopeId: string, anchorId: string): void {
28
+ rootAliases.set(host, { scopeId, anchorId });
29
+ }
30
+
31
+ /** Supports roots/events from a different window and server DOMs without global constructors. */
32
+ function isHtmlElement(value: unknown): value is HTMLElement {
33
+ const element = value as Element | null;
34
+ return element?.nodeType === 1 && element.namespaceURI === 'http://www.w3.org/1999/xhtml'
35
+ && typeof element.getAttribute === 'function';
36
+ }
37
+
23
38
  export class SomaScopedContainerAdapter extends SomaContainerAdapter {
24
39
  /** 本适配器认领的作用域;undefined = 认所有 scoped 锚点 */
25
40
  private readonly scopeId?: string;
@@ -45,17 +60,23 @@ export class SomaScopedContainerAdapter extends SomaContainerAdapter {
45
60
  }
46
61
 
47
62
  findAnchor(root: ParentNode, somaId: string): HTMLElement | null {
63
+ if (isHtmlElement(root) && this.getAnchorId(root) === somaId) return root;
48
64
  return root.querySelector<HTMLElement>(this.anchorSelector(somaId));
49
65
  }
50
66
 
51
67
  findClosestAnchor(target: EventTarget | null): HTMLElement | null {
52
- if (!(target instanceof HTMLElement)) {
68
+ if (!isHtmlElement(target)) {
53
69
  return null;
54
70
  }
55
- return target.closest<HTMLElement>(this.anyAnchorSelector);
71
+ for (let element: HTMLElement | null = target; element; element = element.parentElement) {
72
+ if (this.getAnchorId(element) !== null) return element;
73
+ }
74
+ return null;
56
75
  }
57
76
 
58
77
  getAnchorId(element: HTMLElement): string | null {
78
+ const alias = rootAliases.get(element);
79
+ if (alias && alias.scopeId === this.scopeId) return alias.anchorId;
59
80
  if (this.scopeId && element.getAttribute(SOMA_SCOPE_ATTR) !== this.scopeId) {
60
81
  return null;
61
82
  }
@@ -66,6 +87,12 @@ export class SomaScopedContainerAdapter extends SomaContainerAdapter {
66
87
  const anchors = new Set<string>();
67
88
  const counts = new Map<string, number>();
68
89
 
90
+ const rootId = this.getAnchorId(container);
91
+ if (rootId) {
92
+ anchors.add(rootId);
93
+ counts.set(rootId, 1);
94
+ }
95
+
69
96
  container.querySelectorAll<HTMLElement>(this.anyAnchorSelector).forEach((element) => {
70
97
  const somaId = element.getAttribute(SOMA_SCOPED_ID_ATTR);
71
98
  if (!somaId) return;