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,318 @@
1
+ // REQ-016 build-only preflight. No DOM, component execution or runtime plans.
2
+ import { SomaComponentTreeError, type ComponentTreeErrorCode } from '../../shared/component-tree-errors';
3
+ import type { SomaContractField } from '../../shared/types/component-contract.types';
4
+ import {
5
+ DEFAULT_TREE_LIMITS,
6
+ type ComponentNode,
7
+ type NodeMeta,
8
+ type RepeatNode,
9
+ type SomaComponentTree,
10
+ type TreeCollectionSource,
11
+ type TreeCompileContext,
12
+ type TreeComponentSnapshot,
13
+ type TreeNode,
14
+ type TreeSlotPolicy,
15
+ type TreeValidationResult,
16
+ } from '../../shared/types/component-tree.types';
17
+
18
+ const ID = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
19
+ const VARIABLE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
20
+ const PATH = /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/;
21
+ const RESERVED = new Set(['page', 'p', 'ctrl', 'data', '__proto__', 'prototype', 'constructor']);
22
+ const UNSAFE_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);
23
+ const HOST_SEMANTICS = new Set(['root', 'main', 'section', 'article', 'div']);
24
+
25
+ interface Scope {
26
+ ids: Map<string, NodeMeta>;
27
+ aliases: ReadonlyMap<string, SomaContractField>;
28
+ repeatDepth: number;
29
+ }
30
+
31
+ interface Position {
32
+ root: boolean;
33
+ restrictions: readonly TreeSlotPolicy[];
34
+ repeatAllowed: boolean;
35
+ }
36
+
37
+ function own<T>(record: Readonly<Record<string, T>> | undefined, key: string): T | undefined {
38
+ return record && Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
39
+ }
40
+
41
+ function isPath(value: string): boolean {
42
+ return typeof value === 'string' && PATH.test(value)
43
+ && !value.split('.').some(segment => UNSAFE_SEGMENTS.has(segment));
44
+ }
45
+
46
+ function fieldAt(root: SomaContractField, segments: readonly string[]): SomaContractField | undefined {
47
+ let field: SomaContractField | undefined = root;
48
+ for (const segment of segments) {
49
+ if (field?.type !== 'object') return undefined;
50
+ field = own(field.fields, segment);
51
+ }
52
+ return field;
53
+ }
54
+
55
+ /**
56
+ * Validate only source/context facts. The return value is not an executable asset;
57
+ * binding lowering, effective-parent proof and full artifact delivery are separate.
58
+ */
59
+ export function validateComponentTree(
60
+ tree: SomaComponentTree,
61
+ input: { domain: string; context: TreeCompileContext },
62
+ ): TreeValidationResult {
63
+ function fail(
64
+ code: ComponentTreeErrorCode,
65
+ node: { meta: NodeMeta } | undefined,
66
+ fixHint: string,
67
+ attribute?: string,
68
+ related?: NodeMeta,
69
+ ): never {
70
+ throw new SomaComponentTreeError({
71
+ code,
72
+ phase: 'validate',
73
+ sourceId: tree?.sourceId ?? '<component-tree>',
74
+ nodePath: node?.meta?.nodePath ?? '/',
75
+ ...(node?.meta?.span ? { span: node.meta.span } : {}),
76
+ ...(related ? { relatedSpans: [related.span] } : {}),
77
+ ...(attribute ? { attribute } : {}),
78
+ fixHint,
79
+ });
80
+ }
81
+
82
+ if (!tree || tree.grammarVersion !== 1 || tree.host?.kind !== 'host') {
83
+ fail('CT-SYNTAX-ROOT', tree?.host, '提供 grammarVersion=1 且只有一个 Host 根的解析树。');
84
+ }
85
+ const context = input?.context;
86
+ const registry = context?.registrySnapshot;
87
+ const policy = context?.compositionPolicy;
88
+ if (!registry?.digest || !registry.components || !policy?.policyId || !policy.version
89
+ || !Array.isArray(policy.roots) || policy.roots.length === 0) {
90
+ fail('CT-REGISTRY-CONTEXT', tree.host, '由受信 Host 提供完整 Registry 快照与页面准入策略。');
91
+ }
92
+ const limits = { ...DEFAULT_TREE_LIMITS, ...context.limits };
93
+ for (const value of Object.values(limits)) {
94
+ if (!Number.isSafeInteger(value) || value < 1) {
95
+ fail('CT-LIMIT', tree.host, '部署限额必须是正安全整数。');
96
+ }
97
+ }
98
+ if (!input.domain || tree.host.name !== input.domain) {
99
+ fail('CT-IDENTITY-HOST', tree.host, 'Host.name 必须与 canonical page.domain 一致。', 'name');
100
+ }
101
+ if (!HOST_SEMANTICS.has(tree.host.as)) {
102
+ fail('CT-STRUCTURE-MOUNT', tree.host, 'Host.as 必须使用 root/main/section/article/div。', 'as');
103
+ }
104
+
105
+ // Bound traversal before recursive flattening or semantic checks, including
106
+ // hand-built editor ASTs that did not pass through the source parser.
107
+ let count = 0;
108
+ const inspectShape = (node: TreeNode, depth: number): void => {
109
+ if (++count > limits.maxNodes || depth > limits.maxDepth) {
110
+ fail('CT-LIMIT', node, '减少静态节点数或嵌套深度。');
111
+ }
112
+ if (!node || !['host', 'component', 'slot', 'fragment', 'repeat'].includes(node.kind)) {
113
+ fail('CT-SYNTAX-ELEMENT', node, '解析树只能包含已声明的五种节点。');
114
+ }
115
+ if (node.kind === 'repeat') {
116
+ if (!node.child || !['component', 'fragment'].includes(node.child.kind)) {
117
+ fail('CT-SYNTAX-ELEMENT', node, 'repeat 必须包含一个组件或非空 Fragment。');
118
+ }
119
+ inspectShape(node.child, depth + 1);
120
+ return;
121
+ }
122
+ const children = node.kind === 'component' ? node.slots : node.children;
123
+ if (!Array.isArray(children)) {
124
+ fail('CT-SYNTAX-ELEMENT', node, '节点必须提供结构化的子节点列表。');
125
+ }
126
+ for (const child of children) inspectShape(child, depth + 1);
127
+ };
128
+ inspectShape(tree.host, 1);
129
+
130
+ const slotPolicies = new Map<string, TreeSlotPolicy>();
131
+ for (const rule of policy.slotRules ?? []) {
132
+ const key = `${rule.component}\0${rule.slot}`;
133
+ if (slotPolicies.has(key)) {
134
+ fail('CT-REGISTRY-CONTEXT', tree.host, '同一组件和 slot 只能配置一条准入规则。');
135
+ }
136
+ slotPolicies.set(key, rule);
137
+ }
138
+ const sources = new Map<string, TreeCollectionSource>();
139
+ for (const descriptor of context.collectionSources ?? []) {
140
+ if (!isPath(descriptor.path) || !descriptor.item || sources.has(descriptor.path)
141
+ || !descriptor.statusPlan || !['sync', 'async'].includes(descriptor.statusPlan.kind)
142
+ || (descriptor.statusPlan.kind === 'async' && !isPath(descriptor.statusPlan.statePath))) {
143
+ fail('CT-REPEAT-SOURCE', tree.host, '集合描述必须有唯一安全路径、元素类型和完整 sync/async 状态描述。');
144
+ }
145
+ sources.set(descriptor.path, descriptor);
146
+ }
147
+
148
+ const componentNames = new Set<string>();
149
+ const snapshotFor = (node: ComponentNode): TreeComponentSnapshot => {
150
+ const snapshot = own(registry.components, node.component);
151
+ if (!snapshot || snapshot.name !== node.component || snapshot.contract.name !== node.component) {
152
+ fail('CT-REGISTRY-COMPONENT', node, '组件必须存在于当前 Host 的有效 Registry 快照。', 'component');
153
+ }
154
+ return snapshot;
155
+ };
156
+ const isMacro = (node: TreeNode): node is ComponentNode => node.kind === 'component'
157
+ && own(registry.components, node.component)?.contract.structure?.kind === 'fragment-macro';
158
+
159
+ const expanded = (nodes: readonly TreeNode[]): TreeNode[] => nodes.flatMap(node => {
160
+ if (node.kind === 'fragment') return expanded(node.children);
161
+ if (isMacro(node)) return expanded(node.slots.flatMap(slot => slot.children));
162
+ return [node];
163
+ });
164
+ const rememberId = (node: ComponentNode | SomaComponentTree['host'], scope: Scope): void => {
165
+ if (node.id === undefined && node.kind === 'host') return;
166
+ if (typeof node.id !== 'string' || !ID.test(node.id) || node.id.startsWith('__soma_tree_')) {
167
+ fail('CT-IDENTITY-ID', node, 'id 必须是 1–64 位安全标识符,不能使用内部保留前缀。', 'id');
168
+ }
169
+ const previous = scope.ids.get(node.id);
170
+ if (previous) {
171
+ fail('CT-IDENTITY-ID', node, '同一页面或行模板作用域内的 id 必须唯一。', 'id', previous);
172
+ }
173
+ scope.ids.set(node.id, node.meta);
174
+ };
175
+ const allowedBy = (
176
+ rule: Pick<TreeSlotPolicy, 'allowedComponents' | 'allowedLayers'>,
177
+ component: TreeComponentSnapshot,
178
+ ): boolean => Boolean(rule.allowedComponents?.includes(component.name)
179
+ || rule.allowedLayers?.includes(component.layer));
180
+
181
+ const validateMount = (node: ComponentNode, snapshot: TreeComponentSnapshot): void => {
182
+ const structure = snapshot.contract.structure;
183
+ if (structure?.kind === 'fragment-macro') {
184
+ if (node.mount !== 'fragment' || node.as !== undefined || !structure.rootless
185
+ || structure.tree_mount !== 'erase') {
186
+ fail('CT-STRUCTURE-MOUNT', node, 'Fragment 宏必须 rootless/erase 且 mount=fragment,不能声明 as。', 'mount');
187
+ }
188
+ } else if (node.mount !== 'host' || structure?.rootless || structure?.tree_mount === 'erase') {
189
+ fail('CT-STRUCTURE-MOUNT', node, '普通组件必须保留 HTMLElement host,不能使用 fragment mount。', 'mount');
190
+ }
191
+ if (node.as !== undefined && (!structure?.semantics
192
+ || !structure.semantics.allowed.some(token => token === node.as))) {
193
+ fail('CT-STRUCTURE-MOUNT', node, 'as 必须属于组件契约声明的封闭语义集合。', 'as');
194
+ }
195
+ };
196
+
197
+ const rowItemSchema = (node: RepeatNode, scope: Scope): SomaContractField => {
198
+ if (!isPath(node.source)) {
199
+ fail('CT-REPEAT-SOURCE', node, 'source 只允许已声明集合的安全点分路径。', 'source');
200
+ }
201
+ const [root, ...segments] = node.source.split('.');
202
+ const parentItem = scope.aliases.get(root);
203
+ if (parentItem) {
204
+ const field = fieldAt(parentItem, segments);
205
+ if (field?.type !== 'array' || !field.items) {
206
+ fail('CT-REPEAT-SOURCE', node, '祖先行中的 source 必须是有 items 类型的 array 字段。', 'source');
207
+ }
208
+ return field.items;
209
+ }
210
+ const descriptor = sources.get(node.source);
211
+ if (!descriptor) {
212
+ fail('CT-REPEAT-SOURCE', node, '由 Host/canonical 类型声明提供该数组源,不能按运行数据猜测。', 'source');
213
+ }
214
+ return descriptor.item;
215
+ };
216
+
217
+ const visit = (node: TreeNode, scope: Scope, position: Position): void => {
218
+ if (node.kind === 'host' || node.kind === 'slot') {
219
+ fail('CT-SYNTAX-ELEMENT', node, 'Host 只可作为根,slot 只可直接归属组件。');
220
+ }
221
+ if (node.kind === 'fragment') {
222
+ for (const child of node.children) visit(child, scope, position);
223
+ return;
224
+ }
225
+ if (node.kind === 'repeat') {
226
+ if (!position.repeatAllowed) {
227
+ fail('CT-SLOT-CONTRACT', node, 'repeat 只能作为已登记 collection.item 槽的唯一内容。');
228
+ }
229
+ if (scope.repeatDepth + 1 > limits.maxRepeatDepth) {
230
+ fail('CT-LIMIT', node, '减少嵌套集合层数。');
231
+ }
232
+ if (!VARIABLE.test(node.item) || RESERVED.has(node.item) || scope.aliases.has(node.item)) {
233
+ fail('CT-BINDING-SCOPE', node, '行变量不能遮蔽 page/p/ctrl/data 或祖先行变量。', 'item');
234
+ }
235
+ const item = rowItemSchema(node, scope);
236
+ if (!isPath(node.key) || !node.key.startsWith(`${node.item}.`)) {
237
+ fail('CT-REPEAT-KEY', node, 'key 必须是当前行变量起始的稳定字段路径。', 'key');
238
+ }
239
+ const keyField = fieldAt(item, node.key.split('.').slice(1));
240
+ if (!keyField || !['string', 'number', 'enum'].includes(keyField.type)
241
+ || (keyField.type === 'enum' && (!keyField.values?.length
242
+ || keyField.values.some(value => typeof value !== 'string'
243
+ && (typeof value !== 'number' || !Number.isFinite(value)))))) {
244
+ fail('CT-REPEAT-KEY', node, 'key 字段必须有可验证的字符串或有限数字类型。', 'key');
245
+ }
246
+ if (expanded([node.child]).length === 0) {
247
+ fail('CT-SLOT-CONTRACT', node, 'repeat 的行模板必须至少有一个组件。');
248
+ }
249
+ const aliases = new Map(scope.aliases);
250
+ aliases.set(node.item, item);
251
+ visit(node.child, { ids: new Map(), aliases, repeatDepth: scope.repeatDepth + 1 }, {
252
+ ...position, root: false, repeatAllowed: false,
253
+ });
254
+ return;
255
+ }
256
+
257
+ const snapshot = snapshotFor(node);
258
+ componentNames.add(snapshot.name);
259
+ rememberId(node, scope);
260
+ validateMount(node, snapshot);
261
+ const macro = snapshot.contract.structure?.kind === 'fragment-macro';
262
+ if (!macro) {
263
+ const permitted = position.root
264
+ ? policy.roots.includes(snapshot.name)
265
+ : position.restrictions.length > 0
266
+ ? position.restrictions.every(rule => allowedBy(rule, snapshot))
267
+ : allowedBy(policy, snapshot);
268
+ if (!permitted) {
269
+ fail('CT-POLICY-COMPONENT', node, '组件不符合当前根或继承的 slot 准入规则。', 'component');
270
+ }
271
+ }
272
+
273
+ const seenSlots = new Map<string, NodeMeta>();
274
+ for (const slot of node.slots) {
275
+ if (slot.kind !== 'slot' || !own(snapshot.contract.slots, slot.name)) {
276
+ fail('CT-SLOT-CONTRACT', slot, '仅可投影组件契约已声明的 slot。', 'name');
277
+ }
278
+ const previous = seenSlots.get(slot.name);
279
+ if (previous) fail('CT-SLOT-CONTRACT', slot, '同一组件不能重复提供同名 slot。', 'name', previous);
280
+ seenSlots.set(slot.name, slot.meta);
281
+ if (slotPolicies.get(`${node.component}\0${slot.name}`)?.forbidden) {
282
+ fail('CT-POLICY-COMPONENT', slot, '当前 Host 未开放该 slot,包括显式空投影。', 'name');
283
+ }
284
+ if (own(snapshot.contract.slots, slot.name)?.required && expanded(slot.children).length === 0) {
285
+ fail('CT-SLOT-CONTRACT', slot, '必填 slot 不能只提供空 Fragment。', 'name');
286
+ }
287
+ const collection = own(snapshot.contract.structure?.slots, slot.name)?.kind === 'collection';
288
+ if (collection) {
289
+ const content = expanded(slot.children);
290
+ if (slot.name !== 'item' || content.length !== 1 || content[0].kind !== 'repeat') {
291
+ fail('CT-SLOT-CONTRACT', slot, 'collection.item 槽必须且只能提供一个 repeat。', 'name');
292
+ }
293
+ }
294
+ const rule = macro ? undefined : slotPolicies.get(`${node.component}\0${slot.name}`);
295
+ const inherited = macro ? position.restrictions : position.restrictions.map(parent =>
296
+ parent.descendantAllowedComponents !== undefined || parent.descendantAllowedLayers !== undefined
297
+ ? { ...parent, allowedComponents: parent.descendantAllowedComponents, allowedLayers: parent.descendantAllowedLayers }
298
+ : parent);
299
+ const restrictions = rule ? [...inherited, rule] : inherited;
300
+ const childPosition = macro ? position : { root: false, restrictions, repeatAllowed: collection };
301
+ for (const child of slot.children) visit(child, scope, childPosition);
302
+ }
303
+ for (const [name, slot] of Object.entries(snapshot.contract.slots ?? {})) {
304
+ if (slot.required && !seenSlots.has(name)) {
305
+ fail('CT-SLOT-CONTRACT', node, '组件缺少契约要求的必填 slot。', 'name');
306
+ }
307
+ }
308
+ };
309
+
310
+ const pageScope: Scope = { ids: new Map(), aliases: new Map(), repeatDepth: 0 };
311
+ rememberId(tree.host, pageScope);
312
+ const rootPosition: Position = { root: true, restrictions: [], repeatAllowed: false };
313
+ if (expanded(tree.host.children).length === 0) {
314
+ fail('CT-SYNTAX-ROOT', tree.host, 'Host 必须包含至少一个有效根组件。');
315
+ }
316
+ for (const child of tree.host.children) visit(child, pageScope, rootPosition);
317
+ return { tree, componentNames: Object.freeze([...componentNames].sort()) };
318
+ }
@@ -91,6 +91,7 @@ const IMPORT_REWRITES: Array<{ test: RegExp; to: (match: RegExpMatchArray) => st
91
91
  // Host 安装,只有 package exports 中明确承诺的入口才能存活。未知内部模块在
92
92
  // 这里 fail-closed,而不是为了当前本仓链接方便而悄悄变成公共 API。
93
93
  { test: /^\.\.\/adaptive\/(?:density-arbiter|layout-primitives)$/, to: () => 'soma-ui/adaptive' },
94
+ { test: /^\.\.\/adaptive\/layout-constants$/, to: () => 'soma-ui/adaptive/layout-constants' },
94
95
  { test: /^\.\.\/adaptive\/field-components$/, to: () => 'soma-ui/adaptive/field-components' },
95
96
  { test: /^\.\.\/adaptive\/shape-infer$/, to: () => 'soma-ui/adaptive/shape-infer' },
96
97
  { test: /^\.\.\/adaptive\/shorthand-columns$/, to: () => 'soma-ui/adaptive/shorthand-columns' },
@@ -0,0 +1,79 @@
1
+ import { COMPONENT_TREE_ATTRIBUTES, parseComponentTree } from '../component-tree/parser';
2
+ import { compilePageDeclaration } from '../compiler/page-declaration-compiler';
3
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
4
+ import type { SourceSpan, TreeCompileContext, TreeRegistrySnapshot } from '../../shared/types/component-tree.types';
5
+ export { loadPageMarkupConfig } from '../../server/host/page-markup-config';
6
+
7
+ export interface TreeEditorPosition { line: number; character: number }
8
+ export interface TreeEditorDiagnostic {
9
+ uri: string; code: string; severity: number; source: string; message: string;
10
+ range: { start: TreeEditorPosition; end: TreeEditorPosition };
11
+ }
12
+
13
+ /** Same parser/compiler as publishing. LSP supplies only trusted Host context, never source metadata. */
14
+ export function diagnoseComponentTree(input: {
15
+ html: string; uiYaml: string; htmlUri: string; uiUri: string;
16
+ markup?: 'legacy-html' | 'component-tree'; grammarVersion?: number; treeContext?: TreeCompileContext;
17
+ }): TreeEditorDiagnostic[] {
18
+ try {
19
+ if (input.markup === 'component-tree') parseComponentTree(input.html, { sourceId: input.htmlUri, limits: input.treeContext?.limits });
20
+ compilePageDeclaration(input);
21
+ return [];
22
+ } catch (error) {
23
+ if (!(error instanceof SomaComponentTreeError)) return [{
24
+ uri: input.uiUri, code: 'CT-BINDING-SCOPE', severity: 1, source: 'soma-component-tree',
25
+ message: 'canonical 声明未通过正式解析,请检查声明容器和字段。', range: diagnosticRange(),
26
+ }];
27
+ const diagnostic = error.diagnostic;
28
+ const canonical = diagnostic.phase === 'bind' || diagnostic.nodePath === 'page.domain';
29
+ return [{
30
+ uri: canonical && !diagnostic.span ? input.uiUri : input.htmlUri,
31
+ code: error.code, severity: error.code === 'CT-REGISTRY-CONTEXT' ? 2 : 1,
32
+ source: 'soma-component-tree',
33
+ message: diagnostic.fixHint ?? '组件树未通过正式编译验证。',
34
+ range: diagnosticRange(diagnostic.span),
35
+ }];
36
+ }
37
+ }
38
+
39
+ function diagnosticRange(span?: SourceSpan): TreeEditorDiagnostic['range'] {
40
+ return span ? {
41
+ start: { line: span.startLine - 1, character: span.startColumn - 1 },
42
+ end: { line: span.endLine - 1, character: span.endColumn - 1 },
43
+ } : { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } };
44
+ }
45
+
46
+ /** Tolerant cursor context is only for suggestions; it never claims a partial document is valid. */
47
+ export function completeComponentTree(text: string, position: TreeEditorPosition, registry?: TreeRegistrySnapshot) {
48
+ const lines = text.split('\n');
49
+ const prefix = [...lines.slice(0, position.line), (lines[position.line] ?? '').slice(0, position.character)].join('\n');
50
+ const open = prefix.match(/<([a-z-]*)([^<>]*)$/);
51
+ if (!open) return [];
52
+ const [, tag, rest] = open;
53
+ const item = (label: string, detail: string, kind = 12) => ({ label, insertText: label, detail, kind });
54
+ if (!rest && !Object.hasOwn(COMPONENT_TREE_ATTRIBUTES, tag)) return Object.keys(COMPONENT_TREE_ATTRIBUTES)
55
+ .filter((name) => name.startsWith(tag)).map((name) => item(name, 'component-tree:1 语法元素'));
56
+ const attributes = COMPONENT_TREE_ATTRIBUTES[tag as keyof typeof COMPONENT_TREE_ATTRIBUTES];
57
+ if (!attributes) return [];
58
+ const value = rest.match(/([a-z]+)\s*=\s*["']([^"']*)$/);
59
+ if (value) {
60
+ const [, attribute, partial] = value;
61
+ let values: readonly string[] = [];
62
+ if (tag === 'soma-component' && attribute === 'component') values = Object.keys(registry?.components ?? {}).sort();
63
+ if (tag === 'soma-component' && attribute === 'as') {
64
+ const name = rest.match(/\bcomponent\s*=\s*["']([^"']+)["']/)?.[1];
65
+ values = name ? registry?.components[name]?.contract.structure?.semantics?.allowed ?? [] : [];
66
+ }
67
+ if (tag === 'soma-slot' && attribute === 'name') {
68
+ const stack: string[] = [];
69
+ for (const token of prefix.slice(0, open.index).matchAll(/<\/?soma-component\b[^>]*>/g)) {
70
+ if (token[0].startsWith('</')) stack.pop();
71
+ else stack.push(token[0].match(/\bcomponent\s*=\s*["']([^"']+)["']/)?.[1] ?? '');
72
+ }
73
+ values = Object.keys(registry?.components[stack.at(-1) ?? '']?.contract.slots ?? {});
74
+ }
75
+ return values.filter((name) => name.startsWith(partial)).map((name) => item(name, '实际 Registry 契约', 12));
76
+ }
77
+ const used = new Set([...rest.matchAll(/([a-z]+)\s*=/g)].map((match) => match[1]));
78
+ return attributes.filter((name) => !used.has(name)).map((name) => item(`${name}=""`, 'component-tree:1 属性', 10));
79
+ }
@@ -0,0 +1,42 @@
1
+ // CJS transport adapter. Grammar/diagnostics live in the real TS compiler service.
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { pathToFileURL } = require('node:url');
5
+ let service;
6
+ let hostResolver;
7
+ function getService() {
8
+ if (!service) {
9
+ const compiled = path.resolve(__dirname, '../../../dist/lsp/component-tree.cjs');
10
+ service = fs.existsSync(compiled) ? require(compiled)
11
+ : require('jiti')(__filename, { interopDefault: false })(path.join(__dirname, 'component-tree-service.ts'));
12
+ }
13
+ return service;
14
+ }
15
+ function resolveContext(hostDir, pageBase) {
16
+ if (!hostResolver) hostResolver = require('jiti')(__filename, { interopDefault: false })(
17
+ path.resolve(__dirname, '../../server/host/resolve-host-tree-context.ts'),
18
+ ).resolveHostTreeCompileContext;
19
+ return hostResolver(hostDir, { pageBase });
20
+ }
21
+ function treePageMode(hostDir, base) {
22
+ return getService().loadPageMarkupConfig(path.join(hostDir, 'config'), base);
23
+ }
24
+ function treeDiagnostics(hostDir, base, html, uiYaml) {
25
+ const htmlUri = pathToFileURL(path.join(hostDir, 'html', `${base}.html`)).href;
26
+ const uiUri = pathToFileURL(path.join(hostDir, 'ui', `${base}_ui.yaml`)).href;
27
+ try {
28
+ const mode = treePageMode(hostDir, base);
29
+ const treeContext = mode.markup === 'component-tree' ? resolveContext(hostDir, base) : undefined;
30
+ return getService().diagnoseComponentTree({ html, uiYaml, htmlUri, uiUri, ...mode, treeContext });
31
+ } catch {
32
+ return [{ uri: htmlUri, code: 'CT-REGISTRY-CONTEXT', source: 'soma-component-tree', severity: 2,
33
+ message: '缺少有效的受信页面格式或 Registry 上下文,尚未完成组件树验证。',
34
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } } }];
35
+ }
36
+ }
37
+ function treeCompletions(hostDir, base, text, position) {
38
+ let registry;
39
+ try { registry = resolveContext(hostDir, base)?.registrySnapshot; } catch { /* syntax suggestions remain available */ }
40
+ return getService().completeComponentTree(text, position, registry);
41
+ }
42
+ module.exports = { treePageMode, treeDiagnostics, treeCompletions };
@@ -2,6 +2,8 @@
2
2
  const fs = require('node:fs');
3
3
  const path = require('node:path');
4
4
  const { declarationFacts } = require('./soma-declaration.cjs');
5
+ const { pathToFileURL } = require('node:url');
6
+ const { treePageMode, treeDiagnostics } = require('./component-tree.cjs');
5
7
 
6
8
  function extractSomaIdsFromHtml(html) {
7
9
  const ids = new Set();
@@ -60,13 +62,14 @@ function retiredSidecarPaths(hostDir, base) {
60
62
  ];
61
63
  }
62
64
 
63
- function lintAnchorConsistency(hostDir) {
65
+ function lintAnchorConsistency(hostDir, openDocs = new Map()) {
64
66
  const htmlDir = path.join(hostDir, 'html');
65
67
  const diagnostics = [];
68
+ const readSource = (file) => openDocs.get(pathToFileURL(file).href) ?? openDocs.get(`file://${file}`) ?? fs.readFileSync(file, 'utf8');
66
69
  for (const base of collectHtmlPages(htmlDir)) {
67
70
  const htmlPath = path.join(htmlDir, `${base}.html`);
68
71
  const declarationPath = path.join(hostDir, 'ui', `${base}_ui.yaml`);
69
- const html = fs.readFileSync(htmlPath, 'utf8');
72
+ const html = readSource(htmlPath);
70
73
  const htmlIds = extractSomaIdsFromHtml(html);
71
74
 
72
75
  for (const sidecar of retiredSidecarPaths(hostDir, base).filter(fs.existsSync)) {
@@ -88,7 +91,16 @@ function lintAnchorConsistency(hostDir) {
88
91
  continue;
89
92
  }
90
93
 
91
- const source = fs.readFileSync(declarationPath, 'utf8');
94
+ const source = readSource(declarationPath);
95
+ let treeMode = false;
96
+ if (fs.existsSync(path.join(hostDir, 'config', 'page-markup.config.yaml'))) {
97
+ try { treeMode = treePageMode(hostDir, base).markup === 'component-tree'; }
98
+ catch { treeMode = true; }
99
+ }
100
+ if (treeMode || /<\/?soma-(?:host|component|slot|fragment|repeat)\b/i.test(html)) {
101
+ diagnostics.push(...treeDiagnostics(hostDir, base, html, source));
102
+ continue;
103
+ }
92
104
  let facts;
93
105
  try {
94
106
  facts = declarationFacts(source);
@@ -3,7 +3,9 @@
3
3
  */
4
4
  const fs = require('node:fs');
5
5
  const path = require('node:path');
6
+ const yaml = require('js-yaml');
6
7
  const { declarationFacts } = require('./soma-declaration.cjs');
8
+ const { treePageMode, treeCompletions } = require('./component-tree.cjs');
7
9
 
8
10
  const ANCHOR_PREFIXES = ['btn_', 'input_', 'txt_', 'list_', 'section_', 'nav_', 'link_', 'hero_'];
9
11
 
@@ -33,6 +35,11 @@ function getHtmlAnchorCompletions(hostDir, uri, text, position) {
33
35
  const pageBase = !rel.startsWith('..') && rel.endsWith('.html')
34
36
  ? rel.replace(/\\/g, '/').replace(/\.html$/, '')
35
37
  : path.basename(filePath, '.html');
38
+ let treeMode = /<\/?soma-(?:host|component|slot|fragment|repeat)\b/.test(text);
39
+ if (!treeMode && fs.existsSync(path.join(hostDir, 'config', 'page-markup.config.yaml'))) {
40
+ try { treeMode = treePageMode(hostDir, pageBase).markup === 'component-tree'; } catch { treeMode = true; }
41
+ }
42
+ if (treeMode) return treeCompletions(hostDir, pageBase, text, position);
36
43
  const uiPath = path.join(hostDir, 'ui', `${pageBase}_ui.yaml`);
37
44
  const existing = new Set();
38
45
  for (const m of text.matchAll(/data-soma-id=["']([^"']+)["']/g)) existing.add(m[1]);