soma-core 1.3.3 → 1.3.5

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 (112) hide show
  1. package/README.md +7 -6
  2. package/app/SomaPageClient.tsx +2 -72
  3. package/app/soma/page/route.ts +17 -2
  4. package/bin/soma-lsp.cjs +1 -4
  5. package/core/build/compiler/full-manifest-builder.ts +17 -26
  6. package/core/build/compiler/html-include-expander.ts +56 -0
  7. package/core/build/compiler/page-assets.ts +26 -0
  8. package/core/build/compiler/page-declaration-compiler.ts +85 -0
  9. package/core/build/compiler/rollup-plugin-soma.ts +4 -19
  10. package/core/build/compiler/route-builder.ts +0 -2
  11. package/core/build/compiler/rspack-plugin-soma.js +1 -10
  12. package/core/build/compiler/soma-manifest-webpack-plugin.js +54 -13
  13. package/core/build/compiler/soma-precompile.js +74 -0
  14. package/core/build/compiler/soma-precompile.ts +13 -0
  15. package/core/build/compiler/soma-rspack-yaml-loader.js +5 -11
  16. package/core/build/compiler/soma-webpack-loader.js +6 -21
  17. package/core/build/compiler/vite-plugin-soma.ts +9 -31
  18. package/core/build/component/pack-from-dir.ts +58 -0
  19. package/core/build/component/package-loader.ts +158 -12
  20. package/core/build/eject/plan-eject.ts +15 -21
  21. package/core/build/lsp/cross-file-diagnostics.cjs +82 -113
  22. package/core/build/lsp/extra-completion.cjs +14 -8
  23. package/core/build/lsp/lsp-navigation.cjs +50 -43
  24. package/core/build/lsp/soma-declaration.cjs +85 -0
  25. package/core/build/lsp/ui-yaml-completion.cjs +98 -104
  26. package/core/build/v2/block-compile.ts +200 -0
  27. package/core/build/v2/block-loader.ts +33 -0
  28. package/core/build/v2/html-index.ts +120 -0
  29. package/core/build/v2/migrate-v1.ts +370 -0
  30. package/core/build/v2/soma-file-loader.ts +216 -0
  31. package/core/client/component/ai-catalog.ts +15 -0
  32. package/core/client/component/component-pack.ts +205 -31
  33. package/core/client/component/contract-compat.ts +132 -0
  34. package/core/client/component/example-v2.ts +132 -0
  35. package/core/client/engine/dom-renderer.ts +14 -8
  36. package/core/client/engine/reactive-proxy.ts +8 -7
  37. package/core/client/engine/soma-bootstrap.ts +23 -5
  38. package/core/client/parser/v2/namespace.ts +182 -0
  39. package/core/client/parser/v2/page-parser.ts +359 -0
  40. package/core/client/parser/v2/use-parser.ts +412 -0
  41. package/core/client/parser/value-lang.ts +340 -0
  42. package/core/client/pipes/pipe-registry.ts +1 -1
  43. package/core/client/registry/declaration-renderer.ts +17 -15
  44. package/core/client/registry/page-lifecycle.ts +1 -1
  45. package/core/client/security/attribute-presence.ts +16 -1
  46. package/core/client/theme/harmony.ts +307 -0
  47. package/core/client/theme/scene-tokens.ts +134 -0
  48. package/core/client/theme/theme-axes.ts +228 -0
  49. package/core/client/theme/theme-engine.ts +333 -73
  50. package/core/client/theme/tone-solver.ts +118 -0
  51. package/core/index.ts +74 -2
  52. package/core/server/host/published-page-assets.ts +35 -0
  53. package/core/server/host/server-page-assets.ts +33 -16
  54. package/core/server/host/soma-page-compile.ts +33 -0
  55. package/core/server/index.ts +15 -0
  56. package/core/server/registry/declaration-precompiler.ts +24 -54
  57. package/core/server/registry/page-registry-store.ts +39 -10
  58. package/core/server/registry/services/pages/Get.ts +19 -9
  59. package/core/server/registry/validation/compile-gate.ts +14 -31
  60. package/core/server/registry/validation/cross-check.ts +7 -17
  61. package/core/server/registry/validation/declaration-safety-scan.ts +2 -2
  62. package/core/shared/types/component-contract.types.ts +10 -0
  63. package/dist/core/index.cjs +2144 -155
  64. package/dist/types/build/compiler/full-manifest-builder.d.ts +4 -4
  65. package/dist/types/build/compiler/html-include-expander.d.ts +19 -0
  66. package/dist/types/build/compiler/page-assets.d.ts +3 -0
  67. package/dist/types/build/compiler/page-declaration-compiler.d.ts +33 -0
  68. package/dist/types/build/compiler/rollup-plugin-soma.d.ts +0 -3
  69. package/dist/types/build/compiler/route-builder.d.ts +0 -1
  70. package/dist/types/build/compiler/soma-precompile.d.ts +8 -0
  71. package/dist/types/build/compiler/vite-plugin-soma.d.ts +2 -10
  72. package/dist/types/build/component/pack-from-dir.d.ts +17 -0
  73. package/dist/types/build/component/package-loader.d.ts +33 -2
  74. package/dist/types/build/v2/block-compile.d.ts +28 -0
  75. package/dist/types/build/v2/block-loader.d.ts +9 -0
  76. package/dist/types/build/v2/html-index.d.ts +37 -0
  77. package/dist/types/build/v2/migrate-v1.d.ts +32 -0
  78. package/dist/types/build/v2/soma-file-loader.d.ts +45 -0
  79. package/dist/types/client/component/component-pack.d.ts +23 -3
  80. package/dist/types/client/component/contract-compat.d.ts +16 -0
  81. package/dist/types/client/component/example-v2.d.ts +9 -0
  82. package/dist/types/client/engine/dom-renderer.d.ts +2 -0
  83. package/dist/types/client/engine/soma-bootstrap.d.ts +3 -1
  84. package/dist/types/client/parser/v2/namespace.d.ts +52 -0
  85. package/dist/types/client/parser/v2/page-parser.d.ts +21 -0
  86. package/dist/types/client/parser/v2/use-parser.d.ts +72 -0
  87. package/dist/types/client/parser/value-lang.d.ts +63 -0
  88. package/dist/types/client/registry/declaration-renderer.d.ts +1 -2
  89. package/dist/types/client/theme/harmony.d.ts +77 -0
  90. package/dist/types/client/theme/scene-tokens.d.ts +25 -0
  91. package/dist/types/client/theme/theme-axes.d.ts +81 -0
  92. package/dist/types/client/theme/theme-engine.d.ts +29 -1
  93. package/dist/types/client/theme/tone-solver.d.ts +47 -0
  94. package/dist/types/index.d.ts +13 -2
  95. package/dist/types/server/host/published-page-assets.d.ts +19 -0
  96. package/dist/types/server/host/server-page-assets.d.ts +1 -4
  97. package/dist/types/server/host/soma-page-compile.d.ts +7 -0
  98. package/dist/types/server/index.d.ts +3 -1
  99. package/dist/types/server/registry/declaration-precompiler.d.ts +3 -3
  100. package/dist/types/server/registry/page-registry-store.d.ts +5 -5
  101. package/dist/types/server/registry/validation/compile-gate.d.ts +2 -0
  102. package/dist/types/server/registry/validation/cross-check.d.ts +4 -4
  103. package/dist/types/shared/types/component-contract.types.d.ts +10 -0
  104. package/editor/vscode/package.json +1 -24
  105. package/global.d.ts +1 -11
  106. package/next.config.js +32 -50
  107. package/package.json +3 -2
  108. package/tailwind.config.ts +0 -1
  109. package/tsconfig.json +20 -7
  110. package/core/build/lsp/event-yaml-completion.cjs +0 -106
  111. package/core/client/host-bridge/empty-host/data/README.md +0 -17
  112. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +0 -30
@@ -0,0 +1,370 @@
1
+ // v1 → v2 迁移器(REQ-005 F8.3)。
2
+ //
3
+ // 迁移必须是**机械的**:逐条封闭变换规则,不含判断、不猜意图。
4
+ // 因为迁移器要跑在存量页面上,一次"聪明的推断"就是一次静默改语义。
5
+ //
6
+ // 幂等性与语义等价是两条硬要求:
7
+ // 幂等——迁移已迁过的文件产物不变(否则批量跑两次就出事);
8
+ // 等价——迁移前后作用域清单树一致(由 verifyEquivalence 比对,不靠肉眼)。
9
+ //
10
+ // 不迁移的部分照直报告,不静默丢弃:_style.yaml 的 transitions 需要人工并进
11
+ // HTML class,迁移器只给出清单。
12
+
13
+ import type { BindDeclaration, UiConfig } from '../../shared/types/ui-config.types';
14
+
15
+ export interface V1PageFiles {
16
+ uiYaml: Record<string, unknown>;
17
+ eventYaml?: Record<string, unknown>;
18
+ styleYaml?: Record<string, unknown>;
19
+ dataYaml?: Record<string, unknown>;
20
+ }
21
+
22
+ export interface MigrationReport {
23
+ /** 逐条变换记录(可读,用于 review 迁移结果) */
24
+ changes: string[];
25
+ /** 需要人工处理的残留(迁移器不猜) */
26
+ manual: string[];
27
+ }
28
+
29
+ export interface MigrationResult {
30
+ /** v2 文本(含 `{{` 开关) */
31
+ somaText: string;
32
+ /** 结构形态(便于测试与等价比对) */
33
+ blocks: Record<string, unknown>;
34
+ report: MigrationReport;
35
+ }
36
+
37
+ /** 迁移一页 v1 声明为 v2 块结构 */
38
+ export function migrateV1(files: V1PageFiles): MigrationResult {
39
+ const report: MigrationReport = { changes: [], manual: [] };
40
+ const ui = files.uiYaml as unknown as UiConfig;
41
+
42
+ if (!ui?.bind?.obj) {
43
+ throw new Error('[soma-core][引擎] v1 _ui.yaml 缺少 bind.obj,无法迁移');
44
+ }
45
+
46
+ const pageBlock: Record<string, unknown> = { domain: ui.bind.obj };
47
+ report.changes.push(`bind.obj → domain: ${ui.bind.obj}`);
48
+ if (ui.initProps && Object.keys(ui.initProps).length > 0) {
49
+ pageBlock.initProps = ui.initProps;
50
+ report.changes.push(`initProps(${Object.keys(ui.initProps).length} 项)→ page.initProps`);
51
+ }
52
+ if (ui.bind.var && ui.bind.var !== 'page') {
53
+ report.manual.push(
54
+ `顶层变量名是 "${ui.bind.var}" 而非 page——v2 固定为 page,`
55
+ + '请全局替换该页所有引用后再迁移',
56
+ );
57
+ }
58
+
59
+ // watch:v1 onChange → v2 watch 段
60
+ if (ui.bind.onChange?.length) {
61
+ pageBlock.watch = ui.bind.onChange.map((rule) => ({
62
+ path: rule.condition,
63
+ call: rule.callback,
64
+ ...(rule.debounce !== undefined ? { debounce: rule.debounce } : {}),
65
+ ...(rule.refresh !== undefined ? { refresh: rule.refresh } : {}),
66
+ }));
67
+ report.changes.push(`bind.onChange(${ui.bind.onChange.length} 条)→ watch 段`);
68
+ }
69
+
70
+ // show:平铺 + 实例分离
71
+ const pageUi: Record<string, unknown> = {};
72
+ const componentBlocks: Record<string, Record<string, unknown>> = {};
73
+ const localeNames: string[] = [];
74
+
75
+ flattenShow(ui.show ?? {}, pageUi, componentBlocks, localeNames, report);
76
+
77
+ if (localeNames.length > 0) {
78
+ pageBlock.locale = localeNames;
79
+ for (const name of localeNames) delete pageUi[name];
80
+ report.changes.push(`${localeNames.length} 条镜像文案 → locale 名单`);
81
+ }
82
+ if (Object.keys(pageUi).length > 0) pageBlock.ui = pageUi;
83
+
84
+ // 事件:DOM 事件留 page.event.on;emit 路由迁进对应组件块
85
+ if (files.eventYaml) {
86
+ migrateEvents(files.eventYaml, pageBlock, componentBlocks, report);
87
+ }
88
+
89
+ if (files.dataYaml && Object.keys(files.dataYaml).length > 0) {
90
+ const data = files.dataYaml.data;
91
+ if (data === undefined || data === null || typeof data !== 'object' || Array.isArray(data)) {
92
+ report.manual.push('_data.yaml 必须含 data 映射;未自动并入 page.data,避免生成不可运行的声明');
93
+ } else {
94
+ pageBlock.data = data;
95
+ report.changes.push(`data(${Object.keys(data as Record<string, unknown>).length} 个对象)→ page.data`);
96
+ }
97
+ }
98
+
99
+ // 样式:唯一声明不再接受独立样式侧车;迁移时必须显式并入页面结构。
100
+ if (files.styleYaml) {
101
+ reportStyleMigration(files.styleYaml, report);
102
+ }
103
+
104
+ const blocks: Record<string, unknown> = { page: pageBlock, ...componentBlocks };
105
+ return { somaText: renderSoma(blocks), blocks, report };
106
+ }
107
+
108
+ /** show 树 → 平铺 page.ui + 组件块(实例分离是 v2 的核心形状变化) */
109
+ function flattenShow(
110
+ show: Record<string, unknown>,
111
+ pageUi: Record<string, unknown>,
112
+ componentBlocks: Record<string, Record<string, unknown>>,
113
+ localeNames: string[],
114
+ report: MigrationReport,
115
+ prefix = '',
116
+ ): void {
117
+ for (const [key, value] of Object.entries(show)) {
118
+ if (typeof value === 'string') {
119
+ // 镜像文案:锚点名 = 词典键 → 收进 locale 名单
120
+ if (value === `page._locale.${key}`) localeNames.push(key);
121
+ pageUi[key] = value;
122
+ continue;
123
+ }
124
+ if (value === null || typeof value !== 'object') continue;
125
+
126
+ const node = value as Record<string, unknown>;
127
+
128
+ // 组件实例:props 迁进独立块
129
+ if (node.props !== undefined) {
130
+ const block: Record<string, unknown> = { ui: node.props };
131
+ if (node.when) block.when = node.when;
132
+ componentBlocks[key] = block;
133
+ report.changes.push(`实例 ${key} 的 props → 顶层组件块`);
134
+ // 实例节点下的 show 是插槽内容,归页面作用域,平铺上来
135
+ if (node.show) {
136
+ flattenShow(node.show as Record<string, unknown>, pageUi, componentBlocks, localeNames, report, prefix);
137
+ }
138
+ continue;
139
+ }
140
+
141
+ // 列表作用域:bind + show → each 块
142
+ if (node.bind !== undefined && node.show !== undefined) {
143
+ const bind = node.bind as BindDeclaration;
144
+ const eachBlock: Record<string, unknown> = {
145
+ each: `${bind.obj} as ${bind.var}${bind.role_by ? ` by ${bind.role_by}` : ''}`,
146
+ };
147
+ const childUi: Record<string, unknown> = {};
148
+ flattenShow(node.show as Record<string, unknown>, childUi, componentBlocks, [], report, `${key}.`);
149
+ Object.assign(eachBlock, childUi);
150
+ pageUi[key] = eachBlock;
151
+ report.changes.push(`列表 ${key} 的 bind/show → each 块`);
152
+ continue;
153
+ }
154
+
155
+ // 扩展绑定:when/model/class 拆成平铺后缀键
156
+ for (const suffix of ['when', 'model', 'class'] as const) {
157
+ if (node[suffix] !== undefined) {
158
+ pageUi[`${key}.${suffix}`] = node[suffix];
159
+ }
160
+ }
161
+ if (node.text !== undefined) pageUi[key] = node.text;
162
+ if (node.show !== undefined) {
163
+ flattenShow(node.show as Record<string, unknown>, pageUi, componentBlocks, localeNames, report, prefix);
164
+ }
165
+ }
166
+ }
167
+
168
+ function migrateEvents(
169
+ eventYaml: Record<string, unknown>,
170
+ pageBlock: Record<string, unknown>,
171
+ componentBlocks: Record<string, Record<string, unknown>>,
172
+ report: MigrationReport,
173
+ ): void {
174
+ const on: Record<string, unknown> = {};
175
+ const extra: Record<string, unknown> = {};
176
+
177
+ /**
178
+ * 列表作用域在 v1 事件里是**嵌套**的(外层键 = 列表锚点)。
179
+ * v2 保持同形——曾经把它拍平成 `列表.锚点.事件` 三段,
180
+ * 解析器直接拒收(DOM 事件白名单只认两段),既有 Host 实迁时当场暴露。
181
+ * 嵌套照搬,只把其中的 emit 抽走。
182
+ */
183
+ const walk = (node: Record<string, unknown>, target: Record<string, unknown>): void => {
184
+ for (const [key, value] of Object.entries(node)) {
185
+ if (key === 'timers' || key === 'triggers') {
186
+ extra[key] = value;
187
+ continue;
188
+ }
189
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
190
+ const childTarget: Record<string, unknown> = {};
191
+ walk(value as Record<string, unknown>, childTarget);
192
+ if (Object.keys(childTarget).length > 0) target[key] = childTarget;
193
+ continue;
194
+ }
195
+
196
+ const [anchor, event] = key.split('.');
197
+ const block = componentBlocks[anchor];
198
+ // 组件实例的事件一律是契约 emit;`change` 等名称也不能按 DOM 事件留在 page,
199
+ // 否则唯一声明解析器会明确拒绝并导致迁移结果不可编译。
200
+ if (block && event) {
201
+ const eventSection = (block.event as Record<string, unknown>) ?? {};
202
+ const routes = (eventSection.on as Record<string, unknown>) ?? {};
203
+ routes[event] = value;
204
+ eventSection.on = routes;
205
+ block.event = eventSection;
206
+ report.changes.push(`emit ${key} → 组件块 ${anchor} 的 event.on`);
207
+ continue;
208
+ }
209
+ target[key] = value;
210
+ }
211
+ };
212
+ walk(eventYaml, on);
213
+
214
+ if (Object.keys(on).length > 0 || Object.keys(extra).length > 0) {
215
+ pageBlock.event = {
216
+ ...(Object.keys(on).length > 0 ? { on } : {}),
217
+ ...extra,
218
+ };
219
+ report.changes.push('DOM 事件 → page 块 event.on');
220
+ }
221
+ }
222
+
223
+ function reportStyleMigration(styleYaml: Record<string, unknown>, report: MigrationReport): void {
224
+ const base = styleYaml.base as Record<string, unknown> | undefined;
225
+ const states = styleYaml.states as Record<string, unknown> | undefined;
226
+ const transitions = styleYaml.transitions as Record<string, unknown> | undefined;
227
+
228
+ if (base && Object.keys(base).length > 0) {
229
+ report.manual.push(
230
+ `_style.yaml base(${Object.keys(base).length} 项):类名并进 HTML 的 class 属性`
231
+ + `(锚点:${Object.keys(base).join('、')})`,
232
+ );
233
+ }
234
+ if (transitions && Object.keys(transitions).length > 0) {
235
+ report.manual.push(
236
+ `_style.yaml transitions(${Object.keys(transitions).length} 项):`
237
+ + '改写为 HTML class 的 Tailwind 变体(hover: / focus:)',
238
+ );
239
+ }
240
+ if (states && Object.keys(states).length > 0) {
241
+ report.manual.push(
242
+ `_style.yaml states(${Object.keys(states).length} 项):改写为 ui 段的 锚点.class 条件映射`,
243
+ );
244
+ }
245
+ }
246
+
247
+ /** 块结构 → v2 文本(YAML 风格,两空格缩进) */
248
+ function renderSoma(blocks: Record<string, unknown>): string {
249
+ const lines: string[] = ['{{'];
250
+ for (const [blockId, body] of Object.entries(blocks)) {
251
+ lines.push(`${blockId}:`);
252
+ lines.push(...renderValue(body, 1));
253
+ lines.push('');
254
+ }
255
+ while (lines[lines.length - 1] === '') lines.pop();
256
+ lines.push('}}');
257
+ return lines.join('\n');
258
+ }
259
+
260
+ function renderValue(value: unknown, depth: number): string[] {
261
+ const pad = ' '.repeat(depth);
262
+ if (value === null || value === undefined) return [];
263
+ if (Array.isArray(value)) {
264
+ return value.map((item) => {
265
+ if (item !== null && typeof item === 'object') {
266
+ return `${pad}- ${JSON.stringify(item)}`;
267
+ }
268
+ return `${pad}- ${formatScalar(item)}`;
269
+ });
270
+ }
271
+ if (typeof value === 'object') {
272
+ const lines: string[] = [];
273
+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
274
+ if (child !== null && typeof child === 'object') {
275
+ lines.push(`${pad}${quoteKey(key)}:`);
276
+ lines.push(...renderValue(child, depth + 1));
277
+ } else {
278
+ lines.push(`${pad}${quoteKey(key)}: ${formatScalar(child)}`);
279
+ }
280
+ }
281
+ return lines;
282
+ }
283
+ return [`${pad}${formatScalar(value)}`];
284
+ }
285
+
286
+ function quoteKey(key: string): string {
287
+ return /[:@#]/.test(key) ? `"${key}"` : key;
288
+ }
289
+
290
+ /** 标量格式化:含特殊字符或以 ! 开头必须加引号(YAML 引号纪律) */
291
+ function formatScalar(value: unknown): string {
292
+ if (typeof value !== 'string') return String(value);
293
+ if (/[:,#%¥]|^[!@]|\s\|\s/.test(value)) return JSON.stringify(value);
294
+ return value;
295
+ }
296
+
297
+ /**
298
+ * 语义等价比对:迁移前后的作用域清单树必须一致。
299
+ *
300
+ * 比对的是**结构**而非文本——文本必然不同(那正是迁移的目的),
301
+ * 但绑定关系、作用域层级、事件路由必须逐条对得上。
302
+ */
303
+ export function verifyEquivalence(
304
+ v1Ui: UiConfig,
305
+ v2Compiled: { ui: UiConfig; event: Record<string, unknown> },
306
+ v1Event: Record<string, unknown> = {},
307
+ ): string[] {
308
+ const issues: string[] = [];
309
+
310
+ if (v1Ui.bind.obj !== v2Compiled.ui.bind.obj) {
311
+ issues.push(`domain 不一致: ${v1Ui.bind.obj} → ${v2Compiled.ui.bind.obj}`);
312
+ }
313
+
314
+ const v1Paths = collectBindings(v1Ui.show ?? {}, '');
315
+ const v2Paths = collectBindings(v2Compiled.ui.show ?? {}, '');
316
+ for (const [anchor, expr] of v1Paths) {
317
+ const after = v2Paths.get(anchor);
318
+ if (after === undefined) issues.push(`绑定丢失: ${anchor}`);
319
+ else if (after !== expr) issues.push(`绑定变化: ${anchor} "${expr}" → "${after}"`);
320
+ }
321
+
322
+ // 两侧必须同法拍平:v2 保留列表作用域嵌套,直接比顶层键会把嵌套项误判成丢失
323
+ const v1EventKeys = collectEventKeys(v1Event, '');
324
+ const v2EventKeys = new Set(collectEventKeys(v2Compiled.event, ''));
325
+ for (const key of v1EventKeys) {
326
+ if (!v2EventKeys.has(key)) issues.push(`事件丢失: ${key}`);
327
+ }
328
+
329
+ return issues;
330
+ }
331
+
332
+ function collectBindings(show: Record<string, unknown>, prefix: string): Map<string, string> {
333
+ const out = new Map<string, string>();
334
+ for (const [key, value] of Object.entries(show)) {
335
+ const path = `${prefix}${key}`;
336
+ if (typeof value === 'string') {
337
+ out.set(path, value);
338
+ continue;
339
+ }
340
+ if (value === null || typeof value !== 'object') continue;
341
+ const node = value as Record<string, unknown>;
342
+ if (typeof node.text === 'string') out.set(path, node.text);
343
+ if (typeof node.model === 'string') out.set(`${path}.model`, node.model);
344
+ if (typeof node.when === 'string') out.set(`${path}.when`, node.when);
345
+ if (node.props) {
346
+ for (const [propKey, propValue] of Object.entries(node.props as Record<string, unknown>)) {
347
+ if (typeof propValue === 'string') out.set(`${path}.props.${propKey}`, propValue);
348
+ }
349
+ }
350
+ if (node.show) {
351
+ for (const [childKey, childValue] of collectBindings(node.show as Record<string, unknown>, '')) {
352
+ out.set(childKey, childValue);
353
+ }
354
+ }
355
+ }
356
+ return out;
357
+ }
358
+
359
+ function collectEventKeys(node: Record<string, unknown>, prefix: string): string[] {
360
+ const keys: string[] = [];
361
+ for (const [key, value] of Object.entries(node)) {
362
+ if (key === 'timers' || key === 'triggers') continue;
363
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
364
+ keys.push(...collectEventKeys(value as Record<string, unknown>, `${prefix}${key}.`));
365
+ continue;
366
+ }
367
+ keys.push(`${prefix}${key}`);
368
+ }
369
+ return keys;
370
+ }
@@ -0,0 +1,216 @@
1
+ // v2 容器 · 开关探测与块装载(REQ-005 F1.1 / F1.2)。
2
+ //
3
+ // 容器形态(规格书 §1):`_ui.yaml` 首行 `{{`、末行 `}}` 是 **v2 开关**,
4
+ // 开关之内是纯 YAML 的块集合(顶层键 = 块 id)。
5
+ //
6
+ // 三条设计后果,都是刻意的:
7
+ // ① 不新增文件类型——四件套存储、注册中心四道闸门、eject 全部零改动;
8
+ // ② 开关内是合法 YAML——编辑器/格式化/LSP/AI 先验零成本兑现,
9
+ // 所以这里用标准 YAML 装载,不写自造容器解析器;
10
+ // ③ 版本探测只看首个非注释行——比嗅探文件内容结构干净得多。
11
+ //
12
+ // 块 id 的合法性以 HTML 为源(见 html-index):写了一个 HTML 里不存在的实例锚点,
13
+ // 编译期就拦住——否则运行时表现为"某块声明永远不生效",静默且难查。
14
+
15
+ import yaml from 'js-yaml';
16
+ import type { HtmlAnchorIndex } from './html-index';
17
+
18
+ export class SomaV2ParseError extends Error {
19
+ constructor(
20
+ message: string,
21
+ readonly blockId?: string,
22
+ readonly line?: number,
23
+ ) {
24
+ const where = blockId ? `(块: ${blockId}${line ? `,第 ${line} 行` : ''})` : '';
25
+ super(`[soma-core][引擎] ${message}${where}`);
26
+ this.name = 'SomaV2ParseError';
27
+ }
28
+ }
29
+
30
+ /** 页面壳块的固定 id */
31
+ export const PAGE_BLOCK_ID = 'page';
32
+
33
+ export interface RawBlock {
34
+ blockId: string;
35
+ /** 块体(YAML 装载后的值;页面壳与组件块各自的 schema 由后续 parser 校验) */
36
+ body: Record<string, unknown>;
37
+ /** 块在 `_ui.yaml` 中的起始行(1 基,含开关行偏移) */
38
+ line: number;
39
+ /** 来源:内联块或外置文件 */
40
+ source: 'inline' | 'external';
41
+ }
42
+
43
+ export interface SomaFileLoadInput {
44
+ /** `_ui.yaml` 原文(含首尾开关行) */
45
+ uiYamlRaw: string;
46
+ /** HTML 锚点索引:块 id 合法性以它为源 */
47
+ htmlIndex: HtmlAnchorIndex;
48
+ /** 外置块文件:锚点名 → 块体原文(由 block-loader 提供) */
49
+ externalBlocks?: ReadonlyMap<string, string>;
50
+ }
51
+
52
+ /** 剥掉开关行,返回内层 YAML 与它在原文中的行偏移 */
53
+ function stripSwitch(uiYamlRaw: string): { inner: string; offset: number } {
54
+ const lines = uiYamlRaw.split('\n');
55
+ let openIndex = -1;
56
+ for (let i = 0; i < lines.length; i += 1) {
57
+ const text = lines[i].trim();
58
+ if (text === '' || text.startsWith('#')) continue;
59
+ if (text !== '{{') {
60
+ throw new SomaV2ParseError('v2 声明必须以 `{{` 开关行开头');
61
+ }
62
+ openIndex = i;
63
+ break;
64
+ }
65
+ if (openIndex === -1) {
66
+ throw new SomaV2ParseError('文件为空或只有注释,找不到 `{{` 开关行');
67
+ }
68
+
69
+ let closeIndex = -1;
70
+ for (let i = lines.length - 1; i > openIndex; i -= 1) {
71
+ const text = lines[i].trim();
72
+ if (text === '') continue;
73
+ if (text !== '}}') {
74
+ throw new SomaV2ParseError('v2 声明必须以 `}}` 收口行结尾(开关成对,整文件一对)');
75
+ }
76
+ closeIndex = i;
77
+ break;
78
+ }
79
+ if (closeIndex === -1) {
80
+ throw new SomaV2ParseError('`{{` 开关未闭合——缺少 `}}` 收口行');
81
+ }
82
+
83
+ return {
84
+ inner: lines.slice(openIndex + 1, closeIndex).join('\n'),
85
+ offset: openIndex + 1,
86
+ };
87
+ }
88
+
89
+ interface SomaV2Container {
90
+ doc: Record<string, unknown>;
91
+ inner: string;
92
+ offset: number;
93
+ }
94
+
95
+ /**
96
+ * 只校验 v2 单文件容器本身,不依赖 HTML 锚点。
97
+ *
98
+ * Bundler 的单文件 loader 拿不到同页 HTML,只能在这里确认开关成对、内层 YAML
99
+ * 可解析且顶层是块映射;块 id 与 HTML 的对账仍由页面级 compileSomaV2 完成。
100
+ */
101
+ export function parseSomaV2Container(uiYamlRaw: string): SomaV2Container {
102
+ const { inner, offset } = stripSwitch(uiYamlRaw);
103
+
104
+ let doc: unknown;
105
+ try {
106
+ doc = yaml.load(inner);
107
+ } catch (error) {
108
+ throw new SomaV2ParseError(`YAML 解析失败: ${(error as Error).message}`);
109
+ }
110
+ if (doc === null || doc === undefined) {
111
+ return { doc: {}, inner, offset };
112
+ }
113
+ if (typeof doc !== 'object' || Array.isArray(doc)) {
114
+ throw new SomaV2ParseError('开关内必须是块映射(顶层键 = 块 id)');
115
+ }
116
+
117
+ for (const [blockId, body] of Object.entries(doc as Record<string, unknown>)) {
118
+ if (body === null || body === undefined) {
119
+ throw new SomaV2ParseError('块体为空——不需要声明的组件请直接删掉这个块', blockId);
120
+ }
121
+ if (typeof body !== 'object' || Array.isArray(body)) {
122
+ throw new SomaV2ParseError('块体必须是映射(ui/data/event 三段)', blockId);
123
+ }
124
+ }
125
+
126
+ return { doc: doc as Record<string, unknown>, inner, offset };
127
+ }
128
+
129
+ /**
130
+ * 装载 v2 声明文件:开关剥离 → YAML 装载 → 块 id 校验 → 外置块合流。
131
+ *
132
+ * 每条校验都对应一种"静默失效":写了不存在的锚点、同一实例声明两遍、
133
+ * 块挂在普通锚点上——不拦的话都表现为"这段声明没生效",而不报错。
134
+ */
135
+ export function loadSomaFile(input: SomaFileLoadInput): RawBlock[] {
136
+ const { doc, inner, offset } = parseSomaV2Container(input.uiYamlRaw);
137
+ if (Object.keys(doc).length === 0) return [];
138
+
139
+ const innerLines = inner.split('\n');
140
+ const lineOfKey = (key: string): number => {
141
+ const index = innerLines.findIndex((line) => line.startsWith(`${key}:`));
142
+ return index === -1 ? offset : offset + index + 1;
143
+ };
144
+
145
+ const blocks: RawBlock[] = [];
146
+ const seen = new Set<string>();
147
+
148
+ for (const [blockId, body] of Object.entries(doc as Record<string, unknown>)) {
149
+ const line = lineOfKey(blockId);
150
+ assertBlockId(blockId, input.htmlIndex, line);
151
+ if (seen.has(blockId)) {
152
+ throw new SomaV2ParseError(`块 "${blockId}" 重复声明`, blockId, line);
153
+ }
154
+ if (body === null || body === undefined) {
155
+ throw new SomaV2ParseError('块体为空——不需要声明的组件请直接删掉这个块', blockId, line);
156
+ }
157
+ if (typeof body !== 'object' || Array.isArray(body)) {
158
+ throw new SomaV2ParseError('块体必须是映射(ui/data/event 三段)', blockId, line);
159
+ }
160
+ seen.add(blockId);
161
+ blocks.push({ blockId, body: body as Record<string, unknown>, line, source: 'inline' });
162
+ }
163
+
164
+ // 外置块合流:同锚点内联与外置并存 = 一个事实两处,必须拦
165
+ for (const [blockId, raw] of input.externalBlocks ?? new Map()) {
166
+ assertBlockId(blockId, input.htmlIndex, 0);
167
+ if (seen.has(blockId)) {
168
+ throw new SomaV2ParseError(
169
+ `块 "${blockId}" 同时存在于 _ui.yaml 与 blocks/${blockId}.yaml——一个实例只能有一个声明处`,
170
+ blockId,
171
+ );
172
+ }
173
+ let body: unknown;
174
+ try {
175
+ body = yaml.load(raw);
176
+ } catch (error) {
177
+ throw new SomaV2ParseError(
178
+ `外置块 blocks/${blockId}.yaml 解析失败: ${(error as Error).message}`,
179
+ blockId,
180
+ );
181
+ }
182
+ if (body === null || body === undefined) {
183
+ throw new SomaV2ParseError(`外置块 blocks/${blockId}.yaml 为空`, blockId);
184
+ }
185
+ if (typeof body !== 'object' || Array.isArray(body)) {
186
+ throw new SomaV2ParseError(`外置块 blocks/${blockId}.yaml 必须是映射`, blockId);
187
+ }
188
+ seen.add(blockId);
189
+ blocks.push({ blockId, body: body as Record<string, unknown>, line: 1, source: 'external' });
190
+ }
191
+
192
+ return blocks;
193
+ }
194
+
195
+ function assertBlockId(blockId: string, htmlIndex: HtmlAnchorIndex, line: number): void {
196
+ if (blockId === PAGE_BLOCK_ID) return;
197
+
198
+ if (htmlIndex.instances.has(blockId)) return;
199
+
200
+ // 分两种错法给不同指引——"锚点不存在"与"锚点不是组件实例"是两个问题
201
+ if (htmlIndex.anchors.has(blockId)) {
202
+ throw new SomaV2ParseError(
203
+ `"${blockId}" 是普通锚点,不能作为组件块——`
204
+ + '组件块只能挂在带 data-soma-component 的实例锚点上;'
205
+ + '普通锚点的绑定写在 page 块的 ui: 段',
206
+ blockId,
207
+ line,
208
+ );
209
+ }
210
+ const known = [...htmlIndex.instances].slice(0, 8).join('、');
211
+ throw new SomaV2ParseError(
212
+ `HTML 里没有实例锚点 "${blockId}"${known ? `(现有实例:${known})` : ''}`,
213
+ blockId,
214
+ line,
215
+ );
216
+ }
@@ -6,6 +6,7 @@
6
6
  //
7
7
  // 纪律(D10):目录永远从契约生成,禁止手工维护第二份副本。
8
8
 
9
+ import { deriveV2Example } from './example-v2';
9
10
  import type {
10
11
  SomaComponentContract,
11
12
  SomaGeometryFamily,
@@ -245,6 +246,20 @@ function renderMarkdown(entries: SomaAiCatalogEntry[], conventions?: string): st
245
246
  lines.push('```');
246
247
  lines.push(entry.ai.example.trimEnd());
247
248
  lines.push('```');
249
+
250
+ // DSL v2 写法(由 v1 示例机械派生,见 example-v2.ts)。
251
+ // 派生而不是在 315 份契约里各写一份:契约仍是单一真源,
252
+ // 两份示例不可能不一致——因为后者是前者的函数
253
+ const v2 = deriveV2Example(entry.name, entry.ai.example);
254
+ if (v2) {
255
+ lines.push('');
256
+ // 目录会被压成裸文本喂给模型(围栏与多余空行都剥掉),
257
+ // 所以这行标注必须自带上下文:不能靠代码块的视觉分隔来区分两种写法
258
+ lines.push('v2(html 同上,_ui.yaml 改块声明):');
259
+ lines.push('```');
260
+ lines.push(v2);
261
+ lines.push('```');
262
+ }
248
263
  }
249
264
 
250
265
  if (entry.ai?.antiPatterns?.length) {