@barefootjs/jsx 0.35.5 → 0.35.7

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 (106) hide show
  1. package/dist/analyzer-context.d.ts +5 -4
  2. package/dist/analyzer-context.d.ts.map +1 -1
  3. package/dist/analyzer.d.ts.map +1 -1
  4. package/dist/errors.d.ts +0 -1
  5. package/dist/errors.d.ts.map +1 -1
  6. package/dist/index.js +6745 -6488
  7. package/dist/ir-to-client-js/compute-prop-usage.d.ts +6 -0
  8. package/dist/ir-to-client-js/compute-prop-usage.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts +3 -2
  10. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  11. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts +12 -2
  12. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  13. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +40 -0
  14. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -0
  15. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +13 -0
  16. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts +45 -0
  18. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts.map +1 -0
  19. package/dist/ir-to-client-js/control-flow/plan/types.d.ts +2 -0
  20. package/dist/ir-to-client-js/control-flow/plan/types.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts +12 -0
  22. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow.d.ts +2 -1
  24. package/dist/ir-to-client-js/control-flow.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/emit-reactive.d.ts +7 -3
  26. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/index.d.ts +1 -0
  30. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/phases/event-handlers.d.ts +9 -1
  32. package/dist/ir-to-client-js/phases/event-handlers.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts +5 -0
  34. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/phases/props-extraction.d.ts +15 -13
  36. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/phases.d.ts +12 -1
  38. package/dist/ir-to-client-js/phases.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +50 -0
  41. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +29 -0
  43. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -0
  44. package/dist/ir-to-client-js/utils.d.ts +9 -0
  45. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  46. package/dist/jsx-to-ir.d.ts.map +1 -1
  47. package/dist/prop-rewrite.d.ts.map +1 -1
  48. package/dist/props-binding.d.ts +123 -1
  49. package/dist/props-binding.d.ts.map +1 -1
  50. package/dist/ssr-defaults.d.ts.map +1 -1
  51. package/dist/static-literal.d.ts +20 -8
  52. package/dist/static-literal.d.ts.map +1 -1
  53. package/dist/types.d.ts +7 -0
  54. package/dist/types.d.ts.map +1 -1
  55. package/package.json +2 -2
  56. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +31 -35
  57. package/src/__tests__/aliased-destructured-prop-csr.test.ts +19 -7
  58. package/src/__tests__/body-destructured-prop-default-arrow.test.ts +142 -0
  59. package/src/__tests__/body-destructured-prop-default-propsparams.test.ts +153 -0
  60. package/src/__tests__/body-destructured-props-live.test.ts +245 -0
  61. package/src/__tests__/client-js-generation.test.ts +11 -4
  62. package/src/__tests__/client-only-date-lowering.test.ts +5 -2
  63. package/src/__tests__/destructured-from-props-localconst-value.test.ts +17 -6
  64. package/src/__tests__/destructured-props-live.test.ts +167 -0
  65. package/src/__tests__/doc-examples.test.ts +2 -4
  66. package/src/__tests__/event-delegation-container-collision-2930.test.ts +197 -0
  67. package/src/__tests__/format-error.test.ts +5 -3
  68. package/src/__tests__/issue-2960-multi-root-cond-same-tag.test.ts +141 -0
  69. package/src/__tests__/live-only-props.test.ts +160 -0
  70. package/src/__tests__/prop-references.test.ts +26 -17
  71. package/src/__tests__/props-destructuring.test.ts +6 -275
  72. package/src/__tests__/prune-unused-prop-extractions.test.ts +11 -5
  73. package/src/__tests__/signal-getter-not-called.test.ts +5 -0
  74. package/src/__tests__/ssr-defaults.test.ts +83 -0
  75. package/src/__tests__/staged-ir/02-shadow-guards.test.ts +12 -5
  76. package/src/__tests__/static-literal.test.ts +39 -4
  77. package/src/analyzer-context.ts +8 -7
  78. package/src/analyzer.ts +88 -89
  79. package/src/errors.ts +7 -8
  80. package/src/ir-to-client-js/compute-prop-usage.ts +19 -0
  81. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +5 -0
  82. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +27 -11
  83. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +55 -0
  84. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +13 -0
  85. package/src/ir-to-client-js/control-flow/plan/loop-delegation-index.ts +79 -0
  86. package/src/ir-to-client-js/control-flow/plan/types.ts +2 -0
  87. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +50 -10
  88. package/src/ir-to-client-js/control-flow.ts +68 -31
  89. package/src/ir-to-client-js/emit-reactive.ts +12 -8
  90. package/src/ir-to-client-js/generate-init.ts +6 -0
  91. package/src/ir-to-client-js/html-template.ts +65 -9
  92. package/src/ir-to-client-js/index.ts +45 -3
  93. package/src/ir-to-client-js/phases/event-handlers.ts +10 -0
  94. package/src/ir-to-client-js/phases/props-event-handlers.ts +6 -0
  95. package/src/ir-to-client-js/phases/props-extraction.ts +29 -48
  96. package/src/ir-to-client-js/phases.ts +17 -3
  97. package/src/ir-to-client-js/plan/build-declaration-emit.ts +6 -5
  98. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +31 -10
  99. package/src/ir-to-client-js/rewrite-destructured-props.ts +222 -0
  100. package/src/ir-to-client-js/utils.ts +14 -0
  101. package/src/jsx-to-ir.ts +96 -48
  102. package/src/prop-rewrite.ts +11 -0
  103. package/src/props-binding.ts +185 -6
  104. package/src/ssr-defaults.ts +10 -5
  105. package/src/static-literal.ts +21 -9
  106. package/src/types.ts +7 -0
package/src/jsx-to-ir.ts CHANGED
@@ -41,7 +41,7 @@ import {
41
41
  } from './types.ts'
42
42
  import { type AnalyzerContext, type MultiReturnJsxInfo, getSourceLocation, collectReactiveGetterNames } from './analyzer-context.ts'
43
43
  import { parseExpression, isSupported, parseBlockBody, foldBlockToExpr, predicateTernaryToLogical, tsNodeToParsedExpr, sortComparatorFromArrow, stringifyParsedExpr, cssKebabCase, CALLBACK_METHODS, type ParsedExpr } from './expression-parser.ts'
44
- import type { IRLoopSort, FunctionInfo, ConstantInfo } from './types.ts'
44
+ import type { IRLoopSort, FunctionInfo, ConstantInfo, ParamInfo } from './types.ts'
45
45
  import { formatParamWithType } from './module-exports.ts'
46
46
  import { createError, ErrorCodes, internalInvariant } from './errors.ts'
47
47
  import { CLIENT_BUILTIN_SOURCE, isClientBuiltinName, type ClientBuiltinTag } from './builtins.ts'
@@ -51,7 +51,8 @@ import {
51
51
  collectAstPropRefs,
52
52
  rewriteScopedValueRefs,
53
53
  } from './prop-rewrite.ts'
54
- import { boundPropLocalNames, buildPropAliasMap, resolveAliasOrigin, resolveRestSpreadOriginCore } from './props-binding.ts'
54
+ import { boundPropLocalNames, buildPropAliasMap, resolveAliasOrigin, resolveRestSpreadOriginCore, livePropReadExpr } from './props-binding.ts'
55
+ import { PROPS_PARAM } from './ir-to-client-js/utils.ts'
55
56
  import { resolveFreeRefs, isNameBound as isNameBoundInEnv, type BindingEnvironment } from './free-refs.ts'
56
57
  import { computeFileScope } from './ir-to-client-js/component-scope.ts'
57
58
  import { createTemplateAwareStringProtector } from './ir-to-client-js/html-template.ts'
@@ -129,6 +130,20 @@ interface TransformContext {
129
130
  * `_p.<local>` (#2524 CSR half: `_p` is always caller-keyed).
130
131
  */
131
132
  _destructuredPropAliases?: Map<string, string> | null
133
+ /**
134
+ * Cached local-name → `ParamInfo` map for the same eligible set, so
135
+ * `rewriteBarePropRefs` can apply a prop's destructure DEFAULT. Without
136
+ * it the CSR-only `template:` literal emitted a bare `_p.label` for
137
+ * `data-label={label}` with `label = 'none'`: correct once the caller
138
+ * sends a value, but the attribute was omitted entirely on the first
139
+ * render, where `_p.label` is `undefined`. Covers PARAMETER destructuring
140
+ * and an UNRENAMED BODY destructure default alike (`function Foo(props) {
141
+ * const { label = 'none' } = props }`) — both populate `defaultValue`
142
+ * directly on `propsParams` (the parameter form in `extractProps`, the
143
+ * body form via `collectConstant`'s overlay, #2943), so this map is a
144
+ * plain re-keying of `eligible`, no second default-resolution needed.
145
+ */
146
+ _destructuredPropInfoByName?: ReadonlyMap<string, ParamInfo> | null
132
147
  /**
133
148
  * The active `.map()`/callback binding stack (#2482 Stage 1a) — replaces
134
149
  * the former mutable per-name `Set<string>` mutated in lockstep with
@@ -588,7 +603,18 @@ function rewriteBarePropRefs(text: string, expr: ts.Node, ctx: TransformContext)
588
603
  // for references to those locals and union the matching dep sets.
589
604
  const extraPropRefs = collectBranchLocalPropRefsViaSubstitution(expr, ctx)
590
605
  const propAliases = getDestructuredPropAliases(ctx)
591
- return rewriteBarePropRefsCore(dateLowered, expr, propNames, extraPropRefs, propAliases ?? undefined)
606
+ const propInfoByName = getDestructuredPropInfoByName(ctx)
607
+ // No `usage`/`usedAsCondition`: the `?? []` / `?? {}` fallbacks need
608
+ // Phase-2 `PropUsage` data this Phase-1 rewrite doesn't have. Only the
609
+ // explicit destructure default applies here — see
610
+ // `_destructuredPropInfoByName`.
611
+ const replacementFor = propInfoByName
612
+ ? (localName: string, callerKey: string): string => {
613
+ const info = propInfoByName.get(localName)
614
+ return info ? livePropReadExpr(info, undefined, false) : `${PROPS_PARAM}.${callerKey}`
615
+ }
616
+ : undefined
617
+ return rewriteBarePropRefsCore(dateLowered, expr, propNames, extraPropRefs, propAliases ?? undefined, replacementFor)
592
618
  }
593
619
 
594
620
  /**
@@ -676,10 +702,27 @@ function getDestructuredPropNames(ctx: TransformContext): Set<string> | null {
676
702
  const names = eligible.map(p => p.name)
677
703
  ctx._destructuredPropNames = names.length > 0 ? new Set(names) : null
678
704
  ctx._destructuredPropAliases = buildPropAliasMap(eligible) ?? null
705
+ // #2943: `eligible`'s `ParamInfo`s already carry a body-destructured
706
+ // default when the alias is unrenamed — the analyzer overlays it onto
707
+ // `propsParams` directly at the binding's own declaration
708
+ // (`collectConstant`, `analyzer.ts`), so no separate overlay is needed
709
+ // here (there used to be one; see git history at #2934/#2943 for why).
710
+ const infoByName = new Map<string, ParamInfo>()
711
+ for (const p of eligible) infoByName.set(p.name, p)
712
+ ctx._destructuredPropInfoByName = infoByName.size > 0 ? infoByName : null
679
713
  }
680
714
  return ctx._destructuredPropNames ?? null
681
715
  }
682
716
 
717
+ /**
718
+ * Companion to `getDestructuredPropNames`: local-name → `ParamInfo` for the
719
+ * same shadow-filtered eligible set. Both caches are written in one pass.
720
+ */
721
+ function getDestructuredPropInfoByName(ctx: TransformContext): ReadonlyMap<string, ParamInfo> | null {
722
+ if (ctx._destructuredPropNames === undefined) getDestructuredPropNames(ctx)
723
+ return ctx._destructuredPropInfoByName ?? null
724
+ }
725
+
683
726
  /**
684
727
  * Companion to `getDestructuredPropNames`: the local-name → caller-key
685
728
  * alias map for the SAME shadow-filtered eligible set, populated as a
@@ -2376,8 +2419,9 @@ function transformExpressionInner(
2376
2419
  // Check for bare signal/memo identifier (BF044). A JSX text child is
2377
2420
  // inherently a RENDERED position — unlike a component prop, `{expr}`
2378
2421
  // here always becomes literal rendered output, never an opaque value
2379
- // handed to a consumer to call later — so nested descent is always on.
2380
- checkBareSignalOrMemoIdentifier(expr, ctx, { descendNested: true })
2422
+ // handed to a consumer to call later — so the check (top-level and
2423
+ // nested descent) always fires.
2424
+ checkBareSignalOrMemoIdentifier(expr, ctx, { renderedPosition: true })
2381
2425
 
2382
2426
  // #547: Inline a JSX constant referenced by identifier. Unique to JSX-child
2383
2427
  // position — conditional branches and return position don't resolve
@@ -6621,14 +6665,14 @@ function getAttributeValue(attr: ts.JsxAttribute, ctx: TransformContext): AttrVa
6621
6665
  // `processComponentProps`), and only the element-attribute case is
6622
6666
  // a RENDERED position — a component prop is an opaque value handed
6623
6667
  // to the component, and this codebase's Context-Provider idiom
6624
- // depends on that value being an uncalled accessor (`value={{
6625
- // open }}`, ui/components/ui/select/index.tsx — calling it eagerly
6626
- // there would freeze the value at provider-render time and break
6627
- // every consumer's reactivity). So nested descent is gated on
6628
- // element-vs-component, derived from the tag this attribute lives
6629
- // on; the top-level bare-identifier check stays unconditional
6630
- // either way, unchanged from this diagnostic's original behaviour.
6631
- checkBareSignalOrMemoIdentifier(expr, ctx, { descendNested: isRenderedElementAttribute(attr, ctx) })
6668
+ // depends on that value being an uncalled accessor, whether passed
6669
+ // directly (`x={open}`, #2760) or nested in an object literal
6670
+ // (`value={{ open }}`, ui/components/ui/select/index.tsx) — calling
6671
+ // it eagerly there would freeze the value at provider-render time
6672
+ // and break every consumer's reactivity. So the entire check (top
6673
+ // level included) is gated on element-vs-component, derived from
6674
+ // the tag this attribute lives on.
6675
+ checkBareSignalOrMemoIdentifier(expr, ctx, { renderedPosition: isRenderedElementAttribute(attr, ctx) })
6632
6676
 
6633
6677
  // Static style object: style={{ key: 'value', ... }} → CSS string at compile time
6634
6678
  if (attr.name.getText(ctx.sourceFile) === 'style' && ts.isObjectLiteralExpression(expr)) {
@@ -7708,15 +7752,16 @@ function processComponentProps(
7708
7752
  * hyphenated (a custom element) is a real DOM node, capitalised or
7709
7753
  * dotted (`Select.Provider`) is a component.
7710
7754
  *
7711
- * Feeds `checkBareSignalOrMemoIdentifier`'s `descendNested` gate: a
7755
+ * Feeds `checkBareSignalOrMemoIdentifier`'s `renderedPosition` gate: a
7712
7756
  * DOM attribute value is a RENDERED position (this is genuinely what
7713
7757
  * ends up in the DOM), so a bare getter buried inside it — `style={{
7714
7758
  * color: val }}` — is exactly as much a forgotten `()` as a top-level
7715
7759
  * one. A component prop is not rendered — it's an opaque value handed
7716
7760
  * to the component — and this codebase's Context-Provider idiom
7717
- * depends on that value being an UNCALLED accessor
7761
+ * depends on that value being an UNCALLED accessor, whether passed
7762
+ * directly (`x={open}`) or nested in an object literal
7718
7763
  * (`ui/components/ui/select/index.tsx`'s `value={{ open, ... }}`), so
7719
- * nested descent must not fire there.
7764
+ * the check must not fire there at all (#2760).
7720
7765
  */
7721
7766
  function isRenderedElementAttribute(attr: ts.JsxAttribute, ctx: TransformContext): boolean {
7722
7767
  const tagName = attr.parent.parent.tagName.getText(ctx.sourceFile)
@@ -7728,22 +7773,25 @@ function isRenderedElementAttribute(attr: ts.JsxAttribute, ctx: TransformContext
7728
7773
  * Emits BF044 when a signal/memo getter is passed without calling it.
7729
7774
  * e.g., value={count} instead of value={count()}
7730
7775
  *
7731
- * The top-level check — is `expr` itself a bare reactive identifier —
7732
- * always runs, unchanged from this diagnostic's original behaviour
7733
- * (`value={count}`, `<Foo x={count} />` keep firing regardless of
7734
- * position). `descendNested` additionally opts into walking INSIDE a
7735
- * composite expression — call arguments, template-literal spans,
7776
+ * `renderedPosition` gates the ENTIRE check, top-level included: only a
7777
+ * RENDERED position (a JSX text child; a DOM element's attribute value
7778
+ * via `isRenderedElementAttribute`) risks a forgotten `()` silently
7779
+ * producing wrong output, so only those positions fire at all. A
7780
+ * component prop is not rendered — it's an opaque value handed to the
7781
+ * component — and a bare getter there is this codebase's deliberate
7782
+ * Context-Provider idiom (measured: 66 such uses across
7783
+ * `ui/components/**`/`site/**`, all legitimate, none a forgotten `()`),
7784
+ * whether written directly (`<Foo x={val} />`) or nested inside an
7785
+ * object literal (`<Foo value={{ val }} />`, already silent before this
7786
+ * gate existed) — #2760 settled the two forms as one idiom, not an
7787
+ * inconsistency to fix by tightening the direct form. When
7788
+ * `renderedPosition` is true, nested descent additionally walks INSIDE
7789
+ * a composite expression — call arguments, template-literal spans,
7736
7790
  * ternary branches (condition + both arms), array/object literal
7737
7791
  * members, binary/logical operands, parenthesized wrappers — to catch
7738
- * a bare reference buried anywhere in that reachable set (#2755,
7739
- * #2751: this is the single upstream gate whose shallow top-level-only
7740
- * check let both downstream bugs through). Callers opt in only for
7741
- * RENDERED positions (a JSX text child; a DOM element's attribute value
7742
- * via `isRenderedElementAttribute`) — never for a component prop, where
7743
- * a bare getter is this codebase's deliberate Context-Provider idiom
7744
- * (measured: 66 such uses across `ui/components/**`/`site/**`, all
7745
- * legitimate, none a forgotten `()` — widening the gate to fire there
7746
- * would be a correctness regression, not a fix).
7792
+ * a bare reference buried anywhere in that reachable set (#2755, #2751:
7793
+ * this is the single upstream gate whose shallow top-level-only check
7794
+ * let both downstream bugs through).
7747
7795
  *
7748
7796
  * Two structural exclusions apply whenever descending, both required
7749
7797
  * so the walk doesn't false-positive on shapes that read the name
@@ -7781,8 +7829,10 @@ function isRenderedElementAttribute(attr: ts.JsxAttribute, ctx: TransformContext
7781
7829
  function checkBareSignalOrMemoIdentifier(
7782
7830
  expr: ts.Expression,
7783
7831
  ctx: TransformContext,
7784
- options?: { descendNested?: boolean }
7832
+ options?: { renderedPosition?: boolean }
7785
7833
  ): void {
7834
+ if (!options?.renderedPosition) return
7835
+
7786
7836
  const reactiveNames = new Map<string, 'signal' | 'memo'>()
7787
7837
  for (const signal of ctx.analyzer.signals) reactiveNames.set(signal.getter, 'signal')
7788
7838
  for (const memo of ctx.analyzer.memos) reactiveNames.set(memo.name, 'memo')
@@ -7804,29 +7854,27 @@ function checkBareSignalOrMemoIdentifier(
7804
7854
  )
7805
7855
  }
7806
7856
 
7807
- // Top-level check — unchanged from this diagnostic's original
7808
- // position-gating (fires unconditionally, everywhere), but NOW also
7809
- // respects the ambient loop/callback `BindingScope` a shadowed name
7810
- // needs — a pre-existing gap (the original single-line
7811
- // `if (!ts.isIdentifier(expr)) return` never consulted scope either)
7812
- // that stayed invisible only because a bare top-level identifier
7813
- // shadowed by a `.map(name => ...)` row param never happened to be
7814
- // exercised by any prior test. `ctx.scope` is the LIVE scope at this
7815
- // JSX node — already entered for the current loop row/callback frame
7816
- // by the time an attribute/child expression under it is checked
7817
- // (`enterLoopRow`/`enterCallback`, `scope/binding-scope.ts`) — so
7818
- // `isBound` here is a shadow-guard read in exactly the sense
7819
- // `spec/compiler.md`'s `BindingScope` section describes: is a signal
7820
- // getter of this name shadowed HERE, not "does this expression need
7821
- // its own reactive slot".
7857
+ // Top-level check — `renderedPosition` (checked above) has already
7858
+ // ruled out a component-prop position, so any call reaching here is a
7859
+ // genuinely rendered one. Also respects the ambient loop/callback
7860
+ // `BindingScope` a shadowed name needs — a pre-existing gap (the
7861
+ // original single-line `if (!ts.isIdentifier(expr)) return` never
7862
+ // consulted scope either) that stayed invisible only because a bare
7863
+ // top-level identifier shadowed by a `.map(name => ...)` row param
7864
+ // never happened to be exercised by any prior test. `ctx.scope` is
7865
+ // the LIVE scope at this JSX node — already entered for the current
7866
+ // loop row/callback frame by the time an attribute/child expression
7867
+ // under it is checked (`enterLoopRow`/`enterCallback`,
7868
+ // `scope/binding-scope.ts`) — so `isBound` here is a shadow-guard
7869
+ // read in exactly the sense `spec/compiler.md`'s `BindingScope`
7870
+ // section describes: is a signal getter of this name shadowed HERE,
7871
+ // not "does this expression need its own reactive slot".
7822
7872
  if (ts.isIdentifier(expr)) {
7823
7873
  const kind = reactiveNames.get(expr.text)
7824
7874
  if (kind && !ctx.scope.isBound(expr.text)) report(expr, expr.text, kind)
7825
7875
  return
7826
7876
  }
7827
7877
 
7828
- if (!options?.descendNested) return
7829
-
7830
7878
  const boundStack: Array<Set<string>> = []
7831
7879
  const isBound = (name: string): boolean => {
7832
7880
  for (let i = boundStack.length - 1; i >= 0; i--) {
@@ -99,6 +99,12 @@ function walkWithScope(
99
99
  * binding (`renamed`) — and pullfrog review on #2889 caught that only the
100
100
  * latter was excluded, so a substituted name colliding with the SOURCE key
101
101
  * still corrupted to invalid JS (`const { (_p.tag): renamed } = obj`).
102
+ *
103
+ * The accessor/method/property NAME checks close the same gap for
104
+ * `{ get className() { return className } }` (the shape the
105
+ * reactive-child-props forwarding machinery emits): the name slot is walked
106
+ * like any other identifier, and substituting there yields
107
+ * `get (_p.className ?? '')() { ... }`.
102
108
  */
103
109
  function isNonValuePosition(n: ts.Identifier, parent: ts.Node | undefined): boolean {
104
110
  if (!parent) return false
@@ -108,6 +114,11 @@ function isNonValuePosition(n: ts.Identifier, parent: ts.Node | undefined): bool
108
114
  if ((ts.isParameter(parent) || ts.isVariableDeclaration(parent) || ts.isBindingElement(parent)) && parent.name === n) return true
109
115
  if (ts.isBindingElement(parent) && parent.propertyName === n) return true
110
116
  if (ts.isTypeReferenceNode(parent)) return true
117
+ if (
118
+ (ts.isGetAccessorDeclaration(parent) || ts.isSetAccessorDeclaration(parent) || ts.isMethodDeclaration(parent)) &&
119
+ parent.name === n
120
+ ) return true
121
+ if ((ts.isPropertySignature(parent) || ts.isPropertyDeclaration(parent)) && parent.name === n) return true
111
122
  return false
112
123
  }
113
124
 
@@ -1,5 +1,8 @@
1
1
  import ts from 'typescript'
2
- import type { ConstantInfo, ParamInfo } from './types.ts'
2
+ import type { ConstantInfo, ParamInfo, PropUsage } from './types.ts'
3
+ import { propHasPropertyAccess } from './ir-to-client-js/compute-prop-usage.ts'
4
+ import { parsePropReadInitializer } from './ir-to-client-js/prune-unused-prop-extractions.ts'
5
+ import { PROPS_PARAM } from './ir-to-client-js/utils.ts'
3
6
 
4
7
  /**
5
8
  * Authoritative IdentifierName classification for a destructure-pattern
@@ -88,19 +91,117 @@ export function buildPropAliasMap(params: readonly ParamInfo[]): Map<string, str
88
91
  * Returns an empty map for a parameter-destructuring component
89
92
  * (`propsObjectName === null`) — that shape's aliasing is already fully
90
93
  * covered by `buildPropAliasMap`.
94
+ *
95
+ * Passes `requireLiveRewriteSafe: false` to `resolveBodyPropAliases` — this
96
+ * consumer only needs the local-name↔caller-key mapping to seed the SSR
97
+ * stash under the local's name (#2788), which is sound regardless of
98
+ * `const`/`let` or a later mutation: those two exclusions exist solely to
99
+ * protect the LIVE client-JS rewrite (`rewriteBodyAliasReads`) from turning
100
+ * a reassignment into a silent write-through to the caller's prop, a
101
+ * concern this SSR-side, declaration-time alias mapping doesn't share. A
102
+ * `let`-declared renamed body destructure (`let { children: kids } =
103
+ * props`) is exactly as valid an alias for stash-seeding purposes as a
104
+ * `const` one — inheriting the stricter filter here would silently drop
105
+ * its stash entry and reintroduce #2788 for that one shape.
91
106
  */
92
107
  export function resolveBodyDestructuredPropAliases(
93
108
  localConstants: readonly ConstantInfo[],
94
109
  propsObjectName: string | null,
95
110
  ): Map<string, string> {
96
111
  const aliases = new Map<string, string>()
112
+ for (const [local, alias] of resolveBodyPropAliases(localConstants, propsObjectName, { requireLiveRewriteSafe: false })) {
113
+ if (!alias.hasDefault) aliases.set(local, alias.key)
114
+ }
115
+ return aliases
116
+ }
117
+
118
+ /**
119
+ * A local `const`/`let` in a bare-props-form component (`function
120
+ * Foo(props: Props)`) whose value is a PURE alias of a single caller-facing
121
+ * prop — either a body destructure (`const { value } = props`, `const {
122
+ * label = 'none' } = props`) or an equivalent bare member read (`const label
123
+ * = props.label ?? 'fallback'`); the analyzer's IR can't distinguish the two
124
+ * shapes (both parse to the same `ConstantInfo`), and neither can this
125
+ * resolver — see `resolveBodyAliasReads`'s (`rewrite-destructured-props.ts`)
126
+ * docstring for why that's the right call.
127
+ */
128
+ export interface BodyPropAlias {
129
+ /** Caller-facing prop key (`props.<key>`). */
130
+ key: string
131
+ /** Whether the value has a `?? <default>` (destructure default, or an
132
+ * explicit `props.x ?? d` alias) — `resolveBodyDestructuredPropAliases`
133
+ * excludes these; `resolveBodyAliasReads` handles them itself. */
134
+ hasDefault: boolean
135
+ /** When true, the default value contains an arrow function or function
136
+ * expression — mirrors `ParamInfo.defaultContainsArrow`. `hasDefault`'s
137
+ * own source text is NOT carried here (unlike `defaultContainsArrow`):
138
+ * `rewriteBodyAliasReads` re-derives it from the emitted init body's own
139
+ * declaration rather than from this alias (see its docstring), and the
140
+ * only OTHER consumer that once read a `defaultValue` field here — the
141
+ * `jsx-to-ir.ts` CSR-template overlay — is gone since #2943 folded the
142
+ * default straight onto `ParamInfo.defaultValue` at the analyzer level. */
143
+ defaultContainsArrow?: boolean
144
+ }
145
+
146
+ /**
147
+ * Local-name → alias-info map for every PURE prop-passthrough local in a
148
+ * bare-props-form component — the superset `resolveBodyDestructuredPropAliases`
149
+ * (defaultless only, for the SSR-stash use above) and `resolveBodyAliasReads`
150
+ * (`rewrite-destructured-props.ts`, live-read rewrite including defaults)
151
+ * both build on.
152
+ *
153
+ * Excludes:
154
+ * - `propsObjectName === null` (parameter-destructuring components — that
155
+ * shape's aliasing is fully covered by `buildPropAliasMap` instead).
156
+ * - `isModule` (module-scope constants aren't per-instance prop reads).
157
+ * - When `requireLiveRewriteSafe` is true (the default — the right
158
+ * setting for a caller that turns the alias into a LIVE `_p.X` read,
159
+ * e.g. `rewriteBodyAliasReads`), also excludes:
160
+ * - `let` bindings: a later reassignment (`value = 9`) would need to
161
+ * become `_p.value = 9`, silently writing through to the caller's
162
+ * prop instead of a local variable — never safe to infer.
163
+ * - `mutatedAfterDeclaration` (#2910's `markMutatedConstants`): once
164
+ * something mutates the binding in place after its declaration,
165
+ * `value` no longer tracks the live prop, and treating it as a
166
+ * passthrough alias would silently drop the mutation.
167
+ * A caller that only needs the declaration-time local↔caller-key
168
+ * mapping (e.g. `resolveBodyDestructuredPropAliases`, feeding the SSR
169
+ * stash seed) passes `requireLiveRewriteSafe: false` — a `let` local or
170
+ * one mutated later in the function body is still a perfectly valid
171
+ * alias AT its declaration, which is all an initial SSR-stash seed
172
+ * needs.
173
+ */
174
+ export function resolveBodyPropAliases(
175
+ localConstants: readonly ConstantInfo[],
176
+ propsObjectName: string | null,
177
+ options: { requireLiveRewriteSafe?: boolean } = {},
178
+ ): Map<string, BodyPropAlias> {
179
+ const { requireLiveRewriteSafe = true } = options
180
+ const aliases = new Map<string, BodyPropAlias>()
97
181
  if (propsObjectName === null) return aliases
98
182
  for (const c of localConstants) {
99
- if (c.isModule) continue
100
- const m = c.parsed
101
- if (m?.kind === 'member' && !m.computed && m.object.kind === 'identifier' && m.object.name === propsObjectName) {
102
- aliases.set(c.name, m.property)
103
- }
183
+ if (c.isModule || !c.value) continue
184
+ if (requireLiveRewriteSafe && (c.declarationKind !== 'const' || c.mutatedAfterDeclaration)) continue
185
+ // Re-parse `value` (rather than walking `c.parsed`) so the default's
186
+ // SOURCE TEXT is available verbatim — `ParsedExpr` structures the
187
+ // default but doesn't retain its original formatting, and this reuses
188
+ // the one recognizer (`parsePropReadInitializer`) the emit-time passes
189
+ // (`prune-unused-prop-extractions.ts`, `rewrite-destructured-props.ts`)
190
+ // already share, rather than a third bespoke shape check. Wrapped in
191
+ // parens so a bare object-literal-like value still parses as an
192
+ // expression, matching `ConstantInfo.parsed`'s own convention.
193
+ const sourceFile = ts.createSourceFile('__alias__.ts', `(${c.value.trim()});`, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS)
194
+ const stmt = sourceFile.statements[0]
195
+ if (!stmt || !ts.isExpressionStatement(stmt)) continue
196
+ const node = ts.isParenthesizedExpression(stmt.expression) ? stmt.expression.expression : stmt.expression
197
+ const read = parsePropReadInitializer(node, propsObjectName)
198
+ if (read === null) continue
199
+ const hasDefault = read.fallback !== null
200
+ aliases.set(c.name, {
201
+ key: read.key,
202
+ hasDefault,
203
+ defaultContainsArrow: hasDefault ? c.containsArrow : undefined,
204
+ })
104
205
  }
105
206
  return aliases
106
207
  }
@@ -130,6 +231,84 @@ export function boundPropLocalNames(b: PropsParamBindings): ReadonlySet<string>
130
231
 
131
232
  const EMPTY_SET: ReadonlySet<string> = new Set()
132
233
 
234
+ /**
235
+ * The subset of `ParamInfo` a live prop read actually needs. A body-level
236
+ * pure-alias local (`resolveBodyPropAliases`) has no real `ParamInfo` — it
237
+ * never bound a parameter — so callers synthesize one of these instead of a
238
+ * full `ParamInfo` (which would need a fabricated `type`/`optional`).
239
+ */
240
+ export type LivePropReadInfo = Pick<ParamInfo, 'name' | 'sourceName' | 'defaultValue' | 'defaultContainsArrow'>
241
+
242
+ /** `_p.<callerKey>` — `_p` is always keyed by the caller-facing name (#2524 CSR half). */
243
+ export function propReadBase(p: LivePropReadInfo): string {
244
+ return `${PROPS_PARAM}.${p.sourceName ?? p.name}`
245
+ }
246
+
247
+ /**
248
+ * The text a destructure default contributes as the right operand of a `??`
249
+ * prop read. An arrow (or function-expression) default needs its own
250
+ * parens — `??` binds tighter than an arrow head, so `_p.onInput ?? () =>
251
+ * {}` is a SyntaxError. The one implementation of that decision, shared by
252
+ * `propReadFallback` below (every live `_p.X` read) and `collectConstant`'s
253
+ * body-destructure expansion (`analyzer.ts`, which builds
254
+ * `ConstantInfo.value`) — see #2940, where the analyzer built that value
255
+ * without this check and emitted invalid JS.
256
+ */
257
+ export function coalesceDefaultText(defaultValue: string, defaultContainsArrow: boolean | undefined): string {
258
+ return defaultContainsArrow ? `(${defaultValue})` : defaultValue
259
+ }
260
+
261
+ /**
262
+ * The `??` right-hand side for a prop read, or null when the bare read is
263
+ * correct. Precedence:
264
+ * 1. an explicit destructure default (`{ x = 1 }`) — an arrow default gets
265
+ * an extra paren, since `??` binds tighter than the arrow head and
266
+ * `_p.onInput ?? () => {}` would be a syntax error.
267
+ * 2. `usedAsLoopArray` → `[]`.
268
+ * 3. property/index access → `{}`, UNLESS the prop also guards a
269
+ * conditional: `{}` is truthy, so that would always render the branch.
270
+ * 4. otherwise null — a defaultless optional reads `undefined` when
271
+ * absent, which is what the JS binding did and what SSR produces. A
272
+ * synthesized zero default would diverge from SSR instead (`size ?? 1`
273
+ * seeds 1 server-side; a `_p.size ?? 0` read would hydrate to 0).
274
+ */
275
+ export function propReadFallback(
276
+ p: LivePropReadInfo,
277
+ usage: PropUsage | undefined,
278
+ usedAsCondition: boolean,
279
+ ): string | null {
280
+ if (p.defaultValue) return coalesceDefaultText(p.defaultValue, p.defaultContainsArrow)
281
+ if (usage?.usedAsLoopArray) return '[]'
282
+ if (propHasPropertyAccess(usage) && !usedAsCondition) return '{}'
283
+ return null
284
+ }
285
+
286
+ /**
287
+ * The live read of a destructured prop inside init scope, in the same shape
288
+ * props-object mode emits for `props.X`. The one formula every live-read
289
+ * call site shares: the whole-init-body rewrite
290
+ * (`rewriteDestructuredPropReads`), the reactive attribute rewrite
291
+ * (`emit-reactive.ts`), the controlled-signal sync effect
292
+ * (`build-declaration-emit.ts`), and the Phase-1 CSR `template:` rewrite
293
+ * (`jsx-to-ir.ts`).
294
+ *
295
+ * Parenthesized whenever a fallback is present so it splices safely into an
296
+ * arbitrary read position (a member access, a call argument, …).
297
+ * `emitPropsExtraction` deliberately does NOT use this: its `children` line
298
+ * must stay an unparenthesized `const X = _p.X [?? d]` for
299
+ * `pruneUnusedPropExtractions`'s AST matcher, so it composes
300
+ * `propReadBase`/`propReadFallback` itself.
301
+ */
302
+ export function livePropReadExpr(
303
+ p: LivePropReadInfo,
304
+ usage: PropUsage | undefined,
305
+ usedAsCondition: boolean,
306
+ ): string {
307
+ const base = propReadBase(p)
308
+ const fallback = propReadFallback(p, usage, usedAsCondition)
309
+ return fallback === null ? base : `(${base} ?? ${fallback})`
310
+ }
311
+
133
312
  /**
134
313
  * The two component bindings that forward the caller's leftover props:
135
314
  * the destructured `...rest` binding and a whole undestructured `(props)`
@@ -184,10 +184,15 @@ export function extractSsrDefaults(metadata: IRMetadata): Record<string, SsrDefa
184
184
  // adapters flatten `props.X` to the same bare scalar (`$X` — see
185
185
  // the Mojo emitter's `member()`), NOT a `$props->{X}` hash read,
186
186
  // so an unseeded prop the caller forgets to pass is a strict-mode
187
- // compile error, not a soft `undef` (#2126). Seed every declared
188
- // prop with a `null` fallback (→ undef; the template-side `// …`
189
- // recompute supplies the real default, and a caller-passed prop
190
- // wins via `propName`).
187
+ // compile error, not a soft `undef` (#2126). A BODY-destructured
188
+ // default (`const { label = 'none' } = props`, #2943) reaches this
189
+ // same `p.defaultValue` too — the analyzer overlays it onto
190
+ // `propsParams` at the binding's own declaration (`collectConstant`,
191
+ // `analyzer.ts`) — so it needs no separate branch here: any prop
192
+ // with a static default, from either destructuring form, seeds the
193
+ // evaluated value; one with none seeds `null` (→ undef; the
194
+ // template-side `// …` recompute supplies the real default, and a
195
+ // caller-passed prop wins via `propName`).
191
196
  for (const p of metadata.propsParams) {
192
197
  if (p.isRest) continue
193
198
  // `propName` is the CALLER-facing key (`$props->{propName}` in the Perl
@@ -195,7 +200,7 @@ export function extractSsrDefaults(metadata: IRMetadata): Record<string, SsrDefa
195
200
  // `n`, not the local binding `count` the template variable is keyed by.
196
201
  // `sourceName ?? name` is an identity for every un-aliased prop.
197
202
  const callerPropName = p.sourceName ?? p.name
198
- if (metadata.propsObjectName === null && p.defaultValue !== undefined) {
203
+ if (p.defaultValue !== undefined) {
199
204
  const value = tryStaticEval(p.defaultValue, { bindings: {}, propsLike })
200
205
  out[p.name] = { propName: callerPropName, value: resultToJsonable(value) }
201
206
  } else {
@@ -3,9 +3,9 @@
3
3
  * is a literal, a no-substitution (or fully-static) template literal, an
4
4
  * array-literal of pure elements, or an object-literal of pure values
5
5
  * evaluates here to its plain JS value. Consumed by each adapter's
6
- * `renderLoop` to admit a function-scope local const whose initializer is
7
- * entirely known at compile time as a loop source — inlining its value the
8
- * same way a module-scope const already is — while still refusing a
6
+ * `renderLoop` to admit a local const (module- or function-scope alike,
7
+ * #2946) whose initializer is entirely known at compile time as a loop
8
+ * source — inlining its value as a native literal — while still refusing a
9
9
  * runtime-computed expression (`Object.entries(props.tags).filter(...)`,
10
10
  * #2069) with BF101, since `call`/unresolvable-`member` shapes fall through
11
11
  * to `null` below.
@@ -117,11 +117,23 @@ export function isFullyStaticLiteral(expr: ParsedExpr): boolean {
117
117
  /**
118
118
  * Shared loop-source resolution for `renderLoop` across adapters: the loop
119
119
  * array is either an inline array-literal, or a bare identifier naming a
120
- * FUNCTION-scope (`!isModule`) local const whose initializer evaluates
121
- * statically. Module-scope consts are deliberately excluded — an existing,
122
- * separate seeding path already handles those. Returns the evaluated items,
123
- * or `null` if the source isn't resolvable this way (including when it
124
- * resolves to something other than an array).
120
+ * local const — module-scope or function-scope alike (#2946) — whose
121
+ * initializer evaluates statically. The only exclusions are (1) a name the
122
+ * enclosing loop scope already binds (`isNameShadowed`), (2) a const flagged
123
+ * `mutatedAfterDeclaration` (#2910 — its initializer is a stale snapshot,
124
+ * not the const's current value), and (3) a non-literal initializer.
125
+ *
126
+ * Module-scope consts used to be excluded outright on the theory that an
127
+ * existing, separate seeding path already handled them — but that path
128
+ * (`ssr-defaults.ts`'s `tryStaticEval`/`bindings`, and Go's
129
+ * `convertInitialValue`) only ever sees a module const through a
130
+ * `createSignal(...)` argument. A module const `.map()`'d directly, with no
131
+ * signal in between, was never seeded by anything and silently rendered
132
+ * empty (ERB/Jinja/Twig/Blade/Xslate/minijinja), failed to compile
133
+ * (Mojolicious), or failed at execution time (Go) — see #2946.
134
+ *
135
+ * Returns the evaluated items, or `null` if the source isn't resolvable this
136
+ * way (including when it resolves to something other than an array).
125
137
  */
126
138
  export function resolveStaticLoopSource(
127
139
  arrayParsed: ParsedExpr | undefined,
@@ -133,7 +145,7 @@ export function resolveStaticLoopSource(
133
145
  if (arrayParsed.kind === 'identifier') {
134
146
  if (opts?.isNameShadowed?.(arrayParsed.name)) return null
135
147
  const local = localConstants?.find(c => c.name === arrayParsed.name)
136
- if (!local || local.isModule || !local.parsed) return null
148
+ if (!local?.parsed || local.mutatedAfterDeclaration) return null
137
149
  target = local.parsed
138
150
  }
139
151
  const resolved = evaluateStaticLiteral(target)
package/src/types.ts CHANGED
@@ -2253,6 +2253,13 @@ export interface PropUsage {
2253
2253
  export interface ClientAnalysis {
2254
2254
  needsInit: boolean
2255
2255
  usedProps: string[]
2256
+ /**
2257
+ * The subset of `usedProps` whose declared type is a function — the client
2258
+ * code CALLS these, so they cannot arrive as JSON. Keyed by caller-facing
2259
+ * name (the `bf-p` blob key), valued by the declared type's printable
2260
+ * text. See `computeLiveOnlyProps` (`ir-to-client-js/index.ts`).
2261
+ */
2262
+ liveOnlyProps: Record<string, string>
2256
2263
  }
2257
2264
 
2258
2265
  // =============================================================================