soma-core 1.3.1 → 1.3.3

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 (233) hide show
  1. package/README.md +42 -0
  2. package/app/SomaPageClient.tsx +39 -2
  3. package/app/[...path]/page.tsx +7 -6
  4. package/app/api/[...path]/route.ts +3 -3
  5. package/app/api/soma-registry/[...path]/route.ts +67 -0
  6. package/app/components/SomaHostPage.tsx +3 -8
  7. package/app/components/SomaPageClientBoundary.tsx +13 -0
  8. package/app/layout.tsx +6 -1
  9. package/app/page.tsx +3 -3
  10. package/app/soma/manifest/route.ts +1 -0
  11. package/app/soma/page-object/route.ts +1 -1
  12. package/core/build/compiler/full-manifest-builder.ts +6 -1
  13. package/core/build/compiler/rollup-plugin-soma.ts +6 -0
  14. package/core/build/compiler/soma-manifest-webpack-plugin.js +4 -0
  15. package/core/build/compiler/soma-precompile.js +3507 -2387
  16. package/core/build/compiler/soma-precompile.ts +31 -2
  17. package/core/build/compiler/soma-rspack-yaml-loader.js +3 -0
  18. package/core/build/compiler/soma-webpack-loader.js +7 -1
  19. package/core/build/compiler/vite-plugin-soma.ts +11 -1
  20. package/core/build/component/package-loader.ts +135 -0
  21. package/core/build/eject/apply-eject.ts +133 -0
  22. package/core/build/eject/plan-eject.ts +139 -0
  23. package/core/client/adaptive/flush-scheduler.ts +96 -0
  24. package/core/client/adaptive/hysteresis.ts +56 -0
  25. package/core/client/adaptive/index.ts +23 -0
  26. package/core/client/adaptive/observer-pool.ts +90 -0
  27. package/core/client/base/SomaPageRootBase.ts +50 -0
  28. package/core/client/compiler/adaptive-compile.ts +136 -0
  29. package/core/client/compiler/manifest-compiler.ts +155 -27
  30. package/core/client/component/ai-catalog.ts +262 -0
  31. package/core/client/component/component-definition.types.ts +65 -0
  32. package/core/client/component/component-expander.ts +119 -0
  33. package/core/client/component/component-manager.ts +933 -0
  34. package/core/client/component/component-pack.ts +271 -0
  35. package/core/client/component/component-registry.ts +71 -0
  36. package/core/client/component/pack-styles.ts +94 -0
  37. package/core/client/component/scoped-adapter.ts +85 -0
  38. package/core/client/component/verify-pack.ts +247 -0
  39. package/core/client/container/MiniProgramContainerAdapter.ts +15 -1
  40. package/core/client/container/ReactNativeContainerAdapter.ts +15 -1
  41. package/core/client/container/SomaContainerAdapter.ts +186 -180
  42. package/core/client/data/data-object-resolver.ts +417 -0
  43. package/core/client/diagnostics/SomaDiagnostics.ts +187 -186
  44. package/core/client/diagnostics/boot-timings.ts +152 -0
  45. package/core/client/engine/asset-resolver.ts +12 -2
  46. package/core/client/engine/dom-renderer.ts +235 -16
  47. package/core/client/engine/emit-event.ts +21 -0
  48. package/core/client/engine/event-engine.ts +34 -4
  49. package/core/client/engine/on-change-engine.ts +1 -1
  50. package/core/client/engine/property-watcher.ts +1 -1
  51. package/core/client/engine/reactive-proxy.ts +3 -3
  52. package/core/client/engine/render-engine.ts +43 -4
  53. package/core/client/engine/runtime-builder.ts +23 -0
  54. package/core/client/engine/soma-bootstrap.ts +389 -5
  55. package/core/client/engine/style-binder.ts +47 -1
  56. package/core/client/host-bridge/empty-host/data/README.md +17 -0
  57. package/core/client/infra/http/SomaHttpService.ts +5 -0
  58. package/core/client/observability/error-reporter.ts +173 -0
  59. package/core/client/parser/adaptive-parser.ts +264 -0
  60. package/core/client/parser/data-config-parser.ts +396 -0
  61. package/core/client/parser/pipeline-parser.ts +15 -3
  62. package/core/client/parser/style-config-parser.ts +65 -2
  63. package/core/client/parser/ui-config-parser.ts +52 -3
  64. package/core/client/pipes/pipe-registry.ts +249 -0
  65. package/core/client/quality/SomaQualityRegistry.ts +3 -0
  66. package/core/client/registry/declaration-renderer.ts +159 -0
  67. package/core/client/registry/index.ts +28 -0
  68. package/core/client/registry/page-lifecycle.ts +171 -0
  69. package/core/client/registry/remote-page.ts +139 -0
  70. package/core/client/runtime/SomaRuntimeServices.ts +24 -0
  71. package/core/client/scheduler/SomaScheduler.ts +29 -1
  72. package/core/client/security/attribute-presence.ts +70 -0
  73. package/core/client/security/html-sanitizer.ts +113 -0
  74. package/core/client/security/url-guard.ts +0 -0
  75. package/core/client/theme/theme-engine.ts +936 -0
  76. package/core/client/typography/typography-base.ts +34 -0
  77. package/core/client/validation/contract-validator.ts +48 -5
  78. package/core/index.ts +190 -2
  79. package/core/server/api/IService.ts +18 -6
  80. package/core/server/api/load-host-service.ts +3 -3
  81. package/core/server/host/content-security-policy.ts +190 -0
  82. package/core/server/host/csp-nonce-metadata.ts +75 -0
  83. package/core/server/host/resolve-host-request-hook.ts +5 -0
  84. package/core/server/host/server-page-assets.ts +10 -0
  85. package/core/server/index.ts +30 -1
  86. package/core/server/infra/cache/ServerFileCache.ts +1 -1
  87. package/core/server/mock/node/cli.mjs +2 -2
  88. package/core/server/registry/api-registry-store.ts +518 -0
  89. package/core/server/registry/conditional-object-store.ts +29 -0
  90. package/core/server/registry/declaration-precompiler.ts +129 -0
  91. package/core/server/registry/in-memory-conditional-object-store.ts +43 -0
  92. package/core/server/registry/index.ts +142 -0
  93. package/core/server/registry/page-registry-repository.ts +373 -0
  94. package/core/server/registry/page-registry-store.ts +903 -0
  95. package/core/server/registry/registry-error.ts +17 -0
  96. package/core/server/registry/registry-file-lock.ts +173 -0
  97. package/core/server/registry/registry-response.ts +71 -0
  98. package/core/server/registry/registry-subjects.ts +194 -0
  99. package/core/server/registry/registry-write-pipeline.ts +240 -0
  100. package/core/server/registry/request-body-limit.ts +99 -0
  101. package/core/server/registry/services/apis/Get.ts +25 -0
  102. package/core/server/registry/services/apis/List.ts +41 -0
  103. package/core/server/registry/services/apis/Register.ts +39 -0
  104. package/core/server/registry/services/apis/Unregister.ts +24 -0
  105. package/core/server/registry/services/index.ts +40 -0
  106. package/core/server/registry/services/pages/Get.ts +86 -0
  107. package/core/server/registry/services/pages/List.ts +53 -0
  108. package/core/server/registry/services/pages/Register.ts +49 -0
  109. package/core/server/registry/services/pages/Rollback.ts +36 -0
  110. package/core/server/registry/services/pages/Unregister.ts +23 -0
  111. package/core/server/registry/services/service-utils.ts +21 -0
  112. package/core/server/registry/validation/compile-gate.ts +71 -0
  113. package/core/server/registry/validation/component-existence.ts +55 -0
  114. package/core/server/registry/validation/credential-ban.ts +86 -0
  115. package/core/server/registry/validation/cross-check.ts +77 -0
  116. package/core/server/registry/validation/declaration-safety-scan.ts +102 -0
  117. package/core/shared/types/adaptive.types.ts +109 -0
  118. package/core/shared/types/component-contract.types.ts +110 -0
  119. package/core/shared/types/data-config.types.ts +105 -0
  120. package/core/shared/types/domain.types.ts +6 -0
  121. package/core/shared/types/engine.types.ts +41 -35
  122. package/core/shared/types/manifest.types.ts +55 -32
  123. package/core/shared/types/scope-manifest.types.ts +96 -0
  124. package/core/shared/types/style-config.types.ts +9 -0
  125. package/core/shared/types/ui-config.types.ts +118 -98
  126. package/dist/cli/soma.js +20 -5
  127. package/dist/core/index.cjs +5388 -888
  128. package/dist/types/build/compiler/full-manifest-builder.d.ts +4 -0
  129. package/dist/types/build/compiler/rollup-plugin-soma.d.ts +1 -0
  130. package/dist/types/build/compiler/soma-precompile.d.ts +9 -0
  131. package/dist/types/build/compiler/vite-plugin-soma.d.ts +3 -0
  132. package/dist/types/build/component/package-loader.d.ts +9 -0
  133. package/dist/types/build/eject/apply-eject.d.ts +22 -0
  134. package/dist/types/build/eject/plan-eject.d.ts +32 -0
  135. package/dist/types/client/adaptive/flush-scheduler.d.ts +13 -0
  136. package/dist/types/client/adaptive/hysteresis.d.ts +16 -0
  137. package/dist/types/client/adaptive/index.d.ts +5 -0
  138. package/dist/types/client/adaptive/observer-pool.d.ts +15 -0
  139. package/dist/types/client/base/SomaPageRootBase.d.ts +33 -0
  140. package/dist/types/client/compiler/adaptive-compile.d.ts +26 -0
  141. package/dist/types/client/compiler/manifest-compiler.d.ts +13 -2
  142. package/dist/types/client/component/ai-catalog.d.ts +73 -0
  143. package/dist/types/client/component/component-definition.types.d.ts +54 -0
  144. package/dist/types/client/component/component-expander.d.ts +25 -0
  145. package/dist/types/client/component/component-manager.d.ts +160 -0
  146. package/dist/types/client/component/component-pack.d.ts +90 -0
  147. package/dist/types/client/component/component-registry.d.ts +12 -0
  148. package/dist/types/client/component/pack-styles.d.ts +22 -0
  149. package/dist/types/client/component/scoped-adapter.d.ts +18 -0
  150. package/dist/types/client/component/verify-pack.d.ts +14 -0
  151. package/dist/types/client/data/data-object-resolver.d.ts +71 -0
  152. package/dist/types/client/diagnostics/SomaDiagnostics.d.ts +2 -1
  153. package/dist/types/client/diagnostics/boot-timings.d.ts +30 -0
  154. package/dist/types/client/engine/asset-resolver.d.ts +7 -1
  155. package/dist/types/client/engine/dom-renderer.d.ts +49 -1
  156. package/dist/types/client/engine/emit-event.d.ts +6 -0
  157. package/dist/types/client/engine/event-engine.d.ts +6 -0
  158. package/dist/types/client/engine/render-engine.d.ts +26 -1
  159. package/dist/types/client/engine/runtime-builder.d.ts +7 -0
  160. package/dist/types/client/engine/soma-bootstrap.d.ts +122 -0
  161. package/dist/types/client/infra/http/SomaHttpService.d.ts +2 -0
  162. package/dist/types/client/observability/error-reporter.d.ts +51 -0
  163. package/dist/types/client/parser/adaptive-parser.d.ts +28 -0
  164. package/dist/types/client/parser/data-config-parser.d.ts +34 -0
  165. package/dist/types/client/parser/pipeline-parser.d.ts +2 -0
  166. package/dist/types/client/parser/style-config-parser.d.ts +5 -3
  167. package/dist/types/client/parser/ui-config-parser.d.ts +22 -1
  168. package/dist/types/client/pipes/pipe-registry.d.ts +38 -0
  169. package/dist/types/client/registry/declaration-renderer.d.ts +51 -0
  170. package/dist/types/client/registry/index.d.ts +10 -0
  171. package/dist/types/client/registry/page-lifecycle.d.ts +61 -0
  172. package/dist/types/client/registry/remote-page.d.ts +52 -0
  173. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +16 -0
  174. package/dist/types/client/scheduler/SomaScheduler.d.ts +8 -0
  175. package/dist/types/client/security/attribute-presence.d.ts +7 -0
  176. package/dist/types/client/security/html-sanitizer.d.ts +37 -0
  177. package/dist/types/client/security/url-guard.d.ts +11 -0
  178. package/dist/types/client/theme/theme-engine.d.ts +49 -0
  179. package/dist/types/client/typography/typography-base.d.ts +15 -0
  180. package/dist/types/client/validation/contract-validator.d.ts +2 -0
  181. package/dist/types/index.d.ts +36 -2
  182. package/dist/types/server/api/IService.d.ts +18 -6
  183. package/dist/types/server/host/content-security-policy.d.ts +53 -0
  184. package/dist/types/server/host/csp-nonce-metadata.d.ts +32 -0
  185. package/dist/types/server/host/resolve-host-request-hook.d.ts +5 -0
  186. package/dist/types/server/host/server-page-assets.d.ts +5 -0
  187. package/dist/types/server/index.d.ts +4 -1
  188. package/dist/types/server/registry/api-registry-store.d.ts +141 -0
  189. package/dist/types/server/registry/conditional-object-store.d.ts +27 -0
  190. package/dist/types/server/registry/declaration-precompiler.d.ts +30 -0
  191. package/dist/types/server/registry/in-memory-conditional-object-store.d.ts +8 -0
  192. package/dist/types/server/registry/index.d.ts +29 -0
  193. package/dist/types/server/registry/page-registry-repository.d.ts +58 -0
  194. package/dist/types/server/registry/page-registry-store.d.ts +259 -0
  195. package/dist/types/server/registry/registry-error.d.ts +12 -0
  196. package/dist/types/server/registry/registry-file-lock.d.ts +20 -0
  197. package/dist/types/server/registry/registry-response.d.ts +18 -0
  198. package/dist/types/server/registry/registry-subjects.d.ts +59 -0
  199. package/dist/types/server/registry/registry-write-pipeline.d.ts +48 -0
  200. package/dist/types/server/registry/request-body-limit.d.ts +31 -0
  201. package/dist/types/server/registry/services/apis/Get.d.ts +10 -0
  202. package/dist/types/server/registry/services/apis/List.d.ts +10 -0
  203. package/dist/types/server/registry/services/apis/Register.d.ts +13 -0
  204. package/dist/types/server/registry/services/apis/Unregister.d.ts +12 -0
  205. package/dist/types/server/registry/services/index.d.ts +3 -0
  206. package/dist/types/server/registry/services/pages/Get.d.ts +10 -0
  207. package/dist/types/server/registry/services/pages/List.d.ts +13 -0
  208. package/dist/types/server/registry/services/pages/Register.d.ts +11 -0
  209. package/dist/types/server/registry/services/pages/Rollback.d.ts +9 -0
  210. package/dist/types/server/registry/services/pages/Unregister.d.ts +9 -0
  211. package/dist/types/server/registry/services/service-utils.d.ts +10 -0
  212. package/dist/types/server/registry/validation/compile-gate.d.ts +10 -0
  213. package/dist/types/server/registry/validation/component-existence.d.ts +14 -0
  214. package/dist/types/server/registry/validation/credential-ban.d.ts +15 -0
  215. package/dist/types/server/registry/validation/cross-check.d.ts +16 -0
  216. package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +15 -0
  217. package/dist/types/shared/types/adaptive.types.d.ts +88 -0
  218. package/dist/types/shared/types/component-contract.types.d.ts +68 -0
  219. package/dist/types/shared/types/data-config.types.d.ts +81 -0
  220. package/dist/types/shared/types/domain.types.d.ts +6 -0
  221. package/dist/types/shared/types/engine.types.d.ts +6 -0
  222. package/dist/types/shared/types/manifest.types.d.ts +23 -0
  223. package/dist/types/shared/types/scope-manifest.types.d.ts +82 -0
  224. package/dist/types/shared/types/style-config.types.d.ts +8 -0
  225. package/dist/types/shared/types/ui-config.types.d.ts +20 -0
  226. package/global.d.ts +12 -0
  227. package/next.config.js +76 -1
  228. package/package.json +32 -11
  229. package/proxy.ts +62 -0
  230. package/core/client/engine/theme-variables.ts +0 -37
  231. package/dist/tsconfig.types.tsbuildinfo +0 -1
  232. package/dist/types/client/engine/theme-variables.d.ts +0 -3
  233. package/middleware.ts +0 -33
@@ -0,0 +1,56 @@
1
+ // core/client/adaptive/hysteresis.ts — 施密特迟滞(F-13)
2
+ //
3
+ // 纯函数,无外部状态、无副作用:同输入必同输出,可穷举测试。
4
+ // 只负责人手拖拽造成的边界往复;滚动条引起的结构性振荡**不靠迟滞吸收**,
5
+ // 由 soma-ui 侧 `scrollbar-gutter: stable` 结构性消灭(F-27)——
6
+ // 用迟滞去糊结构性问题,只会把振荡从"看得见"变成"看不见但还在"。
7
+
8
+ /** 迟滞带默认宽度:档位边界的 ±8%。可覆盖,但不可为负或 ≥ 1 */
9
+ export const SOMA_DEFAULT_HYSTERESIS = 0.08;
10
+
11
+ /**
12
+ * 带迟滞的档位解算。
13
+ *
14
+ * 每个边界 b 拆成两个阈值:升档须越过 `b·(1+h)`,降档须跌破 `b·(1−h)`。
15
+ * 于是同一取值点上最多存在两个合法档(当前与相邻),走哪个由 `prev` 决定——
16
+ * 这正是"往复拖拽不抖"的来源。
17
+ *
18
+ * @param value 被判定的量(通常是容器宽度);非有限数时返回 prev(ERR-04)
19
+ * @param bounds 升序边界数组;空数组时返回 prev(无档可分)
20
+ * @param prev 上一档位(0 ~ bounds.length);越界时按无迟滞裸档返回
21
+ * @param h 迟滞带宽度,默认 0.08
22
+ * @returns 档位序号,0 ~ bounds.length
23
+ */
24
+ export function resolveTierWithHysteresis(
25
+ value: number,
26
+ bounds: readonly number[],
27
+ prev: number,
28
+ h: number = SOMA_DEFAULT_HYSTERESIS,
29
+ ): number {
30
+ if (!(h >= 0 && h < 1)) {
31
+ throw new RangeError(`[soma-core][adaptive] 迟滞带 h 必须落在 [0, 1),当前值: ${h}`);
32
+ }
33
+ if (!bounds || bounds.length === 0) return prev;
34
+ if (!Number.isFinite(value)) return prev;
35
+
36
+ const max = bounds.length;
37
+
38
+ // prev 越界(首帧无历史、档位定义变更后的旧值):退回无迟滞裸档,
39
+ // 而不是钳到边界——钳制会让首帧落在错档上,还得多一帧才纠正。
40
+ if (!Number.isInteger(prev) || prev < 0 || prev > max) {
41
+ return rawTier(value, bounds);
42
+ }
43
+
44
+ let tier = prev;
45
+ // 升档与降档互斥:prev 合法时两个循环至多有一个会跑
46
+ while (tier < max && value >= bounds[tier] * (1 + h)) tier++;
47
+ while (tier > 0 && value < bounds[tier - 1] * (1 - h)) tier--;
48
+ return tier;
49
+ }
50
+
51
+ /** 无迟滞裸档:value 越过了几个边界就是第几档 */
52
+ function rawTier(value: number, bounds: readonly number[]): number {
53
+ let tier = 0;
54
+ while (tier < bounds.length && value >= bounds[tier]) tier++;
55
+ return tier;
56
+ }
@@ -0,0 +1,23 @@
1
+ // core/client/adaptive/ — 自适应调度原语三件套(F-11 – F-14 / 契约 C7)
2
+ //
3
+ // core 唯一的运行时新增。**不含任何决策逻辑**:决策函数由调用方(soma-ui)传入,
4
+ // core 只保证调度的性能形态。为什么是三个 API 而不是一个 attachAdaptive:
5
+ // 观察者池解决"多作用域共享一个 RO"的资源问题;
6
+ // 三相调度解决"读写不交错"的性能问题;
7
+ // 迟滞函数解决"档位振荡"的正确性问题。
8
+ // 三者正交、可各自穷举测试;合成一个 API 会把三个可测性质糅成一个不可测的黑盒。
9
+ //
10
+ // 成本契约:独立模块、零依赖、tree-shakeable——不 attach 即不加载不执行;
11
+ // 无 DOM 环境下三件套全部为空实现(迟滞仍是纯计算),调用方无需做环境判断。
12
+
13
+ export { createAdaptiveObserverPool } from './observer-pool';
14
+ export type {
15
+ SomaAdaptiveObserverPool,
16
+ SomaAdaptiveSize,
17
+ SomaAdaptiveSizeCallback,
18
+ } from './observer-pool';
19
+
20
+ export { scheduleAdaptiveFlush } from './flush-scheduler';
21
+ export type { SomaAdaptiveTask } from './flush-scheduler';
22
+
23
+ export { resolveTierWithHysteresis, SOMA_DEFAULT_HYSTERESIS } from './hysteresis';
@@ -0,0 +1,90 @@
1
+ // core/client/adaptive/observer-pool.ts — 自适应观察者池(F-11)
2
+ //
3
+ // 全引擎单例:一个 ResizeObserver 观察所有自适应作用域。
4
+ // 为什么不是每个作用域一个 RO:RO 实例本身有固定开销,几十个作用域就是几十个
5
+ // 独立的观察循环与几十次回调调度;单例把它们合并成一次回调、一个批次。
6
+ //
7
+ // 零主动测量:尺寸只来自回调自带的 contentRect。
8
+ // **不提供任何补测 API**——提供 getBoundingClientRect 之类的入口,
9
+ // 等于在性能契约上开了一个强制回流的口子,而口子一旦开就必然被用。
10
+
11
+ export interface SomaAdaptiveSize {
12
+ width: number;
13
+ height: number;
14
+ }
15
+
16
+ export type SomaAdaptiveSizeCallback = (size: SomaAdaptiveSize) => void;
17
+
18
+ export interface SomaAdaptiveObserverPool {
19
+ /** 订阅元素尺寸;返回退订函数(幂等,重复调用不抛错) */
20
+ observe(target: Element, onSize: SomaAdaptiveSizeCallback): () => void;
21
+ }
22
+
23
+ const NOOP_UNSUBSCRIBE = (): void => {};
24
+
25
+ /** SSR / 无 DOM 环境的空实现:订阅成功但永不回调,调用方无需环境判断(F-14) */
26
+ const EMPTY_POOL: SomaAdaptiveObserverPool = {
27
+ observe: () => NOOP_UNSUBSCRIBE,
28
+ };
29
+
30
+ let singleton: SomaAdaptiveObserverPool | null = null;
31
+
32
+ /**
33
+ * 取得观察者池。
34
+ * 多次调用复用同一实例、同一 ResizeObserver——"create" 是使用面的措辞,
35
+ * 语义上是取单例;调用方不需要自己去做全局缓存。
36
+ */
37
+ export function createAdaptiveObserverPool(): SomaAdaptiveObserverPool {
38
+ // 无 DOM 环境不缓存单例:环境判断本身极廉价,而缓存会让"先 SSR 后补水"
39
+ // 的进程永远停在空实现上。
40
+ if (typeof ResizeObserver === 'undefined') return EMPTY_POOL;
41
+ if (!singleton) singleton = createDomPool();
42
+ return singleton;
43
+ }
44
+
45
+ function createDomPool(): SomaAdaptiveObserverPool {
46
+ /** 元素 → 该元素上的全部回调。WeakMap:元素被卸载即随之回收,无需调用方清场 */
47
+ const subscribers = new WeakMap<Element, Set<SomaAdaptiveSizeCallback>>();
48
+ let observer: ResizeObserver | null = null;
49
+
50
+ const ensureObserver = (): ResizeObserver => {
51
+ if (observer) return observer;
52
+ observer = new ResizeObserver((entries) => {
53
+ for (const entry of entries) {
54
+ const callbacks = subscribers.get(entry.target);
55
+ if (!callbacks || callbacks.size === 0) continue;
56
+ const rect = entry.contentRect;
57
+ const size: SomaAdaptiveSize = { width: rect.width, height: rect.height };
58
+ // 拷贝一份再遍历:回调里退订自己是常见写法,直接遍历原 Set 会漏掉后续项
59
+ for (const callback of [...callbacks]) callback(size);
60
+ }
61
+ });
62
+ return observer;
63
+ };
64
+
65
+ return {
66
+ observe(target: Element, onSize: SomaAdaptiveSizeCallback): () => void {
67
+ const ro = ensureObserver();
68
+ let callbacks = subscribers.get(target);
69
+ if (!callbacks) {
70
+ callbacks = new Set();
71
+ subscribers.set(target, callbacks);
72
+ ro.observe(target);
73
+ }
74
+ callbacks.add(onSize);
75
+
76
+ let released = false;
77
+ return () => {
78
+ if (released) return; // 退订幂等
79
+ released = true;
80
+ const current = subscribers.get(target);
81
+ if (!current) return;
82
+ current.delete(onSize);
83
+ if (current.size === 0) {
84
+ subscribers.delete(target);
85
+ ro.unobserve(target);
86
+ }
87
+ };
88
+ },
89
+ };
90
+ }
@@ -39,6 +39,56 @@ export abstract class SomaPageRootBase implements SomaPageRoot {
39
39
  /** 由引擎注入的运行时基础设施(router / http / notify 等) */
40
40
  _services?: SomaRuntimeServices;
41
41
 
42
+ /**
43
+ * 数据对象层(*_data.yaml,可选件)解析产物挂载点。
44
+ * bootstrap 在数据对象解析完成后注入 { 对象名: 数据 },UI 走既有
45
+ * `page.data.<对象>.<字段>` 绑定通道;页面无数据声明时恒为空对象。
46
+ * 以非枚举属性挂载:不进入页面状态序列化/快照,存量行为零变化。
47
+ */
48
+ data!: Record<string, unknown>;
49
+
50
+ /** 由 bootstrap 注入的数据对象重取钩子(无 *_data.yaml 声明时保持未定义) */
51
+ _reloadData?: () => Promise<void>;
52
+
53
+ constructor() {
54
+ // 字段声明会在构造早期定义可枚举属性,此处重定义为非枚举(configurable 保持 true)
55
+ Object.defineProperty(this, 'data', {
56
+ value: {},
57
+ writable: true,
58
+ enumerable: false,
59
+ configurable: true,
60
+ });
61
+ }
62
+
63
+ /**
64
+ * 重新执行数据对象取数(Domain 可在业务动作后调用刷新 page.data)。
65
+ * 页面未声明数据对象时为空操作。
66
+ */
67
+ async reloadData(): Promise<void> {
68
+ await this._reloadData?.();
69
+ }
70
+
71
+ /**
72
+ * 把此刻改过的页面状态**立刻**推到界面上,不等这次事件处理结束。
73
+ *
74
+ * 什么时候需要它:一次事件 = 一次原子提交是引擎刻意的设计——中间态不闪烁,
75
+ * 出错时未提交的界面变更整体回滚。代价是**长任务的中途进展播不出去**:
76
+ * 实测 AI 生成一次 P50 约 40 秒,期间 Domain 改多少次状态,界面一次都不动,
77
+ * 连"生成中"三个字都不会出现,用户分不清"在想"还是"卡死"。
78
+ *
79
+ * ```ts
80
+ * this.statusText = '正在生成…';
81
+ * await this.publishUi(); // ← 这一帧现在就让用户看见
82
+ * const result = await longTask();
83
+ * ```
84
+ *
85
+ * 代价要写明白:**已经上屏的这部分不再享有失败回滚**。所以它是自愿的——
86
+ * 只有业务知道"这一帧值不值得让用户看见"。不调用则行为与过去完全一致。
87
+ */
88
+ protected async publishUi(): Promise<void> {
89
+ await this._services?.ui?.publish();
90
+ }
91
+
42
92
  /**
43
93
  * 封装页面级异步操作:自动管理 pageLoading / pageError
44
94
  */
@@ -0,0 +1,136 @@
1
+ // core/client/compiler/adaptive-compile.ts — 阶梯编译期展开(F-10 / 契约 C6)
2
+ //
3
+ // 本模块是"自适应上车、性能不降"的核心兑现处:把 `adaptive` 声明在编译期一次性
4
+ // 展开成确定性产物,运行期不再有任何展开判断。
5
+ //
6
+ // 展开规则(三条,互不重叠):
7
+ // 断点型级 → 目标锚点加预置作用域类(纯 CSS 生效,L1 自足,不进运行时)
8
+ // 测量型级 → 执行器配置对象(交 soma-ui 接线层消费,core 不认识执行器做什么)
9
+ // profile → 宿主根 data 属性(供 CSS 与 ui 决策共同消费)
10
+ //
11
+ // 硬边界:编译期不做任何宽度判断与像素计算;不改变 DOM 结构,只加类与 data 属性。
12
+
13
+ import type { IContainerAdapter } from '../container/IContainerAdapter';
14
+ import { SomaAdaptiveConfigError } from '../parser/adaptive-parser';
15
+ import type {
16
+ SomaAdaptiveConfig,
17
+ SomaAdaptiveExecutorConfig,
18
+ SomaAdaptiveScopeClass,
19
+ SomaAdaptiveVocabulary,
20
+ SomaCompiledAdaptive,
21
+ } from '../../shared/types/adaptive.types';
22
+
23
+ /** 宿主根上的画像属性名:CSS 与 ui 决策的共同入口,跨包契约,改名要两边一起改 */
24
+ export const SOMA_ADAPTIVE_PROFILE_ATTR = 'data-soma-adaptive-profile';
25
+
26
+ /** 与解析器同一句接线指路,两处报错口径必须一致 */
27
+ const VOCABULARY_WIRING_HINT =
28
+ '在宿主 bootstrap/soma-bootstrap.ts 中与组件注册同点注入:'
29
+ + 'adaptiveVocabulary: createSomaUiAdaptiveVocabulary()';
30
+
31
+ export interface SomaAdaptiveCompileInput {
32
+ config: SomaAdaptiveConfig;
33
+ /** 已注册词汇表;解析期已断言过声明值在表内,此处只做取值 */
34
+ vocabulary?: SomaAdaptiveVocabulary;
35
+ container: HTMLElement;
36
+ adapter: IContainerAdapter;
37
+ }
38
+
39
+ /**
40
+ * 把 `adaptive` 声明展开为确定性编译产物。
41
+ *
42
+ * 锚点存在性在此校验(解析期看不到 DOM,归属仍是 F-08):
43
+ * 槽与 pin 的目标锚点不可解析时快速失败,不静默丢级——
44
+ * 丢一级的后果是页面在某个宽度下悄悄不降级,比报错难查得多。
45
+ */
46
+ export function compileAdaptive(input: SomaAdaptiveCompileInput): SomaCompiledAdaptive {
47
+ const { config, vocabulary, container, adapter } = input;
48
+
49
+ const scopeClasses: SomaAdaptiveScopeClass[] = [];
50
+ const executors: SomaAdaptiveExecutorConfig[] = [];
51
+
52
+ for (const [index, level] of (config.ladder ?? []).entries()) {
53
+ assertAnchorExists(level.slot, container, adapter, `adaptive.ladder[${index}].${level.slot}`);
54
+
55
+ const definition = vocabulary?.[level.slot]?.[level.value];
56
+ if (!definition) {
57
+ // 页面装载路径上解析期已挡住这条路;预编译路径的词汇归属校验落在这里
58
+ // (构建期取不到宿主 bootstrap 的词汇表,见 ui-config-parser 的
59
+ // adaptiveVocabularyRequired)。两条路径的失败等价,只是时机不同。
60
+ const known = Object.keys(vocabulary?.[level.slot] ?? {});
61
+ throw new SomaAdaptiveConfigError(
62
+ `级 "${level.slot}: ${level.value}" 在词汇表中无定义,无法展开。`
63
+ + (known.length
64
+ ? `槽 "${level.slot}" 的合法取值: ${known.join(' | ')}`
65
+ : `请确认宿主已注册该槽:${VOCABULARY_WIRING_HINT}`),
66
+ `adaptive.ladder[${index}]`,
67
+ );
68
+ }
69
+
70
+ if (definition.kind === 'breakpoint') {
71
+ scopeClasses.push({
72
+ slot: level.slot,
73
+ className: definition.target,
74
+ ...(definition.trigger ? { trigger: definition.trigger } : {}),
75
+ });
76
+ } else {
77
+ executors.push({ slot: level.slot, value: level.value, executor: definition.target });
78
+ }
79
+ }
80
+
81
+ for (const [index, slot] of (config.pin ?? []).entries()) {
82
+ assertAnchorExists(slot, container, adapter, `adaptive.pin[${index}]`);
83
+ }
84
+
85
+ return {
86
+ profile: config.profile,
87
+ scopeClasses,
88
+ executors,
89
+ pinned: [...(config.pin ?? [])],
90
+ };
91
+ }
92
+
93
+ /**
94
+ * 落地编译产物:宿主根写画像属性 + 断点型级挂作用域类。
95
+ *
96
+ * 测量型执行器配置**不在此消费**——它是交给 soma-ui 接线层的数据,
97
+ * core 落地它就等于把组件行为搬进了引擎。
98
+ */
99
+ export function applyCompiledAdaptive(
100
+ compiled: SomaCompiledAdaptive,
101
+ container: HTMLElement,
102
+ adapter: IContainerAdapter,
103
+ ): void {
104
+ const hostRoot = resolveHostRoot(container);
105
+ hostRoot.setAttribute(SOMA_ADAPTIVE_PROFILE_ATTR, compiled.profile);
106
+
107
+ for (const scope of compiled.scopeClasses) {
108
+ const element = adapter.findAnchor(container, scope.slot);
109
+ if (element) {
110
+ adapter.toggleClasses(element, [scope.className], true);
111
+ }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * 宿主根 = 容器内带 `data-soma-host` 的元素;没有就退到容器本身。
117
+ * 不用 documentElement:core 是被集成的框架,往宿主全局写属性是越界。
118
+ */
119
+ function resolveHostRoot(container: HTMLElement): HTMLElement {
120
+ if (container.hasAttribute?.('data-soma-host')) return container;
121
+ return (container.querySelector?.('[data-soma-host]') as HTMLElement | null) ?? container;
122
+ }
123
+
124
+ function assertAnchorExists(
125
+ somaId: string,
126
+ container: HTMLElement,
127
+ adapter: IContainerAdapter,
128
+ path: string,
129
+ ): void {
130
+ if (adapter.findAnchor(container, somaId)) return;
131
+ throw new SomaAdaptiveConfigError(
132
+ `找不到锚点 "${somaId}":adaptive 的槽名与 pin 目标必须是页面中存在的 data-soma-id,`
133
+ + `请核对 HTML 骨架上的 data-soma-id 拼写`,
134
+ path,
135
+ );
136
+ }
@@ -13,6 +13,15 @@ import type {
13
13
  UiConfig,
14
14
  } from '../../shared/types/ui-config.types';
15
15
  import type { ParsedEvent } from '../../shared/types/event.types';
16
+ import type { SomaPipeCall } from '../../shared/types/scope-manifest.types';
17
+ import {
18
+ defaultPipeRegistry,
19
+ hasPipes,
20
+ parsePipedValue,
21
+ type SomaPipeRegistry,
22
+ } from '../pipes/pipe-registry';
23
+ import type { SomaAdaptiveVocabulary } from '../../shared/types/adaptive.types';
24
+ import { compileAdaptive } from './adaptive-compile';
16
25
 
17
26
  export interface SomaManifestCompilerInput {
18
27
  container: HTMLElement;
@@ -20,12 +29,67 @@ export interface SomaManifestCompilerInput {
20
29
  uiConfig: UiConfig;
21
30
  eventConfig: ParsedEvent[];
22
31
  resolver: SomaScopeResolver;
32
+ /** 格式化管道注册表(缺省为内置管道集) */
33
+ pipes?: SomaPipeRegistry;
34
+ /** 阶梯词汇表(F-09);仅当 uiConfig.adaptive 存在时才被读取 */
35
+ adaptiveVocabulary?: SomaAdaptiveVocabulary;
23
36
  }
24
37
 
25
- export class SomaManifestCompiler {
26
- /** 事件编译缓存:eventConfig 不依赖 DOM,可安全缓存 */
27
- private eventCache = new Map<string, { events: SomaCompiledEvent[]; eventIndex: Map<string, SomaCompiledEvent> }>();
38
+ /**
39
+ * 事件编译:ParsedEvent[] → 编译事件表 + 派发索引。
40
+ *
41
+ * **这里刻意没有缓存**(曾经有,按 `JSON.stringify(eventConfig)` 缓存并返回同一批对象)。
42
+ * 拆掉的两条理由,一条是正确性,一条是实测数字:
43
+ *
44
+ * 1) 正确性:产物**不是只读的**。组件管理器的 markEmitRoutes / markChildEmitRoutes
45
+ * 直接在这些对象上写 `config.emitRoute = true`,而 SomaBootstrap 全程复用同一个
46
+ * SomaRuntimeBuilder → 同一个 compiler。于是 hotSwap 到"eventConfig JSON 相同、
47
+ * 但组件布局不同"的页面时,上一帧的 emitRoute 会被原样端上来;
48
+ * SomaEventEngine.init 见 emitRoute 就连监听类型都不注册 —— 那些事件从此
49
+ * **永远拿不到 DOM 监听器**,页面看着好好的,点了没反应,不报任何错。
50
+ * (实测复现:tests/integration/components/event-cache-cross-frame.test.ts)
51
+ *
52
+ * 2) 数字:缓存省下的还没缓存键本身贵(本机 jsdom 实测,eventConfig 60 条)——
53
+ * 被缓存的那段工作 0.0197 ms/次,而每次 compile 都要先付的
54
+ * `JSON.stringify(eventConfig)` 是 0.0180 ms/次:命中一次净赚 0.0018 ms
55
+ * (整条 compile 约 5.4 ms 的 0.03%),未命中则纯亏 0.0180 ms。
56
+ * "改成返回深拷贝"更不划算:structuredClone 0.0607 ms、JSON 往返 0.0423 ms,
57
+ * 都是从头重建(0.0197 ms)的 2–3 倍。
58
+ * 结论:重建比缓存便宜,顺手把共享可变状态一起消灭。
59
+ */
60
+ function compileEvents(eventConfig: ParsedEvent[]): {
61
+ events: SomaCompiledEvent[];
62
+ eventIndex: Map<string, SomaCompiledEvent>;
63
+ } {
64
+ const events: SomaCompiledEvent[] = eventConfig.map((event) => ({
65
+ ...event,
66
+ eventKey: `${event.domEvent}:${event.somaId}`,
67
+ priority: 'immediate' as const,
68
+ }));
69
+
70
+ // 同一锚点 + 同一 DOM 事件可以有多条按键修饰符绑定(↑↓←→/Enter/Esc 各一条),
71
+ // 这是 listbox/tablist/tree 的 ARIA 键盘模式的硬需求。
72
+ // 索引主键仍是 `domEvent:somaId`(派发侧按它查),带修饰符的另存一份候选列表,
73
+ // 由派发侧按 event.key 挑。先前只存最后一条,前面的被静默覆盖(实弹踩过:
74
+ // Select 绑了四个按键,只有最后注册的 Esc 生效)。
75
+ const candidates = new Map<string, SomaCompiledEvent[]>();
76
+ for (const event of events) {
77
+ const existing = candidates.get(event.eventKey);
78
+ if (existing) existing.push(event);
79
+ else candidates.set(event.eventKey, [event]);
80
+ }
81
+
82
+ const eventIndex = new Map<string, SomaCompiledEvent>();
83
+ for (const [key, list] of candidates) {
84
+ // 主条目取第一条不带修饰符的;全都带修饰符时取第一条(派发侧仍会按 key 复核)
85
+ const primary = list.find((event) => !event.keyModifier) ?? list[0];
86
+ eventIndex.set(key, list.length > 1 ? { ...primary, keyVariants: list } : primary);
87
+ }
28
88
 
89
+ return { events, eventIndex };
90
+ }
91
+
92
+ export class SomaManifestCompiler {
29
93
  compile(input: SomaManifestCompilerInput): SomaRuntimeManifest {
30
94
  const bindings: SomaCompiledBinding[] = [];
31
95
  this.walkShow(input.uiConfig.show, input, bindings);
@@ -42,30 +106,28 @@ export class SomaManifestCompiler {
42
106
  }
43
107
  }
44
108
 
45
- // 事件编译缓存:eventConfig 纯数据转换,不依赖 DOM
46
- const eventKey = JSON.stringify(input.eventConfig);
47
- let eventResult = this.eventCache.get(eventKey);
48
- if (!eventResult) {
49
- const events: SomaCompiledEvent[] = input.eventConfig.map((event) => ({
50
- ...event,
51
- eventKey: `${event.domEvent}:${event.somaId}`,
52
- priority: 'immediate' as const,
53
- }));
54
- const eventIndex = new Map<string, SomaCompiledEvent>();
55
- for (const event of events) {
56
- eventIndex.set(event.eventKey, event);
57
- }
58
- eventResult = { events, eventIndex };
59
- this.eventCache.set(eventKey, eventResult);
60
- }
109
+ // 每次编译都产新对象:产物是可变的(emitRoute 由组件管理器现场写),不可跨帧共享
110
+ const eventResult = compileEvents(input.eventConfig);
61
111
 
62
- return {
112
+ const manifest: SomaRuntimeManifest = {
63
113
  bindings,
64
114
  bindingIndex,
65
115
  events: eventResult.events,
66
116
  eventIndex: eventResult.eventIndex,
67
117
  initProps: input.uiConfig.initProps,
68
118
  };
119
+
120
+ // 未声明 adaptive 时整条路径旁路:既不展开也不写字段,产物与迁移前字节级一致
121
+ if (input.uiConfig.adaptive) {
122
+ manifest.adaptive = compileAdaptive({
123
+ config: input.uiConfig.adaptive,
124
+ vocabulary: input.adaptiveVocabulary,
125
+ container: input.container,
126
+ adapter: input.adapter,
127
+ });
128
+ }
129
+
130
+ return manifest;
69
131
  }
70
132
 
71
133
  private walkShow(
@@ -78,14 +140,28 @@ export class SomaManifestCompiler {
78
140
  const element = input.adapter.findAnchor(input.container, rawKey);
79
141
  const role = element ? input.adapter.readRole(element) : null;
80
142
  const dataPath = input.resolver.resolvePath(showValue.bind.obj);
143
+ this.validateScopedPipes(showValue.show, rawKey, input);
81
144
  bindings.push({
82
145
  id: `${rawKey}:${bindings.length}`,
83
146
  somaId: rawKey,
84
- type: role === 'item' ? 'list' : 'obj',
147
+ type: role === 'item' || role?.startsWith('item:') ? 'list' : 'obj',
85
148
  dataPath,
86
149
  watchPaths: dataPath ? [dataPath] : [],
87
150
  childShowConfig: showValue.show,
151
+ roleBy: showValue.bind.role_by,
88
152
  });
153
+ // 嵌套绑定同样支持整块显隐:再补一条 when 绑定(同一锚点,互不干扰)
154
+ if (typeof showValue.when === 'string') {
155
+ const { dataPath: whenPath, negate } = this.parseConditionalPath(showValue.when, input.resolver);
156
+ bindings.push({
157
+ id: `${rawKey}:when:${bindings.length}`,
158
+ somaId: rawKey,
159
+ type: 'when',
160
+ dataPath: whenPath,
161
+ watchPaths: [whenPath],
162
+ negate,
163
+ });
164
+ }
89
165
  continue;
90
166
  }
91
167
 
@@ -97,17 +173,21 @@ export class SomaManifestCompiler {
97
173
  continue;
98
174
  }
99
175
 
100
- const dataPath = input.resolver.resolvePath(String(showValue));
176
+ const piped = this.parsePipes(String(showValue), rawKey, input);
177
+ const dataPath = input.resolver.resolvePath(piped.basePath);
101
178
  const bindingType = this.resolveBindingType(element, attrName);
102
- const isStatic = this.isStaticPath(dataPath);
179
+ const argWatchPaths = piped.argPaths.map((path) => input.resolver.resolvePath(path));
180
+ const isStatic = this.isStaticPath(dataPath)
181
+ && argWatchPaths.every((path) => this.isStaticPath(path));
103
182
  bindings.push({
104
183
  id: `${rawKey}:${bindings.length}`,
105
184
  somaId,
106
185
  type: bindingType,
107
186
  dataPath,
108
- watchPaths: isStatic ? [] : (dataPath ? [dataPath] : []),
187
+ watchPaths: isStatic ? [] : [dataPath, ...argWatchPaths].filter(Boolean),
109
188
  attrName: bindingType === 'attr' ? attrName ?? undefined : undefined,
110
189
  static: isStatic || undefined,
190
+ pipes: piped.pipes.length ? piped.pipes : undefined,
111
191
  });
112
192
  }
113
193
  }
@@ -119,15 +199,19 @@ export class SomaManifestCompiler {
119
199
  bindings: SomaCompiledBinding[],
120
200
  ): void {
121
201
  if (value.text) {
122
- const dataPath = input.resolver.resolvePath(value.text);
123
- const isStatic = this.isStaticPath(dataPath);
202
+ const piped = this.parsePipes(value.text, `${somaId}.text`, input);
203
+ const dataPath = input.resolver.resolvePath(piped.basePath);
204
+ const argWatchPaths = piped.argPaths.map((path) => input.resolver.resolvePath(path));
205
+ const isStatic = this.isStaticPath(dataPath)
206
+ && argWatchPaths.every((path) => this.isStaticPath(path));
124
207
  bindings.push({
125
208
  id: `${somaId}:text:${bindings.length}`,
126
209
  somaId,
127
210
  type: 'text',
128
211
  dataPath,
129
- watchPaths: isStatic ? [] : [dataPath],
212
+ watchPaths: isStatic ? [] : [dataPath, ...argWatchPaths],
130
213
  static: isStatic || undefined,
214
+ pipes: piped.pipes.length ? piped.pipes : undefined,
131
215
  });
132
216
  }
133
217
 
@@ -176,6 +260,50 @@ export class SomaManifestCompiler {
176
260
  }
177
261
  }
178
262
 
263
+ /**
264
+ * 解析并校验展示值上的管道链(编译期白名单,未注册名 fail fast)。
265
+ * 无管道时原样返回(零开销路径)。
266
+ */
267
+ private parsePipes(
268
+ rawValue: string,
269
+ where: string,
270
+ input: SomaManifestCompilerInput,
271
+ ): { basePath: string; pipes: SomaPipeCall[]; argPaths: string[] } {
272
+ if (!hasPipes(rawValue)) {
273
+ return { basePath: rawValue, pipes: [], argPaths: [] };
274
+ }
275
+ const registry = input.pipes ?? defaultPipeRegistry;
276
+ const parsed = parsePipedValue(rawValue, (seg) => input.resolver.hasVar(seg));
277
+ registry.assertKnown(parsed.pipes, where);
278
+ return parsed;
279
+ }
280
+
281
+ /** 列表/对象子作用域配置的管道预校验(行内解释执行前的编译期 fail fast) */
282
+ private validateScopedPipes(
283
+ show: ShowMapping,
284
+ where: string,
285
+ input: SomaManifestCompilerInput,
286
+ ): void {
287
+ for (const [rawKey, value] of Object.entries(show)) {
288
+ if (typeof value === 'string') {
289
+ this.parsePipes(value, `${where}.${rawKey}`, input);
290
+ continue;
291
+ }
292
+ if (this.isNestedShowMapping(value)) {
293
+ this.validateScopedPipes(value.show, `${where}.${rawKey}.show`, input);
294
+ continue;
295
+ }
296
+ if (this.isExtendedShowValue(value)) {
297
+ if (value.text) {
298
+ this.parsePipes(value.text, `${where}.${rawKey}.text`, input);
299
+ }
300
+ if (value.show) {
301
+ this.validateScopedPipes(value.show, `${where}.${rawKey}.show`, input);
302
+ }
303
+ }
304
+ }
305
+ }
306
+
179
307
  private parseSomaKey(rawKey: string): { somaId: string; attrName: string | null } {
180
308
  const [somaId, attrName] = rawKey.split('@');
181
309
  return {