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
@@ -4,9 +4,18 @@
4
4
  // 为什么不是每个作用域一个 RO:RO 实例本身有固定开销,几十个作用域就是几十个
5
5
  // 独立的观察循环与几十次回调调度;单例把它们合并成一次回调、一个批次。
6
6
  //
7
- // 零主动测量:尺寸只来自回调自带的 contentRect。
7
+ // 零主动测量:尺寸只来自回调自带的 entry(contentRect / borderBoxSize)。
8
8
  // **不提供任何补测 API**——提供 getBoundingClientRect 之类的入口,
9
9
  // 等于在性能契约上开了一个强制回流的口子,而口子一旦开就必然被用。
10
+ //
11
+ // 两个盒模型,两条独立的观察通道(`observe` 的 `box` 选项):
12
+ // * 内容盒(默认,不传即是,行为与历史逐字一致)——自适应作用域按它判档,
13
+ // 内边距不该算进"能摆多少内容"的可用宽度;
14
+ // * 边框盒(`{ box: 'border-box' }`)——虚拟列表按它算滚动几何,
15
+ // 一行在滚动条上占多少像素,就是它的边框盒那么多,内边距与边框一个都不能漏。
16
+ // 为什么不统一成一个:两者是**不同的量**,合成一个必然长期错着其中一边。
17
+ // 上一轮 VirtualList 就栽在这里——池子只给内容盒,行一有块向内边距,
18
+ // 记录的行高就比真实行盒小一圈,垫片、滚动条比例、跳转位置跟着一起偏。
10
19
 
11
20
  export interface SomaAdaptiveSize {
12
21
  width: number;
@@ -16,8 +25,17 @@ export interface SomaAdaptiveSize {
16
25
  export type SomaAdaptiveSizeCallback = (size: SomaAdaptiveSize) => void;
17
26
 
18
27
  export interface SomaAdaptiveObserverPool {
19
- /** 订阅元素尺寸;返回退订函数(幂等,重复调用不抛错) */
20
- observe(target: Element, onSize: SomaAdaptiveSizeCallback): () => void;
28
+ /**
29
+ * 订阅元素尺寸;返回退订函数(幂等,重复调用不抛错)。
30
+ * `options.box` 选盒模型:省略 = 内容盒(默认);`'border-box'` = 含内边距与边框的行盒。
31
+ * 选项类型就地写在签名里而不另立导出名:池子对外只该有一个 `observe`,
32
+ * 多一个导出符号就多一份要跟着走的对外契约。
33
+ */
34
+ observe(
35
+ target: Element,
36
+ onSize: SomaAdaptiveSizeCallback,
37
+ options?: { box?: 'content-box' | 'border-box' },
38
+ ): () => void;
21
39
  }
22
40
 
23
41
  const NOOP_UNSUBSCRIBE = (): void => {};
@@ -42,7 +60,80 @@ export function createAdaptiveObserverPool(): SomaAdaptiveObserverPool {
42
60
  return singleton;
43
61
  }
44
62
 
45
- function createDomPool(): SomaAdaptiveObserverPool {
63
+ /** 通道的键:订阅方要的是哪个盒。一批回调里只算被订阅的那一种,另一种连读都不读。 */
64
+ type BoxKind = 'content-box' | 'border-box';
65
+
66
+ /** 内容盒:RO 自带,一字未动——这是历史上唯一的口径。 */
67
+ function contentBoxSizeOf(entry: ResizeObserverEntry): SomaAdaptiveSize {
68
+ const rect = entry.contentRect;
69
+ return { width: rect.width, height: rect.height };
70
+ }
71
+
72
+ /**
73
+ * 边框盒:优先用 `borderBoxSize`(Chrome 84+ / Firefox 92+ / Safari 15.4+,
74
+ * 也是本库目标浏览器的全部),拿不到再走计算样式降级。
75
+ *
76
+ * 逻辑轴 → 物理轴:RO 给的是 `inlineSize`/`blockSize`(随书写方向翻转),
77
+ * 池子对外给的是 `width`/`height`。判据不额外读样式,用同一个 entry 里的
78
+ * `contentBoxSize` 与 `contentRect` 对表:inlineSize 对不上物理宽度就是竖排,两轴互换。
79
+ */
80
+ function borderBoxSizeOf(entry: ResizeObserverEntry): SomaAdaptiveSize {
81
+ const rect = entry.contentRect;
82
+ // 类型上这两个数组属性必有,实现上可能没有(老浏览器、单测里的假 RO),所以按可选读。
83
+ const optional = entry as unknown as {
84
+ borderBoxSize?: ReadonlyArray<{ inlineSize: number; blockSize: number }>;
85
+ contentBoxSize?: ReadonlyArray<{ inlineSize: number; blockSize: number }>;
86
+ };
87
+ // 注:Chrome 84–89 / Firefox 69–91 的 borderBoxSize 是单个对象而不是数组,这里按"拿不到"处理,
88
+ // 走下面的计算样式降级——结果一样对,只是多读一次样式,不值得为两个历史版本多一条分支。
89
+ const border = optional.borderBoxSize?.[0];
90
+ if (!border) return borderBoxFromStyle(entry.target, rect);
91
+ const content = optional.contentBoxSize?.[0];
92
+ const vertical = content !== undefined && Math.abs(content.inlineSize - rect.width) > 0.5;
93
+ return vertical
94
+ ? { width: border.blockSize, height: border.inlineSize }
95
+ : { width: border.inlineSize, height: border.blockSize };
96
+ }
97
+
98
+ /**
99
+ * 降级路径(没有 `borderBoxSize` 时):内容盒 + 计算样式里的内边距与边框 = 边框盒。
100
+ *
101
+ * 命中的是两类环境:① 老浏览器(Safari < 15.4、Chrome < 84)——它们同样不认
102
+ * `observe(target, { box })`,于是只在内容盒变化时触发;单改内边距那一帧收不到通知,
103
+ * 下一次尺寸变化会补上,行高在此期间偏小,但不会错得比改动之前更多。
104
+ * ② 单测里的假 RO(jsdom 本身没有 RO,走的是上面的空池)——假 RO 通常只喂 contentRect。
105
+ *
106
+ * 为什么这里读计算样式不违反"零主动测量":RO 回调发生在布局之后,样式此刻是干净的,
107
+ * 读它不触发重排;本文件又把"先读完整批、再逐个回调"定死,回调里的写不会让同批次后面的读变贵。
108
+ * 连 getComputedStyle 都没有的环境退回内容盒——偏小,但与本次改动之前的行为一致,不抛错。
109
+ */
110
+ function borderBoxFromStyle(target: Element, rect: DOMRectReadOnly): SomaAdaptiveSize {
111
+ // 内容盒为 0 = 元素当下没有盒(display:none、还没布局)。这种时候**不能**拿内边距与边框
112
+ // 凑出一个非零高度:调用方按"高度 > 0"判断行是否渲染完成(ERR-08),凭空给出 1px
113
+ // 会把一行没渲染的行当成量准了,几何直接被污染。现代浏览器的 borderBoxSize 此时也报 0。
114
+ if (rect.width === 0 && rect.height === 0) return { width: 0, height: 0 };
115
+ const view = target.ownerDocument?.defaultView;
116
+ if (!view || typeof view.getComputedStyle !== 'function') return { width: rect.width, height: rect.height };
117
+ const style = view.getComputedStyle(target);
118
+ const px = (value: string): number => {
119
+ const parsed = Number.parseFloat(value);
120
+ return Number.isFinite(parsed) ? parsed : 0;
121
+ };
122
+ return {
123
+ width: rect.width + px(style.paddingLeft) + px(style.paddingRight)
124
+ + px(style.borderLeftWidth) + px(style.borderRightWidth),
125
+ height: rect.height + px(style.paddingTop) + px(style.paddingBottom)
126
+ + px(style.borderTopWidth) + px(style.borderBottomWidth),
127
+ };
128
+ }
129
+
130
+ /**
131
+ * 一个盒模型一条通道:各自一个 RO、一张订阅表。
132
+ * 为什么不共用一个 RO:`observe(target, { box })` 是**按元素**记的,同一元素再 observe 一次
133
+ * 会覆盖上一次的盒模型——两类调用方撞到同一个元素时,后订阅的会把先订阅的触发口径改掉。
134
+ * 分成两条通道后互不相干,单例的成本承诺也还在(最多两个 RO,不随作用域数量增长)。
135
+ */
136
+ function createBoxChannel(box: BoxKind): { observe(target: Element, onSize: SomaAdaptiveSizeCallback): () => void } {
46
137
  /** 元素 → 该元素上的全部回调。WeakMap:元素被卸载即随之回收,无需调用方清场 */
47
138
  const subscribers = new WeakMap<Element, Set<SomaAdaptiveSizeCallback>>();
48
139
  let observer: ResizeObserver | null = null;
@@ -50,13 +141,20 @@ function createDomPool(): SomaAdaptiveObserverPool {
50
141
  const ensureObserver = (): ResizeObserver => {
51
142
  if (observer) return observer;
52
143
  observer = new ResizeObserver((entries) => {
144
+ // 先把整批的尺寸读完,再逐个回调:回调里同步写样式是常见写法,
145
+ // 边读边发会让后面的读撞上被改脏的布局(边框盒的计算样式降级路径尤其吃这一下)。
146
+ const batch: Array<{ callbacks: SomaAdaptiveSizeCallback[]; size: SomaAdaptiveSize }> = [];
53
147
  for (const entry of entries) {
54
148
  const callbacks = subscribers.get(entry.target);
55
149
  if (!callbacks || callbacks.size === 0) continue;
56
- const rect = entry.contentRect;
57
- const size: SomaAdaptiveSize = { width: rect.width, height: rect.height };
58
150
  // 拷贝一份再遍历:回调里退订自己是常见写法,直接遍历原 Set 会漏掉后续项
59
- for (const callback of [...callbacks]) callback(size);
151
+ batch.push({
152
+ callbacks: [...callbacks],
153
+ size: box === 'border-box' ? borderBoxSizeOf(entry) : contentBoxSizeOf(entry),
154
+ });
155
+ }
156
+ for (const item of batch) {
157
+ for (const callback of item.callbacks) callback(item.size);
60
158
  }
61
159
  });
62
160
  return observer;
@@ -69,7 +167,10 @@ function createDomPool(): SomaAdaptiveObserverPool {
69
167
  if (!callbacks) {
70
168
  callbacks = new Set();
71
169
  subscribers.set(target, callbacks);
72
- ro.observe(target);
170
+ // 内容盒是 observe 的默认盒,仍按历史调用不传第二参(老引擎连选项字典都不认);
171
+ // 边框盒必须显式声明,否则"只改内边距、边框盒变了而内容盒没变"的一帧收不到通知。
172
+ if (box === 'border-box') ro.observe(target, { box: 'border-box' });
173
+ else ro.observe(target);
73
174
  }
74
175
  callbacks.add(onSize);
75
176
 
@@ -88,3 +189,16 @@ function createDomPool(): SomaAdaptiveObserverPool {
88
189
  },
89
190
  };
90
191
  }
192
+
193
+ function createDomPool(): SomaAdaptiveObserverPool {
194
+ const channels: Record<BoxKind, ReturnType<typeof createBoxChannel>> = {
195
+ 'content-box': createBoxChannel('content-box'),
196
+ 'border-box': createBoxChannel('border-box'),
197
+ };
198
+
199
+ return {
200
+ observe(target, onSize, options): () => void {
201
+ return channels[options?.box === 'border-box' ? 'border-box' : 'content-box'].observe(target, onSize);
202
+ },
203
+ };
204
+ }
@@ -89,6 +89,35 @@ function compileEvents(eventConfig: ParsedEvent[]): {
89
89
  return { events, eventIndex };
90
90
  }
91
91
 
92
+ /**
93
+ * 列表行 / 对象作用域里的 model 的拒收文案。
94
+ *
95
+ * 引擎为什么不做这件事(两种写法两个原因,文案分开给,免得改法也跟着含混):
96
+ * - 行变量打头(`item.qty`):行数据是数组元素,数组不经响应式代理,回写行字段既不触发重渲、
97
+ * 上层也不会知道——组件那一侧对同一个写法的拒收(component-manager 的 rowVariableRefusal)同因同源;
98
+ * - 页面路径打头(`page.kw`):写回本身走得通(行内组件实例的 model prop 就是这么回写的),
99
+ * 但渲染器在行 / 对象作用域里根本不建 model 绑定:控件不按数据选中、整表同步(syncModels)
100
+ * 只认编译出来的绑定表,行内控件的值到不了处理器。要补齐得连回写、同屏刷新、
101
+ * 无键列表重建时的焦点一起解决,不是在这里加一行能了的事。
102
+ *
103
+ * 所以这里只拒收,不猜:编译期抛错,页面起不来,作者立刻知道;
104
+ * 而不是让一个看着正常的控件在用户手上失效。
105
+ */
106
+ function scopedModelRefusal(where: string, model: string, resolver: SomaScopeResolver): string {
107
+ const first = model.split('.')[0];
108
+ const rowRooted = resolver.hasVar(first) && resolver.getVarPath(first) !== '';
109
+ const why = rowRooted
110
+ ? `"${first}" 是行 / 嵌套作用域变量,行数据不在响应式代理里(数组靠整体替换触发更新),写进去上层不会知道`
111
+ : '渲染器在行 / 对象作用域里不建 model 绑定:控件既不按数据选中,改了也不回写,整表同步同样看不见它';
112
+ return `[soma-core][引擎] ${where}.model: ${model} —— 列表行 / 对象作用域里不支持 model(${why})。`
113
+ + '改法二选一:'
114
+ + '① 显示值用单向绑定(`item.x`、`item.x@value` / `@checked`),改值走事件——'
115
+ + '处理器第一个实参就是当前行数据、第二个是 DOM 事件,在处理器里按引用替换写回页面数据'
116
+ + '(如 this.items = this.items.map(...));'
117
+ + '② 换成带 model prop 的组件实例,props 里把它绑到页面路径(`page.x`)——'
118
+ + '行内实例的 model 回写经页面响应式代理落地,是引擎支持的那条路。';
119
+ }
120
+
92
121
  export class SomaManifestCompiler {
93
122
  compile(input: SomaManifestCompilerInput): SomaRuntimeManifest {
94
123
  const bindings: SomaCompiledBinding[] = [];
@@ -140,7 +169,7 @@ export class SomaManifestCompiler {
140
169
  const element = input.adapter.findAnchor(input.container, rawKey);
141
170
  const role = element ? input.adapter.readRole(element) : null;
142
171
  const dataPath = input.resolver.resolvePath(showValue.bind.obj);
143
- this.validateScopedPipes(showValue.show, rawKey, input);
172
+ this.validateScopedDeclarations(showValue.show, rawKey, input);
144
173
  bindings.push({
145
174
  id: `${rawKey}:${bindings.length}`,
146
175
  somaId: rawKey,
@@ -149,6 +178,8 @@ export class SomaManifestCompiler {
149
178
  watchPaths: dataPath ? [dataPath] : [],
150
179
  childShowConfig: showValue.show,
151
180
  roleBy: showValue.bind.role_by,
181
+ ...(showValue.bind.key ? { keyPath: showValue.bind.key, itemAlias: showValue.bind.var } : {}),
182
+ ...(showValue.bind.repeatPlanId ? { repeatPlanId: showValue.bind.repeatPlanId, itemAlias: showValue.bind.var } : {}),
152
183
  });
153
184
  // 嵌套绑定同样支持整块显隐:再补一条 when 绑定(同一锚点,互不干扰)
154
185
  if (typeof showValue.when === 'string') {
@@ -278,8 +309,17 @@ export class SomaManifestCompiler {
278
309
  return parsed;
279
310
  }
280
311
 
281
- /** 列表/对象子作用域配置的管道预校验(行内解释执行前的编译期 fail fast) */
282
- private validateScopedPipes(
312
+ /**
313
+ * 列表 / 对象子作用域配置的编译期闸门:管道白名单预校验 + model 拒收。
314
+ *
315
+ * 行内绑定是解释执行的(不经这里编译成 BindingEntry),编译期不看就只剩运行时才发现。
316
+ * 两件事都在这一趟走完:管道名不在白名单 → fail fast;行 / 对象作用域里写了 model → 拒收。
317
+ * model 那条从渲染器的挂载期告警移上来(原 SomaDomRenderer.reportScopedModels):
318
+ * 告警发生在绑定表建好之后,页面照常上屏,控件却既不按数据选中、改了也不回写——
319
+ * 一个看着正常、实则失效的表单控件,比页面起不来危险得多。页面与组件实例都经这一趟编译,
320
+ * 两边同一道闸(组件实例不过契约校验器,只有这里拦得住)。
321
+ */
322
+ private validateScopedDeclarations(
283
323
  show: ShowMapping,
284
324
  where: string,
285
325
  input: SomaManifestCompilerInput,
@@ -290,15 +330,18 @@ export class SomaManifestCompiler {
290
330
  continue;
291
331
  }
292
332
  if (this.isNestedShowMapping(value)) {
293
- this.validateScopedPipes(value.show, `${where}.${rawKey}.show`, input);
333
+ this.validateScopedDeclarations(value.show, `${where}.${rawKey}.show`, input);
294
334
  continue;
295
335
  }
296
336
  if (this.isExtendedShowValue(value)) {
337
+ if (typeof value.model === 'string') {
338
+ throw new Error(scopedModelRefusal(`${where}.${rawKey}`, value.model, input.resolver));
339
+ }
297
340
  if (value.text) {
298
341
  this.parsePipes(value.text, `${where}.${rawKey}.text`, input);
299
342
  }
300
343
  if (value.show) {
301
- this.validateScopedPipes(value.show, `${where}.${rawKey}.show`, input);
344
+ this.validateScopedDeclarations(value.show, `${where}.${rawKey}.show`, input);
302
345
  }
303
346
  }
304
347
  }
@@ -10,6 +10,7 @@ import { deriveBlockExample } from './example-blocks';
10
10
  import { renderFieldLines } from '../../shared/component/field-lines';
11
11
  import { deriveContractSample, hasRenderableSample } from '../../shared/component/derive-sample';
12
12
  import { renderKeyboardMatrixLine } from './keyboard-matrix';
13
+ import { copyCatalogExamples, formatSomaCatalogExample, selectSomaCatalogExample, type CatalogExampleCapabilities } from './catalog-examples';
13
14
  import {
14
15
  componentTokenVar,
15
16
  type SomaComponentContract,
@@ -17,6 +18,8 @@ import {
17
18
  type SomaContractOverlay,
18
19
  type SomaGeometryFamily,
19
20
  type SomaContractProp,
21
+ type SomaContractExample,
22
+ type SomaContractStructure,
20
23
  } from '../../shared/types/component-contract.types';
21
24
  import type { SomaComponentDefinition } from './component-definition.types';
22
25
 
@@ -54,6 +57,14 @@ export interface SomaAiCatalogEntry {
54
57
  keyboard?: { contract: SomaContractKeyboard };
55
58
  /** 浮层行为契约(声明了才有) */
56
59
  overlay?: SomaContractOverlay;
60
+ /** Public structural summary; implementation anchor names/selectors never enter the catalog. */
61
+ structure?: {
62
+ kind: SomaContractStructure['kind'];
63
+ rootless: boolean;
64
+ treeMount: SomaContractStructure['tree_mount'];
65
+ semantics?: SomaContractStructure['semantics'];
66
+ slots: Array<{ name: string; kind: 'projection' | 'collection'; directChildren: boolean; rowContainer?: 'none' | 'list-item' }>;
67
+ };
57
68
  /** 契约级依赖(F-46):装这个还要装什么 */
58
69
  uses?: string[];
59
70
  /** 组件级令牌(M-1):这个组件开放的可调旋钮及其 CSS 变量名 */
@@ -62,6 +73,7 @@ export interface SomaAiCatalogEntry {
62
73
  whenToUse: string;
63
74
  whenNotToUse?: string;
64
75
  example: string;
76
+ examples?: readonly SomaContractExample[];
65
77
  antiPatterns?: string[];
66
78
  };
67
79
  /**
@@ -155,6 +167,14 @@ export function buildCatalogEntry(contract: SomaComponentContract): SomaAiCatalo
155
167
  ? { keyboard: { contract: contract.keyboard } }
156
168
  : {}),
157
169
  ...(contract.overlay ? { overlay: contract.overlay } : {}),
170
+ ...(contract.structure ? { structure: {
171
+ kind: contract.structure.kind, rootless: contract.structure.rootless, treeMount: contract.structure.tree_mount,
172
+ ...(contract.structure.semantics ? { semantics: { ...contract.structure.semantics, allowed: [...contract.structure.semantics.allowed] } } : {}),
173
+ slots: Object.entries(contract.structure.slots ?? {}).map(([name, slot]) => ({
174
+ name, kind: slot.kind, directChildren: slot.directChildren,
175
+ ...(slot.rowContainer ? { rowContainer: slot.rowContainer } : {}),
176
+ })),
177
+ } } : {}),
158
178
  ...(contract.uses && contract.uses.length > 0 ? { uses: [...contract.uses] } : {}),
159
179
  ...(contract.tokens && Object.keys(contract.tokens).length > 0
160
180
  ? {
@@ -171,6 +191,7 @@ export function buildCatalogEntry(contract: SomaComponentContract): SomaAiCatalo
171
191
  whenToUse: contract.ai.when_to_use,
172
192
  whenNotToUse: contract.ai.when_not_to_use,
173
193
  example: contract.ai.example,
194
+ ...(contract.ai.examples ? { examples: copyCatalogExamples(contract.ai.examples) } : {}),
174
195
  antiPatterns: contract.ai.anti_patterns,
175
196
  }
176
197
  : undefined,
@@ -196,6 +217,8 @@ export interface GenerateAiCatalogOptions {
196
217
  * 不传则目录产物与历史完全一致。
197
218
  */
198
219
  conventions?: string;
220
+ /** Human/tool consumers may opt in; AI/native-page consumers remain legacy-only by default. */
221
+ exampleCapabilities?: CatalogExampleCapabilities;
199
222
  }
200
223
 
201
224
  /**
@@ -223,7 +246,7 @@ export function generateAiCatalog(
223
246
  return {
224
247
  generatedFrom: entries.map((entry) => `${entry.name}@${entry.version}`),
225
248
  entries,
226
- markdown: renderMarkdown(entries, options?.conventions),
249
+ markdown: renderMarkdown(entries, options?.conventions, options?.exampleCapabilities),
227
250
  };
228
251
  }
229
252
 
@@ -256,7 +279,7 @@ function propTypeLabel(prop: SomaContractProp): string {
256
279
  /** 设计规范章节标题:固定文案,供调用方与测试稳定断言 */
257
280
  const CONVENTIONS_HEADING = '## 版式与视觉规范(生成页面时必须遵守)';
258
281
 
259
- function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string): string {
282
+ function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string, exampleCapabilities?: CatalogExampleCapabilities): string {
260
283
  const lines: string[] = [
261
284
  '# SOMA 组件目录(AI 查表用,契约自动生成 — 禁止手改)',
262
285
  '',
@@ -336,6 +359,13 @@ function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string): st
336
359
  `插槽:${entry.slots.map((s) => `\`${s.name}\`${s.required ? '(必填)' : ''} ${s.desc}`).join(';')}`,
337
360
  );
338
361
  }
362
+ if (entry.structure) {
363
+ lines.push('', `结构:${entry.structure.kind};挂载 ${entry.structure.treeMount};${entry.structure.rootless ? '编译消隐,无运行时实例' : '有稳定运行时宿主'}`);
364
+ if (entry.structure.semantics) lines.push(`语义:${entry.structure.semantics.allowed.join(' / ')}(默认 ${entry.structure.semantics.default})`);
365
+ for (const slot of entry.structure.slots) {
366
+ lines.push(`结构槽 ${slot.name}:${slot.kind}${slot.directChildren ? ',保持直接子项' : ''}${slot.rowContainer ? `,行容器 ${slot.rowContainer}` : ''}`);
367
+ }
368
+ }
339
369
 
340
370
  // 键盘表 / 浮层语义 / 依赖 / 令牌(REQ-011):各一行,声明了才出现。
341
371
  // 它们让"这个组件按键怎么走、Esc 关不关、还要装什么、能调什么"不必读源码——
@@ -357,10 +387,18 @@ function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string): st
357
387
  lines.push(`组件令牌:${entry.tokens.map((token) => `\`${token.cssVar}\`(默认 ${token.default})${token.desc}`).join(';')}`);
358
388
  }
359
389
 
360
- if (entry.ai?.example) {
390
+ const selectedExample = selectSomaCatalogExample(entry, exampleCapabilities);
391
+ if (selectedExample) {
392
+ lines.push('', `完整用法(${selectedExample.format},按消费能力选择):`, '```', formatSomaCatalogExample(selectedExample), '```');
393
+ } else if (entry.ai?.example) {
361
394
  lines.push('');
362
395
  lines.push('用法:');
363
396
  lines.push('```');
397
+ // The compatibility string is never a side channel for tree source into
398
+ // legacy-only/AI catalog readers.
399
+ if (/<\/?soma-(?:host|component|slot|fragment|repeat)\b/i.test(entry.ai.example)) {
400
+ throw new TypeError(`[catalog] ${entry.name}: tree source belongs in format-labelled ai.examples`);
401
+ }
364
402
  lines.push(entry.ai.example.trimEnd());
365
403
  lines.push('```');
366
404
 
@@ -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
+ }
@@ -14,7 +14,7 @@ import type { SomaComponentDefinition } from './component-definition.types';
14
14
 
15
15
  export class SomaComponentDefaultsError extends Error {
16
16
  constructor(message: string) {
17
- super(`[SomaComponentDefaults] ${message}`);
17
+ super(`[soma-core][组件] ${message}`);
18
18
  this.name = 'SomaComponentDefaultsError';
19
19
  }
20
20
  }
@@ -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
  /**
@@ -25,7 +27,7 @@ export const SOMA_CHILD_COMPONENT_ID_ATTR = 'data-soma-child-id';
25
27
 
26
28
  export class SomaComponentExpandError extends Error {
27
29
  constructor(message: string) {
28
- super(`[SomaComponentExpander] ${message}`);
30
+ super(`[soma-core][组件] ${message}`);
29
31
  this.name = 'SomaComponentExpandError';
30
32
  }
31
33
  }
@@ -45,12 +47,13 @@ export class SomaComponentExpander {
45
47
  }
46
48
 
47
49
  /** @returns 本次展开分配的 scopeId(宿主已展开时返回既有的那个) */
48
- expand(host: HTMLElement, def: SomaComponentDefinition): string {
50
+ expand(host: HTMLElement, def: SomaComponentDefinition, plan?: StructurePlan, staticProps?: Record<string, unknown>): string {
49
51
  const existing = this.scopeIdOf(host);
50
52
  if (existing !== null) {
51
53
  return existing;
52
54
  }
53
55
  const scopeId = `c${++scopeSeq}`;
56
+ const prepared = prepareStructureTemplate(host, def, plan, staticProps);
54
57
 
55
58
  // 1. 摘出页面提供的插槽内容(在模板注入前,DocumentFragment 引用在注入后仍有效)
56
59
  const slotContent = new Map<string, DocumentFragment>();
@@ -62,7 +65,8 @@ export class SomaComponentExpander {
62
65
  }
63
66
 
64
67
  // 2. 注入组件模板
65
- host.innerHTML = def.templateHtml;
68
+ commitStructureTemplate(host, prepared);
69
+ if (prepared.rootAlias) registerSomaRootAlias(host, scopeId, prepared.rootAlias);
66
70
 
67
71
  // 3. 内部锚点作用域化(含 <template> 内容,插槽内容尚未注入故不受影响)
68
72
  // 此刻宿主子树里的锚点,恰好就是"本组件模板写下的"全集——包括写在
@@ -82,13 +86,24 @@ export class SomaComponentExpander {
82
86
  for (const outlet of outlets) {
83
87
  const slotName = outlet.getAttribute(SOMA_SLOT_OUTLET_ATTR)!;
84
88
  const content = slotContent.get(slotName);
85
- if (!content) {
89
+ // Existing definitions require the named projection to exist, not to be
90
+ // nonempty. Meaningful-content validation belongs to the new structure
91
+ // protocol; an explicitly empty legacy Drawer body remains compatible.
92
+ const emptyStructureContent = def.contract.structure && content
93
+ && ![...content.childNodes].some(node => node.nodeType === 1 || (node.nodeType === 3 && !!node.textContent?.trim()));
94
+ if (!content || emptyStructureContent) {
95
+ slotContent.delete(slotName);
86
96
  if (def.contract.slots?.[slotName]?.required) {
87
97
  throw new SomaComponentExpandError(
88
98
  `组件 "${def.contract.name}" 的必填插槽 "${slotName}" 缺少内容(<template data-soma-slot="${slotName}">)`,
89
99
  );
90
100
  }
91
- outlet.remove();
101
+ // A collection's optional empty state is an independent semantic row;
102
+ // an absent slot removes that row, not just its now-empty outlet.
103
+ const emptyAnchor = def.structureAdapter?.layoutRoots.empty;
104
+ const parent = outlet.parentElement;
105
+ if (slotName === 'empty' && emptyAnchor && parent?.getAttribute(SOMA_SCOPED_ID_ATTR) === emptyAnchor) parent.remove();
106
+ else outlet.remove();
92
107
  continue;
93
108
  }
94
109
  outlet.replaceWith(content);
@@ -102,6 +117,7 @@ export class SomaComponentExpander {
102
117
  }
103
118
 
104
119
  host.setAttribute(SOMA_COMPONENT_READY_ATTR, scopeId);
120
+ registerPreparedStructure(host, def, scopeId, prepared.staticProps);
105
121
  return scopeId;
106
122
  }
107
123