soma-core 1.5.0 → 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.
Files changed (133) hide show
  1. package/app/SomaPageClient.tsx +28 -9
  2. package/app/soma/manifest/route.ts +3 -0
  3. package/bin/migrate.cjs +71 -1
  4. package/bin/soma-lsp.cjs +8 -1
  5. package/core/build/blocks/block-compile.ts +23 -5
  6. package/core/build/compiler/full-manifest-builder.ts +15 -0
  7. package/core/build/compiler/page-assets.ts +17 -1
  8. package/core/build/compiler/page-declaration-compiler.ts +67 -11
  9. package/core/build/compiler/precompiled-manifest-loader.ts +7 -0
  10. package/core/build/compiler/soma-manifest-webpack-plugin.js +7 -0
  11. package/core/build/compiler/soma-precompile.js +30 -6
  12. package/core/build/component/package-loader.ts +35 -4
  13. package/core/build/component-tree/artifact-codec.ts +192 -0
  14. package/core/build/component-tree/binding-bridge.ts +272 -0
  15. package/core/build/component-tree/collection-binding-lowerer.ts +65 -0
  16. package/core/build/component-tree/definition-preparation.ts +320 -0
  17. package/core/build/component-tree/migration-files.ts +214 -0
  18. package/core/build/component-tree/migration.ts +170 -0
  19. package/core/build/component-tree/parser.ts +362 -0
  20. package/core/build/component-tree/registry-snapshot.ts +317 -0
  21. package/core/build/component-tree/source-preflight.ts +132 -0
  22. package/core/build/component-tree/structure-topology.ts +63 -0
  23. package/core/build/component-tree/validator.ts +318 -0
  24. package/core/build/layout/css-emitter.ts +14 -1
  25. package/core/build/lsp/component-tree-service.ts +79 -0
  26. package/core/build/lsp/component-tree.cjs +42 -0
  27. package/core/build/lsp/cross-file-diagnostics.cjs +15 -3
  28. package/core/build/lsp/extra-completion.cjs +7 -0
  29. package/core/client/compiler/manifest-compiler.ts +2 -0
  30. package/core/client/component/ai-catalog.ts +41 -3
  31. package/core/client/component/catalog-examples.ts +60 -0
  32. package/core/client/component/component-definition.types.ts +9 -0
  33. package/core/client/component/component-expander.ts +39 -8
  34. package/core/client/component/component-manager.ts +107 -16
  35. package/core/client/component/component-registry.ts +10 -1
  36. package/core/client/component/scoped-adapter.ts +29 -2
  37. package/core/client/component/structure-adapter.ts +207 -0
  38. package/core/client/component/verify-pack.ts +64 -1
  39. package/core/client/engine/asset-resolver.ts +1 -1
  40. package/core/client/engine/dom-renderer.ts +283 -0
  41. package/core/client/engine/event-engine.ts +28 -9
  42. package/core/client/engine/render-engine.ts +2 -0
  43. package/core/client/engine/row-range.ts +62 -0
  44. package/core/client/engine/row-scope.ts +77 -0
  45. package/core/client/engine/runtime-builder.ts +2 -0
  46. package/core/client/engine/soma-bootstrap.ts +146 -1
  47. package/core/client/parser/blocks/page-parser.ts +9 -2
  48. package/core/client/parser/ui-config-parser.ts +38 -6
  49. package/core/client/registry/declaration-renderer.ts +32 -24
  50. package/core/client/registry/remote-page.ts +1 -1
  51. package/core/client/theme/theme-engine.ts +61 -1
  52. package/core/client/validation/contract-validator.ts +1 -1
  53. package/core/index.ts +9 -1
  54. package/core/server/host/page-markup-config.ts +42 -0
  55. package/core/server/host/published-page-artifact-cache.ts +36 -4
  56. package/core/server/host/published-page-assets.ts +13 -7
  57. package/core/server/host/resolve-host-tree-context.ts +43 -0
  58. package/core/server/host/server-page-assets.ts +23 -4
  59. package/core/server/host/soma-page-compile.ts +10 -0
  60. package/core/server/page-declaration.ts +7 -0
  61. package/core/server/registry/declaration-precompiler.ts +35 -3
  62. package/core/server/registry/page-registry-repository.ts +31 -3
  63. package/core/server/registry/page-registry-store.ts +64 -7
  64. package/core/server/registry/publish-asset-pin.ts +6 -1
  65. package/core/server/registry/services/pages/Get.ts +11 -6
  66. package/core/server/registry/validation/compile-gate.ts +10 -1
  67. package/core/shared/component-tree-artifact.ts +237 -0
  68. package/core/shared/component-tree-errors.ts +52 -0
  69. package/core/shared/types/component-contract.types.ts +51 -0
  70. package/core/shared/types/component-tree-artifact.types.ts +121 -0
  71. package/core/shared/types/component-tree.types.ts +170 -0
  72. package/core/shared/types/engine.types.ts +5 -0
  73. package/core/shared/types/manifest.types.ts +4 -0
  74. package/core/shared/types/ui-config.types.ts +8 -0
  75. package/dist/cli/soma.js +1 -1
  76. package/dist/core/index.cjs +1976 -692
  77. package/dist/lsp/component-tree.cjs +20807 -0
  78. package/dist/types/build/blocks/block-compile.d.ts +10 -1
  79. package/dist/types/build/compiler/full-manifest-builder.d.ts +9 -0
  80. package/dist/types/build/compiler/page-assets.d.ts +6 -1
  81. package/dist/types/build/compiler/page-declaration-compiler.d.ts +11 -1
  82. package/dist/types/build/component/package-loader.d.ts +4 -1
  83. package/dist/types/build/component-tree/artifact-codec.d.ts +50 -0
  84. package/dist/types/build/component-tree/binding-bridge.d.ts +19 -0
  85. package/dist/types/build/component-tree/collection-binding-lowerer.d.ts +18 -0
  86. package/dist/types/build/component-tree/definition-preparation.d.ts +11 -0
  87. package/dist/types/build/component-tree/migration-files.d.ts +35 -0
  88. package/dist/types/build/component-tree/migration.d.ts +28 -0
  89. package/dist/types/build/component-tree/parser.d.ts +13 -0
  90. package/dist/types/build/component-tree/registry-snapshot.d.ts +15 -0
  91. package/dist/types/build/component-tree/source-preflight.d.ts +22 -0
  92. package/dist/types/build/component-tree/structure-topology.d.ts +7 -0
  93. package/dist/types/build/component-tree/validator.d.ts +9 -0
  94. package/dist/types/build/lsp/component-tree-service.d.ts +34 -0
  95. package/dist/types/client/component/ai-catalog.d.ts +18 -1
  96. package/dist/types/client/component/catalog-examples.d.ts +18 -0
  97. package/dist/types/client/component/component-definition.types.d.ts +9 -0
  98. package/dist/types/client/component/component-expander.d.ts +3 -1
  99. package/dist/types/client/component/component-manager.d.ts +11 -0
  100. package/dist/types/client/component/scoped-adapter.d.ts +1 -0
  101. package/dist/types/client/component/structure-adapter.d.ts +17 -0
  102. package/dist/types/client/engine/dom-renderer.d.ts +15 -0
  103. package/dist/types/client/engine/event-engine.d.ts +1 -0
  104. package/dist/types/client/engine/render-engine.d.ts +1 -0
  105. package/dist/types/client/engine/row-range.d.ts +13 -0
  106. package/dist/types/client/engine/row-scope.d.ts +20 -0
  107. package/dist/types/client/engine/runtime-builder.d.ts +1 -0
  108. package/dist/types/client/engine/soma-bootstrap.d.ts +4 -1
  109. package/dist/types/client/parser/ui-config-parser.d.ts +2 -0
  110. package/dist/types/client/registry/declaration-renderer.d.ts +5 -1
  111. package/dist/types/client/registry/remote-page.d.ts +1 -1
  112. package/dist/types/index.d.ts +3 -2
  113. package/dist/types/server/host/page-markup-config.d.ts +6 -0
  114. package/dist/types/server/host/published-page-artifact-cache.d.ts +9 -1
  115. package/dist/types/server/host/published-page-assets.d.ts +5 -3
  116. package/dist/types/server/host/resolve-host-tree-context.d.ts +8 -0
  117. package/dist/types/server/host/server-page-assets.d.ts +6 -0
  118. package/dist/types/server/host/soma-page-compile.d.ts +10 -1
  119. package/dist/types/server/page-declaration.d.ts +6 -0
  120. package/dist/types/server/registry/declaration-precompiler.d.ts +8 -3
  121. package/dist/types/server/registry/page-registry-repository.d.ts +5 -0
  122. package/dist/types/server/registry/page-registry-store.d.ts +11 -1
  123. package/dist/types/server/registry/publish-asset-pin.d.ts +4 -0
  124. package/dist/types/server/registry/validation/compile-gate.d.ts +4 -1
  125. package/dist/types/shared/component-tree-artifact.d.ts +5 -0
  126. package/dist/types/shared/component-tree-errors.d.ts +22 -0
  127. package/dist/types/shared/types/component-contract.types.d.ts +42 -0
  128. package/dist/types/shared/types/component-tree-artifact.types.d.ts +104 -0
  129. package/dist/types/shared/types/component-tree.types.d.ts +149 -0
  130. package/dist/types/shared/types/engine.types.d.ts +5 -0
  131. package/dist/types/shared/types/manifest.types.d.ts +4 -0
  132. package/dist/types/shared/types/ui-config.types.d.ts +8 -0
  133. package/package.json +3 -1
@@ -0,0 +1,65 @@
1
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
2
+ import type { SomaContractField } from '../../shared/types/component-contract.types';
3
+ import type { CollectionConsumerOwner, CollectionDeclarationScope, RepeatPlan } from '../../shared/types/component-tree-artifact.types';
4
+ import { DEFAULT_TREE_LIMITS, type TreeCollectionSource, type TreeLimits } from '../../shared/types/component-tree.types';
5
+ import { canonicalTreeData } from './artifact-codec';
6
+
7
+ export interface LowerCollectionBindingInput {
8
+ planId: string;
9
+ scopeId: string;
10
+ parentPlanId?: string;
11
+ sourcePath: string;
12
+ itemAlias: string;
13
+ keyPath: string;
14
+ declarationScope: CollectionDeclarationScope;
15
+ consumerOwner: CollectionConsumerOwner;
16
+ rowTemplateId: string;
17
+ localSymbols: Record<string, string>;
18
+ collectionSources: readonly TreeCollectionSource[];
19
+ limits?: Partial<TreeLimits>;
20
+ }
21
+
22
+ /** Shared page/definition source lowering; no controller, reader or DOM execution. */
23
+ export function lowerCollectionBinding(input: LowerCollectionBindingInput): RepeatPlan {
24
+ const safe = canonicalTreeData(input) as unknown as LowerCollectionBindingInput;
25
+ if (!path(safe.sourcePath)) fail('CT-REPEAT-SOURCE', 'source 必须是安全的已声明数组路径');
26
+ if (!/^[$A-Z_a-z][$\w]*$/.test(safe.itemAlias)
27
+ || ['page', 'p', 'ctrl', 'data', '__proto__', 'constructor', 'prototype'].includes(safe.itemAlias)) {
28
+ fail('CT-BINDING-SCOPE', '行别名不得遮蔽保留作用域');
29
+ }
30
+ const sources = safe.collectionSources.filter(source => source.path === safe.sourcePath);
31
+ if (sources.length !== 1) fail('CT-REPEAT-SOURCE', '集合源必须具有唯一且明确的数组元素类型');
32
+ if (!path(safe.keyPath) || !safe.keyPath.startsWith(`${safe.itemAlias}.`)) fail('CT-REPEAT-KEY', 'key 必须来自当前行的字段');
33
+ let field: SomaContractField | undefined = sources[0].item;
34
+ for (const part of safe.keyPath.split('.').slice(1)) field = field?.fields?.[part];
35
+ if (!field || !['string', 'number', 'enum'].includes(field.type)
36
+ || (field.type === 'enum' && (!field.values?.length || field.values.some(value =>
37
+ typeof value !== 'string' && (typeof value !== 'number' || !Number.isFinite(value)))))) {
38
+ fail('CT-REPEAT-KEY', 'key 字段必须有可验证的字符串或有限数字类型');
39
+ }
40
+ const statusPlan = sources[0].statusPlan;
41
+ if (!statusPlan || !['sync', 'async'].includes(statusPlan.kind)
42
+ || (statusPlan.kind === 'async' && !path(statusPlan.statePath))) fail('CT-REPEAT-SOURCE', '异步源必须声明受控状态路径');
43
+ if (!safe.consumerOwner.layoutRootKey || !['none', 'list-item'].includes(safe.consumerOwner.rowContainer)
44
+ || safe.consumerOwner.slotName !== 'item') fail('CT-SLOT-CONTRACT', '集合必须消费已登记 item 出口');
45
+ const limits = { ...DEFAULT_TREE_LIMITS, ...safe.limits };
46
+ if (Object.values(limits).some(value => !Number.isSafeInteger(value) || value < 1)) fail('CT-LIMIT', '集合预算必须是正整数');
47
+ return {
48
+ planId: safe.planId, scopeId: safe.scopeId,
49
+ ...(safe.parentPlanId ? { parentPlanId: safe.parentPlanId } : {}),
50
+ declarationScope: safe.declarationScope, consumerOwner: safe.consumerOwner,
51
+ sourcePath: safe.sourcePath, statusPlan, itemAlias: safe.itemAlias, keyPath: safe.keyPath,
52
+ rowTemplateId: safe.rowTemplateId, localSymbols: safe.localSymbols,
53
+ limits: { maxRows: limits.maxRowsPerCollection, maxPageRows: limits.maxRowsPerPage,
54
+ maxKeyLength: limits.maxKeyLength, maxDepth: limits.maxRepeatDepth },
55
+ };
56
+ }
57
+
58
+ function path(value: string): boolean {
59
+ return typeof value === 'string' && /^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)+$/.test(value)
60
+ && !value.split('.').some(part => ['__proto__', 'constructor', 'prototype'].includes(part));
61
+ }
62
+
63
+ function fail(code: 'CT-REPEAT-SOURCE' | 'CT-REPEAT-KEY' | 'CT-BINDING-SCOPE' | 'CT-LIMIT' | 'CT-SLOT-CONTRACT', fixHint: string): never {
64
+ throw new SomaComponentTreeError({ code, phase: 'bind', sourceId: '<collection>', nodePath: 'repeat', fixHint });
65
+ }
@@ -0,0 +1,320 @@
1
+ import { parseFragment, serialize, type DefaultTreeAdapterMap } from 'parse5';
2
+ import type { SomaComponentDefinition } from '../../client/component/component-definition.types';
3
+ import type { SomaContractField } from '../../shared/types/component-contract.types';
4
+ import type { DefinitionRepeatPlan } from '../../shared/types/component-tree-artifact.types';
5
+ import type { TreeCollectionSource, TreeRegistrySnapshot } from '../../shared/types/component-tree.types';
6
+ import type { ShowMapping, NestedShowMapping } from '../../shared/types/ui-config.types';
7
+ import { parseUiConfig } from '../../client/parser/ui-config-parser';
8
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
9
+ import { buildComponentTreeRegistrySnapshot, type ComponentTreeRegistryEntry } from './registry-snapshot';
10
+ import { canonicalTreeData, digestTreeData } from './artifact-codec';
11
+ import { lowerCollectionBinding } from './collection-binding-lowerer';
12
+ import { assertDefinitionPreparation } from '../../shared/component-tree-artifact';
13
+
14
+ type Node = DefaultTreeAdapterMap['node'];
15
+ type Element = DefaultTreeAdapterMap['element'];
16
+ type Parent = DefaultTreeAdapterMap['parentNode'];
17
+
18
+ export interface PreparedComponentTreeDefinitions {
19
+ definitions: SomaComponentDefinition[];
20
+ registrySnapshot: TreeRegistrySnapshot;
21
+ }
22
+
23
+ /** Prepare real composed definitions on the build/server side, never in a browser factory. */
24
+ export function prepareComponentTreeDefinitions(entries: readonly ComponentTreeRegistryEntry[]): PreparedComponentTreeDefinitions {
25
+ const initial = buildComponentTreeRegistrySnapshot(entries);
26
+ const definitions = entries.map(entry => lowerDefinitionCollections(entry.definition, initial));
27
+ const loweredEntries = entries.map((entry, index) => ({ ...entry, definition: definitions[index] }));
28
+ const registrySnapshot = buildComponentTreeRegistrySnapshot(loweredEntries);
29
+ for (const definition of definitions) {
30
+ const snapshot = registrySnapshot.components[definition.contract.name];
31
+ definition.structureDigest = snapshot.structureDigest;
32
+ definition.contractDigest = snapshot.contractDigest;
33
+ if (definition.definitionRepeatPlans?.length) {
34
+ const dependencyDigests: Record<string, string> = {};
35
+ const visit = (name: string): void => {
36
+ if (dependencyDigests[name]) return;
37
+ const child = registrySnapshot.components[name];
38
+ if (!child) fail(definition.contract.name, '准备计划依赖未实际装配');
39
+ dependencyDigests[name] = child.structureDigest;
40
+ for (const dependency of child.contract.uses ?? []) visit(dependency);
41
+ };
42
+ for (const name of definition.contract.uses ?? []) visit(name);
43
+ for (const plan of definition.definitionRepeatPlans) visit(plan.consumerOwner.componentName);
44
+ definition.definitionPreparation = {
45
+ schemaVersion: 1,
46
+ requiredCapabilities: ['definition-repeat:1', 'repeat-range:1', 'row-bindings:1'],
47
+ dependencyDigests,
48
+ definitionDigest: definitionDigest(definition, dependencyDigests),
49
+ };
50
+ }
51
+ }
52
+ return { definitions, registrySnapshot };
53
+ }
54
+
55
+ /** Trusted templateHtml + nested props/bind/show becomes the same RepeatPlan as a page tree. */
56
+ export function lowerDefinitionCollections(definition: SomaComponentDefinition, registry: TreeRegistrySnapshot): SomaComponentDefinition {
57
+ const result = copyDefinition(definition);
58
+ if (definition.definitionRepeatPlans !== undefined || definition.definitionPreparation !== undefined) {
59
+ assertPreparedDefinition(definition, registry);
60
+ return result;
61
+ }
62
+ if (!definition.uiConfig) return result;
63
+ // Descriptor-only projection rejects accessors before any parser or controller can run.
64
+ const safe = canonicalTreeData(definition.uiConfig);
65
+ const needsPreparation = (value: unknown): boolean => Boolean(value && typeof value === 'object'
66
+ && ('collectionSlot' in value || 'repeatPlanId' in value || Object.values(value).some(needsPreparation)));
67
+ if (!needsPreparation(safe)) return result;
68
+ const config = parseUiConfig(safe, { adaptiveVocabularyRequired: false, collectionBindingStage: 'definition-source' });
69
+ const fragment = parseFragment(definition.templateHtml);
70
+ const plans: DefinitionRepeatPlan[] = [];
71
+ const symbolOccurrences = new Map<string, string[]>();
72
+ let sequence = 0;
73
+ let changed = false;
74
+
75
+ const visit = (show: ShowMapping, root: Parent, parentPlan: DefinitionRepeatPlan | undefined, aliases: Map<string, SomaContractField>): ShowMapping => {
76
+ const output: ShowMapping = {};
77
+ for (const [rawKey, value] of Object.entries(show)) {
78
+ if (!value || typeof value !== 'object') { output[rawKey] = value; continue; }
79
+ if (!('bind' in value)) {
80
+ output[rawKey] = value.show ? { ...value, show: visit(value.show, root, parentPlan, aliases) } : value;
81
+ continue;
82
+ }
83
+ const nested = value as NestedShowMapping;
84
+ if (!nested.bind.collectionSlot) {
85
+ if (nested.bind.repeatPlanId) {
86
+ const existing = definition.definitionRepeatPlans?.find(plan => plan.planId === nested.bind.repeatPlanId);
87
+ if (!existing) fail(definition.contract.name, '绑定引用没有对应的定义准备计划');
88
+ plans.push(canonicalTreeData(existing) as unknown as DefinitionRepeatPlan);
89
+ }
90
+ output[rawKey] = { ...nested, show: visit(nested.show, root, parentPlan, aliases) };
91
+ continue;
92
+ }
93
+ changed = true;
94
+ if (!nested.bind.key || nested.bind.role_by) fail(definition.contract.name, 'collectionSlot 需要唯一显式 key,不能混用 role_by');
95
+ const id = rawKey.split('@')[0];
96
+ const hosts = scopedElements(root).filter(node => attr(node, 'data-soma-id') === id);
97
+ if (hosts.length !== 1) fail(definition.contract.name, '内部集合消费锚点必须在声明作用域中唯一');
98
+ const host = hosts[0];
99
+ const componentName = attr(host, 'data-soma-component');
100
+ const child = componentName ? registry.components[componentName] : undefined;
101
+ const slot = child?.contract.structure?.slots?.[nested.bind.collectionSlot];
102
+ if (!child || !componentName || slot?.kind !== 'collection' || !slot.layoutRoot || !slot.rowContainer) {
103
+ fail(definition.contract.name, '内部集合必须指向实际装配组件的 collection 出口');
104
+ }
105
+ if (!(definition.contract.uses ?? []).includes(componentName)) fail(definition.contract.name, '内部集合消费组件必须在 uses 中声明');
106
+ const projections = host.childNodes.filter(isElement).filter(node => node.tagName === 'template' && attr(node, 'data-soma-slot') === nested.bind.collectionSlot);
107
+ if (projections.length !== 1) fail(definition.contract.name, '内部集合需要唯一具名 item 投影');
108
+ const projection = (projections[0] as DefaultTreeAdapterMap['template']).content;
109
+ const templates = projection.childNodes.filter(isElement).filter(node => node.tagName === 'template' && attr(node, 'data-soma-role') === 'item');
110
+ if (templates.length !== 1 || projection.childNodes.some(node =>
111
+ (isElement(node) && node !== templates[0]) || (node.nodeName === '#text' && !!(node as DefaultTreeAdapterMap['textNode']).value.trim()))) {
112
+ fail(definition.contract.name, 'item 投影只能有一个完整行模板');
113
+ }
114
+ const template = templates[0] as DefaultTreeAdapterMap['template'];
115
+ if (!template.content.childNodes.some(isElement)) fail(definition.contract.name, '集合行模板不能为空');
116
+ const source = definitionSource(definition, nested.bind.obj, aliases);
117
+ if (aliases.has(nested.bind.var)) fail(definition.contract.name, '内部行别名不能遮蔽祖先行');
118
+ const planId = `__soma_definition_${definition.contract.name}_${sequence++}`;
119
+ const rowTemplateId = `${planId}_template`;
120
+ const localSymbols: Record<string, string> = {};
121
+ for (const element of scopedElements(template.content)) {
122
+ const local = attr(element, 'data-soma-id');
123
+ if (!local) continue;
124
+ if (localSymbols[local]) fail(definition.contract.name, '同一行模板中锚点重复');
125
+ const symbol = `${planId}_${local.length}_${local}`;
126
+ localSymbols[local] = symbol;
127
+ const occurrences = symbolOccurrences.get(local) ?? [];
128
+ occurrences.push(symbol);
129
+ symbolOccurrences.set(local, occurrences);
130
+ }
131
+ const plan: DefinitionRepeatPlan = {
132
+ ...lowerCollectionBinding({
133
+ planId, scopeId: planId, ...(parentPlan ? { parentPlanId: parentPlan.planId } : {}),
134
+ sourcePath: nested.bind.obj, itemAlias: nested.bind.var, keyPath: nested.bind.key,
135
+ declarationScope: { kind: 'component', ownerSymbol: definition.contract.name, readerRoot: '__component', emitOwnerSymbol: definition.contract.name,
136
+ ...(parentPlan ? { parentScopeId: parentPlan.scopeId } : {}) },
137
+ consumerOwner: { instanceSymbol: id, componentName, slotName: nested.bind.collectionSlot,
138
+ layoutRootKey: slot.layoutRoot, rowContainer: slot.rowContainer },
139
+ rowTemplateId, localSymbols, collectionSources: [source],
140
+ }), definitionName: definition.contract.name, definitionPlanId: planId,
141
+ };
142
+ plans.push(plan);
143
+ const childAliases = new Map(aliases);
144
+ childAliases.set(nested.bind.var, source.item);
145
+ const childShow = visit(nested.show, template.content, plan, childAliases);
146
+ // Rename the complete lexical scope, including zero-prop component anchors.
147
+ for (const element of scopedElements(template.content)) {
148
+ const local = attr(element, 'data-soma-id');
149
+ if (local && localSymbols[local]) setAttr(element, 'data-soma-id', localSymbols[local]);
150
+ }
151
+ for (const childPlan of plans) {
152
+ if (childPlan.parentPlanId === plan.planId) childPlan.consumerOwner.instanceSymbol = localSymbols[childPlan.consumerOwner.instanceSymbol] ?? childPlan.consumerOwner.instanceSymbol;
153
+ }
154
+ setAttr(template, 'data-soma-repeat-template', rowTemplateId);
155
+ output[rawKey] = { ...nested, bind: { obj: nested.bind.obj, var: nested.bind.var, repeatPlanId: planId }, show: remapShow(childShow, localSymbols) };
156
+ }
157
+ return output;
158
+ };
159
+ config.show = visit(config.show, fragment, undefined, new Map());
160
+ if (!changed && plans.length === 0) return result;
161
+ result.uiConfig = config;
162
+ result.templateHtml = changed ? serialize(fragment) : definition.templateHtml;
163
+ result.definitionRepeatPlans = plans;
164
+ if (definition.eventConfig && changed) result.eventConfig = definition.eventConfig.map(event => {
165
+ const matches = symbolOccurrences.get(event.somaId);
166
+ if (matches && matches.length !== 1) fail(definition.contract.name, '事件锚点跨内部行模板不唯一,需使用明确局部锚点');
167
+ const targetMatches = event.targetId ? symbolOccurrences.get(event.targetId) : undefined;
168
+ if (targetMatches && targetMatches.length !== 1) fail(definition.contract.name, '交互目标跨内部行模板不唯一');
169
+ return { ...event, ...(matches ? { somaId: matches[0] } : {}), ...(targetMatches ? { targetId: targetMatches[0] } : {}) };
170
+ });
171
+ return result;
172
+ }
173
+
174
+ /** Reusing a package artifact is verification, not permission to silently reseal changed plans. */
175
+ function assertPreparedDefinition(definition: SomaComponentDefinition, registry: TreeRegistrySnapshot): void {
176
+ const name = definition.contract.name;
177
+ const preparation = canonicalTreeData(definition.definitionPreparation);
178
+ assertDefinitionPreparation(preparation);
179
+ const plans = canonicalTreeData(definition.definitionRepeatPlans) as unknown as DefinitionRepeatPlan[];
180
+ if (!Array.isArray(plans) || !plans.length || !definition.uiConfig) fail(name, '已准备定义必须包含完整绑定与非空计划');
181
+ if (['definition-repeat:1', 'repeat-range:1', 'row-bindings:1'].some(capability =>
182
+ !preparation.requiredCapabilities.some(value => value === capability))) fail(name, '已准备定义缺少所需运行时能力');
183
+ if (preparation.definitionDigest !== definitionDigest(definition, preparation.dependencyDigests)) fail(name, '已准备定义载荷摘要不一致;必须从原始定义重新构建');
184
+ const dependencies = new Set<string>();
185
+ const addDependency = (dependency: string): void => {
186
+ if (dependencies.has(dependency)) return;
187
+ dependencies.add(dependency);
188
+ const child = registry.components[dependency];
189
+ if (!child || preparation.dependencyDigests[dependency] !== child.structureDigest) fail(name, '已准备定义的依赖供货摘要不一致');
190
+ for (const nested of child.contract.uses ?? []) addDependency(nested);
191
+ };
192
+ for (const dependency of definition.contract.uses ?? []) addDependency(dependency);
193
+ if (dependencies.size !== Object.keys(preparation.dependencyDigests).length) fail(name, '已准备定义的依赖闭包不完整或存在多余依赖');
194
+ const byId = new Map<string, DefinitionRepeatPlan>();
195
+ for (const plan of plans) {
196
+ if (!plan || typeof plan !== 'object' || typeof plan.planId !== 'string' || byId.has(plan.planId)) fail(name, '已准备定义计划身份重复或无效');
197
+ byId.set(plan.planId, plan);
198
+ }
199
+ const config = parseUiConfig(canonicalTreeData(definition.uiConfig), { adaptiveVocabularyRequired: false });
200
+ const fragment = parseFragment(definition.templateHtml);
201
+ const used = new Set<string>();
202
+ const visit = (show: ShowMapping, root: Parent, parent: DefinitionRepeatPlan | undefined, aliases: Map<string, SomaContractField>): void => {
203
+ for (const [key, value] of Object.entries(show)) {
204
+ if (!value || typeof value !== 'object') continue;
205
+ if (!('bind' in value) || !value.bind.repeatPlanId) {
206
+ if (value.show) visit(value.show, root, parent, aliases);
207
+ continue;
208
+ }
209
+ const plan = byId.get(value.bind.repeatPlanId);
210
+ if (!plan || used.has(plan.planId)) fail(name, '集合绑定必须与准备计划一一对应');
211
+ used.add(plan.planId);
212
+ if (plan.definitionName !== name || plan.definitionPlanId !== plan.planId
213
+ || !/^__soma_definition_[A-Z][A-Za-z0-9]*_\d+$/.test(plan.planId)
214
+ || plan.scopeId !== plan.planId || plan.rowTemplateId !== `${plan.planId}_template`) fail(name, '已准备定义计划符号身份不一致');
215
+ const hosts = scopedElements(root).filter(element => attr(element, 'data-soma-id') === key);
216
+ if (hosts.length !== 1) fail(name, '准备计划消费锚点不存在或不唯一');
217
+ const host = hosts[0];
218
+ const componentName = attr(host, 'data-soma-component');
219
+ const child = componentName ? registry.components[componentName] : undefined;
220
+ const slot = child?.contract.structure?.slots?.item;
221
+ if (!componentName || !child || !dependencies.has(componentName) || slot?.kind !== 'collection'
222
+ || !slot.layoutRoot || !slot.rowContainer) fail(name, '准备计划消费组件或 collection 出口不一致');
223
+ const projections = host.childNodes.filter(isElement).filter(element => element.tagName === 'template' && attr(element, 'data-soma-slot') === 'item');
224
+ if (projections.length !== 1) fail(name, '准备计划需要唯一 item 投影');
225
+ const projection = (projections[0] as DefaultTreeAdapterMap['template']).content;
226
+ const templates = projection.childNodes.filter(isElement).filter(element => element.tagName === 'template' && attr(element, 'data-soma-role') === 'item');
227
+ if (templates.length !== 1 || attr(templates[0], 'data-soma-repeat-template') !== plan.rowTemplateId
228
+ || projection.childNodes.some(node => (isElement(node) && node !== templates[0])
229
+ || (node.nodeName === '#text' && !!(node as DefaultTreeAdapterMap['textNode']).value.trim()))) fail(name, '准备计划行模板标记或拓扑不一致');
230
+ const template = templates[0] as DefaultTreeAdapterMap['template'];
231
+ if (!template.content.childNodes.some(isElement)) fail(name, '准备计划行模板不能为空');
232
+ const rowAnchors = scopedElements(template.content).map(element => attr(element, 'data-soma-id')).filter((id): id is string => id !== undefined);
233
+ if (!plan.localSymbols || Array.isArray(plan.localSymbols) || typeof plan.localSymbols !== 'object') fail(name, '准备计划缺少完整局部符号表');
234
+ const localSymbols = Object.entries(plan.localSymbols);
235
+ if (rowAnchors.length !== localSymbols.length || new Set(rowAnchors).size !== rowAnchors.length
236
+ || localSymbols.some(([local, symbol]) => symbol !== `${plan.planId}_${local.length}_${local}` || !rowAnchors.includes(symbol))) fail(name, '准备计划局部符号与完整行模板不一致');
237
+ const source = definitionSource(definition, value.bind.obj, aliases);
238
+ if (aliases.has(value.bind.var)) fail(name, '准备计划行变量遮蔽祖先行');
239
+ const expected: DefinitionRepeatPlan = { ...lowerCollectionBinding({
240
+ planId: plan.planId, scopeId: plan.planId, ...(parent ? { parentPlanId: parent.planId } : {}),
241
+ sourcePath: value.bind.obj, itemAlias: value.bind.var, keyPath: plan.keyPath,
242
+ declarationScope: { kind: 'component', ownerSymbol: name, readerRoot: '__component', emitOwnerSymbol: name,
243
+ ...(parent ? { parentScopeId: parent.scopeId } : {}) },
244
+ consumerOwner: { instanceSymbol: key, componentName, slotName: 'item', layoutRootKey: slot.layoutRoot, rowContainer: slot.rowContainer },
245
+ rowTemplateId: plan.rowTemplateId, localSymbols: plan.localSymbols, collectionSources: [source],
246
+ }), definitionName: name, definitionPlanId: plan.planId };
247
+ if (digestTreeData(expected) !== digestTreeData(plan)) fail(name, '准备计划与绑定、类型、作用域或消费出口不一致');
248
+ visit(value.show, template.content, plan, new Map(aliases).set(value.bind.var, source.item));
249
+ }
250
+ };
251
+ visit(config.show, fragment, undefined, new Map());
252
+ if (used.size !== plans.length) fail(name, '已准备定义存在没有绑定消费者的孤立计划');
253
+ }
254
+
255
+ function definitionDigest(definition: SomaComponentDefinition, dependencyDigests: Record<string, string>): string {
256
+ return digestTreeData({ contract: definition.contract, templateHtml: definition.templateHtml, uiConfig: definition.uiConfig,
257
+ collectionSources: definition.collectionSources, structureAdapter: definition.structureAdapter,
258
+ definitionRepeatPlans: definition.definitionRepeatPlans, dependencyDigests });
259
+ }
260
+
261
+ function definitionSource(definition: SomaComponentDefinition, path: string, aliases: Map<string, SomaContractField>): TreeCollectionSource {
262
+ const [root, ...parts] = path.split('.');
263
+ if (root === 'ctrl') {
264
+ const matches = definition.collectionSources?.filter(source => source.path === path) ?? [];
265
+ if (matches.length !== 1) fail(definition.contract.name, 'ctrl 集合源需要明确且唯一的受信类型/状态描述');
266
+ return matches[0];
267
+ }
268
+ let field: SomaContractField | undefined;
269
+ if (root === 'p') {
270
+ field = definition.contract.props?.[parts.shift()!];
271
+ if (definition.collectionSources?.some(source => source.path === path)) fail(definition.contract.name, 'p 集合类型只由父 contract 声明,不得双写');
272
+ } else field = aliases.get(root);
273
+ for (const part of parts) field = field?.fields?.[part];
274
+ if (field?.type !== 'array' || !field.items) fail(definition.contract.name, '集合源必须声明 array/items 元素类型');
275
+ return { path, item: field.items, statusPlan: { kind: 'sync' } };
276
+ }
277
+
278
+ function remapShow(show: ShowMapping, symbols: Record<string, string>): ShowMapping {
279
+ const output: ShowMapping = {};
280
+ for (const [key, value] of Object.entries(show)) {
281
+ const [id, ...suffix] = key.split('@');
282
+ const mapped = (symbols[id] ?? id) + (suffix.length ? `@${suffix.join('@')}` : '');
283
+ output[mapped] = value && typeof value === 'object' && !('bind' in value) && value.show
284
+ ? { ...value, show: remapShow(value.show, symbols) } : value;
285
+ }
286
+ return output;
287
+ }
288
+
289
+ function scopedElements(root: Parent): Element[] {
290
+ const found: Element[] = [];
291
+ const visit = (node: Node): void => {
292
+ if (!isElement(node)) return;
293
+ found.push(node);
294
+ if (node.tagName === 'template') {
295
+ if (attr(node, 'data-soma-role') === 'item') return;
296
+ for (const child of (node as DefaultTreeAdapterMap['template']).content.childNodes) visit(child);
297
+ }
298
+ for (const child of node.childNodes) visit(child);
299
+ };
300
+ for (const child of root.childNodes) visit(child);
301
+ return found;
302
+ }
303
+
304
+ function isElement(node: Node): node is Element { return 'tagName' in node; }
305
+ function attr(node: Element, name: string): string | undefined { return node.attrs.find(item => item.name === name)?.value; }
306
+ function setAttr(node: Element, name: string, value: string): void {
307
+ const existing = node.attrs.find(item => item.name === name);
308
+ if (existing) existing.value = value; else node.attrs.push({ name, value });
309
+ }
310
+ function copyDefinition(definition: SomaComponentDefinition): SomaComponentDefinition {
311
+ const output: Record<string, unknown> = {};
312
+ for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(definition))) {
313
+ if (!('value' in descriptor)) fail('<definition>', '定义准备不执行属性 getter');
314
+ output[name] = descriptor.value;
315
+ }
316
+ return output as unknown as SomaComponentDefinition;
317
+ }
318
+ function fail(sourceId: string, fixHint: string): never {
319
+ throw new SomaComponentTreeError({ code: 'CT-BINDING-SCOPE', phase: 'bind', sourceId, nodePath: 'definition', fixHint });
320
+ }
@@ -0,0 +1,214 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import yaml from 'js-yaml';
4
+ import { digestTreeData } from './artifact-codec';
5
+ import { planComponentTreeMigration, type ComponentTreeMigrationPlan } from './migration';
6
+ import { loadExternalBlocks, blocksDirOf } from '../blocks/block-loader';
7
+ import { getSomaAssetSources } from '../../server/host/source-packages';
8
+ import { resolveSomaPageSource } from '../../server/host/server-page-assets';
9
+ import { loadPageMarkupConfig } from '../../server/host/page-markup-config';
10
+ import { resolveHostTreeCompileContext } from '../../server/host/resolve-host-tree-context';
11
+ import type { TreeCompileContext } from '../../shared/types/component-tree.types';
12
+
13
+ interface TrackedFile { file: string; text: string; exists: boolean; digest: string; external?: string }
14
+ export interface ComponentTreeMigrationPage {
15
+ hostDir: string;
16
+ base: string;
17
+ plan: ComponentTreeMigrationPlan;
18
+ htmlFile: string;
19
+ uiFile: string;
20
+ markupFile: string;
21
+ files: TrackedFile[];
22
+ /** Source packages are inventory-only; modifying installed dependencies is never automatic. */
23
+ writable: boolean;
24
+ }
25
+ const inspectedPages = new WeakMap<ComponentTreeMigrationPage, string>();
26
+ const inspectedContexts = new WeakMap<ComponentTreeMigrationPage, TreeCompileContext | undefined>();
27
+
28
+ function track(file: string, external?: string): TrackedFile {
29
+ const exists = fs.existsSync(file);
30
+ if (exists && (!fs.lstatSync(file).isFile() || fs.lstatSync(file).isSymbolicLink())) {
31
+ throw new Error('[component-tree migration] source must be a regular non-symlink file');
32
+ }
33
+ const text = exists ? fs.readFileSync(file, 'utf8') : '';
34
+ return { file, text, exists, digest: digestTreeData({ exists, text }), ...(external ? { external } : {}) };
35
+ }
36
+
37
+ /** Standard Host inventory, without loading Domain classes, credentials or application services. */
38
+ export function inspectComponentTreeMigrationPage(
39
+ hostDir: string, pageBase: string, explicitContext?: TreeCompileContext,
40
+ ): ComponentTreeMigrationPage {
41
+ const root = path.resolve(hostDir);
42
+ const sources = getSomaAssetSources(root);
43
+ const resolved = resolveSomaPageSource(sources, `/${pageBase.replace(/^\/+|\.html$/g, '')}`);
44
+ if (!resolved) throw new Error('[component-tree migration] page not found');
45
+ const { source, base } = resolved;
46
+ const htmlFile = path.join(source.assetRoot, 'html', `${base}.html`);
47
+ const uiFile = path.join(source.assetRoot, 'ui', `${base}_ui.yaml`);
48
+ const markupFile = path.join(source.configRoot, 'page-markup.config.yaml');
49
+ const files = [track(htmlFile), track(uiFile), track(markupFile)];
50
+ const uiDir = path.join(source.assetRoot, 'ui');
51
+ const externalBlocks = loadExternalBlocks(uiDir, base);
52
+ for (const block of externalBlocks.keys()) {
53
+ files.push(track(path.join(blocksDirOf(uiDir, base), `${block}.yaml`), `ui/${base}.blocks/${block}.yaml`));
54
+ }
55
+ const includes: Record<string, string> = {};
56
+ for (const supply of [...sources.filter(item => item.type === 'package'), ...sources.filter(item => item.type === 'host')]) {
57
+ const sharedDir = path.join(supply.assetRoot, 'html', 'shared');
58
+ if (!fs.existsSync(sharedDir)) continue;
59
+ for (const item of fs.readdirSync(sharedDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
60
+ if (!item.isFile() || !item.name.endsWith('.html')) continue;
61
+ const tracked = track(path.join(sharedDir, item.name));
62
+ includes[`shared/${item.name}`] = tracked.text;
63
+ files.push(tracked);
64
+ }
65
+ }
66
+ let treeContext = explicitContext;
67
+ if (!treeContext) {
68
+ try { treeContext = resolveHostTreeCompileContext(root, { pageBase: base }); }
69
+ catch { /* The report still inventories unsafe native nodes; a convertible candidate cannot pass without context. */ }
70
+ }
71
+ const sidecars = [path.join(source.assetRoot, 'event', `${base}_event.yaml`),
72
+ path.join(uiDir, `${base}_style.yaml`), path.join(source.assetRoot, 'data', `${base}_data.yaml`),
73
+ path.join(uiDir, `${base}_data.yaml`)];
74
+ files.push(...sidecars.map(file => track(file)));
75
+ const plan = planComponentTreeMigration({
76
+ html: files[0].text, uiYaml: files[1].text, ...loadPageMarkupConfig(source.configRoot, base),
77
+ treeContext, externalBlocks, includes,
78
+ // Even an empty retired sidecar is forbidden by the file Host. Keep it visible in the report.
79
+ ...(sidecars.some(file => fs.existsSync(file)) ? { eventYaml: 'retired source sidecar present' } : {}),
80
+ });
81
+ const inputDigest = digestTreeData(files.map(file => ({ file: file.file, digest: file.digest })));
82
+ plan.sourceDigest = digestTreeData({ logicalSourceDigest: plan.sourceDigest, files: inputDigest });
83
+ plan.planDigest = digestTreeData({ plan: plan.planDigest, sourceDigest: plan.sourceDigest });
84
+ const page = { hostDir: root, base, plan, htmlFile, uiFile, markupFile, files, writable: source.type === 'host' };
85
+ inspectedPages.set(page, digestTreeData(page));
86
+ inspectedContexts.set(page, treeContext);
87
+ return page;
88
+ }
89
+
90
+ export function listComponentTreeMigrationPages(hostDir: string): string[] {
91
+ const pages = new Set<string>();
92
+ for (const source of getSomaAssetSources(path.resolve(hostDir))) {
93
+ const htmlRoot = path.join(source.assetRoot, 'html');
94
+ if (!fs.existsSync(htmlRoot)) continue;
95
+ const pending = [{ directory: htmlRoot, prefix: '' }];
96
+ while (pending.length) {
97
+ const current = pending.pop()!;
98
+ for (const entry of fs.readdirSync(current.directory, { withFileTypes: true })) {
99
+ if (entry.isSymbolicLink() || (!current.prefix && ['shared', 'system'].includes(entry.name))) continue;
100
+ const relative = `${current.prefix}${entry.name}`;
101
+ if (entry.isDirectory()) pending.push({ directory: path.join(current.directory, entry.name), prefix: `${relative}/` });
102
+ else if (entry.isFile() && entry.name.endsWith('.html')) pages.add(relative.slice(0, -5));
103
+ }
104
+ }
105
+ }
106
+ return [...pages].sort();
107
+ }
108
+
109
+ function markupText(page: ComponentTreeMigrationPage): string {
110
+ const raw = page.files.find(file => file.file === page.markupFile)?.text ?? '';
111
+ const loaded: unknown = raw.trim() ? yaml.load(raw) : { pages: {} };
112
+ if (!loaded || typeof loaded !== 'object' || Array.isArray(loaded)) throw new Error('invalid page markup inventory');
113
+ const config = loaded as Record<string, unknown>;
114
+ const entries = config.pages;
115
+ if (!entries || typeof entries !== 'object' || Array.isArray(entries)) throw new Error('invalid pages inventory');
116
+ return yaml.dump({ ...config, pages: { ...entries, [page.base]: { markup: 'component-tree', grammarVersion: 1 } } }, { lineWidth: 120 });
117
+ }
118
+
119
+ function assertUnchanged(page: ComponentTreeMigrationPage): void {
120
+ if (inspectedPages.get(page) !== digestTreeData(page)) throw new Error('migration plan changed after inspection');
121
+ for (const file of page.files) {
122
+ if (track(file.file).digest !== file.digest) throw new Error('[component-tree migration] source changed since inspection; no files replaced');
123
+ }
124
+ // Rescan dependency inventories too: adding a block/include/sidecar invalidates approval.
125
+ const current = inspectComponentTreeMigrationPage(page.hostDir, page.base, inspectedContexts.get(page));
126
+ if (current.plan.sourceDigest !== page.plan.sourceDigest || current.plan.planDigest !== page.plan.planDigest) {
127
+ throw new Error('[component-tree migration] source or dependency inventory changed; no files replaced');
128
+ }
129
+ }
130
+
131
+ /** Explicit proposal output only; existing files are never overwritten. */
132
+ export function writeComponentTreeMigrationProposal(page: ComponentTreeMigrationPage, outputDir: string): void {
133
+ const output = path.resolve(outputDir);
134
+ if (output === page.hostDir || output === path.parse(output).root) throw new Error('proposal output must be a separate explicit directory');
135
+ if (fs.existsSync(output) && (fs.lstatSync(output).isSymbolicLink() || !fs.statSync(output).isDirectory() || fs.readdirSync(output).length > 0)) {
136
+ throw new Error('proposal output must be a new or empty non-symlink directory');
137
+ }
138
+ assertUnchanged(page);
139
+ const outputs = [{ relative: 'report.json', text: JSON.stringify(page.plan, null, 2) + '\n' }];
140
+ if (page.plan.candidate) {
141
+ outputs.push({ relative: `html/${page.base}.html`, text: page.plan.candidate.html },
142
+ { relative: `ui/${page.base}_ui.yaml`, text: page.plan.candidate.uiYaml },
143
+ { relative: 'config/page-markup.config.yaml', text: markupText(page) });
144
+ for (const file of page.files) if (file.external) outputs.push({ relative: file.external, text: file.text });
145
+ }
146
+ for (const item of outputs) {
147
+ const file = path.join(output, item.relative);
148
+ fs.mkdirSync(path.dirname(file), { recursive: true });
149
+ fs.writeFileSync(file, item.text, { encoding: 'utf8', flag: 'wx' });
150
+ }
151
+ }
152
+
153
+ /** Reviewed exact plan only. Stage everything first; retain backups and compensate a failed rename. */
154
+ export function applyComponentTreeMigrationPlan(page: ComponentTreeMigrationPage, approval: {
155
+ sourceDigest: string; planDigest: string; reviewed: boolean;
156
+ }): { changed: string[]; backupDirectory: string } {
157
+ if (!page.writable || page.plan.status !== 'converted' || !page.plan.candidate || !approval.reviewed
158
+ || approval.sourceDigest !== page.plan.sourceDigest || approval.planDigest !== page.plan.planDigest) {
159
+ throw new Error('[component-tree migration] an explicitly reviewed, exact convertible plan is required');
160
+ }
161
+ assertUnchanged(page);
162
+ const hostReal = fs.realpathSync(page.hostDir);
163
+ const replacements = [
164
+ { file: page.htmlFile, text: page.plan.candidate.html },
165
+ { file: page.uiFile, text: page.plan.candidate.uiYaml },
166
+ { file: page.markupFile, text: markupText(page) },
167
+ ].filter(item => page.files.find(file => file.file === item.file)?.text !== item.text);
168
+ for (const item of replacements) {
169
+ let existingParent = path.dirname(item.file);
170
+ while (!fs.existsSync(existingParent)) existingParent = path.dirname(existingParent);
171
+ const parent = fs.realpathSync(existingParent);
172
+ const relative = path.relative(hostReal, parent);
173
+ if (relative.startsWith('..') || path.isAbsolute(relative)) throw new Error('migration target must remain inside the real Host root');
174
+ }
175
+ const backupRoot = path.join(page.hostDir, '.soma', 'migration-backups');
176
+ if (fs.existsSync(path.join(page.hostDir, '.soma')) && fs.lstatSync(path.join(page.hostDir, '.soma')).isSymbolicLink()) {
177
+ throw new Error('migration backup directory must not be a symlink');
178
+ }
179
+ if (fs.existsSync(backupRoot) && fs.lstatSync(backupRoot).isSymbolicLink()) throw new Error('migration backup directory must not be a symlink');
180
+ fs.mkdirSync(backupRoot, { recursive: true });
181
+ const backupDirectory = fs.mkdtempSync(path.join(backupRoot, 'component-tree-'));
182
+ const staged: Array<{ file: string; temporary: string; backup: string; existed: boolean }> = [];
183
+ const changed: typeof staged = [];
184
+ try {
185
+ for (const [index, item] of replacements.entries()) {
186
+ const original = page.files.find(file => file.file === item.file)!;
187
+ const backup = path.join(backupDirectory, `${index}-${path.basename(item.file)}`);
188
+ if (original.exists) fs.copyFileSync(item.file, backup, fs.constants.COPYFILE_EXCL);
189
+ fs.mkdirSync(path.dirname(item.file), { recursive: true });
190
+ const temporary = path.join(path.dirname(item.file), `.soma-tree-${path.basename(backupDirectory)}-${index}.tmp`);
191
+ staged.push({ file: item.file, temporary, backup, existed: original.exists });
192
+ fs.writeFileSync(temporary, item.text, { encoding: 'utf8', flag: 'wx',
193
+ ...(original.exists ? { mode: fs.statSync(item.file).mode } : {}),
194
+ });
195
+ }
196
+ assertUnchanged(page);
197
+ fs.writeFileSync(path.join(backupDirectory, 'report.json'), JSON.stringify({ ...page.plan,
198
+ restoredFiles: staged.map(item => ({ file: item.file, backup: item.existed ? item.backup : null })),
199
+ }, null, 2), { encoding: 'utf8', flag: 'wx' });
200
+ for (const item of staged) { fs.renameSync(item.temporary, item.file); changed.push(item); }
201
+ return { changed: changed.map(item => item.file), backupDirectory };
202
+ } catch (error) {
203
+ let restoreFailures = 0;
204
+ for (const item of changed.reverse()) {
205
+ try {
206
+ if (item.existed) fs.copyFileSync(item.backup, item.file);
207
+ else if (fs.existsSync(item.file)) fs.unlinkSync(item.file);
208
+ } catch { restoreFailures += 1; }
209
+ }
210
+ throw new Error(`[component-tree migration] replacement failed; ${restoreFailures ? `${restoreFailures} original files require manual recovery` : 'original files restored'}, backups: ${backupDirectory}`, { cause: error });
211
+ } finally {
212
+ for (const item of staged) if (fs.existsSync(item.temporary)) fs.unlinkSync(item.temporary);
213
+ }
214
+ }