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
@@ -17,6 +17,32 @@ import {
17
17
  type SomaPipeRegistry,
18
18
  } from '../pipes/pipe-registry';
19
19
  import type { SomaPipeCall } from '../../shared/types/scope-manifest.types';
20
+ import { SomaRowRange } from './row-range';
21
+ import { SomaRowScope, validateRowKeys, type SomaTypedRowKey } from './row-scope';
22
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
23
+ import type { RepeatPlan } from '../../shared/types/component-tree-artifact.types';
24
+ import { resolveCollectionOutlet, publishCollectionState } from '../component/structure-adapter';
25
+
26
+ interface ExplicitListState {
27
+ element: HTMLElement;
28
+ end: Comment;
29
+ rows: Map<SomaTypedRowKey, SomaRowRange>;
30
+ generation: number;
31
+ }
32
+
33
+ // Component-owned renderers and the page renderer share a physical-page budget.
34
+ // Weak roots/scopes never expose business identities or retain unmounted pages.
35
+ const pageRowBudgets = new WeakMap<HTMLElement, Map<SomaRowScope, HTMLElement>>();
36
+ const rowBudgetMembership = new WeakMap<SomaRowScope, Map<SomaRowScope, HTMLElement>>();
37
+
38
+ function pageRowBudget(element: HTMLElement): Map<SomaRowScope, HTMLElement> {
39
+ let root = element;
40
+ while (root.parentElement && root.parentElement !== root.ownerDocument.body
41
+ && root.parentElement !== root.ownerDocument.documentElement) root = root.parentElement;
42
+ let budget = pageRowBudgets.get(root);
43
+ if (!budget) { budget = new Map(); pageRowBudgets.set(root, budget); }
44
+ return budget;
45
+ }
20
46
 
21
47
  export type ModelWriteBack = (path: string, value: string) => void;
22
48
 
@@ -54,6 +80,16 @@ export class SomaDomRenderer {
54
80
  private componentHook: SomaRowComponentHook | null = null;
55
81
  private componentReleaseHook: SomaRowComponentReleaseHook | null = null;
56
82
  private pipeRegistry: SomaPipeRegistry = defaultPipeRegistry;
83
+ private explicitLists = new Map<HTMLElement, ExplicitListState>();
84
+ private repeatPlans = new Map<string, RepeatPlan>();
85
+
86
+ setRepeatPlans(plans: readonly RepeatPlan[]): void {
87
+ this.repeatPlans.clear();
88
+ for (const plan of plans) {
89
+ if (this.repeatPlans.has(plan.planId)) this.repeatArtifactError('集合计划 id 重复');
90
+ this.repeatPlans.set(plan.planId, plan);
91
+ }
92
+ }
57
93
 
58
94
  setComponentHook(hook: SomaRowComponentHook | null): void {
59
95
  this.componentHook = hook;
@@ -197,11 +233,15 @@ export class SomaDomRenderer {
197
233
  : undefined,
198
234
  childShowConfig: binding.childShowConfig,
199
235
  roleBy: binding.roleBy,
236
+ keyPath: binding.keyPath,
237
+ itemAlias: binding.itemAlias,
238
+ repeatPlanId: binding.repeatPlanId,
200
239
  attrName: binding.attrName,
201
240
  negate: binding.negate,
202
241
  classRules: binding.classRules,
203
242
  pipes: binding.pipes,
204
243
  };
244
+ if (binding.repeatPlanId) this.attachRepeatPlan(entry, binding.repeatPlanId);
205
245
 
206
246
  // 编译渲染函数:消除运行时 switch + 类型判断
207
247
  entry.compiledRender = this.compileRenderFn(entry);
@@ -301,6 +341,11 @@ export class SomaDomRenderer {
301
341
 
302
342
  case 'list':
303
343
  return (v) => {
344
+ if (entry.keyPath) {
345
+ if (!this.collectionReady(entry)) return;
346
+ this.renderExplicitList(entry, v);
347
+ return;
348
+ }
304
349
  if (Array.isArray(v)) this.renderList(entry, v);
305
350
  };
306
351
 
@@ -315,6 +360,7 @@ export class SomaDomRenderer {
315
360
  }
316
361
 
317
362
  destroy(): void {
363
+ for (const state of [...this.explicitLists.values()]) this.disposeExplicitList(state);
318
364
  this.modelAbort.abort();
319
365
  this.modelAbort = new AbortController();
320
366
  this.modelListeners = new WeakSet<HTMLElement>();
@@ -442,6 +488,216 @@ export class SomaDomRenderer {
442
488
  }
443
489
  }
444
490
 
491
+ /** All explicit-key sources share this range reconciler; legacy guessing stays separate. */
492
+ private renderExplicitList(entry: BindingEntry, value: unknown, parentScope?: SomaRowScope): void {
493
+ const alias = entry.itemAlias!;
494
+ const keys = validateRowKeys(value, entry.keyPath!, alias, entry.repeatPlan?.limits);
495
+ const rows = value as unknown[];
496
+ const depth = this.rowDepth(parentScope) + 1;
497
+ if (depth > (entry.repeatPlan?.limits.maxDepth ?? 4)) this.repeatLimit('集合嵌套超过受信深度预算');
498
+ const nextSubtreeSize = this.validateNestedRows(rows, keys, alias, entry.childShowConfig, parentScope, depth, entry.repeatPlan?.limits);
499
+ if (!entry.templateCache) throw new SomaComponentTreeError({
500
+ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat',
501
+ fixHint: '显式键集合缺少完整行模板',
502
+ });
503
+ let state = this.explicitLists.get(entry.element);
504
+ const budget = pageRowBudget(entry.element);
505
+ const replacedRoots = [...(state?.rows.values() ?? [])].flatMap(range => [...range.roots]);
506
+ const replacedScopes = new Set([...(state?.rows.values() ?? [])].map(range => range.scope));
507
+ let replaced = 0;
508
+ for (const [scope, owner] of budget) {
509
+ if (replacedScopes.has(scope) || replacedRoots.some(root => root === owner || root.contains(owner))) replaced++;
510
+ }
511
+ if (budget.size - replaced + nextSubtreeSize > (entry.repeatPlan?.limits.maxPageRows ?? 5000)) this.repeatLimit('页面活跃行数超过受信预算');
512
+ const next = new Map<SomaTypedRowKey, SomaRowRange>();
513
+ const preparedRanges = new Set<SomaRowRange>();
514
+ for (let index = 0; index < rows.length; index++) {
515
+ const key = keys[index];
516
+ const picked = this.pickRowTemplate(entry, rows[index]);
517
+ const existing = state?.rows.get(key);
518
+ if (existing && existing.variant === picked.variant) {
519
+ next.set(key, existing);
520
+ } else {
521
+ if (!picked.template) throw new SomaComponentTreeError({
522
+ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat',
523
+ fixHint: '集合行类型没有可用模板',
524
+ });
525
+ const fragment = picked.template.cloneNode(true) as DocumentFragment;
526
+ if (entry.repeatPlan?.consumerOwner.rowContainer === 'list-item') {
527
+ const row = entry.element.ownerDocument.createElement('li');
528
+ row.append(...Array.from(fragment.childNodes));
529
+ fragment.append(row);
530
+ }
531
+ const scope = new SomaRowScope(alias, key, rows[index], parentScope);
532
+ const range = new SomaRowRange(fragment, scope, picked.variant);
533
+ next.set(key, range);
534
+ preparedRanges.add(range);
535
+ }
536
+ }
537
+ if (!state) {
538
+ const end = entry.element.ownerDocument.createComment('/soma-repeat');
539
+ entry.element.appendChild(end);
540
+ state = { element: entry.element, end, rows: new Map(), generation: 0 };
541
+ this.explicitLists.set(entry.element, state);
542
+ }
543
+ // No DOM mutation happened before all keys, templates and row budgets passed.
544
+ let before: Node = state.end;
545
+ for (const range of [...next.values()].reverse()) {
546
+ range.moveBefore(entry.element, before);
547
+ before = range.start;
548
+ }
549
+ for (const [key, range] of state.rows) {
550
+ if (next.get(key) !== range) this.releaseExplicitRange(range);
551
+ }
552
+ state.rows = next;
553
+ state.generation++;
554
+ let applying: SomaRowRange | undefined;
555
+ try { rows.forEach((data, index) => {
556
+ const range = next.get(keys[index])!;
557
+ applying = range;
558
+ budget.set(range.scope, entry.element);
559
+ rowBudgetMembership.set(range.scope, budget);
560
+ range.scope.update(data);
561
+ for (const root of range.roots) {
562
+ this.scopeTracker?.set(root, range.scope);
563
+ if (range.variant) root.setAttribute('data-soma-variant', range.variant);
564
+ if (entry.childShowConfig) this.applyShowConfig(root, range.scope, entry.childShowConfig);
565
+ this.activateDefaultRowComponents(root, range.scope, entry.childShowConfig);
566
+ }
567
+ }); } catch (error) {
568
+ // A controller may fail after DOM commit. Release every uncommitted/new
569
+ // row and the affected reused row through the same lifecycle hooks.
570
+ if (applying) preparedRanges.add(applying);
571
+ for (const [key, range] of next) {
572
+ if (!preparedRanges.has(range)) continue;
573
+ this.releaseExplicitRange(range);
574
+ next.delete(key);
575
+ }
576
+ if (entry.collectionOwner) publishCollectionState(entry.collectionOwner, entry.element, 'error', next.size, state.generation);
577
+ throw error;
578
+ }
579
+ if (entry.collectionOwner) publishCollectionState(entry.collectionOwner, entry.element, 'ready', next.size, state.generation);
580
+ }
581
+
582
+ private attachRepeatPlan(entry: BindingEntry, planId: string): void {
583
+ const plan = this.repeatPlans.get(planId);
584
+ if (!plan) this.repeatArtifactError('集合绑定引用未知计划');
585
+ if (entry.itemAlias !== plan.itemAlias
586
+ || this.resolver?.resolvePath(plan.sourcePath) !== this.resolver?.resolvePath(entry.dataPath)) {
587
+ this.repeatArtifactError('集合绑定与计划的数据源或行变量不一致');
588
+ }
589
+ const host = entry.element;
590
+ const symbol = host.getAttribute('data-soma-id') ?? host.getAttribute('data-soma-scoped-id');
591
+ if (symbol !== plan.consumerOwner.instanceSymbol) this.repeatArtifactError('集合消费宿主与计划符号不一致');
592
+ const outlet = resolveCollectionOutlet(host, plan);
593
+ const templates = [...outlet.querySelectorAll<HTMLTemplateElement>('template[data-soma-role="item"]')]
594
+ .filter(template => template.getAttribute('data-soma-repeat-template') === plan.rowTemplateId);
595
+ if (templates.length !== 1) this.repeatArtifactError('集合计划没有唯一的完整行模板');
596
+ entry.collectionOwner = host;
597
+ entry.element = outlet;
598
+ entry.templateCache = templates[0].content;
599
+ entry.templatesByRole = undefined;
600
+ entry.repeatPlan = plan;
601
+ entry.keyPath = plan.keyPath;
602
+ entry.type = 'list';
603
+ if (plan.statusPlan.kind === 'async') {
604
+ entry.watchPaths = [...new Set([...(entry.watchPaths ?? []), this.resolver!.resolvePath(plan.statusPlan.statePath)])];
605
+ }
606
+ }
607
+
608
+ private collectionReady(entry: BindingEntry, scope?: SomaRowScope): boolean {
609
+ const plan = entry.repeatPlan;
610
+ if (!plan || plan.statusPlan.kind === 'sync') return true;
611
+ const phase = scope ? this.resolveShowValue(plan.statusPlan.statePath, scope)
612
+ : this.resolver?.readFromRoot(this.resolver.resolvePath(plan.statusPlan.statePath));
613
+ if (!['pending', 'ready', 'error'].includes(phase)) this.repeatArtifactError('异步集合状态必须是 pending/ready/error');
614
+ if (phase === 'ready') return true;
615
+ const state = this.explicitLists.get(entry.element);
616
+ if (entry.collectionOwner) publishCollectionState(entry.collectionOwner, entry.element, phase, state?.rows.size ?? 0, state?.generation ?? 0);
617
+ return false;
618
+ }
619
+
620
+ private repeatArtifactError(fixHint: string): never {
621
+ throw new SomaComponentTreeError({ code: 'CT-ARTIFACT-INCOMPLETE', phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat', fixHint });
622
+ }
623
+
624
+ private activateDefaultRowComponents(root: HTMLElement, scope: SomaRowScope, show?: ShowMapping): void {
625
+ if (!this.componentHook || !this.adapter) return;
626
+ const hosts = [root, ...Array.from(root.querySelectorAll<HTMLElement>('[data-soma-component]'))];
627
+ for (const host of hosts) {
628
+ if (!host.hasAttribute('data-soma-component')) continue;
629
+ let foreignRow = false;
630
+ for (let current: HTMLElement | null = host; current; current = current.parentElement) {
631
+ const owner = this.scopeTracker?.get(current);
632
+ if (owner instanceof SomaRowScope) { foreignRow = owner !== scope; break; }
633
+ if (current === root) break;
634
+ }
635
+ if (foreignRow) continue;
636
+ const id = this.adapter.getAnchorId(host);
637
+ if (!id) continue;
638
+ const config = show?.[id];
639
+ if (config && typeof config === 'object' && config.props) continue;
640
+ this.componentHook(host, {}, scope);
641
+ }
642
+ }
643
+
644
+ private validateNestedRows(
645
+ rows: unknown[], keys: SomaTypedRowKey[], alias: string, show: ShowMapping | undefined,
646
+ parent: SomaRowScope | undefined, depth: number, limits?: RepeatPlan['limits'],
647
+ ): number {
648
+ let count = rows.length;
649
+ const visit = (mapping: ShowMapping, scope: SomaRowScope): void => {
650
+ for (const config of Object.values(mapping)) {
651
+ if (!config || typeof config !== 'object') continue;
652
+ if (this.isNestedShowMapping(config) && (config.bind.key || config.bind.repeatPlanId)) {
653
+ const plan = config.bind.repeatPlanId ? this.repeatPlans.get(config.bind.repeatPlanId) : undefined;
654
+ if (config.bind.repeatPlanId && !plan) this.repeatArtifactError('嵌套集合引用未知计划');
655
+ if (plan?.statusPlan.kind === 'async') {
656
+ const phase = this.resolveShowValue(plan.statusPlan.statePath, scope);
657
+ if (!['pending', 'ready', 'error'].includes(phase)) this.repeatArtifactError('异步集合状态无效');
658
+ if (phase !== 'ready') continue;
659
+ }
660
+ if (depth >= (plan?.limits.maxDepth ?? limits?.maxDepth ?? 4)) this.repeatLimit('集合嵌套超过受信深度预算');
661
+ const values = this.resolveShowValue(config.bind.obj, scope);
662
+ const childKeys = validateRowKeys(values, plan?.keyPath ?? config.bind.key!, config.bind.var, plan?.limits);
663
+ count += this.validateNestedRows(values, childKeys, config.bind.var, config.show, scope, depth + 1, plan?.limits ?? limits);
664
+ } else if (!this.isNestedShowMapping(config) && config.show) visit(config.show, scope);
665
+ }
666
+ };
667
+ if (show) rows.forEach((row, index) => visit(show, new SomaRowScope(alias, keys[index], row, parent)));
668
+ if (count > (limits?.maxPageRows ?? 5000)) this.repeatLimit('页面活跃行数超过受信预算');
669
+ return count;
670
+ }
671
+
672
+ private rowDepth(scope?: SomaRowScope): number {
673
+ let depth = 0;
674
+ for (let current = scope; current; current = current.parent) depth++;
675
+ return depth;
676
+ }
677
+
678
+ private repeatLimit(fixHint: string): never {
679
+ throw new SomaComponentTreeError({ code: 'CT-LIMIT', phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat', fixHint });
680
+ }
681
+
682
+ private releaseExplicitRange(range: SomaRowRange): void {
683
+ rowBudgetMembership.get(range.scope)?.delete(range.scope);
684
+ rowBudgetMembership.delete(range.scope);
685
+ range.release(root => {
686
+ for (const state of [...this.explicitLists.values()]) {
687
+ if (root === state.element || root.contains(state.element)) this.disposeExplicitList(state);
688
+ }
689
+ this.componentReleaseHook?.(root);
690
+ this.scopeTracker?.delete(root);
691
+ });
692
+ }
693
+
694
+ private disposeExplicitList(state: ExplicitListState): void {
695
+ if (!this.explicitLists.delete(state.element)) return;
696
+ for (const range of state.rows.values()) this.releaseExplicitRange(range);
697
+ state.rows.clear();
698
+ state.end.remove();
699
+ }
700
+
445
701
  private appendListItem(entry: BindingEntry, itemData: any): void {
446
702
  if (!this.adapter) return;
447
703
  const { template, variant } = this.pickRowTemplate(entry, itemData);
@@ -542,6 +798,7 @@ export class SomaDomRenderer {
542
798
  if (!element) {
543
799
  return;
544
800
  }
801
+ if (this.componentHook && element.hasAttribute('data-soma-component')) this.componentHook(element, config.props ?? {}, data);
545
802
  // 行内嵌套列表的整块显隐(与行内 when 走同一套解析与可见性写入)
546
803
  if (typeof config.when === 'string') {
547
804
  const { path, negate } = this.parseConditionalPath(config.when);
@@ -554,6 +811,20 @@ export class SomaDomRenderer {
554
811
  const nestedData = this.resolveShowValue(config.bind.obj, data);
555
812
  const role = this.adapter.readRole(element);
556
813
  const templateCache = this.adapter.cloneTemplate(element);
814
+ if (config.bind.repeatPlanId) {
815
+ // RuntimeBuilder performs the first page render before Manager.activate
816
+ // installs row hooks. Nested consumer templates become available on the
817
+ // activation render; never infer their outlet from the authored source.
818
+ if (!this.componentHook && !element.hasAttribute('data-soma-component-ready')) return;
819
+ const entry: BindingEntry = {
820
+ element, type: 'list', dataPath: config.bind.obj,
821
+ itemAlias: config.bind.var, childShowConfig: config.show,
822
+ };
823
+ this.attachRepeatPlan(entry, config.bind.repeatPlanId);
824
+ const parentScope = data instanceof SomaRowScope ? data : undefined;
825
+ if (this.collectionReady(entry, parentScope)) this.renderExplicitList(entry, nestedData, parentScope);
826
+ return;
827
+ }
557
828
  if (!templateCache) {
558
829
  return;
559
830
  }
@@ -561,6 +832,15 @@ export class SomaDomRenderer {
561
832
  const templatesByRole = this.collectRoleTemplates(element);
562
833
  const roleBy = config.bind.role_by;
563
834
 
835
+ if (config.bind.key) {
836
+ this.renderExplicitList({
837
+ element, type: 'list', dataPath: config.bind.obj, templateCache,
838
+ templatesByRole, roleBy, childShowConfig: config.show,
839
+ keyPath: config.bind.key, itemAlias: config.bind.var,
840
+ }, nestedData, data instanceof SomaRowScope ? data : undefined);
841
+ return;
842
+ }
843
+
564
844
  // 行内嵌套列表**每次行重渲都整体重建**,是比顶层列表更快的泄漏路径
565
845
  this.clearRendered(element);
566
846
 
@@ -693,6 +973,9 @@ export class SomaDomRenderer {
693
973
  }
694
974
 
695
975
  private resolveShowValue(valuePath: string, itemData: any): any {
976
+ if (itemData instanceof SomaRowScope) {
977
+ return itemData.read(valuePath, path => this.resolver?.readFromRoot(this.resolver.resolvePath(path)));
978
+ }
696
979
  const segments = valuePath.split('.');
697
980
  const firstSeg = segments[0];
698
981
 
@@ -1,5 +1,6 @@
1
1
  import { recordMetric } from '../diagnostics/telemetry-context';
2
2
  import type { IContainerAdapter } from '../container/IContainerAdapter';
3
+ import { SomaRowScope, readRowPath } from './row-scope';
3
4
  import { SOMA_KEY_MODIFIERS } from '../../shared/types/keyboard.types';
4
5
  import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
5
6
  import { SomaMiddlewareChain } from '../middleware/SomaMiddlewareChain';
@@ -75,6 +76,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
75
76
  originalEvent: Event,
76
77
  ) => TContext;
77
78
  private readonly pendingSet = new Set<string>();
79
+ private pendingRows = new WeakSet<HTMLElement>();
78
80
  private readonly abortController = new AbortController();
79
81
 
80
82
  constructor(options: SomaEventEngineOptions<TContext>) {
@@ -139,7 +141,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
139
141
  // 沿 parentElement 向上找锚点对任何 Element 都成立;交给下游仍按 HTMLElement 类型传,
140
142
  // 下游只用 getAttribute / parentElement / tagName / focus / dataset,SVGElement 同样具备。
141
143
  let el: Element | null = start instanceof Element ? start : null;
142
- while (el && el !== this.container) {
144
+ while (el) {
143
145
  const somaId = this.adapter.getAnchorId(el as HTMLElement);
144
146
  if (somaId) {
145
147
  const indexed = this.manifest.eventIndex.get(`${eventType}:${somaId}`);
@@ -150,6 +152,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
150
152
  return { element: el as HTMLElement, config };
151
153
  }
152
154
  }
155
+ if (el === this.container) break;
153
156
  el = el.parentElement;
154
157
  }
155
158
  return null;
@@ -188,6 +191,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
188
191
  destroy(): void {
189
192
  this.abortController.abort();
190
193
  this.pendingSet.clear();
194
+ this.pendingRows = new WeakSet();
191
195
  }
192
196
 
193
197
  private async executeNow(
@@ -196,7 +200,9 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
196
200
  originalEvent: Event,
197
201
  ): Promise<void> {
198
202
  const startedAt = this.adapter.now();
199
- const currentVar = this.getContext(element);
203
+ const rowContext = this.getContext(element);
204
+ if (rowContext instanceof SomaRowScope && !rowContext.active) return;
205
+ const currentVar = rowContext instanceof SomaRowScope ? rowContext.data : rowContext;
200
206
  const context = {
201
207
  config,
202
208
  element,
@@ -208,7 +214,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
208
214
  };
209
215
 
210
216
  const terminal = async (runtime: SomaEventMiddlewareContext & TContext): Promise<void> => {
211
- if (!this.preCheck(config, config.somaId)) {
217
+ if (!this.preCheck(config, config.somaId, element)) {
212
218
  runtime.status = 'blocked';
213
219
  runtime.message = 'pre-check rejected';
214
220
  return;
@@ -262,18 +268,21 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
262
268
  try {
263
269
  if (runsHandler) {
264
270
  try {
265
- this.pendingSet.add(config.somaId);
271
+ if (rowContext instanceof SomaRowScope) this.pendingRows.add(element);
272
+ else this.pendingSet.add(config.somaId);
266
273
  this.callbacks.onSyncModels?.();
267
- const fn = this.resolveFunction(config.funcPath!, currentVar);
274
+ const fn = this.resolveFunction(config.funcPath!, rowContext);
268
275
  // emit 路由:第二实参为契约 payload;DOM 路由保持 originalEvent
269
276
  const handlerArg = isSomaEmitEvent(originalEvent) ? originalEvent.payload : originalEvent;
270
277
  result = await fn(currentVar, handlerArg);
278
+ if (rowContext instanceof SomaRowScope && !rowContext.active) return;
271
279
  } catch (error) {
272
280
  runtime.status = 'error';
273
281
  runtime.message = error instanceof Error ? error.message : String(error);
274
282
  result = false;
275
283
  } finally {
276
- this.pendingSet.delete(config.somaId);
284
+ if (rowContext instanceof SomaRowScope) this.pendingRows.delete(element);
285
+ else this.pendingSet.delete(config.somaId);
277
286
  }
278
287
  }
279
288
 
@@ -341,8 +350,10 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
341
350
  let value: unknown;
342
351
  if (pipeline.funcPath && pipeline.type !== 'NAV_STATIC') {
343
352
  const currentVar = this.getContext(element);
353
+ if (currentVar instanceof SomaRowScope && !currentVar.active) return undefined;
344
354
  const fn = this.resolveFunction(pipeline.funcPath, currentVar);
345
- value = await fn(currentVar, undefined);
355
+ value = await fn(currentVar instanceof SomaRowScope ? currentVar.data : currentVar, undefined);
356
+ if (currentVar instanceof SomaRowScope && !currentVar.active) return undefined;
346
357
  // 一步之内就 commit:后面的步骤(和它们的 when)要看得见这一步的效果
347
358
  await this.callbacks.onCommit();
348
359
  }
@@ -371,8 +382,8 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
371
382
  return undefined;
372
383
  }
373
384
 
374
- private preCheck(config: SomaCompiledEvent, somaId: string): boolean {
375
- if (this.pendingSet.has(somaId)) {
385
+ private preCheck(config: SomaCompiledEvent, somaId: string, element: HTMLElement): boolean {
386
+ if (this.getContext(element) instanceof SomaRowScope ? this.pendingRows.has(element) : this.pendingSet.has(somaId)) {
376
387
  return false;
377
388
  }
378
389
 
@@ -461,6 +472,14 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
461
472
  private resolveFunction(funcPath: string, currentVar: any): Function {
462
473
  const segments = funcPath.split('.');
463
474
  const rootToken = segments[0];
475
+ if (currentVar instanceof SomaRowScope) {
476
+ if (!currentVar.has(rootToken)) return this.resolver.resolveFunction(funcPath);
477
+ const ownerPath = segments.slice(0, -1).join('.');
478
+ const owner = currentVar.read(ownerPath, () => undefined);
479
+ const fn = readRowPath(owner, segments.slice(-1));
480
+ if (typeof fn !== 'function') throw new Error('[SomaEventEngine] Row handler is not a function');
481
+ return fn.bind(owner);
482
+ }
464
483
 
465
484
  // When the root token refers to a list-item var alias and we have a
466
485
  // concrete item context, resolve the function directly on that item rather
@@ -10,6 +10,7 @@ import { SomaPropertyWatcher } from './property-watcher';
10
10
  import type { WatchCallback, WatcherOptions } from '../../shared/types/watcher.types';
11
11
 
12
12
  export interface SomaRenderEngineOptions {
13
+ repeatPlans?: readonly import('../../shared/types/component-tree-artifact.types').RepeatPlan[];
13
14
  container: HTMLElement;
14
15
  adapter: IContainerAdapter;
15
16
  manifest: SomaRuntimeManifest;
@@ -64,6 +65,7 @@ export class SomaRenderEngine {
64
65
 
65
66
  this.renderer = new SomaDomRenderer();
66
67
  this.renderer.init(this.adapter, this.resolver, this.scopeTracker, options.pipeRegistry);
68
+ this.renderer.setRepeatPlans(options.repeatPlans ?? []);
67
69
  this.renderer.setModelWriteBack((path, value) => this.writeToProxy(path, value));
68
70
 
69
71
  this.bindingTable = options.manifest.bindings
@@ -0,0 +1,62 @@
1
+ import type { SomaRowScope } from './row-scope';
2
+
3
+ /** One keyed row is a complete DOM range, not an assumed first element. */
4
+ export class SomaRowRange {
5
+ readonly start: Comment;
6
+ readonly end: Comment;
7
+ readonly roots: readonly HTMLElement[];
8
+ private released = false;
9
+
10
+ constructor(fragment: DocumentFragment, readonly scope: SomaRowScope, readonly variant = '') {
11
+ this.start = fragment.ownerDocument.createComment('soma-row');
12
+ this.end = fragment.ownerDocument.createComment('/soma-row');
13
+ this.roots = Array.from(fragment.children) as HTMLElement[];
14
+ fragment.prepend(this.start);
15
+ fragment.append(this.end);
16
+ }
17
+
18
+ moveBefore(parent: Node, before: Node | null): void {
19
+ if (this.released) return;
20
+ if (this.start.parentNode === parent && this.end.nextSibling === before) return;
21
+ const doc = this.start.ownerDocument;
22
+ const active = doc.activeElement;
23
+ const focused = active?.namespaceURI === 'http://www.w3.org/1999/xhtml'
24
+ && typeof (active as HTMLElement).focus === 'function' ? active as HTMLElement : null;
25
+ const ownedFocus = focused && this.roots.some(root => root === focused || root.contains(focused));
26
+ const textControl = focused && ['input', 'textarea'].includes(focused.localName)
27
+ ? focused as HTMLInputElement | HTMLTextAreaElement : null;
28
+ const selection = ownedFocus && textControl
29
+ ? { start: textControl.selectionStart, end: textControl.selectionEnd, direction: textControl.selectionDirection }
30
+ : undefined;
31
+ const moved = doc.createDocumentFragment();
32
+ for (let node: Node | null = this.start; node;) {
33
+ const next: Node | null = node.nextSibling;
34
+ moved.appendChild(node);
35
+ if (node === this.end) break;
36
+ node = next;
37
+ }
38
+ parent.insertBefore(moved, before);
39
+ if (ownedFocus && focused.isConnected && doc.activeElement !== focused
40
+ && (!doc.activeElement || doc.activeElement === doc.body)) {
41
+ focused.focus({ preventScroll: true });
42
+ if (selection && selection.start !== null && selection.end !== null) {
43
+ (focused as HTMLInputElement | HTMLTextAreaElement).setSelectionRange(
44
+ selection.start, selection.end, selection.direction ?? undefined,
45
+ );
46
+ }
47
+ }
48
+ }
49
+
50
+ release(releaseRoot: (root: HTMLElement) => void): void {
51
+ if (this.released) return;
52
+ this.released = true;
53
+ this.scope.dispose();
54
+ for (const root of this.roots) releaseRoot(root);
55
+ for (let node: Node | null = this.start; node;) {
56
+ const next: Node | null = node.nextSibling;
57
+ node.parentNode?.removeChild(node);
58
+ if (node === this.end) break;
59
+ node = next;
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,77 @@
1
+ import { SomaComponentTreeError } from '../../shared/component-tree-errors';
2
+
3
+ export type SomaTypedRowKey = string | number;
4
+
5
+ /** Lexical row identity is in memory only: no raw business keys in DOM attributes. */
6
+ export class SomaRowScope {
7
+ active = true;
8
+ generation = 0;
9
+
10
+ constructor(
11
+ readonly alias: string,
12
+ readonly key: SomaTypedRowKey,
13
+ public data: unknown,
14
+ readonly parent?: SomaRowScope,
15
+ ) {}
16
+
17
+ has(alias: string): boolean {
18
+ return this.alias === alias || (this.parent?.has(alias) ?? false);
19
+ }
20
+
21
+ read(path: string, fallback: (path: string) => unknown): unknown {
22
+ const parts = path.split('.');
23
+ for (let scope: SomaRowScope | undefined = this; scope; scope = scope.parent) {
24
+ if (scope.alias === parts[0]) return readRowPath(scope.data, parts.slice(1));
25
+ }
26
+ return fallback(path);
27
+ }
28
+
29
+ update(data: unknown): void {
30
+ if (!this.active) return;
31
+ this.data = data;
32
+ this.generation++;
33
+ }
34
+
35
+ dispose(): void {
36
+ this.active = false;
37
+ this.generation++;
38
+ }
39
+ }
40
+
41
+ export function readRowPath(value: unknown, parts: readonly string[]): unknown {
42
+ let current = value;
43
+ for (const part of parts) {
44
+ if (['__proto__', 'prototype', 'constructor'].includes(part)) return undefined;
45
+ if (current == null || (typeof current !== 'object' && typeof current !== 'function')) return undefined;
46
+ current = (current as Record<string, unknown>)[part];
47
+ }
48
+ return current;
49
+ }
50
+
51
+ export function validateRowKeys(rows: unknown, keyPath: string, alias: string, limits?: { maxRows?: number; maxKeyLength?: number }): SomaTypedRowKey[] {
52
+ if (!Array.isArray(rows)) rowError('CT-REPEAT-SOURCE', '集合 ready 状态的数据必须是数组');
53
+ if (rows.length > (limits?.maxRows ?? 1000)) rowError('CT-LIMIT', '集合行数超过受信预算');
54
+ const parts = keyPath.split('.');
55
+ if (parts.shift() !== alias || parts.length === 0
56
+ || parts.some(part => !/^[$A-Z_a-z][$\w]*$/.test(part)
57
+ || ['__proto__', 'prototype', 'constructor'].includes(part))) {
58
+ rowError('CT-REPEAT-KEY', '显式行键必须来自当前行的安全字段路径');
59
+ }
60
+ const seen = new Set<SomaTypedRowKey>();
61
+ return rows.map(row => {
62
+ const key = readRowPath(row, parts);
63
+ if (!((typeof key === 'string' && key.length > 0 && key.length <= (limits?.maxKeyLength ?? 256))
64
+ || (typeof key === 'number' && Number.isFinite(key)))) {
65
+ rowError('CT-REPEAT-KEY', '行键必须是非空有界字符串或有限数字');
66
+ }
67
+ if (seen.has(key)) rowError('CT-REPEAT-KEY', '同一集合中存在重复行键');
68
+ seen.add(key);
69
+ return key;
70
+ });
71
+ }
72
+
73
+ function rowError(code: 'CT-REPEAT-KEY' | 'CT-REPEAT-SOURCE' | 'CT-LIMIT', hint: string): never {
74
+ throw new SomaComponentTreeError({
75
+ code, phase: 'runtime', sourceId: 'runtime', nodePath: 'repeat', fixHint: hint,
76
+ });
77
+ }
@@ -27,6 +27,7 @@ import { SomaTriggerEngine } from './trigger-engine';
27
27
  import { SomaTimerEngine } from './timer-engine';
28
28
 
29
29
  export interface RuntimeBuildInput {
30
+ repeatPlans?: readonly import('../../shared/types/component-tree-artifact.types').RepeatPlan[];
30
31
  container: HTMLElement;
31
32
  adapter: IContainerAdapter;
32
33
  uiConfig: UiConfig;
@@ -99,6 +100,7 @@ export class SomaRuntimeBuilder {
99
100
  propertyWatcher.setRoot(input.proxiedInstance);
100
101
 
101
102
  const renderEngine = new SomaRenderEngine({
103
+ repeatPlans: input.repeatPlans,
102
104
  container: input.container,
103
105
  adapter: input.adapter,
104
106
  manifest,