soma-core 1.5.0 → 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 (133) 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/layout/css-emitter.ts +14 -1
  25. package/core/build/lsp/component-tree-service.ts +79 -0
  26. package/core/build/lsp/component-tree.cjs +42 -0
  27. package/core/build/lsp/cross-file-diagnostics.cjs +15 -3
  28. package/core/build/lsp/extra-completion.cjs +7 -0
  29. package/core/client/compiler/manifest-compiler.ts +2 -0
  30. package/core/client/component/ai-catalog.ts +41 -3
  31. package/core/client/component/catalog-examples.ts +60 -0
  32. package/core/client/component/component-definition.types.ts +9 -0
  33. package/core/client/component/component-expander.ts +39 -8
  34. package/core/client/component/component-manager.ts +107 -16
  35. package/core/client/component/component-registry.ts +10 -1
  36. package/core/client/component/scoped-adapter.ts +29 -2
  37. package/core/client/component/structure-adapter.ts +207 -0
  38. package/core/client/component/verify-pack.ts +64 -1
  39. package/core/client/engine/asset-resolver.ts +1 -1
  40. package/core/client/engine/dom-renderer.ts +283 -0
  41. package/core/client/engine/event-engine.ts +28 -9
  42. package/core/client/engine/render-engine.ts +2 -0
  43. package/core/client/engine/row-range.ts +62 -0
  44. package/core/client/engine/row-scope.ts +77 -0
  45. package/core/client/engine/runtime-builder.ts +2 -0
  46. package/core/client/engine/soma-bootstrap.ts +146 -1
  47. package/core/client/parser/blocks/page-parser.ts +9 -2
  48. package/core/client/parser/ui-config-parser.ts +38 -6
  49. package/core/client/registry/declaration-renderer.ts +32 -24
  50. package/core/client/registry/remote-page.ts +1 -1
  51. package/core/client/theme/theme-engine.ts +61 -1
  52. package/core/client/validation/contract-validator.ts +1 -1
  53. package/core/index.ts +9 -1
  54. package/core/server/host/page-markup-config.ts +42 -0
  55. package/core/server/host/published-page-artifact-cache.ts +36 -4
  56. package/core/server/host/published-page-assets.ts +13 -7
  57. package/core/server/host/resolve-host-tree-context.ts +43 -0
  58. package/core/server/host/server-page-assets.ts +23 -4
  59. package/core/server/host/soma-page-compile.ts +10 -0
  60. package/core/server/page-declaration.ts +7 -0
  61. package/core/server/registry/declaration-precompiler.ts +35 -3
  62. package/core/server/registry/page-registry-repository.ts +31 -3
  63. package/core/server/registry/page-registry-store.ts +64 -7
  64. package/core/server/registry/publish-asset-pin.ts +6 -1
  65. package/core/server/registry/services/pages/Get.ts +11 -6
  66. package/core/server/registry/validation/compile-gate.ts +10 -1
  67. package/core/shared/component-tree-artifact.ts +237 -0
  68. package/core/shared/component-tree-errors.ts +52 -0
  69. package/core/shared/types/component-contract.types.ts +51 -0
  70. package/core/shared/types/component-tree-artifact.types.ts +121 -0
  71. package/core/shared/types/component-tree.types.ts +170 -0
  72. package/core/shared/types/engine.types.ts +5 -0
  73. package/core/shared/types/manifest.types.ts +4 -0
  74. package/core/shared/types/ui-config.types.ts +8 -0
  75. package/dist/cli/soma.js +1 -1
  76. package/dist/core/index.cjs +1976 -692
  77. package/dist/lsp/component-tree.cjs +20807 -0
  78. package/dist/types/build/blocks/block-compile.d.ts +10 -1
  79. package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
  80. package/dist/types/build/compiler/page-assets.d.ts +6 -1
  81. package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
  82. package/dist/types/build/component/package-loader.d.ts +4 -1
  83. package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
  84. package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
  85. package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
  86. package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
  87. package/dist/types/build/component-tree/migration-files.d.ts +35 -0
  88. package/dist/types/build/component-tree/migration.d.ts +28 -0
  89. package/dist/types/build/component-tree/parser.d.ts +13 -0
  90. package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
  91. package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
  92. package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
  93. package/dist/types/build/component-tree/validator.d.ts +9 -0
  94. package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
  95. package/dist/types/client/component/ai-catalog.d.ts +18 -1
  96. package/dist/types/client/component/catalog-examples.d.ts +18 -0
  97. package/dist/types/client/component/component-definition.types.d.ts +9 -0
  98. package/dist/types/client/component/component-expander.d.ts +3 -1
  99. package/dist/types/client/component/component-manager.d.ts +11 -0
  100. package/dist/types/client/component/scoped-adapter.d.ts +1 -0
  101. package/dist/types/client/component/structure-adapter.d.ts +17 -0
  102. package/dist/types/client/engine/dom-renderer.d.ts +15 -0
  103. package/dist/types/client/engine/event-engine.d.ts +1 -0
  104. package/dist/types/client/engine/render-engine.d.ts +1 -0
  105. package/dist/types/client/engine/row-range.d.ts +13 -0
  106. package/dist/types/client/engine/row-scope.d.ts +20 -0
  107. package/dist/types/client/engine/runtime-builder.d.ts +1 -0
  108. package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
  109. package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
  110. package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
  111. package/dist/types/client/registry/remote-page.d.ts +1 -1
  112. package/dist/types/index.d.ts +3 -2
  113. package/dist/types/server/host/page-markup-config.d.ts +6 -0
  114. package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
  115. package/dist/types/server/host/published-page-assets.d.ts +5 -3
  116. package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
  117. package/dist/types/server/host/server-page-assets.d.ts +6 -0
  118. package/dist/types/server/host/soma-page-compile.d.ts +10 -1
  119. package/dist/types/server/page-declaration.d.ts +6 -0
  120. package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
  121. package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
  122. package/dist/types/server/registry/page-registry-store.d.ts +11 -1
  123. package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
  124. package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
  125. package/dist/types/shared/component-tree-artifact.d.ts +5 -0
  126. package/dist/types/shared/component-tree-errors.d.ts +22 -0
  127. package/dist/types/shared/types/component-contract.types.d.ts +42 -0
  128. package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
  129. package/dist/types/shared/types/component-tree.types.d.ts +149 -0
  130. package/dist/types/shared/types/engine.types.d.ts +5 -0
  131. package/dist/types/shared/types/manifest.types.d.ts +4 -0
  132. package/dist/types/shared/types/ui-config.types.d.ts +8 -0
  133. package/package.json +3 -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
  // 此刻宿主子树里的锚点,恰好就是"本组件模板写下的"全集——包括写在
@@ -71,19 +75,35 @@ export class SomaComponentExpander {
71
75
  this.scopeAnchors(host, scopeId);
72
76
 
73
77
  // 4. 插槽投影:出口替换为页面内容(页面锚点保持 data-soma-id,归页面作用域)
74
- const outlets = Array.from(
75
- host.querySelectorAll<HTMLElement>(`[${SOMA_SLOT_OUTLET_ATTR}]`),
76
- );
78
+ // A composite component may place another slotted component in its own
79
+ // template. `querySelectorAll` does not cross HTMLTemplateElement
80
+ // boundaries, so only looking at the live DOM misses the child's outlet;
81
+ // the parent slot is then reported as an unknown slot even though the
82
+ // child is the intended projection target (for example ThemeScope).
83
+ // Walk template contents as well, while keeping the actual projection
84
+ // order stable for multiple outlets.
85
+ const outlets = this.collectSlotOutlets(host);
77
86
  for (const outlet of outlets) {
78
87
  const slotName = outlet.getAttribute(SOMA_SLOT_OUTLET_ATTR)!;
79
88
  const content = slotContent.get(slotName);
80
- 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);
81
96
  if (def.contract.slots?.[slotName]?.required) {
82
97
  throw new SomaComponentExpandError(
83
98
  `组件 "${def.contract.name}" 的必填插槽 "${slotName}" 缺少内容(<template data-soma-slot="${slotName}">)`,
84
99
  );
85
100
  }
86
- 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();
87
107
  continue;
88
108
  }
89
109
  outlet.replaceWith(content);
@@ -97,6 +117,7 @@ export class SomaComponentExpander {
97
117
  }
98
118
 
99
119
  host.setAttribute(SOMA_COMPONENT_READY_ATTR, scopeId);
120
+ registerPreparedStructure(host, def, scopeId, prepared.staticProps);
100
121
  return scopeId;
101
122
  }
102
123
 
@@ -116,4 +137,14 @@ export class SomaComponentExpander {
116
137
  this.scopeAnchors(tpl.content, scopeId);
117
138
  });
118
139
  }
140
+
141
+ private collectSlotOutlets(root: ParentNode): HTMLElement[] {
142
+ const outlets = Array.from(
143
+ root.querySelectorAll<HTMLElement>(`[${SOMA_SLOT_OUTLET_ATTR}]`),
144
+ );
145
+ for (const template of Array.from(root.querySelectorAll<HTMLTemplateElement>('template'))) {
146
+ outlets.push(...this.collectSlotOutlets(template.content));
147
+ }
148
+ return outlets;
149
+ }
119
150
  }
@@ -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,11 @@ 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) ?? {});
152
+ // 组合组件的子组件也必须在页面契约校验前展开。否则子组件模板
153
+ // 里的 data-soma-host 仍封在 template.content 中,页面会误报
154
+ // "缺少 data-soma-host 边界";实例挂载阶段再展开已经太晚。
155
+ this.expandNestedTemplates(host);
142
156
  this.staticDecls.push({
143
157
  host,
144
158
  instanceId,
@@ -196,7 +210,8 @@ export class SomaComponentManager {
196
210
  dispose();
197
211
  }
198
212
  this.watchDisposers.length = 0;
199
- 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) {
200
215
  instance.destroy();
201
216
  }
202
217
  this.instances.clear();
@@ -222,12 +237,12 @@ export class SomaComponentManager {
222
237
  return;
223
238
  }
224
239
  // 被摘除的行根元素自己就可能是组件宿主(行模板根 = 组件)
225
- this.releaseHost(root);
226
240
  for (const host of Array.from(
227
241
  root.querySelectorAll<HTMLElement>(`[${SOMA_COMPONENT_ATTR}]`),
228
- )) {
242
+ ).reverse()) {
229
243
  this.releaseHost(host);
230
244
  }
245
+ this.releaseHost(root);
231
246
  }
232
247
 
233
248
  private releaseHost(host: HTMLElement): void {
@@ -259,7 +274,7 @@ export class SomaComponentManager {
259
274
  const reader = this.createRowReader(this.page, rowData);
260
275
  const existing = this.hostInstances.get(element);
261
276
  if (existing) {
262
- 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));
263
278
  return;
264
279
  }
265
280
 
@@ -268,7 +283,7 @@ export class SomaComponentManager {
268
283
  throw new SomaComponentExpandError(`组件 "${name}" 的宿主元素缺少 data-soma-id`);
269
284
  }
270
285
  const def = this.registry.get(name);
271
- this.expander.expand(element, def);
286
+ this.expandHost(element, def, propsDecl);
272
287
  this.mountInstance(element, instanceId, def, propsDecl, reader);
273
288
  }
274
289
 
@@ -285,7 +300,7 @@ export class SomaComponentManager {
285
300
  host,
286
301
  instanceId,
287
302
  def,
288
- initialProps: resolveProps(propsDecl, reader, def, this.defaultsFor(def)),
303
+ initialProps: withPreparedStructureProps(host, resolveProps(propsDecl, reader, def, this.defaultsFor(def)), propsDecl),
289
304
  scheduler: this.scheduler,
290
305
  diagnostics: this.diagnostics,
291
306
  pipeRegistry: this.pipeRegistry,
@@ -320,17 +335,17 @@ export class SomaComponentManager {
320
335
  const reader = this.createChildReader(parent, rowData);
321
336
  const existing = this.hostInstances.get(element);
322
337
  if (existing) {
323
- 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));
324
339
  return;
325
340
  }
326
341
 
327
342
  const def = this.registry.get(name);
328
- this.expander.expand(element, def);
343
+ this.expandHost(element, def, propsDecl);
329
344
  const child = new SomaComponentInstance({
330
345
  host: element,
331
346
  instanceId: childId,
332
347
  def,
333
- initialProps: resolveProps(propsDecl, reader, def, this.defaultsFor(def)),
348
+ initialProps: withPreparedStructureProps(element, resolveProps(propsDecl, reader, def, this.defaultsFor(def)), propsDecl),
334
349
  scheduler: this.scheduler,
335
350
  diagnostics: this.diagnostics,
336
351
  pipeRegistry: this.pipeRegistry,
@@ -380,11 +395,66 @@ export class SomaComponentManager {
380
395
  );
381
396
  }
382
397
  for (const host of pending) {
383
- 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 ?? {});
384
402
  }
385
403
  }
386
404
  }
387
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
+
388
458
  private createChildReader(parent: SomaComponentInstance, rowData: unknown): ScopeReader {
389
459
  return {
390
460
  read: (path: string) => parent.read(path, rowData),
@@ -469,6 +539,10 @@ export class SomaComponentManager {
469
539
  }
470
540
 
471
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
+ };
472
546
  return {
473
547
  read: (path: string) => {
474
548
  const segments = path.split('.');
@@ -499,7 +573,7 @@ export class SomaComponentManager {
499
573
  for (const path of paths) {
500
574
  const resolved = page.resolver.resolvePath(path);
501
575
  const dispose = page.renderEngine.watch(resolved, () => {
502
- instance.setProps(resolveProps(decl.propsDecl, reader, decl.def));
576
+ instance.setProps(withPreparedStructureProps(decl.host, resolveProps(decl.propsDecl, reader, decl.def), decl.propsDecl));
503
577
  });
504
578
  this.watchDisposers.push(dispose);
505
579
  }
@@ -558,8 +632,11 @@ export class SomaComponentInstance {
558
632
  }> = [];
559
633
  private readonly mountChild: SomaComponentInstanceOptions['mountChild'];
560
634
  private readonly styleOptions?: PackStyleOptions;
635
+ private readonly host: HTMLElement;
561
636
 
562
637
  constructor(options: SomaComponentInstanceOptions) {
638
+ this.host = options.host;
639
+ assertPreparedStructureProps(options.host, options.initialProps);
563
640
  this.def = options.def;
564
641
  this.mountChild = options.mountChild;
565
642
  this.styleOptions = options.styleOptions;
@@ -613,6 +690,7 @@ export class SomaComponentInstance {
613
690
  markChildEmitRoutes(options.host, this.manifest, options.registry, scopeId);
614
691
 
615
692
  this.renderEngine = new SomaRenderEngine({
693
+ repeatPlans: options.def.definitionRepeatPlans,
616
694
  container: options.host,
617
695
  adapter,
618
696
  manifest: this.manifest,
@@ -721,6 +799,7 @@ export class SomaComponentInstance {
721
799
  if (this.destroyed) {
722
800
  return;
723
801
  }
802
+ assertPreparedStructureProps(this.host, next);
724
803
  for (const [key, value] of Object.entries(next)) {
725
804
  if (key === SOMA_COMPONENT_CTRL_KEY) {
726
805
  continue;
@@ -747,8 +826,16 @@ export class SomaComponentInstance {
747
826
  return this.scopeRoot;
748
827
  }
749
828
 
829
+ /** Internal lifecycle ordering: children must release while their DOM is still attached. */
830
+ getHost(): HTMLElement {
831
+ return this.host;
832
+ }
833
+
750
834
  /** 父实例作用域读取;rowData 存在时与列表行内组件的求值语义一致。 */
751
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
+ }
752
839
  const segments = path.split('.');
753
840
  const first = segments[0];
754
841
  if (rowData !== undefined && this.resolver.hasVar(first) && first !== 'p' && first !== 'ctrl') {
@@ -901,7 +988,11 @@ function resolveProps(
901
988
  }
902
989
 
903
990
  for (const [propName, declValue] of Object.entries(propsDecl)) {
904
- 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);
905
996
  }
906
997
  return result;
907
998
  }
@@ -915,13 +1006,13 @@ function collectPagePropsDecls(
915
1006
  if (typeof value === 'string' || value === null || typeof value !== 'object') {
916
1007
  continue;
917
1008
  }
918
- if (isNested(value)) {
919
- continue; // 行作用域内的 props 由渲染钩子按行处理
920
- }
921
1009
  const extended = value as ExtendedShowValue;
922
1010
  if (extended.props) {
923
1011
  into.set(rawKey.split('@')[0], extended.props);
924
1012
  }
1013
+ if (isNested(value)) {
1014
+ continue; // Own props belong to the consumer; child show belongs to its rows.
1015
+ }
925
1016
  if (extended.show) {
926
1017
  collectPagePropsDecls(extended.show, into);
927
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;