soma-core 1.3.3 → 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 (106) hide show
  1. package/README.md +7 -6
  2. package/app/SomaPageClient.tsx +2 -72
  3. package/bin/soma-lsp.cjs +1 -4
  4. package/core/build/compiler/full-manifest-builder.ts +17 -26
  5. package/core/build/compiler/html-include-expander.ts +56 -0
  6. package/core/build/compiler/page-assets.ts +26 -0
  7. package/core/build/compiler/page-declaration-compiler.ts +85 -0
  8. package/core/build/compiler/rollup-plugin-soma.ts +4 -19
  9. package/core/build/compiler/route-builder.ts +0 -2
  10. package/core/build/compiler/rspack-plugin-soma.js +1 -10
  11. package/core/build/compiler/soma-manifest-webpack-plugin.js +54 -13
  12. package/core/build/compiler/soma-precompile.js +74 -0
  13. package/core/build/compiler/soma-precompile.ts +13 -0
  14. package/core/build/compiler/soma-rspack-yaml-loader.js +5 -11
  15. package/core/build/compiler/soma-webpack-loader.js +6 -21
  16. package/core/build/compiler/vite-plugin-soma.ts +9 -31
  17. package/core/build/component/pack-from-dir.ts +58 -0
  18. package/core/build/component/package-loader.ts +158 -12
  19. package/core/build/eject/plan-eject.ts +15 -21
  20. package/core/build/lsp/cross-file-diagnostics.cjs +82 -113
  21. package/core/build/lsp/extra-completion.cjs +14 -8
  22. package/core/build/lsp/lsp-navigation.cjs +50 -43
  23. package/core/build/lsp/soma-declaration.cjs +85 -0
  24. package/core/build/lsp/ui-yaml-completion.cjs +98 -104
  25. package/core/build/v2/block-compile.ts +200 -0
  26. package/core/build/v2/block-loader.ts +33 -0
  27. package/core/build/v2/html-index.ts +120 -0
  28. package/core/build/v2/migrate-v1.ts +370 -0
  29. package/core/build/v2/soma-file-loader.ts +216 -0
  30. package/core/client/component/ai-catalog.ts +15 -0
  31. package/core/client/component/component-pack.ts +205 -31
  32. package/core/client/component/contract-compat.ts +132 -0
  33. package/core/client/component/example-v2.ts +132 -0
  34. package/core/client/engine/dom-renderer.ts +14 -8
  35. package/core/client/engine/reactive-proxy.ts +8 -7
  36. package/core/client/engine/soma-bootstrap.ts +23 -5
  37. package/core/client/parser/v2/namespace.ts +182 -0
  38. package/core/client/parser/v2/page-parser.ts +359 -0
  39. package/core/client/parser/v2/use-parser.ts +412 -0
  40. package/core/client/parser/value-lang.ts +340 -0
  41. package/core/client/pipes/pipe-registry.ts +1 -1
  42. package/core/client/registry/declaration-renderer.ts +17 -15
  43. package/core/client/theme/harmony.ts +307 -0
  44. package/core/client/theme/scene-tokens.ts +134 -0
  45. package/core/client/theme/theme-axes.ts +228 -0
  46. package/core/client/theme/theme-engine.ts +333 -73
  47. package/core/client/theme/tone-solver.ts +118 -0
  48. package/core/index.ts +74 -2
  49. package/core/server/host/server-page-assets.ts +33 -16
  50. package/core/server/host/soma-page-compile.ts +33 -0
  51. package/core/server/index.ts +15 -0
  52. package/core/server/registry/declaration-precompiler.ts +24 -54
  53. package/core/server/registry/page-registry-store.ts +38 -9
  54. package/core/server/registry/services/pages/Get.ts +19 -9
  55. package/core/server/registry/validation/compile-gate.ts +14 -31
  56. package/core/server/registry/validation/cross-check.ts +7 -17
  57. package/core/server/registry/validation/declaration-safety-scan.ts +2 -2
  58. package/core/shared/types/component-contract.types.ts +10 -0
  59. package/dist/core/index.cjs +2138 -154
  60. package/dist/types/build/compiler/full-manifest-builder.d.ts +4 -4
  61. package/dist/types/build/compiler/html-include-expander.d.ts +19 -0
  62. package/dist/types/build/compiler/page-assets.d.ts +3 -0
  63. package/dist/types/build/compiler/page-declaration-compiler.d.ts +33 -0
  64. package/dist/types/build/compiler/rollup-plugin-soma.d.ts +0 -3
  65. package/dist/types/build/compiler/route-builder.d.ts +0 -1
  66. package/dist/types/build/compiler/soma-precompile.d.ts +8 -0
  67. package/dist/types/build/compiler/vite-plugin-soma.d.ts +2 -10
  68. package/dist/types/build/component/pack-from-dir.d.ts +17 -0
  69. package/dist/types/build/component/package-loader.d.ts +33 -2
  70. package/dist/types/build/v2/block-compile.d.ts +28 -0
  71. package/dist/types/build/v2/block-loader.d.ts +9 -0
  72. package/dist/types/build/v2/html-index.d.ts +37 -0
  73. package/dist/types/build/v2/migrate-v1.d.ts +32 -0
  74. package/dist/types/build/v2/soma-file-loader.d.ts +45 -0
  75. package/dist/types/client/component/component-pack.d.ts +23 -3
  76. package/dist/types/client/component/contract-compat.d.ts +16 -0
  77. package/dist/types/client/component/example-v2.d.ts +9 -0
  78. package/dist/types/client/engine/dom-renderer.d.ts +2 -0
  79. package/dist/types/client/engine/soma-bootstrap.d.ts +3 -1
  80. package/dist/types/client/parser/v2/namespace.d.ts +52 -0
  81. package/dist/types/client/parser/v2/page-parser.d.ts +21 -0
  82. package/dist/types/client/parser/v2/use-parser.d.ts +72 -0
  83. package/dist/types/client/parser/value-lang.d.ts +63 -0
  84. package/dist/types/client/registry/declaration-renderer.d.ts +1 -2
  85. package/dist/types/client/theme/harmony.d.ts +77 -0
  86. package/dist/types/client/theme/scene-tokens.d.ts +25 -0
  87. package/dist/types/client/theme/theme-axes.d.ts +81 -0
  88. package/dist/types/client/theme/theme-engine.d.ts +29 -1
  89. package/dist/types/client/theme/tone-solver.d.ts +47 -0
  90. package/dist/types/index.d.ts +13 -2
  91. package/dist/types/server/host/server-page-assets.d.ts +1 -4
  92. package/dist/types/server/host/soma-page-compile.d.ts +7 -0
  93. package/dist/types/server/index.d.ts +3 -1
  94. package/dist/types/server/registry/declaration-precompiler.d.ts +3 -3
  95. package/dist/types/server/registry/page-registry-store.d.ts +4 -4
  96. package/dist/types/server/registry/validation/compile-gate.d.ts +2 -0
  97. package/dist/types/server/registry/validation/cross-check.d.ts +4 -4
  98. package/dist/types/shared/types/component-contract.types.d.ts +10 -0
  99. package/editor/vscode/package.json +1 -24
  100. package/global.d.ts +1 -11
  101. package/next.config.js +32 -50
  102. package/package.json +3 -2
  103. package/tailwind.config.ts +0 -1
  104. package/core/build/lsp/event-yaml-completion.cjs +0 -106
  105. package/core/client/host-bridge/empty-host/data/README.md +0 -17
  106. package/editor/vscode/syntaxes/soma-event-yaml.tmLanguage.json +0 -30
@@ -1,170 +1,164 @@
1
- /**
2
- * _ui.yaml 智能补全:html 锚点、domain 属性路径、YAML 关键字
3
- */
1
+ /** 唯一 SOMA DSL 智能补全:page 块、HTML 锚点、事件与 Domain 路径。 */
4
2
  const fs = require('node:fs');
5
3
  const path = require('node:path');
6
4
 
7
- const UI_ROOT_KEYS = ['bind', 'show', 'model', 'when'];
8
- const BIND_SUB_KEYS = ['obj', 'var'];
9
- const SHOW_ATTR_SUFFIXES = ['@src', '@href', '@alt', '@title', '@value'];
10
-
11
- function extractSomaIdsFromHtml(html) {
12
- const ids = new Set();
13
- for (const m of html.matchAll(/data-soma-id=["']([^"']+)["']/g)) {
14
- ids.add(m[1]);
15
- }
16
- return [...ids].sort();
17
- }
18
-
19
- function collectHtmlPages(htmlDir) {
20
- const pages = [];
21
- if (!fs.existsSync(htmlDir)) return pages;
22
- function walk(dir, prefix = '') {
23
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
24
- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
25
- const full = path.join(dir, entry.name);
26
- if (entry.isDirectory()) walk(full, rel);
27
- else if (entry.name.endsWith('.html')) pages.push(rel.replace(/\.html$/, ''));
28
- }
5
+ const PAGE_KEYS = ['domain: ', 'initProps:', 'ui:', 'event:', 'data:', 'watch:', 'adaptive:', 'locale:', 'alias:'];
6
+ const COMPONENT_KEYS = ['component: ', 'alias:', 'when: ', 'data:', 'ui:', 'event:'];
7
+ const EVENT_KEYS = ['actions:', 'on:'];
8
+ const UI_SUFFIXES = ['@src', '@href', '@alt', '@title', '@value', '.when', '.model', '.class'];
9
+ const DOM_EVENTS = ['click', 'input', 'change', 'keydown.enter', 'submit'];
10
+ const PIPELINE_TYPES = ['UI_REFRESH', 'NAV_ACTION', 'NAV_STATIC', 'UI_INTERACT'];
11
+
12
+ function extractHtmlFacts(html) {
13
+ const anchors = new Set();
14
+ const components = new Set();
15
+ for (const match of html.matchAll(/data-soma-id=["']([^"']+)["']/g)) anchors.add(match[1]);
16
+ for (const match of html.matchAll(/<[^>]*data-soma-component=["'][^"']+["'][^>]*>/g)) {
17
+ const id = match[0].match(/data-soma-id=["']([^"']+)["']/)?.[1];
18
+ if (id) components.add(id);
29
19
  }
30
- walk(htmlDir);
31
- return pages;
20
+ return { anchors: [...anchors].sort(), components: [...components].sort() };
32
21
  }
33
22
 
34
23
  function scanDomainProperties(hostDir, pageBase) {
35
24
  const props = new Set(['_locale', '_config', '_services']);
36
25
  const classPath = path.join(hostDir, 'domain', 'ui', `${pageBase}Class.ts`);
37
26
  if (!fs.existsSync(classPath)) return [...props].sort();
38
-
39
- const src = fs.readFileSync(classPath, 'utf8');
40
- for (const m of src.matchAll(/^\s+(\w+)\s*[=:]/gm)) props.add(m[1]);
41
- for (const m of src.matchAll(/^\s+async\s+(\w+)\s*\(/gm)) props.add(m[1]);
42
- for (const m of src.matchAll(/^\s+(\w+)\s*\([^)]*\)\s*[:{]/gm)) props.add(m[1]);
27
+ const source = fs.readFileSync(classPath, 'utf8');
28
+ for (const match of source.matchAll(/^\s+(\w+)\s*[=:]/gm)) props.add(match[1]);
29
+ for (const match of source.matchAll(/^\s+async\s+(\w+)\s*\(/gm)) props.add(match[1]);
30
+ for (const match of source.matchAll(/^\s+(\w+)\s*\([^)]*\)\s*[:{]/gm)) props.add(match[1]);
43
31
  return [...props].sort();
44
32
  }
45
33
 
46
34
  function pageBaseFromUri(uri, hostDir) {
47
35
  if (!uri) return null;
48
36
  const filePath = decodeURIComponent(uri.replace(/^file:\/\//, ''));
49
- const name = path.basename(filePath);
50
- const m = name.match(/^(.+)_ui\.yaml$/);
51
- if (m) return m[1];
52
- if (hostDir && filePath.startsWith(hostDir)) {
53
- const rel = path.relative(hostDir, filePath);
54
- const mm = rel.match(/ui[/\\](.+)_ui\.yaml$/);
55
- if (mm) return mm[1].replace(/\\/g, '/');
37
+ if (hostDir) {
38
+ const rel = path.relative(path.resolve(hostDir), path.resolve(filePath));
39
+ const nested = rel.match(/^ui[/\\](.+)_ui\.yaml$/);
40
+ if (nested && !rel.startsWith('..')) return nested[1].replace(/\\/g, '/');
56
41
  }
57
- return null;
42
+ return path.basename(filePath).match(/^(.+)_ui\.yaml$/)?.[1] ?? null;
58
43
  }
59
44
 
60
45
  function linePrefix(text, position) {
61
- const lines = text.split('\n');
62
- const line = lines[position.line] ?? '';
63
- return line.slice(0, position.character);
46
+ return (text.split('\n')[position.line] ?? '').slice(0, position.character);
64
47
  }
65
48
 
66
- function getIndent(line) {
67
- const m = line.match(/^(\s*)/);
68
- return m ? m[1].length : 0;
49
+ function indentOf(line) {
50
+ return line.match(/^(\s*)/)?.[1].length ?? 0;
69
51
  }
70
52
 
71
- function getYamlBlockContext(text, position) {
72
- const lines = text.split('\n').slice(0, position.line + 1);
73
- let ctx = 'root';
53
+ function contextPath(text, position) {
54
+ const stack = [];
55
+ const lines = text.split('\n').slice(0, position.line);
74
56
  for (const line of lines) {
75
- const t = line.trim();
76
- if (/^bind:\s*$/.test(t)) ctx = 'bind';
77
- else if (/^show:\s*$/.test(t)) ctx = 'show';
57
+ const match = /^(\s*)["']?([\w@.-]+)["']?:(?:\s.*)?$/.exec(line);
58
+ if (!match) continue;
59
+ const indent = match[1].length;
60
+ while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
61
+ stack.push({ indent, key: match[2] });
78
62
  }
79
- return ctx;
63
+ return stack.map((item) => item.key);
80
64
  }
81
65
 
82
66
  function completionItem(label, detail, kind = 10) {
83
67
  return { label, kind, detail, insertText: label };
84
68
  }
85
69
 
86
- /**
87
- * @returns {Array<{label:string,kind:number,detail?:string,insertText?:string}>}
88
- */
89
70
  function getUiYamlCompletions(hostDir, uri, text, position) {
90
71
  const pageBase = pageBaseFromUri(uri, hostDir);
91
72
  if (!pageBase) return [];
92
-
93
73
  const prefix = linePrefix(text, position);
94
74
  const trimmed = prefix.trimStart();
95
- const indent = getIndent(prefix);
96
- const items = [];
97
-
75
+ const indent = indentOf(prefix);
76
+ const context = contextPath(text, position);
98
77
  const htmlPath = path.join(hostDir, 'html', `${pageBase}.html`);
99
- const somaIds = fs.existsSync(htmlPath) ? extractSomaIdsFromHtml(fs.readFileSync(htmlPath, 'utf8')) : [];
78
+ const facts = fs.existsSync(htmlPath)
79
+ ? extractHtmlFacts(fs.readFileSync(htmlPath, 'utf8'))
80
+ : { anchors: [], components: [] };
81
+ const pageAnchors = facts.anchors.filter((id) => !facts.components.includes(id));
100
82
  const domainProps = scanDomainProperties(hostDir, pageBase);
83
+ const items = [];
101
84
 
102
- const blockCtx = getYamlBlockContext(text, position);
85
+ if (!text.trim() || (position.line === 0 && !trimmed)) {
86
+ return [completionItem('{{', 'SOMA DSL 开关行', 14)];
87
+ }
103
88
 
104
- if (indent === 0 && trimmed.length === 0) {
105
- for (const k of UI_ROOT_KEYS) items.push(completionItem(k, 'ui.yaml 根键'));
89
+ if (indent === 0 && !trimmed) {
90
+ items.push(completionItem('page:', '页面块', 14));
91
+ for (const id of facts.components) items.push(completionItem(`${id}:`, '组件实例块', 5));
106
92
  return items;
107
93
  }
108
94
 
109
- if (/^bind:\s*$/.test(trimmed) || (blockCtx === 'bind' && indent === 2 && trimmed === '')) {
110
- for (const k of BIND_SUB_KEYS) items.push(completionItem(`${k}: `, 'bind 子键', 14));
111
- return items;
95
+ if (context.at(-1) === 'page' && indent === 2 && !trimmed) {
96
+ return PAGE_KEYS.map((key) => completionItem(key, 'page 块键', 14));
112
97
  }
113
98
 
114
- const bindObj = prefix.match(/obj:\s*(\w*)$/);
115
- if (bindObj) {
116
- const guess = pageBase.charAt(0).toUpperCase() + pageBase.slice(1) + 'Class';
117
- items.push(completionItem(guess, 'Domain 类名', 7));
118
- return items;
99
+ const topLevelBlock = context.length === 1 && context[0] !== 'page';
100
+ if (topLevelBlock && indent === 2 && !trimmed) {
101
+ return COMPONENT_KEYS.map((key) => completionItem(key, '组件实例块键', 14));
119
102
  }
120
103
 
121
- const bindVar = prefix.match(/var:\s*(\w*)$/);
122
- if (bindVar) {
123
- for (const v of ['page', 'item', 'c', 'p', 'row']) {
124
- items.push(completionItem(v, '循环变量', 6));
125
- }
126
- return items;
104
+ if (context.at(-1) === 'event' && indent >= 4 && !trimmed) {
105
+ return EVENT_KEYS.map((key) => completionItem(key, '事件段键', 14));
127
106
  }
128
107
 
129
- const showKey = prefix.match(/^(\s*)(\w*)$/);
130
- if (showKey && indent >= 2) {
131
- const partial = showKey[2];
132
- for (const id of somaIds) {
133
- if (!partial || id.startsWith(partial)) {
134
- items.push(completionItem(`${id}: `, 'html data-soma-id', 5));
135
- for (const sfx of SHOW_ATTR_SUFFIXES) {
136
- items.push(completionItem(`${id}${sfx}: `, '属性绑定', 5));
137
- }
108
+ if (/domain:\s*\w*$/.test(prefix)) {
109
+ const name = pageBase.split('/').pop() ?? 'page';
110
+ const guess = name.charAt(0).toUpperCase() + name.slice(1) + 'Class';
111
+ return [completionItem(guess, 'Domain 类名', 7)];
112
+ }
113
+
114
+ const valuePath = prefix.match(/:\s*(?:page\.)?(\w*)$/);
115
+ if (valuePath && (prefix.includes('page.') || !context.includes('on'))) {
116
+ const partial = valuePath[1] ?? '';
117
+ for (const property of domainProps) {
118
+ if (!partial || property.startsWith(partial)) {
119
+ items.push(completionItem(`page.${property}`, `domain.${property}`, 6));
138
120
  }
139
121
  }
140
- if (trimmed.endsWith('when:') || prefix.match(/when:\s*$/)) {
141
- for (const p of domainProps) {
142
- items.push(completionItem(`page.${p}`, '条件表达式', 6));
143
- }
122
+ if (items.length > 0) return items;
123
+ }
124
+
125
+ if (context.slice(-2).join('/') === 'page/ui' && indent >= 4) {
126
+ const partial = trimmed;
127
+ for (const id of pageAnchors) {
128
+ if (partial && !id.startsWith(partial)) continue;
129
+ items.push(completionItem(`${id}: `, 'HTML 页面锚点', 5));
130
+ for (const suffix of UI_SUFFIXES) items.push(completionItem(`${id}${suffix}: `, '绑定后缀', 5));
144
131
  }
145
132
  return items;
146
133
  }
147
134
 
148
- const valuePath = prefix.match(/:\s*(page\.)?(\w*)$/);
149
- if (valuePath) {
150
- const partial = valuePath[2] ?? '';
151
- for (const p of domainProps) {
152
- if (!partial || p.startsWith(partial)) {
153
- items.push(completionItem(`page.${p}`, `domain.${p}`, 6));
154
- items.push(completionItem(`page._locale.${p}`, 'locale 文案', 6));
135
+ if (context.slice(-3).join('/') === 'page/event/on' && indent >= 6 && !trimmed.includes(':')) {
136
+ for (const id of pageAnchors) {
137
+ for (const event of DOM_EVENTS) {
138
+ const label = `${id}.${event}: `;
139
+ if (!trimmed || label.startsWith(trimmed)) items.push(completionItem(label, '页面 DOM 事件', 5));
155
140
  }
156
141
  }
157
142
  return items;
158
143
  }
159
144
 
160
- const modelLine = prefix.match(/^(\s*)(\w*)$/);
161
- if (modelLine && indent >= 4) {
162
- for (const p of domainProps) {
163
- items.push(completionItem(`page.${p}`, 'model 绑定', 6));
164
- }
145
+ if (context.at(-1) === 'on' && context[0] !== 'page' && !trimmed.includes(':')) {
146
+ return [completionItem('change: ', '组件 emit 路由', 5)];
147
+ }
148
+
149
+ if (/:(?:\s*)(?:[A-Z_]*)$/.test(prefix) && context.includes('on')) {
150
+ return PIPELINE_TYPES.map((type) => completionItem(`${type} | `, 'Pipeline 类型', 14));
165
151
  }
166
152
 
167
153
  return items;
168
154
  }
169
155
 
170
- module.exports = { getUiYamlCompletions, extractSomaIdsFromHtml, scanDomainProperties };
156
+ module.exports = {
157
+ getUiYamlCompletions,
158
+ extractSomaIdsFromHtml: (html) => extractHtmlFacts(html).anchors,
159
+ extractHtmlFacts,
160
+ scanDomainProperties,
161
+ PAGE_KEYS,
162
+ PIPELINE_TYPES,
163
+ COMPONENT_KEYS,
164
+ };
@@ -0,0 +1,200 @@
1
+ // v2 编译总调度(REQ-005 F6.2):块声明 → v1 等价产物。
2
+ //
3
+ // 这是"两级编译、单一运行时"的落点:v2 只是更好写的书写层,编译后交给
4
+ // 既有引擎——运行时零新增、对块零感知。产出的 UiConfig / 事件清单 / 数据对象
5
+ // 与手写 v1 完全同形,因此注册中心四道闸门、预编译、eject 全部原样可用。
6
+ //
7
+ // 编译期做完的事(第零条公理:性能由引擎吸收):
8
+ // 开关探测 → 块装载 → 命名空间与别名整体展开 → 路径全名还原 →
9
+ // props 并入 show → emit 路由并入事件清单 → 数据对象接线。
10
+ // 运行时只剩读数据、写 DOM、diff——与原生代码要付的一样。
11
+
12
+ import type { UiConfig } from '../../shared/types/ui-config.types';
13
+ import { buildHtmlAnchorIndex, type HtmlAnchorIndex } from './html-index';
14
+ import { PAGE_BLOCK_ID, SomaV2ParseError, loadSomaFile } from './soma-file-loader';
15
+ import { parsePageBlock } from '../../client/parser/v2/page-parser';
16
+ import { parseUseBlock, type UseBlockAst } from '../../client/parser/v2/use-parser';
17
+
18
+ export interface CompiledSomaV2 {
19
+ /** v1 等价 UiConfig:直接交既有编译管线 */
20
+ ui: UiConfig;
21
+ /** v1 等价事件声明(DOM 事件 + timers/triggers + 组件 emit 路由) */
22
+ event: Record<string, unknown>;
23
+ /** 数据对象声明(页面级 + 各块私有,已带全局身份) */
24
+ data: Record<string, unknown>;
25
+ /** 各组件块的 AST(供生成器族与诊断消费) */
26
+ blocks: ReadonlyMap<string, UseBlockAst>;
27
+ htmlIndex: HtmlAnchorIndex;
28
+ }
29
+
30
+ export interface CompileSomaV2Input {
31
+ html: string;
32
+ uiYamlRaw: string;
33
+ /** 外置块:锚点名 → 块体原文(服务端由 loadExternalBlocks 提供) */
34
+ externalBlocks?: ReadonlyMap<string, string>;
35
+ /** 词典键集合(locale 批量段校验;缺省不校验) */
36
+ localeKeys?: ReadonlySet<string>;
37
+ }
38
+
39
+ /**
40
+ * 编译一份 v2 声明。
41
+ *
42
+ * 本函数只接受 canonical 声明,不做旧页面形状回退;旧输入会在开关校验处明确报错。
43
+ */
44
+ export function compileSomaV2(input: CompileSomaV2Input): CompiledSomaV2 {
45
+ const htmlIndex = buildHtmlAnchorIndex(input.html);
46
+
47
+ if (htmlIndex.duplicates.length > 0) {
48
+ throw new SomaV2ParseError(
49
+ `HTML 锚点重复:${htmlIndex.duplicates.join('、')}——页面内 data-soma-id 必须唯一`,
50
+ );
51
+ }
52
+
53
+ const rawBlocks = loadSomaFile({
54
+ uiYamlRaw: input.uiYamlRaw,
55
+ htmlIndex,
56
+ ...(input.externalBlocks ? { externalBlocks: input.externalBlocks } : {}),
57
+ });
58
+
59
+ const pageRaw = rawBlocks.find((block) => block.blockId === PAGE_BLOCK_ID);
60
+ if (!pageRaw) {
61
+ throw new SomaV2ParseError('缺少 page 块(页面必须声明 domain)');
62
+ }
63
+
64
+ const anchors = new Set(htmlIndex.anchors.keys());
65
+ const page = parsePageBlock({
66
+ body: pageRaw.body,
67
+ anchors,
68
+ instances: htmlIndex.instances,
69
+ ...(input.localeKeys ? { localeKeys: input.localeKeys } : {}),
70
+ });
71
+
72
+ const ui: UiConfig = page.ui;
73
+ const event: Record<string, unknown> = { ...page.eventRaw };
74
+ const data: Record<string, unknown> = {};
75
+
76
+ // 页面级数据对象直接以声明名进入运行时 data;Domain 因而得到 page.data.<name>。
77
+ // 这里不能加 page. 前缀:data-config 的对象键就是运行时对象身份。
78
+ for (const [name, decl] of Object.entries(page.dataRaw ?? {})) {
79
+ data[name] = decl;
80
+ }
81
+
82
+ const blocks = new Map<string, UseBlockAst>();
83
+ for (const raw of rawBlocks) {
84
+ if (raw.blockId === PAGE_BLOCK_ID) continue;
85
+
86
+ const info = htmlIndex.anchors.get(raw.blockId);
87
+ const ast = parseUseBlock({
88
+ blockId: raw.blockId,
89
+ body: raw.body,
90
+ ...(info?.component ? { htmlComponent: info.component } : {}),
91
+ rowVars: rowVarsFor(raw.blockId, htmlIndex, ui),
92
+ });
93
+ blocks.set(raw.blockId, ast);
94
+
95
+ // props 并入 show:行内组件挂到它所属列表的子 show 下,其余挂顶层
96
+ attachInstance(ui, raw.blockId, ast, htmlIndex);
97
+
98
+ // emit 路由并入事件清单:v1 形状是 "实例id.emit名"
99
+ for (const [emitName, expr] of Object.entries(ast.emitRoutes)) {
100
+ event[`${raw.blockId}.${emitName}`] = expr;
101
+ }
102
+
103
+ // 数据对象:块内私有对象已带全局身份
104
+ for (const object of ast.dataObjects) {
105
+ data[object.fullName] = {
106
+ ...(object.from ? { from: object.from } : {}),
107
+ ...(object.save ? { save: object.save } : {}),
108
+ ...(object.refreshMs !== undefined ? { refreshMs: object.refreshMs } : {}),
109
+ ...(object.reloadOn ? { reloadOn: object.reloadOn } : {}),
110
+ ...(object.fields ? { fields: object.fields } : {}),
111
+ };
112
+ }
113
+ }
114
+
115
+ return { ui, event, data, blocks, htmlIndex };
116
+ }
117
+
118
+ /**
119
+ * 该实例可见的行变量:位于行模板内时,取**它所属**列表及其祖先列表的 bind.var。
120
+ *
121
+ * 不是"页面上所有列表的变量"——那会让 A 列表里的组件能引用 B 列表的行变量,
122
+ * 校验形同虚设。
123
+ */
124
+ function rowVarsFor(
125
+ blockId: string,
126
+ htmlIndex: HtmlAnchorIndex,
127
+ ui: UiConfig,
128
+ ): string[] {
129
+ const info = htmlIndex.anchors.get(blockId);
130
+ if (!info?.inRowTemplate || !info.ownerList) return [];
131
+
132
+ const chain: string[] = [];
133
+ const walk = (show: Record<string, unknown>, ancestors: string[]): boolean => {
134
+ for (const [key, value] of Object.entries(show)) {
135
+ if (value === null || typeof value !== 'object') continue;
136
+ const node = value as { bind?: { var?: string }; show?: Record<string, unknown> };
137
+ const nextAncestors = node.bind?.var ? [...ancestors, node.bind.var] : ancestors;
138
+ if (key === info.ownerList && node.bind?.var) {
139
+ chain.push(...nextAncestors);
140
+ return true;
141
+ }
142
+ if (node.show && walk(node.show, nextAncestors)) return true;
143
+ }
144
+ return false;
145
+ };
146
+ walk(ui.show as Record<string, unknown>, []);
147
+ return chain;
148
+ }
149
+
150
+ /** 把实例 props 挂到 UiConfig 的正确层级(行内组件进**它所属**列表的子 show) */
151
+ function attachInstance(
152
+ ui: UiConfig,
153
+ blockId: string,
154
+ ast: UseBlockAst,
155
+ htmlIndex: HtmlAnchorIndex,
156
+ ): void {
157
+ const value = ast.toShowValue();
158
+ const info = htmlIndex.anchors.get(blockId);
159
+
160
+ if (!info?.inRowTemplate) {
161
+ ui.show[blockId] = value;
162
+ return;
163
+ }
164
+
165
+ // 归属由 HTML 位置决定:一页多个列表时,"挂到第一个找到的列表"会静默挂错——
166
+ // 行内组件收不到行数据,页面不报错只是空白(cart 页实测踩到过)。
167
+ const owner = info.ownerList;
168
+ if (!owner) {
169
+ throw new SomaV2ParseError(
170
+ `实例 "${blockId}" 位于行模板内,但 HTML 里找不到它所属的列表锚点`,
171
+ blockId,
172
+ );
173
+ }
174
+
175
+ const target = findListShow(ui.show as Record<string, unknown>, owner);
176
+ if (!target) {
177
+ throw new SomaV2ParseError(
178
+ `实例 "${blockId}" 属于列表 "${owner}",但 page 块没有为该列表声明 each 作用域`,
179
+ blockId,
180
+ );
181
+ }
182
+ target[blockId] = value;
183
+ }
184
+
185
+ /** 按列表锚点名找到它的子 show(列表可嵌套,故递归) */
186
+ function findListShow(
187
+ show: Record<string, unknown>,
188
+ listAnchor: string,
189
+ ): Record<string, unknown> | undefined {
190
+ for (const [key, node] of Object.entries(show)) {
191
+ if (node === null || typeof node !== 'object') continue;
192
+ const nested = node as { bind?: unknown; show?: Record<string, unknown> };
193
+ if (key === listAnchor && nested.bind && nested.show) return nested.show;
194
+ if (nested.show) {
195
+ const found = findListShow(nested.show, listAnchor);
196
+ if (found) return found;
197
+ }
198
+ }
199
+ return undefined;
200
+ }
@@ -0,0 +1,33 @@
1
+ // v2 容器 · 外置块发现(REQ-005 F1.5,服务端)。
2
+ //
3
+ // 块体大到影响主文件阅读时,可**逐字**搬进 `ui/{base}.blocks/{锚点}.yaml`
4
+ // (去掉顶层键那一级缩进即可,语法零改动)——块与文件是同一语法的两种容器。
5
+ //
6
+ // 运行环境:node:fs,只能在构建期/服务端跑。
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ /** 外置块目录名:与页面同 base */
12
+ export function blocksDirOf(uiDir: string, base: string): string {
13
+ return path.join(uiDir, `${base}.blocks`);
14
+ }
15
+
16
+ /**
17
+ * 扫描外置块目录 → 锚点名 → 块体原文。
18
+ *
19
+ * 只收 `.yaml`;文件名即锚点名(合法性由 loadSomaFile 统一校验,
20
+ * 那里有 HTML 索引,报错能点名"现有实例有哪些")。
21
+ */
22
+ export function loadExternalBlocks(uiDir: string, base: string): Map<string, string> {
23
+ const dir = blocksDirOf(uiDir, base);
24
+ const blocks = new Map<string, string>();
25
+ if (!fs.existsSync(dir)) return blocks;
26
+
27
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
28
+ if (!entry.isFile() || !entry.name.endsWith('.yaml')) continue;
29
+ const blockId = entry.name.slice(0, -'.yaml'.length);
30
+ blocks.set(blockId, fs.readFileSync(path.join(dir, entry.name), 'utf-8'));
31
+ }
32
+ return blocks;
33
+ }
@@ -0,0 +1,120 @@
1
+ // v2 容器 · HTML 锚点索引(REQ-005 F1.2)。
2
+ //
3
+ // 块 id 的合法性以 HTML 为源:块 id ∈ {"page"} ∪ HTML 里的组件实例锚点。
4
+ // 编译期没有 DOM(Node 侧),因此按文本扫描——与既有 LSP 跨文件诊断
5
+ // (build/lsp/cross-file-diagnostics.cjs)同款做法,不引入 HTML 解析器依赖。
6
+ //
7
+ // 为什么要区分"实例锚点"与"普通锚点":组件块只能挂在带 data-soma-component
8
+ // 的锚点上;给普通锚点写块 = 声明了一个不存在的组件实例,必须编译期就拦住。
9
+
10
+ /** 锚点在 HTML 中的位置信息(用于报错定位与行变量可见性判定) */
11
+ export interface HtmlAnchorInfo {
12
+ somaId: string;
13
+ /** 带 data-soma-component 时的组件名;普通锚点为 undefined */
14
+ component?: string;
15
+ /** 所在行号(1 基) */
16
+ line: number;
17
+ /** 是否位于列表行模板 <template data-soma-role="item…"> 之内 */
18
+ inRowTemplate: boolean;
19
+ /** 所属行模板的角色后缀(异构列表用;同构为 'item') */
20
+ rowRole?: string;
21
+ /**
22
+ * 所属列表锚点(位于行模板内时)。
23
+ *
24
+ * 为什么必须有它:一页有多个列表时,"行内实例挂到哪个列表的子作用域"
25
+ * 只能由 HTML 位置回答。曾经按"找到的第一个列表"挂载,cart 页两个列表
26
+ * 就把 QtyStepper 挂进了优惠券列表——不报错,只是行内组件永远收不到行数据。
27
+ */
28
+ ownerList?: string;
29
+ }
30
+
31
+ export interface HtmlAnchorIndex {
32
+ /** 全部锚点(含普通锚点) */
33
+ anchors: ReadonlyMap<string, HtmlAnchorInfo>;
34
+ /** 组件实例锚点(可作为块 id) */
35
+ instances: ReadonlySet<string>;
36
+ /** 页面根的 data-soma-host 值 */
37
+ host?: string;
38
+ /** 重复锚点 id(页面内唯一是既有铁律,此处只收集,报错由调用方给措辞) */
39
+ duplicates: readonly string[];
40
+ }
41
+
42
+ const ANCHOR_RE = /data-soma-id=["']([^"']+)["']/g;
43
+ const COMPONENT_NEAR_RE = /data-soma-component=["']([^"']+)["']/;
44
+ const HOST_RE = /data-soma-host=["']([^"']+)["']/;
45
+ const TEMPLATE_OPEN_RE = /<template[^>]*data-soma-role=["']([^"']+)["'][^>]*>/gi;
46
+
47
+ /**
48
+ * 扫描 HTML 建立锚点索引。
49
+ *
50
+ * 组件判定:同一个标签内既有 data-soma-id 又有 data-soma-component。
51
+ * 按标签切分而不是按行——属性可以换行写,按行会漏。
52
+ */
53
+ export function buildHtmlAnchorIndex(html: string): HtmlAnchorIndex {
54
+ const anchors = new Map<string, HtmlAnchorInfo>();
55
+ const instances = new Set<string>();
56
+ const duplicates: string[] = [];
57
+
58
+ // 行模板区间:[起始下标, 结束下标, 角色]
59
+ const templateRanges: Array<{ start: number; end: number; role: string }> = [];
60
+ for (const match of html.matchAll(TEMPLATE_OPEN_RE)) {
61
+ const start = match.index ?? 0;
62
+ const closeIndex = html.indexOf('</template>', start);
63
+ templateRanges.push({
64
+ start,
65
+ end: closeIndex === -1 ? html.length : closeIndex,
66
+ role: match[1],
67
+ });
68
+ }
69
+
70
+ const lineAt = (index: number): number => html.slice(0, index).split('\n').length;
71
+ const roleAt = (index: number): string | undefined =>
72
+ templateRanges.find((range) => index > range.start && index < range.end)?.role;
73
+
74
+ /** 行模板所属的列表锚点:模板标签之前、最近的一个带 data-soma-id 的开标签 */
75
+ const ownerListAt = (index: number): string | undefined => {
76
+ const range = templateRanges.find((r) => index > r.start && index < r.end);
77
+ if (!range) return undefined;
78
+ const before = html.slice(0, range.start);
79
+ const matches = [...before.matchAll(/<[a-zA-Z][^>]*data-soma-id=["']([^"']+)["'][^>]*>/g)];
80
+ return matches.length > 0 ? matches[matches.length - 1][1] : undefined;
81
+ };
82
+
83
+ // 逐标签扫描:从 '<' 到匹配的 '>',属性换行也能正确归组
84
+ const tagRe = /<[a-zA-Z][^>]*>/g;
85
+ for (const tagMatch of html.matchAll(tagRe)) {
86
+ const tag = tagMatch[0];
87
+ const tagIndex = tagMatch.index ?? 0;
88
+ ANCHOR_RE.lastIndex = 0;
89
+ const idMatch = ANCHOR_RE.exec(tag);
90
+ if (!idMatch) continue;
91
+
92
+ const somaId = idMatch[1];
93
+ if (anchors.has(somaId)) {
94
+ if (!duplicates.includes(somaId)) duplicates.push(somaId);
95
+ continue;
96
+ }
97
+
98
+ const componentMatch = COMPONENT_NEAR_RE.exec(tag);
99
+ const role = roleAt(tagIndex);
100
+ const owner = role !== undefined ? ownerListAt(tagIndex) : undefined;
101
+ const info: HtmlAnchorInfo = {
102
+ somaId,
103
+ line: lineAt(tagIndex),
104
+ inRowTemplate: role !== undefined,
105
+ ...(role ? { rowRole: role } : {}),
106
+ ...(owner ? { ownerList: owner } : {}),
107
+ ...(componentMatch ? { component: componentMatch[1] } : {}),
108
+ };
109
+ anchors.set(somaId, info);
110
+ if (componentMatch) instances.add(somaId);
111
+ }
112
+
113
+ const hostMatch = HOST_RE.exec(html);
114
+ return {
115
+ anchors,
116
+ instances,
117
+ duplicates,
118
+ ...(hostMatch ? { host: hostMatch[1] } : {}),
119
+ };
120
+ }