soma-core 1.5.1 → 1.6.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.
- package/app/SomaPageClient.tsx +28 -9
- package/app/soma/manifest/route.ts +3 -0
- package/bin/migrate.cjs +71 -1
- package/bin/soma-lsp.cjs +8 -1
- package/core/build/blocks/block-compile.ts +23 -5
- package/core/build/compiler/full-manifest-builder.ts +15 -0
- package/core/build/compiler/page-assets.ts +17 -1
- package/core/build/compiler/page-declaration-compiler.ts +67 -11
- package/core/build/compiler/precompiled-manifest-loader.ts +7 -0
- package/core/build/compiler/soma-manifest-webpack-plugin.js +7 -0
- package/core/build/compiler/soma-precompile.js +30 -6
- package/core/build/component/package-loader.ts +35 -4
- package/core/build/component-tree/artifact-codec.ts +192 -0
- package/core/build/component-tree/binding-bridge.ts +272 -0
- package/core/build/component-tree/collection-binding-lowerer.ts +65 -0
- package/core/build/component-tree/definition-preparation.ts +320 -0
- package/core/build/component-tree/migration-files.ts +214 -0
- package/core/build/component-tree/migration.ts +170 -0
- package/core/build/component-tree/parser.ts +362 -0
- package/core/build/component-tree/registry-snapshot.ts +317 -0
- package/core/build/component-tree/source-preflight.ts +132 -0
- package/core/build/component-tree/structure-topology.ts +63 -0
- package/core/build/component-tree/validator.ts +318 -0
- package/core/build/lsp/component-tree-service.ts +79 -0
- package/core/build/lsp/component-tree.cjs +42 -0
- package/core/build/lsp/cross-file-diagnostics.cjs +15 -3
- package/core/build/lsp/extra-completion.cjs +7 -0
- package/core/client/compiler/manifest-compiler.ts +2 -0
- package/core/client/component/ai-catalog.ts +41 -3
- package/core/client/component/catalog-examples.ts +60 -0
- package/core/client/component/component-definition.types.ts +9 -0
- package/core/client/component/component-expander.ts +21 -5
- package/core/client/component/component-manager.ts +103 -16
- package/core/client/component/component-registry.ts +10 -1
- package/core/client/component/scoped-adapter.ts +29 -2
- package/core/client/component/structure-adapter.ts +207 -0
- package/core/client/component/verify-pack.ts +21 -1
- package/core/client/engine/asset-resolver.ts +1 -1
- package/core/client/engine/dom-renderer.ts +283 -0
- package/core/client/engine/event-engine.ts +28 -9
- package/core/client/engine/render-engine.ts +2 -0
- package/core/client/engine/row-range.ts +62 -0
- package/core/client/engine/row-scope.ts +77 -0
- package/core/client/engine/runtime-builder.ts +2 -0
- package/core/client/engine/soma-bootstrap.ts +146 -1
- package/core/client/parser/blocks/page-parser.ts +9 -2
- package/core/client/parser/ui-config-parser.ts +38 -6
- package/core/client/registry/declaration-renderer.ts +32 -24
- package/core/client/registry/remote-page.ts +1 -1
- package/core/client/validation/contract-validator.ts +1 -1
- package/core/index.ts +3 -0
- package/core/server/host/page-markup-config.ts +42 -0
- package/core/server/host/published-page-artifact-cache.ts +36 -4
- package/core/server/host/published-page-assets.ts +13 -7
- package/core/server/host/resolve-host-tree-context.ts +43 -0
- package/core/server/host/server-page-assets.ts +23 -4
- package/core/server/host/soma-page-compile.ts +10 -0
- package/core/server/page-declaration.ts +7 -0
- package/core/server/registry/declaration-precompiler.ts +35 -3
- package/core/server/registry/page-registry-repository.ts +31 -3
- package/core/server/registry/page-registry-store.ts +64 -7
- package/core/server/registry/publish-asset-pin.ts +6 -1
- package/core/server/registry/services/pages/Get.ts +11 -6
- package/core/server/registry/validation/compile-gate.ts +10 -1
- package/core/shared/component-tree-artifact.ts +237 -0
- package/core/shared/component-tree-errors.ts +52 -0
- package/core/shared/types/component-contract.types.ts +51 -0
- package/core/shared/types/component-tree-artifact.types.ts +121 -0
- package/core/shared/types/component-tree.types.ts +170 -0
- package/core/shared/types/engine.types.ts +5 -0
- package/core/shared/types/manifest.types.ts +4 -0
- package/core/shared/types/ui-config.types.ts +8 -0
- package/dist/cli/soma.js +1 -1
- package/dist/core/index.cjs +1757 -511
- package/dist/lsp/component-tree.cjs +20807 -0
- package/dist/types/build/blocks/block-compile.d.ts +10 -1
- package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
- package/dist/types/build/compiler/page-assets.d.ts +6 -1
- package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
- package/dist/types/build/component/package-loader.d.ts +4 -1
- package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
- package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
- package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
- package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
- package/dist/types/build/component-tree/migration-files.d.ts +35 -0
- package/dist/types/build/component-tree/migration.d.ts +28 -0
- package/dist/types/build/component-tree/parser.d.ts +13 -0
- package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
- package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
- package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
- package/dist/types/build/component-tree/validator.d.ts +9 -0
- package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
- package/dist/types/client/component/ai-catalog.d.ts +18 -1
- package/dist/types/client/component/catalog-examples.d.ts +18 -0
- package/dist/types/client/component/component-definition.types.d.ts +9 -0
- package/dist/types/client/component/component-expander.d.ts +2 -1
- package/dist/types/client/component/component-manager.d.ts +11 -0
- package/dist/types/client/component/scoped-adapter.d.ts +1 -0
- package/dist/types/client/component/structure-adapter.d.ts +17 -0
- package/dist/types/client/engine/dom-renderer.d.ts +15 -0
- package/dist/types/client/engine/event-engine.d.ts +1 -0
- package/dist/types/client/engine/render-engine.d.ts +1 -0
- package/dist/types/client/engine/row-range.d.ts +13 -0
- package/dist/types/client/engine/row-scope.d.ts +20 -0
- package/dist/types/client/engine/runtime-builder.d.ts +1 -0
- package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
- package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
- package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
- package/dist/types/client/registry/remote-page.d.ts +1 -1
- package/dist/types/index.d.ts +3 -1
- package/dist/types/server/host/page-markup-config.d.ts +6 -0
- package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
- package/dist/types/server/host/published-page-assets.d.ts +5 -3
- package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
- package/dist/types/server/host/server-page-assets.d.ts +6 -0
- package/dist/types/server/host/soma-page-compile.d.ts +10 -1
- package/dist/types/server/page-declaration.d.ts +6 -0
- package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
- package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
- package/dist/types/server/registry/page-registry-store.d.ts +11 -1
- package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
- package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
- package/dist/types/shared/component-tree-artifact.d.ts +5 -0
- package/dist/types/shared/component-tree-errors.d.ts +22 -0
- package/dist/types/shared/types/component-contract.types.d.ts +42 -0
- package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
- package/dist/types/shared/types/component-tree.types.d.ts +149 -0
- package/dist/types/shared/types/engine.types.d.ts +5 -0
- package/dist/types/shared/types/manifest.types.d.ts +4 -0
- package/dist/types/shared/types/ui-config.types.d.ts +8 -0
- package/package.json +2 -1
|
@@ -3547,6 +3547,15 @@ function validateBind(bind, path) {
|
|
|
3547
3547
|
if ("onChange" in bind && bind.onChange !== void 0) {
|
|
3548
3548
|
parseOnChangeRules(bind.onChange, `${path}.onChange`);
|
|
3549
3549
|
}
|
|
3550
|
+
if (bind.key !== void 0 && (typeof bind.key !== "string" || !bind.key.startsWith(`${bind.var}.`) || !/^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)+$/.test(bind.key) || bind.key.split(".").some((part) => ["__proto__", "prototype", "constructor"].includes(part)))) {
|
|
3551
|
+
throw new SomaUiConfigError("bind.key \u5FC5\u987B\u662F\u5F53\u524D\u884C\u53D8\u91CF\u7684\u5B89\u5168\u5B57\u6BB5\u8DEF\u5F84", path);
|
|
3552
|
+
}
|
|
3553
|
+
if (bind.repeatPlanId !== void 0 && (typeof bind.repeatPlanId !== "string" || !bind.repeatPlanId.trim() || bind.key !== void 0 || bind.collectionSlot !== void 0)) {
|
|
3554
|
+
throw new SomaUiConfigError("repeatPlanId \u5FC5\u987B\u662F\u975E\u7A7A\u5F15\u7528\u4E14\u4E0D\u80FD\u4E0E key/collectionSlot \u53CC\u5199", path);
|
|
3555
|
+
}
|
|
3556
|
+
if (bind.collectionSlot !== void 0 && (typeof bind.collectionSlot !== "string" || !bind.collectionSlot.trim() || bind.key === void 0)) {
|
|
3557
|
+
throw new SomaUiConfigError("collectionSlot \u5FC5\u987B\u5177\u540D\u5E76\u63D0\u4F9B\u552F\u4E00\u663E\u5F0F key", path);
|
|
3558
|
+
}
|
|
3550
3559
|
}
|
|
3551
3560
|
function parseOnChangeRules(raw, path) {
|
|
3552
3561
|
if (!Array.isArray(raw)) {
|
|
@@ -3604,7 +3613,7 @@ function isExtendedShowValue(value) {
|
|
|
3604
3613
|
const extendedKeys = ["text", "model", "when", "class", "show", "props"];
|
|
3605
3614
|
return extendedKeys.some((key) => key in value);
|
|
3606
3615
|
}
|
|
3607
|
-
function parseShowMapping(rawShow, path) {
|
|
3616
|
+
function parseShowMapping(rawShow, path, options) {
|
|
3608
3617
|
if (!rawShow || typeof rawShow !== "object") {
|
|
3609
3618
|
throw new SomaUiConfigError(`show \u5FC5\u987B\u662F\u5BF9\u8C61`, path);
|
|
3610
3619
|
}
|
|
@@ -3617,20 +3626,32 @@ function parseShowMapping(rawShow, path) {
|
|
|
3617
3626
|
if (typeof value === "string") {
|
|
3618
3627
|
result[key] = value;
|
|
3619
3628
|
} else if (/^item:.+/.test(key) && typeof value === "object" && value !== null && !isNestedShowMapping(value) && !isExtendedShowValue(value)) {
|
|
3620
|
-
result[key] = { show: parseShowMapping(value, currentPath) };
|
|
3629
|
+
result[key] = { show: parseShowMapping(value, currentPath, options) };
|
|
3621
3630
|
} else if (isNestedShowMapping(value)) {
|
|
3622
3631
|
const nestedPath = `${currentPath}.bind`;
|
|
3623
3632
|
validateBind(value.bind, nestedPath);
|
|
3633
|
+
if (value.bind.collectionSlot !== void 0 && options?.collectionBindingStage !== "definition-source") {
|
|
3634
|
+
throw new SomaUiConfigError("collectionSlot \u4EC5\u5141\u8BB8\u53D7\u4FE1\u7EC4\u4EF6\u5B9A\u4E49\u6E90\uFF1B\u8FD0\u884C\u65F6\u5FC5\u987B\u4F7F\u7528\u51C6\u5907\u8BA1\u5212", nestedPath);
|
|
3635
|
+
}
|
|
3624
3636
|
const nested = {
|
|
3625
3637
|
bind: {
|
|
3626
3638
|
obj: value.bind.obj,
|
|
3627
3639
|
var: value.bind.var,
|
|
3628
|
-
...typeof value.bind.role_by === "string" ? { role_by: value.bind.role_by } : {}
|
|
3640
|
+
...typeof value.bind.role_by === "string" ? { role_by: value.bind.role_by } : {},
|
|
3641
|
+
...value.bind.key !== void 0 ? { key: value.bind.key } : {},
|
|
3642
|
+
...value.bind.repeatPlanId !== void 0 ? { repeatPlanId: value.bind.repeatPlanId } : {},
|
|
3643
|
+
...value.bind.collectionSlot !== void 0 ? { collectionSlot: value.bind.collectionSlot } : {}
|
|
3629
3644
|
},
|
|
3630
|
-
show: parseShowMapping(value.show, `${currentPath}.show
|
|
3645
|
+
show: parseShowMapping(value.show, `${currentPath}.show`, options),
|
|
3631
3646
|
// when 与 bind 同处一层:整块显隐(列表在错误/加载态整体隐藏靠它)
|
|
3632
3647
|
...typeof value.when === "string" ? { when: value.when } : {}
|
|
3633
3648
|
};
|
|
3649
|
+
if (value.props !== void 0) {
|
|
3650
|
+
if (!value.props || typeof value.props !== "object" || Array.isArray(value.props)) {
|
|
3651
|
+
throw new SomaUiConfigError("props \u5FC5\u987B\u662F\u5BF9\u8C61", currentPath);
|
|
3652
|
+
}
|
|
3653
|
+
nested.props = { ...value.props };
|
|
3654
|
+
}
|
|
3634
3655
|
result[key] = nested;
|
|
3635
3656
|
} else if (typeof value === "object" && value !== null && isExtendedShowValue(value)) {
|
|
3636
3657
|
const extended = {};
|
|
@@ -3681,7 +3702,7 @@ function parseShowMapping(rawShow, path) {
|
|
|
3681
3702
|
extended.class = classMap;
|
|
3682
3703
|
}
|
|
3683
3704
|
if ("show" in value && value.show !== void 0) {
|
|
3684
|
-
extended.show = parseShowMapping(value.show, `${currentPath}.show
|
|
3705
|
+
extended.show = parseShowMapping(value.show, `${currentPath}.show`, options);
|
|
3685
3706
|
}
|
|
3686
3707
|
if ("props" in value && value.props !== void 0) {
|
|
3687
3708
|
if (typeof value.props !== "object" || value.props === null || Array.isArray(value.props)) {
|
|
@@ -3737,7 +3758,10 @@ function parseUiConfig(raw, options) {
|
|
|
3737
3758
|
if (Array.isArray(raw.bind.onChange)) {
|
|
3738
3759
|
bind.onChange = parseOnChangeRules(raw.bind.onChange, "bind.onChange");
|
|
3739
3760
|
}
|
|
3740
|
-
|
|
3761
|
+
if (raw.bind.key !== void 0 || raw.bind.repeatPlanId !== void 0 || raw.bind.collectionSlot !== void 0) {
|
|
3762
|
+
throw new SomaUiConfigError("\u9876\u5C42 bind \u4E0D\u63A5\u53D7\u96C6\u5408\u884C\u5B57\u6BB5", "bind");
|
|
3763
|
+
}
|
|
3764
|
+
const show = parseShowMapping(raw.show, "show", options);
|
|
3741
3765
|
const config = { bind, show };
|
|
3742
3766
|
if ("initProps" in raw && raw.initProps !== void 0) {
|
|
3743
3767
|
config.initProps = parseInitProps(raw.initProps, "initProps");
|
|
@@ -30,6 +30,9 @@ import {
|
|
|
30
30
|
type SomaComponentContract,
|
|
31
31
|
} from '../../shared/types/component-contract.types';
|
|
32
32
|
import type { SomaComponentDefinition } from '../../client/component/component-definition.types';
|
|
33
|
+
import { prepareComponentTreeDefinitions } from '../component-tree/definition-preparation';
|
|
34
|
+
import { canonicalTreeData } from '../component-tree/artifact-codec';
|
|
35
|
+
import type { ComponentTreeRegistryEntry } from '../component-tree/registry-snapshot';
|
|
33
36
|
|
|
34
37
|
export class SomaComponentPackageError extends Error {
|
|
35
38
|
/**
|
|
@@ -56,6 +59,8 @@ export interface PackScanWarning {
|
|
|
56
59
|
}
|
|
57
60
|
|
|
58
61
|
export interface LoadPackagesOptions {
|
|
62
|
+
/** Actual composed external dependencies for trusted collection preparation. */
|
|
63
|
+
componentTreeDependencies?: readonly ComponentTreeRegistryEntry[];
|
|
59
64
|
/**
|
|
60
65
|
* 警告汇总回调(缺省时汇总为单块 console.warn)。
|
|
61
66
|
* 刻意做成"扫描结束一次性给全部"而不是逐条打印:dev 服务器的滚动输出里,
|
|
@@ -74,8 +79,10 @@ interface PackageEntry {
|
|
|
74
79
|
}
|
|
75
80
|
|
|
76
81
|
/** 装载单个组件包目录 → 运行时定义(结构校验 fail fast) */
|
|
77
|
-
export function loadComponentPackage(packageDir: string): SomaComponentDefinition {
|
|
78
|
-
|
|
82
|
+
export function loadComponentPackage(packageDir: string, options: LoadPackagesOptions = {}): SomaComponentDefinition {
|
|
83
|
+
const entry = loadComponentPackageEntry(packageDir);
|
|
84
|
+
preparePackageEntries([entry], options);
|
|
85
|
+
return entry.definition;
|
|
79
86
|
}
|
|
80
87
|
|
|
81
88
|
/** 装载单个组件包目录 → 定义 + 样式 + 警告(供整包装载复用) */
|
|
@@ -94,16 +101,26 @@ export function loadComponentPackageEntry(packageDir: string): PackageEntry {
|
|
|
94
101
|
const contract = validateContract(rawContract, packageDir);
|
|
95
102
|
|
|
96
103
|
const templateHtml = fs.readFileSync(templatePath, 'utf-8').trim();
|
|
97
|
-
if (!templateHtml) {
|
|
104
|
+
if (!templateHtml && contract.structure?.kind !== 'fragment-macro') {
|
|
98
105
|
throw new SomaComponentPackageError('template.html 为空', packageDir);
|
|
99
106
|
}
|
|
100
107
|
|
|
101
108
|
const definition: SomaComponentDefinition = { contract, templateHtml };
|
|
109
|
+
const metadataPath = path.join(packageDir, 'definition.yaml');
|
|
110
|
+
if (fs.existsSync(metadataPath)) {
|
|
111
|
+
const raw = canonicalTreeData(yaml.load(fs.readFileSync(metadataPath, 'utf-8')));
|
|
112
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)
|
|
113
|
+
|| Object.keys(raw).some(key => !['structureAdapter', 'collectionSources'].includes(key))) {
|
|
114
|
+
throw new SomaComponentPackageError('definition.yaml 仅接受 structureAdapter/collectionSources 纯实现元信息', packageDir);
|
|
115
|
+
}
|
|
116
|
+
if (raw.structureAdapter !== undefined) definition.structureAdapter = raw.structureAdapter as unknown as SomaComponentDefinition['structureAdapter'];
|
|
117
|
+
if (raw.collectionSources !== undefined) definition.collectionSources = raw.collectionSources as unknown as SomaComponentDefinition['collectionSources'];
|
|
118
|
+
}
|
|
102
119
|
|
|
103
120
|
const uiPath = path.join(packageDir, 'ui.yaml');
|
|
104
121
|
if (fs.existsSync(uiPath)) {
|
|
105
122
|
try {
|
|
106
|
-
definition.uiConfig = parseUiConfig(yaml.load(fs.readFileSync(uiPath, 'utf-8')));
|
|
123
|
+
definition.uiConfig = parseUiConfig(yaml.load(fs.readFileSync(uiPath, 'utf-8')), { collectionBindingStage: 'definition-source' });
|
|
107
124
|
} catch (error) {
|
|
108
125
|
throw new SomaComponentPackageError(
|
|
109
126
|
`ui.yaml 非法: ${(error as Error).message}`,
|
|
@@ -193,9 +210,23 @@ export function scanComponentPackages(
|
|
|
193
210
|
}
|
|
194
211
|
|
|
195
212
|
reportWarnings(rootDir, entries.length, warnings, options.onWarning);
|
|
213
|
+
preparePackageEntries(entries, options);
|
|
196
214
|
return entries;
|
|
197
215
|
}
|
|
198
216
|
|
|
217
|
+
function preparePackageEntries(entries: PackageEntry[], options: LoadPackagesOptions): void {
|
|
218
|
+
const hasCollection = (value: unknown): boolean => {
|
|
219
|
+
if (!value || typeof value !== 'object') return false;
|
|
220
|
+
if ('collectionSlot' in value || 'repeatPlanId' in value) return true;
|
|
221
|
+
return Object.values(value).some(hasCollection);
|
|
222
|
+
};
|
|
223
|
+
if (!entries.some(entry => entry.definition.contract.structure || hasCollection(entry.definition.uiConfig))) return;
|
|
224
|
+
const all = [...(options.componentTreeDependencies ?? []), ...entries.map(entry => ({ definition: entry.definition }))];
|
|
225
|
+
const prepared = prepareComponentTreeDefinitions(all);
|
|
226
|
+
const byName = new Map(prepared.definitions.map(definition => [definition.contract.name, definition]));
|
|
227
|
+
for (const entry of entries) entry.definition = byName.get(entry.definition.contract.name)!;
|
|
228
|
+
}
|
|
229
|
+
|
|
199
230
|
/** 一次性汇总输出:逐条 warn 会淹没在 dev 服务器的滚动输出里 */
|
|
200
231
|
function reportWarnings(
|
|
201
232
|
rootDir: string,
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import yaml from 'js-yaml';
|
|
3
|
+
import { parseUiConfig } from '../../client/parser/ui-config-parser';
|
|
4
|
+
import { compileDataConfig, compileEventConfig } from '../compiler/soma-precompile';
|
|
5
|
+
import { assertRuntimeArtifact } from '../../shared/component-tree-artifact';
|
|
6
|
+
import { SomaComponentTreeError } from '../../shared/component-tree-errors';
|
|
7
|
+
import type { ComponentTreeRuntimeEnvelope, TreeArtifact } from '../../shared/types/component-tree-artifact.types';
|
|
8
|
+
import type { SomaPageMarkup, TreeCompileContext } from '../../shared/types/component-tree.types';
|
|
9
|
+
|
|
10
|
+
/** Increment whenever the tree lowering or logical artifact protocol changes. */
|
|
11
|
+
export const TREE_COMPILER_VERSION = 'component-tree:1.0.0';
|
|
12
|
+
|
|
13
|
+
export interface RuntimeConfigInput {
|
|
14
|
+
uiConfig?: unknown;
|
|
15
|
+
uiYaml?: string;
|
|
16
|
+
eventConfig?: unknown;
|
|
17
|
+
eventYaml?: string;
|
|
18
|
+
triggers?: unknown;
|
|
19
|
+
triggerConfig?: unknown;
|
|
20
|
+
timers?: unknown;
|
|
21
|
+
timerConfig?: unknown;
|
|
22
|
+
dataConfig?: unknown;
|
|
23
|
+
dataYaml?: string;
|
|
24
|
+
styleConfig?: unknown;
|
|
25
|
+
styleYaml?: string;
|
|
26
|
+
layoutCss?: string;
|
|
27
|
+
oouiArtifact?: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface TreeCompileKeyInput {
|
|
31
|
+
html: string;
|
|
32
|
+
uiYaml: string;
|
|
33
|
+
markup?: SomaPageMarkup;
|
|
34
|
+
grammarVersion?: number;
|
|
35
|
+
treeContext: TreeCompileContext;
|
|
36
|
+
externalBlocks?: ReadonlyMap<string, string>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type Data = null | boolean | number | string | Data[] | { [key: string]: Data };
|
|
40
|
+
type DataRecord = { [key: string]: Data };
|
|
41
|
+
|
|
42
|
+
function fail(path: string): never {
|
|
43
|
+
throw new SomaComponentTreeError({
|
|
44
|
+
code: 'CT-ARTIFACT-INCOMPLETE', phase: 'artifact', sourceId: '<runtime-assets>', nodePath: path,
|
|
45
|
+
fixHint: '运行时资产存在缺项、混合副本或非纯数据;请从同一份源与受信上下文重编。',
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Canonical JSON: ordered keys, unchanged strings/array order, no getters or cycles. */
|
|
50
|
+
export function canonicalTreeData(value: unknown): Data {
|
|
51
|
+
const active = new Set<object>();
|
|
52
|
+
let nodes = 0;
|
|
53
|
+
const visit = (item: unknown, depth: number): Data => {
|
|
54
|
+
if (++nodes > 131072 || depth > 96) fail('data.limit');
|
|
55
|
+
if (item === null || typeof item === 'string' || typeof item === 'boolean') return item;
|
|
56
|
+
if (typeof item === 'number' && Number.isFinite(item)) return item;
|
|
57
|
+
if (!item || typeof item !== 'object' || active.has(item)) fail('data');
|
|
58
|
+
if (!Array.isArray(item) && ![Object.prototype, null].includes(Object.getPrototypeOf(item))) fail('data');
|
|
59
|
+
active.add(item);
|
|
60
|
+
const result: Data[] | DataRecord = Array.isArray(item) ? [] : {};
|
|
61
|
+
const keys = Array.isArray(item) ? Array.from({ length: item.length }, (_, i) => String(i)) : Object.keys(item).sort();
|
|
62
|
+
for (const key of keys) {
|
|
63
|
+
if (['__proto__', 'prototype', 'constructor'].includes(key)) fail('data.key');
|
|
64
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, key);
|
|
65
|
+
if (!descriptor || !('value' in descriptor)) fail('data.property');
|
|
66
|
+
if (descriptor.value === undefined && !Array.isArray(item)) continue;
|
|
67
|
+
const child = visit(descriptor.value, depth + 1);
|
|
68
|
+
if (Array.isArray(result)) result.push(child); else result[key] = child;
|
|
69
|
+
}
|
|
70
|
+
active.delete(item);
|
|
71
|
+
return result;
|
|
72
|
+
};
|
|
73
|
+
return visit(value, 0);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function digestTreeData(value: unknown): string {
|
|
77
|
+
return createHash('sha256').update(JSON.stringify(canonicalTreeData(value)), 'utf8').digest('hex');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function record(value: unknown): Record<string, unknown> {
|
|
81
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) fail('config');
|
|
82
|
+
return value as Record<string, unknown>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function same(a: unknown, b: unknown, path: string): unknown {
|
|
86
|
+
if (a !== undefined && b !== undefined && digestTreeData(a) !== digestTreeData(b)) fail(path);
|
|
87
|
+
return a ?? b;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function normalizeUi(raw: unknown, input: RuntimeConfigInput): Data {
|
|
91
|
+
const value = record(canonicalTreeData(raw));
|
|
92
|
+
delete value.layout;
|
|
93
|
+
delete value.ooui;
|
|
94
|
+
const layoutCss = same(same(value.layoutCss, value.layout_css, 'ui.layoutCss'), input.layoutCss, 'layoutCss');
|
|
95
|
+
const oouiArtifact = same(same(value.oouiArtifact, value.ooui_artifact, 'ui.oouiArtifact'), input.oouiArtifact, 'oouiArtifact');
|
|
96
|
+
delete value.layoutCss;
|
|
97
|
+
delete value.oouiArtifact;
|
|
98
|
+
if (layoutCss !== undefined) value.layout_css = layoutCss;
|
|
99
|
+
if (oouiArtifact !== undefined) value.ooui_artifact = oouiArtifact;
|
|
100
|
+
return canonicalTreeData(parseUiConfig(value, { adaptiveVocabularyRequired: false }));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Pure artifact decoding. Never instantiates a Domain or falls back to Host configuration. */
|
|
104
|
+
export function normalizeRuntimeConfig(input: RuntimeConfigInput): Data {
|
|
105
|
+
try {
|
|
106
|
+
// Read a descriptor-only clone before invoking any parser.
|
|
107
|
+
const safe = record(canonicalTreeData(input)) as RuntimeConfigInput;
|
|
108
|
+
if (safe.styleYaml?.trim() || (safe.styleConfig !== undefined && safe.styleConfig !== null
|
|
109
|
+
&& Object.keys(record(safe.styleConfig)).length > 0)) fail('style');
|
|
110
|
+
const objectUi = safe.uiConfig === undefined ? undefined : normalizeUi(safe.uiConfig, safe);
|
|
111
|
+
const yamlUi = safe.uiYaml === undefined ? undefined : normalizeUi(yaml.load(safe.uiYaml), safe);
|
|
112
|
+
const ui = same(objectUi, yamlUi, 'ui');
|
|
113
|
+
if (ui === undefined) fail('ui');
|
|
114
|
+
const triggers = same(safe.triggers, safe.triggerConfig, 'event.triggers');
|
|
115
|
+
const timers = same(safe.timers, safe.timerConfig, 'event.timers');
|
|
116
|
+
const objectEvent = safe.eventConfig === undefined ? undefined : {
|
|
117
|
+
events: safe.eventConfig, triggers: triggers ?? [], timers: timers ?? [],
|
|
118
|
+
};
|
|
119
|
+
if (objectEvent && (!Array.isArray(objectEvent.events) || !Array.isArray(objectEvent.triggers) || !Array.isArray(objectEvent.timers))) fail('event');
|
|
120
|
+
const yamlEvent = safe.eventYaml === undefined ? undefined : compileEventConfig(safe.eventYaml);
|
|
121
|
+
if (yamlEvent) {
|
|
122
|
+
same(triggers, yamlEvent.triggers, 'event.triggers');
|
|
123
|
+
same(timers, yamlEvent.timers, 'event.timers');
|
|
124
|
+
}
|
|
125
|
+
if (objectEvent === undefined && yamlEvent === undefined && (triggers !== undefined || timers !== undefined)) fail('event');
|
|
126
|
+
const event = same(objectEvent, yamlEvent, 'event') ?? { events: [], triggers: [], timers: [] };
|
|
127
|
+
const data = same(safe.dataConfig, safe.dataYaml === undefined ? undefined : compileDataConfig(safe.dataYaml), 'data') ?? { objects: {} };
|
|
128
|
+
return canonicalTreeData({ ui, event, data });
|
|
129
|
+
} catch (error) {
|
|
130
|
+
if (error instanceof SomaComponentTreeError) throw error;
|
|
131
|
+
// YAML and expression parser errors may contain source/business values.
|
|
132
|
+
fail('config');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function treeContextIdentity(context: TreeCompileContext): {
|
|
137
|
+
registrySnapshotDigest: string; policyDigest: string; assetSupplyKey: string;
|
|
138
|
+
} {
|
|
139
|
+
if (!context?.registrySnapshot?.digest || !context.compositionPolicy) fail('context');
|
|
140
|
+
if (context.assetSupplyKey !== undefined && (typeof context.assetSupplyKey !== 'string' || !context.assetSupplyKey.trim())) fail('context.supply');
|
|
141
|
+
return {
|
|
142
|
+
registrySnapshotDigest: context.registrySnapshot.digest,
|
|
143
|
+
policyDigest: digestTreeData({ policy: context.compositionPolicy, limits: context.limits ?? {}, sources: context.collectionSources ?? [] }),
|
|
144
|
+
assetSupplyKey: context.assetSupplyKey ?? digestTreeData({
|
|
145
|
+
registry: context.registrySnapshot.digest,
|
|
146
|
+
packs: Object.values(context.registrySnapshot.components).map(entry => ({ name: entry.name, packName: entry.packName, packVersion: entry.packVersion })).sort((a, b) => a.name.localeCompare(b.name)),
|
|
147
|
+
}),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function computeTreeSourceDigest(input: Pick<TreeCompileKeyInput, 'html' | 'uiYaml' | 'externalBlocks'>): string {
|
|
152
|
+
return digestTreeData({ html: input.html, uiYaml: input.uiYaml,
|
|
153
|
+
externalBlocks: [...(input.externalBlocks ?? [])].sort(([a], [b]) => a.localeCompare(b)),
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function computeTreeCompileKey(input: TreeCompileKeyInput): string {
|
|
158
|
+
if (input.markup !== 'component-tree' || input.grammarVersion !== 1) fail('sourceMarkup');
|
|
159
|
+
return digestTreeData({ sourceDigest: computeTreeSourceDigest(input), compilerVersion: TREE_COMPILER_VERSION,
|
|
160
|
+
grammarVersion: 1, ...treeContextIdentity(input.treeContext) });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function sealTreeRuntimeAssets(input: RuntimeConfigInput & {
|
|
164
|
+
sourceMarkup: 'component-tree'; html: string; artifact: Omit<TreeArtifact, 'artifactDigest'>;
|
|
165
|
+
}): TreeArtifact {
|
|
166
|
+
const artifact = { ...input.artifact, artifactDigest: digestTreeData({
|
|
167
|
+
sourceMarkup: input.sourceMarkup, html: input.html, runtimeConfig: normalizeRuntimeConfig(input),
|
|
168
|
+
artifactWithoutDigest: input.artifact,
|
|
169
|
+
}) };
|
|
170
|
+
assertRuntimeArtifact({ ...input, artifact });
|
|
171
|
+
return artifact;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function verifyTreeRuntimeAssets(
|
|
175
|
+
input: ComponentTreeRuntimeEnvelope & RuntimeConfigInput,
|
|
176
|
+
source?: TreeCompileKeyInput,
|
|
177
|
+
): boolean {
|
|
178
|
+
try {
|
|
179
|
+
assertRuntimeArtifact(input);
|
|
180
|
+
if (input.sourceMarkup !== 'component-tree' || !input.artifact || input.html === undefined) return false;
|
|
181
|
+
const { artifactDigest, ...artifact } = input.artifact;
|
|
182
|
+
if (artifact.compilerVersion !== TREE_COMPILER_VERSION) return false;
|
|
183
|
+
if (source) {
|
|
184
|
+
if (source.markup !== 'component-tree' || source.grammarVersion !== 1
|
|
185
|
+
|| artifact.sourceDigest !== computeTreeSourceDigest(source)) return false;
|
|
186
|
+
const identity = treeContextIdentity(source.treeContext);
|
|
187
|
+
if (artifact.registrySnapshotDigest !== identity.registrySnapshotDigest
|
|
188
|
+
|| artifact.policyDigest !== identity.policyDigest || artifact.assetSupplyKey !== identity.assetSupplyKey) return false;
|
|
189
|
+
}
|
|
190
|
+
return artifactDigest === sealTreeRuntimeAssets({ ...input, sourceMarkup: 'component-tree', html: input.html, artifact }).artifactDigest;
|
|
191
|
+
} catch { return false; }
|
|
192
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import yaml from 'js-yaml';
|
|
2
|
+
import { parseSomaBlockContainer } from '../blocks/block-container';
|
|
3
|
+
import type { CompileSomaBlocksInput } from '../blocks/block-compile';
|
|
4
|
+
import type { HtmlAnchorInfo } from '../blocks/html-index';
|
|
5
|
+
import { SomaComponentTreeError, type ComponentTreeErrorCode } from '../../shared/component-tree-errors';
|
|
6
|
+
import type { ComponentNode, RepeatNode, TreeNode, TreeCompileContext, TreeValidationResult, ComponentTreeTrace } from '../../shared/types/component-tree.types';
|
|
7
|
+
import type { ComponentRef, RepeatPlan, StructurePlan } from '../../shared/types/component-tree-artifact.types';
|
|
8
|
+
import type { SomaContractField, SomaStructureSemanticToken } from '../../shared/types/component-contract.types';
|
|
9
|
+
import { canonicalTreeData } from './artifact-codec';
|
|
10
|
+
import { lowerCollectionBinding } from './collection-binding-lowerer';
|
|
11
|
+
|
|
12
|
+
type RecordValue = Record<string, unknown>;
|
|
13
|
+
type Scope = {
|
|
14
|
+
symbols: Record<string, string>; blocks: RecordValue; used: Set<string>;
|
|
15
|
+
aliases: Map<string, SomaContractField>; parentRepeat?: RepeatPlan;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const TAGS: Record<SomaStructureSemanticToken, string> = {
|
|
19
|
+
root: 'div', div: 'div', flow: 'div', none: 'div', main: 'main', section: 'section',
|
|
20
|
+
article: 'article', aside: 'aside', header: 'header', footer: 'footer', nav: 'nav',
|
|
21
|
+
navigation: 'nav', complementary: 'aside', contentinfo: 'footer', region: 'section', unordered: 'ul', ordered: 'ol',
|
|
22
|
+
};
|
|
23
|
+
const attr = (value: string): string => value.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>');
|
|
24
|
+
|
|
25
|
+
export interface TreeBindingResult {
|
|
26
|
+
html: string;
|
|
27
|
+
uiYaml: string;
|
|
28
|
+
treeBindings: NonNullable<CompileSomaBlocksInput['treeBindings']>;
|
|
29
|
+
structurePlan: StructurePlan[];
|
|
30
|
+
repeatPlans: RepeatPlan[];
|
|
31
|
+
componentRefs: ComponentRef[];
|
|
32
|
+
effectiveParents: ReadonlyMap<string, string | undefined>;
|
|
33
|
+
trace: ComponentTreeTrace;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** AST-owned scopes, canonical rows, lowering and escaped HTML share one symbol table. */
|
|
37
|
+
export function bindComponentTree(
|
|
38
|
+
validated: TreeValidationResult,
|
|
39
|
+
input: { uiYaml: string; externalBlocks?: ReadonlyMap<string, string>; treeContext: TreeCompileContext },
|
|
40
|
+
): TreeBindingResult {
|
|
41
|
+
const { tree } = validated;
|
|
42
|
+
const registry = input.treeContext.registrySnapshot.components;
|
|
43
|
+
const fail: (code: ComponentTreeErrorCode, path: string, hint: string) => never = (code, path, hint) => { throw new SomaComponentTreeError({
|
|
44
|
+
code, phase: 'bind', sourceId: tree.sourceId, nodePath: path, fixHint: hint,
|
|
45
|
+
}); };
|
|
46
|
+
const record = (value: unknown, path: string): RecordValue => {
|
|
47
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) fail('CT-BINDING-SCOPE', path, '声明必须是映射。');
|
|
48
|
+
return value as RecordValue;
|
|
49
|
+
};
|
|
50
|
+
const source = { ...parseSomaBlockContainer(input.uiYaml).doc };
|
|
51
|
+
for (const [name, text] of input.externalBlocks ?? []) {
|
|
52
|
+
if (Object.hasOwn(source, name)) fail('CT-BINDING-DUPLICATE', 'canonical', '同一实例不能同时存在内联与外置声明。');
|
|
53
|
+
try { source[name] = record(yaml.load(text), name); } catch { fail('CT-BINDING-SCOPE', 'canonical', '外置块必须是合法 YAML 映射。'); }
|
|
54
|
+
}
|
|
55
|
+
const doc = record(canonicalTreeData(source), 'canonical');
|
|
56
|
+
const page = record(doc.page, 'page');
|
|
57
|
+
// Page-level raw DOM writes have no targets in this source language.
|
|
58
|
+
if (page.ui && Object.keys(record(page.ui, 'page.ui')).length) fail('CT-BINDING-SCOPE', 'page.ui', '组件宿主只通过自己的 props/when/emits 绑定,不接受原生 text/class/attr/each 旁路。');
|
|
59
|
+
if (page.locale && (!Array.isArray(page.locale) || page.locale.length)) fail('CT-BINDING-SCOPE', 'page.locale', '文字应通过组件 text/label 等契约属性绑定。');
|
|
60
|
+
if (page.ooui !== undefined) fail('CT-BINDING-SCOPE', 'page.ooui', '组件树结构由显式树负责,不能同时生成第二份结构。');
|
|
61
|
+
const normalized: RecordValue = { page };
|
|
62
|
+
const anchors = new Map<string, HtmlAnchorInfo>();
|
|
63
|
+
const instances = new Set<string>();
|
|
64
|
+
const effectiveParents = new Map<string, string | undefined>();
|
|
65
|
+
const structures: StructurePlan[] = [];
|
|
66
|
+
const repeats: RepeatPlan[] = [];
|
|
67
|
+
const collections: NonNullable<CompileSomaBlocksInput['treeBindings']>['collections'][number][] = [];
|
|
68
|
+
const globalAliases = new Set<string>();
|
|
69
|
+
const refs = new Set<string>();
|
|
70
|
+
const traceSources: ComponentTreeTrace['sources'][number][] = [];
|
|
71
|
+
const traceEdges: ComponentTreeTrace['edges'][number][] = [];
|
|
72
|
+
let sequence = 0;
|
|
73
|
+
const collectAliases = (node: TreeNode): void => {
|
|
74
|
+
if (node.kind === 'repeat') { globalAliases.add(node.item); collectAliases(node.child); }
|
|
75
|
+
else for (const child of node.kind === 'component' ? node.slots : node.children) collectAliases(child);
|
|
76
|
+
};
|
|
77
|
+
collectAliases(tree.host);
|
|
78
|
+
const snapshot = (node: ComponentNode) => {
|
|
79
|
+
const entry = registry[node.component];
|
|
80
|
+
if (!entry?.contractDigest || !/^[a-f0-9]{64}$/.test(entry.structureDigest)) fail('CT-REGISTRY-CONTEXT', node.meta.nodePath, '组件树必须使用实际已准备定义生成的 Registry 快照。');
|
|
81
|
+
const visitRef = (name: string): void => { if (refs.has(name)) return; refs.add(name); for (const child of registry[name]?.contract.uses ?? []) visitRef(child); };
|
|
82
|
+
visitRef(node.component);
|
|
83
|
+
return entry;
|
|
84
|
+
};
|
|
85
|
+
const dynamic = (value: unknown, scope: Scope, body: RecordValue): boolean => {
|
|
86
|
+
if (typeof value !== 'string') return false;
|
|
87
|
+
const root = value.trim().replace(/^!/, '').split(/[.\s|]/)[0];
|
|
88
|
+
if ((globalAliases.has(root) && !scope.aliases.has(root)) || root === 'p' || root === 'ctrl') fail('CT-BINDING-SCOPE', 'ui', '绑定不能读取兄弟行或组件内部作用域。');
|
|
89
|
+
return root === 'page' || scope.aliases.has(root) || Object.hasOwn((body.alias as RecordValue) ?? {}, root) || Object.hasOwn((body.data as RecordValue) ?? {}, root);
|
|
90
|
+
};
|
|
91
|
+
const validateValue = (value: unknown, field: SomaContractField, scope: Scope, body: RecordValue, path: string): void => {
|
|
92
|
+
// Closed enum vocabulary wins over coincidentally named Domain/row aliases.
|
|
93
|
+
if (field.type === 'enum' && field.values?.some(item => item === value)) return;
|
|
94
|
+
if (dynamic(value, scope, body)) return;
|
|
95
|
+
const wrong = () => fail('CT-BINDING-SCOPE', path, '静态属性值必须符合当前组件契约类型和封闭字段;动态值使用可见的数据路径。');
|
|
96
|
+
if (field.type === 'enum') { if (!field.values?.some(item => item === value)) wrong(); }
|
|
97
|
+
else if (field.type === 'array') {
|
|
98
|
+
if (!Array.isArray(value)) wrong();
|
|
99
|
+
if (field.items) for (const item of value as unknown[]) validateValue(item, field.items, scope, body, path);
|
|
100
|
+
} else if (field.type === 'object') {
|
|
101
|
+
const object = record(value, path);
|
|
102
|
+
if (field.fields) {
|
|
103
|
+
for (const [key, item] of Object.entries(object)) {
|
|
104
|
+
if (!Object.hasOwn(field.fields, key)) wrong();
|
|
105
|
+
validateValue(item, field.fields[key], scope, body, path);
|
|
106
|
+
}
|
|
107
|
+
for (const [key, child] of Object.entries(field.fields)) if (child.required && !Object.hasOwn(object, key)) wrong();
|
|
108
|
+
}
|
|
109
|
+
} else if (typeof value !== field.type || (typeof value === 'number' && !Number.isFinite(value))) wrong();
|
|
110
|
+
};
|
|
111
|
+
const semantic = (node: ComponentNode, body: RecordValue, scope: Scope): { token?: SomaStructureSemanticToken; staticProps?: Record<string, string | boolean>; tag: string } => {
|
|
112
|
+
const entry = registry[node.component];
|
|
113
|
+
const semantics = entry.contract.structure?.semantics;
|
|
114
|
+
const props = record(body.ui ?? {}, `${node.id}.ui`);
|
|
115
|
+
let token = node.as as SomaStructureSemanticToken | undefined;
|
|
116
|
+
let staticProps: Record<string, string | boolean> | undefined;
|
|
117
|
+
if (semantics) {
|
|
118
|
+
const prop = semantics.staticProp;
|
|
119
|
+
if (prop) {
|
|
120
|
+
const explicit = Object.hasOwn(props, prop);
|
|
121
|
+
const value = props[prop];
|
|
122
|
+
const fromProp = explicit ? (prop === 'ordered' ? typeof value === 'boolean' ? value ? 'ordered' : 'unordered' : undefined : value) : undefined;
|
|
123
|
+
const literal = typeof fromProp === 'string' && semantics.allowed.includes(fromProp as SomaStructureSemanticToken);
|
|
124
|
+
if (explicit && !literal && dynamic(value, scope, body)) fail('CT-STRUCTURE-MOUNT', node.meta.nodePath, '结构语义只接受静态字面量,挂载后不可更换。');
|
|
125
|
+
if (explicit && (typeof fromProp !== 'string' || !semantics.allowed.includes(fromProp as SomaStructureSemanticToken))) fail('CT-STRUCTURE-MOUNT', node.meta.nodePath, '结构属性值不在受控语义集合。');
|
|
126
|
+
if (token && explicit && token !== fromProp) fail('CT-STRUCTURE-MOUNT', node.meta.nodePath, '树 as 与显式语义属性冲突。');
|
|
127
|
+
token ??= fromProp as SomaStructureSemanticToken | undefined;
|
|
128
|
+
token ??= semantics.default;
|
|
129
|
+
staticProps = { [prop]: prop === 'ordered' ? token === 'ordered' : token };
|
|
130
|
+
body.ui = { ...props, ...staticProps };
|
|
131
|
+
} else token ??= semantics.default;
|
|
132
|
+
}
|
|
133
|
+
return { ...(token ? { token } : {}), ...(staticProps ? { staticProps } : {}),
|
|
134
|
+
tag: entry.contract.structure?.tree_mount === 'legacy-host' ? 'div'
|
|
135
|
+
: token ? TAGS[token] : entry.contract.structure?.tree_mount === 'single-host' ? entry.templateRootTag ?? 'div' : 'div' };
|
|
136
|
+
};
|
|
137
|
+
const checkBlock = (node: ComponentNode, raw: unknown, scope: Scope): RecordValue => {
|
|
138
|
+
const body = { ...record(raw ?? {}, node.id) };
|
|
139
|
+
const contract = registry[node.component].contract;
|
|
140
|
+
if (scope.parentRepeat) {
|
|
141
|
+
for (const key of Object.keys(body)) if (!['component', 'alias', 'when', 'ui', 'event', 'rows'].includes(key)) fail('CT-BINDING-SCOPE', node.id, '行块只接受组件、别名、显隐、属性、emit 与嵌套 rows。');
|
|
142
|
+
if (body.event && Object.keys(record(body.event, `${node.id}.event`)).some(key => key !== 'on')) fail('CT-BINDING-SCOPE', node.id, '行块仅允许 event.on,不在每行定义动作或计时器。');
|
|
143
|
+
}
|
|
144
|
+
const props = record(body.ui ?? {}, `${node.id}.ui`);
|
|
145
|
+
for (const [key, value] of Object.entries(props)) {
|
|
146
|
+
if (!Object.hasOwn(contract.props ?? {}, key)) fail(['each', 'items', 'key', 'source', 'collectionSlot'].includes(key) && contract.structure?.slots?.item?.kind === 'collection' ? 'CT-BINDING-DUPLICATE' : 'CT-BINDING-SCOPE', `${node.id}.ui`, '只接受该组件契约 props;集合源只在 repeat 声明。');
|
|
147
|
+
validateValue(value, contract.props![key], scope, body, `${node.id}.ui.${key}`);
|
|
148
|
+
}
|
|
149
|
+
for (const [name, prop] of Object.entries(contract.props ?? {})) if (prop.required && prop.default === undefined && !Object.hasOwn(props, name)) fail('CT-BINDING-SCOPE', `${node.id}.ui`, '补齐组件契约要求的必填属性。');
|
|
150
|
+
if (body.event) for (const name of Object.keys(record(record(body.event, node.id).on ?? {}, node.id))) {
|
|
151
|
+
if (!Object.hasOwn(contract.emits ?? {}, name)) fail('CT-BINDING-SCOPE', `${node.id}.event.on`, '事件必须是当前组件契约声明的 emit。');
|
|
152
|
+
}
|
|
153
|
+
if (body.alias) for (const value of Object.values(record(body.alias, node.id))) dynamic(value, scope, {});
|
|
154
|
+
if (body.when) dynamic(body.when, scope, body);
|
|
155
|
+
return body;
|
|
156
|
+
};
|
|
157
|
+
const checkConstraints = (node: ComponentNode, body: RecordValue): void => {
|
|
158
|
+
const contract = registry[node.component].contract;
|
|
159
|
+
const props = { ...Object.fromEntries(Object.entries(contract.props ?? {}).map(([key, field]) => [key, field.default])), ...record(body.ui ?? {}, node.id) };
|
|
160
|
+
if (node.component === 'Box' && props.display === 'block' && props.gap !== 'none') fail('CT-STRUCTURE-MOUNT', node.id, 'Box 的 block 模式不支持 gap;使用 flex/grid 或 gap=none。');
|
|
161
|
+
if (node.component === 'Text' && ((props.truncate === true && (props.wrap !== 'none' || props.line_clamp !== 0))
|
|
162
|
+
|| (typeof props.line_clamp === 'number' && props.line_clamp !== 0 && (props.truncate === true || props.wrap === 'none')))) fail('CT-STRUCTURE-MOUNT', node.id, 'Text 的 truncate/wrap/line_clamp 组合互斥。');
|
|
163
|
+
if ((node.component === 'Box' && props.as === 'nav') || (node.component === 'Region' && ['navigation', 'region'].includes(String(props.landmark)))) {
|
|
164
|
+
if (typeof props.label !== 'string' || !props.label.trim()) fail('CT-STRUCTURE-MOUNT', node.id, '命名导航或区域必须声明非空 label。');
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
const assertUsed = (scope: Scope): void => {
|
|
168
|
+
for (const id of Object.keys(scope.blocks)) if (id !== 'page' && !scope.used.has(id)) fail('CT-BINDING-SCOPE', 'rows', 'canonical 块必须只引用当前页面或当前行作用域中的组件 id;宏不可寻址。');
|
|
169
|
+
};
|
|
170
|
+
const emit = (node: TreeNode, scope: Scope, parent?: string): string => {
|
|
171
|
+
if (node.kind === 'fragment') return node.children.map(child => emit(child, scope, parent)).join('');
|
|
172
|
+
if (node.kind !== 'component') fail('CT-SLOT-CONTRACT', node.meta.nodePath, '该位置只能发射普通组件或透明 Fragment。');
|
|
173
|
+
const entry = snapshot(node);
|
|
174
|
+
const macro = entry.contract.structure?.kind === 'fragment-macro';
|
|
175
|
+
if (macro) {
|
|
176
|
+
traceSources.push({ ...node.meta });
|
|
177
|
+
traceEdges.push({ fromId: node.meta.nodeId, relation: 'normalizes', toId: 'fragment-erasure' });
|
|
178
|
+
if (Object.hasOwn(scope.blocks, node.id)) fail('CT-STRUCTURE-MOUNT', node.id, 'Fragment 宏不接受运行时声明或寻址。');
|
|
179
|
+
return node.slots.flatMap(slot => slot.children).map(child => emit(child, scope, parent)).join('');
|
|
180
|
+
}
|
|
181
|
+
const symbol = scope.parentRepeat ? `__soma_tree_${scope.parentRepeat.scopeId}_${node.id}` : node.id;
|
|
182
|
+
traceSources.push({ ...node.meta, symbol });
|
|
183
|
+
traceEdges.push({ fromId: node.meta.nodeId, relation: 'derives', toId: symbol },
|
|
184
|
+
{ fromId: `contract:${node.component}:${entry.structureDigest}`, relation: 'verifies', toId: symbol });
|
|
185
|
+
if (parent) traceEdges.push({ fromId: parent, relation: 'projects', toId: symbol });
|
|
186
|
+
if (Object.hasOwn(scope.blocks, node.id)) traceEdges.push({ fromId: `canonical:${scope.parentRepeat?.scopeId ?? 'page'}:${node.id}`, relation: 'binds', toId: symbol });
|
|
187
|
+
scope.symbols[node.id] = symbol;
|
|
188
|
+
scope.used.add(node.id);
|
|
189
|
+
const body = checkBlock(node, scope.blocks[node.id], scope);
|
|
190
|
+
const resolved = semantic(node, body, scope);
|
|
191
|
+
checkConstraints(node, body);
|
|
192
|
+
anchors.set(symbol, { somaId: symbol, component: node.component, line: node.meta.span.startLine,
|
|
193
|
+
inRowTemplate: !!scope.parentRepeat, ...(scope.parentRepeat ? { rowRole: 'item', ownerList: scope.parentRepeat.consumerOwner.instanceSymbol } : {}) });
|
|
194
|
+
instances.add(symbol);
|
|
195
|
+
effectiveParents.set(symbol, parent);
|
|
196
|
+
const slotPlans = Object.entries(entry.contract.slots ?? {}).map(([name]) => {
|
|
197
|
+
const contract = entry.contract.structure?.slots?.[name];
|
|
198
|
+
return { name, kind: contract?.kind ?? 'projection' as const, ownerSymbol: symbol,
|
|
199
|
+
...(contract?.layoutRoot ? { layoutRootKey: contract.layoutRoot } : {}), directChildren: contract?.directChildren ?? false,
|
|
200
|
+
...(contract?.rowContainer ? { rowContainer: contract.rowContainer } : {}) };
|
|
201
|
+
});
|
|
202
|
+
const mount = entry.contract.structure?.tree_mount ?? 'legacy-host';
|
|
203
|
+
if (mount === 'erase') fail('CT-STRUCTURE-MOUNT', node.id, '宏不应生成运行时实例。');
|
|
204
|
+
structures.push({ instanceSymbol: symbol, componentName: node.component, mountMode: mount,
|
|
205
|
+
hostTag: resolved.tag, ...(resolved.token ? { semanticToken: resolved.token } : {}), slotPlans,
|
|
206
|
+
structureDigest: entry.structureDigest, ...(entry.internalRootId ? { internalRootId: entry.internalRootId } : {}),
|
|
207
|
+
...(resolved.staticProps ? { staticProps: resolved.staticProps } : {}) });
|
|
208
|
+
const rows = record(body.rows ?? {}, `${node.id}.rows`);
|
|
209
|
+
for (const slot of Object.keys(rows)) if (entry.contract.structure?.slots?.[slot]?.kind !== 'collection') fail('CT-BINDING-SCOPE', `${node.id}.rows`, 'rows 只能声明当前组件的 collection slot。');
|
|
210
|
+
delete body.rows;
|
|
211
|
+
if (Object.keys(body).length) normalized[symbol] = body;
|
|
212
|
+
const content = node.slots.map(slot => {
|
|
213
|
+
const slotContract = entry.contract.structure?.slots?.[slot.name];
|
|
214
|
+
let children: string;
|
|
215
|
+
if (slotContract?.kind === 'collection') {
|
|
216
|
+
const flat = (nodes: TreeNode[]): TreeNode[] => nodes.flatMap(child => child.kind === 'fragment' ? flat(child.children)
|
|
217
|
+
: child.kind === 'component' && registry[child.component].contract.structure?.kind === 'fragment-macro' ? flat(child.slots.flatMap(item => item.children)) : [child]);
|
|
218
|
+
const repeat = flat(slot.children)[0] as RepeatNode;
|
|
219
|
+
const id = ++sequence;
|
|
220
|
+
let sources = input.treeContext.collectionSources ?? [];
|
|
221
|
+
const [head, ...tail] = repeat.source.split('.');
|
|
222
|
+
let field = scope.aliases.get(head);
|
|
223
|
+
for (const part of tail) field = field?.type === 'object' ? field.fields?.[part] : undefined;
|
|
224
|
+
if (scope.aliases.has(head) && field?.type === 'array' && field.items) sources = [{ path: repeat.source, item: field.items, statusPlan: { kind: 'sync' } }];
|
|
225
|
+
const descriptor = sources.find(item => item.path === repeat.source);
|
|
226
|
+
if (!descriptor) fail('CT-REPEAT-SOURCE', repeat.meta.nodePath, '集合源缺少可信元素类型。');
|
|
227
|
+
const plan = lowerCollectionBinding({ planId: `repeat_${id}`, scopeId: `row_${id}`,
|
|
228
|
+
...(scope.parentRepeat ? { parentPlanId: scope.parentRepeat.planId } : {}),
|
|
229
|
+
sourcePath: repeat.source, itemAlias: repeat.item, keyPath: repeat.key,
|
|
230
|
+
declarationScope: { kind: 'page', ownerSymbol: 'page', readerRoot: tree.host.name, emitOwnerSymbol: 'page',
|
|
231
|
+
...(scope.parentRepeat ? { parentScopeId: scope.parentRepeat.scopeId } : {}) },
|
|
232
|
+
consumerOwner: { instanceSymbol: symbol, componentName: node.component, slotName: slot.name,
|
|
233
|
+
layoutRootKey: slotContract.layoutRoot!, rowContainer: slotContract.rowContainer! },
|
|
234
|
+
rowTemplateId: `template_${id}`, localSymbols: {}, collectionSources: sources, limits: input.treeContext.limits });
|
|
235
|
+
repeats.push(plan);
|
|
236
|
+
traceSources.push({ ...repeat.meta, symbol: plan.planId });
|
|
237
|
+
traceEdges.push({ fromId: repeat.meta.nodeId, relation: 'derives', toId: plan.planId },
|
|
238
|
+
{ fromId: plan.planId, relation: 'scopes', toId: plan.scopeId },
|
|
239
|
+
{ fromId: plan.planId, relation: 'consumes', toId: symbol });
|
|
240
|
+
collections.push({ symbol, ...(scope.parentRepeat ? { parentSymbol: scope.parentRepeat.consumerOwner.instanceSymbol } : {}),
|
|
241
|
+
bind: { obj: plan.sourcePath, var: plan.itemAlias, repeatPlanId: plan.planId } });
|
|
242
|
+
const childScope: Scope = { symbols: plan.localSymbols, blocks: record(rows[slot.name] ?? {}, `${node.id}.rows.${slot.name}`),
|
|
243
|
+
used: new Set(), aliases: new Map(scope.aliases).set(repeat.item, descriptor.item), parentRepeat: plan };
|
|
244
|
+
const row = emit(repeat.child, childScope, `@${plan.planId}`);
|
|
245
|
+
assertUsed(childScope);
|
|
246
|
+
children = `<template data-soma-role="item" data-soma-repeat-template="${plan.rowTemplateId}">${row}</template>`;
|
|
247
|
+
} else {
|
|
248
|
+
const root = slotContract?.layoutRoot ? entry.structureAdapter?.layoutRoots[slotContract.layoutRoot] : undefined;
|
|
249
|
+
const effectiveParent = mount === 'single-host' && slotContract?.directChildren && root === entry.internalRootId ? symbol : `@${symbol}.${slot.name}`;
|
|
250
|
+
children = slot.children.map(child => emit(child, scope, effectiveParent)).join('');
|
|
251
|
+
}
|
|
252
|
+
return `<template data-soma-slot="${attr(slot.name)}">${children}</template>`;
|
|
253
|
+
}).join('');
|
|
254
|
+
return `<${resolved.tag} data-soma-component="${node.component}" data-soma-id="${attr(symbol)}" data-soma-tree-mount="${mount}">${content}</${resolved.tag}>`;
|
|
255
|
+
};
|
|
256
|
+
const scope: Scope = { symbols: {}, blocks: doc, used: new Set(), aliases: new Map() };
|
|
257
|
+
if (tree.host.id) anchors.set(tree.host.id, { somaId: tree.host.id, line: tree.host.meta.span.startLine, inRowTemplate: false });
|
|
258
|
+
const tag = TAGS[tree.host.as as SomaStructureSemanticToken];
|
|
259
|
+
const content = tree.host.children.map(child => emit(child, scope, tree.host.id)).join('');
|
|
260
|
+
assertUsed(scope);
|
|
261
|
+
const html = `<${tag} data-soma-host="${attr(tree.host.name)}"${tree.host.id ? ` data-soma-id="${attr(tree.host.id)}"` : ''}>${content}</${tag}>`;
|
|
262
|
+
// Explicit main landmarks are a page-wide obligation, including repeated static roots.
|
|
263
|
+
const main = (plan: StructurePlan): boolean => plan.hostTag === 'main' || plan.semanticToken === 'main';
|
|
264
|
+
if ((tag === 'main' ? 1 : 0) + structures.filter(main).length > 1) fail('CT-STRUCTURE-MOUNT', 'host', '页面只能有一个主 landmark,不能在重复行中制造多个 main。');
|
|
265
|
+
if (structures.some(plan => main(plan) && plan.instanceSymbol.startsWith('__soma_tree_'))) fail('CT-STRUCTURE-MOUNT', 'rows', '重复行不能声明 main landmark。');
|
|
266
|
+
return { html, uiYaml: `{{\n${yaml.dump(normalized, { noRefs: true, lineWidth: 120 })}}}\n`,
|
|
267
|
+
treeBindings: { htmlIndex: { anchors, instances, host: tree.host.name, duplicates: [] }, collections },
|
|
268
|
+
structurePlan: structures, repeatPlans: repeats, effectiveParents, trace: { sources: traceSources, edges: traceEdges },
|
|
269
|
+
componentRefs: [...refs].sort().map(name => ({ name, contractDigest: registry[name].contractDigest!, structureDigest: registry[name].structureDigest,
|
|
270
|
+
...(registry[name].packName ? { packName: registry[name].packName } : {}), ...(registry[name].packVersion ? { packVersion: registry[name].packVersion } : {}), uses: [...(registry[name].contract.uses ?? [])] })),
|
|
271
|
+
};
|
|
272
|
+
}
|