@barefootjs/jsx 0.39.0 → 0.39.2

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 (74) hide show
  1. package/dist/adapters/interface.d.ts +19 -0
  2. package/dist/adapters/interface.d.ts.map +1 -1
  3. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  4. package/dist/adapters/parsed-expr-emitter.d.ts +2 -2
  5. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  6. package/dist/analyzer.d.ts +19 -0
  7. package/dist/analyzer.d.ts.map +1 -1
  8. package/dist/compiler.d.ts.map +1 -1
  9. package/dist/debug.d.ts.map +1 -1
  10. package/dist/html-types.d.ts +5 -0
  11. package/dist/html-types.d.ts.map +1 -1
  12. package/dist/index.d.ts +2 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1455 -1139
  15. package/dist/ir-to-client-js/collect-elements.d.ts +17 -1
  16. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/reactivity.d.ts +10 -2
  18. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/safe-html.d.ts +1 -1
  20. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/utils.d.ts +11 -7
  22. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  23. package/dist/jsx-to-ir.d.ts.map +1 -1
  24. package/dist/literal-member-index.d.ts +6 -0
  25. package/dist/literal-member-index.d.ts.map +1 -0
  26. package/dist/scope/binding-scope.d.ts +11 -0
  27. package/dist/scope/binding-scope.d.ts.map +1 -1
  28. package/dist/signal-prop-name-collision.d.ts +20 -0
  29. package/dist/signal-prop-name-collision.d.ts.map +1 -0
  30. package/dist/ssr-defaults.d.ts.map +1 -1
  31. package/dist/ssr-seed-plan.d.ts +3 -2
  32. package/dist/ssr-seed-plan.d.ts.map +1 -1
  33. package/dist/types.d.ts +44 -0
  34. package/dist/types.d.ts.map +1 -1
  35. package/package.json +2 -2
  36. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +4 -4
  37. package/src/__tests__/adapter-output.test.ts +142 -0
  38. package/src/__tests__/binding-scope.test.ts +27 -0
  39. package/src/__tests__/client-template-escape-soundness.test.ts +17 -0
  40. package/src/__tests__/conditional-nested-loop-bindings.test.ts +41 -0
  41. package/src/__tests__/create-mutation.test.ts +30 -0
  42. package/src/__tests__/create-query.test.ts +52 -0
  43. package/src/__tests__/debug.test.ts +83 -0
  44. package/src/__tests__/destructured-from-props-localconst-value.test.ts +3 -2
  45. package/src/__tests__/ir-fragment-transparency.test.ts +23 -0
  46. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +245 -0
  47. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +80 -0
  48. package/src/__tests__/literal-member-index.test.ts +14 -0
  49. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +445 -0
  50. package/src/__tests__/signal-prop-name-collision.test.ts +171 -0
  51. package/src/__tests__/ssr-defaults.test.ts +6 -7
  52. package/src/__tests__/ssr-seed-plan.test.ts +23 -0
  53. package/src/__tests__/staged-ir/02-shadow-guards.test.ts +1 -1
  54. package/src/__tests__/staged-ir/08-relocate-unit.test.ts +6 -3
  55. package/src/adapters/interface.ts +19 -0
  56. package/src/adapters/jsx-adapter.ts +30 -20
  57. package/src/adapters/parsed-expr-emitter.ts +3 -3
  58. package/src/analyzer.ts +45 -11
  59. package/src/compiler.ts +78 -46
  60. package/src/debug.ts +34 -2
  61. package/src/html-types.ts +14 -0
  62. package/src/index.ts +2 -0
  63. package/src/ir-to-client-js/collect-elements.ts +72 -13
  64. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +112 -3
  65. package/src/ir-to-client-js/reactivity.ts +31 -1
  66. package/src/ir-to-client-js/safe-html.ts +19 -6
  67. package/src/ir-to-client-js/utils.ts +130 -15
  68. package/src/jsx-to-ir.ts +89 -14
  69. package/src/literal-member-index.ts +12 -0
  70. package/src/scope/binding-scope.ts +31 -1
  71. package/src/signal-prop-name-collision.ts +164 -0
  72. package/src/ssr-defaults.ts +13 -5
  73. package/src/ssr-seed-plan.ts +26 -3
  74. package/src/types.ts +47 -0
package/src/jsx-to-ir.ts CHANGED
@@ -40,7 +40,7 @@ import {
40
40
  isReactiveOrigin,
41
41
  AttrValueOf,
42
42
  } from './types.ts'
43
- import { type AnalyzerContext, type MultiReturnJsxInfo, getSourceLocation, collectReactiveGetterNames } from './analyzer-context.ts'
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, type ParsedExpr } from './expression-parser.ts'
45
45
  import type { IRLoopSort, FunctionInfo, ConstantInfo, ParamInfo } from './types.ts'
46
46
  import { formatParamWithType } from './module-exports.ts'
@@ -2207,7 +2207,7 @@ function isTransparentFragment(
2207
2207
  // Filter out whitespace-only text nodes
2208
2208
  const children = node.children.filter(child => {
2209
2209
  if (ts.isJsxText(child)) {
2210
- return child.text.trim() !== ''
2210
+ return cleanJsxWhitespace(child.text) !== ''
2211
2211
  }
2212
2212
  return true
2213
2213
  })
@@ -2375,11 +2375,15 @@ function transformChildren(
2375
2375
 
2376
2376
  const transformed = transformNode(child, ctx)
2377
2377
  if (transformed) {
2378
- // Skip empty text nodes
2379
- if (transformed.type === 'text' && transformed.value.trim() === '') {
2380
- continue
2381
- }
2382
-
2378
+ // `transformText` (the only producer of `type: 'text'` reached from
2379
+ // here — a `JsxText` child) already returns `null` for a node the
2380
+ // JSX whitespace rule says renders nothing, and keeps a node whose
2381
+ // cleaned value is a meaningful single space (`<b>a</b> <i>b</i>`,
2382
+ // #3237). Re-checking `.value.trim() === ''` here duplicated that
2383
+ // decision with a looser rule that silently discarded exactly that
2384
+ // meaningful space — the "one decision, two implementations"
2385
+ // pattern CLAUDE.md's Reference Adapter section calls out. Trust
2386
+ // the single source of truth instead of re-deciding here.
2383
2387
  result.push(transformed)
2384
2388
  }
2385
2389
  }
@@ -2427,10 +2431,25 @@ function isRenderNothingLiteral(expr: ts.Expression, ctx: TransformContext): boo
2427
2431
  }
2428
2432
 
2429
2433
  function transformText(node: ts.JsxText, ctx: TransformContext): IRText | null {
2430
- // Normalize whitespace (React-like behavior)
2431
- const text = node.text.replace(/\s+/g, ' ')
2432
-
2433
- if (text.trim() === '') {
2434
+ // Normalize whitespace the way JSX itself does (TypeScript/Babel/React
2435
+ // agree): a text node is split on line breaks, and only whitespace that
2436
+ // sits at a line break — the leading run of a non-first line, the
2437
+ // trailing run of a non-last line — is trimmed away; empty lines are
2438
+ // dropped and the rest are rejoined with a single space. Whitespace
2439
+ // that does NOT straddle a line break (interior runs on one line, or
2440
+ // the entirety of a single-line text node) is left exactly as written.
2441
+ // A naive `\s+` collapse over the whole node (the previous behavior)
2442
+ // over-trims: `<div>\n Light\n</div>` compiled to `" Light "` instead
2443
+ // of `"Light"` (#3237).
2444
+ const text = cleanJsxWhitespace(node.text)
2445
+
2446
+ // Empty STRING, not empty-after-trim: a single-line text node made
2447
+ // entirely of whitespace (no line break) is a meaningful single space
2448
+ // in JSX — `<b>a</b> <i>b</i>` — and `cleanJsxWhitespace` already
2449
+ // reduces a multi-line, indentation-only node (no line break survives
2450
+ // the per-line trim) to `''`. Checking `.trim() === ''` here would
2451
+ // discard that meaningful single space too.
2452
+ if (text === '') {
2434
2453
  return null
2435
2454
  }
2436
2455
 
@@ -2446,6 +2465,38 @@ function transformText(node: ts.JsxText, ctx: TransformContext): IRText | null {
2446
2465
  }
2447
2466
  }
2448
2467
 
2468
+ /**
2469
+ * JSX's whitespace-cleanup rule for a text child, as TypeScript, Babel and
2470
+ * React all implement it (see e.g. Babel's `cleanJSXElementLiteralChild`):
2471
+ *
2472
+ * - Split the raw text on line breaks.
2473
+ * - A tab is treated as a space.
2474
+ * - On every line except the first, strip the leading run of spaces
2475
+ * (it is indentation introduced by the line break, not authored text).
2476
+ * - On every line except the last, strip the trailing run of spaces
2477
+ * (same reasoning, from the other side).
2478
+ * - Drop lines that are empty after that trim.
2479
+ * - Join what's left with a single space.
2480
+ *
2481
+ * A single-line text node (no line break at all) is both "first" and
2482
+ * "last", so neither trim applies and the text passes through untouched —
2483
+ * `<b>a</b> <i>b</i>`'s single-space text node, or `const x = 1; ` inside
2484
+ * a `<pre>`, keep their interior whitespace exactly as written.
2485
+ */
2486
+ function cleanJsxWhitespace(raw: string): string {
2487
+ const lines = raw.split(/\r\n|\n|\r/)
2488
+ const kept: string[] = []
2489
+ for (let i = 0; i < lines.length; i++) {
2490
+ const isFirstLine = i === 0
2491
+ const isLastLine = i === lines.length - 1
2492
+ let line = lines[i].replace(/\t/g, ' ')
2493
+ if (!isFirstLine) line = line.replace(/^ +/, '')
2494
+ if (!isLastLine) line = line.replace(/ +$/, '')
2495
+ if (line !== '') kept.push(line)
2496
+ }
2497
+ return kept.join(' ')
2498
+ }
2499
+
2449
2500
  // =============================================================================
2450
2501
  // Expression Transformation
2451
2502
  // =============================================================================
@@ -4780,11 +4831,13 @@ function transformMapCall(
4780
4831
  let children: IRNode[] = []
4781
4832
  let paramBindings: LoopParamBinding[] | undefined
4782
4833
  let flatMapCallback: FlatMapCallback | undefined
4834
+ let itemTypeNode: ts.Node | undefined
4783
4835
 
4784
4836
  if (ts.isArrowFunction(callback)) {
4785
4837
  // Extract parameter names and type annotations
4786
4838
  if (callback.parameters.length > 0) {
4787
4839
  const firstParam = callback.parameters[0]
4840
+ itemTypeNode = firstParam
4788
4841
  param = firstParam.name.getText(ctx.sourceFile)
4789
4842
  if (firstParam.type) {
4790
4843
  paramType = firstParam.type.getText(ctx.sourceFile)
@@ -4813,6 +4866,7 @@ function transformMapCall(
4813
4866
  ts.isBindingElement(elements[1]) && ts.isIdentifier(elements[1].name)) {
4814
4867
  index = elements[0].name.text
4815
4868
  param = elements[1].name.text
4869
+ itemTypeNode = elements[1].name
4816
4870
  // Don't populate paramBindings — the destructure is fully
4817
4871
  // resolved into index + param by the iteration shape.
4818
4872
  } else {
@@ -5536,13 +5590,22 @@ function transformMapCall(
5536
5590
  // createComponent replacement).
5537
5591
  const nestedComponents = collectNestedComponents(children).filter(c => c.name !== childComponent?.name)
5538
5592
 
5593
+ // Scalar operand evidence only. Inferring object rows here would bypass
5594
+ // adapters' existing row-structure capability checks and their diagnostics.
5595
+ const callbackType = itemTypeNode && ctx.analyzer.checker
5596
+ ? tsTypeToTypeInfo(ctx.analyzer.checker.getTypeAtLocation(itemTypeNode), ctx.analyzer.checker)
5597
+ : null
5598
+ const scalarItemType = callbackType?.kind === 'primitive' ||
5599
+ (callbackType?.kind === 'union' && callbackType.unionTypes?.every(t => t.kind === 'primitive'))
5600
+ ? callbackType : null
5601
+
5539
5602
  return {
5540
5603
  type: 'loop',
5541
5604
  method: method === 'flatMap' ? 'flatMap' : undefined,
5542
5605
  array,
5543
5606
  templateArray,
5544
5607
  arrayType: null,
5545
- itemType: null,
5608
+ itemType: scalarItemType,
5546
5609
  param,
5547
5610
  index,
5548
5611
  key,
@@ -6525,6 +6588,7 @@ function expandSpreadAttribute(
6525
6588
  value: AttrValue
6526
6589
  loc: SourceLocation
6527
6590
  freeIdentifiers?: ReadonlySet<string>
6591
+ restExpandedKey?: boolean
6528
6592
  }> {
6529
6593
  const spreadExpr = ctx.getJS(attr.expression)
6530
6594
  const expandedKeys = ctx.analyzer.restPropsExpandedKeys
@@ -6535,13 +6599,17 @@ function expandSpreadAttribute(
6535
6599
  if (expandedKeys.length > 0 && restName && spreadExpr === restName) {
6536
6600
  // Expanded per-key attrs reference `${restName}.${key}` — `restName` is
6537
6601
  // the only free identifier (the `.${key}` tail is a member-access name,
6538
- // not an identifier reference).
6602
+ // not an identifier reference). `restExpandedKey` (#3057) marks these so
6603
+ // Phase 2 (`collectElements`) can bind them reactively off a live
6604
+ // `_p.<key>` read instead of the one-time `${restName}.${key}` snapshot
6605
+ // — see `IRAttribute.restExpandedKey`'s docstring.
6539
6606
  const perKeyFreeIds: ReadonlySet<string> = new Set([restName])
6540
6607
  return expandedKeys.map(key => ({
6541
6608
  name: key,
6542
6609
  value: AttrValueOf.expression(`${restName}.${key}`),
6543
6610
  loc,
6544
6611
  freeIdentifiers: perKeyFreeIds,
6612
+ restExpandedKey: true,
6545
6613
  }))
6546
6614
  }
6547
6615
 
@@ -8281,7 +8349,14 @@ function processComponentProps(
8281
8349
 
8282
8350
  for (const attr of attributes.properties) {
8283
8351
  if (ts.isJsxSpreadAttribute(attr)) {
8284
- props.push(...expandSpreadAttribute(attr, ctx))
8352
+ // `restExpandedKey` (#3057) is consumed only by the element-attribute
8353
+ // path (`collect-elements.ts`'s `attr.restExpandedKey` branch) — a
8354
+ // component-prop forwarded via `{...rest}` already gets a live
8355
+ // `_p.<key>` read through `buildComponentPropsExpr`'s own rest
8356
+ // rewrite, so `IRProp` declares no such field. Strip it here rather
8357
+ // than letting the shared helper's per-key marking leak into IRProp
8358
+ // as an inert flag nothing reads.
8359
+ props.push(...expandSpreadAttribute(attr, ctx).map(({ restExpandedKey: _restExpandedKey, ...prop }) => prop))
8285
8360
  continue
8286
8361
  }
8287
8362
 
@@ -0,0 +1,12 @@
1
+ import type { ParsedExpr } from './expression-parser.ts'
2
+
3
+ /** Recover an index operand from a computed member's property key.
4
+ * Only canonical array indices become numbers: keys such as "01" must
5
+ * remain strings. Both `obj[0]` and `obj['0']` use the same JS key. */
6
+ export function literalMemberIndex(property: string): ParsedExpr {
7
+ const index = Number(property)
8
+ if (Number.isInteger(index) && index >= 0 && index < 0xffffffff && String(index) === property) {
9
+ return { kind: 'literal', value: index, literalType: 'number' }
10
+ }
11
+ return { kind: 'literal', value: property, literalType: 'string' }
12
+ }
@@ -39,6 +39,7 @@ export type ScopeBindingSource = 'item' | 'index' | 'destructure' | 'preamble' |
39
39
 
40
40
  export interface ScopeBinding {
41
41
  readonly source: ScopeBindingSource
42
+ readonly stringValue?: boolean
42
43
  }
43
44
 
44
45
  export interface ScopeFrame {
@@ -54,11 +55,22 @@ export interface ScopeFrame {
54
55
  */
55
56
  export interface LoopBindingSource {
56
57
  readonly param: string
58
+ readonly itemType?: LoopValueType | null
57
59
  readonly index?: string | null
58
60
  readonly paramBindings?: readonly { readonly name: string }[]
59
61
  readonly preamble?: { readonly declaredNames: readonly string[] } | null
60
62
  }
61
63
 
64
+ interface LoopValueType {
65
+ readonly primitive?: string
66
+ readonly unionTypes?: readonly LoopValueType[]
67
+ }
68
+
69
+ function isStringLoopValue(type: LoopValueType): boolean {
70
+ return type.primitive === 'string' ||
71
+ (type.unionTypes !== undefined && type.unionTypes.length > 0 && type.unionTypes.every(isStringLoopValue))
72
+ }
73
+
62
74
  /**
63
75
  * A stack of `ScopeFrame`s, innermost frame at index 0 of the internal
64
76
  * array (i.e. `frames[0]` is what `enterLoopRow`/`enterCallback` most
@@ -112,7 +124,10 @@ export class BindingScope {
112
124
  if (loop.paramBindings && loop.paramBindings.length > 0) {
113
125
  for (const b of loop.paramBindings) bindings.set(b.name, { source: 'destructure' })
114
126
  } else {
115
- bindings.set(loop.param, { source: 'item' })
127
+ bindings.set(loop.param, {
128
+ source: 'item',
129
+ ...(loop.itemType ? { stringValue: isStringLoopValue(loop.itemType) } : {}),
130
+ })
116
131
  }
117
132
  if (loop.index != null) bindings.set(loop.index, { source: 'index' })
118
133
  for (const name of loop.preamble?.declaredNames ?? []) bindings.set(name, { source: 'preamble' })
@@ -141,6 +156,21 @@ export class BindingScope {
141
156
  return false
142
157
  }
143
158
 
159
+ /** Resolve string typing at this position, respecting the nearest binding. */
160
+ isStringValueName(name: string, outer: (name: string) => boolean, componentProperty = false): boolean {
161
+ if (componentProperty) return outer(name)
162
+ const hit = this.lookup(name)
163
+ return hit ? hit.binding.stringValue === true : outer(name)
164
+ }
165
+
166
+ /** Names this frame shadows in an enclosing callback/row frame. */
167
+ shadowedNames(): readonly string[] {
168
+ if (!this.frames[0]) return []
169
+ return [...this.frames[0].bindings.keys()].filter(name =>
170
+ this.frames.slice(1).some(frame => frame.bindings.has(name)),
171
+ )
172
+ }
173
+
144
174
  /**
145
175
  * Resolves `name` against the frame stack innermost-first. `depth 0`
146
176
  * means the innermost (most recently entered) frame; `null` when `name`
@@ -0,0 +1,164 @@
1
+ import ts from 'typescript'
2
+ import path from 'node:path'
3
+ import type { AnalyzerContext } from './analyzer-context.ts'
4
+ import type { ParsedExpr } from './expression-parser.ts'
5
+
6
+ // TypeScript exposes these resolution-cache readers on Program at runtime
7
+ // (its own incremental rebuild uses them), but omits them from the public
8
+ // declaration. Replaying the resolved graph preserves custom host hooks:
9
+ // renaming a local binding never changes any import or type directive.
10
+ type ResolvedProgram = ts.Program & {
11
+ getResolvedModule(file: ts.SourceFile, name: string, mode: ts.ResolutionMode): ts.ResolvedModuleWithFailedLookupLocations | undefined
12
+ getResolvedTypeReferenceDirective(file: ts.SourceFile, name: string, mode: ts.ResolutionMode): ts.ResolvedTypeReferenceDirectiveWithFailedLookupLocations | undefined
13
+ getAutomaticTypeDirectiveResolutions(): { get(name: string, mode: ts.ResolutionMode): ts.ResolvedTypeReferenceDirectiveWithFailedLookupLocations | undefined }
14
+ }
15
+
16
+ /** Preserve a build-supplied Program's virtual files and resolution options
17
+ * when one root's source changes. Other SourceFiles remain untouched. */
18
+ export function programWithSeparatedSource(program: ts.Program, filePath: string, source: string): ts.Program {
19
+ const options = program.getCompilerOptions()
20
+ const host = ts.createCompilerHost(options)
21
+ const directory = program.getCurrentDirectory()
22
+ const target = path.resolve(directory, filePath)
23
+ const matches = (name: string) => path.resolve(directory, name) === target
24
+ const resolvedProgram = program as ResolvedProgram
25
+ const virtualDirectories = new Set<string>()
26
+ for (const file of program.getSourceFiles()) {
27
+ let dir = path.dirname(path.resolve(directory, file.fileName))
28
+ while (!virtualDirectories.has(dir)) {
29
+ virtualDirectories.add(dir)
30
+ const parent = path.dirname(dir)
31
+ if (parent === dir) break
32
+ dir = parent
33
+ }
34
+ }
35
+ return ts.createProgram({ rootNames: program.getRootFileNames(), options, projectReferences: program.getProjectReferences(), host: {
36
+ ...host,
37
+ getCurrentDirectory: () => directory,
38
+ resolveModuleNameLiterals: (literals, containingFile, redirected, compilerOptions, containingSourceFile) => {
39
+ const original = program.getSourceFile(containingFile)
40
+ return literals.map(literal => {
41
+ const mode = program.getModeForUsageLocation(containingSourceFile, literal)
42
+ return (original && resolvedProgram.getResolvedModule(original, literal.text, mode))
43
+ ?? ts.resolveModuleName(literal.text, containingFile, compilerOptions, host, undefined, redirected, mode)
44
+ })
45
+ },
46
+ resolveTypeReferenceDirectiveReferences: (references, containingFile, redirected, compilerOptions, containingSourceFile) => {
47
+ const original = program.getSourceFile(containingFile)
48
+ return references.map(reference => {
49
+ const name = typeof reference === 'string' ? reference : reference.fileName
50
+ const mode = ts.getModeForFileReference(reference, containingSourceFile?.impliedNodeFormat)
51
+ return (original ? resolvedProgram.getResolvedTypeReferenceDirective(original, name, mode)
52
+ : resolvedProgram.getAutomaticTypeDirectiveResolutions().get(name, mode))
53
+ ?? ts.resolveTypeReferenceDirective(name, containingFile, compilerOptions, host, redirected, undefined, mode)
54
+ })
55
+ },
56
+ directoryExists: name => virtualDirectories.has(path.resolve(directory, name)) || host.directoryExists!(name),
57
+ fileExists: name => matches(name) || program.getSourceFile(name) !== undefined || host.fileExists(name),
58
+ readFile: name => matches(name) ? source : program.getSourceFile(name)?.text ?? host.readFile(name),
59
+ getSourceFile: (name, version, onError, shouldCreateNewSourceFile) => {
60
+ if (!matches(name)) return program.getSourceFile(name) ?? host.getSourceFile(name, version, onError, shouldCreateNewSourceFile)
61
+ const file = ts.createSourceFile(name, source, version, true, ts.ScriptKind.TSX)
62
+ file.impliedNodeFormat = program.getSourceFile(name)?.impliedNodeFormat
63
+ return file
64
+ },
65
+ } })
66
+ }
67
+
68
+ function isLiteralTree(expr: ParsedExpr): boolean {
69
+ switch (expr.kind) {
70
+ case 'literal': return true
71
+ case 'array-literal': return expr.elements.every(isLiteralTree)
72
+ case 'object-literal': return expr.properties.every(p => p.kind === 'prop' && isLiteralTree(p.value))
73
+ case 'unary': return ['-', '+'].includes(expr.op) && expr.argument.kind === 'literal' && expr.argument.literalType === 'number'
74
+ default: return false
75
+ }
76
+ }
77
+
78
+ /**
79
+ * A bare prop and a literal-seeded getter are different JS bindings, but
80
+ * scalar template backends flatten both to one variable. Give the local
81
+ * getter a hygienic name before building IR, so every backend (including
82
+ * the client emitter) receives one consistent binding identity.
83
+ *
84
+ * Source edits are AST/symbol-based and preserve untouched source bytes.
85
+ * Property keys, strings, and shadowing callback bindings never rename;
86
+ * shorthand values expand without changing their public keys. The rare
87
+ * collision-only path reuses the analyzer's checker when available. Its
88
+ * fallback binds the already-parsed SourceFile without parsing or loading
89
+ * dependencies: only lexical symbol identity is needed, not types.
90
+ */
91
+ export function separateLiteralSignalPropBindings(
92
+ ctx: AnalyzerContext,
93
+ isNonReference: (id: ts.Identifier) => boolean,
94
+ ): string | null {
95
+ if (!ctx.propsObjectName || !ctx.componentNode) return null
96
+ const propNames = new Set(ctx.propsParams.map(p => p.name))
97
+ const candidates = ctx.signals.filter(s =>
98
+ !s.isModule && !s.getterElided && propNames.has(s.getter) && s.parsed && isLiteralTree(s.parsed),
99
+ )
100
+ if (candidates.length === 0) return null
101
+
102
+ const sf = ctx.sourceFile
103
+ const checker = ctx.checker ?? ts.createProgram([sf.fileName], { noLib: true, noResolve: true }, {
104
+ ...ts.createCompilerHost({ noLib: true, noResolve: true }),
105
+ getSourceFile: () => sf,
106
+ }).getTypeChecker()
107
+ const occupied = new Set<string>()
108
+ function collectNames(node: ts.Node): void {
109
+ // Also avoid case-fold collisions introduced by backend field naming.
110
+ if (ts.isIdentifier(node)) occupied.add(node.text.toLowerCase())
111
+ ts.forEachChild(node, collectNames)
112
+ }
113
+ collectNames(sf)
114
+
115
+ const renames = new Map<ts.Symbol, string>()
116
+ const declarations = new Map(candidates.map(s => [
117
+ sf.getPositionOfLineAndCharacter(s.loc.start.line - 1, s.loc.start.column), s,
118
+ ]))
119
+ function collectBindings(node: ts.Node): void {
120
+ if (ts.isVariableDeclaration(node)) {
121
+ const signal = declarations.get(node.getStart(sf))
122
+ if (signal) {
123
+ const names = ts.isIdentifier(node.name) ? [node.name]
124
+ : ts.isArrayBindingPattern(node.name)
125
+ ? node.name.elements.flatMap(e => ts.isBindingElement(e) && ts.isIdentifier(e.name) ? [e.name] : [])
126
+ : []
127
+ const id = names.find(n => n.text === signal.getter)
128
+ const symbol = id && checker.getSymbolAtLocation(id)
129
+ if (symbol) {
130
+ const base = `bfSignal_${signal.getter}`
131
+ let name = base
132
+ let suffix = 0
133
+ while (occupied.has(name.toLowerCase())) name = `${base}_${++suffix}`
134
+ occupied.add(name.toLowerCase())
135
+ renames.set(symbol, name)
136
+ }
137
+ }
138
+ }
139
+ ts.forEachChild(node, collectBindings)
140
+ }
141
+ collectBindings(ctx.componentNode)
142
+
143
+ const edits: { start: number; end: number; text: string }[] = []
144
+ function collectEdits(node: ts.Node): void {
145
+ if (ts.isIdentifier(node) && !isNonReference(node)) {
146
+ const parent = node.parent
147
+ const shorthand = ts.isShorthandPropertyAssignment(parent) && parent.name === node
148
+ const symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(parent) : checker.getSymbolAtLocation(node)
149
+ const name = symbol && renames.get(symbol)
150
+ if (name) edits.push({
151
+ start: node.getStart(sf), end: node.getEnd(),
152
+ text: shorthand ? `${node.text}: ${name}` : name,
153
+ })
154
+ }
155
+ ts.forEachChild(node, collectEdits)
156
+ }
157
+ collectEdits(ctx.componentNode)
158
+ if (edits.length === 0) return null
159
+ let source = sf.text
160
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
161
+ source = source.slice(0, edit.start) + edit.text + source.slice(edit.end)
162
+ }
163
+ return source
164
+ }
@@ -34,6 +34,7 @@ import { extractFreeIdentifiersFromNode } from './analyzer.ts'
34
34
  import { resolveGetterAliases, collectAliasableGetterNames } from './ir-to-client-js/csr-substitute.ts'
35
35
  import { resolveBodyDestructuredPropAliases } from './props-binding.ts'
36
36
  import type { IRMetadata } from './types.ts'
37
+ import { isElidedFactoryGetter } from './types.ts'
37
38
 
38
39
  /**
39
40
  * A single template-variable default. Keyed in the manifest by the
@@ -247,6 +248,15 @@ export function extractSsrDefaults(metadata: IRMetadata): Record<string, SsrDefa
247
248
  // request-scoped reader, seeded by the adapter's env-signal binding, not a
248
249
  // baked initial value.
249
250
  if (sig.envReader) continue
251
+ // An elided async-factory value (#3245): `getter` holds a synthesized
252
+ // internal name that no expression in the source ever references.
253
+ // Seeding it here would leak that compiler-internal name into every
254
+ // template-stash backend's manifest (and, transitively, the Perl/etc.
255
+ // stash) for a binding nothing reads. See `isElidedFactoryGetter`'s
256
+ // docstring for the full rationale — a plain `createSignal`
257
+ // getter-elided form is unaffected, a pre-existing, separate question
258
+ // this issue doesn't cover.
259
+ if (isElidedFactoryGetter(sig)) continue
250
260
  const value = tryStaticEval(sig.initialValue, { bindings, propsLike })
251
261
  // Self-derivation collision (#2669): a signal whose getter shares its
252
262
  // name with the prop its OWN initializer derives from
@@ -267,11 +277,9 @@ export function extractSsrDefaults(metadata: IRMetadata): Record<string, SsrDefa
267
277
  //
268
278
  // NOT self-derived (the initializer references a DIFFERENT prop, or no
269
279
  // prop at all) keeps today's behavior: the signal's evaluated value
270
- // wins the entry outright. This also correctly leaves alone the
271
- // separate (out-of-scope) case where the signal's OWN initializer does
272
- // NOT reference the same-named prop but the JSX body separately reads
273
- // both `label()` and `props.label` — that's a template-variable-
274
- // aliasing defect, not this one, and must render byte-identically.
280
+ // wins its own entry. Literal-seeded getters that originally shared
281
+ // a bare prop's name have already been separated during analysis;
282
+ // their internal signal entry cannot overwrite the raw prop entry.
275
283
  //
276
284
  // Invariant this establishes (relied on by every template-stash
277
285
  // conformance harness's seeding loops — see `test-render.ts`): a
@@ -10,7 +10,8 @@
10
10
  *
11
11
  * Ordering / acyclicity guarantee: `steps` lists the component's signals
12
12
  * first, then its memos, each group in declaration order (matching
13
- * `IRMetadata.signals` / `IRMetadata.memos`). A binding's name only enters
13
+ * `IRMetadata.signals` / `IRMetadata.memos`), then canonical getter aliases.
14
+ * A binding's name only enters
14
15
  * the scope set AFTER its own step is decided, so a `derived` step's `frees`
15
16
  * can only name `baseScope` entries or EARLIER steps — self- and
16
17
  * forward-references are rejected by construction, and a consumer emitting
@@ -31,6 +32,7 @@
31
32
  */
32
33
 
33
34
  import { collectModuleStringConsts } from './augment-inherited-props.ts'
35
+ import { collectAliasableGetterNames, resolveGetterAliases } from './ir-to-client-js/csr-substitute.ts'
34
36
  import { envSignalReaderFor, type EnvSignalReader } from './adapters/env-signal.ts'
35
37
  import {
36
38
  extractArrowBodyExpression,
@@ -41,9 +43,10 @@ import {
41
43
  type ParsedExpr,
42
44
  } from './expression-parser.ts'
43
45
  import type { IRMetadata } from './types.ts'
46
+ import { isElidedFactoryGetter } from './types.ts'
44
47
 
45
48
  /**
46
- * One binding in component declaration order (signals first, then memos —
49
+ * One binding in dependency order (signals, memos, then getter aliases —
47
50
  * matching `IRMetadata` order and the adapters' iteration).
48
51
  *
49
52
  * - `env-reader`: an env signal whose `envReader` key resolves in the shared
@@ -197,7 +200,17 @@ export function computeSsrSeedPlan(metadata: IRMetadata): SsrSeedPlan {
197
200
  }
198
201
  const expr = signal.initialValue.trim()
199
202
  steps.push(
200
- expr === ''
203
+ // An elided async-factory value (#3245): `signal.getter` is a
204
+ // synthesized internal name nothing in the source ever references
205
+ // (see `isElidedFactoryGetter`'s docstring). Forced `opaque` (never
206
+ // `derived`) so an adapter that seeds `derived` steps in-template
207
+ // (Jinja/Erb/Pebble's `generateDerivedMemoSeed`) can't emit a
208
+ // `{% set __bfGet_x = ... %}` for it — the invariant "one step per
209
+ // signal" still holds (the name stays out of every backend's
210
+ // rendered output; only ITS OWN classify outcome is overridden, not
211
+ // the name's presence in `steps`/`available` for other signals'
212
+ // scope checks).
213
+ expr === '' || isElidedFactoryGetter(signal)
201
214
  ? { kind: 'opaque', name: signal.getter, origin: 'signal' }
202
215
  : classify(
203
216
  signal.getter,
@@ -239,5 +252,15 @@ export function computeSsrSeedPlan(metadata: IRMetadata): SsrSeedPlan {
239
252
  available.add(memo.name)
240
253
  }
241
254
 
255
+ // A getter alias names the live binding, not its pre-recompute default.
256
+ // Seed aliases after every signal/memo so stash adapters do not freeze an
257
+ // unresolved prop-derived memo before its runtime value is available.
258
+ const getters = collectAliasableGetterNames(metadata.signals, metadata.memos)
259
+ for (const [alias, origin] of resolveGetterAliases(metadata.localConstants ?? [], name => getters.has(name))) {
260
+ if (metadata.propsParams.some(p => p.name === alias)) continue
261
+ const parsed: ParsedExpr = { kind: 'call', callee: { kind: 'identifier', name: origin }, args: [] }
262
+ steps.push(classify(alias, 'memo', `${origin}()`, parsed, available))
263
+ available.add(alias)
264
+ }
242
265
  return { baseScope, steps }
243
266
  }
package/src/types.ts CHANGED
@@ -1515,6 +1515,29 @@ export interface IRAttribute extends AttrMeta {
1515
1515
  * same opt-out, applied to element-attribute position.
1516
1516
  */
1517
1517
  clientOnly?: boolean
1518
+ /**
1519
+ * Set when this attribute entry was produced by statically expanding a
1520
+ * closed-type `{...rest}` spread onto one of its known keys
1521
+ * (`expandSpreadAttribute`'s per-key branch, jsx-to-ir.ts) — #3057. The
1522
+ * expanded value (`<restName>.<key>`) reads the destructured rest
1523
+ * OBJECT, a one-time snapshot built at component-init time, so Phase 2's
1524
+ * string-level reactivity heuristics (`needsEffectWrapper`) never
1525
+ * recognize it as reading a live prop the way a bare destructured
1526
+ * parameter does — `rest` isn't itself a tracked prop name, and neither
1527
+ * is the expanded key. Without this flag the attribute is silently
1528
+ * treated as static: it renders once from SSR/the initial client
1529
+ * construction and never updates again, even though the value the child
1530
+ * forwards is exactly as live as any other prop.
1531
+ *
1532
+ * `collectElements` reads this to unconditionally push the attribute
1533
+ * into `ctx.reactiveAttrs`, rewriting its expression onto a live
1534
+ * `_p.<key>` read instead of the snapshot `<restName>.<key>` — the same
1535
+ * write shape `emitAttrUpdate` already produces for a developer-authored
1536
+ * reactive attribute, so a forwarded rest key updates reactively end to
1537
+ * end (undefined → present, present → absent → present again) exactly
1538
+ * like SSR / hydrated / csr-mount agree it should.
1539
+ */
1540
+ restExpandedKey?: boolean
1518
1541
  }
1519
1542
 
1520
1543
  export interface IREvent {
@@ -1649,6 +1672,30 @@ export interface SignalInfo {
1649
1672
  factory?: SignalFactoryCall
1650
1673
  }
1651
1674
 
1675
+ /**
1676
+ * True for the value-elided form of an async reactive factory declaration
1677
+ * (`const [, save] = createMutation(...)`, #3245): `signal.getter` then
1678
+ * holds the synthesized internal name (`__bfGet_<action>`, see
1679
+ * `SignalInfo.getterElided`'s docstring) that nothing in the source ever
1680
+ * references. Every consumer that would otherwise re-emit or seed that name
1681
+ * into caller-facing output (an SSR getter stub, a props struct/constructor
1682
+ * field, an SSR-defaults manifest entry, an SSR seed-plan step) checks this
1683
+ * first and skips it — see `bf debug graph`'s `debug.ts` precedent (#3227)
1684
+ * this generalizes.
1685
+ *
1686
+ * A plain `createSignal` getter-elided form (`const [, setX] =
1687
+ * createSignal(0)`) is NOT covered by this predicate, even though
1688
+ * `analyzer.ts`'s synthesis and `SignalInfo.getterElided`'s own docstring
1689
+ * make clear its getter is *equally* synthesized and unreferenced — it
1690
+ * leaks `__bfGet_<setter>` through the exact same sites today. #3245 scoped
1691
+ * this fix to the `factory` case only; widening this predicate to plain
1692
+ * `getterElided` (dropping the `factory` restriction) would close that gap
1693
+ * too, but is left for a separate follow-up rather than folded in here.
1694
+ */
1695
+ export function isElidedFactoryGetter(signal: Pick<SignalInfo, 'factory' | 'getterElided'>): boolean {
1696
+ return Boolean(signal.factory && signal.getterElided)
1697
+ }
1698
+
1652
1699
  /**
1653
1700
  * The async reactive factory call a signal's value comes from (#3165). Every
1654
1701
  * backend that re-emits the declaration reads this instead of assuming