soma-core 1.3.2 → 1.3.4

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 (281) hide show
  1. package/README.md +43 -0
  2. package/app/SomaPageClient.tsx +22 -68
  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/bin/soma-lsp.cjs +1 -4
  13. package/core/build/compiler/full-manifest-builder.ts +19 -23
  14. package/core/build/compiler/html-include-expander.ts +56 -0
  15. package/core/build/compiler/page-assets.ts +26 -0
  16. package/core/build/compiler/page-declaration-compiler.ts +85 -0
  17. package/core/build/compiler/rollup-plugin-soma.ts +4 -13
  18. package/core/build/compiler/route-builder.ts +0 -2
  19. package/core/build/compiler/rspack-plugin-soma.js +1 -10
  20. package/core/build/compiler/soma-manifest-webpack-plugin.js +54 -9
  21. package/core/build/compiler/soma-precompile.js +3581 -2387
  22. package/core/build/compiler/soma-precompile.ts +44 -2
  23. package/core/build/compiler/soma-rspack-yaml-loader.js +5 -8
  24. package/core/build/compiler/soma-webpack-loader.js +6 -15
  25. package/core/build/compiler/vite-plugin-soma.ts +9 -21
  26. package/core/build/component/pack-from-dir.ts +58 -0
  27. package/core/build/component/package-loader.ts +281 -0
  28. package/core/build/eject/apply-eject.ts +133 -0
  29. package/core/build/eject/plan-eject.ts +133 -0
  30. package/core/build/lsp/cross-file-diagnostics.cjs +82 -113
  31. package/core/build/lsp/extra-completion.cjs +14 -8
  32. package/core/build/lsp/lsp-navigation.cjs +50 -43
  33. package/core/build/lsp/soma-declaration.cjs +85 -0
  34. package/core/build/lsp/ui-yaml-completion.cjs +98 -104
  35. package/core/build/v2/block-compile.ts +200 -0
  36. package/core/build/v2/block-loader.ts +33 -0
  37. package/core/build/v2/html-index.ts +120 -0
  38. package/core/build/v2/migrate-v1.ts +370 -0
  39. package/core/build/v2/soma-file-loader.ts +216 -0
  40. package/core/client/adaptive/flush-scheduler.ts +96 -0
  41. package/core/client/adaptive/hysteresis.ts +56 -0
  42. package/core/client/adaptive/index.ts +23 -0
  43. package/core/client/adaptive/observer-pool.ts +90 -0
  44. package/core/client/base/SomaPageRootBase.ts +50 -0
  45. package/core/client/compiler/adaptive-compile.ts +136 -0
  46. package/core/client/compiler/manifest-compiler.ts +155 -27
  47. package/core/client/component/ai-catalog.ts +277 -0
  48. package/core/client/component/component-definition.types.ts +65 -0
  49. package/core/client/component/component-expander.ts +119 -0
  50. package/core/client/component/component-manager.ts +933 -0
  51. package/core/client/component/component-pack.ts +445 -0
  52. package/core/client/component/component-registry.ts +71 -0
  53. package/core/client/component/contract-compat.ts +132 -0
  54. package/core/client/component/example-v2.ts +132 -0
  55. package/core/client/component/pack-styles.ts +94 -0
  56. package/core/client/component/scoped-adapter.ts +85 -0
  57. package/core/client/component/verify-pack.ts +247 -0
  58. package/core/client/container/MiniProgramContainerAdapter.ts +15 -1
  59. package/core/client/container/ReactNativeContainerAdapter.ts +15 -1
  60. package/core/client/container/SomaContainerAdapter.ts +186 -180
  61. package/core/client/data/data-object-resolver.ts +417 -0
  62. package/core/client/diagnostics/SomaDiagnostics.ts +187 -186
  63. package/core/client/diagnostics/boot-timings.ts +152 -0
  64. package/core/client/engine/asset-resolver.ts +12 -2
  65. package/core/client/engine/dom-renderer.ts +249 -24
  66. package/core/client/engine/emit-event.ts +21 -0
  67. package/core/client/engine/event-engine.ts +34 -4
  68. package/core/client/engine/on-change-engine.ts +1 -1
  69. package/core/client/engine/property-watcher.ts +1 -1
  70. package/core/client/engine/reactive-proxy.ts +11 -10
  71. package/core/client/engine/render-engine.ts +39 -4
  72. package/core/client/engine/runtime-builder.ts +23 -0
  73. package/core/client/engine/soma-bootstrap.ts +380 -7
  74. package/core/client/engine/style-binder.ts +47 -1
  75. package/core/client/observability/error-reporter.ts +173 -0
  76. package/core/client/parser/adaptive-parser.ts +264 -0
  77. package/core/client/parser/data-config-parser.ts +396 -0
  78. package/core/client/parser/pipeline-parser.ts +15 -3
  79. package/core/client/parser/style-config-parser.ts +65 -2
  80. package/core/client/parser/ui-config-parser.ts +52 -3
  81. package/core/client/parser/v2/namespace.ts +182 -0
  82. package/core/client/parser/v2/page-parser.ts +359 -0
  83. package/core/client/parser/v2/use-parser.ts +412 -0
  84. package/core/client/parser/value-lang.ts +340 -0
  85. package/core/client/pipes/pipe-registry.ts +249 -0
  86. package/core/client/quality/SomaQualityRegistry.ts +3 -0
  87. package/core/client/registry/declaration-renderer.ts +161 -0
  88. package/core/client/registry/index.ts +28 -0
  89. package/core/client/registry/page-lifecycle.ts +171 -0
  90. package/core/client/registry/remote-page.ts +139 -0
  91. package/core/client/runtime/SomaRuntimeServices.ts +24 -0
  92. package/core/client/security/attribute-presence.ts +70 -0
  93. package/core/client/security/html-sanitizer.ts +113 -0
  94. package/core/client/security/url-guard.ts +0 -0
  95. package/core/client/theme/harmony.ts +307 -0
  96. package/core/client/theme/scene-tokens.ts +134 -0
  97. package/core/client/theme/theme-axes.ts +228 -0
  98. package/core/client/theme/theme-engine.ts +1196 -0
  99. package/core/client/theme/tone-solver.ts +118 -0
  100. package/core/client/typography/typography-base.ts +34 -0
  101. package/core/client/validation/contract-validator.ts +48 -5
  102. package/core/index.ts +262 -2
  103. package/core/server/api/IService.ts +18 -6
  104. package/core/server/api/load-host-service.ts +3 -3
  105. package/core/server/host/content-security-policy.ts +190 -0
  106. package/core/server/host/csp-nonce-metadata.ts +75 -0
  107. package/core/server/host/resolve-host-request-hook.ts +5 -0
  108. package/core/server/host/server-page-assets.ts +34 -7
  109. package/core/server/host/soma-page-compile.ts +33 -0
  110. package/core/server/index.ts +45 -1
  111. package/core/server/infra/cache/ServerFileCache.ts +1 -1
  112. package/core/server/mock/node/cli.mjs +2 -2
  113. package/core/server/registry/api-registry-store.ts +518 -0
  114. package/core/server/registry/conditional-object-store.ts +29 -0
  115. package/core/server/registry/declaration-precompiler.ts +99 -0
  116. package/core/server/registry/in-memory-conditional-object-store.ts +43 -0
  117. package/core/server/registry/index.ts +142 -0
  118. package/core/server/registry/page-registry-repository.ts +373 -0
  119. package/core/server/registry/page-registry-store.ts +932 -0
  120. package/core/server/registry/registry-error.ts +17 -0
  121. package/core/server/registry/registry-file-lock.ts +173 -0
  122. package/core/server/registry/registry-response.ts +71 -0
  123. package/core/server/registry/registry-subjects.ts +194 -0
  124. package/core/server/registry/registry-write-pipeline.ts +240 -0
  125. package/core/server/registry/request-body-limit.ts +99 -0
  126. package/core/server/registry/services/apis/Get.ts +25 -0
  127. package/core/server/registry/services/apis/List.ts +41 -0
  128. package/core/server/registry/services/apis/Register.ts +39 -0
  129. package/core/server/registry/services/apis/Unregister.ts +24 -0
  130. package/core/server/registry/services/index.ts +40 -0
  131. package/core/server/registry/services/pages/Get.ts +96 -0
  132. package/core/server/registry/services/pages/List.ts +53 -0
  133. package/core/server/registry/services/pages/Register.ts +49 -0
  134. package/core/server/registry/services/pages/Rollback.ts +36 -0
  135. package/core/server/registry/services/pages/Unregister.ts +23 -0
  136. package/core/server/registry/services/service-utils.ts +21 -0
  137. package/core/server/registry/validation/compile-gate.ts +54 -0
  138. package/core/server/registry/validation/component-existence.ts +55 -0
  139. package/core/server/registry/validation/credential-ban.ts +86 -0
  140. package/core/server/registry/validation/cross-check.ts +67 -0
  141. package/core/server/registry/validation/declaration-safety-scan.ts +102 -0
  142. package/core/shared/types/adaptive.types.ts +109 -0
  143. package/core/shared/types/component-contract.types.ts +120 -0
  144. package/core/shared/types/data-config.types.ts +105 -0
  145. package/core/shared/types/domain.types.ts +6 -0
  146. package/core/shared/types/engine.types.ts +41 -35
  147. package/core/shared/types/manifest.types.ts +55 -32
  148. package/core/shared/types/scope-manifest.types.ts +96 -0
  149. package/core/shared/types/style-config.types.ts +9 -0
  150. package/core/shared/types/ui-config.types.ts +118 -98
  151. package/dist/cli/soma.js +20 -5
  152. package/dist/core/index.cjs +7811 -1380
  153. package/dist/types/build/compiler/full-manifest-builder.d.ts +6 -2
  154. package/dist/types/build/compiler/html-include-expander.d.ts +19 -0
  155. package/dist/types/build/compiler/page-assets.d.ts +3 -0
  156. package/dist/types/build/compiler/page-declaration-compiler.d.ts +33 -0
  157. package/dist/types/build/compiler/rollup-plugin-soma.d.ts +0 -2
  158. package/dist/types/build/compiler/route-builder.d.ts +0 -1
  159. package/dist/types/build/compiler/soma-precompile.d.ts +17 -0
  160. package/dist/types/build/compiler/vite-plugin-soma.d.ts +2 -7
  161. package/dist/types/build/component/pack-from-dir.d.ts +17 -0
  162. package/dist/types/build/component/package-loader.d.ts +40 -0
  163. package/dist/types/build/eject/apply-eject.d.ts +22 -0
  164. package/dist/types/build/eject/plan-eject.d.ts +32 -0
  165. package/dist/types/build/v2/block-compile.d.ts +28 -0
  166. package/dist/types/build/v2/block-loader.d.ts +9 -0
  167. package/dist/types/build/v2/html-index.d.ts +37 -0
  168. package/dist/types/build/v2/migrate-v1.d.ts +32 -0
  169. package/dist/types/build/v2/soma-file-loader.d.ts +45 -0
  170. package/dist/types/client/adaptive/flush-scheduler.d.ts +13 -0
  171. package/dist/types/client/adaptive/hysteresis.d.ts +16 -0
  172. package/dist/types/client/adaptive/index.d.ts +5 -0
  173. package/dist/types/client/adaptive/observer-pool.d.ts +15 -0
  174. package/dist/types/client/base/SomaPageRootBase.d.ts +33 -0
  175. package/dist/types/client/compiler/adaptive-compile.d.ts +26 -0
  176. package/dist/types/client/compiler/manifest-compiler.d.ts +13 -2
  177. package/dist/types/client/component/ai-catalog.d.ts +73 -0
  178. package/dist/types/client/component/component-definition.types.d.ts +54 -0
  179. package/dist/types/client/component/component-expander.d.ts +25 -0
  180. package/dist/types/client/component/component-manager.d.ts +160 -0
  181. package/dist/types/client/component/component-pack.d.ts +110 -0
  182. package/dist/types/client/component/component-registry.d.ts +12 -0
  183. package/dist/types/client/component/contract-compat.d.ts +16 -0
  184. package/dist/types/client/component/example-v2.d.ts +9 -0
  185. package/dist/types/client/component/pack-styles.d.ts +22 -0
  186. package/dist/types/client/component/scoped-adapter.d.ts +18 -0
  187. package/dist/types/client/component/verify-pack.d.ts +14 -0
  188. package/dist/types/client/data/data-object-resolver.d.ts +71 -0
  189. package/dist/types/client/diagnostics/SomaDiagnostics.d.ts +2 -1
  190. package/dist/types/client/diagnostics/boot-timings.d.ts +30 -0
  191. package/dist/types/client/engine/asset-resolver.d.ts +7 -1
  192. package/dist/types/client/engine/dom-renderer.d.ts +51 -1
  193. package/dist/types/client/engine/emit-event.d.ts +6 -0
  194. package/dist/types/client/engine/event-engine.d.ts +6 -0
  195. package/dist/types/client/engine/render-engine.d.ts +25 -1
  196. package/dist/types/client/engine/runtime-builder.d.ts +7 -0
  197. package/dist/types/client/engine/soma-bootstrap.d.ts +118 -0
  198. package/dist/types/client/observability/error-reporter.d.ts +51 -0
  199. package/dist/types/client/parser/adaptive-parser.d.ts +28 -0
  200. package/dist/types/client/parser/data-config-parser.d.ts +34 -0
  201. package/dist/types/client/parser/pipeline-parser.d.ts +2 -0
  202. package/dist/types/client/parser/style-config-parser.d.ts +5 -3
  203. package/dist/types/client/parser/ui-config-parser.d.ts +22 -1
  204. package/dist/types/client/parser/v2/namespace.d.ts +52 -0
  205. package/dist/types/client/parser/v2/page-parser.d.ts +21 -0
  206. package/dist/types/client/parser/v2/use-parser.d.ts +72 -0
  207. package/dist/types/client/parser/value-lang.d.ts +63 -0
  208. package/dist/types/client/pipes/pipe-registry.d.ts +38 -0
  209. package/dist/types/client/registry/declaration-renderer.d.ts +50 -0
  210. package/dist/types/client/registry/index.d.ts +10 -0
  211. package/dist/types/client/registry/page-lifecycle.d.ts +61 -0
  212. package/dist/types/client/registry/remote-page.d.ts +52 -0
  213. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +16 -0
  214. package/dist/types/client/security/attribute-presence.d.ts +7 -0
  215. package/dist/types/client/security/html-sanitizer.d.ts +37 -0
  216. package/dist/types/client/security/url-guard.d.ts +11 -0
  217. package/dist/types/client/theme/harmony.d.ts +77 -0
  218. package/dist/types/client/theme/scene-tokens.d.ts +25 -0
  219. package/dist/types/client/theme/theme-axes.d.ts +81 -0
  220. package/dist/types/client/theme/theme-engine.d.ts +77 -0
  221. package/dist/types/client/theme/tone-solver.d.ts +47 -0
  222. package/dist/types/client/typography/typography-base.d.ts +15 -0
  223. package/dist/types/client/validation/contract-validator.d.ts +2 -0
  224. package/dist/types/index.d.ts +47 -2
  225. package/dist/types/server/api/IService.d.ts +18 -6
  226. package/dist/types/server/host/content-security-policy.d.ts +53 -0
  227. package/dist/types/server/host/csp-nonce-metadata.d.ts +32 -0
  228. package/dist/types/server/host/resolve-host-request-hook.d.ts +5 -0
  229. package/dist/types/server/host/server-page-assets.d.ts +2 -0
  230. package/dist/types/server/host/soma-page-compile.d.ts +7 -0
  231. package/dist/types/server/index.d.ts +6 -1
  232. package/dist/types/server/registry/api-registry-store.d.ts +141 -0
  233. package/dist/types/server/registry/conditional-object-store.d.ts +27 -0
  234. package/dist/types/server/registry/declaration-precompiler.d.ts +30 -0
  235. package/dist/types/server/registry/in-memory-conditional-object-store.d.ts +8 -0
  236. package/dist/types/server/registry/index.d.ts +29 -0
  237. package/dist/types/server/registry/page-registry-repository.d.ts +58 -0
  238. package/dist/types/server/registry/page-registry-store.d.ts +259 -0
  239. package/dist/types/server/registry/registry-error.d.ts +12 -0
  240. package/dist/types/server/registry/registry-file-lock.d.ts +20 -0
  241. package/dist/types/server/registry/registry-response.d.ts +18 -0
  242. package/dist/types/server/registry/registry-subjects.d.ts +59 -0
  243. package/dist/types/server/registry/registry-write-pipeline.d.ts +48 -0
  244. package/dist/types/server/registry/request-body-limit.d.ts +31 -0
  245. package/dist/types/server/registry/services/apis/Get.d.ts +10 -0
  246. package/dist/types/server/registry/services/apis/List.d.ts +10 -0
  247. package/dist/types/server/registry/services/apis/Register.d.ts +13 -0
  248. package/dist/types/server/registry/services/apis/Unregister.d.ts +12 -0
  249. package/dist/types/server/registry/services/index.d.ts +3 -0
  250. package/dist/types/server/registry/services/pages/Get.d.ts +10 -0
  251. package/dist/types/server/registry/services/pages/List.d.ts +13 -0
  252. package/dist/types/server/registry/services/pages/Register.d.ts +11 -0
  253. package/dist/types/server/registry/services/pages/Rollback.d.ts +9 -0
  254. package/dist/types/server/registry/services/pages/Unregister.d.ts +9 -0
  255. package/dist/types/server/registry/services/service-utils.d.ts +10 -0
  256. package/dist/types/server/registry/validation/compile-gate.d.ts +12 -0
  257. package/dist/types/server/registry/validation/component-existence.d.ts +14 -0
  258. package/dist/types/server/registry/validation/credential-ban.d.ts +15 -0
  259. package/dist/types/server/registry/validation/cross-check.d.ts +16 -0
  260. package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +15 -0
  261. package/dist/types/shared/types/adaptive.types.d.ts +88 -0
  262. package/dist/types/shared/types/component-contract.types.d.ts +78 -0
  263. package/dist/types/shared/types/data-config.types.d.ts +81 -0
  264. package/dist/types/shared/types/domain.types.d.ts +6 -0
  265. package/dist/types/shared/types/engine.types.d.ts +6 -0
  266. package/dist/types/shared/types/manifest.types.d.ts +23 -0
  267. package/dist/types/shared/types/scope-manifest.types.d.ts +82 -0
  268. package/dist/types/shared/types/style-config.types.d.ts +8 -0
  269. package/dist/types/shared/types/ui-config.types.d.ts +20 -0
  270. package/editor/vscode/package.json +1 -24
  271. package/global.d.ts +5 -11
  272. package/next.config.js +85 -28
  273. package/package.json +33 -11
  274. package/proxy.ts +62 -0
  275. package/tailwind.config.ts +0 -1
  276. package/core/build/lsp/event-yaml-completion.cjs +0 -106
  277. package/core/client/engine/theme-variables.ts +0 -37
  278. package/dist/tsconfig.types.tsbuildinfo +0 -1
  279. package/dist/types/client/engine/theme-variables.d.ts +0 -3
  280. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +0 -30
  281. package/middleware.ts +0 -33
@@ -0,0 +1,340 @@
1
+ // 值语言(DSL v2 · REQ-005 F4):全体系唯一的一条值规则。
2
+ //
3
+ // 值 := 段 ( "|" 管道调用 )*
4
+ // 段 := 路径 | 数字 | 算术表达式(路径 · 数字 · + - * / · 括号 · 一元负号)
5
+ //
6
+ // 为什么算术长成数学的样子而不是 `mul()` 管道:`o.price * o.qty` 谁都看得懂
7
+ // (Excel 用户零学习),而且标量管道 add/sub/mul/div 四个概念因此直接消失——
8
+ // 功能更强的同时概念更少。代价是引入一个**永久封闭**的微文法。
9
+ //
10
+ // 封闭在哪:词元只有六种(路径 / 数字 / + - * / / 括号)。
11
+ // **永不放行**比较、布尔、三元、字符串拼接——拼接有 tpl,判断归 Domain,
12
+ // 分支归 match 与组件多态。这不是"暂时不做",是地基:
13
+ // 词汇封闭同时是 AI 可稳定生成与可完全预编译两条命脉的共同前提
14
+ // (见 REQ-005 需求说明第零条论证)。解析器遇到 `> < ? :` 直接报错并指路。
15
+ //
16
+ // 产物是**可 JSON 序列化的指令节点**,不是闭包:清单要进预编译产物与注册中心
17
+ // (既有约束),闭包在装配期才结。运行时因此零解析——第零条公理的兑现点。
18
+
19
+ import type { SomaPipeCall } from '../../shared/types/scope-manifest.types';
20
+
21
+ export class SomaValueLangError extends Error {
22
+ constructor(message: string, readonly raw: string) {
23
+ super(`[soma-core][引擎] ${message}(值: "${raw}")`);
24
+ this.name = 'SomaValueLangError';
25
+ }
26
+ }
27
+
28
+ /** 值段的指令节点:JSON 可序列化,进清单 */
29
+ export type ValueNode =
30
+ | { kind: 'path'; path: string }
31
+ | { kind: 'lit'; value: string | number | boolean }
32
+ | { kind: 'neg'; operand: ValueNode }
33
+ | { kind: 'arith'; op: '+' | '-' | '*' | '/'; left: ValueNode; right: ValueNode };
34
+
35
+ export interface PipedValue {
36
+ seg: ValueNode;
37
+ pipes: SomaPipeCall[];
38
+ /** 值内引用的全部绑定路径(段内 + 管道实参),供 watchPaths 注册 */
39
+ paths: string[];
40
+ }
41
+
42
+ /**
43
+ * 值位置。算术与计算管道是**展示位专有**——算出来的值不驱动行为,
44
+ * 业务规则(定价、优惠、判断)留在 Domain 才可测试。
45
+ */
46
+ export type ValuePosition = 'display' | 'condition' | 'key';
47
+
48
+ /** 判定一个变量首段是否在当前作用域(与既有 hasVar 同款契约) */
49
+ export type HasVarFn = (segment: string) => boolean;
50
+
51
+ /** 段内是否出现算术运算符(路径词法不含运算符,故零歧义) */
52
+ const ARITH_HINT = /[+\-*/()]/;
53
+ /** 明确拒绝的词元:比较 / 布尔 / 三元 / 字符串拼接意图 */
54
+ const FORBIDDEN = /(>=|<=|==|!=|&&|\|\||[<>?])/;
55
+ /** 合法路径词法:首段已在作用域内时,其余部分必须严格符合此形状 */
56
+ const PATH_SHAPE = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)*$/;
57
+
58
+ // ── 词法 ────────────────────────────────────────────────────────────────────
59
+
60
+ type Token =
61
+ | { t: 'num'; v: number }
62
+ | { t: 'id'; v: string }
63
+ | { t: 'op'; v: '+' | '-' | '*' | '/' }
64
+ | { t: '(' }
65
+ | { t: ')' };
66
+
67
+ function tokenize(raw: string, source: string): Token[] {
68
+ const tokens: Token[] = [];
69
+ let i = 0;
70
+ while (i < raw.length) {
71
+ const ch = raw[i];
72
+ if (ch === ' ' || ch === '\t') { i += 1; continue; }
73
+ if (ch === '(' || ch === ')') { tokens.push({ t: ch } as Token); i += 1; continue; }
74
+ if (ch === '+' || ch === '-' || ch === '*' || ch === '/') {
75
+ tokens.push({ t: 'op', v: ch }); i += 1; continue;
76
+ }
77
+ if (/[0-9]/.test(ch)) {
78
+ let j = i;
79
+ while (j < raw.length && /[0-9.]/.test(raw[j])) j += 1;
80
+ const text = raw.slice(i, j);
81
+ const value = Number(text);
82
+ if (!Number.isFinite(value)) {
83
+ throw new SomaValueLangError(`数字字面量非法: "${text}"`, source);
84
+ }
85
+ tokens.push({ t: 'num', v: value }); i = j; continue;
86
+ }
87
+ if (/[A-Za-z_]/.test(ch)) {
88
+ let j = i;
89
+ while (j < raw.length && /[A-Za-z0-9_.]/.test(raw[j])) j += 1;
90
+ tokens.push({ t: 'id', v: raw.slice(i, j) }); i = j; continue;
91
+ }
92
+ throw new SomaValueLangError(
93
+ `无法识别的字符 "${ch}"——算术只支持路径、数字、+ - * / 与括号`,
94
+ source,
95
+ );
96
+ }
97
+ return tokens;
98
+ }
99
+
100
+ // ── 递归下降(* / 高于 + -,括号最大,一元负号) ──────────────────────────
101
+
102
+ class Parser {
103
+ private pos = 0;
104
+
105
+ constructor(
106
+ private readonly tokens: Token[],
107
+ private readonly source: string,
108
+ private readonly hasVar: HasVarFn,
109
+ private readonly paths: string[],
110
+ ) {}
111
+
112
+ parse(): ValueNode {
113
+ const node = this.expression();
114
+ if (this.pos < this.tokens.length) {
115
+ throw new SomaValueLangError('算术表达式有多余词元(括号是否配对?)', this.source);
116
+ }
117
+ return node;
118
+ }
119
+
120
+ /** 表达式 := 项 { ("+"|"-") 项 } */
121
+ private expression(): ValueNode {
122
+ let left = this.term();
123
+ for (;;) {
124
+ const token = this.tokens[this.pos];
125
+ if (token?.t === 'op' && (token.v === '+' || token.v === '-')) {
126
+ this.pos += 1;
127
+ left = { kind: 'arith', op: token.v, left, right: this.term() };
128
+ continue;
129
+ }
130
+ return left;
131
+ }
132
+ }
133
+
134
+ /** 项 := 因子 { ("*"|"/") 因子 } */
135
+ private term(): ValueNode {
136
+ let left = this.factor();
137
+ for (;;) {
138
+ const token = this.tokens[this.pos];
139
+ if (token?.t === 'op' && (token.v === '*' || token.v === '/')) {
140
+ this.pos += 1;
141
+ left = { kind: 'arith', op: token.v, left, right: this.factor() };
142
+ continue;
143
+ }
144
+ return left;
145
+ }
146
+ }
147
+
148
+ /** 因子 := 路径 | 数字 | "(" 表达式 ")" | "-" 因子 */
149
+ private factor(): ValueNode {
150
+ const token = this.tokens[this.pos];
151
+ if (!token) {
152
+ throw new SomaValueLangError('算术表达式不完整(缺少运算数)', this.source);
153
+ }
154
+ if (token.t === 'op' && token.v === '-') {
155
+ this.pos += 1;
156
+ return { kind: 'neg', operand: this.factor() };
157
+ }
158
+ if (token.t === 'num') {
159
+ this.pos += 1;
160
+ return { kind: 'lit', value: token.v };
161
+ }
162
+ if (token.t === 'id') {
163
+ this.pos += 1;
164
+ return this.pathNode(token.v);
165
+ }
166
+ if (token.t === '(') {
167
+ this.pos += 1;
168
+ const inner = this.expression();
169
+ if (this.tokens[this.pos]?.t !== ')') {
170
+ throw new SomaValueLangError('括号未闭合', this.source);
171
+ }
172
+ this.pos += 1;
173
+ return inner;
174
+ }
175
+ throw new SomaValueLangError('算术表达式中出现意外词元', this.source);
176
+ }
177
+
178
+ private pathNode(text: string): ValueNode {
179
+ if (text === 'true' || text === 'false') {
180
+ return { kind: 'lit', value: text === 'true' };
181
+ }
182
+ const head = text.split('.')[0];
183
+ if (!this.hasVar(head)) {
184
+ throw new SomaValueLangError(
185
+ `路径 "${text}" 的首段 "${head}" 不在当前作用域——算术只接受绑定路径与数字`,
186
+ this.source,
187
+ );
188
+ }
189
+ this.paths.push(text);
190
+ return { kind: 'path', path: text };
191
+ }
192
+ }
193
+
194
+ // ── 对外入口 ────────────────────────────────────────────────────────────────
195
+
196
+ /** 段内是否需要走算术解析(出现运算符或括号即是;路径词法不含它们) */
197
+ export function isArithSegment(segment: string): boolean {
198
+ return ARITH_HINT.test(segment);
199
+ }
200
+
201
+ /**
202
+ * 解析一个值段(不含管道)。
203
+ *
204
+ * 纯路径与纯字面量走快路径;含运算符时进算术文法。
205
+ */
206
+ export function parseValueSegment(
207
+ segment: string,
208
+ hasVar: HasVarFn,
209
+ position: ValuePosition = 'display',
210
+ source = segment,
211
+ ): { node: ValueNode; paths: string[] } {
212
+ const raw = segment.trim();
213
+ if (!raw) {
214
+ throw new SomaValueLangError('值段为空', source);
215
+ }
216
+
217
+ const forbidden = raw.match(FORBIDDEN);
218
+ if (forbidden) {
219
+ throw new SomaValueLangError(
220
+ `不支持的运算符 "${forbidden[0]}"——比较与布尔运算不进 DSL,判断写进 Domain`
221
+ + '(显隐用 when + ! 前缀,多分支用 match 管道或组件多态)',
222
+ source,
223
+ );
224
+ }
225
+
226
+ if (!isArithSegment(raw)) {
227
+ // 纯路径 / 纯字面量
228
+ if (/^-?\d+(\.\d+)?$/.test(raw)) {
229
+ return { node: { kind: 'lit', value: Number(raw) }, paths: [] };
230
+ }
231
+ if (raw === 'true' || raw === 'false') {
232
+ return { node: { kind: 'lit', value: raw === 'true' }, paths: [] };
233
+ }
234
+ const head = raw.split(/[.\s]/)[0];
235
+ if (hasVar(head)) {
236
+ // 首段在作用域内 ⇒ 这是绑定路径的意图,其余部分必须严格合法。
237
+ // 不校验的话 `item.price # 2` 会被当成一个名字很怪的路径静默通过,
238
+ // 运行时读不到值只渲染空白——典型的"不报错但坏掉"。
239
+ if (!PATH_SHAPE.test(raw)) {
240
+ throw new SomaValueLangError(
241
+ `路径 "${raw}" 含非法字符——路径只允许字母、数字、下划线与点`
242
+ + '(若本意是字面量文案,请换一个不以作用域变量开头的写法或加引号)',
243
+ source,
244
+ );
245
+ }
246
+ return { node: { kind: 'path', path: raw }, paths: [raw] };
247
+ }
248
+ return { node: { kind: 'lit', value: raw }, paths: [] };
249
+ }
250
+
251
+ if (position !== 'display') {
252
+ throw new SomaValueLangError(
253
+ `算术只允许出现在展示值位,当前位置是 ${position}`
254
+ + '——算出来的值不驱动行为,业务判断留在 Domain',
255
+ source,
256
+ );
257
+ }
258
+
259
+ const paths: string[] = [];
260
+ const node = new Parser(tokenize(raw, source), source, hasVar, paths).parse();
261
+ return { node, paths };
262
+ }
263
+
264
+ /** 值段内是否只是一条裸路径(供上层决定是否走既有轻路径) */
265
+ export function isPlainPath(node: ValueNode): node is { kind: 'path'; path: string } {
266
+ return node.kind === 'path';
267
+ }
268
+
269
+ // ── 求值(装配期结闭包时使用;纯函数,无副作用) ────────────────────────────
270
+
271
+ export interface EvalOptions {
272
+ /** dev 下算术遇非数值/除零直接抛错(含表达式原文);prod 返回 null 交由上层占位 */
273
+ dev?: boolean;
274
+ }
275
+
276
+ /**
277
+ * 对指令节点求值。
278
+ *
279
+ * 除零与非数值:dev 抛错(点名原文,避免"页面上一个 NaN 查半天"),
280
+ * prod 返回 null——上层渲染占位符,与 role_by 未命中的既有语义一致。
281
+ */
282
+ export function evaluateValueNode(
283
+ node: ValueNode,
284
+ read: (path: string) => unknown,
285
+ options: EvalOptions = {},
286
+ ): unknown {
287
+ switch (node.kind) {
288
+ case 'lit':
289
+ return node.value;
290
+ case 'path':
291
+ return read(node.path);
292
+ case 'neg': {
293
+ const operand = toNumber(evaluateValueNode(node.operand, read, options), node, options);
294
+ return operand === null ? null : -operand;
295
+ }
296
+ case 'arith': {
297
+ const left = toNumber(evaluateValueNode(node.left, read, options), node, options);
298
+ const right = toNumber(evaluateValueNode(node.right, read, options), node, options);
299
+ if (left === null || right === null) return null;
300
+ if (node.op === '/' && right === 0) {
301
+ if (options.dev) {
302
+ throw new SomaValueLangError('除数为 0', describeNode(node));
303
+ }
304
+ return null;
305
+ }
306
+ switch (node.op) {
307
+ case '+': return left + right;
308
+ case '-': return left - right;
309
+ case '*': return left * right;
310
+ case '/': return left / right;
311
+ }
312
+ }
313
+ }
314
+ return null;
315
+ }
316
+
317
+ function toNumber(value: unknown, node: ValueNode, options: EvalOptions): number | null {
318
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
319
+ if (typeof value === 'string' && value.trim() !== '') {
320
+ const parsed = Number(value);
321
+ if (Number.isFinite(parsed)) return parsed;
322
+ }
323
+ if (options.dev) {
324
+ throw new SomaValueLangError(
325
+ `算术运算数不是数值: ${JSON.stringify(value)}`,
326
+ describeNode(node),
327
+ );
328
+ }
329
+ return null;
330
+ }
331
+
332
+ /** 把指令节点还原成近似原文,仅用于报错可读性 */
333
+ export function describeNode(node: ValueNode): string {
334
+ switch (node.kind) {
335
+ case 'lit': return String(node.value);
336
+ case 'path': return node.path;
337
+ case 'neg': return `-${describeNode(node.operand)}`;
338
+ case 'arith': return `${describeNode(node.left)} ${node.op} ${describeNode(node.right)}`;
339
+ }
340
+ }
@@ -0,0 +1,249 @@
1
+ // 格式化管道(组件体系 U4):绑定值的展示格式化,让 Domain 回归存原始值。
2
+ //
3
+ // 语法(soma-core/doc/soma DSL 语法全书.md(格式化管道章)):
4
+ // item_price: item.price | money
5
+ // tip: page._locale.cart_total_count | tpl(count: page.totalCount)
6
+ // created: order.createdAt | date(YYYY-MM-DD HH:mm)
7
+ // 规则:纯函数、注册制白名单(未注册名编译报错)、可链式、仅用于展示位置。
8
+
9
+ import type { SomaPipeArg, SomaPipeCall } from '../../shared/types/scope-manifest.types';
10
+
11
+ export interface SomaPipeContext {
12
+ /** 读取绑定路径当前值(页面作用域=根实例;行作用域=行数据语义) */
13
+ read(path: string): unknown;
14
+ /** 当前 locale 表(货币符号、免费文案等本地化取值) */
15
+ locale(): Record<string, unknown> | undefined;
16
+ }
17
+
18
+ /** 管道函数:纯函数,入值 + 已求值实参 → 展示字符串 */
19
+ export type SomaPipeFn = (
20
+ value: unknown,
21
+ args: Record<string, unknown>,
22
+ ctx: SomaPipeContext,
23
+ ) => string;
24
+
25
+ export class SomaPipeError extends Error {
26
+ constructor(message: string) {
27
+ super(`[soma-core][管道] ${message}`);
28
+ this.name = 'SomaPipeError';
29
+ }
30
+ }
31
+
32
+ export interface ParsedPipedValue {
33
+ /** 管道前的绑定路径(原样,未经 resolver) */
34
+ basePath: string;
35
+ pipes: SomaPipeCall[];
36
+ /** 实参中的绑定路径(原样),供 watchPaths 注册 */
37
+ argPaths: string[];
38
+ }
39
+
40
+ /** 值是否携带管道(展示位置专用判断) */
41
+ export function hasPipes(rawValue: string): boolean {
42
+ return rawValue.includes(' | ');
43
+ }
44
+
45
+ const parseCache = new Map<string, ParsedPipedValue>();
46
+
47
+ /**
48
+ * 解析 `path | pipe1 | pipe2(k: v, 字面量)` 形式的值。
49
+ * 实参判定:首段是已注册 var 的视为绑定路径,其余为字面量(数字/布尔自动转型)。
50
+ * 结果按原始串缓存(编译路径与行内解释路径共享)。
51
+ */
52
+ export function parsePipedValue(
53
+ rawValue: string,
54
+ hasVar: (seg: string) => boolean,
55
+ ): ParsedPipedValue {
56
+ const cacheKey = rawValue;
57
+ const cached = parseCache.get(cacheKey);
58
+ if (cached) {
59
+ return cached;
60
+ }
61
+
62
+ const segments = rawValue.split(/\s+\|\s+/);
63
+ const basePath = segments[0].trim();
64
+ const pipes: SomaPipeCall[] = [];
65
+ const argPaths: string[] = [];
66
+
67
+ for (const segment of segments.slice(1)) {
68
+ const match = segment.trim().match(/^([a-z][a-zA-Z0-9_]*)(?:\((.*)\))?$/);
69
+ if (!match) {
70
+ throw new SomaPipeError(`管道段格式错误: "${segment}"(应为 name 或 name(args))`);
71
+ }
72
+ const [, name, rawArgs] = match;
73
+ const args: Record<string, SomaPipeArg> = {};
74
+
75
+ if (rawArgs !== undefined && rawArgs.trim() !== '') {
76
+ const parts = rawArgs.split(',').map((part) => part.trim()).filter(Boolean);
77
+ parts.forEach((part, index) => {
78
+ const colonIndex = part.indexOf(':');
79
+ const key = colonIndex > 0 ? part.slice(0, colonIndex).trim() : String(index);
80
+ const valueText = colonIndex > 0 ? part.slice(colonIndex + 1).trim() : part;
81
+ const arg = classifyArg(valueText, hasVar);
82
+ args[key] = arg;
83
+ if (arg.kind === 'binding') {
84
+ argPaths.push(String(arg.value));
85
+ }
86
+ });
87
+ }
88
+
89
+ pipes.push({ name, args: Object.keys(args).length ? args : undefined });
90
+ }
91
+
92
+ const parsed: ParsedPipedValue = { basePath, pipes, argPaths };
93
+ parseCache.set(cacheKey, parsed);
94
+ return parsed;
95
+ }
96
+
97
+ function classifyArg(valueText: string, hasVar: (seg: string) => boolean): SomaPipeArg {
98
+ const quoted = valueText.match(/^"(.*)"$|^'(.*)'$/);
99
+ if (quoted) {
100
+ return { kind: 'literal', value: quoted[1] ?? quoted[2] ?? '' };
101
+ }
102
+ if (/^-?\d+(\.\d+)?$/.test(valueText)) {
103
+ return { kind: 'literal', value: Number(valueText) };
104
+ }
105
+ if (valueText === 'true' || valueText === 'false') {
106
+ return { kind: 'literal', value: valueText === 'true' };
107
+ }
108
+ if (hasVar(valueText.split('.')[0])) {
109
+ return { kind: 'binding', value: valueText };
110
+ }
111
+ return { kind: 'literal', value: valueText };
112
+ }
113
+
114
+ // ─── 注册表 ──────────────────────────────────────────────────
115
+
116
+ export class SomaPipeRegistry {
117
+ private readonly fns = new Map<string, SomaPipeFn>();
118
+
119
+ constructor(custom?: Record<string, SomaPipeFn>) {
120
+ for (const [name, fn] of Object.entries(BUILTIN_PIPES)) {
121
+ this.fns.set(name, fn);
122
+ }
123
+ for (const [name, fn] of Object.entries(custom ?? {})) {
124
+ if (!/^[a-z][a-zA-Z0-9_]*$/.test(name)) {
125
+ throw new SomaPipeError(`管道名 "${name}" 不合法(小写字母开头)`);
126
+ }
127
+ this.fns.set(name, fn);
128
+ }
129
+ }
130
+
131
+ has(name: string): boolean {
132
+ return this.fns.has(name);
133
+ }
134
+
135
+ /** 编译期白名单校验:未注册名直接抛错(fail fast) */
136
+ assertKnown(pipes: SomaPipeCall[], where: string): void {
137
+ for (const pipe of pipes) {
138
+ if (!this.fns.has(pipe.name)) {
139
+ throw new SomaPipeError(
140
+ `未注册的管道 "${pipe.name}"(位置: ${where};已注册: ${[...this.fns.keys()].join(', ')})`,
141
+ );
142
+ }
143
+ }
144
+ }
145
+
146
+ /** 链式应用(从左到右);单个管道异常时降级为原值字符串并告警,不中断渲染 */
147
+ apply(value: unknown, pipes: SomaPipeCall[], ctx: SomaPipeContext): string {
148
+ let current: unknown = value;
149
+ for (const pipe of pipes) {
150
+ const fn = this.fns.get(pipe.name);
151
+ if (!fn) {
152
+ console.warn(`[soma-core][管道] 未注册的管道 "${pipe.name}",跳过`);
153
+ continue;
154
+ }
155
+ const args: Record<string, unknown> = {};
156
+ for (const [key, arg] of Object.entries(pipe.args ?? {})) {
157
+ args[key] = arg.kind === 'binding' ? ctx.read(String(arg.value)) : arg.value;
158
+ }
159
+ try {
160
+ current = fn(current, args, ctx);
161
+ } catch (error) {
162
+ console.warn(`[soma-core][管道] 管道 "${pipe.name}" 执行失败:`, error);
163
+ return String(value ?? '');
164
+ }
165
+ }
166
+ return String(current ?? '');
167
+ }
168
+ }
169
+
170
+ // ─── 内置管道 ────────────────────────────────────────────────
171
+
172
+ function localeText(ctx: SomaPipeContext, key: string, fallback: string): string {
173
+ const locale = ctx.locale();
174
+ const value = locale?.[key];
175
+ return typeof value === 'string' ? value : fallback;
176
+ }
177
+
178
+ const BUILTIN_PIPES: Record<string, SomaPipeFn> = {
179
+ /**
180
+ * 金额:money | money(neg) | money(free)
181
+ * neg:非零值加负号(折扣行);free:零值显示免费文案(locale.money_free)。
182
+ */
183
+ money(value, args, ctx) {
184
+ const num = Number(value);
185
+ if (!Number.isFinite(num)) {
186
+ return String(value ?? '');
187
+ }
188
+ const mode = args['0'];
189
+ if (mode === 'free' && num === 0) {
190
+ return localeText(ctx, 'money_free', '免费');
191
+ }
192
+ const symbol = localeText(ctx, 'money_symbol', '¥');
193
+ const amount = Math.abs(num).toLocaleString('zh-CN', {
194
+ minimumFractionDigits: 2,
195
+ maximumFractionDigits: 2,
196
+ });
197
+ const negative = mode === 'neg' ? num !== 0 : num < 0;
198
+ return `${negative ? '-' : ''}${symbol}${amount}`;
199
+ },
200
+
201
+ /** 模板插值:value 为模板串(通常 _locale.key),{name} 用实参替换 */
202
+ tpl(value, args) {
203
+ let text = String(value ?? '');
204
+ for (const [key, arg] of Object.entries(args)) {
205
+ text = text.split(`{${key}}`).join(String(arg ?? ''));
206
+ }
207
+ return text;
208
+ },
209
+
210
+ /** 日期格式化:date(YYYY-MM-DD HH:mm:ss),接受 Date/ISO 串/时间戳 */
211
+ date(value, args) {
212
+ const input = typeof value === 'number' || value instanceof Date
213
+ ? new Date(value)
214
+ : new Date(String(value ?? ''));
215
+ if (Number.isNaN(input.getTime())) {
216
+ return String(value ?? '');
217
+ }
218
+ const format = String(args['0'] ?? 'YYYY-MM-DD');
219
+ const pad = (n: number) => String(n).padStart(2, '0');
220
+ return format
221
+ .replace('YYYY', String(input.getFullYear()))
222
+ .replace('MM', pad(input.getMonth() + 1))
223
+ .replace('DD', pad(input.getDate()))
224
+ .replace('HH', pad(input.getHours()))
225
+ .replace('mm', pad(input.getMinutes()))
226
+ .replace('ss', pad(input.getSeconds()));
227
+ },
228
+
229
+ /** 百分比:percent(小数位),输入为比率(0.125 → 12.5%) */
230
+ percent(value, args) {
231
+ const num = Number(value);
232
+ if (!Number.isFinite(num)) {
233
+ return String(value ?? '');
234
+ }
235
+ const digits = Number(args['0'] ?? 0);
236
+ return `${(num * 100).toFixed(digits)}%`;
237
+ },
238
+
239
+ /** 单复数文案:plural(单数key, 复数key),按数值取 locale 文案并替换 {count} */
240
+ plural(value, args, ctx) {
241
+ const num = Number(value);
242
+ const key = String(num === 1 ? args['0'] ?? '' : args['1'] ?? args['0'] ?? '');
243
+ const template = localeText(ctx, key, key);
244
+ return template.split('{count}').join(String(value ?? ''));
245
+ },
246
+ };
247
+
248
+ /** 默认注册表(仅内置管道),未传自定义管道时全局共享 */
249
+ export const defaultPipeRegistry = new SomaPipeRegistry();
@@ -38,7 +38,10 @@ export class SomaQualityRegistry {
38
38
  { id: 'cache', name: 'Parse cache', carrier: 'SomaAssetResolver', description: 'LRU cache for YAML parse results' },
39
39
  ];
40
40
 
41
+ // 可注册扩展面(Host 注入)。主题故意不在此列:令牌派生是引擎内建,见 theme-engine.ts。
41
42
  static readonly extensibilityDimensions: ExtensibilityDimension[] = [
43
+ { id: 'components', name: 'Component registry', carrier: 'SomaComponentRegistry', description: 'Host/page register SomaComponentDefinition; not theme' },
44
+ { id: 'pipes', name: 'Format pipes', carrier: 'SomaPipeRegistry', description: 'Host register pure format pipes; merge with builtins' },
42
45
  { id: 'adapter', name: 'Container adapter', carrier: 'SomaContainerAdapter', description: 'Isolate DOM ops for cross-platform hosts' },
43
46
  { id: 'middleware', name: 'Middleware chains', carrier: 'SomaMiddlewareChain', description: 'Onion-model hooks for render and event engines' },
44
47
  { id: 'hotswap', name: 'Hot swap', carrier: 'SomaBootstrap.hotSwap', description: 'Replace ui/event/style/DomainClass at runtime' },