@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
package/src/analyzer.ts CHANGED
@@ -10,9 +10,10 @@ import ts from 'typescript'
10
10
  import { foldRenderReassignmentsInSource } from './fold-render-reassignments.ts'
11
11
  import { CLIENT_DIRECTIVE_INTERIOR_RE, USE_CLIENT_DIRECTIVE, isUseClientDirectiveText } from './directives.ts'
12
12
  import type { ImportSpecifier, TypeInfo, ParamInfo, PropDefaultPart, PropDefaultRead, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation, SignalFactoryCall, MemoInfo } from './types.ts'
13
- import { parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr, stringifyParsedExpr, type ParsedExpr } from './expression-parser.ts'
13
+ import { CALLBACK_METHODS, parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr, stringifyParsedExpr, type ParsedExpr } from './expression-parser.ts'
14
14
  import type { CallbackBodyAcceptor } from './adapters/interface.ts'
15
- import { rewriteBarePropRefs, splitScopedValueRefs } from './prop-rewrite.ts'
15
+ import { collectAssignmentTargets, rewriteBarePropRefs, splitScopedValueRefs } from './prop-rewrite.ts'
16
+ import { isEventHandlerName } from './event-handler-name.ts'
16
17
  import { buildPropAliasMap, coalesceDefaultText, livePropReadExpr, signalPropSeed } from './props-binding.ts'
17
18
  import { incrementCounter } from './instrumentation.ts'
18
19
  import {
@@ -4705,6 +4706,7 @@ function validateContext(ctx: AnalyzerContext): void {
4705
4706
  // `localConstants` binding after its declaration — flag those bindings so
4706
4707
  // downstream inlining never re-embeds their stale initializer text (#2910).
4707
4708
  markMutatedConstants(ctx)
4709
+ markWrittenBindings(ctx)
4708
4710
 
4709
4711
  // BF052: init statements that write to an identifier with no visible
4710
4712
  // declaration cause a ReferenceError in ESM strict mode. Flag them
@@ -5013,6 +5015,285 @@ function markMutatedConstants(ctx: AnalyzerContext): void {
5013
5015
  }
5014
5016
  }
5015
5017
 
5018
+ /**
5019
+ * Flag the component-scope bindings the component writes anywhere in its
5020
+ * body, nested functions and markup included (`collectAssignmentTargets`),
5021
+ * which `markMutatedConstants` does not see: it reads only the top-level
5022
+ * statements, up to the first nested function.
5023
+ *
5024
+ * - Every written binding gets `reassigned` (`ParamInfo` and
5025
+ * `ConstantInfo` alike), so it fails `keepsDeclaredValue`: it is a local
5026
+ * the component owns, never rewritten into a live prop read (`++start`
5027
+ * would become `++(_p.start ?? 0)`, a SyntaxError).
5028
+ * - A `localConstants` binding a write changes during render (a markup
5029
+ * expression, not an event handler) gets `mutatedAfterDeclaration`, like
5030
+ * a top-level statement's write: its declared value is no longer what a
5031
+ * later read sees, so nothing inlines it (`{++nextId}` would become
5032
+ * `++(0)`). A write in an event handler or another callback leaves the
5033
+ * declared value in place for render, so the binding stays inlinable.
5034
+ */
5035
+ function markWrittenBindings(ctx: AnalyzerContext): void {
5036
+ const body = ctx.componentNode?.body
5037
+ if (!body) return
5038
+ const params = ctx.propsObjectName === null ? ctx.propsParams.filter(p => !p.isRest) : []
5039
+ const names = new Set<string>([...params.map(p => p.name), ...ctx.localConstants.map(c => c.name)])
5040
+ if (names.size === 0) return
5041
+
5042
+ const { written, writingInitializers } = collectBindingWrites(ctx, body, names)
5043
+ for (const p of params) {
5044
+ if (written.has(p.name)) p.reassigned = true
5045
+ }
5046
+ for (const c of ctx.localConstants) {
5047
+ const when = written.get(c.name)
5048
+ if (when) c.reassigned = true
5049
+ // A const whose initializer writes (`const label = ++start`) must run
5050
+ // once, where it is declared: inlining its value anywhere else would
5051
+ // repeat the write, or carry it into the template's module scope.
5052
+ if (when === 'render' || writingInitializers.has(c.name)) c.mutatedAfterDeclaration = true
5053
+ }
5054
+ }
5055
+
5056
+ /**
5057
+ * Every write `markWrittenBindings` acts on, by binding: whether one runs
5058
+ * during render, and which top-level declarations' initializers write. A
5059
+ * markup write is reported (BF065) on the way.
5060
+ */
5061
+ function collectBindingWrites(
5062
+ ctx: AnalyzerContext,
5063
+ body: ts.Node,
5064
+ names: ReadonlySet<string>,
5065
+ ): { written: Map<string, 'render' | 'deferred'>; writingInitializers: Set<string | undefined> } {
5066
+ const written = new Map<string, 'render' | 'deferred'>()
5067
+ const writingInitializers = new Set<string | undefined>()
5068
+ const roots: readonly ts.Node[] = ts.isBlock(body) ? body.statements : [body]
5069
+ for (const root of roots) {
5070
+ for (const id of collectAssignmentTargets(root, names)) {
5071
+ const when = writeTiming(id, root)
5072
+ if (when === 'markup') reportMarkupWrite(ctx, id)
5073
+ if (when === 'statement') writingInitializers.add(declaredByInitializer(id, root))
5074
+ if (written.get(id.text) !== 'render') written.set(id.text, when === 'deferred' ? 'deferred' : 'render')
5075
+ }
5076
+ }
5077
+ return { written, writingInitializers }
5078
+ }
5079
+
5080
+ /**
5081
+ * When the write `id` (inside the component-body statement `root`) runs:
5082
+ * `'markup'` while a markup expression renders, `'statement'` while a
5083
+ * top-level statement runs (init runs it too), `'deferred'` later.
5084
+ * `markupTiming` decides a write that markup reaches; any other write keeps
5085
+ * the statement rule (`statementTiming`).
5086
+ */
5087
+ function writeTiming(id: ts.Identifier, root: ts.Node): 'markup' | 'statement' | 'deferred' {
5088
+ const inMarkup = markupTiming(id, root)
5089
+ return inMarkup === 'outside' ? statementTiming(id, root) : inMarkup
5090
+ }
5091
+
5092
+ /**
5093
+ * The one compositional rule for a write markup reaches. From the write
5094
+ * site, climb to the nearest enclosing function literal F:
5095
+ *
5096
+ * - none before a markup expression (`JsxExpression` / spread attribute):
5097
+ * the write runs while that expression renders — `'markup'`, an
5098
+ * event-handler attribute included (`onClick={(++id, () => {})}`);
5099
+ * - F found: follow how F's value is used (`valueUseOf`: parentheses,
5100
+ * casts, a conditional's branches, `&&` / `||` / `??`, a comma's last
5101
+ * operand, object / array literal members — not a spread, which runs
5102
+ * getters or iterates), then
5103
+ * - the callee of a call (an IIFE, `(c ? f : g)()`): F runs when that
5104
+ * call is evaluated — the same rule from the call;
5105
+ * - directly a JSX attribute's value (a child prop, a context value's
5106
+ * `setApi`, an event handler): handed on, it runs when the receiver
5107
+ * calls it — `'deferred'`;
5108
+ * - an argument of a call: `'deferred'` only when that call is, by the
5109
+ * same value walk and through further wrapper calls, an
5110
+ * event-handler attribute's value (`onClick={wrap(() => ++n)}`,
5111
+ * `onInput={debounce(…)}`); otherwise the callee may run it while
5112
+ * rendering (`Array.from(xs, () => ++n)`, `.map`, `.replace`), so
5113
+ * the same rule from the call;
5114
+ * - anything else (stored in a variable, a JSX child): the same rule
5115
+ * from where its value lands, so unknown use inside markup refuses.
5116
+ *
5117
+ * `'outside'` when the climb reaches the component-body statement without
5118
+ * meeting markup.
5119
+ */
5120
+ function markupTiming(site: ts.Node, root: ts.Node): 'markup' | 'deferred' | 'outside' {
5121
+ for (let n: ts.Node = site; n !== root && n.parent; n = n.parent) {
5122
+ const parent = n.parent
5123
+ if (ts.isJsxExpression(parent) || ts.isJsxSpreadAttribute(parent)) return 'markup'
5124
+ if (isFunctionScope(parent)) return functionUseTiming(parent, root)
5125
+ }
5126
+ return 'outside'
5127
+ }
5128
+
5129
+ function functionUseTiming(fn: ts.Node, root: ts.Node): 'markup' | 'deferred' | 'outside' {
5130
+ const { use, dropped } = valueWalk(fn)
5131
+ // A setter an object spread meets is neither copied nor called.
5132
+ if (dropped) return 'deferred'
5133
+ const parent = use.parent
5134
+ if (ts.isJsxExpression(parent) && ts.isJsxAttribute(parent.parent)) return 'deferred'
5135
+ if (ts.isCallExpression(parent) && parent.expression !== use && isEventHandlerValue(parent)) return 'deferred'
5136
+ return markupTiming(ts.isCallExpression(parent) ? parent : use, root)
5137
+ }
5138
+
5139
+ /** Whether `call` is, through value-passing wrappers and further calls, an event-handler attribute's value. */
5140
+ function isEventHandlerValue(call: ts.CallExpression): boolean {
5141
+ const use = valueUseOf(call)
5142
+ const parent = use.parent
5143
+ if (ts.isJsxExpression(parent) && ts.isJsxAttribute(parent.parent)) {
5144
+ return ts.isIdentifier(parent.parent.name) && isEventHandlerName(parent.parent.name.text)
5145
+ }
5146
+ return ts.isCallExpression(parent) && parent.expression !== use && isEventHandlerValue(parent)
5147
+ }
5148
+
5149
+ /**
5150
+ * The outermost expression that carries `node`'s value unchanged: through
5151
+ * parentheses, casts, a conditional's branches (not its condition), `&&` /
5152
+ * `||` / `??`, a comma's last operand, object / array literal members, and a
5153
+ * spread that copies it (`spreadPassesOn`).
5154
+ */
5155
+ function valueUseOf(node: ts.Node): ts.Node {
5156
+ return valueWalk(node).use
5157
+ }
5158
+
5159
+ /**
5160
+ * `valueUseOf`'s walk. `dropped`: the value is a setter an object spread
5161
+ * meets, which the spread neither copies nor calls.
5162
+ */
5163
+ function valueWalk(node: ts.Node): { use: ts.Node; dropped: boolean } {
5164
+ let v = node
5165
+ let member: ts.Node | undefined
5166
+ for (;;) {
5167
+ const p = v.parent
5168
+ if (!p) return { use: v, dropped: false }
5169
+ if (ts.isSpreadAssignment(p) || ts.isSpreadElement(p)) {
5170
+ const spread = spreadPassesOn(p, v, member)
5171
+ if (spread === 'dropped') return { use: v, dropped: true }
5172
+ if (spread === 'consumed') return { use: v, dropped: false }
5173
+ } else if (!passesValueOn(v)) {
5174
+ return { use: v, dropped: false }
5175
+ }
5176
+ if (ts.isObjectLiteralExpression(p)) member = v
5177
+ v = p
5178
+ }
5179
+ }
5180
+
5181
+ /**
5182
+ * What a spread does with its operand `v`, per JavaScript:
5183
+ *
5184
+ * - an object spread copies the operand literal's data properties and
5185
+ * methods (`'passes'`), calls its getters (`'consumed'`: the rule
5186
+ * applies from the spread site) and skips its setters (`'dropped'`);
5187
+ * `member` is the operand member the walk came through;
5188
+ * - an array or argument spread of an array literal copies its elements
5189
+ * (`'passes'`); of anything else it runs the operand's iterator, which may
5190
+ * run any function in it (`'consumed'`).
5191
+ */
5192
+ function spreadPassesOn(
5193
+ p: ts.SpreadAssignment | ts.SpreadElement,
5194
+ v: ts.Node,
5195
+ member: ts.Node | undefined,
5196
+ ): 'passes' | 'consumed' | 'dropped' {
5197
+ if (ts.isSpreadElement(p)) return ts.isArrayLiteralExpression(v) ? 'passes' : 'consumed'
5198
+ if (!ts.isObjectLiteralExpression(v)) return 'consumed'
5199
+ if (member && ts.isGetAccessorDeclaration(member)) return 'consumed'
5200
+ if (member && ts.isSetAccessorDeclaration(member)) return 'dropped'
5201
+ return 'passes'
5202
+ }
5203
+
5204
+ function passesValueOn(v: ts.Node): boolean {
5205
+ const p = v.parent
5206
+ if (ts.isParenthesizedExpression(p) || ts.isAsExpression(p) || ts.isSatisfiesExpression(p)) return true
5207
+ if (ts.isNonNullExpression(p) || ts.isTypeAssertionExpression(p)) return true
5208
+ if (ts.isConditionalExpression(p)) return p.condition !== v
5209
+ if (ts.isBinaryExpression(p)) return isValuePassingOperator(p, v)
5210
+ if (ts.isPropertyAssignment(p)) return p.initializer === v
5211
+ return ts.isObjectLiteralExpression(p) || ts.isArrayLiteralExpression(p)
5212
+ }
5213
+
5214
+ function isValuePassingOperator(p: ts.BinaryExpression, v: ts.Node): boolean {
5215
+ const op = p.operatorToken.kind
5216
+ if (op === ts.SyntaxKind.CommaToken) return p.right === v
5217
+ return op === ts.SyntaxKind.AmpersandAmpersandToken || op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken
5218
+ }
5219
+
5220
+ /**
5221
+ * The statement rule for a write no markup reaches: a top-level statement
5222
+ * runs during render (`'statement'`) unless a function encloses the write
5223
+ * that is not invoked where it stands (`isInvokedInPlace`) — `'deferred'`.
5224
+ * That only decides whether a later read may inline the binding's declared
5225
+ * value (`mutatedAfterDeclaration`).
5226
+ */
5227
+ function statementTiming(id: ts.Identifier, root: ts.Node): 'statement' | 'deferred' {
5228
+ for (let n: ts.Node = id; n !== root && n.parent; n = n.parent) {
5229
+ if (isFunctionScope(n.parent) && !isInvokedInPlace(n.parent)) return 'deferred'
5230
+ }
5231
+ return 'statement'
5232
+ }
5233
+
5234
+ /**
5235
+ * Whether a function literal outside markup is called where it stands: the
5236
+ * callee of a call (an IIFE, `(() => …)()`), or the callback of an array
5237
+ * iteration method, which calls it before returning (`xs.map(cb)`, the
5238
+ * higher-order methods of `CALLBACK_METHODS`, plus `forEach`). Any other
5239
+ * function there is deferred, which only decides whether a later read may
5240
+ * inline the binding's declared value (`mutatedAfterDeclaration`).
5241
+ */
5242
+ function isInvokedInPlace(fn: ts.Node): boolean {
5243
+ let node = fn
5244
+ while (ts.isParenthesizedExpression(node.parent)) node = node.parent
5245
+ const call = node.parent
5246
+ if (!ts.isCallExpression(call)) return false
5247
+ if (call.expression === node) return true
5248
+ return call.arguments[0] === node && isArrayIterationCallee(call.expression)
5249
+ }
5250
+
5251
+ /** `<receiver>.<method>` where `method` is an array iteration method that calls its callback in place. */
5252
+ function isArrayIterationCallee(callee: ts.Expression): boolean {
5253
+ if (!ts.isPropertyAccessExpression(callee)) return false
5254
+ const method = callee.name.text
5255
+ return CALLBACK_METHODS.has(method) || method === 'forEach'
5256
+ }
5257
+
5258
+ /**
5259
+ * The name a top-level declaration binds when the write `id` sits in its
5260
+ * initializer (`const label = ++start` → `label`), or undefined.
5261
+ */
5262
+ function declaredByInitializer(id: ts.Identifier, root: ts.Node): string | undefined {
5263
+ for (let n: ts.Node = id; n !== root && n.parent; n = n.parent) {
5264
+ const parent = n.parent
5265
+ if (ts.isVariableDeclaration(parent) && parent.initializer === n && ts.isIdentifier(parent.name)) return parent.name.text
5266
+ }
5267
+ return undefined
5268
+ }
5269
+
5270
+ /**
5271
+ * BF065: a client component's markup writes a component binding while it
5272
+ * renders (`{++nextId}`, a `.map()` row that increments a counter). A
5273
+ * callback the markup hands on (an event handler, a child prop, a context
5274
+ * value) is not: it runs when called. The client renders markup in two places that
5275
+ * cannot share that write: the client template, which runs at module scope
5276
+ * with no binding to write, and init, which re-evaluates only reactive
5277
+ * positions. A client-side mount would lose the written value, so the
5278
+ * shape is refused rather than rendered empty. A server-only component has
5279
+ * no client side and renders it as JavaScript does.
5280
+ */
5281
+ function reportMarkupWrite(ctx: AnalyzerContext, id: ts.Identifier): void {
5282
+ if (!ctx.hasUseClientDirective) return
5283
+ ctx.errors.push(
5284
+ createError(ErrorCodes.STAGE_WRITE_IN_MARKUP, getSourceLocation(id, ctx.sourceFile, ctx.filePath), {
5285
+ message:
5286
+ `The markup writes '${id.text}' while it renders. The client template cannot write a component binding, ` +
5287
+ 'so a client-side mount would lose the written value.',
5288
+ suggestion: {
5289
+ message:
5290
+ `Compute the value before the return (\`const label = ++${id.text}\`) and render that, ` +
5291
+ 'or keep the value in a signal and update it from an event handler.',
5292
+ },
5293
+ }),
5294
+ )
5295
+ }
5296
+
5016
5297
  function validateInitStatementReferences(ctx: AnalyzerContext): void {
5017
5298
  if (ctx.initStatements.length === 0) return
5018
5299
 
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Whether an identifier is WRITTEN by the expression that contains it.
3
+ *
4
+ * Every substitution the compiler performs over a parsed expression (a
5
+ * destructured prop's live read `_p.x ?? d`, a constant's inlined value, a
6
+ * signal's initial value in the client template) replaces a READ of a
7
+ * binding with an expression that produces its value. A write position
8
+ * cannot take that replacement: `++nextId` becomes `++(0)` and `start += 1`
9
+ * becomes `(_p.start ?? 0) += 1`, both a SyntaxError that breaks the whole
10
+ * client module. The substitution walks ask this predicate first and leave
11
+ * a written identifier alone; the caller then decides what a write to the
12
+ * binding means in its scope (a local in the init body, a template slot
13
+ * left to init).
14
+ *
15
+ * Needs a tree built with parent pointers (`setParentNodes`).
16
+ */
17
+
18
+ import ts from 'typescript'
19
+
20
+ /** `=`, and every compound assignment (`+=`, `??=`, `<<=`, …). */
21
+ function isAssignmentOperator(kind: ts.SyntaxKind): boolean {
22
+ return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment
23
+ }
24
+
25
+ /** Wrappers that keep their operand an assignment target: `(x) = 1`, `x! = 1`, `(x as T) = 1`. */
26
+ function isTransparentWrapper(n: ts.Node): boolean {
27
+ return (
28
+ ts.isParenthesizedExpression(n) ||
29
+ ts.isNonNullExpression(n) ||
30
+ ts.isAsExpression(n) ||
31
+ ts.isTypeAssertionExpression(n) ||
32
+ ts.isSatisfiesExpression(n)
33
+ )
34
+ }
35
+
36
+ /**
37
+ * The node one level up a destructuring-assignment pattern from `node`, or
38
+ * null when `parent` is not a pattern piece that keeps `node` a target: an
39
+ * array element or spread (`[x, ...rest] = …`), an object shorthand or
40
+ * property value (`({ x, k: y } = …)`), or an object spread.
41
+ */
42
+ function patternContainer(node: ts.Node, parent: ts.Node): ts.Node | null {
43
+ if (ts.isArrayLiteralExpression(parent) || ts.isObjectLiteralExpression(parent)) return parent
44
+ if (ts.isSpreadElement(parent) || ts.isSpreadAssignment(parent)) return parent
45
+ if (ts.isShorthandPropertyAssignment(parent) && parent.name === node) return parent
46
+ if (ts.isPropertyAssignment(parent) && parent.initializer === node) return parent
47
+ return null
48
+ }
49
+
50
+ /**
51
+ * True when `id` is the target of an assignment (`x = …`, `x += …`), an
52
+ * update (`++x`, `x--`), a destructuring assignment (`[x, y] = …`,
53
+ * `({ x } = …)`, `[x = 1] = …`) or a `for (x of …)` / `for (x in …)` head.
54
+ * A member write (`x.a = 1`, `x[i]++`) writes the object, not the binding,
55
+ * so `x` there is a read.
56
+ */
57
+ export function isAssignmentTargetIdentifier(id: ts.Identifier): boolean {
58
+ let node: ts.Node = id
59
+ let parent: ts.Node | undefined = id.parent
60
+ while (parent) {
61
+ if (isTransparentWrapper(parent)) {
62
+ node = parent
63
+ parent = parent.parent
64
+ continue
65
+ }
66
+ if (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) {
67
+ return parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken
68
+ }
69
+ if (ts.isBinaryExpression(parent)) {
70
+ return parent.left === node && isAssignmentOperator(parent.operatorToken.kind)
71
+ }
72
+ if ((ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.initializer === node) return true
73
+ const container = patternContainer(node, parent)
74
+ if (!container) return false
75
+ node = container
76
+ parent = container.parent
77
+ }
78
+ return false
79
+ }
@@ -12,7 +12,7 @@
12
12
 
13
13
  import ts from 'typescript'
14
14
 
15
- import type { ComponentIR, IRMetadata, IRNode, IRElement, TypeInfo } from './types.ts'
15
+ import type { ComponentIR, IRMetadata, IRNode, IRElement, IRTemplatePart, TypeInfo } from './types.ts'
16
16
  import { isBooleanAttr } from './html-constants.ts'
17
17
 
18
18
  /**
@@ -290,10 +290,10 @@ export function augmentInheritedPropAccesses(ir: ComponentIR): void {
290
290
  // component renders it. Classify these reads as nillable (`unknown`)
291
291
  // unless a `?? <literal>` pins a concrete type.
292
292
  for (const prop of (node as unknown as { props?: IRElement['attrs'] }).props ?? []) {
293
- const v = prop.value as { kind?: string; expr?: string; parts?: Array<{ type: string } & Record<string, string>> }
293
+ const v = prop.value as { kind?: string; expr?: string; parts?: IRTemplatePart[] }
294
294
  if (v?.parts) {
295
295
  for (const part of v.parts) {
296
- if (part.type === 'string') scan(part.value)
296
+ if (part.type === 'expression') scan(part.expr)
297
297
  else if (part.type === 'ternary') {
298
298
  scan(part.condition)
299
299
  scan(part.whenTrue)
@@ -311,11 +311,7 @@ export function augmentInheritedPropAccesses(ir: ComponentIR): void {
311
311
  kind?: string
312
312
  expr?: string
313
313
  presenceOrUndefined?: boolean
314
- parts?: Array<
315
- | { type: 'string'; value: string }
316
- | { type: 'ternary'; condition: string; whenTrue: string; whenFalse: string }
317
- | { type: 'lookup'; key: string }
318
- >
314
+ parts?: IRTemplatePart[]
319
315
  }
320
316
  // Template-literal attr values (`className={\`… \${props.className ??
321
317
  // ''}\`}`) carry their `props.X` reads inside the parts structure,
@@ -324,7 +320,7 @@ export function augmentInheritedPropAccesses(ir: ComponentIR): void {
324
320
  // textual field of every part shape.
325
321
  if (v?.parts) {
326
322
  for (const part of v.parts) {
327
- if (part.type === 'string') scan(part.value)
323
+ if (part.type === 'expression') scan(part.expr)
328
324
  else if (part.type === 'ternary') {
329
325
  scan(part.condition)
330
326
  scan(part.whenTrue)
@@ -174,10 +174,10 @@ function collectAndPrefixAttrs(
174
174
  break
175
175
  case 'template': {
176
176
  prefixIRTemplateParts(attr.value.parts, layerName)
177
- // Extract constant references from ${expr} in string parts
177
+ // Extract constant references from expression parts
178
178
  for (const part of attr.value.parts) {
179
- if (part.type === 'string' && part.value.includes('${')) {
180
- collectConstantRefs(part.value, referencedConstants, constantNames)
179
+ if (part.type === 'expression') {
180
+ collectConstantRefs(part.expr, referencedConstants, constantNames)
181
181
  }
182
182
  }
183
183
  break
@@ -211,8 +211,7 @@ function prefixIRTemplateParts(parts: IRTemplatePart[], layerName: string): void
211
211
  if (part.type === 'ternary') {
212
212
  part.whenTrue = prefixClassString(part.whenTrue, layerName)
213
213
  part.whenFalse = prefixClassString(part.whenFalse, layerName)
214
- } else if (part.type === 'string' && !part.value.includes('${')) {
215
- // Only prefix pure static text (no ${expr} references)
214
+ } else if (part.type === 'string') {
216
215
  part.value = prefixClassString(part.value, layerName)
217
216
  }
218
217
  }
package/src/debug.ts CHANGED
@@ -2365,6 +2365,7 @@ function attrValueToString(value: AttrValue): string | null {
2365
2365
  case 'template':
2366
2366
  return value.parts
2367
2367
  .map(p => {
2368
+ if (p.type === 'expression') return p.expr
2368
2369
  if (p.type === 'ternary') return `${p.condition} ${p.whenTrue} ${p.whenFalse}`
2369
2370
  if (p.type === 'lookup') return p.key
2370
2371
  return ''
package/src/errors.ts CHANGED
@@ -181,6 +181,15 @@ export const ErrorCodes = {
181
181
  // back to its row, so its delegated event handlers would stop running
182
182
  // after hydration (#3318). A keyed top-level row is supported.
183
183
  ROW_PORTAL_UNPAIRABLE: 'BF064',
184
+ // A `'use client'` component's markup writes a component binding while it
185
+ // renders (`{++nextId}`, a `.map()` row incrementing a counter, a
186
+ // callback any call in the markup may run in place), outside a function
187
+ // the markup hands on (an attribute / prop value, or a wrapped event
188
+ // handler; `markupTiming`). The client template runs at module scope
189
+ // and cannot write the binding, and init re-evaluates only reactive
190
+ // positions, so a client-side mount would silently lose the written
191
+ // value. Refused instead (`markWrittenBindings`, analyzer.ts).
192
+ STAGE_WRITE_IN_MARKUP: 'BF065',
184
193
 
185
194
  // Inline JSX-callback synthesis errors (BF080-BF089) — raised by the
186
195
  // preprocess-inline-jsx-callbacks pass (#1211) when an inline JSX-
@@ -320,6 +329,8 @@ const errorMessages: Record<ErrorCode, string> = {
320
329
 
321
330
  [ErrorCodes.ROW_PORTAL_UNPAIRABLE]:
322
331
  'A ref callback portals an element out of a .map() row that hydration cannot pair with the element (the row root itself, a nested or unkeyed loop, an element inside a reactive conditional in the row, or an element inside a child component\'s children), so its event handlers would stop running after hydration.',
332
+ [ErrorCodes.STAGE_WRITE_IN_MARKUP]:
333
+ "A client component's markup writes a component binding while it renders (an assignment or ++/-- outside an event handler), which the client template cannot reproduce.",
323
334
 
324
335
  [ErrorCodes.INLINE_JSX_CALLBACK_CAPTURE]:
325
336
  "Inline JSX-returning arrow function captures a non-module identifier. Extract the callback into a top-level 'use client' component (e.g. `function MyNode(n) { return <div/> }` then `renderNode={MyNode}`) or pass captured values via component props.",
package/src/index.ts CHANGED
@@ -108,7 +108,13 @@ export { generateModuleExports, extractFunctionParams, formatParamWithType, find
108
108
  // Adapters
109
109
  export { BaseAdapter } from './adapters/interface.ts'
110
110
  export { DslTemplateAdapter } from './adapters/dsl-template-adapter.ts'
111
- export type { TemplateIdentifierSpelling } from './adapters/dsl-template-adapter.ts'
111
+ export type {
112
+ LoopPlanSpelling,
113
+ LoopRefusalSpelling,
114
+ LoopRow,
115
+ LoopRowSpelling,
116
+ TemplateIdentifierSpelling,
117
+ } from './adapters/dsl-template-adapter.ts'
112
118
  // Dependency-free adapter for tooling that only needs client JS (e.g. the
113
119
  // profiler scenario driver) — the client output is adapter-independent.
114
120
  export { TestAdapter, testAdapter } from './adapters/test-adapter.ts'
@@ -152,6 +158,7 @@ export {
152
158
  emitCallbackEval,
153
159
  isPredicateMethod,
154
160
  lowerCallbackMethod,
161
+ lowerSortComparator,
155
162
  nestedCallbackRefusal,
156
163
  filterPredicateShapeRefusal,
157
164
  missingFilterPredicateRefusal,
@@ -168,6 +175,7 @@ export type {
168
175
  CallbackLoweringOptions,
169
176
  CallbackPlan,
170
177
  PredicateMethod,
178
+ SortPlan,
171
179
  } from './adapters/callback-method.ts'
172
180
  export type {
173
181
  ArrayMethodArg,
@@ -181,12 +189,23 @@ export type {
181
189
  export { derivesScopeFromSlot } from './adapters/child-scope.ts'
182
190
  export { childTemplateName, componentPropKey, isEmptyComponentProps, planComponentProps, propsSpreadParam, resolveComponentPropKeys, spellComponentProps } from './adapters/component-props.ts'
183
191
  export type { ComponentPropEntry, ComponentPropSegment, ComponentPropSpelling, ComponentPropsOptions, ComponentPropsParam, EarlierComponentProps, ResolvedComponentProp, SpelledComponentPropSegment } from './adapters/component-props.ts'
184
- export { parseUndefinedAlternateTernary, planAttrExpression, planSpreadAttr, unsupportedAttrExpression, unsupportedAttrExpressionError } from './adapters/attr-plan.ts'
192
+ export { parseUndefinedAlternateTernary, planAttrExpression, planSpreadAttr, } from './adapters/attr-plan.ts'
185
193
  export type { AttrExpressionPlan, AttrPlanContext, SpreadAttrPlan, SpreadPlanContext, UndefinedAlternateTernary } from './adapters/attr-plan.ts'
186
- export { planLoop } from './adapters/loop-plan.ts'
194
+ export { loopHeaderTargets, planLoop, savedLoopBindings, spellDestructureLocals, spellFilteredRow, spellSortedSource } from './adapters/loop-plan.ts'
187
195
  export { computedConstContext, inlineComputedConstAttr, inlineComputedConsts } from './adapters/computed-const.ts'
188
196
  export type { ComputedConstContext } from './adapters/computed-const.ts'
189
- export type { LoopPlan, LoopPlanContext } from './adapters/loop-plan.ts'
197
+ export type {
198
+ DestructureSpelling,
199
+ DestructureValue,
200
+ LoopFilterPlan,
201
+ LoopFilterPredicate,
202
+ LoopFilterSpelling,
203
+ LoopPlan,
204
+ LoopPlanContext,
205
+ LoopRowScopes,
206
+ LoopSortSpelling,
207
+ SavedLoopBinding,
208
+ } from './adapters/loop-plan.ts'
190
209
  export { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from './static-literal.ts'
191
210
  export {
192
211
  arithmeticOperandIsNull,
@@ -480,7 +480,7 @@ function populateCsrInlinable(
480
480
  // sees `props.X` and can detect bridged-arg calls. The final
481
481
  // emit-time substitution applies the bare-prop rewrite.
482
482
  const source = c.value!.trim()
483
- const { rewritten, freeIdentifiers } = csrSubstitute(source, env)
483
+ const { rewritten, freeIdentifiers, writes } = csrSubstitute(source, env)
484
484
 
485
485
  // If the rewrite still references any unresolved local constant
486
486
  // by name, defer to a later iteration — its substitution may
@@ -505,7 +505,7 @@ function populateCsrInlinable(
505
505
  // `rewritePropsObjectRef` doesn't need to redo the AST work. The
506
506
  // free identifiers are re-extracted from the bridged form so
507
507
  // the post-substitution unsafe-name check stays exact.
508
- const bridgedRewritten = bridgedCsrForm(rewritten, source, env, relocateEnv, receivers)
508
+ const bridgedRewritten = bridgedCsrForm(rewritten, writes, source, env, relocateEnv, receivers)
509
509
  if (bridgedRewritten === null) {
510
510
  ctx.csrInlinable.set(c.name, null)
511
511
  } else {
@@ -552,15 +552,18 @@ function hasNoCsrSubstitute(c: ConstantInfo): boolean {
552
552
 
553
553
  /**
554
554
  * The bridged CSR form of a const whose substituted text is `rewritten`, or
555
- * null when it isn't safe in template scope.
555
+ * null when it isn't safe in template scope. A value that writes a binding
556
+ * (`writes`, see `csrSubstitute`) runs only where it is declared.
556
557
  */
557
558
  function bridgedCsrForm(
558
559
  rewritten: string,
560
+ writes: ReadonlySet<string>,
559
561
  source: string,
560
562
  env: CsrEnv,
561
563
  relocateEnv: RelocateEnv,
562
564
  receivers: ReturnType<typeof inlinedReceiverCheck>,
563
565
  ): string | null {
566
+ if (writes.size > 0) return null
564
567
  const inlineResult = isInlinableInTemplate(rewritten, relocateEnv)
565
568
  return inlineResult.ok ? inlineResult.rewrittenValue : receivers.check(source, env)
566
569
  }
@@ -633,7 +636,7 @@ function collectTemplateRiskyNames(irRoot: IRNode): Set<string> {
633
636
  // Mirror the emitter's input source for each template position
634
637
  // (`transformExpr` in html-template.ts uses `templateExpr ?? expr`).
635
638
  // The `template*` rewrites — bare prop refs to `_p.X`, plus
636
- // `IRTemplateLiteral` parts' `templateValue`/`templateCondition`/
639
+ // `IRTemplateLiteral` parts' `templateExpr`/`templateCondition`/
637
640
  // `templateKey` — are what `transformExpr` actually substitutes
638
641
  // through, so the diagnostic gate needs to look at the same string.
639
642
  // Reading the raw form would drift from emission and could miss /
@@ -28,6 +28,7 @@ import {
28
28
  buildChildRefBindings,
29
29
  hasReactiveLoopBindings,
30
30
  buildChildrenTextEffect,
31
+ buildRowEventBinding,
31
32
  } from '../shared.ts'
32
33
  import { irChildrenToJsExpr, renderPreamble } from '../../html-template.ts'
33
34
  import { buildReactiveEffectsPlan } from './build-reactive-effects.ts'
@@ -138,6 +139,18 @@ export function buildComponentLoopPlan(elem: TopLevelLoop, profileComponentName?
138
139
  : elem.bindings.reactiveTexts
139
140
  const hasReactiveEffects = hasReactiveLoopBindings({ ...elem.bindings, reactiveTexts: rowReactiveTexts })
140
141
 
142
+ // #3607: an event on an element forwarded as the root component's own
143
+ // `children` is collected into `elem.bindings.events` by the same
144
+ // `collectLoopChildBindings` walk as the reactive attrs/texts above, and
145
+ // was dropped here the same way they were before #3143. A component-root
146
+ // loop has no delegation pass (`loopEventDelegationVariant` returns null
147
+ // for it), so each row attaches its handlers directly, exactly like the
148
+ // composite row's `outerEvents`. Events inside an inner loop of the
149
+ // forwarded children (`nestedLoops` non-empty) are not reached here.
150
+ const rowEvents = elem.bindings.events
151
+ .filter(ev => ev.nestedLoops.length === 0)
152
+ .map(ev => buildRowEventBinding(ev, elem.param, elem.paramBindings, elem.index))
153
+
141
154
  return {
142
155
  kind: 'component',
143
156
  // Rows are createComponent-driven: a lowered HTML-string leaf passed as a
@@ -156,11 +169,14 @@ export function buildComponentLoopPlan(elem: TopLevelLoop, profileComponentName?
156
169
  componentPropsExpr: propsExpr,
157
170
  keyExpr,
158
171
  nestedComps,
159
- // Refs on a component element (`<Comp ref={fn} />`) are not currently
160
- // wired here — the body root is the component, not a DOM element, so
161
- // the per-item factory has no `__el` handle to invoke. Still required
162
- // by the type so the structural invariant (every variant has a
163
- // `childRefs`) is preserved; populated as empty.
172
+ rowEvents,
173
+ // #3612: refs on elements forwarded as the root component's own
174
+ // `children` (`<Chip><input ref={el => …} /></Chip>`), collected by the
175
+ // same `collectLoopChildBindings` walk as `rowEvents` above and resolved
176
+ // with the same loop-param accessor rewrite. Each row (hydrated and
177
+ // client-built) invokes them against its own element. A `ref` on the
178
+ // root component element itself (`<Chip ref={fn} />`) is a prop, not a
179
+ // binding here: it goes to the component through `componentPropsExpr`.
164
180
  childRefs: buildChildRefBindings(elem.bindings.refs, elem.param, elem.paramBindings, elem.index),
165
181
  profileLoopId: profileComponentName ? `${profileComponentName}#binding:${elem.slotId}` : undefined,
166
182
  reactiveEffects: hasReactiveEffects