@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
@@ -352,6 +352,89 @@ describe('extractSsrDefaults', () => {
352
352
  expect(defaults?.text).toEqual({ propName: 'text', value: null })
353
353
  })
354
354
 
355
+ test('bare-props-form BODY-destructured default (#2943) seeds the evaluated default, not null', () => {
356
+ // Before #2943, `extractPropsFromTypeMembers` built `propsParams` from
357
+ // the TYPE annotation alone, with no notion of a body destructure's
358
+ // own default — this entry seeded `value: null` regardless, and every
359
+ // non-Hono template adapter's presence-guard classification omitted
360
+ // the attribute entirely instead of falling back to `'none'`. The
361
+ // analyzer now overlays the default directly onto `propsParams`
362
+ // (`collectConstant`), so this is the SAME code path as the
363
+ // parameter-destructured "destructured prop defaults" test above —
364
+ // just reached through a body destructure instead.
365
+ const metadata = metadataFor(`
366
+ function Foo(props: { label?: string }) {
367
+ const { label = 'none' } = props
368
+ return <div data-label={label} />
369
+ }
370
+ `)
371
+ const defaults = extractSsrDefaults(metadata)
372
+ expect(defaults?.label).toEqual({ propName: 'label', value: 'none' })
373
+ })
374
+
375
+ test('bare-props-form BODY-destructured RENAMED default (#2943): two entries, each correctly classified', () => {
376
+ // `const { label: text = 'none' } = props` — `label` remains a real,
377
+ // separately-classified binding (no default of its own: a bare
378
+ // `props.label` read elsewhere in the same component still needs its
379
+ // own presence guard / stash entry), and `text` gets its OWN entry
380
+ // with `propName: 'label'` (the caller-facing key) and the evaluated
381
+ // default. `deriveStashFromDefaults` then seeds `text` from the
382
+ // caller's `label` when supplied, else `'none'` — never from `text`
383
+ // itself (`props` has no `text` key at all).
384
+ const metadata = metadataFor(`
385
+ function Foo(props: { label?: string }) {
386
+ const { label: text = 'none' } = props
387
+ return <div data-label={text} />
388
+ }
389
+ `)
390
+ const defaults = extractSsrDefaults(metadata)
391
+ expect(defaults?.label).toEqual({ propName: 'label', value: null })
392
+ expect(defaults?.text).toEqual({ propName: 'label', value: 'none' })
393
+
394
+ expect(deriveStashFromDefaults(defaults!, { label: 'named' })).toMatchObject({ text: 'named' })
395
+ expect(deriveStashFromDefaults(defaults!, {})).toMatchObject({ text: 'none' })
396
+ })
397
+
398
+ test('bare-props-form body-destructure rename (#2788) seeds the SSR stash under the LOCAL name', () => {
399
+ // `function Foo(props: Props) { const { children: kids } = props }` —
400
+ // propsParams here comes from the TYPE annotation and has no notion of
401
+ // the body-level rename, so the template-stash reads a LOCAL `kids`
402
+ // that pass-1 seeding would otherwise never populate. The safety-net
403
+ // loop in `extractSsrDefaults` (backed by `resolveBodyDestructuredPropAliases`)
404
+ // exists specifically to also seed the entry under `kids`.
405
+ const metadata = metadataFor(`
406
+ function Foo(props: { children?: string }) {
407
+ const { children: kids } = props
408
+ return <span>{kids}</span>
409
+ }
410
+ `)
411
+
412
+ const defaults = extractSsrDefaults(metadata)
413
+ expect(defaults?.children).toEqual({ propName: 'children', value: null })
414
+ expect(defaults?.kids).toEqual(defaults?.children)
415
+ })
416
+
417
+ // Pullfrog review (PR #2941): `resolveBodyDestructuredPropAliases` is now
418
+ // a filtered view over `resolveBodyPropAliases`, which excludes `let`
419
+ // bindings and mutated locals — a restriction that's correct for the
420
+ // LIVE client-JS rewrite (`rewriteBodyAliasReads`) but has no bearing on
421
+ // this SSR-stash safety net, which only needs the declaration-time
422
+ // local↔caller-key mapping. Without `requireLiveRewriteSafe: false`
423
+ // threaded through, a `let`-declared rename would silently lose its
424
+ // stash entry here — a reintroduction of #2788 for that one shape.
425
+ test('bare-props-form body-destructure rename via `let` (#2788 regression guard) still seeds the SSR stash', () => {
426
+ const metadata = metadataFor(`
427
+ function Foo(props: { children?: string }) {
428
+ let { children: kids } = props
429
+ return <span>{kids}</span>
430
+ }
431
+ `)
432
+
433
+ const defaults = extractSsrDefaults(metadata)
434
+ expect(defaults?.children).toEqual({ propName: 'children', value: null })
435
+ expect(defaults?.kids).toEqual(defaults?.children)
436
+ })
437
+
355
438
  test('memo derived from a signal evaluates through the chain', () => {
356
439
  const metadata = metadataFor(`
357
440
  'use client'
@@ -37,9 +37,16 @@ describe('Shadow guards: bare names that shadow props are NOT rewritten to _p.X'
37
37
  expect(initBody).not.toMatch(/_p\.count\(\)/)
38
38
  })
39
39
 
40
- test('earlier local const with default shadowing prop', () => {
41
- // `label` is a derived local. Even though props has a `label` field,
42
- // the bare reference inside subsequent locals resolves to the local.
40
+ // #2934: `label` here is a PURE alias of the `label` prop (the analyzer's
41
+ // IR can't distinguish `const label = props.label ?? 'fallback'` from a
42
+ // destructure default), not a genuinely distinct local shadowing an
43
+ // unrelated prop of the same name — so it is NOT a shadow-guard case
44
+ // after all. `resolveBodyPropAliases` now recognizes it, deletes its own
45
+ // extraction, and rewrites every reference (including from `upper`'s own
46
+ // initializer) to a live `_p.label` read, same as the parameter-
47
+ // destructured form. `upper` itself stays an ordinary once-evaluated
48
+ // local — `.toUpperCase()` is a real computation, not a passthrough.
49
+ test('a plain member-access prop alias is rewritten live, including from a dependent local', () => {
43
50
  const { initBody, errors } = compile(`
44
51
  'use client'
45
52
 
@@ -53,8 +60,8 @@ describe('Shadow guards: bare names that shadow props are NOT rewritten to _p.X'
53
60
  `)
54
61
 
55
62
  expect(errors).toEqual([])
56
- expect(initBody).toMatch(/upper\s*=\s*label\.toUpperCase\(\)/)
57
- expect(initBody).not.toMatch(/_p\.label\.toUpperCase/)
63
+ expect(initBody).not.toMatch(/const\s+label\s*=/)
64
+ expect(initBody).toMatch(/upper\s*=\s*\(_p\.label\s*\?\?\s*'fallback'\)\.toUpperCase\(\)/)
58
65
  })
59
66
 
60
67
  test('nested arrow param shadowing prop name', () => {
@@ -3,9 +3,10 @@ import { parseExpression } from '../expression-parser'
3
3
  import { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from '../static-literal'
4
4
  import type { ConstantInfo } from '../types'
5
5
 
6
- // #2208: a function-scope local const whose initializer is fully known at
7
- // compile time (no prop/signal/function-call dependency) should bind as a
8
- // loop source the same way a module-scope const already does.
6
+ // #2208: a local const whose initializer is fully known at compile time (no
7
+ // prop/signal/function-call dependency) should bind as a loop source the
8
+ // same way an inline array literal does — module-scope and function-scope
9
+ // alike (#2946).
9
10
  describe('evaluateStaticLiteral (#2208)', () => {
10
11
  test('scalars', () => {
11
12
  expect(evaluateStaticLiteral(parseExpression("'Alpha'"))).toEqual({ value: 'Alpha' })
@@ -97,11 +98,45 @@ describe('resolveStaticLoopSource (#2208)', () => {
97
98
  expect(resolveStaticLoopSource(parseExpression('items'), locals)).toEqual([{ label: 'Alpha' }])
98
99
  })
99
100
 
100
- test('a MODULE-scope const is excluded (handled by the existing seeding path instead)', () => {
101
+ test('a MODULE-scope const with a static initializer resolves exactly like a function-scope one (#2946)', () => {
101
102
  const locals = [constant({ name: 'items', parsed: parseExpression("[{ label: 'Alpha' }]"), isModule: true })]
103
+ expect(resolveStaticLoopSource(parseExpression('items'), locals)).toEqual([{ label: 'Alpha' }])
104
+ })
105
+
106
+ test('a MODULE-scope const whose initializer is runtime-computed still refuses (#2946)', () => {
107
+ const locals = [constant({ name: 'items', parsed: parseExpression('buildItems()'), isModule: true })]
102
108
  expect(resolveStaticLoopSource(parseExpression('items'), locals)).toBeNull()
103
109
  })
104
110
 
111
+ test('a MODULE-scope const shadowed by an enclosing loop param is excluded via isNameShadowed (#2946)', () => {
112
+ const locals = [constant({ name: 'items', parsed: parseExpression("[{ label: 'Alpha' }]"), isModule: true })]
113
+ const result = resolveStaticLoopSource(parseExpression('items'), locals, {
114
+ isNameShadowed: name => name === 'items',
115
+ })
116
+ expect(result).toBeNull()
117
+ })
118
+
119
+ test('a const mutated after its declaration (#2910) refuses regardless of scope', () => {
120
+ const moduleLocals = [
121
+ constant({
122
+ name: 'items',
123
+ parsed: parseExpression("[{ label: 'Alpha' }]"),
124
+ isModule: true,
125
+ mutatedAfterDeclaration: true,
126
+ }),
127
+ ]
128
+ expect(resolveStaticLoopSource(parseExpression('items'), moduleLocals)).toBeNull()
129
+
130
+ const functionLocals = [
131
+ constant({
132
+ name: 'items',
133
+ parsed: parseExpression("[{ label: 'Alpha' }]"),
134
+ mutatedAfterDeclaration: true,
135
+ }),
136
+ ]
137
+ expect(resolveStaticLoopSource(parseExpression('items'), functionLocals)).toBeNull()
138
+ })
139
+
105
140
  test('a runtime-computed local const (#2069) still refuses', () => {
106
141
  const locals = [constant({ name: 'entries', parsed: parseExpression('Object.entries(props.tags)') })]
107
142
  expect(resolveStaticLoopSource(parseExpression('entries'), locals)).toBeNull()
@@ -29,12 +29,13 @@ import type { CallbackBodyAcceptor } from './adapters/interface.ts'
29
29
  import { nodeContainsJsx } from './reactivity-checker.ts'
30
30
 
31
31
  /**
32
- * Deferred info for BF043 (props destructuring warning).
33
- * Recorded during extractProps(), emitted only for stateful components in validateContext().
32
+ * The props destructuring pattern's own source location. Carries no
33
+ * diagnostic of its own — it is the more precise location other
34
+ * props-parameter diagnostics point at instead of the component root (see
35
+ * `compiler.ts`'s `checkRichTypePropSerialization`).
34
36
  */
35
37
  export interface PropsDestructuringInfo {
36
38
  loc: SourceLocation
37
- hasIgnoreDirective: boolean
38
39
  }
39
40
 
40
41
  /**
@@ -182,7 +183,7 @@ export interface AnalyzerContext {
182
183
  restPropsName: string | null
183
184
  /** Keys that can be statically expanded from rest props (closed type) */
184
185
  restPropsExpandedKeys: string[]
185
- /** Deferred BF043 info; emitted only for stateful components in validateContext() */
186
+ /** Set when the props parameter is a destructuring pattern — see `PropsDestructuringInfo`. */
186
187
  propsDestructuring: PropsDestructuringInfo | null
187
188
 
188
189
  // JSX return — widened to any `ts.Expression` so the Phase 1 dispatcher
@@ -322,9 +323,9 @@ export function createAnalyzerContext(
322
323
  // to compiles with no `error`-severity diagnostic: a compile that
323
324
  // already refused loudly may take degraded fallback paths whose
324
325
  // artifacts are gated by the error — the invariant this trips on is
325
- // the SILENT leak. A `warning` (e.g. BF043 props-destructuring) does
326
- // not gate anything, so it must not silently disarm this assertion too
327
- // (#2867) — only `error` severity does.
326
+ // the SILENT leak. A `warning`-severity diagnostic does not gate
327
+ // anything, so it must not silently disarm this assertion too (#2867)
328
+ // — only `error` severity does.
328
329
  if (
329
330
  process.env.BF_ASSERT_NO_JSX_IN_GETJS === '1' &&
330
331
  !this.errors.some((e) => e.severity === 'error') &&
package/src/analyzer.ts CHANGED
@@ -11,7 +11,7 @@ import type { ImportSpecifier, TypeInfo, ParamInfo, ReactiveFactoryInfo, Decline
11
11
  import { parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr } from './expression-parser.ts'
12
12
  import type { CallbackBodyAcceptor } from './adapters/interface.ts'
13
13
  import { rewriteBarePropRefs } from './prop-rewrite.ts'
14
- import { buildPropAliasMap } from './props-binding.ts'
14
+ import { buildPropAliasMap, coalesceDefaultText } from './props-binding.ts'
15
15
  import { incrementCounter } from './instrumentation.ts'
16
16
  import {
17
17
  type AnalyzerContext,
@@ -25,7 +25,7 @@ import {
25
25
  isArrowComponentFunction,
26
26
  collectReactiveGetterNames,
27
27
  } from './analyzer-context.ts'
28
- import { createError, createWarning, ErrorCodes, type ErrorCode } from './errors.ts'
28
+ import { createError, ErrorCodes, type ErrorCode } from './errors.ts'
29
29
  import { baseTypeName } from './rich-type-evidence.ts'
30
30
  import { CATALOGUED_RICH_TYPE_NAMES } from './date-lowering.ts'
31
31
  import path from 'node:path'
@@ -3130,6 +3130,30 @@ function getSystemConstructKind(node: ts.Node): 'createContext' | 'weakMap' | un
3130
3130
  return undefined
3131
3131
  }
3132
3132
 
3133
+ /**
3134
+ * The default-value-shaped fields a binding element's own `initializer`
3135
+ * contributes to a `ParamInfo` — `defaultValue`'s source text, `parsed`'s
3136
+ * structured mirror (from the initializer's OWN AST node, no re-parse),
3137
+ * and `defaultContainsArrow`. Shared by the parameter-destructured path
3138
+ * (`extractProps`'s Pattern 1, below) and the BODY-destructure-from-props
3139
+ * path (`collectConstant`'s object-binding-pattern branch, #2943) so "what
3140
+ * does this default look like structurally" has one implementation, not
3141
+ * two independently-drifting ones.
3142
+ */
3143
+ function bindingElementDefaultFields(
3144
+ initializer: ts.Expression | undefined,
3145
+ ctx: AnalyzerContext,
3146
+ ): Pick<ParamInfo, 'defaultValue' | 'parsed' | 'defaultContainsArrow'> {
3147
+ const defaultValue = initializer ? ctx.getJS(initializer) : undefined
3148
+ const defaultContainsArrow = initializer ? nodeContainsArrow(initializer) : false
3149
+ const parsedDefault = initializer ? tsNodeToParsedExpr(initializer) : undefined
3150
+ return {
3151
+ defaultValue,
3152
+ ...(parsedDefault && parsedDefault.kind !== 'unsupported' && { parsed: parsedDefault }),
3153
+ defaultContainsArrow: defaultContainsArrow || undefined,
3154
+ }
3155
+ }
3156
+
3133
3157
  function collectConstant(
3134
3158
  node: ts.VariableDeclaration,
3135
3159
  ctx: AnalyzerContext,
@@ -3157,10 +3181,18 @@ function collectConstant(
3157
3181
  if (!ts.isBindingElement(el) || !ts.isIdentifier(el.name) || el.dotDotDotToken) continue
3158
3182
  const localName = el.name.text
3159
3183
  const sourceKey = el.propertyName && ts.isIdentifier(el.propertyName) ? el.propertyName.text : localName
3160
- const defaultValueExpr = el.initializer ? ctx.getJS(el.initializer) : undefined
3184
+ // Shared with the #2943 `ParamInfo` overlay below so "what does this
3185
+ // default look like" (source text, `defaultContainsArrow`) has one
3186
+ // computation, not two independently-drifting ones.
3187
+ const defaultFields = el.initializer ? bindingElementDefaultFields(el.initializer, ctx) : undefined
3161
3188
  const baseValue = `${propsName}.${sourceKey}`
3162
- const value = defaultValueExpr ? `${baseValue} ?? ${defaultValueExpr}` : baseValue
3163
- const containsArrow = el.initializer ? nodeContainsArrow(el.initializer) : false
3189
+ // Parenthesize an arrow/function-expression default (#2940) — `??`
3190
+ // binds tighter than an arrow head, so a bare `props.fmt ?? (v) =>
3191
+ // ...` is a SyntaxError in the emitted JS. Same rule
3192
+ // `propReadFallback` already applies to every other live prop read.
3193
+ const value = defaultFields?.defaultValue !== undefined
3194
+ ? `${baseValue} ?? ${coalesceDefaultText(defaultFields.defaultValue, defaultFields.defaultContainsArrow)}`
3195
+ : baseValue
3164
3196
  const freeIdentifiers = el.initializer ? extractFreeIdentifiersFromNode(el.initializer) : new Set([propsName])
3165
3197
  // Structured parse of `value`, same as the plain-identifier branch
3166
3198
  // below (#2724 review finding): without this, a RENAMED destructure
@@ -3186,11 +3218,59 @@ function collectConstant(
3186
3218
  type: null,
3187
3219
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
3188
3220
  freeIdentifiers,
3189
- containsArrow: containsArrow || undefined,
3221
+ containsArrow: defaultFields?.defaultContainsArrow,
3190
3222
  // Body-level destructure-from-props is collected only when
3191
3223
  // _isModule === false; binding lives in init scope.
3192
3224
  origin: { phase: 'hydrate', scope: 'init', effect: 'pure' },
3193
3225
  })
3226
+
3227
+ // #2943: a BODY destructure's default (`const { label = 'none' } =
3228
+ // props`) has no other way to reach `ParamInfo.defaultValue` —
3229
+ // `extractPropsFromTypeMembers` builds `propsParams` purely from the
3230
+ // TYPE annotation, which has no notion of a body-level default. Every
3231
+ // downstream consumer that reads `ParamInfo.defaultValue`/`.optional`
3232
+ // (each adapter's "does this attribute need a presence guard"
3233
+ // classification, `extractSsrDefaults`'s SSR-stash seed, the
3234
+ // CSR-fresh-mount `template:` lambda) needs the default visible here,
3235
+ // on the SAME shared `ParamInfo` the parameter-destructured form
3236
+ // already populates via `bindingElementDefaultFields` above — not on
3237
+ // a second, parallel structure only the CSR lambda used to consult.
3238
+ //
3239
+ // A `let` binding or one `markMutatedConstants` later flags as
3240
+ // mutated is still a perfectly valid default AT its declaration —
3241
+ // this is a static, compile-time fact about the source, not a
3242
+ // liveness question, so (unlike `resolveBodyPropAliases`'s
3243
+ // `requireLiveRewriteSafe` gate) nothing here excludes them.
3244
+ if (el.initializer && defaultFields) {
3245
+ const existing = ctx.propsParams.find(p => !p.isRest && p.sourceName === undefined && p.name === sourceKey)
3246
+ if (localName === sourceKey) {
3247
+ // Unrenamed: overlay onto the type-member entry `sourceKey`
3248
+ // already has (or synthesize one for an untyped `props` param,
3249
+ // matching the parameter-destructured form's own `unknown`
3250
+ // fallback for an unannotated `{ x = 1 }`). Never clobber a
3251
+ // default some earlier binding element already established.
3252
+ if (existing) {
3253
+ if (existing.defaultValue === undefined) Object.assign(existing, { optional: true, ...defaultFields })
3254
+ } else {
3255
+ ctx.propsParams.push({ name: localName, type: { kind: 'unknown', raw: 'unknown' }, optional: true, ...defaultFields })
3256
+ }
3257
+ } else if (!ctx.propsParams.some(p => p.name === localName)) {
3258
+ // Renamed (`const { label: text = 'none' } = props`): ADD a
3259
+ // second entry rather than replacing `sourceKey`'s — a bare
3260
+ // `props.label` read elsewhere in the same component is still a
3261
+ // real, separately-classified binding (no default, needs its own
3262
+ // presence guard / stash entry), and `text` needs `sourceName` so
3263
+ // every `sourceName ?? name` consumer resolves the caller-facing
3264
+ // key correctly.
3265
+ ctx.propsParams.push({
3266
+ name: localName,
3267
+ type: existing?.type ?? { kind: 'unknown', raw: 'unknown' },
3268
+ optional: true,
3269
+ sourceName: sourceKey,
3270
+ ...defaultFields,
3271
+ })
3272
+ }
3273
+ }
3194
3274
  }
3195
3275
  return
3196
3276
  }
@@ -3431,57 +3511,6 @@ function collectConstant(
3431
3511
  })
3432
3512
  }
3433
3513
 
3434
- // =============================================================================
3435
- // Ignore Directive Detection
3436
- // =============================================================================
3437
-
3438
- /**
3439
- * Check if a node has an ignore directive comment for the specified rule.
3440
- * Supports: // @bf-ignore rule-id
3441
- *
3442
- * For arrow function components, also checks the parent VariableStatement.
3443
- */
3444
- function hasIgnoreDirective(
3445
- node: ts.Node,
3446
- sourceFile: ts.SourceFile,
3447
- ruleId: string
3448
- ): boolean {
3449
- const checkComments = (targetNode: ts.Node): boolean => {
3450
- const fullStart = targetNode.getFullStart()
3451
- const leadingComments = ts.getLeadingCommentRanges(
3452
- sourceFile.getFullText(),
3453
- fullStart
3454
- )
3455
- if (!leadingComments) return false
3456
-
3457
- for (const range of leadingComments) {
3458
- const text = sourceFile.getFullText().slice(range.pos, range.end)
3459
- if (text.includes(`@bf-ignore ${ruleId}`)) {
3460
- return true
3461
- }
3462
- }
3463
- return false
3464
- }
3465
-
3466
- // Check the node itself
3467
- if (checkComments(node)) return true
3468
-
3469
- // For arrow functions, check the parent VariableStatement
3470
- // AST structure: VariableStatement > VariableDeclarationList > VariableDeclaration > ArrowFunction
3471
- if (ts.isArrowFunction(node)) {
3472
- let current: ts.Node | undefined = node.parent
3473
- while (current) {
3474
- if (ts.isVariableStatement(current)) {
3475
- if (checkComments(current)) return true
3476
- break
3477
- }
3478
- current = current.parent
3479
- }
3480
- }
3481
-
3482
- return false
3483
- }
3484
-
3485
3514
  // =============================================================================
3486
3515
  // Props Extraction
3487
3516
  // =============================================================================
@@ -3489,13 +3518,7 @@ function hasIgnoreDirective(
3489
3518
  function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): void {
3490
3519
  // Pattern 1: Destructured props - { prop1, prop2 }
3491
3520
  if (ts.isObjectBindingPattern(param.name)) {
3492
- // Record destructuring info for deferred BF043 emission (stateful components only)
3493
- const componentNode = ctx.componentNode
3494
- const ignored = !!(componentNode && hasIgnoreDirective(componentNode, ctx.sourceFile, 'props-destructuring'))
3495
- ctx.propsDestructuring = {
3496
- loc: getSourceLocation(param, ctx.sourceFile, ctx.filePath),
3497
- hasIgnoreDirective: ignored,
3498
- }
3521
+ ctx.propsDestructuring = { loc: getSourceLocation(param, ctx.sourceFile, ctx.filePath) }
3499
3522
 
3500
3523
  // Resolve each destructured binding's declared type from the param's type
3501
3524
  // annotation, so `{ value }: Props` keeps the same per-prop TypeInfo as the
@@ -3506,7 +3529,6 @@ function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): voi
3506
3529
  for (const element of param.name.elements) {
3507
3530
  if (ts.isBindingElement(element) && ts.isIdentifier(element.name)) {
3508
3531
  const localName = element.name.text
3509
- const defaultValue = element.initializer ? ctx.getJS(element.initializer) : undefined
3510
3532
 
3511
3533
  // Handle rest props: { ...props }
3512
3534
  if (element.dotDotDotToken) {
@@ -3523,22 +3545,13 @@ function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): voi
3523
3545
  const member = memberTypes?.get(sourcePropName)
3524
3546
  const resolvedType: TypeInfo = member?.type ?? { kind: 'unknown', raw: 'unknown' }
3525
3547
 
3526
- const defaultContainsArrow = element.initializer ? nodeContainsArrow(element.initializer) : false
3527
- // Structured mirror of `defaultValue`, from the binding element's OWN
3528
- // `initializer` node — `tsNodeToParsedExpr` converts the already-parsed
3529
- // AST directly, no re-parse of the `defaultValue` text (same convention
3530
- // as `SignalInfo.parsed`). An unsupported shape leaves `parsed` unset;
3531
- // consumers fall back to `defaultValue` text.
3532
- const parsedDefault = element.initializer ? tsNodeToParsedExpr(element.initializer) : undefined
3533
3548
  ctx.propsParams.push({
3534
3549
  name: localName,
3535
3550
  type: resolvedType,
3536
3551
  // The type's `?` and a destructure default (`{ x = 1 }`) both mean
3537
3552
  // the caller may omit the prop.
3538
3553
  optional: !!member?.optional || !!element.initializer,
3539
- defaultValue,
3540
- ...(parsedDefault && parsedDefault.kind !== 'unsupported' && { parsed: parsedDefault }),
3541
- defaultContainsArrow: defaultContainsArrow || undefined,
3554
+ ...bindingElementDefaultFields(element.initializer, ctx),
3542
3555
  // Only aliased bindings carry the source key — see ParamInfo.sourceName.
3543
3556
  ...(sourcePropName !== localName && { sourceName: sourcePropName }),
3544
3557
  })
@@ -3965,20 +3978,6 @@ function extractDependencies(code: string, ctx: AnalyzerContext): string[] {
3965
3978
  // =============================================================================
3966
3979
 
3967
3980
  function validateContext(ctx: AnalyzerContext): void {
3968
- // BF043: Emit props destructuring warning only for stateful components.
3969
- // Stateless components can safely destructure props since values are static.
3970
- const isStateful = ctx.signals.length > 0 || ctx.memos.length > 0 ||
3971
- ctx.effects.length > 0 || ctx.onMounts.length > 0
3972
- if (ctx.propsDestructuring && isStateful && !ctx.propsDestructuring.hasIgnoreDirective) {
3973
- ctx.errors.push(
3974
- createWarning(ErrorCodes.PROPS_DESTRUCTURING, ctx.propsDestructuring.loc, {
3975
- suggestion: {
3976
- message: 'Use props object directly: function Component(props: Props) { ... props.checked ... }',
3977
- },
3978
- })
3979
- )
3980
- }
3981
-
3982
3981
  // Check for 'use client' directive if any browser-only API is used.
3983
3982
  // Browser-only APIs include signals AND context/portal runtime hooks:
3984
3983
  // their implementations live in `@barefootjs/client/runtime` and require
package/src/errors.ts CHANGED
@@ -51,8 +51,9 @@ export const ErrorCodes = {
51
51
  // to resolve the identifier at return position too.
52
52
  RETURN_VALUE_NOT_JSX: 'BF027',
53
53
 
54
- // Component errors (BF043-BF049)
55
- PROPS_DESTRUCTURING: 'BF043',
54
+ // Component errors (BF043-BF049). BF043 is retired (it warned that props
55
+ // destructuring broke reactivity, which it no longer does) and is the next
56
+ // free slot.
56
57
  SIGNAL_GETTER_NOT_CALLED: 'BF044',
57
58
  JSX_IN_LOCAL_FUNCTION: 'BF045',
58
59
  COMPONENT_REQUIRED_PROP_MISSING: 'BF046',
@@ -181,8 +182,6 @@ const errorMessages: Record<ErrorCode, string> = {
181
182
  [ErrorCodes.RETURN_VALUE_NOT_JSX]:
182
183
  "Component's return value is not recognized as JSX — return the JSX expression directly instead of binding it to a local variable first.",
183
184
 
184
- [ErrorCodes.PROPS_DESTRUCTURING]:
185
- 'Props destructuring in function parameters breaks reactivity. Use props object directly.',
186
185
  [ErrorCodes.SIGNAL_GETTER_NOT_CALLED]:
187
186
  'Signal/memo getter passed without calling it. Use getter() to read the value.',
188
187
  [ErrorCodes.JSX_IN_LOCAL_FUNCTION]:
@@ -382,10 +381,10 @@ export function formatError(
382
381
  options?: { projectDir?: string },
383
382
  ): string {
384
383
  // Lowercase severity matches the prose convention in
385
- // `docs/core/advanced/error-codes.md` (`error[BF001]:`,
386
- // `warning[BF043]:`) — that doc IS the rendering contract referenced
387
- // by `bf guide advanced/error-codes`, so keep the wire format aligned
388
- // with the reference rather than the function's old uppercase shape.
384
+ // `docs/core/advanced/error-codes.md` (`error[BF001]:`) — that doc IS the
385
+ // rendering contract referenced by `bf guide advanced/error-codes`, so
386
+ // keep the wire format aligned with the reference rather than the
387
+ // function's old uppercase shape.
389
388
  const severityLabel = error.severity
390
389
  const lines: string[] = []
391
390
 
@@ -67,3 +67,22 @@ export function propHasPropertyAccess(u: PropUsage | undefined): boolean {
67
67
  if (!u) return false
68
68
  return u.accessKinds.has('property') || u.accessKinds.has('index')
69
69
  }
70
+
71
+ /**
72
+ * Which of `propNames` guard a conditional branch. A prop in this set must
73
+ * NOT get a `{}` fallback even when it has property access — `{}` is truthy,
74
+ * so the branch would always render when the caller omits the prop.
75
+ */
76
+ export function computePropsUsedAsConditions(
77
+ ctx: Pick<ClientJsContext, 'conditionalElements' | 'clientOnlyConditionals'>,
78
+ propNames: ReadonlySet<string>,
79
+ ): Set<string> {
80
+ const result = new Set<string>()
81
+ for (const cond of ctx.conditionalElements) {
82
+ if (propNames.has(cond.condition)) result.add(cond.condition)
83
+ }
84
+ for (const cond of ctx.clientOnlyConditionals) {
85
+ if (propNames.has(cond.condition)) result.add(cond.condition)
86
+ }
87
+ return result
88
+ }
@@ -17,16 +17,19 @@ import type {
17
17
  EventDelegationPlan,
18
18
  ItemLookup,
19
19
  } from './types.ts'
20
+ import type { ContainerOwnHandler } from './event-collision.ts'
20
21
 
21
22
  export function buildDynamicLoopDelegationPlan(
22
23
  elem: TopLevelLoop,
23
24
  profileComponentName?: string,
25
+ ownHandlers?: Map<string, ContainerOwnHandler>,
24
26
  ): EventDelegationPlan {
25
27
  return {
26
28
  kind: 'event-delegation',
27
29
  containerVar: `_${varSlotId(elem.slotId)}`,
28
30
  events: elem.bindings.events,
29
31
  profileComponentName,
32
+ ownHandlers,
30
33
  itemLookup: buildKeyedOrIndexLookup({
31
34
  // Chain `.filter()` / `.toSorted()` so the index-based lookup walks
32
35
  // the same array shape mapArray reconciled into the DOM (#1434).
@@ -93,12 +96,14 @@ export function buildBranchLoopDelegationPlan(
93
96
  export function buildStaticArrayDelegationPlan(
94
97
  elem: TopLevelLoop,
95
98
  profileComponentName?: string,
99
+ ownHandlers?: Map<string, ContainerOwnHandler>,
96
100
  ): EventDelegationPlan {
97
101
  return {
98
102
  kind: 'event-delegation',
99
103
  containerVar: `_${varSlotId(elem.slotId)}`,
100
104
  events: elem.bindings.events,
101
105
  profileComponentName,
106
+ ownHandlers,
102
107
  itemLookup: {
103
108
  kind: 'static-index',
104
109
  // Static arrays render through the same `.filter()`/`.toSorted()`
@@ -62,29 +62,45 @@ export interface BuildLoopPlanOptions {
62
62
  lazyScope?: LazyRowScopeInfo
63
63
  }
64
64
 
65
+ /** Which `LoopPlan` variant `buildLoopPlan` would build for a given loop. */
66
+ export type LoopVariantKind = 'plain' | 'static' | 'composite' | 'component'
67
+
65
68
  /**
66
- * The single public builder. Selects the variant via the decision tree
67
- * described above and returns the discriminated `LoopPlan`.
69
+ * Classify which variant `buildLoopPlan` would build for `elem`, without
70
+ * building it. Mirrors the decision tree below exactly — pulled out so a
71
+ * caller that only needs the classification (e.g. the event-delegation
72
+ * eligibility precompute, #2930) doesn't have to duplicate these predicates
73
+ * or pay for building the full `LoopPlan`.
68
74
  */
69
- export function buildLoopPlan(elem: TopLevelLoop, opts: BuildLoopPlanOptions): LoopPlan {
75
+ export function classifyLoopKind(elem: TopLevelLoop): LoopVariantKind {
70
76
  // Whole-item conditional bodies (#1665) render 0-or-1 element per item, so
71
77
  // they need anchored `mapArrayAnchored` emission regardless of whether the
72
78
  // array is static or dynamic. Routing both through the plain (anchored)
73
79
  // path keeps `const arr` and `signal()` behaviour identical — a static
74
80
  // array's per-item conditional still toggles reactively instead of freezing
75
81
  // in the SSR-time `forEach` (which has no conditional handling at all).
76
- if (elem.bodyIsItemConditional) {
77
- return buildPlainLoopPlan(elem, opts.profileComponentName, opts.lazyScope)
78
- }
79
- if (elem.isStaticArray) {
80
- return buildStaticLoopPlan(elem, opts.unsafeLocalNames, opts.profileComponentName)
81
- }
82
+ if (elem.bodyIsItemConditional) return 'plain'
83
+ if (elem.isStaticArray) return 'static'
82
84
  const hasInnerStructure = (elem.nestedComponents?.length ?? 0) > 0
83
85
  || (elem.innerLoops?.length ?? 0) > 0
84
- if (elem.useElementReconciliation && hasInnerStructure) {
86
+ if (elem.useElementReconciliation && hasInnerStructure) return 'composite'
87
+ if (elem.childComponent) return 'component'
88
+ return 'plain'
89
+ }
90
+
91
+ /**
92
+ * The single public builder. Dispatches via `classifyLoopKind` and returns
93
+ * the discriminated `LoopPlan`.
94
+ */
95
+ export function buildLoopPlan(elem: TopLevelLoop, opts: BuildLoopPlanOptions): LoopPlan {
96
+ const kind = classifyLoopKind(elem)
97
+ if (kind === 'static') {
98
+ return buildStaticLoopPlan(elem, opts.unsafeLocalNames, opts.profileComponentName)
99
+ }
100
+ if (kind === 'composite') {
85
101
  return buildTopLevelCompositePlan(elem, opts.profileComponentName)
86
102
  }
87
- if (elem.childComponent) {
103
+ if (kind === 'component') {
88
104
  return buildComponentLoopPlan(elem, opts.profileComponentName)
89
105
  }
90
106
  return buildPlainLoopPlan(elem, opts.profileComponentName, opts.lazyScope)