soma-core 1.5.1 → 2.0.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 (173) 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 +212 -21
  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/eject/component-eject.ts +1 -0
  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/adaptive/observer-pool.ts +122 -8
  30. package/core/client/compiler/manifest-compiler.ts +48 -5
  31. package/core/client/component/ai-catalog.ts +41 -3
  32. package/core/client/component/catalog-examples.ts +60 -0
  33. package/core/client/component/component-defaults.ts +1 -1
  34. package/core/client/component/component-definition.types.ts +9 -0
  35. package/core/client/component/component-expander.ts +22 -6
  36. package/core/client/component/component-manager.ts +881 -45
  37. package/core/client/component/component-pack.ts +1 -1
  38. package/core/client/component/component-registry.ts +11 -2
  39. package/core/client/component/scoped-adapter.ts +29 -2
  40. package/core/client/component/structure-adapter.ts +207 -0
  41. package/core/client/component/verify-pack.ts +21 -1
  42. package/core/client/container/SomaContainerAdapter.ts +103 -2
  43. package/core/client/data/data-object-resolver.ts +45 -1
  44. package/core/client/engine/asset-resolver.ts +1 -1
  45. package/core/client/engine/dom-renderer.ts +712 -26
  46. package/core/client/engine/event-engine.ts +328 -21
  47. package/core/client/engine/property-watcher.ts +164 -18
  48. package/core/client/engine/reactive-proxy.ts +194 -23
  49. package/core/client/engine/render-engine.ts +120 -11
  50. package/core/client/engine/row-range.ts +62 -0
  51. package/core/client/engine/row-scope.ts +77 -0
  52. package/core/client/engine/runtime-builder.ts +2 -0
  53. package/core/client/engine/scope-resolver.ts +3 -3
  54. package/core/client/engine/soma-bootstrap.ts +176 -17
  55. package/core/client/parser/adaptive-parser.ts +1 -1
  56. package/core/client/parser/annotation-extractor.ts +1 -1
  57. package/core/client/parser/blocks/page-parser.ts +53 -3
  58. package/core/client/parser/blocks/use-parser.ts +21 -6
  59. package/core/client/parser/data-config-parser.ts +1 -1
  60. package/core/client/parser/pipeline-parser.ts +252 -15
  61. package/core/client/parser/style-config-parser.ts +1 -1
  62. package/core/client/parser/timer-parser.ts +1 -1
  63. package/core/client/parser/trigger-parser.ts +1 -1
  64. package/core/client/parser/ui-config-parser.ts +39 -7
  65. package/core/client/pipes/pipe-registry.ts +45 -4
  66. package/core/client/registry/declaration-renderer.ts +32 -24
  67. package/core/client/registry/remote-page.ts +1 -1
  68. package/core/client/runtime/SomaSnapshotStore.ts +1 -1
  69. package/core/client/scheduler/SomaScheduler.ts +1 -1
  70. package/core/client/security/attribute-presence.ts +3 -0
  71. package/core/client/theme/harmony.ts +135 -13
  72. package/core/client/theme/scene-tokens.ts +17 -2
  73. package/core/client/theme/theme-axes.ts +43 -6
  74. package/core/client/theme/theme-engine.ts +921 -126
  75. package/core/client/validation/contract-validator.ts +2 -2
  76. package/core/index.ts +3 -0
  77. package/core/server/host/page-markup-config.ts +42 -0
  78. package/core/server/host/published-page-artifact-cache.ts +36 -4
  79. package/core/server/host/published-page-assets.ts +13 -7
  80. package/core/server/host/resolve-host-tree-context.ts +43 -0
  81. package/core/server/host/server-page-assets.ts +23 -4
  82. package/core/server/host/soma-page-compile.ts +10 -0
  83. package/core/server/mock/node/cli.mjs +3 -3
  84. package/core/server/page-declaration.ts +7 -0
  85. package/core/server/registry/declaration-precompiler.ts +35 -3
  86. package/core/server/registry/page-registry-repository.ts +31 -3
  87. package/core/server/registry/page-registry-store.ts +64 -7
  88. package/core/server/registry/publish-asset-pin.ts +6 -1
  89. package/core/server/registry/services/pages/Get.ts +11 -6
  90. package/core/server/registry/validation/compile-gate.ts +10 -1
  91. package/core/shared/component-tree-artifact.ts +237 -0
  92. package/core/shared/component-tree-errors.ts +52 -0
  93. package/core/shared/path-algebra.ts +1 -1
  94. package/core/shared/types/component-contract.types.ts +51 -0
  95. package/core/shared/types/component-tree-artifact.types.ts +121 -0
  96. package/core/shared/types/component-tree.types.ts +170 -0
  97. package/core/shared/types/engine.types.ts +5 -0
  98. package/core/shared/types/event.types.ts +8 -4
  99. package/core/shared/types/manifest.types.ts +4 -0
  100. package/core/shared/types/ui-config.types.ts +8 -0
  101. package/dist/cli/soma.js +1 -1
  102. package/dist/core/index.cjs +14508 -11358
  103. package/dist/lsp/component-tree.cjs +20997 -0
  104. package/dist/types/build/blocks/block-compile.d.ts +10 -1
  105. package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
  106. package/dist/types/build/compiler/page-assets.d.ts +6 -1
  107. package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
  108. package/dist/types/build/component/package-loader.d.ts +4 -1
  109. package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
  110. package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
  111. package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
  112. package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
  113. package/dist/types/build/component-tree/migration-files.d.ts +35 -0
  114. package/dist/types/build/component-tree/migration.d.ts +28 -0
  115. package/dist/types/build/component-tree/parser.d.ts +13 -0
  116. package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
  117. package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
  118. package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
  119. package/dist/types/build/component-tree/validator.d.ts +9 -0
  120. package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
  121. package/dist/types/client/adaptive/observer-pool.d.ts +9 -2
  122. package/dist/types/client/compiler/manifest-compiler.d.ts +11 -2
  123. package/dist/types/client/component/ai-catalog.d.ts +18 -1
  124. package/dist/types/client/component/catalog-examples.d.ts +18 -0
  125. package/dist/types/client/component/component-definition.types.d.ts +9 -0
  126. package/dist/types/client/component/component-expander.d.ts +2 -1
  127. package/dist/types/client/component/component-manager.d.ts +97 -0
  128. package/dist/types/client/component/scoped-adapter.d.ts +1 -0
  129. package/dist/types/client/component/structure-adapter.d.ts +17 -0
  130. package/dist/types/client/container/SomaContainerAdapter.d.ts +8 -0
  131. package/dist/types/client/data/data-object-resolver.d.ts +19 -0
  132. package/dist/types/client/engine/dom-renderer.d.ts +125 -2
  133. package/dist/types/client/engine/event-engine.d.ts +62 -3
  134. package/dist/types/client/engine/property-watcher.d.ts +41 -1
  135. package/dist/types/client/engine/reactive-proxy.d.ts +42 -2
  136. package/dist/types/client/engine/render-engine.d.ts +55 -3
  137. package/dist/types/client/engine/row-range.d.ts +13 -0
  138. package/dist/types/client/engine/row-scope.d.ts +20 -0
  139. package/dist/types/client/engine/runtime-builder.d.ts +1 -0
  140. package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
  141. package/dist/types/client/parser/blocks/use-parser.d.ts +18 -0
  142. package/dist/types/client/parser/pipeline-parser.d.ts +12 -4
  143. package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
  144. package/dist/types/client/pipes/pipe-registry.d.ts +39 -1
  145. package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
  146. package/dist/types/client/registry/remote-page.d.ts +1 -1
  147. package/dist/types/client/theme/harmony.d.ts +44 -2
  148. package/dist/types/client/theme/scene-tokens.d.ts +11 -1
  149. package/dist/types/client/theme/theme-axes.d.ts +36 -6
  150. package/dist/types/index.d.ts +3 -1
  151. package/dist/types/server/host/page-markup-config.d.ts +6 -0
  152. package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
  153. package/dist/types/server/host/published-page-assets.d.ts +5 -3
  154. package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
  155. package/dist/types/server/host/server-page-assets.d.ts +6 -0
  156. package/dist/types/server/host/soma-page-compile.d.ts +10 -1
  157. package/dist/types/server/page-declaration.d.ts +6 -0
  158. package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
  159. package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
  160. package/dist/types/server/registry/page-registry-store.d.ts +11 -1
  161. package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
  162. package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
  163. package/dist/types/shared/component-tree-artifact.d.ts +5 -0
  164. package/dist/types/shared/component-tree-errors.d.ts +22 -0
  165. package/dist/types/shared/types/component-contract.types.d.ts +42 -0
  166. package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
  167. package/dist/types/shared/types/component-tree.types.d.ts +149 -0
  168. package/dist/types/shared/types/engine.types.d.ts +5 -0
  169. package/dist/types/shared/types/event.types.d.ts +8 -4
  170. package/dist/types/shared/types/manifest.types.d.ts +4 -0
  171. package/dist/types/shared/types/ui-config.types.d.ts +8 -0
  172. package/package.json +5 -4
  173. package/dist/preview-export.cjs +0 -3401
@@ -0,0 +1,192 @@
1
+ import { createHash } from 'node:crypto';
2
+ import yaml from 'js-yaml';
3
+ import { parseUiConfig } from '../../client/parser/ui-config-parser';
4
+ import { compileDataConfig, compileEventConfig } from '../compiler/soma-precompile';
5
+ import { assertRuntimeArtifact } from '../../shared/component-tree-artifact';
6
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
7
+ import type { ComponentTreeRuntimeEnvelope, TreeArtifact } from '../../shared/types/component-tree-artifact.types';
8
+ import type { SomaPageMarkup, TreeCompileContext } from '../../shared/types/component-tree.types';
9
+
10
+ /** Increment whenever the tree lowering or logical artifact protocol changes. */
11
+ export const TREE_COMPILER_VERSION = 'component-tree:1.0.0';
12
+
13
+ export interface RuntimeConfigInput {
14
+ uiConfig?: unknown;
15
+ uiYaml?: string;
16
+ eventConfig?: unknown;
17
+ eventYaml?: string;
18
+ triggers?: unknown;
19
+ triggerConfig?: unknown;
20
+ timers?: unknown;
21
+ timerConfig?: unknown;
22
+ dataConfig?: unknown;
23
+ dataYaml?: string;
24
+ styleConfig?: unknown;
25
+ styleYaml?: string;
26
+ layoutCss?: string;
27
+ oouiArtifact?: unknown;
28
+ }
29
+
30
+ export interface TreeCompileKeyInput {
31
+ html: string;
32
+ uiYaml: string;
33
+ markup?: SomaPageMarkup;
34
+ grammarVersion?: number;
35
+ treeContext: TreeCompileContext;
36
+ externalBlocks?: ReadonlyMap<string, string>;
37
+ }
38
+
39
+ type Data = null | boolean | number | string | Data[] | { [key: string]: Data };
40
+ type DataRecord = { [key: string]: Data };
41
+
42
+ function fail(path: string): never {
43
+ throw new SomaComponentTreeError({
44
+ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'artifact', sourceId: '<runtime-assets>', nodePath: path,
45
+ fixHint: '运行时资产存在缺项、混合副本或非纯数据;请从同一份源与受信上下文重编。',
46
+ });
47
+ }
48
+
49
+ /** Canonical JSON: ordered keys, unchanged strings/array order, no getters or cycles. */
50
+ export function canonicalTreeData(value: unknown): Data {
51
+ const active = new Set<object>();
52
+ let nodes = 0;
53
+ const visit = (item: unknown, depth: number): Data => {
54
+ if (++nodes > 131072 || depth > 96) fail('data.limit');
55
+ if (item === null || typeof item === 'string' || typeof item === 'boolean') return item;
56
+ if (typeof item === 'number' && Number.isFinite(item)) return item;
57
+ if (!item || typeof item !== 'object' || active.has(item)) fail('data');
58
+ if (!Array.isArray(item) && ![Object.prototype, null].includes(Object.getPrototypeOf(item))) fail('data');
59
+ active.add(item);
60
+ const result: Data[] | DataRecord = Array.isArray(item) ? [] : {};
61
+ const keys = Array.isArray(item) ? Array.from({ length: item.length }, (_, i) => String(i)) : Object.keys(item).sort();
62
+ for (const key of keys) {
63
+ if (['__proto__', 'prototype', 'constructor'].includes(key)) fail('data.key');
64
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
65
+ if (!descriptor || !('value' in descriptor)) fail('data.property');
66
+ if (descriptor.value === undefined && !Array.isArray(item)) continue;
67
+ const child = visit(descriptor.value, depth + 1);
68
+ if (Array.isArray(result)) result.push(child); else result[key] = child;
69
+ }
70
+ active.delete(item);
71
+ return result;
72
+ };
73
+ return visit(value, 0);
74
+ }
75
+
76
+ export function digestTreeData(value: unknown): string {
77
+ return createHash('sha256').update(JSON.stringify(canonicalTreeData(value)), 'utf8').digest('hex');
78
+ }
79
+
80
+ function record(value: unknown): Record<string, unknown> {
81
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail('config');
82
+ return value as Record<string, unknown>;
83
+ }
84
+
85
+ function same(a: unknown, b: unknown, path: string): unknown {
86
+ if (a !== undefined && b !== undefined && digestTreeData(a) !== digestTreeData(b)) fail(path);
87
+ return a ?? b;
88
+ }
89
+
90
+ function normalizeUi(raw: unknown, input: RuntimeConfigInput): Data {
91
+ const value = record(canonicalTreeData(raw));
92
+ delete value.layout;
93
+ delete value.ooui;
94
+ const layoutCss = same(same(value.layoutCss, value.layout_css, 'ui.layoutCss'), input.layoutCss, 'layoutCss');
95
+ const oouiArtifact = same(same(value.oouiArtifact, value.ooui_artifact, 'ui.oouiArtifact'), input.oouiArtifact, 'oouiArtifact');
96
+ delete value.layoutCss;
97
+ delete value.oouiArtifact;
98
+ if (layoutCss !== undefined) value.layout_css = layoutCss;
99
+ if (oouiArtifact !== undefined) value.ooui_artifact = oouiArtifact;
100
+ return canonicalTreeData(parseUiConfig(value, { adaptiveVocabularyRequired: false }));
101
+ }
102
+
103
+ /** Pure artifact decoding. Never instantiates a Domain or falls back to Host configuration. */
104
+ export function normalizeRuntimeConfig(input: RuntimeConfigInput): Data {
105
+ try {
106
+ // Read a descriptor-only clone before invoking any parser.
107
+ const safe = record(canonicalTreeData(input)) as RuntimeConfigInput;
108
+ if (safe.styleYaml?.trim() || (safe.styleConfig !== undefined && safe.styleConfig !== null
109
+ && Object.keys(record(safe.styleConfig)).length > 0)) fail('style');
110
+ const objectUi = safe.uiConfig === undefined ? undefined : normalizeUi(safe.uiConfig, safe);
111
+ const yamlUi = safe.uiYaml === undefined ? undefined : normalizeUi(yaml.load(safe.uiYaml), safe);
112
+ const ui = same(objectUi, yamlUi, 'ui');
113
+ if (ui === undefined) fail('ui');
114
+ const triggers = same(safe.triggers, safe.triggerConfig, 'event.triggers');
115
+ const timers = same(safe.timers, safe.timerConfig, 'event.timers');
116
+ const objectEvent = safe.eventConfig === undefined ? undefined : {
117
+ events: safe.eventConfig, triggers: triggers ?? [], timers: timers ?? [],
118
+ };
119
+ if (objectEvent && (!Array.isArray(objectEvent.events) || !Array.isArray(objectEvent.triggers) || !Array.isArray(objectEvent.timers))) fail('event');
120
+ const yamlEvent = safe.eventYaml === undefined ? undefined : compileEventConfig(safe.eventYaml);
121
+ if (yamlEvent) {
122
+ same(triggers, yamlEvent.triggers, 'event.triggers');
123
+ same(timers, yamlEvent.timers, 'event.timers');
124
+ }
125
+ if (objectEvent === undefined && yamlEvent === undefined && (triggers !== undefined || timers !== undefined)) fail('event');
126
+ const event = same(objectEvent, yamlEvent, 'event') ?? { events: [], triggers: [], timers: [] };
127
+ const data = same(safe.dataConfig, safe.dataYaml === undefined ? undefined : compileDataConfig(safe.dataYaml), 'data') ?? { objects: {} };
128
+ return canonicalTreeData({ ui, event, data });
129
+ } catch (error) {
130
+ if (error instanceof SomaComponentTreeError) throw error;
131
+ // YAML and expression parser errors may contain source/business values.
132
+ fail('config');
133
+ }
134
+ }
135
+
136
+ export function treeContextIdentity(context: TreeCompileContext): {
137
+ registrySnapshotDigest: string; policyDigest: string; assetSupplyKey: string;
138
+ } {
139
+ if (!context?.registrySnapshot?.digest || !context.compositionPolicy) fail('context');
140
+ if (context.assetSupplyKey !== undefined && (typeof context.assetSupplyKey !== 'string' || !context.assetSupplyKey.trim())) fail('context.supply');
141
+ return {
142
+ registrySnapshotDigest: context.registrySnapshot.digest,
143
+ policyDigest: digestTreeData({ policy: context.compositionPolicy, limits: context.limits ?? {}, sources: context.collectionSources ?? [] }),
144
+ assetSupplyKey: context.assetSupplyKey ?? digestTreeData({
145
+ registry: context.registrySnapshot.digest,
146
+ packs: Object.values(context.registrySnapshot.components).map(entry => ({ name: entry.name, packName: entry.packName, packVersion: entry.packVersion })).sort((a, b) => a.name.localeCompare(b.name)),
147
+ }),
148
+ };
149
+ }
150
+
151
+ export function computeTreeSourceDigest(input: Pick<TreeCompileKeyInput, 'html' | 'uiYaml' | 'externalBlocks'>): string {
152
+ return digestTreeData({ html: input.html, uiYaml: input.uiYaml,
153
+ externalBlocks: [...(input.externalBlocks ?? [])].sort(([a], [b]) => a.localeCompare(b)),
154
+ });
155
+ }
156
+
157
+ export function computeTreeCompileKey(input: TreeCompileKeyInput): string {
158
+ if (input.markup !== 'component-tree' || input.grammarVersion !== 1) fail('sourceMarkup');
159
+ return digestTreeData({ sourceDigest: computeTreeSourceDigest(input), compilerVersion: TREE_COMPILER_VERSION,
160
+ grammarVersion: 1, ...treeContextIdentity(input.treeContext) });
161
+ }
162
+
163
+ export function sealTreeRuntimeAssets(input: RuntimeConfigInput & {
164
+ sourceMarkup: 'component-tree'; html: string; artifact: Omit<TreeArtifact, 'artifactDigest'>;
165
+ }): TreeArtifact {
166
+ const artifact = { ...input.artifact, artifactDigest: digestTreeData({
167
+ sourceMarkup: input.sourceMarkup, html: input.html, runtimeConfig: normalizeRuntimeConfig(input),
168
+ artifactWithoutDigest: input.artifact,
169
+ }) };
170
+ assertRuntimeArtifact({ ...input, artifact });
171
+ return artifact;
172
+ }
173
+
174
+ export function verifyTreeRuntimeAssets(
175
+ input: ComponentTreeRuntimeEnvelope & RuntimeConfigInput,
176
+ source?: TreeCompileKeyInput,
177
+ ): boolean {
178
+ try {
179
+ assertRuntimeArtifact(input);
180
+ if (input.sourceMarkup !== 'component-tree' || !input.artifact || input.html === undefined) return false;
181
+ const { artifactDigest, ...artifact } = input.artifact;
182
+ if (artifact.compilerVersion !== TREE_COMPILER_VERSION) return false;
183
+ if (source) {
184
+ if (source.markup !== 'component-tree' || source.grammarVersion !== 1
185
+ || artifact.sourceDigest !== computeTreeSourceDigest(source)) return false;
186
+ const identity = treeContextIdentity(source.treeContext);
187
+ if (artifact.registrySnapshotDigest !== identity.registrySnapshotDigest
188
+ || artifact.policyDigest !== identity.policyDigest || artifact.assetSupplyKey !== identity.assetSupplyKey) return false;
189
+ }
190
+ return artifactDigest === sealTreeRuntimeAssets({ ...input, sourceMarkup: 'component-tree', html: input.html, artifact }).artifactDigest;
191
+ } catch { return false; }
192
+ }
@@ -0,0 +1,272 @@
1
+ import yaml from 'js-yaml';
2
+ import { parseSomaBlockContainer } from '../blocks/block-container';
3
+ import type { CompileSomaBlocksInput } from '../blocks/block-compile';
4
+ import type { HtmlAnchorInfo } from '../blocks/html-index';
5
+ import { SomaComponentTreeError, type ComponentTreeErrorCode } from '../../shared/component-tree-errors';
6
+ import type { ComponentNode, RepeatNode, TreeNode, TreeCompileContext, TreeValidationResult, ComponentTreeTrace } from '../../shared/types/component-tree.types';
7
+ import type { ComponentRef, RepeatPlan, StructurePlan } from '../../shared/types/component-tree-artifact.types';
8
+ import type { SomaContractField, SomaStructureSemanticToken } from '../../shared/types/component-contract.types';
9
+ import { canonicalTreeData } from './artifact-codec';
10
+ import { lowerCollectionBinding } from './collection-binding-lowerer';
11
+
12
+ type RecordValue = Record<string, unknown>;
13
+ type Scope = {
14
+ symbols: Record<string, string>; blocks: RecordValue; used: Set<string>;
15
+ aliases: Map<string, SomaContractField>; parentRepeat?: RepeatPlan;
16
+ };
17
+
18
+ const TAGS: Record<SomaStructureSemanticToken, string> = {
19
+ root: 'div', div: 'div', flow: 'div', none: 'div', main: 'main', section: 'section',
20
+ article: 'article', aside: 'aside', header: 'header', footer: 'footer', nav: 'nav',
21
+ navigation: 'nav', complementary: 'aside', contentinfo: 'footer', region: 'section', unordered: 'ul', ordered: 'ol',
22
+ };
23
+ const attr = (value: string): string => value.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
24
+
25
+ export interface TreeBindingResult {
26
+ html: string;
27
+ uiYaml: string;
28
+ treeBindings: NonNullable<CompileSomaBlocksInput['treeBindings']>;
29
+ structurePlan: StructurePlan[];
30
+ repeatPlans: RepeatPlan[];
31
+ componentRefs: ComponentRef[];
32
+ effectiveParents: ReadonlyMap<string, string | undefined>;
33
+ trace: ComponentTreeTrace;
34
+ }
35
+
36
+ /** AST-owned scopes, canonical rows, lowering and escaped HTML share one symbol table. */
37
+ export function bindComponentTree(
38
+ validated: TreeValidationResult,
39
+ input: { uiYaml: string; externalBlocks?: ReadonlyMap<string, string>; treeContext: TreeCompileContext },
40
+ ): TreeBindingResult {
41
+ const { tree } = validated;
42
+ const registry = input.treeContext.registrySnapshot.components;
43
+ const fail: (code: ComponentTreeErrorCode, path: string, hint: string) => never = (code, path, hint) => { throw new SomaComponentTreeError({
44
+ code, phase: 'bind', sourceId: tree.sourceId, nodePath: path, fixHint: hint,
45
+ }); };
46
+ const record = (value: unknown, path: string): RecordValue => {
47
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail('CT-BINDING-SCOPE', path, '声明必须是映射。');
48
+ return value as RecordValue;
49
+ };
50
+ const source = { ...parseSomaBlockContainer(input.uiYaml).doc };
51
+ for (const [name, text] of input.externalBlocks ?? []) {
52
+ if (Object.hasOwn(source, name)) fail('CT-BINDING-DUPLICATE', 'canonical', '同一实例不能同时存在内联与外置声明。');
53
+ try { source[name] = record(yaml.load(text), name); } catch { fail('CT-BINDING-SCOPE', 'canonical', '外置块必须是合法 YAML 映射。'); }
54
+ }
55
+ const doc = record(canonicalTreeData(source), 'canonical');
56
+ const page = record(doc.page, 'page');
57
+ // Page-level raw DOM writes have no targets in this source language.
58
+ if (page.ui && Object.keys(record(page.ui, 'page.ui')).length) fail('CT-BINDING-SCOPE', 'page.ui', '组件宿主只通过自己的 props/when/emits 绑定,不接受原生 text/class/attr/each 旁路。');
59
+ if (page.locale && (!Array.isArray(page.locale) || page.locale.length)) fail('CT-BINDING-SCOPE', 'page.locale', '文字应通过组件 text/label 等契约属性绑定。');
60
+ if (page.ooui !== undefined) fail('CT-BINDING-SCOPE', 'page.ooui', '组件树结构由显式树负责,不能同时生成第二份结构。');
61
+ const normalized: RecordValue = { page };
62
+ const anchors = new Map<string, HtmlAnchorInfo>();
63
+ const instances = new Set<string>();
64
+ const effectiveParents = new Map<string, string | undefined>();
65
+ const structures: StructurePlan[] = [];
66
+ const repeats: RepeatPlan[] = [];
67
+ const collections: NonNullable<CompileSomaBlocksInput['treeBindings']>['collections'][number][] = [];
68
+ const globalAliases = new Set<string>();
69
+ const refs = new Set<string>();
70
+ const traceSources: ComponentTreeTrace['sources'][number][] = [];
71
+ const traceEdges: ComponentTreeTrace['edges'][number][] = [];
72
+ let sequence = 0;
73
+ const collectAliases = (node: TreeNode): void => {
74
+ if (node.kind === 'repeat') { globalAliases.add(node.item); collectAliases(node.child); }
75
+ else for (const child of node.kind === 'component' ? node.slots : node.children) collectAliases(child);
76
+ };
77
+ collectAliases(tree.host);
78
+ const snapshot = (node: ComponentNode) => {
79
+ const entry = registry[node.component];
80
+ if (!entry?.contractDigest || !/^[a-f0-9]{64}$/.test(entry.structureDigest)) fail('CT-REGISTRY-CONTEXT', node.meta.nodePath, '组件树必须使用实际已准备定义生成的 Registry 快照。');
81
+ const visitRef = (name: string): void => { if (refs.has(name)) return; refs.add(name); for (const child of registry[name]?.contract.uses ?? []) visitRef(child); };
82
+ visitRef(node.component);
83
+ return entry;
84
+ };
85
+ const dynamic = (value: unknown, scope: Scope, body: RecordValue): boolean => {
86
+ if (typeof value !== 'string') return false;
87
+ const root = value.trim().replace(/^!/, '').split(/[.\s|]/)[0];
88
+ if ((globalAliases.has(root) && !scope.aliases.has(root)) || root === 'p' || root === 'ctrl') fail('CT-BINDING-SCOPE', 'ui', '绑定不能读取兄弟行或组件内部作用域。');
89
+ return root === 'page' || scope.aliases.has(root) || Object.hasOwn((body.alias as RecordValue) ?? {}, root) || Object.hasOwn((body.data as RecordValue) ?? {}, root);
90
+ };
91
+ const validateValue = (value: unknown, field: SomaContractField, scope: Scope, body: RecordValue, path: string): void => {
92
+ // Closed enum vocabulary wins over coincidentally named Domain/row aliases.
93
+ if (field.type === 'enum' && field.values?.some(item => item === value)) return;
94
+ if (dynamic(value, scope, body)) return;
95
+ const wrong = () => fail('CT-BINDING-SCOPE', path, '静态属性值必须符合当前组件契约类型和封闭字段;动态值使用可见的数据路径。');
96
+ if (field.type === 'enum') { if (!field.values?.some(item => item === value)) wrong(); }
97
+ else if (field.type === 'array') {
98
+ if (!Array.isArray(value)) wrong();
99
+ if (field.items) for (const item of value as unknown[]) validateValue(item, field.items, scope, body, path);
100
+ } else if (field.type === 'object') {
101
+ const object = record(value, path);
102
+ if (field.fields) {
103
+ for (const [key, item] of Object.entries(object)) {
104
+ if (!Object.hasOwn(field.fields, key)) wrong();
105
+ validateValue(item, field.fields[key], scope, body, path);
106
+ }
107
+ for (const [key, child] of Object.entries(field.fields)) if (child.required && !Object.hasOwn(object, key)) wrong();
108
+ }
109
+ } else if (typeof value !== field.type || (typeof value === 'number' && !Number.isFinite(value))) wrong();
110
+ };
111
+ const semantic = (node: ComponentNode, body: RecordValue, scope: Scope): { token?: SomaStructureSemanticToken; staticProps?: Record<string, string | boolean>; tag: string } => {
112
+ const entry = registry[node.component];
113
+ const semantics = entry.contract.structure?.semantics;
114
+ const props = record(body.ui ?? {}, `${node.id}.ui`);
115
+ let token = node.as as SomaStructureSemanticToken | undefined;
116
+ let staticProps: Record<string, string | boolean> | undefined;
117
+ if (semantics) {
118
+ const prop = semantics.staticProp;
119
+ if (prop) {
120
+ const explicit = Object.hasOwn(props, prop);
121
+ const value = props[prop];
122
+ const fromProp = explicit ? (prop === 'ordered' ? typeof value === 'boolean' ? value ? 'ordered' : 'unordered' : undefined : value) : undefined;
123
+ const literal = typeof fromProp === 'string' && semantics.allowed.includes(fromProp as SomaStructureSemanticToken);
124
+ if (explicit && !literal && dynamic(value, scope, body)) fail('CT-STRUCTURE-MOUNT', node.meta.nodePath, '结构语义只接受静态字面量,挂载后不可更换。');
125
+ if (explicit && (typeof fromProp !== 'string' || !semantics.allowed.includes(fromProp as SomaStructureSemanticToken))) fail('CT-STRUCTURE-MOUNT', node.meta.nodePath, '结构属性值不在受控语义集合。');
126
+ if (token && explicit && token !== fromProp) fail('CT-STRUCTURE-MOUNT', node.meta.nodePath, '树 as 与显式语义属性冲突。');
127
+ token ??= fromProp as SomaStructureSemanticToken | undefined;
128
+ token ??= semantics.default;
129
+ staticProps = { [prop]: prop === 'ordered' ? token === 'ordered' : token };
130
+ body.ui = { ...props, ...staticProps };
131
+ } else token ??= semantics.default;
132
+ }
133
+ return { ...(token ? { token } : {}), ...(staticProps ? { staticProps } : {}),
134
+ tag: entry.contract.structure?.tree_mount === 'legacy-host' ? 'div'
135
+ : token ? TAGS[token] : entry.contract.structure?.tree_mount === 'single-host' ? entry.templateRootTag ?? 'div' : 'div' };
136
+ };
137
+ const checkBlock = (node: ComponentNode, raw: unknown, scope: Scope): RecordValue => {
138
+ const body = { ...record(raw ?? {}, node.id) };
139
+ const contract = registry[node.component].contract;
140
+ if (scope.parentRepeat) {
141
+ for (const key of Object.keys(body)) if (!['component', 'alias', 'when', 'ui', 'event', 'rows'].includes(key)) fail('CT-BINDING-SCOPE', node.id, '行块只接受组件、别名、显隐、属性、emit 与嵌套 rows。');
142
+ if (body.event && Object.keys(record(body.event, `${node.id}.event`)).some(key => key !== 'on')) fail('CT-BINDING-SCOPE', node.id, '行块仅允许 event.on,不在每行定义动作或计时器。');
143
+ }
144
+ const props = record(body.ui ?? {}, `${node.id}.ui`);
145
+ for (const [key, value] of Object.entries(props)) {
146
+ if (!Object.hasOwn(contract.props ?? {}, key)) fail(['each', 'items', 'key', 'source', 'collectionSlot'].includes(key) && contract.structure?.slots?.item?.kind === 'collection' ? 'CT-BINDING-DUPLICATE' : 'CT-BINDING-SCOPE', `${node.id}.ui`, '只接受该组件契约 props;集合源只在 repeat 声明。');
147
+ validateValue(value, contract.props![key], scope, body, `${node.id}.ui.${key}`);
148
+ }
149
+ for (const [name, prop] of Object.entries(contract.props ?? {})) if (prop.required && prop.default === undefined && !Object.hasOwn(props, name)) fail('CT-BINDING-SCOPE', `${node.id}.ui`, '补齐组件契约要求的必填属性。');
150
+ if (body.event) for (const name of Object.keys(record(record(body.event, node.id).on ?? {}, node.id))) {
151
+ if (!Object.hasOwn(contract.emits ?? {}, name)) fail('CT-BINDING-SCOPE', `${node.id}.event.on`, '事件必须是当前组件契约声明的 emit。');
152
+ }
153
+ if (body.alias) for (const value of Object.values(record(body.alias, node.id))) dynamic(value, scope, {});
154
+ if (body.when) dynamic(body.when, scope, body);
155
+ return body;
156
+ };
157
+ const checkConstraints = (node: ComponentNode, body: RecordValue): void => {
158
+ const contract = registry[node.component].contract;
159
+ const props = { ...Object.fromEntries(Object.entries(contract.props ?? {}).map(([key, field]) => [key, field.default])), ...record(body.ui ?? {}, node.id) };
160
+ if (node.component === 'Box' && props.display === 'block' && props.gap !== 'none') fail('CT-STRUCTURE-MOUNT', node.id, 'Box 的 block 模式不支持 gap;使用 flex/grid 或 gap=none。');
161
+ if (node.component === 'Text' && ((props.truncate === true && (props.wrap !== 'none' || props.line_clamp !== 0))
162
+ || (typeof props.line_clamp === 'number' && props.line_clamp !== 0 && (props.truncate === true || props.wrap === 'none')))) fail('CT-STRUCTURE-MOUNT', node.id, 'Text 的 truncate/wrap/line_clamp 组合互斥。');
163
+ if ((node.component === 'Box' && props.as === 'nav') || (node.component === 'Region' && ['navigation', 'region'].includes(String(props.landmark)))) {
164
+ if (typeof props.label !== 'string' || !props.label.trim()) fail('CT-STRUCTURE-MOUNT', node.id, '命名导航或区域必须声明非空 label。');
165
+ }
166
+ };
167
+ const assertUsed = (scope: Scope): void => {
168
+ for (const id of Object.keys(scope.blocks)) if (id !== 'page' && !scope.used.has(id)) fail('CT-BINDING-SCOPE', 'rows', 'canonical 块必须只引用当前页面或当前行作用域中的组件 id;宏不可寻址。');
169
+ };
170
+ const emit = (node: TreeNode, scope: Scope, parent?: string): string => {
171
+ if (node.kind === 'fragment') return node.children.map(child => emit(child, scope, parent)).join('');
172
+ if (node.kind !== 'component') fail('CT-SLOT-CONTRACT', node.meta.nodePath, '该位置只能发射普通组件或透明 Fragment。');
173
+ const entry = snapshot(node);
174
+ const macro = entry.contract.structure?.kind === 'fragment-macro';
175
+ if (macro) {
176
+ traceSources.push({ ...node.meta });
177
+ traceEdges.push({ fromId: node.meta.nodeId, relation: 'normalizes', toId: 'fragment-erasure' });
178
+ if (Object.hasOwn(scope.blocks, node.id)) fail('CT-STRUCTURE-MOUNT', node.id, 'Fragment 宏不接受运行时声明或寻址。');
179
+ return node.slots.flatMap(slot => slot.children).map(child => emit(child, scope, parent)).join('');
180
+ }
181
+ const symbol = scope.parentRepeat ? `__soma_tree_${scope.parentRepeat.scopeId}_${node.id}` : node.id;
182
+ traceSources.push({ ...node.meta, symbol });
183
+ traceEdges.push({ fromId: node.meta.nodeId, relation: 'derives', toId: symbol },
184
+ { fromId: `contract:${node.component}:${entry.structureDigest}`, relation: 'verifies', toId: symbol });
185
+ if (parent) traceEdges.push({ fromId: parent, relation: 'projects', toId: symbol });
186
+ if (Object.hasOwn(scope.blocks, node.id)) traceEdges.push({ fromId: `canonical:${scope.parentRepeat?.scopeId ?? 'page'}:${node.id}`, relation: 'binds', toId: symbol });
187
+ scope.symbols[node.id] = symbol;
188
+ scope.used.add(node.id);
189
+ const body = checkBlock(node, scope.blocks[node.id], scope);
190
+ const resolved = semantic(node, body, scope);
191
+ checkConstraints(node, body);
192
+ anchors.set(symbol, { somaId: symbol, component: node.component, line: node.meta.span.startLine,
193
+ inRowTemplate: !!scope.parentRepeat, ...(scope.parentRepeat ? { rowRole: 'item', ownerList: scope.parentRepeat.consumerOwner.instanceSymbol } : {}) });
194
+ instances.add(symbol);
195
+ effectiveParents.set(symbol, parent);
196
+ const slotPlans = Object.entries(entry.contract.slots ?? {}).map(([name]) => {
197
+ const contract = entry.contract.structure?.slots?.[name];
198
+ return { name, kind: contract?.kind ?? 'projection' as const, ownerSymbol: symbol,
199
+ ...(contract?.layoutRoot ? { layoutRootKey: contract.layoutRoot } : {}), directChildren: contract?.directChildren ?? false,
200
+ ...(contract?.rowContainer ? { rowContainer: contract.rowContainer } : {}) };
201
+ });
202
+ const mount = entry.contract.structure?.tree_mount ?? 'legacy-host';
203
+ if (mount === 'erase') fail('CT-STRUCTURE-MOUNT', node.id, '宏不应生成运行时实例。');
204
+ structures.push({ instanceSymbol: symbol, componentName: node.component, mountMode: mount,
205
+ hostTag: resolved.tag, ...(resolved.token ? { semanticToken: resolved.token } : {}), slotPlans,
206
+ structureDigest: entry.structureDigest, ...(entry.internalRootId ? { internalRootId: entry.internalRootId } : {}),
207
+ ...(resolved.staticProps ? { staticProps: resolved.staticProps } : {}) });
208
+ const rows = record(body.rows ?? {}, `${node.id}.rows`);
209
+ for (const slot of Object.keys(rows)) if (entry.contract.structure?.slots?.[slot]?.kind !== 'collection') fail('CT-BINDING-SCOPE', `${node.id}.rows`, 'rows 只能声明当前组件的 collection slot。');
210
+ delete body.rows;
211
+ if (Object.keys(body).length) normalized[symbol] = body;
212
+ const content = node.slots.map(slot => {
213
+ const slotContract = entry.contract.structure?.slots?.[slot.name];
214
+ let children: string;
215
+ if (slotContract?.kind === 'collection') {
216
+ const flat = (nodes: TreeNode[]): TreeNode[] => nodes.flatMap(child => child.kind === 'fragment' ? flat(child.children)
217
+ : child.kind === 'component' && registry[child.component].contract.structure?.kind === 'fragment-macro' ? flat(child.slots.flatMap(item => item.children)) : [child]);
218
+ const repeat = flat(slot.children)[0] as RepeatNode;
219
+ const id = ++sequence;
220
+ let sources = input.treeContext.collectionSources ?? [];
221
+ const [head, ...tail] = repeat.source.split('.');
222
+ let field = scope.aliases.get(head);
223
+ for (const part of tail) field = field?.type === 'object' ? field.fields?.[part] : undefined;
224
+ if (scope.aliases.has(head) && field?.type === 'array' && field.items) sources = [{ path: repeat.source, item: field.items, statusPlan: { kind: 'sync' } }];
225
+ const descriptor = sources.find(item => item.path === repeat.source);
226
+ if (!descriptor) fail('CT-REPEAT-SOURCE', repeat.meta.nodePath, '集合源缺少可信元素类型。');
227
+ const plan = lowerCollectionBinding({ planId: `repeat_${id}`, scopeId: `row_${id}`,
228
+ ...(scope.parentRepeat ? { parentPlanId: scope.parentRepeat.planId } : {}),
229
+ sourcePath: repeat.source, itemAlias: repeat.item, keyPath: repeat.key,
230
+ declarationScope: { kind: 'page', ownerSymbol: 'page', readerRoot: tree.host.name, emitOwnerSymbol: 'page',
231
+ ...(scope.parentRepeat ? { parentScopeId: scope.parentRepeat.scopeId } : {}) },
232
+ consumerOwner: { instanceSymbol: symbol, componentName: node.component, slotName: slot.name,
233
+ layoutRootKey: slotContract.layoutRoot!, rowContainer: slotContract.rowContainer! },
234
+ rowTemplateId: `template_${id}`, localSymbols: {}, collectionSources: sources, limits: input.treeContext.limits });
235
+ repeats.push(plan);
236
+ traceSources.push({ ...repeat.meta, symbol: plan.planId });
237
+ traceEdges.push({ fromId: repeat.meta.nodeId, relation: 'derives', toId: plan.planId },
238
+ { fromId: plan.planId, relation: 'scopes', toId: plan.scopeId },
239
+ { fromId: plan.planId, relation: 'consumes', toId: symbol });
240
+ collections.push({ symbol, ...(scope.parentRepeat ? { parentSymbol: scope.parentRepeat.consumerOwner.instanceSymbol } : {}),
241
+ bind: { obj: plan.sourcePath, var: plan.itemAlias, repeatPlanId: plan.planId } });
242
+ const childScope: Scope = { symbols: plan.localSymbols, blocks: record(rows[slot.name] ?? {}, `${node.id}.rows.${slot.name}`),
243
+ used: new Set(), aliases: new Map(scope.aliases).set(repeat.item, descriptor.item), parentRepeat: plan };
244
+ const row = emit(repeat.child, childScope, `@${plan.planId}`);
245
+ assertUsed(childScope);
246
+ children = `<template data-soma-role="item" data-soma-repeat-template="${plan.rowTemplateId}">${row}</template>`;
247
+ } else {
248
+ const root = slotContract?.layoutRoot ? entry.structureAdapter?.layoutRoots[slotContract.layoutRoot] : undefined;
249
+ const effectiveParent = mount === 'single-host' && slotContract?.directChildren && root === entry.internalRootId ? symbol : `@${symbol}.${slot.name}`;
250
+ children = slot.children.map(child => emit(child, scope, effectiveParent)).join('');
251
+ }
252
+ return `<template data-soma-slot="${attr(slot.name)}">${children}</template>`;
253
+ }).join('');
254
+ return `<${resolved.tag} data-soma-component="${node.component}" data-soma-id="${attr(symbol)}" data-soma-tree-mount="${mount}">${content}</${resolved.tag}>`;
255
+ };
256
+ const scope: Scope = { symbols: {}, blocks: doc, used: new Set(), aliases: new Map() };
257
+ if (tree.host.id) anchors.set(tree.host.id, { somaId: tree.host.id, line: tree.host.meta.span.startLine, inRowTemplate: false });
258
+ const tag = TAGS[tree.host.as as SomaStructureSemanticToken];
259
+ const content = tree.host.children.map(child => emit(child, scope, tree.host.id)).join('');
260
+ assertUsed(scope);
261
+ const html = `<${tag} data-soma-host="${attr(tree.host.name)}"${tree.host.id ? ` data-soma-id="${attr(tree.host.id)}"` : ''}>${content}</${tag}>`;
262
+ // Explicit main landmarks are a page-wide obligation, including repeated static roots.
263
+ const main = (plan: StructurePlan): boolean => plan.hostTag === 'main' || plan.semanticToken === 'main';
264
+ if ((tag === 'main' ? 1 : 0) + structures.filter(main).length > 1) fail('CT-STRUCTURE-MOUNT', 'host', '页面只能有一个主 landmark,不能在重复行中制造多个 main。');
265
+ if (structures.some(plan => main(plan) && plan.instanceSymbol.startsWith('__soma_tree_'))) fail('CT-STRUCTURE-MOUNT', 'rows', '重复行不能声明 main landmark。');
266
+ return { html, uiYaml: `{{\n${yaml.dump(normalized, { noRefs: true, lineWidth: 120 })}}}\n`,
267
+ treeBindings: { htmlIndex: { anchors, instances, host: tree.host.name, duplicates: [] }, collections },
268
+ structurePlan: structures, repeatPlans: repeats, effectiveParents, trace: { sources: traceSources, edges: traceEdges },
269
+ componentRefs: [...refs].sort().map(name => ({ name, contractDigest: registry[name].contractDigest!, structureDigest: registry[name].structureDigest,
270
+ ...(registry[name].packName ? { packName: registry[name].packName } : {}), ...(registry[name].packVersion ? { packVersion: registry[name].packVersion } : {}), uses: [...(registry[name].contract.uses ?? [])] })),
271
+ };
272
+ }
@@ -0,0 +1,65 @@
1
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
2
+ import type { SomaContractField } from '../../shared/types/component-contract.types';
3
+ import type { CollectionConsumerOwner, CollectionDeclarationScope, RepeatPlan } from '../../shared/types/component-tree-artifact.types';
4
+ import { DEFAULT_TREE_LIMITS, type TreeCollectionSource, type TreeLimits } from '../../shared/types/component-tree.types';
5
+ import { canonicalTreeData } from './artifact-codec';
6
+
7
+ export interface LowerCollectionBindingInput {
8
+ planId: string;
9
+ scopeId: string;
10
+ parentPlanId?: string;
11
+ sourcePath: string;
12
+ itemAlias: string;
13
+ keyPath: string;
14
+ declarationScope: CollectionDeclarationScope;
15
+ consumerOwner: CollectionConsumerOwner;
16
+ rowTemplateId: string;
17
+ localSymbols: Record<string, string>;
18
+ collectionSources: readonly TreeCollectionSource[];
19
+ limits?: Partial<TreeLimits>;
20
+ }
21
+
22
+ /** Shared page/definition source lowering; no controller, reader or DOM execution. */
23
+ export function lowerCollectionBinding(input: LowerCollectionBindingInput): RepeatPlan {
24
+ const safe = canonicalTreeData(input) as unknown as LowerCollectionBindingInput;
25
+ if (!path(safe.sourcePath)) fail('CT-REPEAT-SOURCE', 'source 必须是安全的已声明数组路径');
26
+ if (!/^[$A-Z_a-z][$\w]*$/.test(safe.itemAlias)
27
+ || ['page', 'p', 'ctrl', 'data', '__proto__', 'constructor', 'prototype'].includes(safe.itemAlias)) {
28
+ fail('CT-BINDING-SCOPE', '行别名不得遮蔽保留作用域');
29
+ }
30
+ const sources = safe.collectionSources.filter(source => source.path === safe.sourcePath);
31
+ if (sources.length !== 1) fail('CT-REPEAT-SOURCE', '集合源必须具有唯一且明确的数组元素类型');
32
+ if (!path(safe.keyPath) || !safe.keyPath.startsWith(`${safe.itemAlias}.`)) fail('CT-REPEAT-KEY', 'key 必须来自当前行的字段');
33
+ let field: SomaContractField | undefined = sources[0].item;
34
+ for (const part of safe.keyPath.split('.').slice(1)) field = field?.fields?.[part];
35
+ if (!field || !['string', 'number', 'enum'].includes(field.type)
36
+ || (field.type === 'enum' && (!field.values?.length || field.values.some(value =>
37
+ typeof value !== 'string' && (typeof value !== 'number' || !Number.isFinite(value)))))) {
38
+ fail('CT-REPEAT-KEY', 'key 字段必须有可验证的字符串或有限数字类型');
39
+ }
40
+ const statusPlan = sources[0].statusPlan;
41
+ if (!statusPlan || !['sync', 'async'].includes(statusPlan.kind)
42
+ || (statusPlan.kind === 'async' && !path(statusPlan.statePath))) fail('CT-REPEAT-SOURCE', '异步源必须声明受控状态路径');
43
+ if (!safe.consumerOwner.layoutRootKey || !['none', 'list-item'].includes(safe.consumerOwner.rowContainer)
44
+ || safe.consumerOwner.slotName !== 'item') fail('CT-SLOT-CONTRACT', '集合必须消费已登记 item 出口');
45
+ const limits = { ...DEFAULT_TREE_LIMITS, ...safe.limits };
46
+ if (Object.values(limits).some(value => !Number.isSafeInteger(value) || value < 1)) fail('CT-LIMIT', '集合预算必须是正整数');
47
+ return {
48
+ planId: safe.planId, scopeId: safe.scopeId,
49
+ ...(safe.parentPlanId ? { parentPlanId: safe.parentPlanId } : {}),
50
+ declarationScope: safe.declarationScope, consumerOwner: safe.consumerOwner,
51
+ sourcePath: safe.sourcePath, statusPlan, itemAlias: safe.itemAlias, keyPath: safe.keyPath,
52
+ rowTemplateId: safe.rowTemplateId, localSymbols: safe.localSymbols,
53
+ limits: { maxRows: limits.maxRowsPerCollection, maxPageRows: limits.maxRowsPerPage,
54
+ maxKeyLength: limits.maxKeyLength, maxDepth: limits.maxRepeatDepth },
55
+ };
56
+ }
57
+
58
+ function path(value: string): boolean {
59
+ return typeof value === 'string' && /^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)+$/.test(value)
60
+ && !value.split('.').some(part => ['__proto__', 'constructor', 'prototype'].includes(part));
61
+ }
62
+
63
+ function fail(code: 'CT-REPEAT-SOURCE' | 'CT-REPEAT-KEY' | 'CT-BINDING-SCOPE' | 'CT-LIMIT' | 'CT-SLOT-CONTRACT', fixHint: string): never {
64
+ throw new SomaComponentTreeError({ code, phase: 'bind', sourceId: '<collection>', nodePath: 'repeat', fixHint });
65
+ }