soma-core 1.3.1 → 1.3.3

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 (233) hide show
  1. package/README.md +42 -0
  2. package/app/SomaPageClient.tsx +39 -2
  3. package/app/[...path]/page.tsx +7 -6
  4. package/app/api/[...path]/route.ts +3 -3
  5. package/app/api/soma-registry/[...path]/route.ts +67 -0
  6. package/app/components/SomaHostPage.tsx +3 -8
  7. package/app/components/SomaPageClientBoundary.tsx +13 -0
  8. package/app/layout.tsx +6 -1
  9. package/app/page.tsx +3 -3
  10. package/app/soma/manifest/route.ts +1 -0
  11. package/app/soma/page-object/route.ts +1 -1
  12. package/core/build/compiler/full-manifest-builder.ts +6 -1
  13. package/core/build/compiler/rollup-plugin-soma.ts +6 -0
  14. package/core/build/compiler/soma-manifest-webpack-plugin.js +4 -0
  15. package/core/build/compiler/soma-precompile.js +3507 -2387
  16. package/core/build/compiler/soma-precompile.ts +31 -2
  17. package/core/build/compiler/soma-rspack-yaml-loader.js +3 -0
  18. package/core/build/compiler/soma-webpack-loader.js +7 -1
  19. package/core/build/compiler/vite-plugin-soma.ts +11 -1
  20. package/core/build/component/package-loader.ts +135 -0
  21. package/core/build/eject/apply-eject.ts +133 -0
  22. package/core/build/eject/plan-eject.ts +139 -0
  23. package/core/client/adaptive/flush-scheduler.ts +96 -0
  24. package/core/client/adaptive/hysteresis.ts +56 -0
  25. package/core/client/adaptive/index.ts +23 -0
  26. package/core/client/adaptive/observer-pool.ts +90 -0
  27. package/core/client/base/SomaPageRootBase.ts +50 -0
  28. package/core/client/compiler/adaptive-compile.ts +136 -0
  29. package/core/client/compiler/manifest-compiler.ts +155 -27
  30. package/core/client/component/ai-catalog.ts +262 -0
  31. package/core/client/component/component-definition.types.ts +65 -0
  32. package/core/client/component/component-expander.ts +119 -0
  33. package/core/client/component/component-manager.ts +933 -0
  34. package/core/client/component/component-pack.ts +271 -0
  35. package/core/client/component/component-registry.ts +71 -0
  36. package/core/client/component/pack-styles.ts +94 -0
  37. package/core/client/component/scoped-adapter.ts +85 -0
  38. package/core/client/component/verify-pack.ts +247 -0
  39. package/core/client/container/MiniProgramContainerAdapter.ts +15 -1
  40. package/core/client/container/ReactNativeContainerAdapter.ts +15 -1
  41. package/core/client/container/SomaContainerAdapter.ts +186 -180
  42. package/core/client/data/data-object-resolver.ts +417 -0
  43. package/core/client/diagnostics/SomaDiagnostics.ts +187 -186
  44. package/core/client/diagnostics/boot-timings.ts +152 -0
  45. package/core/client/engine/asset-resolver.ts +12 -2
  46. package/core/client/engine/dom-renderer.ts +235 -16
  47. package/core/client/engine/emit-event.ts +21 -0
  48. package/core/client/engine/event-engine.ts +34 -4
  49. package/core/client/engine/on-change-engine.ts +1 -1
  50. package/core/client/engine/property-watcher.ts +1 -1
  51. package/core/client/engine/reactive-proxy.ts +3 -3
  52. package/core/client/engine/render-engine.ts +43 -4
  53. package/core/client/engine/runtime-builder.ts +23 -0
  54. package/core/client/engine/soma-bootstrap.ts +389 -5
  55. package/core/client/engine/style-binder.ts +47 -1
  56. package/core/client/host-bridge/empty-host/data/README.md +17 -0
  57. package/core/client/infra/http/SomaHttpService.ts +5 -0
  58. package/core/client/observability/error-reporter.ts +173 -0
  59. package/core/client/parser/adaptive-parser.ts +264 -0
  60. package/core/client/parser/data-config-parser.ts +396 -0
  61. package/core/client/parser/pipeline-parser.ts +15 -3
  62. package/core/client/parser/style-config-parser.ts +65 -2
  63. package/core/client/parser/ui-config-parser.ts +52 -3
  64. package/core/client/pipes/pipe-registry.ts +249 -0
  65. package/core/client/quality/SomaQualityRegistry.ts +3 -0
  66. package/core/client/registry/declaration-renderer.ts +159 -0
  67. package/core/client/registry/index.ts +28 -0
  68. package/core/client/registry/page-lifecycle.ts +171 -0
  69. package/core/client/registry/remote-page.ts +139 -0
  70. package/core/client/runtime/SomaRuntimeServices.ts +24 -0
  71. package/core/client/scheduler/SomaScheduler.ts +29 -1
  72. package/core/client/security/attribute-presence.ts +70 -0
  73. package/core/client/security/html-sanitizer.ts +113 -0
  74. package/core/client/security/url-guard.ts +0 -0
  75. package/core/client/theme/theme-engine.ts +936 -0
  76. package/core/client/typography/typography-base.ts +34 -0
  77. package/core/client/validation/contract-validator.ts +48 -5
  78. package/core/index.ts +190 -2
  79. package/core/server/api/IService.ts +18 -6
  80. package/core/server/api/load-host-service.ts +3 -3
  81. package/core/server/host/content-security-policy.ts +190 -0
  82. package/core/server/host/csp-nonce-metadata.ts +75 -0
  83. package/core/server/host/resolve-host-request-hook.ts +5 -0
  84. package/core/server/host/server-page-assets.ts +10 -0
  85. package/core/server/index.ts +30 -1
  86. package/core/server/infra/cache/ServerFileCache.ts +1 -1
  87. package/core/server/mock/node/cli.mjs +2 -2
  88. package/core/server/registry/api-registry-store.ts +518 -0
  89. package/core/server/registry/conditional-object-store.ts +29 -0
  90. package/core/server/registry/declaration-precompiler.ts +129 -0
  91. package/core/server/registry/in-memory-conditional-object-store.ts +43 -0
  92. package/core/server/registry/index.ts +142 -0
  93. package/core/server/registry/page-registry-repository.ts +373 -0
  94. package/core/server/registry/page-registry-store.ts +903 -0
  95. package/core/server/registry/registry-error.ts +17 -0
  96. package/core/server/registry/registry-file-lock.ts +173 -0
  97. package/core/server/registry/registry-response.ts +71 -0
  98. package/core/server/registry/registry-subjects.ts +194 -0
  99. package/core/server/registry/registry-write-pipeline.ts +240 -0
  100. package/core/server/registry/request-body-limit.ts +99 -0
  101. package/core/server/registry/services/apis/Get.ts +25 -0
  102. package/core/server/registry/services/apis/List.ts +41 -0
  103. package/core/server/registry/services/apis/Register.ts +39 -0
  104. package/core/server/registry/services/apis/Unregister.ts +24 -0
  105. package/core/server/registry/services/index.ts +40 -0
  106. package/core/server/registry/services/pages/Get.ts +86 -0
  107. package/core/server/registry/services/pages/List.ts +53 -0
  108. package/core/server/registry/services/pages/Register.ts +49 -0
  109. package/core/server/registry/services/pages/Rollback.ts +36 -0
  110. package/core/server/registry/services/pages/Unregister.ts +23 -0
  111. package/core/server/registry/services/service-utils.ts +21 -0
  112. package/core/server/registry/validation/compile-gate.ts +71 -0
  113. package/core/server/registry/validation/component-existence.ts +55 -0
  114. package/core/server/registry/validation/credential-ban.ts +86 -0
  115. package/core/server/registry/validation/cross-check.ts +77 -0
  116. package/core/server/registry/validation/declaration-safety-scan.ts +102 -0
  117. package/core/shared/types/adaptive.types.ts +109 -0
  118. package/core/shared/types/component-contract.types.ts +110 -0
  119. package/core/shared/types/data-config.types.ts +105 -0
  120. package/core/shared/types/domain.types.ts +6 -0
  121. package/core/shared/types/engine.types.ts +41 -35
  122. package/core/shared/types/manifest.types.ts +55 -32
  123. package/core/shared/types/scope-manifest.types.ts +96 -0
  124. package/core/shared/types/style-config.types.ts +9 -0
  125. package/core/shared/types/ui-config.types.ts +118 -98
  126. package/dist/cli/soma.js +20 -5
  127. package/dist/core/index.cjs +5388 -888
  128. package/dist/types/build/compiler/full-manifest-builder.d.ts +4 -0
  129. package/dist/types/build/compiler/rollup-plugin-soma.d.ts +1 -0
  130. package/dist/types/build/compiler/soma-precompile.d.ts +9 -0
  131. package/dist/types/build/compiler/vite-plugin-soma.d.ts +3 -0
  132. package/dist/types/build/component/package-loader.d.ts +9 -0
  133. package/dist/types/build/eject/apply-eject.d.ts +22 -0
  134. package/dist/types/build/eject/plan-eject.d.ts +32 -0
  135. package/dist/types/client/adaptive/flush-scheduler.d.ts +13 -0
  136. package/dist/types/client/adaptive/hysteresis.d.ts +16 -0
  137. package/dist/types/client/adaptive/index.d.ts +5 -0
  138. package/dist/types/client/adaptive/observer-pool.d.ts +15 -0
  139. package/dist/types/client/base/SomaPageRootBase.d.ts +33 -0
  140. package/dist/types/client/compiler/adaptive-compile.d.ts +26 -0
  141. package/dist/types/client/compiler/manifest-compiler.d.ts +13 -2
  142. package/dist/types/client/component/ai-catalog.d.ts +73 -0
  143. package/dist/types/client/component/component-definition.types.d.ts +54 -0
  144. package/dist/types/client/component/component-expander.d.ts +25 -0
  145. package/dist/types/client/component/component-manager.d.ts +160 -0
  146. package/dist/types/client/component/component-pack.d.ts +90 -0
  147. package/dist/types/client/component/component-registry.d.ts +12 -0
  148. package/dist/types/client/component/pack-styles.d.ts +22 -0
  149. package/dist/types/client/component/scoped-adapter.d.ts +18 -0
  150. package/dist/types/client/component/verify-pack.d.ts +14 -0
  151. package/dist/types/client/data/data-object-resolver.d.ts +71 -0
  152. package/dist/types/client/diagnostics/SomaDiagnostics.d.ts +2 -1
  153. package/dist/types/client/diagnostics/boot-timings.d.ts +30 -0
  154. package/dist/types/client/engine/asset-resolver.d.ts +7 -1
  155. package/dist/types/client/engine/dom-renderer.d.ts +49 -1
  156. package/dist/types/client/engine/emit-event.d.ts +6 -0
  157. package/dist/types/client/engine/event-engine.d.ts +6 -0
  158. package/dist/types/client/engine/render-engine.d.ts +26 -1
  159. package/dist/types/client/engine/runtime-builder.d.ts +7 -0
  160. package/dist/types/client/engine/soma-bootstrap.d.ts +122 -0
  161. package/dist/types/client/infra/http/SomaHttpService.d.ts +2 -0
  162. package/dist/types/client/observability/error-reporter.d.ts +51 -0
  163. package/dist/types/client/parser/adaptive-parser.d.ts +28 -0
  164. package/dist/types/client/parser/data-config-parser.d.ts +34 -0
  165. package/dist/types/client/parser/pipeline-parser.d.ts +2 -0
  166. package/dist/types/client/parser/style-config-parser.d.ts +5 -3
  167. package/dist/types/client/parser/ui-config-parser.d.ts +22 -1
  168. package/dist/types/client/pipes/pipe-registry.d.ts +38 -0
  169. package/dist/types/client/registry/declaration-renderer.d.ts +51 -0
  170. package/dist/types/client/registry/index.d.ts +10 -0
  171. package/dist/types/client/registry/page-lifecycle.d.ts +61 -0
  172. package/dist/types/client/registry/remote-page.d.ts +52 -0
  173. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +16 -0
  174. package/dist/types/client/scheduler/SomaScheduler.d.ts +8 -0
  175. package/dist/types/client/security/attribute-presence.d.ts +7 -0
  176. package/dist/types/client/security/html-sanitizer.d.ts +37 -0
  177. package/dist/types/client/security/url-guard.d.ts +11 -0
  178. package/dist/types/client/theme/theme-engine.d.ts +49 -0
  179. package/dist/types/client/typography/typography-base.d.ts +15 -0
  180. package/dist/types/client/validation/contract-validator.d.ts +2 -0
  181. package/dist/types/index.d.ts +36 -2
  182. package/dist/types/server/api/IService.d.ts +18 -6
  183. package/dist/types/server/host/content-security-policy.d.ts +53 -0
  184. package/dist/types/server/host/csp-nonce-metadata.d.ts +32 -0
  185. package/dist/types/server/host/resolve-host-request-hook.d.ts +5 -0
  186. package/dist/types/server/host/server-page-assets.d.ts +5 -0
  187. package/dist/types/server/index.d.ts +4 -1
  188. package/dist/types/server/registry/api-registry-store.d.ts +141 -0
  189. package/dist/types/server/registry/conditional-object-store.d.ts +27 -0
  190. package/dist/types/server/registry/declaration-precompiler.d.ts +30 -0
  191. package/dist/types/server/registry/in-memory-conditional-object-store.d.ts +8 -0
  192. package/dist/types/server/registry/index.d.ts +29 -0
  193. package/dist/types/server/registry/page-registry-repository.d.ts +58 -0
  194. package/dist/types/server/registry/page-registry-store.d.ts +259 -0
  195. package/dist/types/server/registry/registry-error.d.ts +12 -0
  196. package/dist/types/server/registry/registry-file-lock.d.ts +20 -0
  197. package/dist/types/server/registry/registry-response.d.ts +18 -0
  198. package/dist/types/server/registry/registry-subjects.d.ts +59 -0
  199. package/dist/types/server/registry/registry-write-pipeline.d.ts +48 -0
  200. package/dist/types/server/registry/request-body-limit.d.ts +31 -0
  201. package/dist/types/server/registry/services/apis/Get.d.ts +10 -0
  202. package/dist/types/server/registry/services/apis/List.d.ts +10 -0
  203. package/dist/types/server/registry/services/apis/Register.d.ts +13 -0
  204. package/dist/types/server/registry/services/apis/Unregister.d.ts +12 -0
  205. package/dist/types/server/registry/services/index.d.ts +3 -0
  206. package/dist/types/server/registry/services/pages/Get.d.ts +10 -0
  207. package/dist/types/server/registry/services/pages/List.d.ts +13 -0
  208. package/dist/types/server/registry/services/pages/Register.d.ts +11 -0
  209. package/dist/types/server/registry/services/pages/Rollback.d.ts +9 -0
  210. package/dist/types/server/registry/services/pages/Unregister.d.ts +9 -0
  211. package/dist/types/server/registry/services/service-utils.d.ts +10 -0
  212. package/dist/types/server/registry/validation/compile-gate.d.ts +10 -0
  213. package/dist/types/server/registry/validation/component-existence.d.ts +14 -0
  214. package/dist/types/server/registry/validation/credential-ban.d.ts +15 -0
  215. package/dist/types/server/registry/validation/cross-check.d.ts +16 -0
  216. package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +15 -0
  217. package/dist/types/shared/types/adaptive.types.d.ts +88 -0
  218. package/dist/types/shared/types/component-contract.types.d.ts +68 -0
  219. package/dist/types/shared/types/data-config.types.d.ts +81 -0
  220. package/dist/types/shared/types/domain.types.d.ts +6 -0
  221. package/dist/types/shared/types/engine.types.d.ts +6 -0
  222. package/dist/types/shared/types/manifest.types.d.ts +23 -0
  223. package/dist/types/shared/types/scope-manifest.types.d.ts +82 -0
  224. package/dist/types/shared/types/style-config.types.d.ts +8 -0
  225. package/dist/types/shared/types/ui-config.types.d.ts +20 -0
  226. package/global.d.ts +12 -0
  227. package/next.config.js +76 -1
  228. package/package.json +32 -11
  229. package/proxy.ts +62 -0
  230. package/core/client/engine/theme-variables.ts +0 -37
  231. package/dist/tsconfig.types.tsbuildinfo +0 -1
  232. package/dist/types/client/engine/theme-variables.d.ts +0 -3
  233. package/middleware.ts +0 -33
@@ -0,0 +1,933 @@
1
+ // 组件管理器:组件实例的完整生命周期编排。
2
+ //
3
+ // 一个组件实例 = 一个复用现有引擎的"迷你页面":
4
+ // 实例作用域根(props + ctrl)→ ScopeResolver → ManifestCompiler
5
+ // → RenderEngine + EventEngine(经 Scoped 适配器隔离锚点)。
6
+ // 页面与实例之间只有两条通道:
7
+ // props 下行(页面路径 → 实例作用域,prop 源变更触发实例整树重渲);
8
+ // emit 上行(契约 emit → 页面 Pipeline,四动词与修饰符原样可用)。
9
+ //
10
+ // 设计规范:soma-core/doc/soma 作用域清单树.md、soma-ui/doc/soma 组件契约.md。
11
+
12
+ import { SomaManifestCompiler } from '../compiler/manifest-compiler';
13
+ import { isKnownDomEvent } from '../parser/pipeline-parser';
14
+ import { SomaRenderEngine } from '../engine/render-engine';
15
+ import { SomaEventEngine } from '../engine/event-engine';
16
+ import { SomaScopeResolver } from '../engine/scope-resolver';
17
+ import { SomaEmitEvent } from '../engine/emit-event';
18
+ import type { SomaScheduler } from '../scheduler/SomaScheduler';
19
+ import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
20
+ import type { SomaRuntimeManifest } from '../../shared/types/manifest.types';
21
+ import type {
22
+ ExtendedShowValue,
23
+ NestedShowMapping,
24
+ ShowMapping,
25
+ ShowValue,
26
+ UiConfig,
27
+ } from '../../shared/types/ui-config.types';
28
+ import type { SomaComponentDefinition } from './component-definition.types';
29
+ import { SOMA_COMPONENT_CTRL_KEY } from './component-definition.types';
30
+ import { SomaComponentRegistry } from './component-registry';
31
+ import {
32
+ SomaComponentExpander,
33
+ SomaComponentExpandError,
34
+ SOMA_CHILD_COMPONENT_ID_ATTR,
35
+ SOMA_COMPONENT_ATTR,
36
+ SOMA_COMPONENT_READY_ATTR,
37
+ } from './component-expander';
38
+ import { SomaScopedContainerAdapter, SOMA_SCOPE_ATTR } from './scoped-adapter';
39
+
40
+ const MAX_EXPANSION_ROUNDS = 8;
41
+
42
+ /** 页面运行时接入点(activate 入参) */
43
+ export interface SomaComponentPageRuntime {
44
+ container: HTMLElement;
45
+ renderEngine: SomaRenderEngine;
46
+ eventEngine: SomaEventEngine;
47
+ resolver: SomaScopeResolver;
48
+ manifest: SomaRuntimeManifest;
49
+ /** 页面运行时服务表(自治组件按白名单注入用) */
50
+ services?: Record<string, unknown>;
51
+ }
52
+
53
+ export interface SomaComponentManagerOptions {
54
+ registry: SomaComponentRegistry;
55
+ scheduler?: SomaScheduler;
56
+ diagnostics?: SomaDiagnostics;
57
+ /** 格式化管道注册表(实例内部绑定同样可用管道) */
58
+ pipeRegistry?: import('../pipes/pipe-registry').SomaPipeRegistry;
59
+ }
60
+
61
+ /** 作用域读取器:绑定路径求值 + var 判定(页面作用域 / 行作用域两种实现) */
62
+ interface ScopeReader {
63
+ read(path: string): unknown;
64
+ hasVar(seg: string): boolean;
65
+ }
66
+
67
+ interface StaticInstanceDecl {
68
+ host: HTMLElement;
69
+ instanceId: string;
70
+ def: SomaComponentDefinition;
71
+ propsDecl: Record<string, unknown>;
72
+ }
73
+
74
+ export class SomaComponentManager {
75
+ private readonly registry: SomaComponentRegistry;
76
+ private readonly scheduler?: SomaScheduler;
77
+ private readonly diagnostics?: SomaDiagnostics;
78
+ private readonly pipeRegistry?: import('../pipes/pipe-registry').SomaPipeRegistry;
79
+ private readonly expander = new SomaComponentExpander();
80
+
81
+ private staticDecls: StaticInstanceDecl[] = [];
82
+ private propsIndex = new Map<string, Record<string, unknown>>();
83
+ private readonly instances = new Set<SomaComponentInstance>();
84
+ private readonly hostInstances = new WeakMap<HTMLElement, SomaComponentInstance>();
85
+ private readonly watchDisposers: Array<() => void> = [];
86
+ private page: SomaComponentPageRuntime | null = null;
87
+
88
+ constructor(options: SomaComponentManagerOptions) {
89
+ this.registry = options.registry;
90
+ this.scheduler = options.scheduler;
91
+ this.diagnostics = options.diagnostics;
92
+ this.pipeRegistry = options.pipeRegistry;
93
+ }
94
+
95
+ /**
96
+ * 阶段 A(页面引擎构建前):展开容器内全部静态实例的模板。
97
+ * 组件嵌套(插槽内容里再放组件)通过多轮扫描收敛,超过深度上限报错。
98
+ */
99
+ prepare(container: HTMLElement, uiConfig: UiConfig): void {
100
+ this.propsIndex = collectPagePropsDecls(uiConfig.show);
101
+ this.staticDecls = [];
102
+
103
+ for (let round = 0; round < MAX_EXPANSION_ROUNDS + 1; round++) {
104
+ const pending = Array.from(
105
+ container.querySelectorAll<HTMLElement>(`[${SOMA_COMPONENT_ATTR}]`),
106
+ ).filter((host) =>
107
+ !this.expander.isExpanded(host) && !host.hasAttribute(SOMA_CHILD_COMPONENT_ID_ATTR),
108
+ );
109
+
110
+ if (pending.length === 0) {
111
+ return;
112
+ }
113
+ if (round === MAX_EXPANSION_ROUNDS) {
114
+ throw new SomaComponentExpandError(
115
+ `组件嵌套深度超过上限 ${MAX_EXPANSION_ROUNDS}(可能存在循环引用)`,
116
+ );
117
+ }
118
+
119
+ for (const host of pending) {
120
+ const name = host.getAttribute(SOMA_COMPONENT_ATTR)!;
121
+ const instanceId = host.getAttribute('data-soma-id');
122
+ if (!instanceId) {
123
+ throw new SomaComponentExpandError(`组件 "${name}" 的宿主元素缺少 data-soma-id`);
124
+ }
125
+ const def = this.registry.get(name);
126
+ this.expander.expand(host, def);
127
+ this.staticDecls.push({
128
+ host,
129
+ instanceId,
130
+ def,
131
+ propsDecl: this.propsIndex.get(instanceId) ?? {},
132
+ });
133
+ }
134
+ }
135
+ }
136
+
137
+ /**
138
+ * 阶段 B(页面引擎构建后):标记 emit 路由、挂载静态实例、
139
+ * 注册 prop 源路径 watch、装配行内组件钩子。
140
+ */
141
+ activate(page: SomaComponentPageRuntime): void {
142
+ this.page = page;
143
+ this.markEmitRoutes(page);
144
+
145
+ for (const decl of this.staticDecls) {
146
+ const reader = this.createPageReader(page);
147
+ const instance = this.mountInstance(decl.host, decl.instanceId, decl.def, decl.propsDecl, reader);
148
+ this.registerPropWatches(page, decl, instance, reader);
149
+ }
150
+
151
+ page.renderEngine.setComponentHook((element, propsDecl, rowData) => {
152
+ this.applyRowComponent(element, propsDecl, rowData);
153
+ });
154
+ // 挂载与释放必须成对装配:列表 diff 删掉的行要带走它自己的实例
155
+ page.renderEngine.setComponentReleaseHook((removedRoot) => {
156
+ this.releaseSubtree(removedRoot);
157
+ });
158
+ // 页面首渲发生在钩子装配前(runtime-builder 内部),补一次全量渲染
159
+ // 让首屏列表行内的组件实例完成展开挂载(仅组件页面支付此成本)
160
+ page.renderEngine.render();
161
+ }
162
+
163
+ destroy(): void {
164
+ for (const dispose of this.watchDisposers) {
165
+ dispose();
166
+ }
167
+ this.watchDisposers.length = 0;
168
+ for (const instance of this.instances) {
169
+ instance.destroy();
170
+ }
171
+ this.instances.clear();
172
+ this.staticDecls = [];
173
+ this.page?.renderEngine.setComponentHook(null);
174
+ this.page?.renderEngine.setComponentReleaseHook(null);
175
+ this.page = null;
176
+ }
177
+
178
+ /**
179
+ * 一段渲染产物离开 DOM:销毁其中的全部组件实例(含嵌套的孙实例)。
180
+ *
181
+ * 三件事必须一起做,缺一条就还是泄漏:
182
+ * 出强引用实例表(`instances` 是 Set,不是 WeakMap —— 它才是内存泄漏点);
183
+ * 出宿主索引(否则同一元素若被复用会拿到已死实例);
184
+ * `instance.destroy()`(onUnmount + eventEngine.destroy + renderEngine.destroy)。
185
+ *
186
+ * 子树里的实例既可能是行内实例(applyRowComponent),也可能是它们模板里的
187
+ * 子实例(applyChildComponent)——两者都登记在 hostInstances 上,一次遍历全收。
188
+ */
189
+ private releaseSubtree(root: HTMLElement): void {
190
+ if (this.instances.size === 0) {
191
+ return;
192
+ }
193
+ // 被摘除的行根元素自己就可能是组件宿主(行模板根 = 组件)
194
+ this.releaseHost(root);
195
+ for (const host of Array.from(
196
+ root.querySelectorAll<HTMLElement>(`[${SOMA_COMPONENT_ATTR}]`),
197
+ )) {
198
+ this.releaseHost(host);
199
+ }
200
+ }
201
+
202
+ private releaseHost(host: HTMLElement): void {
203
+ const instance = this.hostInstances.get(host);
204
+ if (!instance) {
205
+ return;
206
+ }
207
+ this.hostInstances.delete(host);
208
+ this.instances.delete(instance);
209
+ instance.destroy();
210
+ }
211
+
212
+ // ─── 行内实例(dom-renderer 钩子) ─────────────────────────
213
+
214
+ private applyRowComponent(
215
+ element: HTMLElement,
216
+ propsDecl: Record<string, unknown>,
217
+ rowData: unknown,
218
+ ): void {
219
+ const name = element.getAttribute(SOMA_COMPONENT_ATTR);
220
+ if (!name) {
221
+ console.warn('[soma-core][组件] props 声明的锚点不是组件宿主(缺少 data-soma-component):', element);
222
+ return;
223
+ }
224
+ if (!this.page) {
225
+ return;
226
+ }
227
+
228
+ const reader = this.createRowReader(this.page, rowData);
229
+ const existing = this.hostInstances.get(element);
230
+ if (existing) {
231
+ existing.setProps(resolveProps(propsDecl, reader, existing.def));
232
+ return;
233
+ }
234
+
235
+ const instanceId = element.getAttribute('data-soma-id');
236
+ if (!instanceId) {
237
+ throw new SomaComponentExpandError(`组件 "${name}" 的宿主元素缺少 data-soma-id`);
238
+ }
239
+ const def = this.registry.get(name);
240
+ this.expander.expand(element, def);
241
+ this.mountInstance(element, instanceId, def, propsDecl, reader);
242
+ }
243
+
244
+ // ─── 实例装配 ──────────────────────────────────────────────
245
+
246
+ private mountInstance(
247
+ host: HTMLElement,
248
+ instanceId: string,
249
+ def: SomaComponentDefinition,
250
+ propsDecl: Record<string, unknown>,
251
+ reader: ScopeReader,
252
+ ): SomaComponentInstance {
253
+ const instance = new SomaComponentInstance({
254
+ host,
255
+ instanceId,
256
+ def,
257
+ initialProps: resolveProps(propsDecl, reader, def),
258
+ scheduler: this.scheduler,
259
+ diagnostics: this.diagnostics,
260
+ pipeRegistry: this.pipeRegistry,
261
+ services: this.filterServices(def),
262
+ dispatchEmit: (emitName, payload) => this.dispatchEmit(instanceId, host, emitName, payload),
263
+ registry: this.registry,
264
+ expandNested: (root) => this.expandNestedTemplates(root),
265
+ mountChild: (parent, childHost, childPropsDecl, rowData) =>
266
+ this.applyChildComponent(parent, childHost, childPropsDecl, rowData),
267
+ releaseSubtree: (removedRoot) => this.releaseSubtree(removedRoot),
268
+ });
269
+ this.instances.add(instance);
270
+ this.hostInstances.set(host, instance);
271
+ return instance;
272
+ }
273
+
274
+ /**
275
+ * 父组件模板里的真实子组件:props 在父实例作用域求值,emit 回到父实例事件清单。
276
+ * 这是通用组合能力;父子双方仍各自拥有独立 controller / render / event 生命周期。
277
+ */
278
+ private applyChildComponent(
279
+ parent: SomaComponentInstance,
280
+ element: HTMLElement,
281
+ propsDecl: Record<string, unknown>,
282
+ rowData: unknown,
283
+ ): void {
284
+ const name = element.getAttribute(SOMA_COMPONENT_ATTR);
285
+ const childId = element.getAttribute(SOMA_CHILD_COMPONENT_ID_ATTR);
286
+ if (!name || !childId) return;
287
+
288
+ const reader = this.createChildReader(parent, rowData);
289
+ const existing = this.hostInstances.get(element);
290
+ if (existing) {
291
+ existing.setProps(resolveProps(propsDecl, reader, existing.def));
292
+ return;
293
+ }
294
+
295
+ const def = this.registry.get(name);
296
+ this.expander.expand(element, def);
297
+ const child = new SomaComponentInstance({
298
+ host: element,
299
+ instanceId: childId,
300
+ def,
301
+ initialProps: resolveProps(propsDecl, reader, def),
302
+ scheduler: this.scheduler,
303
+ diagnostics: this.diagnostics,
304
+ pipeRegistry: this.pipeRegistry,
305
+ services: this.filterServices(def),
306
+ registry: this.registry,
307
+ expandNested: (root) => this.expandNestedTemplates(root),
308
+ mountChild: (owner, childHost, childProps, nestedRow) =>
309
+ this.applyChildComponent(owner, childHost, childProps, nestedRow),
310
+ releaseSubtree: (removedRoot) => this.releaseSubtree(removedRoot),
311
+ dispatchEmit: (emitName, payload) => parent.dispatchChildEmit(childId, element, emitName, payload),
312
+ });
313
+ this.instances.add(child);
314
+ this.hostInstances.set(element, child);
315
+ }
316
+
317
+ /**
318
+ * 阶段 A'(**实例编译之前**):把宿主子树里静态嵌套的子组件**结构**先展开。
319
+ *
320
+ * 只展开、不建实例。目的只有一个:让**插槽投影先于父的编译发生**。
321
+ * 不这么做的话,父模板写在 `<template data-soma-slot>` 里的那段内容在父编译时
322
+ * 还封在 template 里——querySelectorAll 不下钻 template content,
323
+ * SomaDomRenderer.bindEntry 找不到锚点就直接 `return null`,绑定被**整条丢弃**,
324
+ * 于是投影进去的文本渲染成 "--"、列表渲染成空,且全程不报错。
325
+ * (页面把内容投影进组件插槽之所以是通的,正是因为 prepare() 早于页面编译。
326
+ * 这里补的是同一件事在组件层的对称形态。)
327
+ *
328
+ * 多轮收敛:一轮展开会把插槽内容搬进 DOM,其中可能还有孙组件宿主,下一轮接着展开。
329
+ * 未注册的组件名在此静默跳过(不阻塞收敛),照旧由 applyChildComponent 抛错点名。
330
+ */
331
+ private expandNestedTemplates(root: HTMLElement): void {
332
+ for (let round = 0; round < MAX_EXPANSION_ROUNDS + 1; round++) {
333
+ const pending = Array.from(
334
+ root.querySelectorAll<HTMLElement>(`[${SOMA_CHILD_COMPONENT_ID_ATTR}]`),
335
+ ).filter((host) => {
336
+ if (this.expander.isExpanded(host)) return false;
337
+ const name = host.getAttribute(SOMA_COMPONENT_ATTR);
338
+ return !!name && this.registry.has(name);
339
+ });
340
+
341
+ if (pending.length === 0) {
342
+ return;
343
+ }
344
+ if (round === MAX_EXPANSION_ROUNDS) {
345
+ throw new SomaComponentExpandError(
346
+ `组件嵌套深度超过上限 ${MAX_EXPANSION_ROUNDS}(可能存在循环引用)`,
347
+ );
348
+ }
349
+ for (const host of pending) {
350
+ this.expander.expand(host, this.registry.get(host.getAttribute(SOMA_COMPONENT_ATTR)!));
351
+ }
352
+ }
353
+ }
354
+
355
+ private createChildReader(parent: SomaComponentInstance, rowData: unknown): ScopeReader {
356
+ return {
357
+ read: (path: string) => parent.read(path, rowData),
358
+ hasVar: (seg: string) => parent.hasVar(seg),
359
+ };
360
+ }
361
+
362
+ /** 自治组件服务注入:按定义白名单过滤页面服务表(白名单外不可见) */
363
+ private filterServices(def: SomaComponentDefinition): Record<string, unknown> | undefined {
364
+ if (!def.services?.length) {
365
+ return undefined;
366
+ }
367
+ const source = (this.page?.services ?? {}) as Record<string, unknown>;
368
+ const filtered: Record<string, unknown> = {};
369
+ for (const name of def.services) {
370
+ if (name in source) {
371
+ filtered[name] = source[name];
372
+ } else {
373
+ console.warn(`[soma-core][组件] 组件 "${def.contract.name}" 声明的服务 "${name}" 不存在于页面运行时`);
374
+ }
375
+ }
376
+ return filtered;
377
+ }
378
+
379
+ /** 页面订阅了的契约 emit → 走页面 Pipeline;未订阅静默丢弃(契约规范第 4 章) */
380
+ private dispatchEmit(instanceId: string, host: HTMLElement, emitName: string, payload: unknown): void {
381
+ const config = this.page?.manifest.eventIndex.get(`${emitName}:${instanceId}`);
382
+ if (!config?.emitRoute || !this.page) {
383
+ return;
384
+ }
385
+ void this.page.eventEngine.execute(config, host, new SomaEmitEvent(emitName, payload));
386
+ }
387
+
388
+ /**
389
+ * 把页面事件清单中"实例id.契约emit名"的条目标记为 emit 路由。
390
+ * 覆盖静态实例与行模板内的实例(模板内容递归扫描)。
391
+ */
392
+ private markEmitRoutes(page: SomaComponentPageRuntime): void {
393
+ const hosts = new Map<string, string>();
394
+ collectComponentHosts(page.container, hosts);
395
+
396
+ for (const [instanceId, name] of hosts) {
397
+ if (!this.registry.has(name)) {
398
+ continue;
399
+ }
400
+ const contract = this.registry.get(name).contract;
401
+ for (const emitName of Object.keys(contract.emits ?? {})) {
402
+ const config = page.manifest.eventIndex.get(`${emitName}:${instanceId}`);
403
+ if (config) {
404
+ config.emitRoute = true;
405
+ }
406
+ }
407
+ }
408
+
409
+ // 兜底告警:既非 DOM 事件、又没匹配上任何契约 emit 的订阅(多为拼写错误)
410
+ for (const event of page.manifest.events) {
411
+ if (!event.emitRoute && event.domEvent && !isKnownDomEvent(event.domEvent)) {
412
+ console.warn(
413
+ `[soma-core][组件] 事件订阅 "${event.somaId}.${event.domEvent}" ` +
414
+ `既不是 DOM 事件,也未匹配任何组件契约 emit,永远不会触发`,
415
+ );
416
+ }
417
+ }
418
+ }
419
+
420
+ // ─── props 求值 ────────────────────────────────────────────
421
+
422
+ private createPageReader(page: SomaComponentPageRuntime): ScopeReader {
423
+ return {
424
+ read: (path: string) => {
425
+ const resolved = page.resolver.resolvePath(path);
426
+ return page.resolver.readFromRoot(resolved);
427
+ },
428
+ hasVar: (seg: string) => page.resolver.hasVar(seg),
429
+ };
430
+ }
431
+
432
+ /** 行作用域读取:与 dom-renderer.resolveShowValue 同语义 */
433
+ private createRowReader(page: SomaComponentPageRuntime, rowData: unknown): ScopeReader {
434
+ return {
435
+ read: (path: string) => {
436
+ const segments = path.split('.');
437
+ const firstSeg = segments[0];
438
+ if (page.resolver.hasVar(firstSeg)) {
439
+ const varPath = page.resolver.getVarPath(firstSeg);
440
+ if (!varPath) {
441
+ return page.resolver.readFromRoot(segments.slice(1).join('.'));
442
+ }
443
+ return segments.slice(1).reduce((obj: any, key) => obj?.[key], rowData);
444
+ }
445
+ return segments.reduce((obj: any, key) => obj?.[key], rowData);
446
+ },
447
+ hasVar: (seg: string) => page.resolver.hasVar(seg),
448
+ };
449
+ }
450
+
451
+ /** 静态实例的 prop 源路径 watch:源变更 → 重解析 → 实例更新 */
452
+ private registerPropWatches(
453
+ page: SomaComponentPageRuntime,
454
+ decl: StaticInstanceDecl,
455
+ instance: SomaComponentInstance,
456
+ reader: ScopeReader,
457
+ ): void {
458
+ const paths = new Set<string>();
459
+ collectBindingPaths(decl.propsDecl, page.resolver, paths);
460
+
461
+ for (const path of paths) {
462
+ const resolved = page.resolver.resolvePath(path);
463
+ const dispose = page.renderEngine.watch(resolved, () => {
464
+ instance.setProps(resolveProps(decl.propsDecl, reader, decl.def));
465
+ });
466
+ this.watchDisposers.push(dispose);
467
+ }
468
+ }
469
+ }
470
+
471
+ // ─── 组件实例 ────────────────────────────────────────────────
472
+
473
+ interface SomaComponentInstanceOptions {
474
+ host: HTMLElement;
475
+ instanceId: string;
476
+ def: SomaComponentDefinition;
477
+ initialProps: Record<string, unknown>;
478
+ scheduler?: SomaScheduler;
479
+ diagnostics?: SomaDiagnostics;
480
+ pipeRegistry?: import('../pipes/pipe-registry').SomaPipeRegistry;
481
+ services?: Record<string, unknown>;
482
+ dispatchEmit: (emitName: string, payload: unknown) => void;
483
+ registry: SomaComponentRegistry;
484
+ /** 编译前的结构展开(插槽投影必须先于编译完成,见 expandNestedTemplates) */
485
+ expandNested: (root: HTMLElement) => void;
486
+ mountChild: (
487
+ parent: SomaComponentInstance,
488
+ host: HTMLElement,
489
+ propsDecl: Record<string, unknown>,
490
+ rowData: unknown,
491
+ ) => void;
492
+ /** 本实例内部列表删行时的释放通道(与 mountChild 成对,见 releaseSubtree) */
493
+ releaseSubtree: (removedRoot: HTMLElement) => void;
494
+ }
495
+
496
+ export class SomaComponentInstance {
497
+ readonly def: SomaComponentDefinition;
498
+ private readonly scopeRoot: Record<string, unknown>;
499
+ private readonly renderEngine: SomaRenderEngine;
500
+ private readonly eventEngine: SomaEventEngine;
501
+ private readonly resolver: SomaScopeResolver;
502
+ private readonly manifest: SomaRuntimeManifest;
503
+ private destroyed = false;
504
+ /**
505
+ * 模板里静态嵌套的子组件(宿主元素 + 父 uiConfig 里那份 props 声明)。
506
+ *
507
+ * 为什么要记住:父实例的作用域根是普通对象、没有响应式代理,
508
+ * 走的是"整树重渲"的路子,而 `props` 声明**不生成绑定**
509
+ * (manifest-compiler 只为 text/model/when/class/show 生成),
510
+ * 所以子组件不在任何 watch 里。页面层的静态实例有 registerPropWatches
511
+ * 补这一课,组件层此前没有对应通道——子组件因此永远停在首帧值,
512
+ * 父把 expanded/loading 这类受控 props 下发给子的写法在真实页面上是坏的,
513
+ * 而且不报错:单测只要断言 emit 上行就全绿。
514
+ */
515
+ private readonly staticChildren: Array<{
516
+ host: HTMLElement;
517
+ propsDecl: Record<string, unknown>;
518
+ }> = [];
519
+ private readonly mountChild: SomaComponentInstanceOptions['mountChild'];
520
+
521
+ constructor(options: SomaComponentInstanceOptions) {
522
+ this.def = options.def;
523
+ this.mountChild = options.mountChild;
524
+ this.scopeRoot = { ...options.initialProps };
525
+
526
+ if (options.def.controllerFactory) {
527
+ this.scopeRoot[SOMA_COMPONENT_CTRL_KEY] = options.def.controllerFactory({
528
+ props: this.scopeRoot,
529
+ emit: (name, payload) => options.dispatchEmit(name, payload),
530
+ host: options.host,
531
+ services: options.services,
532
+ // 惰性求值:工厂执行时引擎尚未就绪,refresh 只在实例存活且引擎可用时生效
533
+ refresh: () => {
534
+ if (!this.destroyed && this.renderEngine) {
535
+ this.rerender();
536
+ }
537
+ },
538
+ });
539
+ }
540
+
541
+ const uiConfig: UiConfig = options.def.uiConfig ?? {
542
+ bind: { obj: '__component', var: 'p' },
543
+ show: {},
544
+ };
545
+
546
+ this.resolver = new SomaScopeResolver();
547
+ this.resolver.build(uiConfig, this.scopeRoot);
548
+
549
+ // 本实例的作用域标记:展开器写在宿主的 ready 属性上。
550
+ // 适配器只认这个 scopeId —— 父实例因此看得见"自己投影进子组件插槽的内容",
551
+ // 同时看不见子组件自己的内部锚点(两者都住在同一棵子树里,只差归属)。
552
+ const scopeId = options.host.getAttribute(SOMA_COMPONENT_READY_ATTR) ?? undefined;
553
+ const adapter = new SomaScopedContainerAdapter(scopeId);
554
+
555
+ // 编译前先把静态子组件的**结构**展开:插槽投影完成后,
556
+ // 投影内容才从 <template> 里进到 DOM,编译器与绑定表才看得见它。
557
+ options.expandNested(options.host);
558
+
559
+ const compiler = new SomaManifestCompiler();
560
+ this.manifest = compiler.compile({
561
+ container: options.host,
562
+ adapter,
563
+ uiConfig,
564
+ eventConfig: options.def.eventConfig ?? [],
565
+ resolver: this.resolver,
566
+ pipes: options.pipeRegistry,
567
+ });
568
+ markChildEmitRoutes(options.host, this.manifest, options.registry, scopeId);
569
+
570
+ this.renderEngine = new SomaRenderEngine({
571
+ container: options.host,
572
+ adapter,
573
+ manifest: this.manifest,
574
+ proxiedInstance: this.scopeRoot,
575
+ resolver: this.resolver,
576
+ scheduler: options.scheduler,
577
+ diagnostics: options.diagnostics,
578
+ pipeRegistry: options.pipeRegistry,
579
+ });
580
+ this.renderEngine.setComponentHook((element, propsDecl, rowData) => {
581
+ if (element.hasAttribute(SOMA_CHILD_COMPONENT_ID_ATTR)) {
582
+ options.mountChild(this, element, propsDecl, rowData);
583
+ }
584
+ });
585
+ // 组件模板自己的行模板里也能实例化子组件(缺口 B),删行同样要带走它们
586
+ this.renderEngine.setComponentReleaseHook((removedRoot) => options.releaseSubtree(removedRoot));
587
+ // 父模板里不在 bind 行模板中的静态子组件不会经过 DomRenderer 的行钩子;
588
+ // 直接按父 uiConfig 的 props 声明挂载。列表克隆中的子组件仍由上面的钩子负责。
589
+ //
590
+ // 只挂**本作用域**声明的子组件宿主:结构展开已经把整棵嵌套树摊平进 DOM,
591
+ // 不按 scope 过滤就会把孙组件(属于子实例)也抢过来挂。反过来,投影进子组件
592
+ // 插槽的孙组件宿主带的是**父**的 scope,正好被这里捞到——这半边此前是漏的
593
+ // (旧代码取的是编译前的 querySelectorAll 快照,投影进来的宿主永远不在里面)。
594
+ const staticChildProps = collectPagePropsDecls(uiConfig.show);
595
+ for (const childHost of Array.from(
596
+ options.host.querySelectorAll<HTMLElement>(ownChildSelector(scopeId)),
597
+ )) {
598
+ const childId = childHost.getAttribute(SOMA_CHILD_COMPONENT_ID_ATTR);
599
+ if (!childId) continue;
600
+ const propsDecl = staticChildProps.get(childId) ?? {};
601
+ this.staticChildren.push({ host: childHost, propsDecl });
602
+ options.mountChild(this, childHost, propsDecl, undefined);
603
+ }
604
+ this.renderEngine.render();
605
+
606
+ this.eventEngine = new SomaEventEngine({
607
+ manifest: this.manifest,
608
+ container: options.host,
609
+ adapter,
610
+ resolver: this.resolver,
611
+ scopeTracker: this.renderEngine.getScopeTracker(),
612
+ callbacks: {
613
+ // 实例作用域根是普通对象(无响应式代理),统一整树重渲(实例子树很小)
614
+ onRefresh: () => this.rerender(),
615
+ onCommit: () => this.rerender(),
616
+ },
617
+ diagnostics: options.diagnostics,
618
+ scheduler: options.scheduler,
619
+ });
620
+ this.eventEngine.init();
621
+
622
+ // 自治组件生命周期:引擎就绪后 onMount(异步完成自动重渲)
623
+ const ctrl = this.scopeRoot[SOMA_COMPONENT_CTRL_KEY] as
624
+ | { onMount?: () => void | Promise<void> }
625
+ | undefined;
626
+ if (typeof ctrl?.onMount === 'function') {
627
+ void Promise.resolve(ctrl.onMount())
628
+ .then(() => {
629
+ if (!this.destroyed) {
630
+ this.rerender();
631
+ }
632
+ })
633
+ .catch((error) => {
634
+ console.warn(`[soma-core][组件] "${options.def.contract.name}" onMount 失败:`, error);
635
+ });
636
+ }
637
+ }
638
+
639
+ /**
640
+ * 整树重渲 + 把新的 props 推给模板里静态嵌套的子组件。
641
+ *
642
+ * 两件事必须绑在一起做:实例这一层的每一次重渲都意味着 `p.*` / `ctrl.*`
643
+ * 可能算出了新值,而子组件的 props 正是由这些表达式求值来的。
644
+ * 分开写迟早会有人新加一处 `renderEngine.render()` 却忘了刷子组件——
645
+ * 那种漏法不报错、只是子组件停在旧值,是最难查的一类。
646
+ */
647
+ private rerender(): void {
648
+ this.renderEngine.render();
649
+ if (this.staticChildren.length === 0) return;
650
+ for (const child of this.staticChildren) {
651
+ this.mountChild(this, child.host, child.propsDecl, undefined);
652
+ }
653
+ }
654
+
655
+ /** props 下行更新:浅合并后整树重渲(ctrl 派生 getter 自然重算) */
656
+ setProps(next: Record<string, unknown>): void {
657
+ if (this.destroyed) {
658
+ return;
659
+ }
660
+ for (const [key, value] of Object.entries(next)) {
661
+ if (key === SOMA_COMPONENT_CTRL_KEY) {
662
+ continue;
663
+ }
664
+ this.scopeRoot[key] = value;
665
+ }
666
+ this.rerender();
667
+ // props 变更钩子:浮层类组件需要在"打开/关闭"翻转时做副作用
668
+ // (焦点陷阱移入与归还、滚动锁定…),这类事情模板绑定表达不了。
669
+ // 可选实现,失败不影响渲染。
670
+ const ctrl = this.scopeRoot[SOMA_COMPONENT_CTRL_KEY] as
671
+ { onPropsChange?: () => void } | undefined;
672
+ try {
673
+ ctrl?.onPropsChange?.();
674
+ } catch (error) {
675
+ console.warn('[soma-core][组件] onPropsChange 失败:', error);
676
+ }
677
+ }
678
+
679
+ getScopeRoot(): Record<string, unknown> {
680
+ return this.scopeRoot;
681
+ }
682
+
683
+ /** 父实例作用域读取;rowData 存在时与列表行内组件的求值语义一致。 */
684
+ read(path: string, rowData?: unknown): unknown {
685
+ const segments = path.split('.');
686
+ const first = segments[0];
687
+ if (rowData !== undefined && this.resolver.hasVar(first) && first !== 'p' && first !== 'ctrl') {
688
+ return segments.slice(1).reduce(
689
+ (value: any, key) => value?.[key],
690
+ rowData,
691
+ );
692
+ }
693
+ const resolved = this.resolver.resolvePath(path);
694
+ return this.resolver.readFromRoot(resolved);
695
+ }
696
+
697
+ hasVar(segment: string): boolean {
698
+ // ctrl 不由 bind 声明,而是引擎注入实例作用域根的(SOMA_COMPONENT_CTRL_KEY),
699
+ // 所以 resolver 的变量表里没有它。但上面的 read() 第一分支已显式为 'ctrl' 留了位置
700
+ // ——设计上它本就该可读,只是这里没同步认它。
701
+ //
702
+ // 后果比"不支持"更糟:resolvePropValue 用 hasVar 判定「路径还是字面量」,
703
+ // 认不出就把 'ctrl.xxx' 当字面量原样下发,子组件渲染出表达式原文、不报错。
704
+ // 于是父组件无法把派生值喂给模板内的子组件,"用组件搭组件"看着能跑却是坏的
705
+ // ——293 个 soma-ui 组件里只有 1 个敢嵌套,多个组件的文件头把这归因于"引擎不支持"。
706
+ //
707
+ // 唯一调用方是子组件 reader(createChildReader),影响面止于子组件 props 求值。
708
+ if (segment === SOMA_COMPONENT_CTRL_KEY) return true;
709
+ return this.resolver.hasVar(segment);
710
+ }
711
+
712
+ /** 子组件契约 emit → 父组件 eventConfig → 父 ctrl;未订阅时静默丢弃。 */
713
+ dispatchChildEmit(
714
+ childId: string,
715
+ childHost: HTMLElement,
716
+ emitName: string,
717
+ payload: unknown,
718
+ ): void {
719
+ if (this.destroyed) return;
720
+ const config = this.manifest.eventIndex.get(`${emitName}:${childId}`);
721
+ if (!config) return;
722
+ void this.eventEngine.execute(config, childHost, new SomaEmitEvent(emitName, payload));
723
+ }
724
+
725
+ destroy(): void {
726
+ if (this.destroyed) {
727
+ return;
728
+ }
729
+ this.destroyed = true;
730
+ const ctrl = this.scopeRoot[SOMA_COMPONENT_CTRL_KEY] as { onUnmount?: () => void } | undefined;
731
+ try {
732
+ ctrl?.onUnmount?.();
733
+ } catch (error) {
734
+ console.warn('[soma-core][组件] onUnmount 失败:', error);
735
+ }
736
+ this.eventEngine.destroy();
737
+ this.renderEngine.setComponentHook(null);
738
+ this.renderEngine.setComponentReleaseHook(null);
739
+ this.renderEngine.destroy();
740
+ this.staticChildren.length = 0;
741
+ }
742
+ }
743
+
744
+ // ─── 求值与遍历工具 ──────────────────────────────────────────
745
+
746
+ /**
747
+ * prop 声明值求值规则(DSL 扩展规范第 2 章):
748
+ * - 字符串:`!path` → 布尔取反;首段是已注册 var → 绑定路径;否则字面量字符串
749
+ * - number / boolean → 字面量
750
+ * - 数组 / 普通对象 → 逐项递归
751
+ */
752
+ function resolvePropValue(value: unknown, reader: ScopeReader): unknown {
753
+ if (typeof value === 'string') {
754
+ if (value.startsWith('!')) {
755
+ return !reader.read(value.slice(1));
756
+ }
757
+ if (reader.hasVar(value.split('.')[0])) {
758
+ return reader.read(value);
759
+ }
760
+ return value;
761
+ }
762
+ if (Array.isArray(value)) {
763
+ return value.map((item) => resolvePropValue(item, reader));
764
+ }
765
+ if (value !== null && typeof value === 'object') {
766
+ const result: Record<string, unknown> = {};
767
+ for (const [key, item] of Object.entries(value)) {
768
+ result[key] = resolvePropValue(item, reader);
769
+ }
770
+ return result;
771
+ }
772
+ return value;
773
+ }
774
+
775
+ /**
776
+ * 契约默认值下发前的隔离拷贝。
777
+ *
778
+ * `prop.default` 是**契约字面量**:它住在组件定义模块里、进程内永久存活,
779
+ * 而同一个 def 对象会发给该组件的每一个实例。直接 `result[x] = prop.default`
780
+ * 等于让所有实例共享同一个数组/对象——一次 push 就全局污染,且跨页面、
781
+ * 跨 hotSwap、跨整个进程不消失,全程零报错。
782
+ * 行内实例把放大系数从"一页一个"抬到"一张表 N 行 N 个"。
783
+ *
784
+ * 写入方不止组件 controller:`SomaRenderEngine.writeToProxy` 沿嵌套 model 路径
785
+ * (`p.values.email`)赋值时也会写进这个共享对象,那条路一行组件代码都不经过。
786
+ *
787
+ * **只浅拷贝,不深拷贝**,理由是数据而不是偏好:
788
+ * soma-ui 全部 310 个容器默认值里,291 个是 `[]`、19 个是 `{}`,
789
+ * 非空的只有 2 个且都是深度 1 的扁平字符串对象——浅拷贝 100% 覆盖。
790
+ * 嵌套内容真要出现,也只可能来自页面下发的数据(那属于页面自己的状态,
791
+ * 按引用下行正是绑定语义),不该由这里代管。
792
+ *
793
+ * 拷贝边界(拷错比不拷更坏,会静默改变语义):
794
+ * 只拷**数组**与**普通对象**;函数、类实例、DOM 节点、Date/Map/Set/RegExp
795
+ * 这类带原型的内建对象与 `null` 一律原样下发——浅拷会把 Date 变成 `{}`、
796
+ * 把类实例剥掉原型链,那是另一种静默失败。
797
+ */
798
+ function isolateContractDefault(value: unknown): unknown {
799
+ if (Array.isArray(value)) {
800
+ return value.slice();
801
+ }
802
+ if (value !== null && typeof value === 'object') {
803
+ const proto = Object.getPrototypeOf(value);
804
+ if (proto === Object.prototype) {
805
+ return { ...(value as Record<string, unknown>) };
806
+ }
807
+ if (proto === null) {
808
+ return Object.assign(Object.create(null), value) as Record<string, unknown>;
809
+ }
810
+ }
811
+ return value;
812
+ }
813
+
814
+ function resolveProps(
815
+ propsDecl: Record<string, unknown>,
816
+ reader: ScopeReader,
817
+ def: SomaComponentDefinition,
818
+ ): Record<string, unknown> {
819
+ const result: Record<string, unknown> = {};
820
+
821
+ // 契约默认值兜底(C4:零 props 可渲染);必须逐实例隔离,见 isolateContractDefault
822
+ for (const [propName, prop] of Object.entries(def.contract.props ?? {})) {
823
+ if (prop.default !== undefined) {
824
+ result[propName] = isolateContractDefault(prop.default);
825
+ }
826
+ }
827
+
828
+ for (const [propName, declValue] of Object.entries(propsDecl)) {
829
+ result[propName] = resolvePropValue(declValue, reader);
830
+ }
831
+ return result;
832
+ }
833
+
834
+ /** 收集页面作用域(含 extended.show 嵌套,不进入 bind 行作用域)的 props 声明 */
835
+ function collectPagePropsDecls(
836
+ show: ShowMapping,
837
+ into = new Map<string, Record<string, unknown>>(),
838
+ ): Map<string, Record<string, unknown>> {
839
+ for (const [rawKey, value] of Object.entries(show)) {
840
+ if (typeof value === 'string' || value === null || typeof value !== 'object') {
841
+ continue;
842
+ }
843
+ if (isNested(value)) {
844
+ continue; // 行作用域内的 props 由渲染钩子按行处理
845
+ }
846
+ const extended = value as ExtendedShowValue;
847
+ if (extended.props) {
848
+ into.set(rawKey.split('@')[0], extended.props);
849
+ }
850
+ if (extended.show) {
851
+ collectPagePropsDecls(extended.show, into);
852
+ }
853
+ }
854
+ return into;
855
+ }
856
+
857
+ /** 递归收集 props 声明里的绑定路径(供 watch 注册) */
858
+ function collectBindingPaths(
859
+ value: unknown,
860
+ resolver: SomaScopeResolver,
861
+ into: Set<string>,
862
+ ): void {
863
+ if (typeof value === 'string') {
864
+ const raw = value.startsWith('!') ? value.slice(1) : value;
865
+ if (resolver.hasVar(raw.split('.')[0])) {
866
+ into.add(raw);
867
+ }
868
+ return;
869
+ }
870
+ if (Array.isArray(value)) {
871
+ for (const item of value) {
872
+ collectBindingPaths(item, resolver, into);
873
+ }
874
+ return;
875
+ }
876
+ if (value !== null && typeof value === 'object') {
877
+ for (const item of Object.values(value)) {
878
+ collectBindingPaths(item, resolver, into);
879
+ }
880
+ }
881
+ }
882
+
883
+ /** 递归收集容器内(含 template 内容)的组件宿主:实例id → 组件名 */
884
+ function collectComponentHosts(root: ParentNode, into: Map<string, string>): void {
885
+ root.querySelectorAll<HTMLElement>(`[${SOMA_COMPONENT_ATTR}]`).forEach((host) => {
886
+ const id = host.getAttribute('data-soma-id');
887
+ const name = host.getAttribute(SOMA_COMPONENT_ATTR);
888
+ if (id && name) {
889
+ into.set(id, name);
890
+ }
891
+ });
892
+ root.querySelectorAll<HTMLTemplateElement>('template').forEach((tpl) => {
893
+ collectComponentHosts(tpl.content, into);
894
+ });
895
+ }
896
+
897
+ /**
898
+ * 「本作用域自己声明的子组件宿主」选择器。
899
+ * 结构展开会把整棵嵌套树摊进同一子树,只靠 data-soma-child-id 已分不清是谁的孩子;
900
+ * scopeId 缺省(宿主未经展开器处理)时退回旧的全捞行为。
901
+ */
902
+ function ownChildSelector(scopeId: string | undefined): string {
903
+ return scopeId
904
+ ? `[${SOMA_CHILD_COMPONENT_ID_ATTR}][${SOMA_SCOPE_ATTR}="${scopeId}"]`
905
+ : `[${SOMA_CHILD_COMPONENT_ID_ATTR}]`;
906
+ }
907
+
908
+ /** 父定义中的 child emit 只走显式路由,绝不能再响应同名冒泡 DOM 事件。 */
909
+ function markChildEmitRoutes(
910
+ root: ParentNode,
911
+ manifest: SomaRuntimeManifest,
912
+ registry: SomaComponentRegistry,
913
+ scopeId?: string,
914
+ ): void {
915
+ const selector = ownChildSelector(scopeId);
916
+ const visit = (scope: ParentNode): void => {
917
+ scope.querySelectorAll<HTMLElement>(selector).forEach((host) => {
918
+ const childId = host.getAttribute(SOMA_CHILD_COMPONENT_ID_ATTR);
919
+ const name = host.getAttribute(SOMA_COMPONENT_ATTR);
920
+ if (!childId || !name || !registry.has(name)) return;
921
+ for (const emitName of Object.keys(registry.get(name).contract.emits ?? {})) {
922
+ const config = manifest.eventIndex.get(`${emitName}:${childId}`);
923
+ if (config) config.emitRoute = true;
924
+ }
925
+ });
926
+ scope.querySelectorAll<HTMLTemplateElement>('template').forEach((template) => visit(template.content));
927
+ };
928
+ visit(root);
929
+ }
930
+
931
+ function isNested(value: ShowValue): value is NestedShowMapping {
932
+ return typeof value === 'object' && value !== null && 'bind' in value && 'show' in value;
933
+ }