@barefootjs/jsx 0.39.8 → 0.40.0

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 (118) hide show
  1. package/dist/adapters/attr-plan.d.ts +1 -20
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +19 -7
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +79 -1
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  7. package/dist/adapters/loop-plan.d.ts +173 -9
  8. package/dist/adapters/loop-plan.d.ts.map +1 -1
  9. package/dist/adapters/parsed-expr-emitter.d.ts +20 -3
  10. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  11. package/dist/analyzer.d.ts.map +1 -1
  12. package/dist/assignment-target.d.ts +26 -0
  13. package/dist/assignment-target.d.ts.map +1 -0
  14. package/dist/augment-inherited-props.d.ts.map +1 -1
  15. package/dist/css-layer-prefixer.d.ts.map +1 -1
  16. package/dist/debug.d.ts.map +1 -1
  17. package/dist/errors.d.ts +1 -0
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/index.d.ts +6 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2566 -2007
  22. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  27. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  31. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/props-extraction.d.ts +5 -3
  35. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  37. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  40. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/utils.d.ts +1 -1
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/jsx-to-ir.d.ts.map +1 -1
  44. package/dist/module-exports.d.ts.map +1 -1
  45. package/dist/prop-rewrite.d.ts +17 -8
  46. package/dist/prop-rewrite.d.ts.map +1 -1
  47. package/dist/props-binding.d.ts +57 -0
  48. package/dist/props-binding.d.ts.map +1 -1
  49. package/dist/scope/binding-scope.d.ts +32 -2
  50. package/dist/scope/binding-scope.d.ts.map +1 -1
  51. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  52. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  53. package/dist/template-parts.d.ts +1 -1
  54. package/dist/template-parts.d.ts.map +1 -1
  55. package/dist/types.d.ts +30 -2
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +2 -2
  58. package/src/__tests__/arithmetic-lowering.test.ts +5 -1
  59. package/src/__tests__/attr-plan.test.ts +1 -14
  60. package/src/__tests__/binding-scope.test.ts +29 -0
  61. package/src/__tests__/client-template-escape-soundness.test.ts +17 -4
  62. package/src/__tests__/client-template-static-delimiters.test.ts +57 -0
  63. package/src/__tests__/create-query.test.ts +1 -1
  64. package/src/__tests__/dsl-template-adapter.test.ts +70 -0
  65. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  66. package/src/__tests__/extract-function-params.test.ts +37 -0
  67. package/src/__tests__/issue-2960-multi-root-cond-same-tag.test.ts +18 -0
  68. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +11 -0
  69. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  70. package/src/__tests__/loop-plan.test.ts +196 -1
  71. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  72. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  73. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  74. package/src/__tests__/props-alias-const.test.ts +60 -1
  75. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  76. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  77. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  78. package/src/__tests__/template-parts-literal-boundary.test.ts +22 -0
  79. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  80. package/src/adapters/attr-plan.ts +2 -54
  81. package/src/adapters/callback-method.ts +25 -10
  82. package/src/adapters/dsl-template-adapter.ts +155 -2
  83. package/src/adapters/loop-plan.ts +267 -14
  84. package/src/adapters/parsed-expr-emitter.ts +37 -4
  85. package/src/analyzer.ts +283 -2
  86. package/src/assignment-target.ts +79 -0
  87. package/src/augment-inherited-props.ts +5 -9
  88. package/src/css-layer-prefixer.ts +4 -5
  89. package/src/debug.ts +1 -0
  90. package/src/errors.ts +11 -0
  91. package/src/index.ts +23 -4
  92. package/src/ir-to-client-js/compute-inlinability.ts +7 -4
  93. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  94. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  95. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  96. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  97. package/src/ir-to-client-js/csr-substitute.ts +70 -22
  98. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  99. package/src/ir-to-client-js/emit-registration.ts +6 -1
  100. package/src/ir-to-client-js/html-template.ts +70 -52
  101. package/src/ir-to-client-js/phases/props-extraction.ts +26 -5
  102. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  103. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  104. package/src/ir-to-client-js/rewrite-destructured-props.ts +2 -2
  105. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  106. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  107. package/src/ir-to-client-js/utils.ts +41 -97
  108. package/src/jsx-to-ir.ts +65 -32
  109. package/src/loop-destructure.ts +4 -1
  110. package/src/module-exports.ts +13 -21
  111. package/src/prop-rewrite.ts +31 -72
  112. package/src/props-binding.ts +73 -1
  113. package/src/rich-type-refusal.ts +3 -1
  114. package/src/scope/binding-scope.ts +39 -3
  115. package/src/scope/lexical-scope-walk.ts +167 -0
  116. package/src/template-parts.ts +4 -2
  117. package/src/template-position-walk.ts +3 -1
  118. package/src/types.ts +27 -2
@@ -22,7 +22,7 @@ import type {
22
22
  LoopChildReactiveText,
23
23
  TopLevelLoop,
24
24
  } from '../../types.ts'
25
- import type { IRLoopChildComponent } from '../../../types.ts'
25
+ import type { IRLoopChildComponent, JsSourceText } from '../../../types.ts'
26
26
  import type { SafeHtml } from '../../safe-html.ts'
27
27
  import type { SkeletonSlotPaths } from '../../html-template.ts'
28
28
  import type { ReactiveEffectsPlan } from './reactive-effects.ts'
@@ -116,6 +116,22 @@ export interface LoopChildRefBinding {
116
116
  ssrPortalOwner?: boolean
117
117
  }
118
118
 
119
+ /**
120
+ * A loop-row child event resolved for a direct per-row listener (#3607):
121
+ * `handler` is already in the form the row binds its item in (wrapped with
122
+ * the loop-param accessor for a `mapArray` row, plain for a static
123
+ * `forEach` row), so the stringifier only spells the `qsa` lookup +
124
+ * `addEventListener` line.
125
+ */
126
+ export interface LoopRowEventBinding {
127
+ /** bf slot ID of the element bearing the handler. */
128
+ childSlotId: string
129
+ /** JSX event name (`click`, `input`, …); normalised to the DOM name at emit. */
130
+ eventName: string
131
+ /** Handler expression, as the row's binding of the item reads it. */
132
+ handler: JsSourceText
133
+ }
134
+
119
135
  /**
120
136
  * Plain element body, no child components, no inner loops. Covers the
121
137
  * single-line and multi-line renderItem shapes — the stringifier picks
@@ -216,6 +232,14 @@ interface ComponentLoopVariant extends DynamicLoopCommon {
216
232
  keyExpr: string
217
233
  /** Nested child component initialisers; empty for the simple case. */
218
234
  nestedComps: NestedComponentInit[]
235
+ /**
236
+ * Event handlers on elements forwarded as the ROOT component's own
237
+ * `children` (`<Chip><button onClick={...}/></Chip>`, #3607), outside any
238
+ * inner loop. Attached directly to each row (hydrated and client-built)
239
+ * the same way the composite row attaches `outerEvents`. Non-empty forces
240
+ * the SSR/CSR split shape (the simple shape has no row handle).
241
+ */
242
+ rowEvents: readonly LoopRowEventBinding[]
219
243
  /**
220
244
  * Reactive-effects plan for the loop ROOT component's own reactive attrs /
221
245
  * texts / conditionals — i.e. bindings on elements forwarded as the root
@@ -21,7 +21,7 @@ import { spliceChildValue } from '../safe-html.ts'
21
21
  import { emitListenerBlock } from './stringify/event-listener.ts'
22
22
  import { nameForRegistryRef } from '../component-scope.ts'
23
23
  import { BF_SCOPE, BF_HOST, BF_AT } from '@barefootjs/shared'
24
- import type { LoopChildRefBinding, PreambleRegionPlan, NestedChildrenTextEffect } from './plan/loop.ts'
24
+ import type { LoopChildRefBinding, LoopRowEventBinding, PreambleRegionPlan, NestedChildrenTextEffect } from './plan/loop.ts'
25
25
  import type { PreambleRegionSource } from '../../types.ts'
26
26
  import {
27
27
  extractFreeIdentifiersFromText,
@@ -383,8 +383,46 @@ function emitEventSetup(
383
383
  bodyIsMultiRoot: boolean = false,
384
384
  loopIndex?: string | null,
385
385
  ): void {
386
- const handler = loopParam ? wrapLoopParamAsAccessor(ev.handler, loopParam, loopParamBindings, loopIndex) : ev.handler
387
- emitListenerBlock(ls, indent, elVar, ev.childSlotId, '__e', ev.eventName, handler, 'dom', bodyIsMultiRoot)
386
+ const binding = loopParam
387
+ ? buildRowEventBinding(ev, loopParam, loopParamBindings, loopIndex)
388
+ : { childSlotId: ev.childSlotId, eventName: ev.eventName, handler: ev.handler }
389
+ emitRowEventListener(ls, indent, elVar, binding, bodyIsMultiRoot)
390
+ }
391
+
392
+ /**
393
+ * Resolve a loop-row child event into the binding a renderItem body attaches
394
+ * directly to the row's element (`emitRowEventListener`): the handler gets
395
+ * the same loop-param accessor rewrite as every other per-row read (#2859),
396
+ * so a row that survives a same-key reorder reads its current item / index.
397
+ */
398
+ export function buildRowEventBinding(
399
+ ev: LoopChildEvent,
400
+ loopParam: string,
401
+ loopParamBindings: readonly LoopParamBinding[] | undefined,
402
+ loopIndex?: string | null,
403
+ ): LoopRowEventBinding {
404
+ return {
405
+ childSlotId: ev.childSlotId,
406
+ eventName: ev.eventName,
407
+ handler: wrapLoopParamAsAccessor(ev.handler, loopParam, loopParamBindings, loopIndex),
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Emit the per-row `{ const __e = qsa(<elVar>, '[bf="<slot>"]'); if (__e)
413
+ * __e.addEventListener(...) }` block for one resolved row event binding.
414
+ * Shared by the composite row (`emitComponentAndEventSetup`) and the
415
+ * component-root row (`stringifyComponentLoop`, #3607), so both spell the
416
+ * direct per-row listener the same way.
417
+ */
418
+ export function emitRowEventListener(
419
+ ls: string[],
420
+ indent: string,
421
+ elVar: string,
422
+ binding: LoopRowEventBinding,
423
+ bodyIsMultiRoot: boolean = false,
424
+ ): void {
425
+ emitListenerBlock(ls, indent, elVar, binding.childSlotId, '__e', binding.eventName, binding.handler, 'dom', bodyIsMultiRoot)
388
426
  }
389
427
 
390
428
  /**
@@ -4,7 +4,8 @@
4
4
  * Two output shapes (preserved byte-identical from the legacy
5
5
  * `emitComponentLoopReconciliation` for the case it covered):
6
6
  *
7
- * nestedComps.length === 0 AND reactiveEffects === null (simple) —
7
+ * nestedComps, rowEvents, childRefs empty AND reactiveEffects === null
8
+ * (simple) —
8
9
  * two-line renderItem body:
9
10
  * <i>mapArray(() => <arr>, <container>, <keyFn>, (<head>, <idx>, __existing) => {
10
11
  * <i> <unwrap?>
@@ -19,12 +20,16 @@
19
20
  * <i> if (__existing) {
20
21
  * <i> initChild('<C>', __existing, <props>)
21
22
  * <i> {<each nested initChild + optional createEffect>}
23
+ * <i> {<each row event: qsa + addEventListener>}
22
24
  * <i> <stringifyReactiveEffects on __existing if reactiveEffects>
25
+ * <i> {<each row ref: qsa + callback invocation>}
23
26
  * <i> return __existing
24
27
  * <i> }
25
28
  * <i> const __csrEl = createComponent('<C>', <props>, <key>)
26
29
  * <i> {<each nested initChild + optional createEffect>}
30
+ * <i> {<each row event: qsa + addEventListener>}
27
31
  * <i> <stringifyReactiveEffects on __csrEl if reactiveEffects>
32
+ * <i> {<each row ref: qsa + callback invocation>}
28
33
  * <i> return __csrEl
29
34
  * <i>})
30
35
  *
@@ -35,7 +40,8 @@
35
40
  import { stringifyReactiveEffects } from './reactive-effects.ts'
36
41
  import type { ComponentLoopPlan, NestedComponentInit } from '../plan/types.ts'
37
42
  import { nameForRegistryRef } from '../../component-scope.ts'
38
- import { stringifyChildrenTextEffect } from '../shared.ts'
43
+ import { stringifyChildrenTextEffect, emitRowEventListener } from '../shared.ts'
44
+ import { emitLoopChildRefs } from './loop.ts'
39
45
 
40
46
  export function stringifyComponentLoop(lines: string[], plan: ComponentLoopPlan): void {
41
47
  const {
@@ -50,6 +56,8 @@ export function stringifyComponentLoop(lines: string[], plan: ComponentLoopPlan)
50
56
  componentPropsExpr,
51
57
  keyExpr,
52
58
  nestedComps,
59
+ rowEvents,
60
+ childRefs,
53
61
  reactiveEffects,
54
62
  profileLoopId,
55
63
  mapPreambleWrapped,
@@ -77,7 +85,11 @@ export function stringifyComponentLoop(lines: string[], plan: ComponentLoopPlan)
77
85
  // exactly the `<Chip><a href={...}>...</a></Chip>` shape: `<a>` isn't a
78
86
  // component, so `nestedComps` was always empty, and the "simple" path
79
87
  // never even looked at `reactiveEffects`.
80
- if (nestedComps.length === 0 && !reactiveEffects) {
88
+ //
89
+ // #3607: the same holds for a handler on a forwarded element — it needs
90
+ // the row element to attach to, and (#3612) for a `ref` callback on one —
91
+ // it needs the row element to look the target up in.
92
+ if (nestedComps.length === 0 && !reactiveEffects && rowEvents.length === 0 && childRefs.length === 0) {
81
93
  lines.push(` if (__existing) { initChild('${scopedComp}', __existing, ${componentPropsExpr}); return __existing }`)
82
94
  lines.push(` return createComponent('${scopedComp}', ${componentPropsExpr}, ${keyExpr})`)
83
95
  lines.push(` }, '${markerId}'${loopBfId})`)
@@ -88,18 +100,26 @@ export function stringifyComponentLoop(lines: string[], plan: ComponentLoopPlan)
88
100
  lines.push(` if (__existing) {`)
89
101
  lines.push(` initChild('${scopedComp}', __existing, ${componentPropsExpr})`)
90
102
  for (const nc of nestedComps) emitNestedInit(lines, ' ', '__existing', nc)
103
+ for (const ev of rowEvents) emitRowEventListener(lines, ' ', '__existing', ev)
91
104
  if (reactiveEffects) {
92
105
  stringifyReactiveEffects(lines, reactiveEffects, { indent: ' ', elVar: '__existing' })
93
106
  }
107
+ // #3612: refs run last, as on the composite row (`stringifyCompositeLoop`),
108
+ // so the callback sees the row with its handlers and effects in place.
109
+ // A ref that portals its element is refused (BF064) inside a child
110
+ // component's forwarded children, so no row portal claim is needed here.
111
+ emitLoopChildRefs(lines, childRefs, { indent: ' ', elVar: '__existing', bodyIsMultiRoot: false, containerVar })
94
112
  lines.push(` return __existing`)
95
113
  lines.push(` }`)
96
114
 
97
115
  // CSR side
98
116
  lines.push(` const __csrEl = createComponent('${scopedComp}', ${componentPropsExpr}, ${keyExpr})`)
99
117
  for (const nc of nestedComps) emitNestedInit(lines, ' ', '__csrEl', nc)
118
+ for (const ev of rowEvents) emitRowEventListener(lines, ' ', '__csrEl', ev)
100
119
  if (reactiveEffects) {
101
120
  stringifyReactiveEffects(lines, reactiveEffects, { indent: ' ', elVar: '__csrEl' })
102
121
  }
122
+ emitLoopChildRefs(lines, childRefs, { indent: ' ', elVar: '__csrEl', bodyIsMultiRoot: false, containerVar })
103
123
  lines.push(` return __csrEl`)
104
124
  lines.push(` }, '${markerId}'${loopBfId})`)
105
125
  }
@@ -32,6 +32,7 @@ import type { ConstantInfo, MemoInfo, SignalInfo } from '../types.ts'
32
32
  import type { BindingScope } from '../scope/binding-scope.ts'
33
33
  import { resolveAliasOrigin } from '../props-binding.ts'
34
34
  import { signalSecondBinding } from '../signal-initializer.ts'
35
+ import { isAssignmentTargetIdentifier } from '../assignment-target.ts'
35
36
 
36
37
  /**
37
38
  * CSR-substituted const value: the const's initializer with every
@@ -141,9 +142,9 @@ export function csrSubstitute(
141
142
  value: string,
142
143
  env: CsrEnv,
143
144
  enclosingScope?: BindingScope,
144
- ): { rewritten: string; freeIdentifiers: ReadonlySet<string> } {
145
+ ): CsrSubstituteResult {
145
146
  if (!value || value.trim().length === 0) {
146
- return { rewritten: value, freeIdentifiers: new Set() }
147
+ return { rewritten: value, freeIdentifiers: new Set(), writes: new Set() }
147
148
  }
148
149
 
149
150
  // Fixed-point iteration handles substitutions whose replacements
@@ -153,22 +154,39 @@ export function csrSubstitute(
153
154
  const maxIter = env.substitutions.size + 1
154
155
  let current = value
155
156
  let lastFreeIdentifiers: ReadonlySet<string> = new Set()
157
+ const writes = new Set<string>()
156
158
  for (let i = 0; i < maxIter; i++) {
157
159
  const step = csrSubstituteOnce(current, env, enclosingScope)
158
160
  lastFreeIdentifiers = step.freeIdentifiers
161
+ for (const name of step.writes) writes.add(name)
159
162
  if (step.rewritten === current) break
160
163
  current = step.rewritten
161
164
  }
162
- return { rewritten: current, freeIdentifiers: lastFreeIdentifiers }
165
+ return { rewritten: current, freeIdentifiers: lastFreeIdentifiers, writes }
166
+ }
167
+
168
+ /**
169
+ * `csrSubstitute`'s result. `writes` names the free identifiers the
170
+ * expression assigns or updates (`++nextId`, `start += 1`, `[a, b] = …`),
171
+ * including those inside a spliced memo body or a nested arrow. Such a name
172
+ * is never substituted (`++(0)` is a SyntaxError) and the template lambda,
173
+ * which runs at module scope, has no binding to write, so a caller treats a
174
+ * non-empty set like an unsafe local: the template leaves the position to
175
+ * init.
176
+ */
177
+ export interface CsrSubstituteResult {
178
+ rewritten: string
179
+ freeIdentifiers: ReadonlySet<string>
180
+ writes: ReadonlySet<string>
163
181
  }
164
182
 
165
183
  function csrSubstituteOnce(
166
184
  value: string,
167
185
  env: CsrEnv,
168
186
  enclosingScope?: BindingScope,
169
- ): { rewritten: string; freeIdentifiers: ReadonlySet<string> } {
187
+ ): CsrSubstituteResult {
170
188
  if (!value || value.trim().length === 0) {
171
- return { rewritten: value, freeIdentifiers: new Set() }
189
+ return { rewritten: value, freeIdentifiers: new Set(), writes: new Set() }
172
190
  }
173
191
  const sourceFile = ts.createSourceFile(
174
192
  '__csr_substitute__.ts',
@@ -179,7 +197,7 @@ function csrSubstituteOnce(
179
197
  )
180
198
  const stmt = sourceFile.statements[0]
181
199
  if (!stmt || !ts.isExpressionStatement(stmt)) {
182
- return { rewritten: value, freeIdentifiers: extractFreeIdentifiersFromText(value) }
200
+ return { rewritten: value, freeIdentifiers: extractFreeIdentifiersFromText(value), writes: new Set() }
183
201
  }
184
202
  const exprNode = ts.isParenthesizedExpression(stmt.expression)
185
203
  ? stmt.expression.expression
@@ -192,6 +210,7 @@ function csrSubstituteOnce(
192
210
 
193
211
  type Splice = { start: number; end: number; text: string }
194
212
  const splices: Splice[] = []
213
+ const writes = new Set<string>()
195
214
 
196
215
  // Track the bound names in nested arrow/function scopes so we don't
197
216
  // substitute identifiers shadowed by a parameter or local binding.
@@ -218,6 +237,34 @@ function csrSubstituteOnce(
218
237
  const bareReplacementText = (sub: CsrSubstitution): string =>
219
238
  sub.kind === 'call' ? `(() => (${sub.replacement}))` : `(${sub.replacement})`
220
239
 
240
+ // The substitution for a free reference `id`, or undefined. A written
241
+ // name (`++nextId`, `({ x } = obj)`) is recorded in `writes` and never
242
+ // substituted: a value is not an assignment target (`++(0)` is a
243
+ // SyntaxError).
244
+ const readSubstitution = (id: ts.Identifier): CsrSubstitution | undefined => {
245
+ if (isBound(id.text)) return undefined
246
+ if (isAssignmentTargetIdentifier(id)) {
247
+ if (!isFunctionLocal(id.text)) writes.add(id.text)
248
+ return undefined
249
+ }
250
+ return env.substitutions.get(id.text)
251
+ }
252
+
253
+ // Every name a function inside `value` declares anywhere in its body
254
+ // (`for (let i …)`, a nested block's `let`, a catch variable), innermost
255
+ // last. `boundStack` binds only a body's top-level declarations, which
256
+ // is all substitution needs; a write to one of these is the function's
257
+ // own, never a write to a component binding.
258
+ const functionLocalStack: Array<Set<string>> = []
259
+ const isFunctionLocal = (name: string): boolean => functionLocalStack.some(frame => frame.has(name))
260
+ const collectFunctionLocals = (n: ts.Node, out: Set<string>): void => {
261
+ ts.forEachChild(n, child => {
262
+ if (ts.isVariableDeclaration(child)) collectBindingNames(child.name, out)
263
+ else if (ts.isFunctionDeclaration(child) && child.name) out.add(child.name.text)
264
+ if (!ts.isFunctionLike(child)) collectFunctionLocals(child, out)
265
+ })
266
+ }
267
+
221
268
  const collectBindingNames = (name: ts.BindingName, out: Set<string>): void => {
222
269
  if (ts.isIdentifier(name)) out.add(name.text)
223
270
  else if (ts.isObjectBindingPattern(name)) {
@@ -286,18 +333,16 @@ function csrSubstituteOnce(
286
333
  // `call`-kind entry needs the thunk form too (#2924) — same as the
287
334
  // bare-identifier branch below.
288
335
  if (ts.isShorthandPropertyAssignment(node)) {
289
- if (ts.isIdentifier(node.name) && !isBound(node.name.text)) {
290
- const sub = env.substitutions.get(node.name.text)
291
- if (sub) {
292
- // The shorthand expands to a key-value pair when we substitute,
293
- // so emit `name: (replacement)` to keep the object literal
294
- // grammatical. Position spans the whole shorthand.
295
- splices.push({
296
- start: node.getStart(sourceFile) - OFFSET,
297
- end: node.getEnd() - OFFSET,
298
- text: `${node.name.text}: ${bareReplacementText(sub)}`,
299
- })
300
- }
336
+ const sub = readSubstitution(node.name)
337
+ if (sub) {
338
+ // The shorthand expands to a key-value pair when we substitute,
339
+ // so emit `name: (replacement)` to keep the object literal
340
+ // grammatical. Position spans the whole shorthand.
341
+ splices.push({
342
+ start: node.getStart(sourceFile) - OFFSET,
343
+ end: node.getEnd() - OFFSET,
344
+ text: `${node.name.text}: ${bareReplacementText(sub)}`,
345
+ })
301
346
  }
302
347
  return
303
348
  }
@@ -321,8 +366,12 @@ function csrSubstituteOnce(
321
366
  if (node.body && ts.isBlock(node.body)) {
322
367
  collectBlockDeclarations(node.body, bound)
323
368
  }
369
+ const locals = new Set(bound)
370
+ collectFunctionLocals(node.body, locals)
324
371
  boundStack.push(bound)
325
- if (node.body) visit(node.body)
372
+ functionLocalStack.push(locals)
373
+ visit(node.body)
374
+ functionLocalStack.pop()
326
375
  boundStack.pop()
327
376
  return
328
377
  }
@@ -340,8 +389,7 @@ function csrSubstituteOnce(
340
389
  // getter) substitutes to a thunk over its value here, not the value
341
390
  // itself — the bare form is the accessor, not a read of it (#2924).
342
391
  if (ts.isIdentifier(node)) {
343
- if (isBound(node.text)) return
344
- const sub = env.substitutions.get(node.text)
392
+ const sub = readSubstitution(node)
345
393
  if (sub) {
346
394
  splices.push({
347
395
  start: node.getStart(sourceFile) - OFFSET,
@@ -396,7 +444,7 @@ function csrSubstituteOnce(
396
444
  if (enclosingScope.isBound(name)) freeIdentifiers.delete(name)
397
445
  }
398
446
  }
399
- return { rewritten, freeIdentifiers }
447
+ return { rewritten, freeIdentifiers, writes }
400
448
  }
401
449
 
402
450
  export function extractFreeIdentifiersFromText(text: string): Set<string> {
@@ -17,7 +17,7 @@ import { toLocaleDatePlugin, foldedArgToClientJs } from '../to-locale-date-lower
17
17
  import { tsNodeToParsedExpr } from '../expression-parser.ts'
18
18
  import type { LoweringMatcher } from '../lowering-registry.ts'
19
19
  import { rewriteBarePropRefs } from '../prop-rewrite.ts'
20
- import { livePropReadExpr } from '../props-binding.ts'
20
+ import { livePropReadExpr, keepsDeclaredValue } from '../props-binding.ts'
21
21
 
22
22
  /**
23
23
  * Profile mode (#1690, SR3/SR4): the id appended to a DOM-binding effect so the
@@ -327,7 +327,7 @@ export function rewriteDestructuredPropsInExpr(expr: string, ctx: ClientJsContex
327
327
  const propAliases = new Map<string, string>()
328
328
  const propsByName = new Map<string, ClientJsContext['propsParams'][number]>()
329
329
  for (const prop of ctx.propsParams) {
330
- if (isChildrenPropParam(prop)) continue
330
+ if (isChildrenPropParam(prop) || !keepsDeclaredValue(prop)) continue
331
331
  propNames.add(prop.name)
332
332
  propsByName.set(prop.name, prop)
333
333
  // `_p` is always keyed by the caller-facing name (#2524 CSR half).
@@ -14,6 +14,7 @@ import { csrSubstitute, type CsrEnv } from './csr-substitute.ts'
14
14
  import { markupSlotIdsOf } from './markup-slots.ts'
15
15
  import { nameForRegistryRef } from './component-scope.ts'
16
16
  import { resolveRestSpreadNames } from './prop-handling.ts'
17
+ import { writesAnyBinding } from '../props-binding.ts'
17
18
 
18
19
  /**
19
20
  * Resolve chained references within a constants map.
@@ -191,7 +192,11 @@ export function emitRegistrationAndHydration(
191
192
 
192
193
  // Build ComponentDef object for hydrate()
193
194
  const defParts: string[] = [`init: ${initFunctionName(name)}`]
194
- if (canGenerateStaticTemplate(_ir.root, reactiveGetterNames, inlinableConstants, unsafeLocalNames)) {
195
+ // A component that writes a binding (`writesAnyBinding`) always takes the
196
+ // CSR template below: only that emitter checks each expression for a
197
+ // write (`csrSubstitute`'s `writes`) and leaves it to init, so no template
198
+ // path can carry `++start` into module scope, where `start` does not exist.
199
+ if (!writesAnyBinding(ctx) && canGenerateStaticTemplate(_ir.root, reactiveGetterNames, inlinableConstants, unsafeLocalNames)) {
195
200
  const markupSlotIds = markupSlotIdsOf(ctx)
196
201
  const templateHtml = irToComponentTemplate(_ir.root, inlinableConstants, restSpreadNames, ctx.propsObjectName, markupSlotIds, ctx.restPropsName)
197
202
  if (templateHtml) {