@barefootjs/jsx 0.38.0 → 0.39.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 (87) hide show
  1. package/dist/action-accessor.d.ts +159 -0
  2. package/dist/action-accessor.d.ts.map +1 -0
  3. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  4. package/dist/analyzer.d.ts +30 -1
  5. package/dist/analyzer.d.ts.map +1 -1
  6. package/dist/async-action-refusal.d.ts +45 -0
  7. package/dist/async-action-refusal.d.ts.map +1 -0
  8. package/dist/compiler.d.ts.map +1 -1
  9. package/dist/debug.d.ts +61 -5
  10. package/dist/debug.d.ts.map +1 -1
  11. package/dist/errors.d.ts +4 -0
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/format-date-refusal.d.ts +2 -6
  14. package/dist/format-date-refusal.d.ts.map +1 -1
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1056 -344
  18. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/compute-scope.d.ts.map +1 -1
  22. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  23. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/declaration-sort.d.ts +2 -1
  26. package/dist/ir-to-client-js/declaration-sort.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/emit-module-level.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +7 -5
  30. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/types.d.ts +4 -0
  34. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/utils.d.ts +41 -2
  36. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  37. package/dist/jsx-to-ir.d.ts.map +1 -1
  38. package/dist/signal-initializer.d.ts +24 -0
  39. package/dist/signal-initializer.d.ts.map +1 -0
  40. package/dist/template-position-walk.d.ts +68 -0
  41. package/dist/template-position-walk.d.ts.map +1 -0
  42. package/dist/types.d.ts +51 -0
  43. package/dist/types.d.ts.map +1 -1
  44. package/package.json +2 -2
  45. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +191 -1
  46. package/src/__tests__/action-accessor.test.ts +166 -0
  47. package/src/__tests__/create-mutation.test.ts +220 -0
  48. package/src/__tests__/create-query.test.ts +644 -0
  49. package/src/__tests__/csr-fragment-root-scope-shape.test.ts +156 -0
  50. package/src/__tests__/debug.test.ts +222 -0
  51. package/src/__tests__/doc-examples.test.ts +66 -3
  52. package/src/__tests__/props-destructuring.test.ts +79 -4
  53. package/src/__tests__/reactive-factory-arity.test.ts +311 -0
  54. package/src/__tests__/ssr-portal-ref-callback.test.ts +5 -3
  55. package/src/action-accessor.ts +289 -0
  56. package/src/adapters/jsx-adapter.ts +17 -0
  57. package/src/analyzer.ts +558 -33
  58. package/src/async-action-refusal.ts +254 -0
  59. package/src/compiler.ts +3 -0
  60. package/src/debug.ts +318 -103
  61. package/src/errors.ts +39 -0
  62. package/src/format-date-refusal.ts +6 -125
  63. package/src/index.ts +2 -1
  64. package/src/ir-to-client-js/build-references.ts +6 -2
  65. package/src/ir-to-client-js/collect-elements.ts +1 -0
  66. package/src/ir-to-client-js/compute-inlinability.ts +2 -1
  67. package/src/ir-to-client-js/compute-scope.ts +3 -1
  68. package/src/ir-to-client-js/control-flow/plan/build-insert.ts +1 -0
  69. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  70. package/src/ir-to-client-js/control-flow/stringify/insert.ts +1 -1
  71. package/src/ir-to-client-js/csr-substitute.ts +11 -3
  72. package/src/ir-to-client-js/declaration-sort.ts +7 -3
  73. package/src/ir-to-client-js/emit-module-level.ts +7 -4
  74. package/src/ir-to-client-js/emit-registration.ts +5 -10
  75. package/src/ir-to-client-js/index.ts +7 -2
  76. package/src/ir-to-client-js/phases/ref-callbacks.ts +1 -1
  77. package/src/ir-to-client-js/plan/build-declaration-emit.ts +16 -15
  78. package/src/ir-to-client-js/plan/declaration-emit.ts +7 -5
  79. package/src/ir-to-client-js/prop-handling.ts +4 -0
  80. package/src/ir-to-client-js/reactivity.ts +1 -0
  81. package/src/ir-to-client-js/stringify/declaration-emit.ts +14 -7
  82. package/src/ir-to-client-js/types.ts +4 -0
  83. package/src/ir-to-client-js/utils.ts +55 -7
  84. package/src/jsx-to-ir.ts +36 -2
  85. package/src/signal-initializer.ts +36 -0
  86. package/src/template-position-walk.ts +203 -0
  87. package/src/types.ts +52 -0
package/src/errors.ts CHANGED
@@ -178,6 +178,27 @@ export const ErrorCodes = {
178
178
  REACTIVE_FACTORY_MODULE_CAPTURE: 'BF112',
179
179
  REACTIVE_FACTORY_IMPORT_COLLISION: 'BF113',
180
180
  REACTIVE_FACTORY_PARAM_SHADOWED: 'BF114',
181
+ // A tuple destructure of `createSignal`/`createMemo` whose element count
182
+ // the factory doesn't return (#3159). Before this code existed, an
183
+ // over-arity destructure (`const [a, b, c] = createSignal(...)`) silently
184
+ // dropped the WHOLE declaration from the compiled output — every
185
+ // reference then fell through to an unrelated same-name prop accessor if
186
+ // one happened to exist, or threw ReferenceError at hydrate if not.
187
+ REACTIVE_FACTORY_ARITY_MISMATCH: 'BF115',
188
+ // An authored `createSignal`/`createMemo` call with more arguments than
189
+ // the primitive accepts (#3159). Before this code existed, the extra
190
+ // argument(s) were silently dropped from the emitted client JS.
191
+ REACTIVE_FACTORY_EXTRA_ARGUMENTS: 'BF116',
192
+ // An async action's accessors (`action.isPending()` / `action.error()`, from
193
+ // `createQuery` or `createMutation`), or the action itself, read in a
194
+ // template-lowered position where their seed would not render like Hono
195
+ // (#3165; #3166 seeds the positions where it does). Refused on every
196
+ // adapter including Hono. See `async-action-refusal.ts`.
197
+ ASYNC_ACTION_READ_IN_TEMPLATE: 'BF117',
198
+ // An `initial` option passed to `createMutation` (#3210). A mutation has no
199
+ // initial request to seed from (spec/async.md §7.4): its value is
200
+ // `undefined` until the action is called, and the runtime ignores the key.
201
+ MUTATION_INITIAL_OPTION: 'BF118',
181
202
  } as const
182
203
 
183
204
  export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]
@@ -301,6 +322,24 @@ const errorMessages: Record<ErrorCode, string> = {
301
322
 
302
323
  [ErrorCodes.REACTIVE_FACTORY_PARAM_SHADOWED]:
303
324
  'Reactive factory parameter is shadowed by a nested declaration inside the factory body, so argument substitution at the inline site would be ambiguous. Rename the inner binding so it does not collide with the parameter.',
325
+
326
+ [ErrorCodes.REACTIVE_FACTORY_ARITY_MISMATCH]:
327
+ "Tuple destructure of 'createSignal'/'createMemo' does not match the number of " +
328
+ 'elements the factory returns. `createSignal` returns `[getter, setter]` (destructure ' +
329
+ '1 or 2 elements); `createMemo` returns a single getter (do not destructure it as an ' +
330
+ 'array at all).',
331
+
332
+ [ErrorCodes.REACTIVE_FACTORY_EXTRA_ARGUMENTS]:
333
+ "'createSignal'/'createMemo' call passes more arguments than the primitive accepts " +
334
+ '(`createSignal(initialValue?)`, `createMemo(computeFn)`, `createSearchParams()`). The extra argument(s) are ' +
335
+ 'silently dropped from the compiled client JS.',
336
+
337
+ [ErrorCodes.ASYNC_ACTION_READ_IN_TEMPLATE]:
338
+ "An async action's accessors (`isPending()` / `error()`) cannot be read in this template position — " +
339
+ 'the request function never runs on the server, so there is no value to render.',
340
+ [ErrorCodes.MUTATION_INITIAL_OPTION]:
341
+ '`createMutation` takes no `initial` option — a mutation has no initial request to seed its value from. ' +
342
+ 'Use `createQuery` for a value that needs an initial state.',
304
343
  }
305
344
 
306
345
  // =============================================================================
@@ -25,12 +25,8 @@
25
25
  * METHOD CALL on a host-rich-typed receiver have a catalogued lowering) and
26
26
  * short-circuits when the component has no `propsType` — a `formatDate`
27
27
  * call needs no receiver type at all and can appear in a props-free
28
- * component, so it cannot share that early return. The tree coverage below
29
- * intentionally mirrors that module's `walkNode` / `walkAttrValue` /
30
- * `walkTemplateParts` (element/component/provider attrs, loop array +
31
- * children, conditional/if-statement branches, async fallback + children)
32
- * for the same reason both checks need it: "every position a template
33
- * could render" — for two unrelated predicates.
28
+ * component, so it cannot share that early return. The positions come from
29
+ * `walkTemplatePositions` (`template-position-walk.ts`), which BF117 shares.
34
30
  */
35
31
 
36
32
  import type {
@@ -38,12 +34,10 @@ import type {
38
34
  IRMetadata,
39
35
  CompilerError,
40
36
  SourceLocation,
41
- AttrValue,
42
- IRTemplatePart,
43
37
  } from './types.ts'
44
38
  import type { ParsedExpr } from './expression-parser.ts'
45
- import { parseExpression } from './expression-parser.ts'
46
39
  import { ErrorCodes } from './errors.ts'
40
+ import { walkTemplatePositions } from './template-position-walk.ts'
47
41
 
48
42
  /** Entries that re-export the pure client `formatDate` helper (#2324). */
49
43
  const FORMAT_DATE_SOURCES: ReadonlySet<string> = new Set([
@@ -74,7 +68,9 @@ export function checkAuthoredFormatDateCalls(root: IRNode, metadata: IRMetadata,
74
68
  const names = collectFormatDateBoundNames(metadata)
75
69
  if (names.size === 0) return
76
70
  const seen = new Set<string>()
77
- walkNode(root, names, errors, seen)
71
+ walkTemplatePositions(root, ({ expr, loc }) => {
72
+ if (exprCallsName(expr, names)) pushDiagnostic(errors, seen, loc, anyName(names))
73
+ })
78
74
  }
79
75
 
80
76
  function pushDiagnostic(errors: CompilerError[], seen: Set<string>, loc: SourceLocation, name: string): void {
@@ -149,118 +145,3 @@ function anyName(names: ReadonlySet<string>): string {
149
145
  for (const n of names) return n
150
146
  return 'formatDate'
151
147
  }
152
-
153
- /**
154
- * `IRTemplatePart.ternary.condition` / `.lookup.key` carry no attached
155
- * parse (unlike every other position here), so parse on demand — same as
156
- * `rich-type-refusal.ts`'s `walkTemplateParts`. `ternary.whenTrue` /
157
- * `.whenFalse` are ALSO raw, unparsed text (the per-branch rendered
158
- * snippet), so they get the same on-demand treatment: this is exactly the
159
- * `format-date-ternary` shape (#2843) — a call in a ternary CONSEQUENT
160
- * inside a structured template-literal attribute.
161
- */
162
- function walkTemplateParts(
163
- parts: readonly IRTemplatePart[],
164
- loc: SourceLocation,
165
- names: ReadonlySet<string>,
166
- errors: CompilerError[],
167
- seen: Set<string>,
168
- ): void {
169
- const checkText = (text: string) => {
170
- const trimmed = text.trim()
171
- if (!trimmed) return
172
- if (exprCallsName(parseExpression(trimmed), names)) pushDiagnostic(errors, seen, loc, anyName(names))
173
- }
174
- for (const part of parts) {
175
- if (part.type === 'ternary') {
176
- checkText(part.condition)
177
- checkText(part.whenTrue)
178
- checkText(part.whenFalse)
179
- } else if (part.type === 'lookup') {
180
- checkText(part.key)
181
- }
182
- }
183
- }
184
-
185
- function walkAttrValue(
186
- value: AttrValue,
187
- clientOnly: boolean | undefined,
188
- loc: SourceLocation,
189
- names: ReadonlySet<string>,
190
- errors: CompilerError[],
191
- seen: Set<string>,
192
- ): void {
193
- if (clientOnly) return
194
- if (value.kind === 'expression') {
195
- if (value.parsed && exprCallsName(value.parsed, names)) pushDiagnostic(errors, seen, loc, anyName(names))
196
- if (value.parts) walkTemplateParts(value.parts, loc, names, errors, seen)
197
- } else if (value.kind === 'spread') {
198
- if (value.parsed && exprCallsName(value.parsed, names)) pushDiagnostic(errors, seen, loc, anyName(names))
199
- } else if (value.kind === 'template') {
200
- walkTemplateParts(value.parts, loc, names, errors, seen)
201
- }
202
- }
203
-
204
- function walkNode(node: IRNode, names: ReadonlySet<string>, errors: CompilerError[], seen: Set<string>): void {
205
- if (node.type === 'expression') {
206
- if (!node.clientOnly && node.parsed && exprCallsName(node.parsed, names)) {
207
- pushDiagnostic(errors, seen, node.loc, anyName(names))
208
- }
209
- } else if (node.type === 'conditional') {
210
- if (!node.clientOnly && node.parsedCondition && exprCallsName(node.parsedCondition, names)) {
211
- pushDiagnostic(errors, seen, node.loc, anyName(names))
212
- }
213
- } else if (node.type === 'if-statement') {
214
- if (node.parsedCondition && exprCallsName(node.parsedCondition, names)) {
215
- pushDiagnostic(errors, seen, node.loc, anyName(names))
216
- }
217
- }
218
-
219
- if (node.type === 'element') {
220
- for (const attr of node.attrs) walkAttrValue(attr.value, attr.clientOnly, attr.loc, names, errors, seen)
221
- } else if (node.type === 'component') {
222
- for (const prop of node.props) walkAttrValue(prop.value, prop.clientOnly, prop.loc, names, errors, seen)
223
- } else if (node.type === 'provider') {
224
- walkAttrValue(node.valueProp.value, node.valueProp.clientOnly, node.valueProp.loc, names, errors, seen)
225
- }
226
-
227
- switch (node.type) {
228
- case 'element':
229
- case 'component':
230
- case 'fragment':
231
- case 'provider':
232
- for (const child of node.children) walkNode(child, names, errors, seen)
233
- break
234
- case 'async':
235
- walkNode(node.fallback, names, errors, seen)
236
- for (const child of node.children) walkNode(child, names, errors, seen)
237
- break
238
- case 'loop': {
239
- if (node.clientOnly) break
240
- if (node.arrayParsed && exprCallsName(node.arrayParsed, names)) pushDiagnostic(errors, seen, node.loc, anyName(names))
241
- for (const child of node.children) walkNode(child, names, errors, seen)
242
- if (node.childComponent) {
243
- for (const child of node.childComponent.children) walkNode(child, names, errors, seen)
244
- }
245
- for (const nested of node.nestedComponents ?? []) {
246
- for (const child of nested.children) walkNode(child, names, errors, seen)
247
- }
248
- for (const seg of node.flatMapCallback?.segments ?? []) {
249
- if (seg.kind === 'jsx') walkNode(seg.ir, names, errors, seen)
250
- }
251
- for (const seg of node.preamble?.segments ?? []) {
252
- if (seg.kind === 'jsx') walkNode(seg.ir, names, errors, seen)
253
- }
254
- break
255
- }
256
- case 'conditional':
257
- if (node.clientOnly) break
258
- walkNode(node.whenTrue, names, errors, seen)
259
- walkNode(node.whenFalse, names, errors, seen)
260
- break
261
- case 'if-statement':
262
- walkNode(node.consequent, names, errors, seen)
263
- if (node.alternate) walkNode(node.alternate, names, errors, seen)
264
- break
265
- }
266
- }
package/src/index.ts CHANGED
@@ -89,7 +89,7 @@ export type {
89
89
  } from './types.ts'
90
90
 
91
91
  // Analyzer
92
- export { analyzeComponent, listComponentFunctions, listComponentFunctions as listExportedComponents, scanComponentFile, createProgramForFile, needsTypeBasedDetection, resolveRelativeImportToFile, REACTIVE_PRIMITIVES, BROWSER_ONLY_CLIENT_APIS, type AnalyzerContext, type ComponentFileScan } from './analyzer.ts'
92
+ export { analyzeComponent, listComponentFunctions, listComponentFunctions as listExportedComponents, scanComponentFile, createProgramForFile, createAnchoredProgram, needsTypeBasedDetection, resolveRelativeImportToFile, REACTIVE_PRIMITIVES, BROWSER_ONLY_CLIENT_APIS, type AnalyzerContext, type ComponentFileScan } from './analyzer.ts'
93
93
  export { createProgramForCorpus, type SharedProgramOptions } from './shared-program.ts'
94
94
 
95
95
  // JSX to IR transformer
@@ -256,6 +256,7 @@ export {
256
256
  buildLoopSummary,
257
257
  buildWhyUpdate,
258
258
  traceUpdatePath,
259
+ traceableNames,
259
260
  formatComponentGraph,
260
261
  formatUpdatePath,
261
262
  formatEventSummary,
@@ -41,6 +41,7 @@ import { attrValueToString } from './utils.ts'
41
41
  import type { ClientJsContext } from './types.ts'
42
42
  import { extractIdentifiers, extractTemplateIdentifiers } from './identifiers.ts'
43
43
  import { walkIR } from './walker.ts'
44
+ import { signalSecondBinding } from '../signal-initializer.ts'
44
45
 
45
46
  // All non-declaration edge origins share a single null source — no
46
47
  // query on the graph distinguishes them on read today. Stage E
@@ -59,7 +60,8 @@ export function buildReferencesGraph(ctx: ClientJsContext, irRoot: IRNode): Refe
59
60
  for (const f of ctx.localFunctions) declaredNames.add(f.name)
60
61
  for (const s of ctx.signals) {
61
62
  declaredNames.add(s.getter)
62
- if (s.setter) declaredNames.add(s.setter)
63
+ const second = signalSecondBinding(s)
64
+ if (second) declaredNames.add(second)
63
65
  }
64
66
  for (const m of ctx.memos) declaredNames.add(m.name)
65
67
  for (const p of ctx.propsParams) {
@@ -189,7 +191,9 @@ export function buildReferencesGraph(ctx: ClientJsContext, irRoot: IRNode): Refe
189
191
 
190
192
  // identifiers.ts L137-139
191
193
  for (const signal of ctx.signals) {
192
- addExprEdges({ kind: 'signal', name: signal.getter }, signal.initialValue, 'init-body')
194
+ // An async factory's declaration is its whole call (`createQuery(fn,
195
+ // options)`, #3165): the request function's reads are dependencies too.
196
+ addExprEdges({ kind: 'signal', name: signal.getter }, signal.factory?.argsText ?? signal.initialValue, 'init-body')
193
197
  }
194
198
 
195
199
  // identifiers.ts L141-143
@@ -1077,6 +1077,7 @@ function collectFromElement(element: IRElement, ctx: ClientJsContext, insideCond
1077
1077
  ctx.refElements.push({
1078
1078
  slotId: element.slotId,
1079
1079
  callback: element.ref,
1080
+ ...(element.ssrPortalOwnerScope && { ssrPortalOwner: true }),
1080
1081
  })
1081
1082
  }
1082
1083
 
@@ -33,6 +33,7 @@ import { createError, ErrorCodes } from '../errors.ts'
33
33
  import { attrValueToString } from './utils.ts'
34
34
  import { walkIR, type IRVisitor } from './walker.ts'
35
35
  import { buildSignalMemoEnv, csrSubstitute, resolveGetterAliases, type CsrEnv, type CsrSubstitution } from './csr-substitute.ts'
36
+ import { signalSecondBinding } from '../signal-initializer.ts'
36
37
 
37
38
  /**
38
39
  * Build a `RelocateEnv` from a live `ClientJsContext`. The IR-keyed env
@@ -266,7 +267,7 @@ export function computeInlinability(
266
267
 
267
268
  // --- Constants (initial classification) ---
268
269
  const signalGetters = new Set(ctx.signals.map(s => s.getter))
269
- const signalSetters = new Set(ctx.signals.filter(s => s.setter).map(s => s.setter!))
270
+ const signalSetters = new Set(ctx.signals.flatMap(s => signalSecondBinding(s) ?? []))
270
271
  const memoNames = new Set(ctx.memos.map(m => m.name))
271
272
  // A bare alias-hop chain that ultimately names a signal/memo getter
272
273
  // (`const items__alias = items`, #2778) is `reactive-read` the same as
@@ -21,6 +21,7 @@ import {
21
21
  graphFunctionReferences,
22
22
  graphUsedIdentifiers,
23
23
  } from './build-references.ts'
24
+ import { signalSecondBinding } from '../signal-initializer.ts'
24
25
 
25
26
  export interface DeclarationScopes {
26
27
  constantScope: Map<string, DeclarationScope>
@@ -104,7 +105,8 @@ export function computeDeclarationScopes(
104
105
  const initRequired = new Set<string>()
105
106
  for (const s of ctx.signals) {
106
107
  initRequired.add(s.getter)
107
- if (s.setter) initRequired.add(s.setter)
108
+ const second = signalSecondBinding(s)
109
+ if (second) initRequired.add(second)
108
110
  }
109
111
  for (const m of ctx.memos) initRequired.add(m.name)
110
112
  for (const p of ctx.propsParams) initRequired.add(p.name)
@@ -79,6 +79,7 @@ function buildArmBody(branch: BranchSummary, options: BuildInsertOptions): ArmBo
79
79
  refs: branch.refs.map(r => ({
80
80
  slotId: r.slotId,
81
81
  callback: r.callback,
82
+ ...(r.ssrPortalOwner && { ssrPortalOwner: true }),
82
83
  })),
83
84
  childComponents: branch.childComponents.map(c => ({
84
85
  name: c.name,
@@ -92,6 +92,8 @@ export interface ArmEventBind {
92
92
  export interface ArmRefBind {
93
93
  slotId: string
94
94
  callback: string
95
+ /** The element's `IRElement.ssrPortalOwnerScope` — see `emitRefCall`. */
96
+ ssrPortalOwner?: boolean
95
97
  }
96
98
 
97
99
  export interface ArmChildComponentInit {
@@ -124,7 +124,7 @@ function emitArmBody(
124
124
 
125
125
  for (const ref of body.refs) {
126
126
  const v = varSlotId(ref.slotId)
127
- lines.push(`${indent}if (_${v}) ${emitRefCall(ref.callback, `_${v}`)}`)
127
+ lines.push(`${indent}if (_${v}) ${emitRefCall(ref.callback, `_${v}`, ref.ssrPortalOwner)}`)
128
128
  }
129
129
 
130
130
  // 3. Child component initializations from the branch swap.
@@ -31,6 +31,7 @@ import { extractFreeIdentifiersFromNode } from '../analyzer.ts'
31
31
  import type { ConstantInfo, MemoInfo, SignalInfo } from '../types.ts'
32
32
  import type { BindingScope } from '../scope/binding-scope.ts'
33
33
  import { resolveAliasOrigin } from '../props-binding.ts'
34
+ import { signalSecondBinding } from '../signal-initializer.ts'
34
35
 
35
36
  /**
36
37
  * CSR-substituted const value: the const's initializer with every
@@ -600,8 +601,12 @@ export function buildSignalMemoEnv(
600
601
  // that shim directly, with no thunk-wrapping needed. `s.setter` is
601
602
  // null for the setter-elided declaration form (`const [count] =
602
603
  // createSignal(...)`), which has no name to register.
603
- if (s.setter) {
604
- substitutions.set(s.setter, { kind: 'identifier', replacement: '() => {}', freeIdentifiers: new Set() })
604
+ // An async factory's action (#3165) gets the same no-op: forwarding it as
605
+ // a value (`<Retry run={fetchItems} />`) is allowed, and every read of
606
+ // its accessors in a template position is refused before emit (BF117).
607
+ const second = signalSecondBinding(s)
608
+ if (second) {
609
+ substitutions.set(second, { kind: 'identifier', replacement: '() => {}', freeIdentifiers: new Set() })
605
610
  }
606
611
  }
607
612
  for (const m of memos) {
@@ -639,7 +644,10 @@ function normalizeSignalInitial(signal: SignalInfo, propsObjectName: string | nu
639
644
  const initialValue = signal.initialValue
640
645
  const propsName = propsObjectName ?? 'props'
641
646
  const propsPrefix = `${propsName}.`
642
- if (initialValue.startsWith(propsPrefix) && !initialValue.includes('??')) {
647
+ // An async factory's `initial` (#3165) renders exactly as given: an absent
648
+ // prop means no obtained result, so the value is `undefined` on the server
649
+ // too, never a type default.
650
+ if (!signal.factory && initialValue.startsWith(propsPrefix) && !initialValue.includes('??')) {
643
651
  return `${initialValue} ?? ${inferDefaultValue(signal.type)}`
644
652
  }
645
653
  // Destructured mode (#2265): `templateInitialValue` (when present) has
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { ConstantInfo, FunctionInfo, MemoInfo, ReferencesGraph, SignalInfo } from '../types.ts'
11
11
  import { graphDeclarationReferences } from './build-references.ts'
12
+ import { signalSecondBinding } from '../signal-initializer.ts'
12
13
 
13
14
  // =============================================================================
14
15
  // Declaration types
@@ -22,14 +23,17 @@ export type Declaration =
22
23
 
23
24
  /**
24
25
  * Return the names defined by a declaration.
25
- * Signals define both getter and setter names.
26
+ * Signals define both getter and setter names (an async factory's second
27
+ * binding is its action, #3165).
26
28
  */
27
29
  export function providedNames(decl: Declaration): string[] {
28
30
  switch (decl.kind) {
29
31
  case 'constant':
30
32
  return [decl.info.name]
31
- case 'signal':
32
- return decl.info.setter ? [decl.info.getter, decl.info.setter] : [decl.info.getter]
33
+ case 'signal': {
34
+ const second = signalSecondBinding(decl.info)
35
+ return second ? [decl.info.getter, second] : [decl.info.getter]
36
+ }
33
37
  case 'memo':
34
38
  return [decl.info.name]
35
39
  case 'function':
@@ -26,6 +26,7 @@ import {
26
26
  collectUserDomImports,
27
27
  detectUsedImports,
28
28
  } from './imports.ts'
29
+ import { signalFactoryInitializer, signalSecondBinding } from '../signal-initializer.ts'
29
30
 
30
31
  /**
31
32
  * Build the module-level code block that replaces `MODULE_CONSTANTS_PLACEHOLDER`.
@@ -70,13 +71,15 @@ export function emitModuleLevelDeclarations(
70
71
  }
71
72
  for (const signal of moduleLevelSignals) {
72
73
  const tupleVar = `__bf_m_${signal.getter}_tuple`
74
+ const initializer = signalFactoryInitializer(signal) ?? `createSignal(${signal.initialValue})`
75
+ const second = signalSecondBinding(signal)
73
76
  if (signal.isExported) {
74
- lines.push(`export const [${signal.getter}${signal.setter ? `, ${signal.setter}` : ''}] = createSignal(${signal.initialValue})`)
77
+ lines.push(`export const [${signal.getter}${second ? `, ${second}` : ''}] = ${initializer}`)
75
78
  } else {
76
- lines.push(`var ${tupleVar} = ${tupleVar} ?? createSignal(${signal.initialValue})`)
79
+ lines.push(`var ${tupleVar} = ${tupleVar} ?? ${initializer}`)
77
80
  lines.push(`var ${signal.getter} = ${tupleVar}[0]`)
78
- if (signal.setter) {
79
- lines.push(`var ${signal.setter} = ${tupleVar}[1]`)
81
+ if (second) {
82
+ lines.push(`var ${second} = ${tupleVar}[1]`)
80
83
  }
81
84
  }
82
85
  }
@@ -4,9 +4,9 @@
4
4
  * and the final hydrate() call emission.
5
5
  */
6
6
 
7
- import type { ComponentIR, IRFragment, IRNode, ReferencesGraph, SignalInfo } from '../types.ts'
7
+ import type { ComponentIR, IRNode, ReferencesGraph, SignalInfo } from '../types.ts'
8
8
  import type { ClientJsContext } from './types.ts'
9
- import { PROPS_PARAM, isCommentScopedRoot, initFunctionName } from './utils.ts'
9
+ import { PROPS_PARAM, componentDefScopeFlags, initFunctionName } from './utils.ts'
10
10
  import { computeInlinability, toLegacyInlinability } from './compute-inlinability.ts'
11
11
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate, createStringProtector } from './html-template.ts'
12
12
  import { markupSlotIdsOf } from './markup-slots.ts'
@@ -214,8 +214,8 @@ export function emitRegistrationAndHydration(
214
214
  // ITS OWN real scope id — the wrapping comment marks a scope with no
215
215
  // DOM presence of its own, and `materializeComponent` must leave
216
216
  // `scopeId` null so it doesn't stamp over (or duplicate) the child's.
217
- const isFragmentRoot = _ir.root.type === 'fragment' && !!(_ir.root as IRFragment).needsScopeComment
218
- const isCommentScope = isCommentScopedRoot(_ir.root)
217
+ // Both flags come from `componentDefScopeFlags` (utils.ts), shared with
218
+ // the template-only registration path (`generateTemplateOnlyMount`).
219
219
 
220
220
  // Build ComponentDef object for hydrate()
221
221
  const defParts: string[] = [`init: ${initFunctionName(name)}`]
@@ -243,12 +243,7 @@ export function emitRegistrationAndHydration(
243
243
  }
244
244
  }
245
245
  // No else: top-level-only components skip template entirely (save bytes)
246
- if (isCommentScope) {
247
- defParts.push('comment: true')
248
- }
249
- if (isFragmentRoot) {
250
- defParts.push('fragmentRoot: true')
251
- }
246
+ defParts.push(...componentDefScopeFlags(_ir.root))
252
247
 
253
248
  const registryKey = nameForRegistryRef(name)
254
249
  // When the registry key was file-scoped (`Name__<8hex>`, for a
@@ -16,7 +16,7 @@ import { buildReferencesGraph, graphUsedIdentifiers } from './build-references.t
16
16
  import { addConstantPropRefsToSet } from './init-declarations.ts'
17
17
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate } from './html-template.ts'
18
18
  import { markupSlotIdsOf } from './markup-slots.ts'
19
- import { PROPS_PARAM, initFunctionName } from './utils.ts'
19
+ import { PROPS_PARAM, initFunctionName, componentDefScopeFlags } from './utils.ts'
20
20
  import { buildInlinableConstants, csrInlinableConstantsFromCtx } from './emit-registration.ts'
21
21
  import { buildEnvFromCtx } from './compute-inlinability.ts'
22
22
  import { nameForRegistryRef, buildImportAliasMap, setActiveImportAliases } from './component-scope.ts'
@@ -363,7 +363,12 @@ function generateTemplateOnlyMount(ir: ComponentIR, ctx: ClientJsContext): strin
363
363
  // `emitRegistrationAndHydration`: the hashed key must not reach `bf-s`
364
364
  // (#2518).
365
365
  const nameField = registryKey !== name ? `, name: '${name}'` : ''
366
- lines.push(`hydrate('${registryKey}', { init: ${initName}, template: (${PROPS_PARAM}) => \`${templateHtml}\`${nameField} })`)
366
+ // Scope-shape flags from the same helper `emitRegistrationAndHydration`
367
+ // uses — a fragment-rooted stateless child must declare `comment` /
368
+ // `fragmentRoot` too, or `renderChild()` stamps `bf-s` onto its first
369
+ // element while SSR scopes it with a comment pair.
370
+ const scopeFlags = componentDefScopeFlags(ir.root).map((f) => `, ${f}`).join('')
371
+ lines.push(`hydrate('${registryKey}', { init: ${initName}, template: (${PROPS_PARAM}) => \`${templateHtml}\`${scopeFlags}${nameField} })`)
367
372
  // See `emitRegistrationAndHydration` (./emit-registration.ts) for the
368
373
  // rationale on why the component is also emitted as a callable
369
374
  // shim. The same applies for template-only components since they
@@ -16,6 +16,6 @@ export function emitRefCallbacks(
16
16
  for (const elem of ctx.refElements) {
17
17
  if (conditionalSlotIds.has(elem.slotId)) continue
18
18
  const v = varSlotId(elem.slotId)
19
- lines.push(` if (_${v}) ${emitRefCall(elem.callback, `_${v}`)}`)
19
+ lines.push(` if (_${v}) ${emitRefCall(elem.callback, `_${v}`, elem.ssrPortalOwner)}`)
20
20
  }
21
21
  }
@@ -14,7 +14,7 @@ import type { ClientJsContext } from '../types.ts'
14
14
  import type { ParamInfo, SignalInfo } from '../../types.ts'
15
15
  import { inferDefaultValue, PROPS_PARAM } from '../utils.ts'
16
16
  import { livePropReadExpr } from '../../props-binding.ts'
17
- import { ENV_SIGNAL_CLIENT_FACTORY } from '../../adapters/env-signal.ts'
17
+ import { signalFactoryInitializer, signalSecondBinding } from '../../signal-initializer.ts'
18
18
  import type {
19
19
  ControlledSignalEffectPlan,
20
20
  DeclarationEmitPlan,
@@ -87,20 +87,21 @@ function buildSignalPlan(
87
87
  ctx: ClientJsContext,
88
88
  lookups: DeclarationEmitLookups,
89
89
  ): SignalEmitPlan {
90
- if (signal.envReader) {
91
- // Emit the factory as written (alias / namespace aware, #2057), falling back
92
- // to the canonical name if the callee text wasn't captured.
93
- const factory = signal.envFactory ?? ENV_SIGNAL_CLIENT_FACTORY[signal.envReader]
94
- if (factory) {
95
- return {
96
- kind: 'signal',
97
- getter: signal.getter,
98
- setter: signal.setter,
99
- getterElided: signal.getterElided,
100
- initialValueExpr: '',
101
- controlledEffect: null,
102
- initializerOverride: `${factory}()`,
103
- }
90
+ // Env signals (#2057) and async factories (#3165) re-emit their own factory
91
+ // call, as written (alias / namespace aware), instead of `createSignal`.
92
+ const initializerOverride = signalFactoryInitializer(signal)
93
+ if (initializerOverride) {
94
+ return {
95
+ kind: 'signal',
96
+ getter: signal.getter,
97
+ setter: signalSecondBinding(signal),
98
+ getterElided: signal.getterElided,
99
+ initialValueExpr: '',
100
+ controlledEffect: null,
101
+ initializerOverride,
102
+ // An env signal is a stable request-scoped view, emitted unconditionally;
103
+ // an async factory owns a request, so it is created only on its branch.
104
+ branchCondition: signal.factory ? signal.branchCondition : undefined,
104
105
  }
105
106
  }
106
107
  const controlledEffect = buildControlledSignalEffect(signal, lookups)
@@ -62,11 +62,13 @@ export interface SignalEmitPlan {
62
62
  bfId?: string
63
63
  /**
64
64
  * When set, the full initializer expression to emit verbatim instead of
65
- * `createSignal(<initialValueExpr>)`. Env signals (#2057) emit their own
66
- * factory call — e.g. `createSearchParams()` — with no baked initial value,
67
- * profile id, controlled effect, or branch condition (the tuple is a stable
68
- * request-scoped view, not stored state). When present the stringifier emits
69
- * `const [<getter>, <setter>] = <initializerOverride>` and nothing else.
65
+ * `createSignal(<initialValueExpr>)`. Env signals (#2057) and async
66
+ * factories (#3165) emit their own factory call — e.g.
67
+ * `createSearchParams()`, `createQuery(fn, options)` — with no baked initial
68
+ * value, profile id, or controlled effect; `setter` then holds the tuple's
69
+ * second binding (an async factory's action). When present the stringifier
70
+ * emits `const [<getter>, <setter>] = <initializerOverride>` (or the
71
+ * `branchCondition` form, which only an async factory sets) and nothing else.
70
72
  */
71
73
  initializerOverride?: string
72
74
  }
@@ -189,6 +189,10 @@ export function getControlledPropName(
189
189
  propsParams: ParamInfo[],
190
190
  propsObjectName: string | null = null
191
191
  ): string | null {
192
+ // An async factory's value (`createQuery(fn, { initial: props.posts })`,
193
+ // #3165) takes `initial` once; later values come from its own requests, so
194
+ // it is never re-synced from the prop.
195
+ if (signal.factory) return null
192
196
  const initialValue = signal.initialValue.trim()
193
197
  const isDefaultProp = (propName: string) => propName.startsWith('default')
194
198
  // Use the source-level props name for pattern matching (not the generated PROPS_PARAM)
@@ -488,6 +488,7 @@ export function collectConditionalBranchRefs(node: IRNode): ConditionalBranchRef
488
488
  refs.push({
489
489
  slotId: el.slotId,
490
490
  callback: el.ref,
491
+ ...(el.ssrPortalOwnerScope && { ssrPortalOwner: true }),
491
492
  })
492
493
  }
493
494
  }, true)
@@ -70,15 +70,22 @@ function emitSignal(lines: string[], plan: SignalEmitPlan): void {
70
70
  // getter name into output (#2468 sweep — dropping the declaration
71
71
  // entirely left the setter as a guaranteed ReferenceError).
72
72
  const getterSlot = plan.getterElided ? '' : plan.getter
73
- // Env signal (#2057): emit its own factory call verbatim (`createSearchParams()`)
74
- // — a stable request-scoped view, so no baked initial value, profile id,
75
- // controlled effect, or branch condition applies.
73
+ // Env signal (#2057) or async factory (#3165): emit its own factory call
74
+ // verbatim (`createSearchParams()`, `createQuery(fn, options)`) — no baked
75
+ // initial value, profile id, or controlled effect applies. Only an async
76
+ // factory carries a branch condition (see `SignalEmitPlan.branchCondition`).
76
77
  if (plan.initializerOverride) {
77
- if (plan.setter) {
78
- lines.push(` const [${getterSlot}, ${plan.setter}] = ${plan.initializerOverride}`)
79
- } else {
80
- lines.push(` const [${plan.getter}] = ${plan.initializerOverride}`)
78
+ const bindings = plan.setter ? `${getterSlot}, ${plan.setter}` : plan.getter
79
+ if (plan.branchCondition) {
80
+ lines.push(plan.setter
81
+ ? (plan.getterElided ? ` let ${plan.setter}` : ` let ${plan.getter}, ${plan.setter}`)
82
+ : ` let ${plan.getter}`)
83
+ lines.push(` if (${plan.branchCondition}) {`)
84
+ lines.push(` ;[${bindings}] = ${plan.initializerOverride}`)
85
+ lines.push(` }`)
86
+ return
81
87
  }
88
+ lines.push(` const [${bindings}] = ${plan.initializerOverride}`)
82
89
  return
83
90
  }
84
91
  const id = bfIdArg(plan.bfId)
@@ -203,6 +203,8 @@ export interface ConditionalBranchEvent {
203
203
  export interface ConditionalBranchRef {
204
204
  slotId: string
205
205
  callback: string
206
+ /** Mirrors `IRElement.ssrPortalOwnerScope` — see `emitRefCall`. */
207
+ ssrPortalOwner?: boolean
206
208
  }
207
209
 
208
210
  export interface ConditionalBranchChildComponent {
@@ -740,6 +742,8 @@ export type CollectedLoop = TopLevelLoop | BranchLoop | NestedLoop
740
742
  export interface RefElement {
741
743
  slotId: string
742
744
  callback: string
745
+ /** Mirrors `IRElement.ssrPortalOwnerScope` — see `emitRefCall`. */
746
+ ssrPortalOwner?: boolean
743
747
  }
744
748
 
745
749
  export interface ChildInit {