soma-core 1.4.2 → 1.5.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 (212) hide show
  1. package/bin/component.cjs +240 -0
  2. package/bin/eject.cjs +174 -0
  3. package/bin/migrate.cjs +362 -0
  4. package/core/build/blocks/block-compile.ts +143 -17
  5. package/core/build/blocks/migrate-flat.ts +118 -25
  6. package/core/build/compiler/page-declaration-compiler.ts +149 -5
  7. package/core/build/compiler/route-builder.ts +0 -4
  8. package/core/build/compiler/soma-precompile.js +431 -26
  9. package/core/build/component/component-graph.ts +28 -105
  10. package/core/build/component/package-loader.ts +18 -4
  11. package/core/build/eject/component-eject.ts +8 -2
  12. package/core/build/layout/constraint-solver.ts +131 -16
  13. package/core/build/layout/css-emitter.ts +15 -9
  14. package/core/build/ooui/artifact/artifact.types.ts +275 -0
  15. package/core/build/ooui/artifact/emit-artifact.ts +269 -0
  16. package/core/build/ooui/artifact/emit-html.ts +204 -0
  17. package/core/build/ooui/artifact/index.ts +53 -0
  18. package/core/build/ooui/artifact/spatial-tree.ts +268 -0
  19. package/core/build/ooui/artifact/utility-class.ts +83 -0
  20. package/core/build/ooui/composition/candidate.types.ts +323 -0
  21. package/core/build/ooui/composition/control-model.ts +114 -0
  22. package/core/build/ooui/composition/registry.ts +520 -0
  23. package/core/build/ooui/composition/select.ts +232 -0
  24. package/core/build/ooui/diagnostics/codes.ts +230 -0
  25. package/core/build/ooui/diagnostics/error.ts +235 -0
  26. package/core/build/ooui/diagnostics/format.ts +106 -0
  27. package/core/build/ooui/diagnostics/index.ts +62 -0
  28. package/core/build/ooui/diagnostics/issue.types.ts +112 -0
  29. package/core/build/ooui/engine-slot.ts +184 -0
  30. package/core/build/ooui/index.ts +1427 -0
  31. package/core/build/ooui/intent/derive-intent.ts +450 -0
  32. package/core/build/ooui/intent/field-rules.ts +330 -0
  33. package/core/build/ooui/intent/intent.types.ts +476 -0
  34. package/core/build/ooui/intent/verb-events.ts +285 -0
  35. package/core/build/ooui/page/budget.ts +503 -0
  36. package/core/build/ooui/page/compose-page.ts +736 -0
  37. package/core/build/ooui/page/index.ts +66 -0
  38. package/core/build/ooui/page/page.types.ts +402 -0
  39. package/core/build/ooui/page/region-row.ts +241 -0
  40. package/core/build/ooui/semantic/expand-page-surface.ts +180 -0
  41. package/core/build/ooui/semantic/kernel.types.ts +187 -0
  42. package/core/build/ooui/semantic/normalize.ts +784 -0
  43. package/core/build/ooui/semantic/origin.types.ts +211 -0
  44. package/core/build/ooui/semantic/role-alias.ts +154 -0
  45. package/core/build/ooui/semantic/shorthand.ts +233 -0
  46. package/core/build/ooui/semantic/surface.types.ts +78 -0
  47. package/core/build/ooui/semantic/validate-request.ts +267 -0
  48. package/core/build/ooui/spatial/emit-utility.ts +480 -0
  49. package/core/build/ooui/spatial/ir.types.ts +443 -0
  50. package/core/build/ooui/spatial/registry.ts +565 -0
  51. package/core/build/ooui/spatial/solve.ts +769 -0
  52. package/core/build/ooui/spatial/utility.types.ts +242 -0
  53. package/core/build/ooui/trace/index.ts +40 -0
  54. package/core/build/ooui/trace/render.ts +190 -0
  55. package/core/build/ooui/trace/source.types.ts +69 -0
  56. package/core/build/ooui/trace/trace.types.ts +326 -0
  57. package/core/client/component/example-blocks.ts +1 -7
  58. package/core/client/component/theme-component-tokens.ts +12 -15
  59. package/core/client/data/data-object-resolver.ts +27 -8
  60. package/core/client/diagnostics/telemetry-context.ts +0 -4
  61. package/core/client/engine/asset-resolver.ts +0 -1
  62. package/core/client/engine/event-engine.ts +7 -3
  63. package/core/client/engine/soma-bootstrap.ts +292 -34
  64. package/core/client/engine/style-binder.ts +0 -1
  65. package/core/client/infra/http/IHttpClient.ts +0 -6
  66. package/core/client/infra/http/SomaHttpService.ts +4 -1
  67. package/core/client/infra/notify/DomNotifyService.ts +1 -1
  68. package/core/client/infra/router/router-path.ts +0 -6
  69. package/core/client/parser/annotation-extractor.ts +1 -1
  70. package/core/client/parser/blocks/namespace.ts +30 -5
  71. package/core/client/parser/blocks/page-parser.ts +44 -1
  72. package/core/client/parser/blocks/use-parser.ts +266 -46
  73. package/core/client/parser/data-config-parser.ts +71 -3
  74. package/core/client/parser/layout-parser.ts +4 -3
  75. package/core/client/parser/reaction-parser.ts +0 -1
  76. package/core/client/parser/ui-config-parser.ts +212 -74
  77. package/core/client/theme/scene-tokens.ts +9 -3
  78. package/core/client/theme/theme-axes.ts +74 -16
  79. package/core/client/theme/theme-engine.ts +280 -69
  80. package/core/client/theme/tone-solver.ts +9 -8
  81. package/core/index.ts +18 -4
  82. package/core/server/api/load-host-service.ts +8 -2
  83. package/core/server/declaration-safety.ts +11 -0
  84. package/core/server/host/page-response-request.ts +0 -2
  85. package/core/server/host/published-page-artifact-cache.ts +244 -0
  86. package/core/server/host/published-page-assets.ts +44 -5
  87. package/core/server/mock/node/cli.mjs +0 -1
  88. package/core/server/mock/node/schema-generator.mjs +0 -1
  89. package/core/server/ooui.ts +34 -0
  90. package/core/server/page-assets.ts +8 -0
  91. package/core/server/page-declaration.ts +18 -0
  92. package/core/server/registry/asset-store.ts +327 -0
  93. package/core/server/registry/declaration-precompiler.ts +49 -6
  94. package/core/server/registry/index.ts +47 -1
  95. package/core/server/registry/page-registry-repository.ts +6 -2
  96. package/core/server/registry/page-registry-store.ts +133 -19
  97. package/core/server/registry/publish-asset-pin.ts +557 -0
  98. package/core/server/registry/services/pages/List.ts +15 -3
  99. package/core/server/registry/validation/compile-gate.ts +180 -8
  100. package/core/server/registry/validation/declaration-safety-scan.ts +113 -23
  101. package/core/shared/component/derive-sample.ts +201 -16
  102. package/core/shared/component/field-lines.ts +98 -8
  103. package/core/shared/container-breakpoints.ts +46 -0
  104. package/core/shared/object-semantics.ts +240 -0
  105. package/core/shared/ooui-declaration.ts +235 -0
  106. package/core/shared/types/component-contract.types.ts +7 -6
  107. package/core/shared/types/data-config.types.ts +95 -0
  108. package/core/shared/types/domain.types.ts +0 -24
  109. package/core/shared/types/engine.types.ts +0 -5
  110. package/core/shared/types/layout-constraint.types.ts +16 -0
  111. package/core/shared/types/ui-config.types.ts +163 -13
  112. package/dist/cli/soma.js +24 -11
  113. package/dist/core/index.cjs +1563 -800
  114. package/dist/types/build/blocks/block-compile.d.ts +16 -1
  115. package/dist/types/build/blocks/migrate-flat.d.ts +17 -0
  116. package/dist/types/build/compiler/page-declaration-compiler.d.ts +46 -0
  117. package/dist/types/build/compiler/route-builder.d.ts +0 -1
  118. package/dist/types/build/component/component-graph.d.ts +17 -53
  119. package/dist/types/build/component/package-loader.d.ts +8 -1
  120. package/dist/types/build/layout/constraint-solver.d.ts +46 -4
  121. package/dist/types/build/ooui/artifact/artifact.types.d.ts +180 -0
  122. package/dist/types/build/ooui/artifact/emit-artifact.d.ts +58 -0
  123. package/dist/types/build/ooui/artifact/emit-html.d.ts +53 -0
  124. package/dist/types/build/ooui/artifact/index.d.ts +5 -0
  125. package/dist/types/build/ooui/artifact/spatial-tree.d.ts +48 -0
  126. package/dist/types/build/ooui/artifact/utility-class.d.ts +46 -0
  127. package/dist/types/build/ooui/composition/candidate.types.d.ts +206 -0
  128. package/dist/types/build/ooui/composition/control-model.d.ts +37 -0
  129. package/dist/types/build/ooui/composition/registry.d.ts +66 -0
  130. package/dist/types/build/ooui/composition/select.d.ts +63 -0
  131. package/dist/types/build/ooui/diagnostics/codes.d.ts +28 -0
  132. package/dist/types/build/ooui/diagnostics/error.d.ts +135 -0
  133. package/dist/types/build/ooui/diagnostics/format.d.ts +51 -0
  134. package/dist/types/build/ooui/diagnostics/index.d.ts +25 -0
  135. package/dist/types/build/ooui/diagnostics/issue.types.d.ts +56 -0
  136. package/dist/types/build/ooui/engine-slot.d.ts +41 -0
  137. package/dist/types/build/ooui/index.d.ts +286 -0
  138. package/dist/types/build/ooui/intent/derive-intent.d.ts +32 -0
  139. package/dist/types/build/ooui/intent/field-rules.d.ts +99 -0
  140. package/dist/types/build/ooui/intent/intent.types.d.ts +318 -0
  141. package/dist/types/build/ooui/intent/verb-events.d.ts +70 -0
  142. package/dist/types/build/ooui/page/budget.d.ts +28 -0
  143. package/dist/types/build/ooui/page/compose-page.d.ts +41 -0
  144. package/dist/types/build/ooui/page/index.d.ts +4 -0
  145. package/dist/types/build/ooui/page/page.types.d.ts +264 -0
  146. package/dist/types/build/ooui/page/region-row.d.ts +16 -0
  147. package/dist/types/build/ooui/semantic/expand-page-surface.d.ts +33 -0
  148. package/dist/types/build/ooui/semantic/kernel.types.d.ts +125 -0
  149. package/dist/types/build/ooui/semantic/normalize.d.ts +45 -0
  150. package/dist/types/build/ooui/semantic/origin.types.d.ts +95 -0
  151. package/dist/types/build/ooui/semantic/role-alias.d.ts +35 -0
  152. package/dist/types/build/ooui/semantic/shorthand.d.ts +60 -0
  153. package/dist/types/build/ooui/semantic/surface.types.d.ts +16 -0
  154. package/dist/types/build/ooui/semantic/validate-request.d.ts +19 -0
  155. package/dist/types/build/ooui/spatial/emit-utility.d.ts +43 -0
  156. package/dist/types/build/ooui/spatial/ir.types.d.ts +280 -0
  157. package/dist/types/build/ooui/spatial/registry.d.ts +110 -0
  158. package/dist/types/build/ooui/spatial/solve.d.ts +42 -0
  159. package/dist/types/build/ooui/spatial/utility.types.d.ts +191 -0
  160. package/dist/types/build/ooui/trace/index.d.ts +3 -0
  161. package/dist/types/build/ooui/trace/render.d.ts +42 -0
  162. package/dist/types/build/ooui/trace/source.types.d.ts +25 -0
  163. package/dist/types/build/ooui/trace/trace.types.d.ts +143 -0
  164. package/dist/types/client/component/example-blocks.d.ts +0 -2
  165. package/dist/types/client/component/theme-component-tokens.d.ts +8 -5
  166. package/dist/types/client/data/data-object-resolver.d.ts +10 -2
  167. package/dist/types/client/diagnostics/telemetry-context.d.ts +0 -1
  168. package/dist/types/client/engine/soma-bootstrap.d.ts +123 -10
  169. package/dist/types/client/infra/http/IHttpClient.d.ts +0 -5
  170. package/dist/types/client/infra/http/SomaHttpService.d.ts +1 -1
  171. package/dist/types/client/infra/router/router-path.d.ts +0 -2
  172. package/dist/types/client/parser/blocks/namespace.d.ts +20 -0
  173. package/dist/types/client/parser/blocks/page-parser.d.ts +9 -0
  174. package/dist/types/client/parser/blocks/use-parser.d.ts +38 -4
  175. package/dist/types/client/parser/data-config-parser.d.ts +13 -0
  176. package/dist/types/client/parser/ui-config-parser.d.ts +1 -11
  177. package/dist/types/client/theme/scene-tokens.d.ts +9 -3
  178. package/dist/types/client/theme/theme-axes.d.ts +64 -1
  179. package/dist/types/client/theme/theme-engine.d.ts +13 -8
  180. package/dist/types/client/theme/tone-solver.d.ts +9 -5
  181. package/dist/types/index.d.ts +4 -5
  182. package/dist/types/server/declaration-safety.d.ts +7 -0
  183. package/dist/types/server/host/page-response-request.d.ts +0 -1
  184. package/dist/types/server/host/published-page-artifact-cache.d.ts +64 -0
  185. package/dist/types/server/ooui.d.ts +18 -0
  186. package/dist/types/server/page-assets.d.ts +7 -0
  187. package/dist/types/server/page-declaration.d.ts +14 -0
  188. package/dist/types/server/registry/asset-store.d.ts +112 -0
  189. package/dist/types/server/registry/declaration-precompiler.d.ts +23 -3
  190. package/dist/types/server/registry/index.d.ts +3 -1
  191. package/dist/types/server/registry/page-registry-store.d.ts +57 -4
  192. package/dist/types/server/registry/publish-asset-pin.d.ts +166 -0
  193. package/dist/types/server/registry/services/pages/List.d.ts +9 -3
  194. package/dist/types/server/registry/validation/compile-gate.d.ts +63 -0
  195. package/dist/types/shared/component/derive-sample.d.ts +14 -0
  196. package/dist/types/shared/container-breakpoints.d.ts +42 -0
  197. package/dist/types/shared/object-semantics.d.ts +42 -0
  198. package/dist/types/shared/ooui-declaration.d.ts +135 -0
  199. package/dist/types/shared/types/component-contract.types.d.ts +7 -6
  200. package/dist/types/shared/types/data-config.types.d.ts +86 -0
  201. package/dist/types/shared/types/domain.types.d.ts +0 -21
  202. package/dist/types/shared/types/engine.types.d.ts +0 -4
  203. package/dist/types/shared/types/layout-constraint.types.d.ts +1 -0
  204. package/dist/types/shared/types/ui-config.types.d.ts +157 -12
  205. package/next.config.js +106 -13
  206. package/package.json +28 -2
  207. package/core/client/host-bridge/index.ts +0 -27
  208. package/core/client/parser/yaml-loader.ts +0 -36
  209. package/core/shared/manifest/manifest-contract.ts +0 -12
  210. package/dist/types/client/host-bridge/index.d.ts +0 -9
  211. package/dist/types/client/parser/yaml-loader.d.ts +0 -21
  212. package/dist/types/shared/manifest/manifest-contract.d.ts +0 -4
@@ -0,0 +1,362 @@
1
+ /**
2
+ * `soma migrate` —— 平铺三件套 → 块声明 的批量迁移命令(REQ-005 F8.3)。
3
+ *
4
+ * ── 为什么这个文件今天才出现 ───────────────────────────────────────
5
+ * 迁移器 `core/build/blocks/migrate-flat.ts` 早就写完、14 条用例全绿,
6
+ * 而《声明语法手册》里明写着一行:
7
+ *
8
+ * | 平铺 → 块 迁移 | 引擎侧有迁移器,**未对外提供批量迁移命令** |
9
+ *
10
+ * 也就是说:能力在,入口没有。宿主要迁移只能自己去 import 一个内部模块——
11
+ * 而那是包的内部路径,随时会搬家。`verify:reachable` 把它报成
12
+ * "只有测试够得到",这个文件就是那条缺失的连接。
13
+ *
14
+ * ── 迁移必须是机械的 ───────────────────────────────────────────────
15
+ * 迁移器自己的文件头写着:逐条封闭变换规则、不含判断、不猜意图——
16
+ * 因为它跑在**存量页面**上,一次"聪明的推断"就是一次静默改语义。
17
+ * 本命令照此办理,并把两条硬要求暴露成命令行行为:
18
+ *
19
+ * · **等价**——迁移前后作用域清单树必须一致(`verifyEquivalence` 比对,
20
+ * 不靠肉眼)。不一致时**不写盘**,直接报出差异并以非零码退出。
21
+ * · **不静默丢弃**——迁移器报告里"未迁移的部分"(如 `_style.yaml` 的
22
+ * transitions 需要人工并进 HTML class)原样打印出来;**带着这类残留的侧车
23
+ * 一份都不删,整页不写盘**,等人处理完再跑一次。
24
+ *
25
+ * ── 侧车在哪儿找、删哪几份 ─────────────────────────────────────────
26
+ * 服务端认哪几处侧车(`server-page-assets` 的 SOMA_PAGE_SIDECAR_FORBIDDEN,422),
27
+ * 这里就找哪几处;删的**恰好**是迁移器报"已完整迁入"(`sidecars[kind] === 'migrated'`)的那几份。
28
+ * 曾经两头都错:
29
+ * · 只在 `_ui.yaml` 旁边找 `_event.yaml`,而标准布局放在 `event/<base>_event.yaml`——
30
+ * 事件一条没读到,等价校验拿 {} 去比当然"等价",写下去整页事件丢失;
31
+ * · 无条件删 `_style.yaml`(迁移器从不迁它),却从不删已并进 page.data 的 `_data.yaml`——
32
+ * 前者丢内容,后者留下一份让服务端 422 的残件。
33
+ *
34
+ * 缺省 `--dry-run`:**要显式写 `--write` 才落盘**。批量改存量页面的命令
35
+ * 默认动手是危险的——看一眼再决定,比迁完再回滚便宜。
36
+ */
37
+ const fs = require('node:fs');
38
+ const path = require('node:path');
39
+
40
+ function usage() {
41
+ console.error([
42
+ 'Usage:',
43
+ ' soma migrate <目录> [--write] 平铺三件套(_ui/_event/_style/_data.yaml) → 块声明',
44
+ '',
45
+ '选项:',
46
+ ' --write 真的落盘(缺省只试跑并打印报告,不改任何文件)',
47
+ ' --html <目录> 页面 HTML 所在目录(缺省先找与 YAML 同目录,再找标准布局的 html/)',
48
+ '',
49
+ '<目录> 是 *_ui.yaml 所在目录(标准布局下即 ui/ 或其子目录);侧车按服务端的位置找:',
50
+ ' event/<页>_event.yaml · ui/<页>_style.yaml · data/<页>_data.yaml · ui/<页>_data.yaml',
51
+ '',
52
+ '三条硬要求由本命令强制,不可关闭:',
53
+ ' · 等价——迁移前后作用域清单树必须一致,不一致时不写盘;',
54
+ ' · 不静默丢弃——迁移器报告里未迁移的部分原样打印;',
55
+ ' · 侧车里有没迁的内容时,整页不写盘、侧车一份不删;只删已完整迁入的侧车。',
56
+ ].join('\n'));
57
+ }
58
+
59
+ /**
60
+ * 迁移器与块编译器是 TS 源码,用 jiti 现编译加载——与 `soma db` / `soma eject` 同一条路。
61
+ *
62
+ * 曾经抄的是 `bin/component.cjs` 那条"先 dist、回退 tsx/cjs":dist/cli 下从来不产这两个模块
63
+ * (tsconfig.cli.json 只编 bin/soma.ts),于是永远走 tsx;而 tsx 只在 devDependencies 里——
64
+ * 仓内跑得通、装出去的包里一跑就 "Cannot find module 'tsx/cjs'"。jiti 是运行时依赖。
65
+ */
66
+ function loadBuildModule(packageRoot, relative) {
67
+ const createJiti = require('jiti');
68
+ const jiti = createJiti(__filename, { interopDefault: true });
69
+ return jiti(path.resolve(packageRoot, 'core/build', `${relative}.ts`));
70
+ }
71
+
72
+ /**
73
+ * 标准 Host 布局下,`dir` 在资产根里的位置。
74
+ *
75
+ * 服务端以资产根为基准定位一页的全部文件:`html/<页>.html`、`ui/<页>_ui.yaml`、
76
+ * `event/<页>_event.yaml`、`data/<页>_data.yaml`,页名可以带子目录。
77
+ * 本命令收的是 `*_ui.yaml` 所在目录,也就是 `ui/` 或它的子目录——往上找到名为 `ui`
78
+ * 的那一层,它的父目录就是资产根,中间那段就是页名的目录前缀。
79
+ * 找不到(非标准布局)返回 null,只认与 `_ui.yaml` 同目录的侧车。
80
+ */
81
+ function resolveHostLayout(dir) {
82
+ let current = dir;
83
+ for (;;) {
84
+ if (path.basename(current) === 'ui') {
85
+ return { assetRoot: path.dirname(current), sub: path.relative(current, dir) };
86
+ }
87
+ const parent = path.dirname(current);
88
+ if (parent === current) return null;
89
+ current = parent;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * 一页的 HTML 与全部侧车——**服务端查哪几处,这里就查哪几处**:
95
+ * event/<页>_event.yaml · ui/<页>_style.yaml · data/<页>_data.yaml · ui/<页>_data.yaml
96
+ * (与 server-page-assets / manifest 插件 / LSP 三处的清单逐项对齐),外加非标准布局下
97
+ * 与 `_ui.yaml` 同目录的 `_event.yaml`(本命令一直认的旧位置)。
98
+ *
99
+ * 同一种侧车命中不止一份时如实全列出来,由调用方拒绝——哪份在生效,本命令不猜。
100
+ */
101
+ function locatePageFiles(dir, base, htmlDir) {
102
+ const layout = resolveHostLayout(dir);
103
+ const inAssetRoot = (segment, file) => (layout ? [path.join(layout.assetRoot, segment, layout.sub, file)] : []);
104
+ const candidates = {
105
+ eventYaml: [path.join(dir, `${base}_event.yaml`), ...inAssetRoot('event', `${base}_event.yaml`)],
106
+ styleYaml: [path.join(dir, `${base}_style.yaml`)],
107
+ dataYaml: [path.join(dir, `${base}_data.yaml`), ...inAssetRoot('data', `${base}_data.yaml`)],
108
+ };
109
+ const sidecars = {};
110
+ for (const [kind, files] of Object.entries(candidates)) {
111
+ sidecars[kind] = [...new Set(files)].filter((file) => fs.existsSync(file));
112
+ }
113
+ const htmlCandidates = htmlDir
114
+ ? [path.join(htmlDir, `${base}.html`)]
115
+ : [path.join(dir, `${base}.html`), ...inAssetRoot('html', `${base}.html`)];
116
+ return { html: htmlCandidates.find((file) => fs.existsSync(file)) ?? null, sidecars };
117
+ }
118
+
119
+ /**
120
+ * 目录下的平铺页。
121
+ *
122
+ * 迁移器收的是**已解析的对象**(`FlatPageFiles` 是 `Record<string, unknown>`),
123
+ * 不是 YAML 文本——解析放到逐页处理里做,一页的 YAML 坏了只算这一页失败。
124
+ * HTML 不进迁移器,它是后面等价校验时编译块声明用的(`compileSomaBlocks` 要靠它核锚点)。
125
+ */
126
+ function collectPages(dir, htmlDir, skipped) {
127
+ const pages = [];
128
+ for (const name of fs.readdirSync(dir).sort()) {
129
+ if (!name.endsWith('_ui.yaml')) continue;
130
+ const base = name.slice(0, -'_ui.yaml'.length);
131
+ const raw = fs.readFileSync(path.join(dir, name), 'utf8');
132
+ // 已经是块声明的跳过:`{{` 开关是块声明的唯一标记,重迁一次是无意义的写盘。
133
+ // 记下来:"没有平铺页"与"全都已经迁过了"是两回事,消息不能混。
134
+ if (raw.trimStart().startsWith('{{')) { skipped.push(base); continue; }
135
+ pages.push({ base, dir, raw, ...locatePageFiles(dir, base, htmlDir) });
136
+ }
137
+ return pages;
138
+ }
139
+
140
+ function errorMessage(error) {
141
+ return error && error.message ? error.message : String(error);
142
+ }
143
+
144
+ /**
145
+ * 迁移一个目录。返回退出码与计数,不自己退出进程(测试与 runMigrate 共用)。
146
+ *
147
+ * @param options.target `*_ui.yaml` 所在目录(绝对路径)
148
+ * @param options.htmlDir 显式给的 HTML 目录;不给时按 locatePageFiles 的顺序找
149
+ * @param options.write 是否落盘
150
+ * @param options.modules `{ migrateFlatToBlocks, verifyEquivalence, compileSomaBlocks }`
151
+ */
152
+ function migrateDirectory({ target, htmlDir, write, modules }) {
153
+ const yaml = require('js-yaml');
154
+ const { migrateFlatToBlocks, verifyEquivalence, compileSomaBlocks } = modules;
155
+ const shown = (file) => path.relative(target, file) || path.basename(file);
156
+
157
+ const skipped = [];
158
+ const pages = collectPages(target, htmlDir, skipped);
159
+ if (pages.length === 0) {
160
+ // 两种"没有可迁移的"含义完全不同,报同一句话会让人以为路径写错了。
161
+ if (skipped.length > 0) {
162
+ console.log(`[soma migrate] ${target} 下的 ${skipped.length} 页都已经是块声明了,无需迁移:`);
163
+ for (const base of skipped) console.log(` · ${base}`);
164
+ return { exitCode: 0, pages: 0, failed: 0, inequivalent: 0, blocked: 0, migrated: 0 };
165
+ }
166
+ console.error(`[soma migrate] ${target} 下没有 *_ui.yaml——检查路径是否指向页面声明目录。`);
167
+ return { exitCode: 1, pages: 0, failed: 0, inequivalent: 0, blocked: 0, migrated: 0 };
168
+ }
169
+ if (skipped.length > 0) {
170
+ console.log(`[soma migrate] 跳过 ${skipped.length} 页(已经是块声明):${skipped.join('、')}`);
171
+ }
172
+
173
+ // 三类没写盘的页分开计:修法完全不同——
174
+ // failed YAML 解析 / 迁移器抛错 / 产物编译不过:声明本身有问题;
175
+ // inequivalent 迁得出来但语义不等价:迁移器的变换对这一页不成立;
176
+ // blocked 侧车里有迁移器不迁的内容、或同一种侧车不止一份:要人先处理。
177
+ // 曾经全算进一个计数、统一报"未通过等价校验",编译不过的页也被说成不等价,排查方向一开始就是错的。
178
+ let failed = 0;
179
+ let inequivalent = 0;
180
+ let blocked = 0;
181
+ let migrated = 0;
182
+ for (const page of pages) {
183
+ // 同一种侧车两处都有:迁移器只能吃一份——吃哪份,另一份的内容都会在删除时丢掉。
184
+ const ambiguous = Object.values(page.sidecars).filter((files) => files.length > 1);
185
+ if (ambiguous.length > 0) {
186
+ console.error(`\n✗ ${page.base} 同一种侧车有不止一份——这一页不写盘、侧车一份不删`);
187
+ for (const files of ambiguous) console.error(` ${files.map(shown).join(' 与 ')}`);
188
+ console.error(' 先合并成一份再迁:哪份在生效,本命令不猜。');
189
+ blocked += 1;
190
+ continue;
191
+ }
192
+ const sidecarFile = (kind) => page.sidecars[kind][0];
193
+
194
+ let files;
195
+ try {
196
+ files = { uiYaml: yaml.load(page.raw) ?? {} };
197
+ for (const kind of Object.keys(page.sidecars)) {
198
+ const file = sidecarFile(kind);
199
+ if (file) files[kind] = yaml.load(fs.readFileSync(file, 'utf8')) ?? {};
200
+ }
201
+ } catch (error) {
202
+ console.error(`\n✗ ${page.base} YAML 解析失败:${errorMessage(error)}`);
203
+ failed += 1;
204
+ continue;
205
+ }
206
+
207
+ let result;
208
+ try {
209
+ result = migrateFlatToBlocks(files);
210
+ } catch (error) {
211
+ console.error(`\n✗ ${page.base} 迁移失败:${errorMessage(error)}`);
212
+ failed += 1;
213
+ continue;
214
+ }
215
+
216
+ // 等价校验:不一致时**不写盘**。迁移器自己的纪律是"语义等价由 verifyEquivalence
217
+ // 比对,不靠肉眼"——那条纪律只有在这里真的挡住写盘时才成立。
218
+ //
219
+ // 校验要拿**编译后**的块结果(`{ ui, event }`)去比,不是比文本:
220
+ // 文本一定不一样(那正是迁移做的事),要比的是语义。
221
+ let compiled;
222
+ try {
223
+ const html = page.html ? fs.readFileSync(page.html, 'utf8') : '';
224
+ compiled = compileSomaBlocks({ html, uiYamlRaw: result.somaText });
225
+ } catch (error) {
226
+ console.error(`\n✗ ${page.base} 迁移产物编译不过:${errorMessage(error)}`);
227
+ failed += 1;
228
+ continue;
229
+ }
230
+ // 事件侧车顶层不是映射时迁移器报人工(下面整页拦下),这里不拿它去比
231
+ const flatEvent = files.eventYaml && typeof files.eventYaml === 'object' && !Array.isArray(files.eventYaml)
232
+ ? files.eventYaml
233
+ : {};
234
+ const issues = verifyEquivalence(
235
+ files.uiYaml,
236
+ { ui: compiled.ui, event: compiled.event },
237
+ flatEvent,
238
+ );
239
+ if (issues.length > 0) {
240
+ console.error(`\n✗ ${page.base} 迁移前后语义不等价(${issues.length} 条)——**不写盘**`);
241
+ for (const line of issues) console.error(` ${line}`);
242
+ console.error(' 问题:等价性是这次迁移唯一的安全网。不等价还写下去,');
243
+ console.error(' 存量页面会被静默改掉语义,而改动分散在几十个文件里。');
244
+ inequivalent += 1;
245
+ continue;
246
+ }
247
+
248
+ // 不静默丢弃:侧车里有迁移器没迁的内容 → 整页不写盘、一份侧车都不删。
249
+ // 只写 _ui.yaml、把那份侧车留下也不行:服务端见到残留侧车一律 422,
250
+ // 而这页已经是块声明、本命令不会再迁它第二次——人工清单就再也不会有人打印了。
251
+ const dispositions = result.sidecars ?? {};
252
+ const pending = Object.keys(dispositions).filter((kind) => dispositions[kind] === 'manual');
253
+ if (pending.length > 0) {
254
+ console.error(`\n✗ ${page.base} 侧车里有迁移器没迁的内容——这一页不写盘、侧车一份不删`);
255
+ for (const line of result.report.manual) console.error(` 需人工处理:${line}`);
256
+ console.error(` 涉及:${pending.map((kind) => shown(sidecarFile(kind))).join('、')}`);
257
+ console.error(' 把这些内容并进 _ui.yaml / HTML、从侧车里拿掉之后再跑一次。');
258
+ blocked += 1;
259
+ continue;
260
+ }
261
+
262
+ // 删的恰好是迁移器报"已完整迁入"的那几份——不多删(内容会丢),也不少删(服务端会 422)
263
+ const retired = Object.keys(dispositions)
264
+ .filter((kind) => dispositions[kind] === 'migrated')
265
+ .map(sidecarFile)
266
+ .filter(Boolean);
267
+
268
+ console.log(`\n✓ ${page.base}`);
269
+ // 不静默丢弃:迁移器报的"需人工处理"(与侧车无关的那些,如顶层变量名)原样打印,由人接手。
270
+ for (const line of result.report.manual) {
271
+ console.log(` 需人工处理:${line}`);
272
+ }
273
+
274
+ if (write) {
275
+ fs.writeFileSync(path.join(page.dir, `${page.base}_ui.yaml`), result.somaText, 'utf8');
276
+ // 侧车已退役:内容并进块声明之后,留着它服务端会 422,也更容易让人以为它还在生效。
277
+ for (const file of retired) fs.rmSync(file);
278
+ if (retired.length > 0) console.log(` 已删除侧车:${retired.map(shown).join('、')}`);
279
+ migrated += 1;
280
+ } else if (retired.length > 0) {
281
+ console.log(` --write 时删除侧车:${retired.map(shown).join('、')}`);
282
+ }
283
+ }
284
+
285
+ console.log(`\n[soma migrate] ${pages.length} 页:${failed} 页迁移失败(YAML / 迁移器 / 产物编译),`
286
+ + `${inequivalent} 页未通过等价校验,${blocked} 页有侧车需人工处理`
287
+ + (write ? `,${migrated} 页已写盘` : '(试跑,未写任何文件——加 --write 才落盘)'));
288
+ return {
289
+ exitCode: failed + inequivalent + blocked > 0 ? 1 : 0,
290
+ pages: pages.length,
291
+ failed,
292
+ inequivalent,
293
+ blocked,
294
+ migrated,
295
+ };
296
+ }
297
+
298
+ /**
299
+ * 命令行参数 → `{ dir, write, htmlDir }`(路径未解析)。
300
+ *
301
+ * `--html` 带一个取值,那个取值不是目标目录:曾经"第一个不以 -- 开头的参数就是目标",
302
+ * `soma migrate --html ../html ui` 会把 ../html 当成页面声明目录去迁。
303
+ */
304
+ function parseMigrateArgs(args) {
305
+ let dir;
306
+ let htmlDir;
307
+ let write = false;
308
+ for (let index = 0; index < args.length; index += 1) {
309
+ const item = args[index];
310
+ if (item === '--write') {
311
+ write = true;
312
+ } else if (item === '--html') {
313
+ const value = args[index + 1];
314
+ if (value !== undefined && !value.startsWith('--')) {
315
+ htmlDir = value;
316
+ index += 1;
317
+ }
318
+ } else if (item.startsWith('--html=')) {
319
+ htmlDir = item.slice('--html='.length);
320
+ } else if (!item.startsWith('--') && dir === undefined) {
321
+ dir = item;
322
+ }
323
+ }
324
+ return { dir, write, htmlDir: htmlDir || undefined };
325
+ }
326
+
327
+ /** `argv` 形如 `[node, 脚本, 'migrate', ...参数]`(soma-inline 与独立进程两种调法同形) */
328
+ function runMigrate(argv) {
329
+ const { dir, write, htmlDir: htmlArg } = parseMigrateArgs(argv.slice(3));
330
+ if (!dir) {
331
+ usage();
332
+ process.exit(1);
333
+ }
334
+ const cwd = process.env.SOMA_INVOKE_CWD || process.cwd();
335
+ const target = path.resolve(cwd, dir);
336
+ if (!fs.existsSync(target)) {
337
+ console.error(`[soma migrate] 目录不存在:${target}`);
338
+ process.exit(1);
339
+ }
340
+ // 不给 --html 时留空:由 locatePageFiles 按「同目录 → 标准布局 html/」的顺序找
341
+ const htmlDir = htmlArg ? path.resolve(cwd, htmlArg) : undefined;
342
+
343
+ const packageRoot = path.resolve(__dirname, '..');
344
+ const { migrateFlatToBlocks, verifyEquivalence } = loadBuildModule(packageRoot, 'blocks/migrate-flat');
345
+ const { compileSomaBlocks } = loadBuildModule(packageRoot, 'blocks/block-compile');
346
+
347
+ const outcome = migrateDirectory({
348
+ target,
349
+ htmlDir,
350
+ write,
351
+ modules: { migrateFlatToBlocks, verifyEquivalence, compileSomaBlocks },
352
+ });
353
+ process.exit(outcome.exitCode);
354
+ }
355
+
356
+ module.exports = { runMigrate, migrateDirectory, locatePageFiles, parseMigrateArgs };
357
+
358
+ // 发布入口(dist/cli/soma.js)以独立进程调本文件:`node migrate.cjs migrate <目录> ...`;
359
+ // soma-inline.cjs 则 require 后直接调 runMigrate。两种 argv 同形。
360
+ if (require.main === module) {
361
+ runMigrate(process.argv);
362
+ }
@@ -10,18 +10,39 @@
10
10
  // 运行时只剩读数据、写 DOM、diff——与原生代码要付的一样。
11
11
 
12
12
  import type { UiConfig } from '../../shared/types/ui-config.types';
13
+ import type { SomaDataObjectRelation } from '../../shared/types/data-config.types';
13
14
  import { buildHtmlAnchorIndex, type HtmlAnchorIndex } from './html-index';
14
15
  import { PAGE_BLOCK_ID, SomaBlockParseError, loadSomaFile } from './block-container';
15
16
  import { parsePageBlock } from '../../client/parser/blocks/page-parser';
16
- import { parseUseBlock, type DataObjectDecl, type UseBlockAst } from '../../client/parser/blocks/use-parser';
17
+ import {
18
+ parseUseBlock,
19
+ type DataObjectDecl,
20
+ type FieldDecl,
21
+ type UseBlockAst,
22
+ } from '../../client/parser/blocks/use-parser';
17
23
 
18
24
  export interface CompiledSomaBlocks {
19
25
  /** 平铺等价 UiConfig:直接交既有编译管线 */
20
26
  ui: UiConfig;
21
27
  /** 平铺等价事件声明(DOM 事件 + timers/triggers + 组件 emit 路由) */
22
28
  event: Record<string, unknown>;
23
- /** 数据对象声明(页面级 + 各块私有,已带全局身份) */
29
+ /**
30
+ * 数据对象声明——**核心层**,形状即数据对象层(`data-config-parser`)的输入:
31
+ * 页面级对象用声明名,各块私有对象用扁平名 `块id__名`。
32
+ */
24
33
  data: Record<string, unknown>;
34
+ /**
35
+ * 表层对象声明(REQ-014 §38.5 断线 ②):人写形态,**尚未展开**。
36
+ *
37
+ * 不在这里展开是有意的:展开点只准有一个
38
+ * (`build/ooui/semantic/normalize.ts`,§2.3 判据 3)。本模块住在
39
+ * `core/build/blocks/`,把展开器搬进来等于给它开第二个入口,
40
+ * 而两处对 `enum(a|b|c)` 的空格与转义处理必然分叉——表现是
41
+ * "同一份 YAML 在预览里三个候选、在发布产物里两个",两边各自都跑得出来。
42
+ *
43
+ * 展开与并入 `data` 由 `compilePageDeclaration` 做一次。没写就没有这个字段。
44
+ */
45
+ surface?: Record<string, unknown>;
25
46
  /** 各组件块的 AST(供生成器族与诊断消费) */
26
47
  blocks: ReadonlyMap<string, UseBlockAst>;
27
48
  htmlIndex: HtmlAnchorIndex;
@@ -79,6 +100,17 @@ export function compileSomaBlocks(input: CompileSomaBlocksInput): CompiledSomaBl
79
100
  data[name] = decl;
80
101
  }
81
102
 
103
+ // 数据表里每个名字的出处:块私有对象的扁平名与页面级对象落进同一张表、同一个 page.data,
104
+ // 撞名只能在合表这一刻拦——晚了就是后写的静默盖掉先写的。
105
+ // 表层 objects: 的名字也登记:它们在 compilePageDeclaration 展开后并进同一张表。
106
+ const dataOwners = new Map<string, string>();
107
+ for (const name of Object.keys(page.dataRaw ?? {})) {
108
+ dataOwners.set(name, 'page 块 data: 里的同名对象');
109
+ }
110
+ for (const name of Object.keys(page.surfaceRaw ?? {})) {
111
+ if (!dataOwners.has(name)) dataOwners.set(name, 'page 块 objects: 里的同名对象');
112
+ }
113
+
82
114
  const blocks = new Map<string, UseBlockAst>();
83
115
  for (const raw of rawBlocks) {
84
116
  if (raw.blockId === PAGE_BLOCK_ID) continue;
@@ -89,6 +121,7 @@ export function compileSomaBlocks(input: CompileSomaBlocksInput): CompiledSomaBl
89
121
  body: raw.body,
90
122
  ...(info?.component ? { htmlComponent: info.component } : {}),
91
123
  rowVars: rowVarsFor(raw.blockId, htmlIndex, ui),
124
+ inRowTemplate: info?.inRowTemplate === true,
92
125
  });
93
126
  blocks.set(raw.blockId, ast);
94
127
 
@@ -100,25 +133,120 @@ export function compileSomaBlocks(input: CompileSomaBlocksInput): CompiledSomaBl
100
133
  event[`${raw.blockId}.${emitName}`] = expr;
101
134
  }
102
135
 
103
- // 数据对象:块内私有对象已带全局身份
136
+ // 块私有数据对象:以扁平名 `块id__名` 进同一张数据表,形状换成数据对象层认的那一套
137
+ const flatNames = new Map(ast.dataObjects.map((object) => [object.localName, object.fullName]));
104
138
  for (const object of ast.dataObjects) {
105
- data[object.fullName] = {
106
- ...(object.from ? { from: object.from } : {}),
107
- ...(object.save ? { write: normalizeSave(object.save) } : {}),
108
- ...(object.refreshMs !== undefined ? { refreshMs: object.refreshMs } : {}),
109
- ...(object.reloadOn ? { reloadOn: object.reloadOn } : {}),
110
- ...(object.fields ? { fields: object.fields } : {}),
111
- };
139
+ const owner = dataOwners.get(object.fullName);
140
+ if (owner) {
141
+ throw new SomaBlockParseError(
142
+ `私有数据对象 "${object.localName}" 的全局名 "${object.fullName}" 与 ${owner} 撞名`
143
+ + '——两者会落到同一个 page.data 键上,后写的静默盖掉先写的;请给其中一方改名',
144
+ raw.blockId,
145
+ );
146
+ }
147
+ dataOwners.set(object.fullName, `块 "${raw.blockId}" 的私有对象 "${object.localName}"`);
148
+ data[object.fullName] = toDataObjectConfig(object, flatNames, raw.blockId);
112
149
  }
113
150
  }
114
151
 
115
- return { ui, event, data, blocks, htmlIndex };
152
+ return {
153
+ ui,
154
+ event,
155
+ data,
156
+ ...(page.surfaceRaw ? { surface: page.surfaceRaw } : {}),
157
+ blocks,
158
+ htmlIndex,
159
+ };
160
+ }
161
+
162
+ /**
163
+ * 块私有数据对象 → 数据对象层(`data-config-parser`)认的形状。逐项对位,不近似、不丢:
164
+ *
165
+ * | 块声明 | 数据对象层 |
166
+ * |---|---|
167
+ * | 对象键 `名` | `块id__名`(use-parser 已铸好,规则见 `blockDataObjectName`) |
168
+ * | `from: { api, params }` | `from: [{ api, params }]`(块里只有一个来源;params 已是 `$` 引用或字面量) |
169
+ * | `save` | `write`(见 normalizeSave) |
170
+ * | `fields.*.values` 映射 | `fields.*.options` 数组 `[{ key, label }]` |
171
+ * | `relations[].to` 指向本块对象 | 同一套扁平名(见 flattenRelationTargets) |
172
+ * | `roles`、字段的 name / type / permission / rules / modifies | 原样 |
173
+ *
174
+ * 没有对应物的写法(`refresh` / `reload_on` / `save.trigger` / 不带 message 的规则 /
175
+ * 行模板里的私有对象)在 use-parser 就被拒收了:走到这里的每个键,下游都有人读。
176
+ */
177
+ function toDataObjectConfig(
178
+ object: DataObjectDecl,
179
+ flatNames: ReadonlyMap<string, string>,
180
+ blockId: string,
181
+ ): Record<string, unknown> {
182
+ // 数据对象层的对象要么有 from、要么有 mock 样本;块声明没有 mock 位,
183
+ // 不写 from 的对象在合表后的那一遍解析里必然被拒——在这里就说清是哪个块的哪个对象
184
+ if (!object.from) {
185
+ throw new SomaBlockParseError(
186
+ `私有数据对象 "${object.localName}" 缺少 from`
187
+ + '——数据对象层的对象必须有取数来源(块声明没有 mock 样本位),请补 from: { api, params }',
188
+ blockId,
189
+ );
190
+ }
191
+ const params = Object.keys(object.from.params).length > 0 ? { params: object.from.params } : {};
192
+ return {
193
+ from: [{ api: object.from.api, ...params }],
194
+ ...(object.save ? { write: normalizeSave(object.save) } : {}),
195
+ ...(object.fields ? { fields: toDataFields(object.fields) } : {}),
196
+ // REQ-014 期 2'.1:对象级角色与关系必须一路带下去。
197
+ // use-parser 已经解析并校验了它们,这里不带 = 「解析了、引擎不消费」——
198
+ // 那正是 `save:` 归一之前踩过的坑(见下方 normalizeSave 的注释):
199
+ // 语法检查通过、声明看起来生效了,运行期没有任何东西读它。
200
+ ...(object.roles ? { roles: object.roles } : {}),
201
+ ...(object.relations
202
+ ? { relations: flattenRelationTargets(object.relations, flatNames) }
203
+ : {}),
204
+ };
205
+ }
206
+
207
+ /**
208
+ * 字段字典:块拼写 `values`(值 → 文案映射)编成数据对象层的 `options` 数组,
209
+ * 其余键两边同名原样。不编的话 `values` 在数据对象层是未知键,整张页过不了解析。
210
+ */
211
+ function toDataFields(fields: Readonly<Record<string, FieldDecl>>): Record<string, Record<string, unknown>> {
212
+ const result: Record<string, Record<string, unknown>> = {};
213
+ for (const [key, field] of Object.entries(fields)) {
214
+ const { values, ...rest } = field;
215
+ result[key] = {
216
+ ...rest,
217
+ ...(values
218
+ ? { options: Object.entries(values).map(([value, label]) => ({ key: value, label: String(label) })) }
219
+ : {}),
220
+ };
221
+ }
222
+ return result;
223
+ }
224
+
225
+ /**
226
+ * 块内关系目标 → 扁平名,与对象键**同一套换名**(`名` → `块id__名`)。
227
+ *
228
+ * 对象键已经换成扁平名,而 `relations[].to` 若还留着块内短名,合并后的数据表里就没有
229
+ * 它指的那个对象:轻则被判「未声明的数据对象」,重则页面级恰好有个同名对象,关系被静默
230
+ * 接到别人身上。use-parser 把 `to` 的存在性留给合并后的那一遍,前提正是这里把名字换对。
231
+ *
232
+ * 只换指向**本块自己声明的**对象的 `to`——块作用域的解析顺序本来就是「自有 data 优先」
233
+ * (`namespace.ts`)。其余名字(页面级对象、别的块的扁平名、写错的名字)原样留下,
234
+ * 交给合并后的存在性检查裁决,这里不猜。
235
+ */
236
+ function flattenRelationTargets(
237
+ relations: readonly SomaDataObjectRelation[],
238
+ flatNames: ReadonlyMap<string, string>,
239
+ ): SomaDataObjectRelation[] {
240
+ return relations.map((relation) => {
241
+ const flat = flatNames.get(relation.to);
242
+ return flat ? { ...relation, to: flat } : relation;
243
+ });
116
244
  }
117
245
 
118
246
  /**
119
247
  * 块声明 `save:` 归一为写通道 `write:`(REQ-010 F-38)。
120
248
  *
121
- * `save` 此前是「解析了、引擎不消费」的一条声明——语法检查通过、trigger 也校验了,
249
+ * `save` 此前是「解析了、引擎不消费」的一条声明——语法检查通过,
122
250
  * 但运行期没有任何东西读它。写了 `save` 的块,点了那个动作之后什么都不会发生,
123
251
  * 而且不报错。这是最坏的一类:声明看起来生效了。
124
252
  *
@@ -129,18 +257,16 @@ export function compileSomaBlocks(input: CompileSomaBlocksInput): CompiledSomaBl
129
257
  * | `api` / `method` | `update.api` / `update.method`(块的 save 语义就是回写既有记录) |
130
258
  * | `key` | `version`(乐观锁位) |
131
259
  * | `fields` | `only`(请求体白名单) |
132
- * | `trigger` | **暂留**:它是「哪个动作触发提交」,属动作编排(S4 AO),本次不落 |
133
260
  *
134
- * `trigger` 落不了的部分在这里保留原样而不是丢掉——丢掉的话,S4 接编排时
135
- * 已经没有地方能知道作者当初写的是哪个动作了。
261
+ * `trigger` 不在表里:写通道没有「哪个动作触发提交」这一环——提交由消费该对象的组件
262
+ * 经 data 端口 `submit(对象名)` 发起。它曾被原样塞进 `write.trigger`,而那是数据对象层
263
+ * 闭集外的键,整张页因此发布不了;现在它在 use-parser 就被拒收并指路。
136
264
  */
137
265
  function normalizeSave(save: NonNullable<DataObjectDecl['save']>): Record<string, unknown> {
138
266
  return {
139
267
  update: { api: save.api, method: save.method },
140
268
  ...(save.key !== undefined ? { version: save.key } : {}),
141
269
  ...(save.fields !== undefined ? { only: save.fields } : {}),
142
- // 触发动作:等 AO 动作编排(S4)接手,届时编译成一条 `do: DATA | commit` 步骤
143
- trigger: save.trigger,
144
270
  };
145
271
  }
146
272