@barefootjs/jsx 0.35.4 → 0.35.6

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 (113) 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 +5306 -4949
  7. package/dist/ir-to-client-js/compute-inlinability.d.ts +8 -0
  8. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/compute-prop-usage.d.ts +6 -0
  10. package/dist/ir-to-client-js/compute-prop-usage.d.ts.map +1 -1
  11. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts +3 -2
  12. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  13. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts +12 -2
  14. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  15. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +40 -0
  16. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -0
  17. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +13 -0
  18. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts +45 -0
  20. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts.map +1 -0
  21. package/dist/ir-to-client-js/control-flow/plan/types.d.ts +2 -0
  22. package/dist/ir-to-client-js/control-flow/plan/types.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts +12 -0
  24. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow.d.ts +2 -1
  26. package/dist/ir-to-client-js/control-flow.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/emit-reactive.d.ts +7 -3
  28. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/imports.d.ts +2 -2
  31. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/index.d.ts +1 -0
  33. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/event-handlers.d.ts +9 -1
  35. package/dist/ir-to-client-js/phases/event-handlers.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts +5 -0
  37. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/phases/props-extraction.d.ts +15 -13
  39. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/phases.d.ts +12 -1
  41. package/dist/ir-to-client-js/phases.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +50 -0
  45. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +29 -0
  47. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -0
  48. package/dist/ir-to-client-js/utils.d.ts +21 -1
  49. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  50. package/dist/jsx-to-ir.d.ts.map +1 -1
  51. package/dist/prop-rewrite.d.ts.map +1 -1
  52. package/dist/props-binding.d.ts +112 -1
  53. package/dist/props-binding.d.ts.map +1 -1
  54. package/dist/ssr-defaults.d.ts.map +1 -1
  55. package/dist/static-literal.d.ts +20 -8
  56. package/dist/static-literal.d.ts.map +1 -1
  57. package/dist/types.d.ts +38 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/package.json +2 -2
  60. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +31 -35
  61. package/src/__tests__/aliased-destructured-prop-csr.test.ts +19 -7
  62. package/src/__tests__/body-destructured-prop-default-propsparams.test.ts +153 -0
  63. package/src/__tests__/body-destructured-props-live.test.ts +245 -0
  64. package/src/__tests__/client-js-generation.test.ts +11 -4
  65. package/src/__tests__/client-only-date-lowering.test.ts +5 -2
  66. package/src/__tests__/destructured-from-props-localconst-value.test.ts +17 -6
  67. package/src/__tests__/destructured-props-live.test.ts +167 -0
  68. package/src/__tests__/doc-examples.test.ts +2 -4
  69. package/src/__tests__/event-delegation-container-collision-2930.test.ts +197 -0
  70. package/src/__tests__/format-error.test.ts +5 -3
  71. package/src/__tests__/issue-2910-mutated-const-not-inlined.test.ts +118 -0
  72. package/src/__tests__/issue-2910-own-scope-id-emission.test.ts +64 -0
  73. package/src/__tests__/live-only-props.test.ts +160 -0
  74. package/src/__tests__/prop-references.test.ts +26 -17
  75. package/src/__tests__/props-destructuring.test.ts +6 -275
  76. package/src/__tests__/prune-unused-prop-extractions.test.ts +11 -5
  77. package/src/__tests__/signal-getter-not-called.test.ts +5 -0
  78. package/src/__tests__/ssr-defaults.test.ts +83 -0
  79. package/src/__tests__/staged-ir/02-shadow-guards.test.ts +12 -5
  80. package/src/__tests__/static-literal.test.ts +39 -4
  81. package/src/analyzer-context.ts +8 -7
  82. package/src/analyzer.ts +233 -106
  83. package/src/errors.ts +7 -8
  84. package/src/ir-to-client-js/compute-inlinability.ts +8 -1
  85. package/src/ir-to-client-js/compute-prop-usage.ts +19 -0
  86. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +5 -0
  87. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +27 -11
  88. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +55 -0
  89. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +13 -0
  90. package/src/ir-to-client-js/control-flow/plan/loop-delegation-index.ts +79 -0
  91. package/src/ir-to-client-js/control-flow/plan/types.ts +2 -0
  92. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +50 -10
  93. package/src/ir-to-client-js/control-flow.ts +68 -31
  94. package/src/ir-to-client-js/emit-reactive.ts +12 -8
  95. package/src/ir-to-client-js/emit-registration.ts +2 -2
  96. package/src/ir-to-client-js/generate-init.ts +22 -2
  97. package/src/ir-to-client-js/imports.ts +6 -0
  98. package/src/ir-to-client-js/index.ts +51 -3
  99. package/src/ir-to-client-js/phases/event-handlers.ts +10 -0
  100. package/src/ir-to-client-js/phases/props-event-handlers.ts +6 -0
  101. package/src/ir-to-client-js/phases/props-extraction.ts +29 -48
  102. package/src/ir-to-client-js/phases.ts +17 -3
  103. package/src/ir-to-client-js/plan/build-declaration-emit.ts +6 -5
  104. package/src/ir-to-client-js/prop-handling.ts +9 -0
  105. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +31 -10
  106. package/src/ir-to-client-js/rewrite-destructured-props.ts +210 -0
  107. package/src/ir-to-client-js/utils.ts +29 -1
  108. package/src/jsx-to-ir.ts +110 -48
  109. package/src/prop-rewrite.ts +11 -0
  110. package/src/props-binding.ts +171 -6
  111. package/src/ssr-defaults.ts +10 -5
  112. package/src/static-literal.ts +21 -9
  113. package/src/types.ts +38 -0
@@ -1,67 +1,48 @@
1
1
  /**
2
- * `props-extraction` phase — emit `const propName = _p.propName ?? <default>`
3
- * declarations at the top of the init body.
2
+ * `props-extraction` phase — emit the one surviving one-time prop
3
+ * extraction, `const children = _p.children [?? <default>]`.
4
4
  *
5
- * The default value depends on usage:
6
- * - prop has explicit default → use it (wrap arrow defaults
7
- * in parens for syntax safety)
8
- * - prop is consumed as a loop array → `?? []`
9
- * - prop has property/index access → `?? {}` (skipped when the
10
- * prop is a conditional guard
11
- * so falsy values stay falsy)
12
- * - otherwise → no default
5
+ * `children` must stay a ONE-TIME read: a prop's slot-children value is a
6
+ * getter that INSTANTIATES child components when read (see
7
+ * `prune-unused-prop-extractions.ts`), so reading it live at every
8
+ * `{children}` reference would re-mount the children each time. Every
9
+ * other destructured prop is rewritten to a live read instead, by
10
+ * `rewriteDestructuredPropReads` (`generate-init.ts`).
13
11
  *
14
- * Skipped entirely when the component uses an opaque props object name
15
- * (`propsObjectName != null`) — in that case downstream code reads
16
- * `_p.X` directly via the late-stage rename.
12
+ * The line is composed from `propReadBase`/`propReadFallback` rather than
13
+ * `livePropReadExpr` so it stays unparenthesized — that exact
14
+ * `const X = _p.X [?? d]` shape is what `pruneUnusedPropExtractions`'s AST
15
+ * matcher recognizes when the init body never reads `children`.
16
+ *
17
+ * Skipped entirely for an opaque props object (`propsObjectName != null`):
18
+ * downstream code there reads `_p.X` directly via the late-stage rename.
17
19
  */
18
20
 
19
21
  import type { PropUsage } from '../../types.ts'
20
- import { propHasPropertyAccess } from '../compute-prop-usage.ts'
22
+ import { computePropsUsedAsConditions } from '../compute-prop-usage.ts'
23
+ import { propReadBase, propReadFallback } from '../../props-binding.ts'
21
24
  import type { ClientJsContext } from '../types.ts'
22
25
  import { PROPS_PARAM } from '../utils.ts'
23
26
 
27
+ const CHILDREN = 'children'
28
+
24
29
  export function emitPropsExtraction(
25
30
  lines: string[],
26
31
  ctx: ClientJsContext,
27
32
  neededProps: Set<string>,
28
33
  propUsage: Map<string, PropUsage>,
29
34
  ): void {
30
- if (neededProps.size === 0 || ctx.propsObjectName) return
35
+ if (ctx.propsObjectName) return
36
+ if (!neededProps.has(CHILDREN)) return
31
37
 
32
- // Props that guard a conditional branch must remain falsy when undefined,
33
- // so `{}` (truthy) is the wrong default for them — track and exclude.
34
- const propsUsedAsConditions = new Set<string>()
35
- for (const cond of ctx.conditionalElements) {
36
- if (neededProps.has(cond.condition)) propsUsedAsConditions.add(cond.condition)
37
- }
38
- for (const cond of ctx.clientOnlyConditionals) {
39
- if (neededProps.has(cond.condition)) propsUsedAsConditions.add(cond.condition)
38
+ const prop = ctx.propsParams.find(p => p.name === CHILDREN)
39
+ if (!prop) {
40
+ lines.push(` const ${CHILDREN} = ${PROPS_PARAM}.${CHILDREN}`, '')
41
+ return
40
42
  }
41
43
 
42
- for (const propName of neededProps) {
43
- const prop = ctx.propsParams.find(p => p.name === propName)
44
- // `_p` is always keyed by the caller-facing name (#2524 CSR half); the
45
- // local binding on the left of `const` stays `propName`.
46
- const callerKey = prop?.sourceName ?? propName
47
- const usage = propUsage.get(propName)
48
- const defaultVal = prop?.defaultValue
49
- if (defaultVal) {
50
- // `props.onInput ?? () => {}` is a syntax error — `??` binds tighter
51
- // than the arrow head. Wrap arrow defaults in parens.
52
- const wrappedDefault = prop?.defaultContainsArrow ? `(${defaultVal})` : defaultVal
53
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? ${wrappedDefault}`)
54
- } else if (usage?.usedAsLoopArray) {
55
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? []`)
56
- } else if (propHasPropertyAccess(usage) && !propsUsedAsConditions.has(propName)) {
57
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? {}`)
58
- } else {
59
- // No synthesized default for a defaultless optional (`{ size }:
60
- // { size?: number }`): the JS binding is `undefined` when absent, and
61
- // a zero default would diverge from SSR (`size ?? 1` seeds 1
62
- // server-side; a `_p.size ?? 0` extraction would hydrate to 0).
63
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey}`)
64
- }
65
- }
66
- lines.push('')
44
+ const usedAsCondition = computePropsUsedAsConditions(ctx, neededProps).has(CHILDREN)
45
+ const fallback = propReadFallback(prop, propUsage.get(CHILDREN), usedAsCondition)
46
+ const read = propReadBase(prop) + (fallback === null ? '' : ` ?? ${fallback}`)
47
+ lines.push(` const ${CHILDREN} = ${read}`, '')
67
48
  }
@@ -17,6 +17,7 @@ import type { ComponentIR, PropUsage, ReferencesGraph } from '../types.ts'
17
17
  import type { ClientJsContext } from './types.ts'
18
18
  import type { LocalClassification } from './init-declarations.ts'
19
19
  import { collectConditionalSlotIds } from './phases/conditional-slot-ids.ts'
20
+ import { buildLoopDelegationIndex, type LoopDelegationIndex } from './control-flow/plan/loop-delegation-index.ts'
20
21
  import { emitEffectsAndOnMounts } from './phases/effects-and-on-mounts.ts'
21
22
  import { emitEventHandlers } from './phases/event-handlers.ts'
22
23
  import { emitInitStatements } from './phases/init-statements.ts'
@@ -51,6 +52,16 @@ export interface PhaseCtx {
51
52
  /** Slots that live inside a conditional branch (handled via `insert()`).
52
53
  * Cached so `event-handlers` and `ref-callbacks` don't recompute. */
53
54
  conditionalSlotIds: Set<string>
55
+ /**
56
+ * Which (container slot, DOM event) pairs a top-level `.map()` loop will
57
+ * delegate, and which loop is last among those sharing a pair (#2930).
58
+ * Computed once, ahead of both `event-handlers` (which must suppress a
59
+ * container's own listener for a delegated pair) and `loop-updates`
60
+ * (which folds that handler into the delegated listener instead) — those
61
+ * two phases run in that order, so this can't be computed by either one
62
+ * lazily on first use.
63
+ */
64
+ loopDelegationIndex: LoopDelegationIndex
54
65
  /** Local names that resolve to component-scope expressions and therefore
55
66
  * become `[]` / `undefined` when referenced from the CSR template (the
56
67
  * same set the registration emitter feeds `generateCsrTemplate`).
@@ -60,10 +71,13 @@ export interface PhaseCtx {
60
71
  }
61
72
 
62
73
  /** Build the read-only carrier that every phase consumes. */
63
- export function buildPhaseCtx(args: Omit<PhaseCtx, 'conditionalSlotIds'>): PhaseCtx {
74
+ export function buildPhaseCtx(
75
+ args: Omit<PhaseCtx, 'conditionalSlotIds' | 'loopDelegationIndex'>,
76
+ ): PhaseCtx {
64
77
  return {
65
78
  ...args,
66
79
  conditionalSlotIds: collectConditionalSlotIds(args.ctx),
80
+ loopDelegationIndex: buildLoopDelegationIndex(args.ctx.loopElements),
67
81
  }
68
82
  }
69
83
 
@@ -222,7 +236,7 @@ export const PHASES: readonly EmitPhase[] = [
222
236
  {
223
237
  id: 'event-handlers',
224
238
  dependsOn: ['rest-attr-applications'],
225
- run: (lines, p) => emitEventHandlers(lines, p.ctx, p.conditionalSlotIds),
239
+ run: (lines, p) => emitEventHandlers(lines, p.ctx, p.conditionalSlotIds, p.loopDelegationIndex),
226
240
  },
227
241
  {
228
242
  id: 'reactive-prop-bindings',
@@ -256,7 +270,7 @@ export const PHASES: readonly EmitPhase[] = [
256
270
  // contract is enforceable at registry-validation time.
257
271
  id: 'loop-updates',
258
272
  dependsOn: ['provider-and-child-inits'],
259
- run: (lines, p) => emitLoopUpdates(lines, p.ctx, p.unsafeLocalNames),
273
+ run: (lines, p) => emitLoopUpdates(lines, p.ctx, p.unsafeLocalNames, p.conditionalSlotIds, p.loopDelegationIndex),
260
274
  },
261
275
  {
262
276
  id: 'static-array-child-inits',
@@ -13,6 +13,7 @@ import type { Declaration } from '../declaration-sort.ts'
13
13
  import type { ClientJsContext } from '../types.ts'
14
14
  import type { ParamInfo, SignalInfo } from '../../types.ts'
15
15
  import { inferDefaultValue, PROPS_PARAM } from '../utils.ts'
16
+ import { livePropReadExpr } from '../../props-binding.ts'
16
17
  import { ENV_SIGNAL_CLIENT_FACTORY } from '../../adapters/env-signal.ts'
17
18
  import type {
18
19
  ControlledSignalEffectPlan,
@@ -182,11 +183,11 @@ function buildControlledSignalEffect(
182
183
  if (!signal.setter) return null // read-only — no sync needed
183
184
 
184
185
  const prop = lookups.propByName.get(controlled.propName)
185
- // `_p` is always keyed by the caller-facing name (#2524 CSR half).
186
- const callerKey = prop?.sourceName ?? controlled.propName
187
- const accessorExpr = prop?.defaultValue
188
- ? `(${PROPS_PARAM}.${callerKey} ?? ${prop.defaultValue})`
189
- : `${PROPS_PARAM}.${callerKey}`
186
+ // No `usage`/`usedAsCondition`: a controlled prop's sync effect reads it
187
+ // as a plain value, never as a loop array or a conditional guard.
188
+ const accessorExpr = prop
189
+ ? livePropReadExpr(prop, undefined, false)
190
+ : `${PROPS_PARAM}.${controlled.propName}`
190
191
 
191
192
  return { setter: signal.setter, accessorExpr }
192
193
  }
@@ -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
  }
@@ -36,6 +36,35 @@ import ts from 'typescript'
36
36
  import { collectValueReferencedNames } from '../value-references.ts'
37
37
  import { PROPS_PARAM } from './utils.ts'
38
38
 
39
+ /**
40
+ * Does `init` read `<objectName>.<key>` or `<objectName>.<key> ?? <fallback>`?
41
+ * The one recognizer for "a prop read initializer", shared by
42
+ * `propExtractionName` below (which additionally requires the bound name to
43
+ * equal `key`, and always reads off `_p`), `rewriteBodyAliasReads`
44
+ * (`rewrite-destructured-props.ts`, which does not require the name match —
45
+ * a renamed alias's bound name differs from `key` by definition, but also
46
+ * always reads off `_p`), and `resolveBodyPropAliases` (`props-binding.ts`,
47
+ * which reads off the SOURCE-level props object name, e.g. `props` —
48
+ * `objectName` defaults to `_p` for the first two, post-rename, callers).
49
+ */
50
+ export function parsePropReadInitializer(
51
+ init: ts.Expression,
52
+ objectName: string = PROPS_PARAM,
53
+ ): { key: string; fallback: ts.Expression | null } | null {
54
+ let core: ts.Expression = init
55
+ let fallback: ts.Expression | null = null
56
+ if (
57
+ ts.isBinaryExpression(core) &&
58
+ core.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken
59
+ ) {
60
+ fallback = core.right
61
+ core = core.left
62
+ }
63
+ if (!ts.isPropertyAccessExpression(core)) return null
64
+ if (!ts.isIdentifier(core.expression) || core.expression.text !== objectName) return null
65
+ return { key: core.name.text, fallback }
66
+ }
67
+
39
68
  /** Is `stmt` a single-declarator `const X = _p.X…` prop extraction whose
40
69
  * initializer is `_p.X` or `_p.X ?? <default>`? Returns the bound name, or
41
70
  * null when the statement is anything else. */
@@ -46,16 +75,8 @@ function propExtractionName(stmt: ts.Statement): string | null {
46
75
  const decl = decls[0]!
47
76
  if (!ts.isIdentifier(decl.name) || !decl.initializer) return null
48
77
 
49
- let core: ts.Expression = decl.initializer
50
- if (
51
- ts.isBinaryExpression(core) &&
52
- core.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken
53
- ) {
54
- core = core.left
55
- }
56
- if (!ts.isPropertyAccessExpression(core)) return null
57
- if (!ts.isIdentifier(core.expression) || core.expression.text !== PROPS_PARAM) return null
58
- if (core.name.text !== decl.name.text) return null
78
+ const parsed = parsePropReadInitializer(decl.initializer)
79
+ if (parsed === null || parsed.key !== decl.name.text) return null
59
80
  return decl.name.text
60
81
  }
61
82
 
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Live-read rewrite for destructured props.
3
+ *
4
+ * A destructured name can appear bare in a dozen raw-captured text shapes
5
+ * (effect bodies, memo computations, signal initials, handler bodies,
6
+ * `mapArray` row bodies, conditional thunks, …), so rewriting it per
7
+ * emitter would mean N places to keep in sync; the single door is the
8
+ * joined init body, same precedent as `rewritePropsObjectRef`
9
+ * (`rewrite-props-object.ts`) one step earlier in the same pipeline.
10
+ *
11
+ * Two shapes reach this door, dispatched on `ctx.propsObjectName`:
12
+ *
13
+ * - PARAMETER destructuring (`function Child({ value })`,
14
+ * `propsObjectName === null`) — `rewriteParamDestructuredReads`, Move
15
+ * B's original mechanism (#2932).
16
+ * - a BODY destructure or bare-member alias off the whole props object
17
+ * (`function Child(props) { const { value } = props; ... }`,
18
+ * `propsObjectName` set) — `rewriteBodyAliasReads` (#2934). Move B left
19
+ * this branch a no-op: `rewritePropsObjectRef` (the pass immediately
20
+ * before this one) already turns `props.value` into `_p.value`
21
+ * wherever the SOURCE wrote it as a member access, but a body
22
+ * destructure's downstream USES are bare identifiers (`value`, not
23
+ * `props.value`), which that rename never touches — they stayed
24
+ * captured at the local's ONE declaration-time read forever.
25
+ */
26
+
27
+ import ts from 'typescript'
28
+ import type { PropUsage } from '../types.ts'
29
+ import { computePropsUsedAsConditions } from './compute-prop-usage.ts'
30
+ import { boundPropLocalNames, livePropReadExpr, resolveBodyPropAliases, type LivePropReadInfo } from '../props-binding.ts'
31
+ import { parsePropReadInitializer } from './prune-unused-prop-extractions.ts'
32
+ import { rewriteScopedValueRefs } from '../prop-rewrite.ts'
33
+ import { identifierPattern } from '../identifier-pattern.ts'
34
+ import { PROPS_PARAM } from './utils.ts'
35
+ import type { ClientJsContext } from './types.ts'
36
+
37
+ export function rewriteDestructuredPropReads(
38
+ code: string,
39
+ ctx: ClientJsContext,
40
+ propUsage: ReadonlyMap<string, PropUsage>,
41
+ ): string {
42
+ return ctx.propsObjectName === null
43
+ ? rewriteParamDestructuredReads(code, ctx, propUsage)
44
+ : rewriteBodyAliasReads(code, ctx)
45
+ }
46
+
47
+ /**
48
+ * Rewrite every bare value-position read of a PARAMETER-destructured prop in
49
+ * `code` (the joined `init*` body, already past `rewritePropsObjectRef`) to a
50
+ * live `_p.<key>` read.
51
+ *
52
+ * The walk is `rewriteScopedValueRefs` (`prop-rewrite.ts`), which carries a
53
+ * binding-scope stack, so `items.map((title) => title.a)` and a
54
+ * handler-local `const title = 'local'` keep their own binding even when
55
+ * `title` is also a prop name.
56
+ *
57
+ * Excluding `children`: reading `_p.children` live re-invokes a getter that
58
+ * instantiates child components (see `emitPropsExtraction`) — `children`
59
+ * must stay a captured-once read, by design.
60
+ *
61
+ * A null result can only mean `code` did not parse — never that a
62
+ * substitution broke it, since the walk parses the pristine input and every
63
+ * substituted string is a well-formed expression spliced where the walk
64
+ * already proved an identifier sat. The one shape that trips it is a
65
+ * tracked pre-existing hole (`map-body-no-silent-divergence.test.ts`'s
66
+ * `KNOWN_HOLES`): a `.map()` preamble leaking raw JSX, which is already a
67
+ * browser `SyntaxError` with or without this rewrite. Warning and passing
68
+ * the code through keeps that a tracked silent hole instead of promoting it
69
+ * to a compiler crash — same precedent as `pruneUnusedPropExtractions`.
70
+ */
71
+ function rewriteParamDestructuredReads(
72
+ code: string,
73
+ ctx: ClientJsContext,
74
+ propUsage: ReadonlyMap<string, PropUsage>,
75
+ ): string {
76
+ const names = new Set(boundPropLocalNames(ctx))
77
+ names.delete('children')
78
+ if (names.size === 0) return code
79
+
80
+ const propsUsedAsConditions = computePropsUsedAsConditions(ctx, names)
81
+ const propByName = new Map<string, LivePropReadInfo>()
82
+ for (const p of ctx.propsParams) propByName.set(p.name, p)
83
+
84
+ const replacementFor = (name: string): string => {
85
+ // `names` comes from `ctx.propsParams`, so the fallback is unreachable —
86
+ // kept over a non-null assertion.
87
+ const prop = propByName.get(name)
88
+ if (!prop) return `${PROPS_PARAM}.${name}`
89
+ return livePropReadExpr(prop, propUsage.get(name), propsUsedAsConditions.has(name))
90
+ }
91
+
92
+ const result = rewriteScopedValueRefs(code, names, replacementFor, { allowStatements: true })
93
+ if (result === null) {
94
+ console.warn(
95
+ `[barefootjs] rewriteDestructuredPropReads: the generated init body for ` +
96
+ `component "${ctx.componentName}" did not parse as JS/TSX (most likely a ` +
97
+ `pre-existing raw-JSX leak — see this function's docstring); skipping the ` +
98
+ `live-prop-read rewrite for it.`,
99
+ )
100
+ return code
101
+ }
102
+ return result
103
+ }
104
+
105
+ /**
106
+ * Rewrite every bare value-position read of a BODY-destructured (or
107
+ * bare-member-alias) prop local in `code` to a live `_p.<key>` read, for a
108
+ * bare-props-form component (`function Foo(props: Props)`).
109
+ *
110
+ * `resolveBodyPropAliases` can't distinguish `const { value } = props` from
111
+ * `const value = props.value` (the analyzer's IR is identical for both —
112
+ * see its docstring), so this rewrite treats them identically too. That's
113
+ * the correct call, not a shortcut: BOTH are pure single-prop passthroughs
114
+ * with no computation of their own, so both should read live, matching
115
+ * `props.value` used directly (which already reads live via
116
+ * `rewritePropsObjectRef`).
117
+ *
118
+ * A body alias's declaration is a REAL statement in `code` (unlike a
119
+ * parameter-destructured name, which never had one) — `const value =
120
+ * _p.value;`, physically sitting in the init body. Left in place, it would
121
+ * shadow every reference the rewrite is trying to make live (the walk sees
122
+ * it as a `Block`-scope declaration and treats every use as already
123
+ * correctly bound, exactly as it should for a genuine local). So this pass
124
+ * locates and DELETES each qualifying declaration BEFORE walking, rather
125
+ * than relying on `pruneUnusedPropExtractions` (which runs after this pass
126
+ * and only prunes an EXACT `const X = _p.X` shape — never a renamed alias's
127
+ * `const v = _p.value`, since its bound name doesn't match the read key).
128
+ *
129
+ * Only a declaration whose initializer is *exactly* `_p.<key>` [`?? <d>`] is
130
+ * touched — matched via `parsePropReadInitializer`, the same recognizer
131
+ * `pruneUnusedPropExtractions` uses for its narrower same-name case. A local
132
+ * this pass can't re-locate in that exact shape is left alone entirely
133
+ * (conservative false-keep: it stays captured, i.e. today's behavior, never
134
+ * a half-rewrite).
135
+ *
136
+ * Excluding `key === 'children'`: same hazard as the parameter form above,
137
+ * keyed by the CALLER-FACING name (`const { children: kids } = props`
138
+ * aliases `kids -> children` and must stay captured-once too).
139
+ */
140
+ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
141
+ const aliases = resolveBodyPropAliases(ctx.localConstants, ctx.propsObjectName)
142
+ for (const [local, alias] of aliases) {
143
+ if (alias.key === 'children') aliases.delete(local)
144
+ }
145
+ if (aliases.size === 0) return code
146
+ // Quick exit when none of the candidate local names appear at all.
147
+ if (![...aliases.keys()].some((name) => identifierPattern(name).test(code))) return code
148
+
149
+ const sourceFile = ts.createSourceFile('init-body.ts', code, ts.ScriptTarget.Latest, /*setParentNodes*/ true, ts.ScriptKind.TS)
150
+
151
+ const spans: Array<readonly [number, number]> = []
152
+ const located = new Map<string, { key: string; defaultValue?: string; defaultContainsArrow?: boolean }>()
153
+ for (const stmt of sourceFile.statements) {
154
+ if (!ts.isFunctionDeclaration(stmt) || !stmt.name?.text.startsWith('init') || !stmt.body) continue
155
+ for (const inner of stmt.body.statements) {
156
+ if (!ts.isVariableStatement(inner)) continue
157
+ if ((inner.declarationList.flags & ts.NodeFlags.Const) === 0) continue
158
+ const decls = inner.declarationList.declarations
159
+ if (decls.length !== 1) continue
160
+ const decl = decls[0]!
161
+ if (!ts.isIdentifier(decl.name) || !decl.initializer) continue
162
+ const alias = aliases.get(decl.name.text)
163
+ if (!alias) continue
164
+ const parsedInit = parsePropReadInitializer(decl.initializer)
165
+ if (parsedInit === null || parsedInit.key !== alias.key) continue
166
+ if ((parsedInit.fallback !== null) !== alias.hasDefault) continue
167
+ located.set(decl.name.text, {
168
+ key: alias.key,
169
+ defaultValue: parsedInit.fallback?.getText(sourceFile),
170
+ defaultContainsArrow: alias.defaultContainsArrow,
171
+ })
172
+ spans.push([inner.getFullStart(), inner.getEnd()])
173
+ }
174
+ }
175
+ if (located.size === 0) return code
176
+
177
+ // Delete the located declarations first (back-to-front) so the walk below
178
+ // never sees them as a shadowing local binding.
179
+ let stripped = code
180
+ for (const [start, end] of [...spans].sort((a, b) => b[0] - a[0])) {
181
+ stripped = stripped.slice(0, start) + stripped.slice(end)
182
+ }
183
+
184
+ const names = new Set(located.keys())
185
+ const replacementFor = (name: string): string => {
186
+ // `names` comes from `located`, so the fallback is unreachable — kept
187
+ // over a non-null assertion.
188
+ const info = located.get(name)
189
+ if (!info) return `${PROPS_PARAM}.${name}`
190
+ const prop: LivePropReadInfo = {
191
+ name,
192
+ sourceName: info.key,
193
+ defaultValue: info.defaultValue,
194
+ defaultContainsArrow: info.defaultContainsArrow,
195
+ }
196
+ return livePropReadExpr(prop, undefined, false)
197
+ }
198
+
199
+ const result = rewriteScopedValueRefs(stripped, names, replacementFor, { allowStatements: true })
200
+ if (result === null) {
201
+ console.warn(
202
+ `[barefootjs] rewriteDestructuredPropReads: the generated init body for ` +
203
+ `component "${ctx.componentName}" did not parse as JS/TSX after removing its ` +
204
+ `body-destructured prop-alias declarations; skipping the live-prop-read ` +
205
+ `rewrite for it.`,
206
+ )
207
+ return code
208
+ }
209
+ return result
210
+ }
@@ -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'
@@ -264,6 +278,20 @@ export function toDomEventName(eventName: string): string {
264
278
  return jsxToDomEventMap[eventName] ?? eventName
265
279
  }
266
280
 
281
+ /**
282
+ * Non-bubbling events that require `addEventListener` with capture for
283
+ * delegation. Shared between the delegation stringifier and the own-handler
284
+ * collision check (#2930) so both agree on which events a container's own
285
+ * bubble-phase handler can never collide with in the first place — a
286
+ * container's own non-capturing `onFocus`, say, only fires when the
287
+ * container itself is the target, never for a descendant row.
288
+ */
289
+ export const NON_BUBBLING_EVENTS = new Set([
290
+ 'blur', 'focus', 'load', 'unload',
291
+ 'mouseenter', 'mouseleave',
292
+ 'pointerenter', 'pointerleave',
293
+ ])
294
+
267
295
  /**
268
296
  * Quote a prop name if it is not a valid JS identifier.
269
297
  * Returns the name as-is for valid identifiers (e.g., "checked"),