@barefootjs/jsx 0.39.5 → 0.39.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 (129) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +142 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +153 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/computed-const.d.ts +52 -0
  14. package/dist/adapters/computed-const.d.ts.map +1 -0
  15. package/dist/adapters/dangerous-inner-html.d.ts +10 -0
  16. package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
  17. package/dist/adapters/element-shell.d.ts +44 -0
  18. package/dist/adapters/element-shell.d.ts.map +1 -0
  19. package/dist/adapters/interface.d.ts +2 -0
  20. package/dist/adapters/interface.d.ts.map +1 -1
  21. package/dist/adapters/literal-value.d.ts +22 -0
  22. package/dist/adapters/literal-value.d.ts.map +1 -0
  23. package/dist/adapters/loop-plan.d.ts +53 -0
  24. package/dist/adapters/loop-plan.d.ts.map +1 -0
  25. package/dist/adapters/prop-classes.d.ts +37 -0
  26. package/dist/adapters/prop-classes.d.ts.map +1 -0
  27. package/dist/analyzer.d.ts.map +1 -1
  28. package/dist/augment-inherited-props.d.ts +7 -0
  29. package/dist/augment-inherited-props.d.ts.map +1 -1
  30. package/dist/expression-parser.d.ts +38 -0
  31. package/dist/expression-parser.d.ts.map +1 -1
  32. package/dist/fold-render-reassignments.d.ts +43 -0
  33. package/dist/fold-render-reassignments.d.ts.map +1 -0
  34. package/dist/free-refs.d.ts +9 -0
  35. package/dist/free-refs.d.ts.map +1 -1
  36. package/dist/index.d.ts +23 -5
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +3954 -2401
  39. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
  41. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/html-template.d.ts +9 -10
  44. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
  47. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
  49. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/utils.d.ts +13 -0
  51. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  52. package/dist/jsx-to-ir.d.ts +465 -1
  53. package/dist/jsx-to-ir.d.ts.map +1 -1
  54. package/dist/nullable-signal-attr.d.ts +22 -2
  55. package/dist/nullable-signal-attr.d.ts.map +1 -1
  56. package/dist/props-binding.d.ts +34 -5
  57. package/dist/props-binding.d.ts.map +1 -1
  58. package/dist/relocate.d.ts +16 -0
  59. package/dist/relocate.d.ts.map +1 -1
  60. package/dist/ssr-seed-plan.d.ts +0 -6
  61. package/dist/ssr-seed-plan.d.ts.map +1 -1
  62. package/dist/types.d.ts +54 -2
  63. package/dist/types.d.ts.map +1 -1
  64. package/package.json +2 -2
  65. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  66. package/src/__tests__/action-accessor.test.ts +6 -24
  67. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  68. package/src/__tests__/attr-plan.test.ts +121 -0
  69. package/src/__tests__/binding-scope-ratchet.test.ts +12 -12
  70. package/src/__tests__/block-memo-type.test.ts +51 -0
  71. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  72. package/src/__tests__/boolean-result.test.ts +34 -1
  73. package/src/__tests__/callback-method.test.ts +264 -0
  74. package/src/__tests__/client-only-date-lowering.test.ts +2 -2
  75. package/src/__tests__/component-props.test.ts +148 -0
  76. package/src/__tests__/computed-const.test.ts +101 -0
  77. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  78. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  79. package/src/__tests__/element-shell.test.ts +78 -0
  80. package/src/__tests__/fold-render-reassignments.test.ts +96 -0
  81. package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
  82. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  83. package/src/__tests__/loop-plan.test.ts +104 -0
  84. package/src/__tests__/map-call-decisions.test.ts +521 -0
  85. package/src/__tests__/memo-body-expr.test.ts +120 -0
  86. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  87. package/src/__tests__/prop-handling.test.ts +35 -16
  88. package/src/__tests__/props-alias-const.test.ts +65 -0
  89. package/src/__tests__/signal-prop-seed.test.ts +90 -0
  90. package/src/__tests__/ssr-seed-plan.test.ts +54 -1
  91. package/src/__tests__/static-template-reachability.test.ts +137 -0
  92. package/src/adapters/array-method.ts +193 -0
  93. package/src/adapters/attr-plan.ts +228 -0
  94. package/src/adapters/boolean-result.ts +208 -12
  95. package/src/adapters/callback-method.ts +363 -0
  96. package/src/adapters/component-props.ts +144 -0
  97. package/src/adapters/component-tree.ts +118 -0
  98. package/src/adapters/computed-const.ts +185 -0
  99. package/src/adapters/dangerous-inner-html.ts +33 -0
  100. package/src/adapters/element-shell.ts +160 -0
  101. package/src/adapters/interface.ts +8 -0
  102. package/src/adapters/literal-value.ts +36 -0
  103. package/src/adapters/loop-plan.ts +88 -0
  104. package/src/adapters/prop-classes.ts +73 -0
  105. package/src/analyzer.ts +271 -82
  106. package/src/augment-inherited-props.ts +12 -0
  107. package/src/expression-parser.ts +537 -374
  108. package/src/fold-render-reassignments.ts +314 -0
  109. package/src/free-refs.ts +49 -0
  110. package/src/index.ts +61 -3
  111. package/src/ir-to-client-js/compute-inlinability.ts +93 -17
  112. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  113. package/src/ir-to-client-js/csr-substitute.ts +13 -35
  114. package/src/ir-to-client-js/emit-registration.ts +3 -2
  115. package/src/ir-to-client-js/html-template.ts +26 -70
  116. package/src/ir-to-client-js/index.ts +3 -2
  117. package/src/ir-to-client-js/init-declarations.ts +1 -1
  118. package/src/ir-to-client-js/plan/build-declaration-emit.ts +25 -51
  119. package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
  120. package/src/ir-to-client-js/prop-handling.ts +13 -54
  121. package/src/ir-to-client-js/rewrite-destructured-props.ts +6 -5
  122. package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
  123. package/src/ir-to-client-js/utils.ts +11 -0
  124. package/src/jsx-to-ir.ts +1346 -1022
  125. package/src/nullable-signal-attr.ts +85 -4
  126. package/src/props-binding.ts +100 -5
  127. package/src/relocate.ts +40 -8
  128. package/src/ssr-seed-plan.ts +18 -6
  129. package/src/types.ts +50 -2
@@ -221,7 +221,7 @@ function emitKeyedLookup(
221
221
  if (hasBindings) {
222
222
  // TDZ-safe shape — see #951.
223
223
  ls.push(` const __bfLoopItem = ${arrayExpr}.find(item => String(${keyWithItem}) === key)`)
224
- ls.push(` if (__bfLoopItem) {`)
224
+ ls.push(` if (__bfLoopItem !== undefined) {`)
225
225
  ls.push(` const ${param} = __bfLoopItem`)
226
226
  if (preambleLine) ls.push(` ${preambleLine}`)
227
227
  if (idxLine) ls.push(` ${idxLine}`)
@@ -239,8 +239,10 @@ function emitKeyedLookup(
239
239
  // the item null guard — a `.find()` miss (stale-DOM race, e.g. the
240
240
  // clicked row's key no longer in the current array) must short-circuit
241
241
  // before a preamble that dereferences the item ever runs (BUG-4).
242
+ // Every item guard here tests for that miss (`undefined`), never
243
+ // truthiness: a row item can be `0`, `''` or `false` (#3433).
242
244
  ls.push(` const ${param} = ${arrayExpr}.find(item => String(${keyWithItem}) === key)`)
243
- ls.push(` if (${param}) {`)
245
+ ls.push(` if (${param} !== undefined) {`)
244
246
  if (preambleLine) ls.push(` ${preambleLine}`)
245
247
  if (idxLine) ls.push(` ${idxLine}`)
246
248
  ls.push(` ;${handlerCall}`)
@@ -273,14 +275,14 @@ function emitKeyedLookup(
273
275
  ? substituteLoopBindings(rawKey, nested.paramBindings, 'item')
274
276
  : rawKey.replace(identifierPattern(nested.param, 'g'), 'item')
275
277
  const outerRef = hasBindings ? '__bfLoopItem' : param
276
- ls.push(` const ${nested.param} = ${outerRef} && ${nested.array}.find(item => String(${innerKeyExpr}) === innerKey${nested.depth})`)
278
+ ls.push(` const ${nested.param} = ${outerRef} !== undefined ? ${nested.array}.find(item => String(${innerKeyExpr}) === innerKey${nested.depth}) : undefined`)
277
279
  }
278
280
  const outerGuard = hasBindings ? '__bfLoopItem' : param
279
281
  const allParams = [outerGuard, ...ev.nestedLoops.map(n => n.param)]
280
282
  // Preamble and idx binding run INSIDE the combined item guard (BUG-4) —
281
283
  // a nested `.find()` miss must short-circuit before the preamble runs.
282
284
  const idxLine = indexBindingLine(ev.handler, indexParam, `${arrayExpr}.findIndex(item => String(${keyWithItem}) === outerKey)`)
283
- ls.push(` if (${allParams.join(' && ')}) {`)
285
+ ls.push(` if (${allParams.map(p => `${p} !== undefined`).join(' && ')}) {`)
284
286
  if (preambleLine) ls.push(` ${preambleLine}`)
285
287
  if (idxLine) ls.push(` ${idxLine}`)
286
288
  ls.push(` ;${handlerCall}`)
@@ -301,7 +303,7 @@ function emitDynamicIndexLookup(
301
303
  ls.push(` const idx = Array.from(li.parentElement.children).indexOf(li)`)
302
304
  if (hasBindings) {
303
305
  ls.push(` const __bfLoopItem = ${arrayExpr}[idx]`)
304
- ls.push(` if (__bfLoopItem) {`)
306
+ ls.push(` if (__bfLoopItem !== undefined) {`)
305
307
  ls.push(` const ${param} = __bfLoopItem`)
306
308
  if (preambleLine) ls.push(` ${preambleLine}`)
307
309
  if (idxLine) ls.push(` ${idxLine}`)
@@ -311,7 +313,7 @@ function emitDynamicIndexLookup(
311
313
  // Preamble and idx binding run INSIDE the item null guard (BUG-4) — an
312
314
  // out-of-range index (stale-DOM race) must short-circuit first.
313
315
  ls.push(` const ${param} = ${arrayExpr}[idx]`)
314
- ls.push(` if (${param}) {`)
316
+ ls.push(` if (${param} !== undefined) {`)
315
317
  if (preambleLine) ls.push(` ${preambleLine}`)
316
318
  if (idxLine) ls.push(` ${idxLine}`)
317
319
  ls.push(` ;${handlerCall}`)
@@ -338,7 +340,7 @@ function emitStaticIndexLookup(
338
340
  ls.push(` const ${param} = ${arrayExpr}[__idx]`)
339
341
  // Preamble and idx binding run INSIDE the item null guard (BUG-4) — an
340
342
  // out-of-range index (stale-DOM race) must short-circuit first.
341
- ls.push(` if (${param}) {`)
343
+ ls.push(` if (${param} !== undefined) {`)
342
344
  // Nested static `.map()` params (#3240): static arrays carry no
343
345
  // data-key markers, so — unlike `emitKeyedLookup`'s nested branch, which
344
346
  // resolves each level via `closest('[data-key-N]')` — each nested level's
@@ -26,7 +26,7 @@
26
26
  */
27
27
 
28
28
  import ts from 'typescript'
29
- import { inferDefaultValue } from './utils.ts'
29
+ import { inferDefaultValue, readsBareProp } from './utils.ts'
30
30
  import { extractFreeIdentifiersFromNode } from '../analyzer.ts'
31
31
  import type { ConstantInfo, MemoInfo, SignalInfo } from '../types.ts'
32
32
  import type { BindingScope } from '../scope/binding-scope.ts'
@@ -295,7 +295,7 @@ function csrSubstituteOnce(
295
295
  // Arrow function: bind params + any block-scoped locals declared
296
296
  // inside the body, recurse, unbind. Pre-collecting body locals
297
297
  // before descending matters for the IIFE shape that
298
- // `extractMemoBodyExpr` produces for non-trivial memo bodies:
298
+ // `MemoInfo.bodyExpr` carries for non-trivial memo bodies:
299
299
  //
300
300
  // (() => { const items = foo; return items.length })()
301
301
  //
@@ -457,28 +457,6 @@ export function extractFreeIdentifiersFromTemplateText(template: string): Set<st
457
457
  return ids
458
458
  }
459
459
 
460
- /**
461
- * Reduce a memo's `() => expr` source to the expression that should be
462
- * substituted in for `memoName()`. Matches the extraction done by the
463
- * legacy `buildSignalAndMemoMaps` in `emit-registration.ts`:
464
- *
465
- * - `() => expr` → `expr`
466
- * - `() => { return e; }` → `e`
467
- * - `() => { ...complex... }` → `(() => { ...complex... })()`
468
- *
469
- * The IIFE form for non-trivial blocks keeps intermediate `const`/`let`
470
- * bindings in scope; inlining the block bare would dangle them.
471
- */
472
- export function extractMemoBodyExpr(computation: string): string {
473
- const arrowMatch = computation.match(/^\(\)\s*=>\s*(.+)$/s)
474
- if (!arrowMatch) return computation
475
- const body = arrowMatch[1].trim()
476
- if (!body.startsWith('{')) return body
477
- const simpleReturn = body.match(/^\{\s*return\s+([\s\S]+?)\s*;?\s*\}$/)
478
- if (simpleReturn) return simpleReturn[1]
479
- return `(() => ${body})()`
480
- }
481
-
482
460
  /**
483
461
  * Which local consts are bare alias-hop chains that ultimately name a
484
462
  * substitutable signal/memo getter (`isGetter`) — e.g. `const
@@ -587,7 +565,7 @@ export function buildSignalMemoEnv(
587
565
  if (s.envReader) continue
588
566
  substitutions.set(s.getter, {
589
567
  kind: 'call',
590
- replacement: normalizeSignalInitial(s, propsObjectName),
568
+ replacement: normalizeSignalInitial(s),
591
569
  freeIdentifiers: s.initialFreeIdentifiers ?? new Set(),
592
570
  })
593
571
  // A bare reference to the SETTER (`<Display update={setCount} />`,
@@ -612,12 +590,13 @@ export function buildSignalMemoEnv(
612
590
  for (const m of memos) {
613
591
  substitutions.set(m.name, {
614
592
  kind: 'call',
615
- // Destructured mode (#2468): `templateComputation` (when present) has
593
+ // Destructured mode (#2468): `templateBodyExpr` (when present) has
616
594
  // bare destructured prop refs already rewritten to `_p.X` — the
617
595
  // spliced body lands in the module-scope template arrow, which is not
618
596
  // a closure over init's `const value = _p.value` extraction. Mirrors
619
- // the signal `templateInitialValue` handling above (#2265).
620
- replacement: extractMemoBodyExpr(m.templateComputation ?? m.computation),
597
+ // the signal `templateInitialValue` handling above (#2265). The body
598
+ // itself is read from the callback node by the analyzer (#3510).
599
+ replacement: m.templateBodyExpr ?? m.bodyExpr ?? 'undefined',
621
600
  freeIdentifiers: m.computationFreeIdentifiers ?? new Set(),
622
601
  })
623
602
  }
@@ -629,7 +608,8 @@ export function buildSignalMemoEnv(
629
608
 
630
609
  /**
631
610
  * Add the `?? <default>` SSR fallback to a signal's initial value when
632
- * the value is a bare `propsName.X` reference. Returns the value in raw
611
+ * the value is a bare `propsName.X` reference (`readsBareProp`, read from
612
+ * the analyzer's `SignalInfo.propSeed`, #3508). Returns the value in raw
633
613
  * (props.X) form — the `propsObjectName → _p` rewrite is deferred to
634
614
  * `rewritePropsObjectRef` at emit time so the post-substitution
635
615
  * `isInlinableInTemplate` check still sees bridged-arg shapes (#1138).
@@ -637,17 +617,15 @@ export function buildSignalMemoEnv(
637
617
  * The `??` fallback prevents literal `undefined` from leaking into the
638
618
  * SSR HTML when the prop is omitted — `inferDefaultValue` picks a
639
619
  * type-appropriate sentinel (`0` for number, `''` for string, etc.).
640
- * Skipped when the value already carries its own `??` so user-supplied
641
- * defaults aren't masked.
620
+ * Skipped when the value carries a fallback of its own (`??` / `||`) so
621
+ * user-supplied defaults aren't masked.
642
622
  */
643
- function normalizeSignalInitial(signal: SignalInfo, propsObjectName: string | null): string {
623
+ function normalizeSignalInitial(signal: SignalInfo): string {
644
624
  const initialValue = signal.initialValue
645
- const propsName = propsObjectName ?? 'props'
646
- const propsPrefix = `${propsName}.`
647
625
  // An async factory's `initial` (#3165) renders exactly as given: an absent
648
626
  // prop means no obtained result, so the value is `undefined` on the server
649
627
  // too, never a type default.
650
- if (!signal.factory && initialValue.startsWith(propsPrefix) && !initialValue.includes('??')) {
628
+ if (!signal.factory && readsBareProp(signal)) {
651
629
  return `${initialValue} ?? ${inferDefaultValue(signal.type)}`
652
630
  }
653
631
  // Destructured mode (#2265): `templateInitialValue` (when present) has
@@ -7,6 +7,7 @@
7
7
  import type { ComponentIR, IRNode, ReferencesGraph, SignalInfo } from '../types.ts'
8
8
  import type { ClientJsContext } from './types.ts'
9
9
  import { PROPS_PARAM, componentDefScopeFlags, initFunctionName } from './utils.ts'
10
+ import { collectReactiveGetterNames } from '../analyzer-context.ts'
10
11
  import { computeInlinability, toLegacyInlinability } from './compute-inlinability.ts'
11
12
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate, createStringProtector } from './html-template.ts'
12
13
  import { markupSlotIdsOf } from './markup-slots.ts'
@@ -190,7 +191,7 @@ export function emitRegistrationAndHydration(
190
191
  lines.push(`}`)
191
192
  lines.push('')
192
193
 
193
- const propNamesForStaticCheck = new Set(ctx.propsParams.map((p) => p.name))
194
+ const reactiveGetterNames = collectReactiveGetterNames(ctx.signals, ctx.memos)
194
195
  const { inlinableConstants, unsafeLocalNames } = inlinability ?? buildInlinableConstants(ctx, graph, _ir.root)
195
196
 
196
197
  // Build rest spread names: these are rest/props spreads handled by
@@ -219,7 +220,7 @@ export function emitRegistrationAndHydration(
219
220
 
220
221
  // Build ComponentDef object for hydrate()
221
222
  const defParts: string[] = [`init: ${initFunctionName(name)}`]
222
- if (canGenerateStaticTemplate(_ir.root, propNamesForStaticCheck, inlinableConstants, unsafeLocalNames)) {
223
+ if (canGenerateStaticTemplate(_ir.root, reactiveGetterNames, inlinableConstants, unsafeLocalNames)) {
223
224
  const markupSlotIds = markupSlotIdsOf(ctx)
224
225
  const templateHtml = irToComponentTemplate(_ir.root, inlinableConstants, restSpreadNames, ctx.propsObjectName, markupSlotIds, ctx.restPropsName)
225
226
  if (templateHtml) {
@@ -2124,26 +2124,32 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
2124
2124
  * Returns false if the component has:
2125
2125
  * - Loops (which use dynamic signal arrays)
2126
2126
  * - Child components (which can't be fully represented in templates)
2127
- * - Signal calls in expressions (like todos().length)
2128
- * - References to local variables not available at module scope (#343)
2127
+ * - A free reference that the module-scope template lambda cannot reach:
2128
+ * a signal getter or memo (`todos().length`, `label + count()`), or a local
2129
+ * variable not available at module scope (#343)
2129
2130
  *
2130
2131
  * Components that fail this check should not have registerTemplate() generated
2131
2132
  * as the template would reference undefined variables at module scope.
2132
2133
  *
2134
+ * The decision reads only the IR's free identifiers (`origin.freeRefs` for
2135
+ * expressions and conditions, `freeIdentifiers` for attributes), never the
2136
+ * expression text, so it does not depend on operand order (#3509).
2137
+ *
2133
2138
  * @param node - IR node to check
2134
- * @param propNames - Set of prop names (safe to reference via props parameter)
2139
+ * @param reactiveGetterNames - Signal getter and memo names (not callable in the template lambda)
2135
2140
  * @param inlinableConstants - Constants that can be substituted with their values
2136
2141
  * @param unsafeLocalNames - Local names that cannot be used in module-scope templates
2137
2142
  */
2138
2143
  export function canGenerateStaticTemplate(
2139
2144
  node: IRNode,
2140
- propNames: Set<string>,
2145
+ reactiveGetterNames: ReadonlySet<string>,
2141
2146
  inlinableConstants?: Map<string, string>,
2142
2147
  unsafeLocalNames?: Set<string>
2143
2148
  ): boolean {
2144
- const hasUnsafeRef = (freeIds: ReadonlySet<string> | undefined): boolean => {
2145
- return !!(unsafeLocalNames && unsafeLocalNames.size > 0 && setIntersects(freeIds, unsafeLocalNames))
2146
- }
2149
+ const recurse = (child: IRNode): boolean =>
2150
+ canGenerateStaticTemplate(child, reactiveGetterNames, inlinableConstants, unsafeLocalNames)
2151
+ const hasUnreachableRef = (freeIds: ReadonlySet<string> | undefined): boolean =>
2152
+ setIntersects(freeIds, reactiveGetterNames) || setIntersects(freeIds, unsafeLocalNames)
2147
2153
 
2148
2154
  switch (node.type) {
2149
2155
  case 'loop':
@@ -2153,59 +2159,32 @@ export function canGenerateStaticTemplate(
2153
2159
  return false
2154
2160
 
2155
2161
  case 'expression':
2156
- if (hasUnsafeRef(freeIdsFromRefs(node.origin?.freeRefs))) return false
2157
- // Use AST-derived flag when available, fall back to string check for older IR
2158
- if ((node.hasFunctionCalls ?? node.expr.includes('()')) && !isSimplePropExpression(node.expr, propNames)) {
2159
- return false
2160
- }
2161
- return true
2162
+ return !hasUnreachableRef(freeIdsFromRefs(node.origin?.freeRefs))
2162
2163
 
2163
2164
  case 'element':
2164
2165
  for (const attr of node.attrs) {
2165
- if (attr.name === '...') {
2166
- // Computed local spreads are now handled by spreadAttrs() at runtime.
2167
- // Only check for unsafe references that would fail at module scope.
2168
- const valueStr = attrValueToString(attr.value)
2169
- if (valueStr && hasUnsafeRef(attr.freeIdentifiers)) return false
2170
- if (valueStr && valueStr.includes('()') && !isSimplePropExpression(valueStr, propNames)) return false
2171
- continue
2172
- }
2173
- // Only `expression` / `template` carry runtime references worth probing.
2174
- if (attr.value.kind === 'expression' || attr.value.kind === 'template' || attr.value.kind === 'spread') {
2175
- const valueStr = attrValueToString(attr.value)
2176
- if (valueStr) {
2177
- if (hasUnsafeRef(attr.freeIdentifiers)) return false
2178
- if (valueStr.includes('()') && !isSimplePropExpression(valueStr, propNames)) {
2179
- return false
2180
- }
2181
- }
2182
- }
2166
+ // Only `expression` / `template` / `spread` carry runtime references
2167
+ // worth probing. A spread (`{...rest}`) of a computed local is handled
2168
+ // by spreadAttrs() at runtime, so the same reachability check applies.
2169
+ const probes = attr.name === '...' || attr.value.kind === 'expression' ||
2170
+ attr.value.kind === 'template' || attr.value.kind === 'spread'
2171
+ if (probes && attrValueToString(attr.value) && hasUnreachableRef(attr.freeIdentifiers)) return false
2183
2172
  }
2184
- return node.children.every((c) => canGenerateStaticTemplate(c, propNames, inlinableConstants, unsafeLocalNames))
2173
+ return node.children.every(recurse)
2185
2174
 
2186
2175
  case 'conditional':
2187
- if (hasUnsafeRef(freeIdsFromRefs(node.origin?.freeRefs))) return false
2188
- if (node.condition.includes('()') && !isSimplePropExpression(node.condition, propNames)) {
2189
- return false
2190
- }
2191
- return canGenerateStaticTemplate(node.whenTrue, propNames, inlinableConstants, unsafeLocalNames) &&
2192
- canGenerateStaticTemplate(node.whenFalse, propNames, inlinableConstants, unsafeLocalNames)
2176
+ if (hasUnreachableRef(freeIdsFromRefs(node.origin?.freeRefs))) return false
2177
+ return recurse(node.whenTrue) && recurse(node.whenFalse)
2193
2178
 
2194
2179
  case 'fragment':
2195
- return node.children.every((c) => canGenerateStaticTemplate(c, propNames, inlinableConstants, unsafeLocalNames))
2180
+ return node.children.every(recurse)
2196
2181
 
2197
2182
  case 'if-statement':
2198
- if (!canGenerateStaticTemplate(node.consequent, propNames, inlinableConstants, unsafeLocalNames)) {
2199
- return false
2200
- }
2201
- if (node.alternate && !canGenerateStaticTemplate(node.alternate, propNames, inlinableConstants, unsafeLocalNames)) {
2202
- return false
2203
- }
2204
- return true
2183
+ return recurse(node.consequent) && (!node.alternate || recurse(node.alternate))
2205
2184
 
2206
2185
  case 'provider':
2207
2186
  case 'async':
2208
- return node.children.every((c) => canGenerateStaticTemplate(c, propNames, inlinableConstants, unsafeLocalNames))
2187
+ return node.children.every(recurse)
2209
2188
 
2210
2189
  case 'text':
2211
2190
  return true
@@ -2903,26 +2882,3 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2903
2882
  }
2904
2883
  }
2905
2884
 
2906
- /**
2907
- * Check if an expression is a simple prop-based expression.
2908
- * Simple prop expressions access props only: todo.done, todo.text, props.name
2909
- * Non-prop expressions call signals: todos(), todos().length, todos().filter(...)
2910
- */
2911
- export function isSimplePropExpression(expr: string, propNames: Set<string>): boolean {
2912
- const match = expr.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*)/)
2913
- if (!match) {
2914
- // No identifier at start (e.g., template literal `${...}`) — check for signal calls
2915
- return !expr.includes('()')
2916
- }
2917
-
2918
- const rootIdent = match[1]
2919
- if (propNames.has(rootIdent)) {
2920
- // Even if root is a prop name, calling it as a function means it's a signal getter
2921
- const rest = expr.slice(rootIdent.length)
2922
- if (rest.startsWith('(')) return false
2923
- return true
2924
- }
2925
- if (expr.includes('()')) return false
2926
-
2927
- return true
2928
- }
@@ -17,6 +17,7 @@ import { addConstantPropRefsToSet } from './init-declarations.ts'
17
17
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate } from './html-template.ts'
18
18
  import { markupSlotIdsOf } from './markup-slots.ts'
19
19
  import { PROPS_PARAM, initFunctionName, componentDefScopeFlags, isTransparentFragmentRoot } from './utils.ts'
20
+ import { collectReactiveGetterNames } from '../analyzer-context.ts'
20
21
  import { buildInlinableConstants, csrInlinableConstantsFromCtx } from './emit-registration.ts'
21
22
  import { buildEnvFromCtx } from './compute-inlinability.ts'
22
23
  import { nameForRegistryRef, buildImportAliasMap, setActiveImportAliases } from './component-scope.ts'
@@ -317,7 +318,7 @@ function hasInitScopeOnlyConstant(ctx: ClientJsContext): boolean {
317
318
  * Returns '' if a static template cannot be generated.
318
319
  */
319
320
  function generateTemplateOnlyMount(ir: ComponentIR, ctx: ClientJsContext): string {
320
- const propNamesForStaticCheck = new Set(ctx.propsParams.map((p) => p.name))
321
+ const reactiveGetterNames = collectReactiveGetterNames(ctx.signals, ctx.memos)
321
322
  const graph = buildReferencesGraph(ctx, ir.root)
322
323
  const { inlinableConstants, unsafeLocalNames } = buildInlinableConstants(ctx, graph, ir.root)
323
324
 
@@ -329,7 +330,7 @@ function generateTemplateOnlyMount(ir: ComponentIR, ctx: ClientJsContext): strin
329
330
 
330
331
  let templateHtml: string | undefined
331
332
 
332
- if (canGenerateStaticTemplate(ir.root, propNamesForStaticCheck, inlinableConstants, unsafeLocalNames)) {
333
+ if (canGenerateStaticTemplate(ir.root, reactiveGetterNames, inlinableConstants, unsafeLocalNames)) {
333
334
  // `ctx.dynamicElements` is always empty on this template-only path
334
335
  // (`needsClientJs(ctx)` gates it) — derived through the shared function
335
336
  // anyway rather than special-casing "no markup slots here" (#2651).
@@ -106,7 +106,7 @@ export function classifyLocalDeclarations(
106
106
  moduleLevelSignals.push(signal)
107
107
  continue
108
108
  }
109
- const controlledPropName = getControlledPropName(signal, ctx.propsParams, ctx.propsObjectName)
109
+ const controlledPropName = getControlledPropName(signal)
110
110
  if (controlledPropName) {
111
111
  controlledSignals.push({ signal, propName: controlledPropName })
112
112
  }
@@ -12,7 +12,7 @@ import type { ControlledSignal } from '../init-declarations.ts'
12
12
  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
- import { inferDefaultValue, PROPS_PARAM } from '../utils.ts'
15
+ import { inferDefaultValue, PROPS_PARAM, readsBareProp } from '../utils.ts'
16
16
  import { livePropReadExpr } from '../../props-binding.ts'
17
17
  import { signalFactoryInitializer, signalSecondBinding } from '../../signal-initializer.ts'
18
18
  import type {
@@ -113,7 +113,7 @@ function buildSignalPlan(
113
113
  getter: signal.getter,
114
114
  setter: signal.setter,
115
115
  getterElided: signal.getterElided,
116
- initialValueExpr: resolveSignalInitialValue(signal, ctx, lookups),
116
+ initialValueExpr: resolveSignalInitialValue(signal, lookups),
117
117
  controlledEffect,
118
118
  branchCondition: signal.branchCondition,
119
119
  bfId: ctx.profile ? `${ctx.componentName}#signal:${signal.getter}` : undefined,
@@ -121,57 +121,28 @@ function buildSignalPlan(
121
121
  }
122
122
 
123
123
  /**
124
- * Order of checks:
125
- * 1. Reads a prop directly without `??` → wrap with the prop's inferred
126
- * default (`_p.X ?? <inferredDefault>`).
127
- * 2. Controlled signal:
128
- * - has `??` already → respect the user's expression (rewrite props
129
- * prefix only).
130
- * - no `??` → synthesize `_p.<propName> ?? <defaultVal>`.
131
- * 3. Other reads of `propsName.X` → straight prop rewrite.
132
- * 4. Otherwise → verbatim.
124
+ * The signal's initial value, decided from `SignalInfo.propSeed` (#3508):
125
+ * 1. A bare read of the props object (`props.X`, `props.row.count`) →
126
+ * `<it> ?? <inferred default>`, so the signal never starts as
127
+ * `undefined`.
128
+ * 2. A controlled signal seeded by a bare destructured binding →
129
+ * `_p.<caller key> ?? <the prop's default>`.
130
+ * 3. Anything else (a `??` / `||` fallback the user wrote, any other
131
+ * expression) → the initializer as written; `generateInit`'s
132
+ * `rewritePropsObjectRef` maps its `props.X` reads to `_p.X`.
133
133
  */
134
- function resolveSignalInitialValue(
135
- signal: SignalInfo,
136
- ctx: ClientJsContext,
137
- lookups: DeclarationEmitLookups,
138
- ): string {
139
- const propsName = ctx.propsObjectName ?? 'props'
140
- const propsPrefix = `${propsName}.`
141
- const startsWithPropsPrefix = signal.initialValue.startsWith(propsPrefix)
142
- const hasNullish = signal.initialValue.includes('??')
143
-
144
- // Case 1: bare `propsName.X` read — append the inferred default so the
145
- // signal never starts as `undefined`.
146
- if (startsWithPropsPrefix && !hasNullish) {
147
- const propRef = `${PROPS_PARAM}.` + signal.initialValue.slice(propsPrefix.length)
148
- return `${propRef} ?? ${inferDefaultValue(signal.type)}`
149
- }
150
-
151
- const controlled = lookups.controlledBySignal.get(signal)
152
- if (controlled) {
153
- // Case 2a: user already wrote `??` — keep their default but rewrite
154
- // a leading `propsName.` prefix.
155
- if (hasNullish) {
156
- if (ctx.propsObjectName && startsWithPropsPrefix) {
157
- return `${PROPS_PARAM}.` + signal.initialValue.slice(propsPrefix.length)
158
- }
159
- return signal.initialValue
134
+ function resolveSignalInitialValue(signal: SignalInfo, lookups: DeclarationEmitLookups): string {
135
+ const seed = signal.propSeed
136
+ if (readsBareProp(signal)) return `${signal.initialValue} ?? ${inferDefaultValue(signal.type)}`
137
+ if (seed && seed.fallback === null) {
138
+ const controlled = lookups.controlledBySignal.get(signal)
139
+ if (controlled) {
140
+ const prop = lookups.propByName.get(controlled.propName)
141
+ const defaultVal = prop?.defaultValue ?? inferDefaultValue(signal.type)
142
+ // `_p` is always keyed by the caller-facing name (#2524 CSR half).
143
+ return `${PROPS_PARAM}.${prop?.sourceName ?? controlled.propName} ?? ${defaultVal}`
160
144
  }
161
- // Case 2b: synthesize the prop accessor + default.
162
- const prop = lookups.propByName.get(controlled.propName)
163
- const defaultVal = prop?.defaultValue ?? inferDefaultValue(signal.type)
164
- // `_p` is always keyed by the caller-facing name (#2524 CSR half).
165
- return `${PROPS_PARAM}.${prop?.sourceName ?? controlled.propName} ?? ${defaultVal}`
166
145
  }
167
-
168
- // Case 3: non-controlled `propsObjectName.X` (only when destructured-
169
- // props mode is OFF — the destructured form has no `propsObjectName`).
170
- if (ctx.propsObjectName && startsWithPropsPrefix) {
171
- return `${PROPS_PARAM}.` + signal.initialValue.slice(propsPrefix.length)
172
- }
173
-
174
- // Case 4: fall-through.
175
146
  return signal.initialValue
176
147
  }
177
148
 
@@ -190,5 +161,8 @@ function buildControlledSignalEffect(
190
161
  ? livePropReadExpr(prop, undefined, false)
191
162
  : `${PROPS_PARAM}.${controlled.propName}`
192
163
 
193
- return { setter: signal.setter, accessorExpr }
164
+ // A `||` fallback (`createSignal(props.value || '')`) also replaces a
165
+ // falsy prop, so the re-sync sets the initializer's value, not the raw prop.
166
+ const valueExpr = signal.propSeed?.fallback?.op === '||' ? signal.initialValue : undefined
167
+ return { setter: signal.setter, accessorExpr, valueExpr }
194
168
  }
@@ -80,6 +80,11 @@ export interface ControlledSignalEffectPlan {
80
80
  accessorExpr: string
81
81
  /** Profile-mode IR-aligned id, appended as the `createEffect` 2nd arg (#1690). */
82
82
  bfId?: string
83
+ /**
84
+ * When set, the value the effect sets once the prop is defined (the
85
+ * signal's initializer, for a `||` fallback); otherwise the prop itself.
86
+ */
87
+ valueExpr?: string
83
88
  }
84
89
 
85
90
  export interface MemoEmitPlan {
@@ -172,61 +172,20 @@ export function expandConstantForReactivity(
172
172
  }
173
173
 
174
174
  /**
175
- * Check if a signal is initialized from a prop value (controlled signal pattern).
176
- * Returns the prop name if the signal's initial value references a prop, null otherwise.
175
+ * The prop a signal is controlled by: its initializer reads that declared
176
+ * prop itself (not a member of it), bare or with a `??` / `||` fallback (`createSignal(props.checked)`,
177
+ * `createSignal(value ?? 0)`), so a createEffect re-syncs it when the
178
+ * parent's prop changes. Read from the analyzer's `SignalInfo.propSeed`, the
179
+ * same field `resolveSignalInitialValue` reads, never from the text (#3508).
177
180
  *
178
- * Detects patterns like:
179
- * const [controlledChecked, setControlledChecked] = createSignal(props.checked)
180
- * const [controlledValue, setControlledValue] = createSignal(value)
181
- *
182
- * These signals need a createEffect to sync with parent's prop changes.
183
- *
184
- * Note: Props starting with "default" (e.g., defaultChecked, defaultValue) are
185
- * excluded as they are initial values, not controlled props.
181
+ * Props starting with "default" (`defaultChecked`) are initial values, not
182
+ * controlled props, and an async factory's value (`createQuery(fn, {
183
+ * initial: props.posts })`, #3165) takes `initial` once, then comes from its
184
+ * own requests.
186
185
  */
187
- export function getControlledPropName(
188
- signal: SignalInfo,
189
- propsParams: ParamInfo[],
190
- propsObjectName: string | null = null
191
- ): string | null {
192
- // An async factory's value (`createQuery(fn, { initial: props.posts })`,
193
- // #3165) takes `initial` once; later values come from its own requests, so
194
- // it is never re-synced from the prop.
195
- if (signal.factory) return null
196
- const initialValue = signal.initialValue.trim()
197
- const isDefaultProp = (propName: string) => propName.startsWith('default')
198
- // Use the source-level props name for pattern matching (not the generated PROPS_PARAM)
199
- const propsName = propsObjectName ?? 'props'
200
-
201
- // Direct <propsName>.X reference, optionally with ?? or || fallback
202
- // e.g., props.checked, p.value ?? 0, props.initial || ''
203
- const propsPattern = new RegExp(`^${propsName}\\.(\\w+)(?:\\s*(?:\\?\\?|\\|\\|)\\s*.+)?$`)
204
- const propsMatch = initialValue.match(propsPattern)
205
- if (propsMatch) {
206
- const propName = propsMatch[1]
207
- if (propsParams.some((p) => p.name === propName) && !isDefaultProp(propName)) {
208
- return propName
209
- }
210
- }
211
-
212
- // Simple prop name (e.g., checked in createSignal(checked))
213
- if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(initialValue)) {
214
- if (propsParams.some((p) => p.name === initialValue) && !isDefaultProp(initialValue)) {
215
- return initialValue
216
- }
217
- }
218
-
219
- // Prop with nullish coalescing or logical OR fallback
220
- // e.g., checked ?? false, props.checked ?? false, p.value || ''
221
- const fallbackPattern = new RegExp(`^(?:${propsName}\\.)?(\\w+)\\s*(?:\\?\\?|\\|\\|)\\s*.+$`)
222
- const fallbackMatch = initialValue.match(fallbackPattern)
223
- if (fallbackMatch) {
224
- const propName = fallbackMatch[1]
225
- if (propsParams.some((p) => p.name === propName) && !isDefaultProp(propName)) {
226
- return propName
227
- }
228
- }
229
-
230
- return null
186
+ export function getControlledPropName(signal: SignalInfo): string | null {
187
+ const seed = signal.propSeed
188
+ if (signal.factory || !seed || seed.nested || !seed.declared) return null
189
+ return seed.propName.startsWith('default') ? null : seed.propName
231
190
  }
232
191
 
@@ -107,11 +107,12 @@ function rewriteParamDestructuredReads(
107
107
  * bare-member-alias) prop local in `code` to a live `_p.<key>` read, for a
108
108
  * bare-props-form component (`function Foo(props: Props)`).
109
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
110
+ * `resolveBodyPropAliases` treats `const { value } = props` and `const value
111
+ * = props.value` alike (their `value` text is identical; only
112
+ * `ConstantInfo.propsDestructure` tells them apart, #3501), and so does this
113
+ * rewrite. That's the correct call, not a shortcut: BOTH are pure
114
+ * single-prop passthroughs with no computation of their own, so both should
115
+ * read live, matching
115
116
  * `props.value` used directly (which already reads live via
116
117
  * `rewritePropsObjectRef`).
117
118
  *
@@ -125,7 +125,7 @@ function emitSignal(lines: string[], plan: SignalEmitPlan): void {
125
125
  function emitControlledEffect(lines: string[], plan: ControlledSignalEffectPlan): void {
126
126
  lines.push(` createEffect(() => {`)
127
127
  lines.push(` const __val = ${plan.accessorExpr}`)
128
- lines.push(` if (__val !== undefined) ${plan.setter}(__val)`)
128
+ lines.push(` if (__val !== undefined) ${plan.setter}(${plan.valueExpr ?? '__val'})`)
129
129
  lines.push(` }${bfIdArg(plan.bfId)})`)
130
130
  }
131
131
 
@@ -469,6 +469,17 @@ export function emitRefCall(callback: string, elementVar: string, ssrPortalOwner
469
469
  return `{ ${call}; if (__scopeId) ${elementVar}.setAttribute('${BF_PORTAL_OWNER}', __scopeId) }`
470
470
  }
471
471
 
472
+ /**
473
+ * Whether a signal's initializer is a bare read of the props object
474
+ * (`props.X`, `props.row.count`) with no fallback of its own
475
+ * (`SignalInfo.propSeed`, #3508), the one shape both the init
476
+ * body and the CSR template give a type default (`?? <inferDefaultValue>`)
477
+ * so an omitted prop never seeds the signal with `undefined`.
478
+ */
479
+ export function readsBareProp(signal: { propSeed?: { via: string; fallback: unknown } }): boolean {
480
+ return signal.propSeed?.via === 'member' && signal.propSeed.fallback === null
481
+ }
482
+
472
483
  /** Infer a sensible JS default value literal from a type descriptor. */
473
484
  export function inferDefaultValue(type: { kind: string; primitive?: string }): string {
474
485
  if (type.kind === 'primitive') {