@barefootjs/jsx 0.35.3 → 0.35.5

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 (36) hide show
  1. package/dist/analyzer.d.ts.map +1 -1
  2. package/dist/debug.d.ts +33 -3
  3. package/dist/debug.d.ts.map +1 -1
  4. package/dist/index.js +267 -73
  5. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  6. package/dist/ir-to-client-js/compute-inlinability.d.ts +8 -0
  7. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  8. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/imports.d.ts +2 -2
  10. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  11. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  12. package/dist/ir-to-client-js/types.d.ts +25 -0
  13. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/utils.d.ts +12 -1
  15. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  16. package/dist/types.d.ts +31 -0
  17. package/dist/types.d.ts.map +1 -1
  18. package/package.json +2 -2
  19. package/src/__tests__/debug.test.ts +246 -0
  20. package/src/__tests__/issue-2897-static-loop-conditional.test.ts +340 -0
  21. package/src/__tests__/issue-2910-mutated-const-not-inlined.test.ts +118 -0
  22. package/src/__tests__/issue-2910-own-scope-id-emission.test.ts +64 -0
  23. package/src/__tests__/lazy-conditional.test.ts +1 -0
  24. package/src/analyzer.ts +157 -22
  25. package/src/debug.ts +214 -84
  26. package/src/ir-to-client-js/collect-elements.ts +83 -3
  27. package/src/ir-to-client-js/compute-inlinability.ts +8 -1
  28. package/src/ir-to-client-js/emit-registration.ts +2 -2
  29. package/src/ir-to-client-js/generate-init.ts +16 -2
  30. package/src/ir-to-client-js/imports.ts +6 -0
  31. package/src/ir-to-client-js/index.ts +6 -0
  32. package/src/ir-to-client-js/prop-handling.ts +9 -0
  33. package/src/ir-to-client-js/types.ts +37 -1
  34. package/src/ir-to-client-js/utils.ts +15 -1
  35. package/src/jsx-to-ir.ts +14 -0
  36. package/src/types.ts +31 -0
@@ -5,7 +5,7 @@
5
5
  import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp, pickAttrMetaFromIR } from '../types.ts'
6
6
  import type { ClientJsContext, ConditionalBranchChildComponent, ConditionalBranchReactiveAttr, BranchLoop, ConditionalBranchTextEffect, ConditionalElement, LoopChildBindings, LoopChildBranchSummary, LoopChildConditional, LoopOffset, NestedLoop } from './types.ts'
7
7
  import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, type LoopParamSpec } from './utils.ts'
8
- import { classifyReactivity, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
8
+ import { classifyReactivity, needsEffectWrapper, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
9
9
  import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, jsxChildrenPropGetterExpr, buildLoopSkeletonTemplate, computeSkeletonSlotPaths, renderFlatMapClientBody, renderFlatMapProjectionClientBody, flatMapCallbackHasKeyedLeaf, type SkeletonSlotPaths } from './html-template.ts'
10
10
  import { detectRootNamespaceWrapTag } from './control-flow/stringify/template-parse.ts'
11
11
  import { expandDynamicPropValue, expandConstantForReactivity, resolveRestSpreadOrigin, resolveRestSpreadNames } from './prop-handling.ts'
@@ -752,10 +752,78 @@ export function collectElements(
752
752
  // Determine rendering strategy for dynamic arrays:
753
753
  // Use element reconciliation when the loop body has nested components,
754
754
  // or when inner loops need their own mapArray for events/reactive text.
755
- const { useElementReconciliation, innerLoops } = projectionInner
755
+ const { useElementReconciliation: reconciliationBase, innerLoops } = projectionInner
756
756
  ? { useElementReconciliation: false, innerLoops: undefined }
757
757
  : decideLoopRendering(l, siblingOffsets, ctx)
758
758
 
759
+ // #2897: a static (non-signal) array's forEach bake and the
760
+ // `inner-loop-nested` clone-and-wire architecture (#2798) have NO
761
+ // conditional-handling machinery at all — a `{cond ? A : B}` inside
762
+ // either the outer row or a depth-1 inner loop's row bakes to its
763
+ // initial branch at compile time and never updates, since neither
764
+ // path ever re-evaluates the condition. `elem.bodyIsItemConditional`
765
+ // (below) already carves out the WHOLE-row, one-empty-branch shape;
766
+ // this widens the same idea to any conditional anywhere in the row
767
+ // tree. `bindings.conditionals` is the outer row's own conditionals
768
+ // (never recurses into `loop` nodes, see `collectLoopChildConditionals`'s
769
+ // `stopAt(..., 'loop', ...)`); `innerLoops[i].bindings.conditionals` is
770
+ // collected separately per inner loop (#2706) — together they cover
771
+ // the whole tree with no overlap. Excludes a child-component-rooted
772
+ // outer item (`l.childComponent`) — out of scope, matching #2798's own
773
+ // plain-element-only scoping for the identical reason (#1725's
774
+ // document-order-zip shape doesn't address plain-element bindings).
775
+ //
776
+ // Gated on `reactiveBeyondLoopScope`, not mere presence: EVERY
777
+ // loop-param-referencing conditional lands in `bindings.conditionals`
778
+ // (`classifyReactivity` reports `'loop-param'` for `item.key === 'x'`
779
+ // exactly like it does for `flag()` — array static-ness plays no part
780
+ // in that classification, by design). For a static array the row
781
+ // item never changes after first render, so a condition that reads
782
+ // ONLY the item/index (`item.key === 'messages'`) is exactly as
783
+ // compile-time-bakeable as the #2798 static path already assumes —
784
+ // regardless of whether its branches are a bare element or a child
785
+ // component (`SocialShell`'s `NAV_ITEMS.map()` row: `{item.key ===
786
+ // 'messages' ? <SocialUnreadBadge /> : null}` inside a static
787
+ // function-local array — the static `outer-nested`/`inner-loop-nested`
788
+ // init already tolerates an absent-this-row child component). Only a
789
+ // condition that can ITSELF change value later (`flag()`, or a mixed
790
+ // `item.x && flag()`) needs the escalation #2897 actually fixed.
791
+ const staticRowHasConditional = !projectionInner && l.isStaticArray && !l.childComponent
792
+ && bindings.conditionals.some(c => c.reactiveBeyondLoopScope)
793
+ const staticInnerLoopHasConditional = !projectionInner && l.isStaticArray && !l.childComponent
794
+ && (innerLoops ?? []).some(il => il.bindings.conditionals.some(c => c.reactiveBeyondLoopScope))
795
+ const hasInnerStructure = (l.nestedComponents?.length ?? 0) > 0 || (innerLoops?.length ?? 0) > 0
796
+ // An own-row conditional alone needs no inner structure to reconcile —
797
+ // it falls through (via `clientIsStaticArray` below) straight to the
798
+ // plain dynamic-array path, which already wires a bare conditional's
799
+ // live branch-swap correctly (`buildLoopReactiveEffectsPlan`, proven
800
+ // by the identical shape on a signal-backed array). But when the row
801
+ // ALSO has a sibling inner loop (`hasInnerStructure`), that plain path
802
+ // (`buildPlainLoopPlan`) never reads `TopLevelLoop.innerLoops` at all —
803
+ // only the composite and static-array-child-init plans do — so an
804
+ // inner loop's own ref/reactive-attr/reactive-text bindings would be
805
+ // silently dropped (pullfrog review on #2899: confirmed by compiling
806
+ // a static row with a signal-driven sibling conditional next to an
807
+ // inner loop with a `ref` — the ref callback never appeared in the
808
+ // emitted JS). Escalating to the composite path here, exactly as an
809
+ // inner-loop conditional already does, keeps those bindings wired.
810
+ // An inner-loop conditional always DOES need reconciliation on its
811
+ // own (no `hasInnerStructure` gate needed there — `innerLoops` being
812
+ // non-empty is exactly what `hasInnerStructure` already asks), since
813
+ // #2798's static machinery it would otherwise take has no conditional
814
+ // support to add to — `buildTopLevelCompositePlan` already handles
815
+ // nested loops of arbitrary depth, including the conditional case,
816
+ // unconditionally.
817
+ const useElementReconciliation =
818
+ reconciliationBase || staticInnerLoopHasConditional || (staticRowHasConditional && hasInnerStructure)
819
+ // The client-side `isStaticArray` field (NOT the IR-level `l.isStaticArray`,
820
+ // which SSR adapters like Go template's static-loop baking still read
821
+ // directly and are unaffected by — #2897 is client-JS-only): false
822
+ // whenever a conditional forces this loop off the static fast path,
823
+ // so `buildLoopPlan`'s dispatcher and `buildStaticArrayChildInitsPlan`
824
+ // both skip the static machinery for it automatically.
825
+ const clientIsStaticArray = l.isStaticArray && !staticRowHasConditional && !staticInnerLoopHasConditional
826
+
759
827
  let template = ''
760
828
  let templateIndexed: string | undefined
761
829
  let staticItemTemplate: string | undefined
@@ -878,7 +946,7 @@ export function collectElements(
878
946
  bindings,
879
947
  childComponent: l.childComponent,
880
948
  nestedComponents: l.nestedComponents,
881
- isStaticArray: l.isStaticArray,
949
+ isStaticArray: clientIsStaticArray,
882
950
  useElementReconciliation,
883
951
  innerLoops: (useElementReconciliation || (l.isStaticArray && innerLoops?.length)) ? innerLoops : undefined,
884
952
  offset: resolveLoopOffset(siblingOffsets.get(l)),
@@ -1565,6 +1633,17 @@ export function collectLoopChildConditionals(
1565
1633
  // accessors; classifyReactivity sees all three paths (signal/memo/prop
1566
1634
  // + loop-param + loop-index, #2861).
1567
1635
  if (!readsPreamble && classifyReactivity(expanded.expr, ctx, scope, expanded.freeIds).kind === 'none') return
1636
+ // #2897 follow-up: does the condition read anything beyond the loop
1637
+ // item/index? `classifyReactivity`'s `kind` can't answer this — it
1638
+ // reports `'loop-param'` first whenever a loop-bound name appears,
1639
+ // even alongside a signal read (`item.x && flag()`), which is the
1640
+ // right precedence for its own two typed callers but the wrong
1641
+ // question here. Computed independently so a static array's
1642
+ // escalation decision (`collect-elements.ts`'s `loop:` visitor) can
1643
+ // ask "can this branch decision change after first render" instead
1644
+ // of "does this touch the loop param at all" — see
1645
+ // `LoopChildConditional.reactiveBeyondLoopScope`'s doc comment.
1646
+ const reactiveBeyondLoopScope = n.reactive || readsPreamble || needsEffectWrapper(expanded.expr, ctx, expanded.freeIds)
1568
1647
 
1569
1648
  const loopParamsForCond =
1570
1649
  loopParams ?? (loopParam ? [{ param: loopParam, bindings: loopParamBindings, index: loopIndex }] : undefined)
@@ -1583,6 +1662,7 @@ export function collectLoopChildConditionals(
1583
1662
  whenFalse: summarizeLoopChildBranch(n.whenFalse, ctx, siblingOffsets, loopParam, loopParamBindings, preambleNames, loopIndex),
1584
1663
  ...(expanded.freeIds !== undefined && { conditionFreeIdentifiers: expanded.freeIds }),
1585
1664
  ...(readsPreamble && { readsPreamble: true }),
1665
+ reactiveBeyondLoopScope,
1586
1666
  })
1587
1667
  },
1588
1668
  })
@@ -113,6 +113,12 @@ export type ConstantInlinability =
113
113
  /** After chained-ref resolution, the inlined value still mentions
114
114
  * a name classified unsafe above. Transitive demotion. */
115
115
  | { kind: 'depends-on-unsafe' }
116
+ /** A same-scope statement mutates this binding's value after its
117
+ * declaration (`ConstantInfo.mutatedAfterDeclaration`, #2910) — e.g.
118
+ * `const config = {}; for (...) config[k] = ...`. `value` is a
119
+ * pre-mutation snapshot; inlining it anywhere would silently drop
120
+ * the mutation, so this is unsafe exactly like an init-local. */
121
+ | { kind: 'mutated-after-declaration' }
116
122
 
117
123
  export type FunctionInlinability =
118
124
  /** Module-scope function that does NOT touch component internals —
@@ -339,7 +345,7 @@ function populateCsrInlinable(ctx: ClientJsContext, relocateEnv: RelocateEnv, ge
339
345
  // call-kind entry (`buildEnvWithConsts`'s Map spread puts `constSubs`
340
346
  // last) — the literal `(undefined)()` this issue is about (#2778).
341
347
  for (const c of ctx.localConstants) {
342
- if (c.isJsx || !c.value || c.containsArrow || c.systemConstructKind || getterAliases.has(c.name)) {
348
+ if (c.isJsx || !c.value || c.containsArrow || c.systemConstructKind || c.mutatedAfterDeclaration || getterAliases.has(c.name)) {
343
349
  ctx.csrInlinable.set(c.name, null)
344
350
  finalised.add(c.name)
345
351
  }
@@ -626,6 +632,7 @@ function classifyConstantInitial(
626
632
  ): { status: ConstantInlinability; decisions: RelocateDecision[] } {
627
633
  if (c.isJsx) return { status: { kind: 'jsx-inline' }, decisions: [] }
628
634
  if (!c.value) return { status: { kind: 'placeholder-let' }, decisions: [] }
635
+ if (c.mutatedAfterDeclaration) return { status: { kind: 'mutated-after-declaration' }, decisions: [] }
629
636
  if (c.containsArrow) return { status: { kind: 'arrow-literal' }, decisions: [] }
630
637
  if (c.systemConstructKind) return { status: { kind: 'system-construct' }, decisions: [] }
631
638
  // A multi-hop alias chain to a getter (`const a = items; const b = a`)
@@ -6,7 +6,7 @@
6
6
 
7
7
  import type { ComponentIR, IRFragment, IRNode, ReferencesGraph, SignalInfo } from '../types.ts'
8
8
  import type { ClientJsContext } from './types.ts'
9
- import { PROPS_PARAM } from './utils.ts'
9
+ import { PROPS_PARAM, isCommentScopedRoot } from './utils.ts'
10
10
  import { computeInlinability, toLegacyInlinability } from './compute-inlinability.ts'
11
11
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate, createStringProtector } from './html-template.ts'
12
12
  import { markupSlotIdsOf } from './markup-slots.ts'
@@ -215,7 +215,7 @@ export function emitRegistrationAndHydration(
215
215
  // DOM presence of its own, and `materializeComponent` must leave
216
216
  // `scopeId` null so it doesn't stamp over (or duplicate) the child's.
217
217
  const isFragmentRoot = _ir.root.type === 'fragment' && !!(_ir.root as IRFragment).needsScopeComment
218
- const isCommentScope = isFragmentRoot || _ir.root.type === 'component'
218
+ const isCommentScope = isCommentScopedRoot(_ir.root)
219
219
 
220
220
  // Build ComponentDef object for hydrate()
221
221
  const defParts: string[] = [`init: init${name}`]
@@ -10,7 +10,7 @@
10
10
 
11
11
  import type { ComponentIR } from '../types.ts'
12
12
  import type { ClientJsContext } from './types.ts'
13
- import { PROPS_PARAM } from './utils.ts'
13
+ import { PROPS_PARAM, isCommentScopedRoot } from './utils.ts'
14
14
  import { buildReferencesGraph } from './build-references.ts'
15
15
  import { computePropUsage } from './compute-prop-usage.ts'
16
16
  import { IMPORT_PLACEHOLDER, MODULE_CONSTANTS_PLACEHOLDER } from './imports.ts'
@@ -44,7 +44,21 @@ export function generateInitFunction(
44
44
  // Host scope id for (bf-h, bf-m) child lookups inside this init body
45
45
  // (#1249). Compile-time selectors emit
46
46
  // `[bf-h="${__scopeId}"][bf-m="<slotId>"]` against this value.
47
- lines.push(` const __scopeId = __scope.getAttribute('${BF_SCOPE}')`)
47
+ //
48
+ // A comment-scoped root (`comment: true` — a `needsScopeComment` fragment
49
+ // root, or a root that is itself a single child-component call, #2649) is
50
+ // mounted on a PROXY element whose OWN `bf-s` attribute names its
51
+ // host/parent scope, not this component's — this component's real id
52
+ // lives in the comment-scope registry the proxy was registered under
53
+ // (`ownScopeId`, #2910). Reading the raw attribute there resolves to the
54
+ // wrong id, so every `.map()`-produced child this component's init tries
55
+ // to find via `[bf-h="${__scopeId}"]` silently matches nothing. An
56
+ // element-scoped root keeps reading the attribute directly.
57
+ lines.push(
58
+ isCommentScopedRoot(ir.root)
59
+ ? ` const __scopeId = ownScopeId(__scope)`
60
+ : ` const __scopeId = __scope.getAttribute('${BF_SCOPE}')`,
61
+ )
48
62
  lines.push('')
49
63
 
50
64
  // --- Analysis: one graph, many queries; scope routing as data ---
@@ -61,6 +61,12 @@ export const RUNTIME_IMPORT_CANDIDATES = [
61
61
  // rewrite targets `formatDate(recv, pattern, tz)`, so the emitted code
62
62
  // needs the runtime export when the component didn't import it itself.
63
63
  'formatDate',
64
+ // A comment-scoped component's own scope id (#2910) — reads the
65
+ // `commentScopeRegistry` entry the proxy element was registered under
66
+ // (falling back to its `bf-s` attribute for an element-scoped root), so
67
+ // `[bf-h="${__scopeId}"]` child lookups target THIS component's children
68
+ // rather than the proxy's host/parent scope. See `generate-init.ts`.
69
+ 'ownScopeId',
64
70
  ] as const
65
71
 
66
72
  /** @deprecated Use RUNTIME_IMPORT_CANDIDATES */
@@ -256,6 +256,12 @@ function hasInitScopeOnlyConstant(ctx: ClientJsContext): boolean {
256
256
  for (const c of ctx.localConstants) {
257
257
  if (c.isModule || c.isJsx || c.containsArrow || c.systemConstructKind) continue
258
258
  if (!c.value) continue
259
+ // A mutated binding's value is a pre-mutation snapshot (#2910) —
260
+ // `isInlinableInTemplate` would happily pass a value like `{}` that
261
+ // looks safe on its own, but the mutating statement that gives it its
262
+ // real value only runs in init scope, so the const needs init scope
263
+ // exactly as if the value itself had failed the check.
264
+ if (c.mutatedAfterDeclaration) return true
259
265
  if (!isInlinableInTemplate(c.value, env).ok) return true
260
266
  }
261
267
  return false
@@ -113,6 +113,11 @@ export function expandDynamicPropValue(value: string, ctx: ClientJsContext, scop
113
113
  if (scope?.isBound(trimmedValue)) return value
114
114
 
115
115
  const constant = ctx.localConstants.find((c) => c.name === trimmedValue)
116
+ // A binding mutated after its declaration (#2910) has no compile-time
117
+ // value — `constant.value` is a snapshot from BEFORE the mutation ran.
118
+ // Re-embedding it here would silently drop the mutation; keep the bare
119
+ // reference instead so the emitted getter reads the LIVE binding.
120
+ if (constant?.mutatedAfterDeclaration) return value
116
121
  if (constant && constant.value) {
117
122
  return constant.value
118
123
  }
@@ -156,6 +161,10 @@ export function expandConstantForReactivity(
156
161
  if (scope?.isBound(trimmedValue)) return { expr, freeIds: originalFreeIds }
157
162
 
158
163
  const constant = ctx.localConstants.find((c) => c.name === trimmedValue)
164
+ // See `expandDynamicPropValue`'s matching guard (#2910): a mutated
165
+ // binding's `value` is a stale pre-mutation snapshot, so it must not be
166
+ // substituted in place of a live reference.
167
+ if (constant?.mutatedAfterDeclaration) return { expr, freeIds: originalFreeIds }
159
168
  if (constant && constant.value) {
160
169
  return { expr: constant.value, freeIds: constant.freeIdentifiers }
161
170
  }
@@ -625,6 +625,31 @@ export interface LoopChildConditional {
625
625
  * preamble-bound identifier unexpanded on purpose (#2482 Stage 1b).
626
626
  */
627
627
  readsPreamble?: boolean
628
+ /**
629
+ * `condition` can change value after first render — it reads a signal,
630
+ * memo, prop, or preamble-derived reactive local, as opposed to reading
631
+ * ONLY the (for a static array, fixed-forever) loop item/index (#2897
632
+ * follow-up). `classifyReactivity`'s `kind` can't answer this: it
633
+ * reports `'loop-param'` for ANY expression referencing a loop-bound
634
+ * name, even one that ALSO reads a signal (`item.x && flag()`) — that
635
+ * precedence is deliberate for its own two `ReactivitySource`-typed
636
+ * callers and must not change. This field is computed independently,
637
+ * at collection time, as `n.reactive || readsPreamble ||
638
+ * needsEffectWrapper(...)` — the same "does it need a patchable slot
639
+ * beyond the row's own item" question, without the loop-param
640
+ * short-circuit.
641
+ *
642
+ * Consumers: a static array's row/inner-loop conditional only needs
643
+ * escalation off the compile-time-bakeable static path when THIS is
644
+ * true — a condition that reads only the item/index never changes for
645
+ * a static array, so the row's branch decision (bare element OR child
646
+ * component) is correctly baked once by SSR and wired once by the
647
+ * static `initChild` pass, exactly as it was before #2897. A dynamic
648
+ * (signal-backed) array's `mapArray`/`insert()` path is unaffected by
649
+ * this field — every loop-param conditional is genuinely per-row
650
+ * reactive there, so `bindings.conditionals` itself is never filtered.
651
+ */
652
+ reactiveBeyondLoopScope: boolean
628
653
  }
629
654
 
630
655
  export interface TopLevelLoop extends LoopCore {
@@ -673,7 +698,18 @@ export interface TopLevelLoop extends LoopCore {
673
698
  nestedComponents?: IRLoopChildComponent[] // For nested components in loop bodies
674
699
  // Per-item bindings (events / reactiveAttrs / reactiveTexts / refs / conditionals)
675
700
  // now live on `LoopCore.bindings` — see issue #1244 §B.
676
- isStaticArray: boolean // True if array is a static prop (not a signal)
701
+ // True when this loop takes the static forEach fast path — the IR's own
702
+ // `isStaticArray` (a static, non-signal array) MINUS a fast-path refusal
703
+ // (#2897): a conditional anywhere in the row tree (this row's own
704
+ // `bindings.conditionals`, or any depth-1 `innerLoops[i].bindings.conditionals`)
705
+ // forces this false even when the IR flag is true, since neither the static
706
+ // forEach bake nor `inner-loop-nested`'s clone-and-wire architecture has any
707
+ // conditional-handling machinery — the row falls through to the plain/
708
+ // composite dynamic path instead, which already wires a conditional's live
709
+ // branch-swap correctly. SSR adapters (e.g. Go template's static-loop
710
+ // baking) read the IR-level `isStaticArray` directly and are unaffected;
711
+ // this field is client-JS routing only.
712
+ isStaticArray: boolean
677
713
  useElementReconciliation?: boolean // True: mapArray/mapArrayAnchored + composite rendering (native root with child components)
678
714
  /** Inner loop metadata for composite element reconciliation (array, param, key, container) */
679
715
  innerLoops?: NestedLoop[]
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import ts from 'typescript'
7
- import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode } from '../types.ts'
7
+ import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR } from '../types.ts'
8
8
  import type { TopLevelLoop, BranchLoop, LoopOffset } from './types.ts'
9
9
  import { buildLoopChainExpr } from '../loop-chain.ts'
10
10
  import { templatePartsToJsExpr } from '../template-parts.ts'
@@ -36,6 +36,20 @@ export { DATA_KEY, DATA_KEY_PREFIX, DATA_BF_PH, BF_LOOP_START, BF_LOOP_END, loop
36
36
  */
37
37
  export const PROPS_PARAM = '_p'
38
38
 
39
+ /**
40
+ * True when the component's rendered root is a comment-scoped proxy rather
41
+ * than an element carrying its own `bf-s`/`bf-h` scope id directly — the
42
+ * `comment: true` def flag's condition (`emit-registration.ts`), computed
43
+ * here so `generate-init.ts` can decide the SAME thing before that phase
44
+ * runs (#2910). Two shapes share this: a genuine `needsScopeComment`
45
+ * fragment root (SSR wraps it in `<!--bf-scope:-->`) and a root that is
46
+ * itself a single child-component call (`root.type === 'component'`, #2649)
47
+ * — the wrapping comment marks a scope with no DOM presence of its own.
48
+ */
49
+ export function isCommentScopedRoot(root: ComponentIR['root']): boolean {
50
+ return (root.type === 'fragment' && !!(root as IRFragment).needsScopeComment) || root.type === 'component'
51
+ }
52
+
39
53
  /**
40
54
  * Get the data-key attribute name for a given loop depth.
41
55
  * Outer loop (depth 0): 'data-key'
package/src/jsx-to-ir.ts CHANGED
@@ -6816,6 +6816,9 @@ function tryResolveTemplateSpanFromConst(
6816
6816
  if (ctx.scope.isBound(expr.text)) return null
6817
6817
  const constInfo = findLocalConst(expr.text, ctx.analyzer)
6818
6818
  if (!constInfo) return null
6819
+ // #2910: see `tryResolveIdentifierAsTemplateLiteral`'s matching guard —
6820
+ // a binding mutated after its declaration has no compile-time value.
6821
+ if (constInfo.mutatedAfterDeclaration) return null
6819
6822
  const ast = parseConstInitializer(constInfo)
6820
6823
  if (!ast) return null
6821
6824
  if (ts.isStringLiteral(ast) || ts.isNoSubstitutionTemplateLiteral(ast)) {
@@ -6833,6 +6836,8 @@ function tryResolveTemplateSpanFromConst(
6833
6836
  if (ctx.scope.isBound(expr.expression.text)) return null
6834
6837
  const constInfo = findLocalConst(expr.expression.text, ctx.analyzer)
6835
6838
  if (!constInfo) return null
6839
+ // #2910: see `tryResolveIdentifierAsTemplateLiteral`'s matching guard.
6840
+ if (constInfo.mutatedAfterDeclaration) return null
6836
6841
  const ast = parseConstInitializer(constInfo)
6837
6842
  if (!ast || !ts.isObjectLiteralExpression(ast)) return null
6838
6843
  const cases: Record<string, string> = {}
@@ -7011,6 +7016,15 @@ function tryResolveIdentifierAsTemplateLiteral(
7011
7016
  if (ctx.scope.isBound(ident.text)) return null
7012
7017
  const constInfo = findLocalConst(ident.text, ctx.analyzer)
7013
7018
  if (!constInfo) return null
7019
+ // #2910: a binding mutated after its declaration has no compile-time
7020
+ // value — baking its DECLARATION-TIME literal into the IR here would
7021
+ // freeze the attribute at a pre-mutation snapshot, permanently invisible
7022
+ // to `ir-to-client-js`'s own `mutatedAfterDeclaration` guard (which only
7023
+ // sees this attribute AFTER it has already been resolved to a literal
7024
+ // `template` AttrValue, too late to intervene). Falling through to
7025
+ // `null` here keeps the attribute a plain `expression`, so the runtime
7026
+ // reference stays live.
7027
+ if (constInfo.mutatedAfterDeclaration) return null
7014
7028
  const ast = parseConstInitializer(constInfo)
7015
7029
  if (!ast) return null
7016
7030
 
package/src/types.ts CHANGED
@@ -1736,6 +1736,17 @@ export interface InitStatementInfo {
1736
1736
  * at runtime.
1737
1737
  */
1738
1738
  assignedIdentifiers?: Set<string>
1739
+ /**
1740
+ * Identifiers mutated IN PLACE by this statement — a property/element
1741
+ * write (`config[k] = …`), a known mutating method call
1742
+ * (`items.push(...)`), or `Object.assign(target, …)` — as opposed to
1743
+ * `assignedIdentifiers`, which tracks reassignment of the binding
1744
+ * itself. Read by `markMutatedConstants` (analyzer.ts) to flag the
1745
+ * matching `ConstantInfo.mutatedAfterDeclaration` (#2910): a `const`
1746
+ * whose value is later mutated this way can no longer be treated as
1747
+ * equal to its declaration-time initializer text.
1748
+ */
1749
+ mutatedIdentifiers?: Set<string>
1739
1750
  /**
1740
1751
  * When true, the emitted statement must be prefixed with `;` to defeat
1741
1752
  * ASI fusion with the previous line. Tracked in IR rather than recovered
@@ -1984,6 +1995,26 @@ export interface ConstantInfo {
1984
1995
  isJsxFunction?: boolean
1985
1996
  /** When true, the initializer contains an arrow function or function expression (computed from AST). */
1986
1997
  containsArrow?: boolean
1998
+ /**
1999
+ * When true, a same-scope statement (a `for`/`while` body, or any other
2000
+ * imperative statement) mutates this binding's value AFTER its
2001
+ * declaration — in place (`config[k] = …`, `items.push(...)`) or by
2002
+ * reassigning the binding itself (`let`, later `x = …`) — so `value`
2003
+ * (the declaration's initializer text) no longer reflects what the
2004
+ * binding actually holds by the time the rest of the component runs
2005
+ * (#2910). Set by `markMutatedConstants` (analyzer.ts) from
2006
+ * `InitStatementInfo.mutatedIdentifiers`/`assignedIdentifiers`.
2007
+ *
2008
+ * Every consumer that would otherwise re-inline `value` verbatim in
2009
+ * place of a bare reference to `name` — `expandDynamicPropValue`,
2010
+ * `expandConstantForReactivity`, CSR template inlining
2011
+ * (`compute-inlinability.ts`), and `hasInitScopeOnlyConstant` — must
2012
+ * check this first and fall back to a live reference to the binding
2013
+ * instead. Skipping this check re-embeds a snapshot of the value from
2014
+ * BEFORE the mutation ran, silently dropping everything the mutation
2015
+ * was supposed to do.
2016
+ */
2017
+ mutatedAfterDeclaration?: boolean
1987
2018
  /** The kind of system construct, if the initializer is createContext() or new WeakMap(). */
1988
2019
  systemConstructKind?: 'createContext' | 'weakMap'
1989
2020
  /** Value with destructured prop refs rewritten to _p.propName, for template inlining. */