@barefootjs/jsx 0.26.4 → 0.27.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 (73) hide show
  1. package/dist/compiler.d.ts.map +1 -1
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +321 -104
  5. package/dist/ir-to-client-js/client-only-elision.d.ts +103 -0
  6. package/dist/ir-to-client-js/client-only-elision.d.ts.map +1 -0
  7. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  8. package/dist/ir-to-client-js/control-flow/shared.d.ts +1 -1
  9. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts +54 -0
  10. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts.map +1 -0
  11. package/dist/ir-to-client-js/control-flow/stringify/inner-loop.d.ts.map +1 -1
  12. package/dist/ir-to-client-js/control-flow/stringify/insert.d.ts.map +1 -1
  13. package/dist/ir-to-client-js/control-flow/stringify/loop-child-arm.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +17 -20
  15. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  16. package/dist/ir-to-client-js/control-flow/stringify/reactive-effects.d.ts +63 -4
  17. package/dist/ir-to-client-js/control-flow/stringify/reactive-effects.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow.d.ts +1 -1
  19. package/dist/ir-to-client-js/element-refs.d.ts +8 -3
  20. package/dist/ir-to-client-js/element-refs.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/emit-reactive.d.ts +8 -1
  22. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/html-template.d.ts +24 -0
  24. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/imports.d.ts +2 -2
  26. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/types.d.ts +9 -1
  29. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/utils.d.ts +1 -1
  31. package/dist/types.d.ts +25 -2
  32. package/dist/types.d.ts.map +1 -1
  33. package/package.json +2 -2
  34. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +398 -671
  35. package/src/__tests__/child-components-in-map.test.ts +4 -4
  36. package/src/__tests__/client-js-generation.test.ts +19 -11
  37. package/src/__tests__/composite-branch-loop.test.ts +2 -2
  38. package/src/__tests__/cross-file-client-signal.test.ts +5 -1
  39. package/src/__tests__/early-return-scope-var-ref.test.ts +10 -11
  40. package/src/__tests__/inline-jsx-callback.test.ts +6 -4
  41. package/src/__tests__/ir-jsx-props.test.ts +6 -5
  42. package/src/__tests__/loop-fallback-wrap.test.ts +3 -4
  43. package/src/__tests__/module-level-signal.audit.test.ts +7 -2
  44. package/src/__tests__/nested-loop-conditional.test.ts +9 -7
  45. package/src/__tests__/nested-loop-reactive-attrs.test.ts +2 -2
  46. package/src/__tests__/preamble-region-patch.test.ts +18 -12
  47. package/src/__tests__/profile-cond-binding-ids.test.ts +3 -2
  48. package/src/__tests__/profile-loop-binding-ids.test.ts +4 -3
  49. package/src/__tests__/profile-nested-binding-ids.test.ts +11 -6
  50. package/src/__tests__/reactive-attrs-in-map.test.ts +6 -4
  51. package/src/__tests__/template-closure.test.ts +1 -1
  52. package/src/compiler.ts +11 -0
  53. package/src/index.ts +1 -0
  54. package/src/ir-to-client-js/client-only-elision.ts +273 -0
  55. package/src/ir-to-client-js/collect-elements.ts +8 -4
  56. package/src/ir-to-client-js/control-flow/shared.ts +1 -1
  57. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +12 -4
  58. package/src/ir-to-client-js/control-flow/stringify/claim-plan.ts +68 -0
  59. package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +18 -9
  60. package/src/ir-to-client-js/control-flow/stringify/insert.ts +17 -11
  61. package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +35 -16
  62. package/src/ir-to-client-js/control-flow/stringify/loop.ts +48 -46
  63. package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +241 -31
  64. package/src/ir-to-client-js/control-flow.ts +1 -1
  65. package/src/ir-to-client-js/element-refs.ts +9 -11
  66. package/src/ir-to-client-js/emit-reactive.ts +50 -14
  67. package/src/ir-to-client-js/html-template.ts +29 -9
  68. package/src/ir-to-client-js/imports.ts +7 -4
  69. package/src/ir-to-client-js/reactivity.ts +3 -2
  70. package/src/ir-to-client-js/types.ts +10 -2
  71. package/src/ir-to-client-js/utils.ts +1 -1
  72. package/src/jsx-to-ir.ts +8 -7
  73. package/src/types.ts +25 -2
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Slot unification Step B (`spec/slot-unification.md` §3(b), §5 "Step B —
3
+ * marker elision"): decide, EXACTLY ONCE and BEFORE either `adapter.generate`
4
+ * (SSR) or `generateClientJs` (CSR) run, which `/* @client *\/` text slots
5
+ * can drop their `<!--bf:sN-->…<!--/-->` marker pair entirely from both
6
+ * outputs. Every consumer (all nine SSR adapters' `renderExpression`, and
7
+ * the CSR emitters in `html-template.ts`) reads the single
8
+ * `IRExpression.markerless` flag this pass writes — nobody re-derives the
9
+ * decision, per CLAUDE.md's "Never add compiler options/hooks for
10
+ * tool-specific output rewriting" spirit: one door in, everyone reads it.
11
+ *
12
+ * Scope — deliberately the NARROWEST slice of §3(b)'s elision rule that is
13
+ * fully sound today, not the general case:
14
+ *
15
+ * Only `expr.clientOnly && expr.slotId` expressions OUTSIDE any loop or
16
+ * conditional branch (i.e. reachable from the component's own render tree
17
+ * by walking only `element`/`text`/`expression`/`fragment` nodes).
18
+ *
19
+ * Why THIS slice and not ordinary reactive text slots (loop rows,
20
+ * conditional branches): every other kind of slot's SSR-rendered width is
21
+ * DATA-DEPENDENT — an ordinary `{item.name}` may render empty or non-empty
22
+ * per request, so a LATER sibling's absolute child-index path would only be
23
+ * valid for the specific width THIS request happened to produce, not for
24
+ * every request the compiled function ever serves. `/* @client *\/`
25
+ * expressions are the one case free of that problem: SSR can never evaluate
26
+ * client-only JS (the whole point of the escape valve), so its rendered
27
+ * width is deterministically ZERO on every request, for every adapter, with
28
+ * no data dependence at all. That determinism is what makes computing a
29
+ * real, reusable, hydration-safe path sound here without also solving the
30
+ * general "does an earlier sibling's width vary by request" problem.
31
+ *
32
+ * Path safety within that scope — the part that generalizes A3's
33
+ * `computeSkeletonSlotPaths` (`html-template.ts`) rather than reinventing
34
+ * it: paths are root-relative child-index chains, exactly like that
35
+ * function's, walked in document order with the SAME "once we hit something
36
+ * whose contributed width isn't a compile-time constant, every remaining
37
+ * sibling AND everything nested inside it loses eligibility" rule (nested
38
+ * content reached only through an uncertain-index sibling would resolve an
39
+ * absolute path through that uncertain index — silently wrong, not loud, so
40
+ * it must never be attempted). Concretely, walking a children list left to
41
+ * right:
42
+ * - a static `element` always contributes exactly one node — recurse into
43
+ * its own children as an independent, freshly-indexed scope (its own
44
+ * internal accounting can't leak out, and nothing external can poison
45
+ * it either, since the element itself is a fixed anchor regardless of
46
+ * what's inside it);
47
+ * - static `text` contributes a node per HTML-parser text-run-merging
48
+ * rules (adjacent text/expression children collapse into ONE Text
49
+ * node — mirrors `computeSkeletonSlotPaths`'s `pendingText` tracking);
50
+ * - a `clientOnly` expression with a slotId is the one ELIGIBLE case,
51
+ * PROVIDED it is not itself part of a merged text run (rule (i) — the
52
+ * `/* @client *\/` slot must not be immediately adjacent, once markers
53
+ * are gone, to loose text or another expression, or the HTML parser
54
+ * would merge them into one Text node with no way to tell which
55
+ * content is which). Once one is elided, this level (and everything
56
+ * nested inside any later sibling) is marked ineligible for the
57
+ * remainder of the walk at this level — see the "freeze" note below;
58
+ * - any other `expression` (a real reactive/static text or markup slot),
59
+ * any `conditional`/`loop`/`component`/`async`/`provider`/
60
+ * `if-statement`/`slot` node, is data-dependent or opaque width and
61
+ * FREEZES the rest of this children list (see below) — this is
62
+ * strictly conservative: it also means a `/* @client *\/` expression
63
+ * is never eligible once any of these appears earlier at the same
64
+ * level, even though `/* @client *\/`'s own width is always zero,
65
+ * because SIBLINGS reached only via nested recursion past that point
66
+ * would otherwise resolve an absolute path through the frozen node's
67
+ * uncertain contributed width;
68
+ * - the same hazard-tag / force-close-group / void-element / `<tr>`
69
+ * foster-parenting guards `computeSkeletonSlotPaths` uses (imported,
70
+ * not re-derived) abort the ENTIRE walk (a global bail, exactly like
71
+ * that function's `state.bailed`) — a parser hazard means every index
72
+ * computed anywhere in this tree is suspect, not just the ones near
73
+ * the hazard, so "don't guess" means don't guess about the blast
74
+ * radius either.
75
+ *
76
+ * "Freeze" (the one simplification versus a maximally-precise per-branch
77
+ * eligibility tracker): once ANY `/* @client *\/` slot at a given level is
78
+ * elided — OR once anything data-dependent/opaque is seen at that level —
79
+ * that level's remaining siblings (and anything nested only through them)
80
+ * stop being assigned real paths for the rest of THIS walk, even though a
81
+ * maximally precise analysis could sometimes still find one. This caps
82
+ * elision at (at most) one `/* @client *\/` slot per static subtree —
83
+ * conservative by design, matching the elision rule's own framing, and it
84
+ * guarantees two elided slots can never end up needing an insertion whose
85
+ * reference node depends on the other's still-unresolved width. Freezing is
86
+ * PER CHILDREN-LIST (an element's own children start a fresh, unfrozen
87
+ * scope) — global-bail is reserved for hazard tags alone.
88
+ *
89
+ * Deferred (loudly, not silently): ordinary reactive text slots in loop
90
+ * rows / conditional branches keep their markers — see above for why
91
+ * widening this to data-dependent-width content needs a materially
92
+ * different (and per-adapter-verified) safety argument that this PR does
93
+ * not attempt.
94
+ */
95
+
96
+ import type { IRNode, IRExpression } from '../types.ts'
97
+ import {
98
+ VOID_ELEMENTS,
99
+ SKELETON_PATH_HAZARD_TAGS,
100
+ skeletonForceCloseGroup,
101
+ hasForeignTableRowContent,
102
+ flattenSkeletonChildren,
103
+ } from './html-template.ts'
104
+
105
+ /** Global bail, mirroring `computeSkeletonSlotPaths`'s `state.bailed`: once
106
+ * a parser hazard is seen anywhere, every remaining step of this ONE
107
+ * `decideClientOnlyElision` call becomes a no-op. Slots already elided
108
+ * before the hazard was reached keep their `markerless`/`elidedPath` —
109
+ * those paths were computed from safe ground and remain valid; only
110
+ * FURTHER assignment stops. */
111
+ interface ElisionState {
112
+ bailed: boolean
113
+ }
114
+
115
+ /**
116
+ * Entry point: mutates `root`'s `expression` nodes in place, setting
117
+ * `markerless`/`elidedPath` on every eligible `/* @client *\/` slot found.
118
+ * Safe to call on any component's render tree; a tree with none simply
119
+ * mutates nothing.
120
+ */
121
+ export function decideClientOnlyElision(root: IRNode): void {
122
+ walkNode(root, [], new Set(), { bailed: false })
123
+ }
124
+
125
+ /** Walk one node that occupies a known position (`path`) in its parent's
126
+ * children. Only `element`/`fragment` are ever recursed into by the
127
+ * children-list walker below — this wrapper exists so both the top-level
128
+ * call and `walkChildren`'s per-element recursion can share one path. */
129
+ function walkNode(
130
+ node: IRNode,
131
+ path: readonly number[],
132
+ forceCloseAncestors: ReadonlySet<number>,
133
+ state: ElisionState,
134
+ ): void {
135
+ if (state.bailed) return
136
+ if (node.type === 'element') {
137
+ if (!elementIsPathSafe(node.tag, flattenSkeletonChildren(node.children))) {
138
+ state.bailed = true
139
+ return
140
+ }
141
+ const groupIdx = skeletonForceCloseGroup(node.tag)
142
+ if (groupIdx >= 0 && forceCloseAncestors.has(groupIdx)) {
143
+ state.bailed = true
144
+ return
145
+ }
146
+ const nextAncestors = groupIdx >= 0 ? new Set([...forceCloseAncestors, groupIdx]) : forceCloseAncestors
147
+ walkChildren(flattenSkeletonChildren(node.children), path, nextAncestors, state)
148
+ } else if (node.type === 'fragment') {
149
+ walkChildren(flattenSkeletonChildren(node.children), path, forceCloseAncestors, state)
150
+ }
151
+ // Any other root shape (a bare conditional/loop/component return, etc.)
152
+ // has no static children list to walk — nothing to do.
153
+ }
154
+
155
+ /**
156
+ * Walk one parent's (already-fragment-flattened) children left to right,
157
+ * assigning paths to eligible `/* @client *\/` slots. `parentPath` is the
158
+ * path to the PARENT of this children list (the element/root whose
159
+ * `childNodes` these indices are relative to). `forceCloseAncestors`
160
+ * mirrors `computeSkeletonSlotPaths`'s ancestor-threaded force-close-group
161
+ * tracking (`<h2>` inside an open `<h1>`, `<li>` inside an open `<li>`, …) —
162
+ * threaded down through element recursion, exactly like that function.
163
+ * `frozen` is local to THIS call (this one children list) — an element's
164
+ * own children get a fresh, unfrozen scope regardless of what froze here.
165
+ */
166
+ function walkChildren(
167
+ children: readonly IRNode[],
168
+ parentPath: readonly number[],
169
+ forceCloseAncestors: ReadonlySet<number>,
170
+ state: ElisionState,
171
+ ): void {
172
+ let frozen = false
173
+ let idx = 0
174
+ let pendingText = false
175
+
176
+ for (let i = 0; i < children.length; i++) {
177
+ if (state.bailed) return
178
+ const child = children[i]
179
+
180
+ switch (child.type) {
181
+ case 'text': {
182
+ if (child.value === '') continue
183
+ if (!pendingText) idx += 1
184
+ pendingText = true
185
+ continue
186
+ }
187
+
188
+ case 'expression': {
189
+ if (child.expr === 'null' || child.expr === 'undefined') continue
190
+ if (child.clientOnly && child.slotId) {
191
+ const adjacent = isTextLike(children[i - 1]) || isTextLike(children[i + 1])
192
+ if (!frozen && !adjacent) {
193
+ markElided(child, [...parentPath, idx])
194
+ frozen = true // one elision per level — see module docstring
195
+ } else {
196
+ frozen = true // still freeze: an un-elided expression here is
197
+ // no different from any other data-dependent-width sibling.
198
+ }
199
+ idx += 1
200
+ pendingText = false
201
+ continue
202
+ }
203
+ // Any other expression — data-dependent width. Freeze the rest of
204
+ // this level; still consume ONE index (best-effort bookkeeping —
205
+ // nothing downstream reads `idx` past this point since `frozen`
206
+ // blocks any further assignment).
207
+ frozen = true
208
+ idx += 1
209
+ pendingText = false
210
+ continue
211
+ }
212
+
213
+ case 'element': {
214
+ if (!elementIsPathSafe(child.tag, flattenSkeletonChildren(child.children))) {
215
+ // Hazard shape: bail the WHOLE walk (matches
216
+ // `computeSkeletonSlotPaths`'s "don't guess" stance), not just
217
+ // this level — a parser hazard means indices anywhere in this
218
+ // tree are untrustworthy, not only the ones near it.
219
+ state.bailed = true
220
+ return
221
+ }
222
+ if (!frozen) {
223
+ walkNode(child, [...parentPath, idx], forceCloseAncestors, state)
224
+ }
225
+ idx += 1
226
+ pendingText = false
227
+ continue
228
+ }
229
+
230
+ case 'fragment':
231
+ continue // already flattened
232
+
233
+ default:
234
+ // conditional / loop / component / async / provider / if-statement /
235
+ // slot: opaque or variable width. Freeze the rest of this level.
236
+ frozen = true
237
+ idx += 1
238
+ pendingText = false
239
+ continue
240
+ }
241
+ }
242
+ }
243
+
244
+ /** True for a node that would merge (per HTML text-node-merging rules) with
245
+ * an adjacent bare-text-position slot if that slot's markers were removed —
246
+ * rule (i) of §3(b). `undefined` (no sibling — start/end of the children
247
+ * list) is never adjacent. */
248
+ function isTextLike(node: IRNode | undefined): boolean {
249
+ if (!node) return false
250
+ if (node.type === 'text') return node.value !== ''
251
+ if (node.type === 'expression') return node.expr !== 'null' && node.expr !== 'undefined'
252
+ return false
253
+ }
254
+
255
+ function markElided(expr: IRExpression, path: readonly number[]): void {
256
+ expr.markerless = true
257
+ expr.elidedPath = path
258
+ }
259
+
260
+ /**
261
+ * Mirrors `computeSkeletonSlotPaths`'s per-element safety checks (hazard
262
+ * tags, void elements, `<tr>` foster-parenting) without re-deriving the
263
+ * underlying tag sets — imported from `html-template.ts` so the two walks
264
+ * can never silently diverge on which shapes are hazardous. Force-close
265
+ * groups are checked separately by the caller (`walkNode`), which has the
266
+ * ancestor set this check does not.
267
+ */
268
+ function elementIsPathSafe(tag: string, flatChildren: readonly IRNode[]): boolean {
269
+ if (SKELETON_PATH_HAZARD_TAGS.has(tag)) return false
270
+ if (VOID_ELEMENTS.has(tag) && flatChildren.length > 0) return false
271
+ if (tag === 'tr' && hasForeignTableRowContent(flatChildren)) return false
272
+ return true
273
+ }
@@ -414,8 +414,8 @@ export function collectInnerLoops(
414
414
 
415
415
  /**
416
416
  * Decide whether a loop's runtime rendering needs element reconciliation
417
- * (reconcileElements + composite item rendering) rather than the simple
418
- * template-per-item path, and collect inner-loop metadata for its body.
417
+ * (mapArray/mapArrayAnchored + composite item rendering) rather than the
418
+ * simple template-per-item path, and collect inner-loop metadata for its body.
419
419
  *
420
420
  * Used by both the top-level `case 'loop'` in `collectElements` and the
421
421
  * branch-loop collector in `collectBranchLoops`. Each call site applies
@@ -595,7 +595,11 @@ export function collectElements(
595
595
  },
596
596
  expression: ({ node: ex, scope: inCond }) => {
597
597
  if (ex.clientOnly && ex.slotId) {
598
- ctx.clientOnlyElements.push({ slotId: ex.slotId, expression: ex.expr })
598
+ ctx.clientOnlyElements.push({
599
+ slotId: ex.slotId,
600
+ expression: ex.expr,
601
+ elidedPath: ex.markerless ? ex.elidedPath : undefined,
602
+ })
599
603
  return
600
604
  }
601
605
  if (!ex.slotId || inCond) return
@@ -1113,7 +1117,7 @@ function collectBranchLoops(
1113
1117
  : decideLoopRendering(n, siblingOffsets, undefined)
1114
1118
 
1115
1119
  // Build the item template from loop children.
1116
- // Use loopDepth=0: this loop gets its own reconcileElements (independent
1120
+ // Use loopDepth=0: this loop gets its own mapArray/mapArrayAnchored call (independent
1117
1121
  // from the conditional's template), so items use data-key (not data-key-1).
1118
1122
  // Pass loopParams so expressions reference the per-item signal accessor,
1119
1123
  // keeping the template consistent with reactive effect expressions that
@@ -29,7 +29,7 @@ import {
29
29
  } from '../csr-substitute.ts'
30
30
 
31
31
  /**
32
- * Build the `keyFn` argument for mapArray / reconcileElements. `null` when
32
+ * Build the `keyFn` argument for mapArray / mapArrayAnchored. `null` when
33
33
  * the loop has no key expression. Every `CollectedLoop` variant (top-level /
34
34
  * branch / nested) carries an `index: string | null` field (#2218 threaded
35
35
  * it onto `NestedLoop` too), so the index param — when present — is always
@@ -14,7 +14,7 @@ import { stringifyCompositeLoop } from './composite-loop.ts'
14
14
  import { stringifyEventDelegation } from './event-delegation.ts'
15
15
  import { stringifyReactiveEffects } from './reactive-effects.ts'
16
16
  import { emitTemplateCloneInline, emitLoopItemElementSetup } from './template-parse.ts'
17
- import { emitLoopChildRefs, emitPreambleRegionEffects } from './loop.ts'
17
+ import { emitLoopChildRefs } from './loop.ts'
18
18
  import type {
19
19
  BranchLoopPlan,
20
20
  BranchPlainLoopPlan,
@@ -115,11 +115,19 @@ function emitPlain(lines: string[], plan: BranchPlainLoopPlan): void {
115
115
  indent: ' ',
116
116
  singleRootLayout: 'inline',
117
117
  })
118
- if (reactiveEffects !== null) {
119
- stringifyReactiveEffects(lines, reactiveEffects, { indent: ' ', elVar: '__el', bodyIsMultiRoot })
118
+ if (reactiveEffects !== null || preambleRegions.length > 0) {
119
+ // Row-granularity effects (§3(c)): mirrors `stringifyPlainLoop`'s
120
+ // top-level call — attrs, outer texts, and preamble regions merge
121
+ // into ONE row effect (see `stringifyReactiveEffects`'s docstring).
122
+ stringifyReactiveEffects(lines, reactiveEffects, {
123
+ indent: ' ',
124
+ elVar: '__el',
125
+ bodyIsMultiRoot,
126
+ preambleRegions,
127
+ mapPreambleWrapped,
128
+ })
120
129
  }
121
130
  emitLoopChildRefs(lines, childRefs, { indent: ' ', elVar: '__el', bodyIsMultiRoot })
122
- emitPreambleRegionEffects(lines, preambleRegions, mapPreambleWrapped, { indent: ' ', elVar: '__el' })
123
131
  lines.push(` return __el`)
124
132
  lines.push(` }, '${markerId}'${loopBfId})`)
125
133
  }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Claim-plan literal rendering — the compiler-side half of slot unification
3
+ * A3 (`spec/slot-unification.md` §4/§5-A3). The runtime's `SlotSpec`/
4
+ * `ClaimPlan` (`@barefootjs/client/runtime/claim-slots.ts`, A2) are pure
5
+ * data: `{ id, kind, path }` triples. This module is the single place that
6
+ * turns compile-time slot descriptors into that data's source-text form —
7
+ * every content-slot emission site (loop rows, preamble regions, dynamic
8
+ * text/JSX slots, `@client` expressions) renders its plan through
9
+ * `claimPlanLiteral`, never by hand-splicing strings, so the literal shape
10
+ * can only ever match `SlotSpec`.
11
+ *
12
+ * Paths are real root-relative child-index arrays wherever the caller
13
+ * already has them (the hoisted single-root loop skeleton, #2143's
14
+ * `SkeletonSlotPaths`); everywhere else a slot gets `path: []` and A2's
15
+ * `lazySlots`/`claimSlots` marker-scan fallback resolves it — sound, just a
16
+ * per-claim scan instead of an O(depth) walk. This is the explicit
17
+ * "cannot be statically pathed" escape valve `spec/slot-unification.md`
18
+ * §5-A3 sanctions, not a shortcut invented here.
19
+ */
20
+
21
+ export interface ClaimSlotSpec {
22
+ readonly id: string
23
+ readonly kind: 'text' | 'markup'
24
+ /** Root-relative child-index path, used when the path is unconditionally
25
+ * valid at claim time. Ignored when `pathExpr` is set. */
26
+ readonly path: readonly number[]
27
+ /**
28
+ * Raw JS expression (already rendered source text) evaluating to a
29
+ * `number[]` at runtime, for the one case a plain literal can't express:
30
+ * a hoisted-skeleton path that's valid ONLY on the fresh-CSR-clone branch,
31
+ * never on the hydration-adopts-SSR branch (#2143 precedent — `__p` is
32
+ * nulled when `__existing` is truthy because the skeleton's simplified
33
+ * markup doesn't describe the real SSR-rendered tree). Typically
34
+ * `__existing ? [] : [1, 0]`. Overrides `path` when present.
35
+ */
36
+ readonly pathExpr?: string
37
+ /**
38
+ * Slot unification Step B (`spec/slot-unification.md` §3(b), §5 Step B):
39
+ * true when NO marker was emitted for this slot — `path`'s last index is
40
+ * the slot's own position, not an anchor comment. Only ever set by
41
+ * `client-only-elision.ts`-derived callers; every other emission site
42
+ * omits it (falsy = today's marker-based behavior, unchanged).
43
+ */
44
+ readonly markerless?: boolean
45
+ }
46
+
47
+ /** Render one `SlotSpec` as a source-text object literal. */
48
+ function slotSpecLiteral(slot: ClaimSlotSpec): string {
49
+ const pathSrc = slot.pathExpr ?? `[${slot.path.join(', ')}]`
50
+ const markerlessSrc = slot.markerless ? ', markerless: true' : ''
51
+ return `{ id: '${slot.id}', kind: '${slot.kind}', path: ${pathSrc}${markerlessSrc} }`
52
+ }
53
+
54
+ /** Render a `ClaimPlan` (an array of `SlotSpec`) as a source-text array literal. */
55
+ export function claimPlanLiteral(slots: readonly ClaimSlotSpec[]): string {
56
+ return `[${slots.map(slotSpecLiteral).join(', ')}]`
57
+ }
58
+
59
+ /**
60
+ * A stable JS identifier for the claimed-slot writer covering `slots`,
61
+ * derived from the first slot's id. Slot ids are unique per component (the
62
+ * `bf="sN"` marker namespace), so this can never collide across two
63
+ * distinct claim-plan call sites within the same emitted component.
64
+ */
65
+ export function claimWriterVarName(slots: readonly ClaimSlotSpec[], sanitize: (id: string) => string): string {
66
+ const first = slots[0]?.id ?? '0'
67
+ return `__bfw_${sanitize(first)}`
68
+ }
@@ -30,11 +30,12 @@
30
30
  * <indent>}) }
31
31
  */
32
32
 
33
- import { keyAttrName, profileBindingId } from '../../utils.ts'
33
+ import { keyAttrName, profileBindingId, varSlotId } from '../../utils.ts'
34
34
  import { emitComponentAndEventSetup } from '../shared.ts'
35
35
  import { emitAttrUpdate } from '../../emit-reactive.ts'
36
36
  import { emitMultiRootTemplateCloneLines, templateRootIsSvg } from './template-parse.ts'
37
37
  import { emitLoopChildRefs } from './loop.ts'
38
+ import { claimPlanLiteral, claimWriterVarName, type ClaimSlotSpec } from './claim-plan.ts'
38
39
  import type {
39
40
  InnerLoopPlan,
40
41
  InnerLoopsPlan,
@@ -110,15 +111,23 @@ function emitReactive(lines: string[], inner: InnerLoopPlan, indent: string, pc:
110
111
  if (inner.childLevels.length > 0) {
111
112
  stringifyInnerLoops(lines, inner.childLevels, `${indent} `, pc)
112
113
  }
113
- for (const text of emit.reactiveTexts) {
114
+ const conditionalTexts = emit.reactiveTexts.filter(t => t.insideConditional)
115
+ const plainTexts = emit.reactiveTexts.filter(t => !t.insideConditional)
116
+ for (const text of conditionalTexts) {
114
117
  const bf = profileBindingId(pc, text.slotId)
115
- if (text.insideConditional) {
116
- // Re-query $t inside the effect: insert() may swap the text node so a
117
- // captured reference would silently stop updating.
118
- lines.push(`${indent} createEffect(() => { const [__rt] = $t(__innerEl${uid}, '${text.slotId}'); if (__rt) __rt.textContent = String(${text.wrappedExpression}) }${bf})`)
119
- } else {
120
- lines.push(`${indent} { const [__rt] = $t(__innerEl${uid}, '${text.slotId}')`)
121
- lines.push(`${indent} if (__rt) createEffect(() => { __rt.textContent = String(${text.wrappedExpression}) }${bf}) }`)
118
+ // A fresh `claimSlots` claim on every run (not the cached `lazySlots`
119
+ // door): insert() may swap the branch's DOM between runs, and 'text'
120
+ // writes are a plain, idempotent `nodeValue` assignment with no
121
+ // dedup/trust-first-run state to go stale so re-claiming here is exactly
122
+ // as safe as, and replaces, the old re-query-$t-on-every-run discipline.
123
+ lines.push(`${indent} createEffect(() => { claimSlots(__innerEl${uid}, [{ id: '${text.slotId}', kind: 'text', path: [] }]).write('${text.slotId}', String(${text.wrappedExpression})) }${bf})`)
124
+ }
125
+ if (plainTexts.length > 0) {
126
+ const slots: ClaimSlotSpec[] = plainTexts.map(t => ({ id: t.slotId, kind: 'text', path: [] }))
127
+ const writer = claimWriterVarName(slots, varSlotId)
128
+ lines.push(`${indent} const ${writer} = lazySlots(__innerEl${uid}, ${claimPlanLiteral(slots)})`)
129
+ for (const text of plainTexts) {
130
+ lines.push(`${indent} createEffect(() => { ${writer}('${text.slotId}', String(${text.wrappedExpression})) }${profileBindingId(pc, text.slotId)})`)
122
131
  }
123
132
  }
124
133
  for (const attr of emit.reactiveAttrs) {
@@ -34,6 +34,7 @@ import type { InsertPlan, InsertArm, ArmBody, ScopeRef } from '../plan/types.ts'
34
34
  import { stringifyBranchLoops } from './branch-loop.ts'
35
35
  import { emitListenerLine } from './event-listener.ts'
36
36
  import { nameForRegistryRef } from '../../component-scope.ts'
37
+ import { claimPlanLiteral, claimWriterVarName, type ClaimSlotSpec } from './claim-plan.ts'
37
38
 
38
39
  export interface StringifyInsertOptions {
39
40
  /** Indent on the `insert(` line itself. */
@@ -173,18 +174,23 @@ function emitArmBody(
173
174
  lines.push(`${indent}} }`)
174
175
  }
175
176
 
176
- for (const te of body.textEffects) {
177
- const v = varSlotId(te.slotId)
178
- // Route through `__bfText` so a JSX-valued expression (`{cond && logo(id)}`)
177
+ if (body.textEffects.length > 0) {
178
+ // 'markup' kind so a JSX-valued expression (`{cond && logo(id)}`)
179
179
  // re-splices the live element by identity instead of stringifying it to
180
- // "[object HTMLElement]" — the branch template already spliced it via
181
- // `__bfSlot`, and this effect re-renders it when its deps change (#1663).
182
- // The `let` tracker carries the replaced node across reactive re-runs.
183
- lines.push(`${indent}let __anchor_${v} = $t(__branchScope, '${te.slotId}')[0]`)
184
- lines.push(`${indent}__disposers.push(createDisposableEffect(() => {`)
185
- lines.push(`${indent} const __val = ${te.expression}`)
186
- lines.push(`${indent} __anchor_${v} = __bfText(__anchor_${v}, __val)`)
187
- lines.push(`${indent}}${bindingBfId(te.slotId)}))`)
180
+ // "[object HTMLElement]" — the same contract `__bfText` used to provide
181
+ // (#1663). Built fresh here, inside this arm's `bindEvents` body, so
182
+ // every branch activation re-claims against that swap's own
183
+ // `__branchScope` DOM (spec/slot-unification.md §5-A3's "branch-internal
184
+ // slots re-claim per branch activation").
185
+ const slots: ClaimSlotSpec[] = body.textEffects.map(te => ({ id: te.slotId, kind: 'markup', path: [] }))
186
+ const writer = claimWriterVarName(slots, varSlotId)
187
+ lines.push(`${indent}const ${writer} = lazySlots(__branchScope, ${claimPlanLiteral(slots)})`)
188
+ for (const te of body.textEffects) {
189
+ // `escapeTextOrNode`: see emit-reactive.ts's identical wrap for why a
190
+ // string value must be escaped before a 'markup' writer's
191
+ // `innerHTML =` insertion, while a live Node passes through untouched.
192
+ lines.push(`${indent}__disposers.push(createDisposableEffect(() => { ${writer}('${te.slotId}', escapeTextOrNode(${te.expression})) }${bindingBfId(te.slotId)}))`)
193
+ }
188
194
  }
189
195
 
190
196
  // Branch loops, now fully Plan-built. The stringifier writes its own
@@ -17,6 +17,7 @@ import { emitAttrUpdate } from '../../emit-reactive.ts'
17
17
  import { templateRootIsSvg } from './template-parse.ts'
18
18
  import { emitListenerLine } from './event-listener.ts'
19
19
  import { nameForRegistryRef } from '../../component-scope.ts'
20
+ import { claimPlanLiteral, claimWriterVarName, type ClaimSlotSpec } from './claim-plan.ts'
20
21
  import type {
21
22
  BranchChildComponentInitsPlan,
22
23
  BranchEventBindingsPlan,
@@ -153,15 +154,22 @@ export function stringifyBranchInnerLoops(
153
154
  inner.outerLoopParamBindings,
154
155
  )
155
156
  }
156
- for (const text of inner.reactiveTexts) {
157
+ const conditionalTexts = inner.reactiveTexts.filter(t => t.insideConditional)
158
+ const plainTexts = inner.reactiveTexts.filter(t => !t.insideConditional)
159
+ for (const text of conditionalTexts) {
157
160
  const bf = profileBindingId(pc, text.slotId)
158
- if (text.insideConditional) {
159
- // Re-query $t inside the effect: insert() may swap the text node so a
160
- // captured reference would silently stop updating.
161
- lines.push(`${indent} createEffect(() => { const [__rt] = $t(__bel${uid}, '${text.slotId}'); if (__rt) __rt.textContent = String(${text.wrappedExpression}) }${bf})`)
162
- } else {
163
- lines.push(`${indent} { const [__rt] = $t(__bel${uid}, '${text.slotId}')`)
164
- lines.push(`${indent} if (__rt) createEffect(() => { __rt.textContent = String(${text.wrappedExpression}) }${bf}) }`)
161
+ // Fresh `claimSlots` claim every run (not the cached `lazySlots` door):
162
+ // insert() may swap the branch's DOM between runs, and a 'text' write
163
+ // is a plain, idempotent `nodeValue` assignment with no dedup state to
164
+ // go stale replaces the old re-query-$t-on-every-run discipline.
165
+ lines.push(`${indent} createEffect(() => { claimSlots(__bel${uid}, [{ id: '${text.slotId}', kind: 'text', path: [] }]).write('${text.slotId}', String(${text.wrappedExpression})) }${bf})`)
166
+ }
167
+ if (plainTexts.length > 0) {
168
+ const slots: ClaimSlotSpec[] = plainTexts.map(t => ({ id: t.slotId, kind: 'text', path: [] }))
169
+ const writer = claimWriterVarName(slots, varSlotId)
170
+ lines.push(`${indent} const ${writer} = lazySlots(__bel${uid}, ${claimPlanLiteral(slots)})`)
171
+ for (const text of plainTexts) {
172
+ lines.push(`${indent} createEffect(() => { ${writer}('${text.slotId}', String(${text.wrappedExpression})) }${profileBindingId(pc, text.slotId)})`)
165
173
  }
166
174
  }
167
175
  if (inner.nestedConditionals.length > 0) {
@@ -254,14 +262,25 @@ export function stringifyLoopChildArm(
254
262
  lines.push(`${armIndent}}))`)
255
263
  }
256
264
 
257
- for (const text of arm.texts) {
258
- // __bfText (not a naive `.textContent = String(...)`) so a Child-position
259
- // expression whose value is a live Node (e.g. a hoisted `renderNode={(n)
260
- // => <PillNode/>}` callback, #1213) is spliced into the slot by identity
261
- // instead of being stringified to "[object HTMLElement]" (#2347).
262
- const varName = `__rt_${varSlotId(text.slotId)}`
263
- lines.push(`${armIndent}let ${varName} = $t(__branchScope, '${text.slotId}')[0]`)
264
- lines.push(`${armIndent}__disposers.push(createDisposableEffect(() => { ${varName} = __bfText(${varName}, ${text.wrappedExpression}) }${profileBindingId(pc, text.slotId)}))`)
265
+ if (arm.texts.length > 0) {
266
+ // 'markup' kind (not 'text') because a Child-position expression's value
267
+ // may be a live Node (e.g. a hoisted `renderNode={(n) => <PillNode/>}`
268
+ // callback, #1213) claim-slots' markup writer splices a Node in by
269
+ // identity instead of stringifying it to "[object HTMLElement]" (#2347),
270
+ // the same contract `__bfText` used to provide. The writer is built
271
+ // fresh HERE, inside this arm's `bindEvents` body, so every branch
272
+ // activation re-claims against that swap's own `__branchScope` DOM
273
+ // (spec/slot-unification.md §5-A3's "branch-internal slots re-claim per
274
+ // branch activation").
275
+ const slots: ClaimSlotSpec[] = arm.texts.map(t => ({ id: t.slotId, kind: 'markup', path: [] }))
276
+ const writer = claimWriterVarName(slots, varSlotId)
277
+ lines.push(`${armIndent}const ${writer} = lazySlots(__branchScope, ${claimPlanLiteral(slots)})`)
278
+ for (const text of arm.texts) {
279
+ // `escapeTextOrNode`: see emit-reactive.ts's identical wrap for why a
280
+ // string value must be escaped before a 'markup' writer's
281
+ // `innerHTML =` insertion, while a live Node passes through untouched.
282
+ lines.push(`${armIndent}__disposers.push(createDisposableEffect(() => { ${writer}('${text.slotId}', escapeTextOrNode(${text.wrappedExpression})) }${profileBindingId(pc, text.slotId)}))`)
283
+ }
265
284
  }
266
285
 
267
286
  lines.push(`${armIndent}return () => __disposers.forEach(d => d())`)