@barefootjs/jsx 0.39.6 → 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 (89) hide show
  1. package/dist/adapters/attr-plan.d.ts +8 -1
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +27 -0
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/computed-const.d.ts +52 -0
  6. package/dist/adapters/computed-const.d.ts.map +1 -0
  7. package/dist/adapters/dangerous-inner-html.d.ts +10 -0
  8. package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
  9. package/dist/adapters/element-shell.d.ts +44 -0
  10. package/dist/adapters/element-shell.d.ts.map +1 -0
  11. package/dist/adapters/interface.d.ts +2 -0
  12. package/dist/adapters/interface.d.ts.map +1 -1
  13. package/dist/analyzer.d.ts.map +1 -1
  14. package/dist/augment-inherited-props.d.ts +7 -0
  15. package/dist/augment-inherited-props.d.ts.map +1 -1
  16. package/dist/fold-render-reassignments.d.ts +43 -0
  17. package/dist/fold-render-reassignments.d.ts.map +1 -0
  18. package/dist/free-refs.d.ts +9 -0
  19. package/dist/free-refs.d.ts.map +1 -1
  20. package/dist/index.d.ts +8 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2285 -1583
  23. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
  25. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/html-template.d.ts +9 -10
  28. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
  31. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
  33. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/utils.d.ts +13 -0
  35. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  36. package/dist/jsx-to-ir.d.ts.map +1 -1
  37. package/dist/nullable-signal-attr.d.ts +3 -2
  38. package/dist/nullable-signal-attr.d.ts.map +1 -1
  39. package/dist/props-binding.d.ts +34 -5
  40. package/dist/props-binding.d.ts.map +1 -1
  41. package/dist/relocate.d.ts +16 -0
  42. package/dist/relocate.d.ts.map +1 -1
  43. package/dist/ssr-seed-plan.d.ts +0 -6
  44. package/dist/ssr-seed-plan.d.ts.map +1 -1
  45. package/dist/types.d.ts +54 -2
  46. package/dist/types.d.ts.map +1 -1
  47. package/package.json +2 -2
  48. package/src/__tests__/block-memo-type.test.ts +51 -0
  49. package/src/__tests__/callback-method.test.ts +75 -0
  50. package/src/__tests__/client-only-date-lowering.test.ts +2 -2
  51. package/src/__tests__/computed-const.test.ts +101 -0
  52. package/src/__tests__/element-shell.test.ts +78 -0
  53. package/src/__tests__/fold-render-reassignments.test.ts +96 -0
  54. package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
  55. package/src/__tests__/memo-body-expr.test.ts +120 -0
  56. package/src/__tests__/prop-handling.test.ts +35 -16
  57. package/src/__tests__/props-alias-const.test.ts +65 -0
  58. package/src/__tests__/signal-prop-seed.test.ts +90 -0
  59. package/src/__tests__/ssr-seed-plan.test.ts +54 -1
  60. package/src/__tests__/static-template-reachability.test.ts +137 -0
  61. package/src/adapters/attr-plan.ts +29 -1
  62. package/src/adapters/callback-method.ts +62 -0
  63. package/src/adapters/computed-const.ts +185 -0
  64. package/src/adapters/dangerous-inner-html.ts +33 -0
  65. package/src/adapters/element-shell.ts +160 -0
  66. package/src/adapters/interface.ts +8 -0
  67. package/src/analyzer.ts +271 -82
  68. package/src/augment-inherited-props.ts +12 -0
  69. package/src/fold-render-reassignments.ts +314 -0
  70. package/src/free-refs.ts +49 -0
  71. package/src/index.ts +9 -2
  72. package/src/ir-to-client-js/compute-inlinability.ts +93 -17
  73. package/src/ir-to-client-js/csr-substitute.ts +13 -35
  74. package/src/ir-to-client-js/emit-registration.ts +3 -2
  75. package/src/ir-to-client-js/html-template.ts +26 -70
  76. package/src/ir-to-client-js/index.ts +3 -2
  77. package/src/ir-to-client-js/init-declarations.ts +1 -1
  78. package/src/ir-to-client-js/plan/build-declaration-emit.ts +25 -51
  79. package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
  80. package/src/ir-to-client-js/prop-handling.ts +13 -54
  81. package/src/ir-to-client-js/rewrite-destructured-props.ts +6 -5
  82. package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
  83. package/src/ir-to-client-js/utils.ts +11 -0
  84. package/src/jsx-to-ir.ts +39 -52
  85. package/src/nullable-signal-attr.ts +7 -4
  86. package/src/props-binding.ts +100 -5
  87. package/src/relocate.ts +40 -8
  88. package/src/ssr-seed-plan.ts +18 -6
  89. package/src/types.ts +50 -2
@@ -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') {
package/src/jsx-to-ir.ts CHANGED
@@ -42,7 +42,7 @@ import {
42
42
  } from './types.ts'
43
43
  import { type AnalyzerContext, type MultiReturnJsxInfo, getSourceLocation, collectReactiveGetterNames, tsTypeToTypeInfo } from './analyzer-context.ts'
44
44
  import { parseExpression, isSupported, parseBlockBody, foldBlockToExpr, predicateTernaryToLogical, tsNodeToParsedExpr, sortComparatorFromArrow, stringifyParsedExpr, cssKebabCase, CALLBACK_METHODS, unboundCallbackParamRead, unboundCallbackParamReason, type ParsedExpr } from './expression-parser.ts'
45
- import type { IRLoopSort, FunctionInfo, ConstantInfo, ParamInfo } from './types.ts'
45
+ import type { IRLoopSort, FunctionInfo, ConstantInfo, ParamInfo, FreeReference } from './types.ts'
46
46
  import { formatParamWithType } from './module-exports.ts'
47
47
  import { createError, ErrorCodes, internalInvariant } from './errors.ts'
48
48
  import { CLIENT_BUILTIN_SOURCE, isClientBuiltinName, type ClientBuiltinTag } from './builtins.ts'
@@ -52,10 +52,10 @@ import {
52
52
  collectAstPropRefs,
53
53
  rewriteScopedValueRefs,
54
54
  } from './prop-rewrite.ts'
55
- import { boundPropLocalNames, buildPropAliasMap, resolveAliasOrigin, resolveRestSpreadOriginCore, livePropReadExpr } from './props-binding.ts'
55
+ import { boundPropLocalNames, buildPropAliasMap, isPropsAliasConst, resolveAliasOrigin, resolveRestSpreadOriginCore, livePropReadExpr } from './props-binding.ts'
56
56
  import { PROPS_PARAM } from './ir-to-client-js/utils.ts'
57
57
  import { walkIR } from './ir-to-client-js/walker.ts'
58
- import { resolveFreeRefs, isNameBound as isNameBoundInEnv, type BindingEnvironment } from './free-refs.ts'
58
+ import { resolveFreeRefs, rebindHelperParamRefs, isNameBound as isNameBoundInEnv, type BindingEnvironment } from './free-refs.ts'
59
59
  import { computeFileScope } from './ir-to-client-js/component-scope.ts'
60
60
  import { createTemplateAwareStringProtector } from './ir-to-client-js/html-template.ts'
61
61
  import { extractFreeIdentifiersFromText } from './ir-to-client-js/csr-substitute.ts'
@@ -414,7 +414,7 @@ function exprReferencesModuleClientSignal(expr: ts.Expression, ctx: TransformCon
414
414
  /**
415
415
  * Walk an expression AST to check if it contains any CallExpression.
416
416
  * Catches all call patterns: identifier(), obj.method(), fn?.(), IIFEs, etc.
417
- * Used by canGenerateStaticTemplate() to detect expressions unsafe for static rendering.
417
+ * Recorded on the IR as `hasFunctionCalls`.
418
418
  */
419
419
  function exprHasFunctionCalls(expr: ts.Expression): boolean {
420
420
  let found = false
@@ -750,11 +750,7 @@ function getDestructuredPropNames(ctx: TransformContext): Set<string> | null {
750
750
  }
751
751
  for (const m of ctx.analyzer.memos) shadowed.add(m.name)
752
752
  for (const c of ctx.analyzer.localConstants) {
753
- const isDestructureFromProps =
754
- typeof c.value === 'string' &&
755
- (c.value === `${ctx.analyzer.propsObjectName}.${c.name}` ||
756
- c.value.startsWith(`${ctx.analyzer.propsObjectName}.${c.name} ??`))
757
- if (!isDestructureFromProps) shadowed.add(c.name)
753
+ if (!isPropsAliasConst(c, ctx.analyzer.propsObjectName)) shadowed.add(c.name)
758
754
  }
759
755
  }
760
756
  const eligible = ctx.analyzer.propsParams.filter(p => !shadowed.has(p.name))
@@ -2721,38 +2717,7 @@ function transformJsxFunctionCall(
2721
2717
  ctx: TransformContext,
2722
2718
  _isClientOnly: boolean
2723
2719
  ): IRNode {
2724
- // Build substitution map: paramName → argument expression text
2725
- const substitutions = new Map<string, string>()
2726
- for (let i = 0; i < jsxFunc.params.length; i++) {
2727
- const paramName = jsxFunc.params[i]
2728
- const arg = callExpr.arguments[i]
2729
- if (arg) {
2730
- substitutions.set(paramName, ctx.getJS(arg))
2731
- }
2732
- }
2733
-
2734
- // Temporarily override getJS to apply parameter substitutions.
2735
- // Capture analyzer.getJS (the base implementation) to avoid circular references.
2736
- const baseGetJS = ctx.analyzer.getJS.bind(ctx.analyzer)
2737
- const originalCtxGetJS = ctx.getJS
2738
- const originalAnalyzerGetJS = ctx.analyzer.getJS
2739
-
2740
- const substitutedGetJS = (node: ts.Node) => {
2741
- let text = baseGetJS(node)
2742
- for (const [paramName, argExpr] of substitutions) {
2743
- // Replacer function, not the string form: `argExpr` is arbitrary
2744
- // caller-supplied JS text and may itself contain `$` sequences
2745
- // (`$&`, `$1`, …) that `String.replace`'s string-replacement form
2746
- // would interpret specially instead of inserting literally (#2592).
2747
- text = text.replace(identifierPattern(paramName, 'g'), () => argExpr)
2748
- }
2749
- return text
2750
- }
2751
-
2752
- ctx.getJS = substitutedGetJS
2753
- ctx.analyzer.getJS = substitutedGetJS
2754
-
2755
- try {
2720
+ return withHelperParamsSubstituted(callExpr, jsxFunc.params, ctx, () => {
2756
2721
  const result = transformNode(jsxFunc.jsxReturn, ctx)
2757
2722
  return result ?? {
2758
2723
  type: 'expression' as const,
@@ -2768,27 +2733,38 @@ function transformJsxFunctionCall(
2768
2733
  freeRefs: [],
2769
2734
  },
2770
2735
  }
2771
- } finally {
2772
- ctx.getJS = originalCtxGetJS
2773
- ctx.analyzer.getJS = originalAnalyzerGetJS
2774
- }
2736
+ })
2775
2737
  }
2776
2738
 
2777
- function transformMultiReturnJsxFunctionCall(
2739
+ /**
2740
+ * Run `build` with the helper's parameters substituted by the call's
2741
+ * arguments, for both inliners (#569). The substitution is textual (`getJS`
2742
+ * output), so the free references the built IR records still name the
2743
+ * parameters, which resolve to nothing in the component. Afterwards each
2744
+ * parameter reference is replaced by the argument's own free references
2745
+ * (`rebindHelperParamRefs`), so a consumer that reads the IR instead of the
2746
+ * text sees that `render(count())` reads the `count` signal (#3509).
2747
+ */
2748
+ function withHelperParamsSubstituted(
2778
2749
  callExpr: ts.CallExpression,
2779
- info: MultiReturnJsxInfo,
2750
+ params: readonly string[],
2780
2751
  ctx: TransformContext,
2752
+ build: (getText: (node: ts.Node) => string) => IRNode,
2781
2753
  ): IRNode {
2782
2754
  // Build substitution map: paramName → argument expression text
2783
2755
  const substitutions = new Map<string, string>()
2784
- for (let i = 0; i < info.params.length; i++) {
2785
- const paramName = info.params[i]
2756
+ const argRefs = new Map<string, FreeReference[]>()
2757
+ const env = makeBindingEnv(ctx)
2758
+ for (let i = 0; i < params.length; i++) {
2786
2759
  const arg = callExpr.arguments[i]
2787
2760
  if (arg) {
2788
- substitutions.set(paramName, ctx.getJS(arg))
2761
+ substitutions.set(params[i], ctx.getJS(arg))
2762
+ argRefs.set(params[i], resolveFreeRefs(arg, env))
2789
2763
  }
2790
2764
  }
2791
2765
 
2766
+ // Temporarily override getJS to apply parameter substitutions.
2767
+ // Capture analyzer.getJS (the base implementation) to avoid circular references.
2792
2768
  const baseGetJS = ctx.analyzer.getJS.bind(ctx.analyzer)
2793
2769
  const originalCtxGetJS = ctx.getJS
2794
2770
  const originalAnalyzerGetJS = ctx.analyzer.getJS
@@ -2809,14 +2785,25 @@ function transformMultiReturnJsxFunctionCall(
2809
2785
  ctx.analyzer.getJS = substitutedGetJS
2810
2786
 
2811
2787
  try {
2812
- const loc = getSourceLocation(callExpr, ctx.sourceFile, ctx.filePath)
2813
- return foldMultiReturnBranches(info, ctx, loc, substitutedGetJS)
2788
+ const result = build(substitutedGetJS)
2789
+ rebindHelperParamRefs(result, argRefs)
2790
+ return result
2814
2791
  } finally {
2815
2792
  ctx.getJS = originalCtxGetJS
2816
2793
  ctx.analyzer.getJS = originalAnalyzerGetJS
2817
2794
  }
2818
2795
  }
2819
2796
 
2797
+ function transformMultiReturnJsxFunctionCall(
2798
+ callExpr: ts.CallExpression,
2799
+ info: MultiReturnJsxInfo,
2800
+ ctx: TransformContext,
2801
+ ): IRNode {
2802
+ const loc = getSourceLocation(callExpr, ctx.sourceFile, ctx.filePath)
2803
+ return withHelperParamsSubstituted(callExpr, info.params, ctx, (getText) =>
2804
+ foldMultiReturnBranches(info, ctx, loc, getText))
2805
+ }
2806
+
2820
2807
  /**
2821
2808
  * Fold an extracted multi-return branch structure (if/else-if chain or switch)
2822
2809
  * into a right-nested chain of `IRConditional` nodes, terminating in the
@@ -140,8 +140,9 @@ function collectNullableNumberProps(ir: ComponentIR): ReadonlySet<string> {
140
140
  *
141
141
  * - a read of a nullable signal or of a memo whose type or body can be
142
142
  * nullish (`label()` with `label = createMemo(() => s())`);
143
- * - an optional member read (`user()?.name`), or a member read of a value
144
- * that can itself be nullish;
143
+ * - an optional member read (`user()?.name`), an index or computed-key read
144
+ * (`pair[1]`, `row[key]`), or a member read of a value that can itself be
145
+ * nullish;
145
146
  * - a ternary branch, or an `??` / `||` / `&&` operand the result can be;
146
147
  * - a literal `undefined` / `null`.
147
148
  *
@@ -178,10 +179,12 @@ export function attrValueMayBeNullish(
178
179
  visiting.delete(getter)
179
180
  return result
180
181
  }
182
+ // A computed key or an index (`pair[1]`, `row[key]`) reads `undefined`
183
+ // when it is out of range or absent (#3497).
181
184
  case 'member':
182
- return expr.optional || walk(expr.object, shadowed)
185
+ return expr.optional || expr.computed || walk(expr.object, shadowed)
183
186
  case 'index-access':
184
- return walk(expr.object, shadowed)
187
+ return true
185
188
  case 'conditional':
186
189
  return walk(expr.consequent, shadowed) || walk(expr.alternate, shadowed)
187
190
  case 'logical':