@barefootjs/jsx 0.37.1 → 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 (168) 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/env-signal.d.ts +0 -8
  4. package/dist/adapters/env-signal.d.ts.map +1 -1
  5. package/dist/adapters/interface.d.ts +12 -0
  6. package/dist/adapters/interface.d.ts.map +1 -1
  7. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  8. package/dist/analyzer.d.ts +61 -1
  9. package/dist/analyzer.d.ts.map +1 -1
  10. package/dist/async-action-refusal.d.ts +45 -0
  11. package/dist/async-action-refusal.d.ts.map +1 -0
  12. package/dist/builtin-lowering-plugins.d.ts.map +1 -1
  13. package/dist/compiler.d.ts.map +1 -1
  14. package/dist/component-root-scope-comment.d.ts +36 -0
  15. package/dist/component-root-scope-comment.d.ts.map +1 -0
  16. package/dist/debug.d.ts +61 -5
  17. package/dist/debug.d.ts.map +1 -1
  18. package/dist/errors.d.ts +7 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/event-handler-name.d.ts +13 -0
  21. package/dist/event-handler-name.d.ts.map +1 -0
  22. package/dist/expression-parser.d.ts +9 -0
  23. package/dist/expression-parser.d.ts.map +1 -1
  24. package/dist/format-date-refusal.d.ts +33 -0
  25. package/dist/format-date-refusal.d.ts.map +1 -0
  26. package/dist/index.d.ts +6 -4
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +3260 -1914
  29. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/compute-scope.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/plan/build-branch-loop.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  39. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/control-flow/plan/lazy-row-eligibility.d.ts +1 -1
  41. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +57 -12
  42. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/control-flow/shared.d.ts +44 -3
  44. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +7 -5
  46. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/declaration-sort.d.ts +2 -1
  49. package/dist/ir-to-client-js/declaration-sort.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/emit-module-level.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/emit-reactive.d.ts +43 -2
  52. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  55. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +7 -5
  56. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  57. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  58. package/dist/ir-to-client-js/reactivity.d.ts +9 -1
  59. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  60. package/dist/ir-to-client-js/source-map.d.ts.map +1 -1
  61. package/dist/ir-to-client-js/types.d.ts +4 -0
  62. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/utils.d.ts +66 -1
  64. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  65. package/dist/jsx-to-ir.d.ts.map +1 -1
  66. package/dist/opaque-local-accessor.d.ts +27 -0
  67. package/dist/opaque-local-accessor.d.ts.map +1 -0
  68. package/dist/signal-initializer.d.ts +24 -0
  69. package/dist/signal-initializer.d.ts.map +1 -0
  70. package/dist/template-position-walk.d.ts +68 -0
  71. package/dist/template-position-walk.d.ts.map +1 -0
  72. package/dist/to-locale-date-lowering.d.ts +7 -4
  73. package/dist/to-locale-date-lowering.d.ts.map +1 -1
  74. package/dist/types.d.ts +104 -17
  75. package/dist/types.d.ts.map +1 -1
  76. package/package.json +2 -2
  77. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +878 -4528
  78. package/src/__tests__/action-accessor.test.ts +166 -0
  79. package/src/__tests__/binding-scope-ratchet.test.ts +21 -10
  80. package/src/__tests__/branch-local-in-raw-capture.test.ts +1 -1
  81. package/src/__tests__/branch-local-same-name-collision.test.ts +9 -9
  82. package/src/__tests__/client-js-generation.test.ts +175 -0
  83. package/src/__tests__/component-root-scope-comment.test.ts +106 -0
  84. package/src/__tests__/create-mutation.test.ts +220 -0
  85. package/src/__tests__/create-query.test.ts +644 -0
  86. package/src/__tests__/csr-fragment-root-scope-shape.test.ts +156 -0
  87. package/src/__tests__/debug.test.ts +222 -0
  88. package/src/__tests__/doc-examples.test.ts +78 -25
  89. package/src/__tests__/event-handler-name.test.ts +74 -0
  90. package/src/__tests__/flatmap-segments.test.ts +11 -9
  91. package/src/__tests__/format-date-refusal.test.ts +134 -0
  92. package/src/__tests__/fragment-wrapped-conditional-return-branch.test.ts +132 -0
  93. package/src/__tests__/hydrate-template.test.ts +9 -1
  94. package/src/__tests__/issue-2798-static-nested-loop-bindings.test.ts +2 -2
  95. package/src/__tests__/issue-3009-loop-branch-ref.test.ts +2 -2
  96. package/src/__tests__/issue-3044-nested-prop-object-array-not-static.test.ts +213 -0
  97. package/src/__tests__/issue-3113-init-fn-name-collision.test.ts +133 -0
  98. package/src/__tests__/jsx-return-type-assertion.test.ts +2 -2
  99. package/src/__tests__/lazy-row-eligibility.test.ts +5 -4
  100. package/src/__tests__/loop-row-child-children-reactive-attrs.test.ts +108 -0
  101. package/src/__tests__/loop-row-child-text-children-markers.test.ts +158 -0
  102. package/src/__tests__/opaque-local-accessor.test.ts +90 -0
  103. package/src/__tests__/profiler-e2e.test.ts +13 -8
  104. package/src/__tests__/props-destructuring.test.ts +79 -4
  105. package/src/__tests__/reactive-factory-arity.test.ts +311 -0
  106. package/src/__tests__/ref-attr-absent-at-ssr.test.ts +472 -0
  107. package/src/__tests__/ssr-portal-ref-callback.test.ts +219 -0
  108. package/src/action-accessor.ts +289 -0
  109. package/src/adapters/env-signal.ts +2 -21
  110. package/src/adapters/interface.ts +13 -0
  111. package/src/adapters/jsx-adapter.ts +17 -0
  112. package/src/analyzer.ts +589 -60
  113. package/src/async-action-refusal.ts +254 -0
  114. package/src/builtin-lowering-plugins.ts +0 -2
  115. package/src/compiler.ts +27 -0
  116. package/src/component-root-scope-comment.ts +59 -0
  117. package/src/debug.ts +318 -103
  118. package/src/errors.ts +83 -1
  119. package/src/event-handler-name.ts +14 -0
  120. package/src/expression-parser.ts +41 -17
  121. package/src/format-date-refusal.ts +147 -0
  122. package/src/index.ts +14 -3
  123. package/src/ir-to-client-js/build-references.ts +6 -2
  124. package/src/ir-to-client-js/child-components.ts +8 -3
  125. package/src/ir-to-client-js/collect-elements.ts +28 -13
  126. package/src/ir-to-client-js/compute-inlinability.ts +2 -1
  127. package/src/ir-to-client-js/compute-scope.ts +3 -1
  128. package/src/ir-to-client-js/control-flow/plan/build-branch-loop.ts +2 -4
  129. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +67 -5
  130. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +3 -6
  131. package/src/ir-to-client-js/control-flow/plan/build-insert.ts +1 -0
  132. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +2 -1
  133. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +23 -11
  134. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  135. package/src/ir-to-client-js/control-flow/plan/lazy-row-eligibility.ts +3 -3
  136. package/src/ir-to-client-js/control-flow/plan/loop.ts +51 -10
  137. package/src/ir-to-client-js/control-flow/shared.ts +78 -5
  138. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +25 -12
  139. package/src/ir-to-client-js/control-flow/stringify/insert.ts +1 -1
  140. package/src/ir-to-client-js/csr-substitute.ts +11 -3
  141. package/src/ir-to-client-js/declaration-sort.ts +7 -3
  142. package/src/ir-to-client-js/emit-module-level.ts +7 -4
  143. package/src/ir-to-client-js/emit-reactive.ts +140 -10
  144. package/src/ir-to-client-js/emit-registration.ts +6 -11
  145. package/src/ir-to-client-js/generate-init.ts +2 -2
  146. package/src/ir-to-client-js/html-template.ts +41 -19
  147. package/src/ir-to-client-js/index.ts +9 -3
  148. package/src/ir-to-client-js/phases/ref-callbacks.ts +1 -1
  149. package/src/ir-to-client-js/plan/build-declaration-emit.ts +16 -15
  150. package/src/ir-to-client-js/plan/declaration-emit.ts +7 -5
  151. package/src/ir-to-client-js/prop-handling.ts +4 -0
  152. package/src/ir-to-client-js/reactivity.ts +21 -16
  153. package/src/ir-to-client-js/source-map.ts +2 -1
  154. package/src/ir-to-client-js/stringify/declaration-emit.ts +14 -7
  155. package/src/ir-to-client-js/types.ts +4 -0
  156. package/src/ir-to-client-js/utils.ts +89 -7
  157. package/src/jsx-to-ir.ts +772 -50
  158. package/src/opaque-local-accessor.ts +44 -0
  159. package/src/rich-type-refusal.ts +1 -1
  160. package/src/signal-initializer.ts +36 -0
  161. package/src/template-position-walk.ts +203 -0
  162. package/src/to-locale-date-lowering.ts +7 -4
  163. package/src/types.ts +103 -15
  164. package/dist/format-date-lowering.d.ts +0 -30
  165. package/dist/format-date-lowering.d.ts.map +0 -1
  166. package/src/__tests__/create-selector.test.ts +0 -124
  167. package/src/__tests__/format-date-lowering.test.ts +0 -125
  168. package/src/format-date-lowering.ts +0 -55
package/src/analyzer.ts CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  import ts from 'typescript'
10
10
  import { CLIENT_DIRECTIVE_INTERIOR_RE, USE_CLIENT_DIRECTIVE, isUseClientDirectiveText } from './directives.ts'
11
- import type { ImportSpecifier, TypeInfo, ParamInfo, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation } from './types.ts'
11
+ import type { ImportSpecifier, TypeInfo, ParamInfo, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation, SignalFactoryCall } from './types.ts'
12
12
  import { parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr } from './expression-parser.ts'
13
13
  import type { CallbackBodyAcceptor } from './adapters/interface.ts'
14
14
  import { rewriteBarePropRefs } from './prop-rewrite.ts'
@@ -31,6 +31,7 @@ import { baseTypeName } from './rich-type-evidence.ts'
31
31
  import { CATALOGUED_RICH_TYPE_NAMES } from './date-lowering.ts'
32
32
  import path from 'node:path'
33
33
  import fs from 'node:fs'
34
+ import { signalSecondBinding } from './signal-initializer.ts'
34
35
 
35
36
  // =============================================================================
36
37
  // TypeScript Program Creation
@@ -55,11 +56,6 @@ export function needsTypeBasedDetection(source: string): boolean {
55
56
  if (REACTIVE_BRAND_PACKAGES.some(pkg => source.includes(pkg))) return true
56
57
  // BF023/BF024 nullable-key check needs getTypeAtLocation() on the key expression.
57
58
  if (/\.map\s*\(/.test(source)) return true
58
- // createSelector's returned accessor is Reactive<>-branded like a library
59
- // accessor above — a selector call outside any `.map()` (no loop in the
60
- // file at all) would otherwise skip the TypeChecker entirely and miss the
61
- // brand.
62
- if (source.includes('createSelector')) return true
63
59
  return false
64
60
  }
65
61
 
@@ -101,14 +97,29 @@ function findBrandPackageImportLoc(
101
97
  * imported types may resolve to `any` and the signal/memo regex fallback kicks in.
102
98
  * For full type resolution in build tools, pass a pre-built ts.Program via
103
99
  * CompileOptions.program instead.
100
+ *
101
+ * `hostOptions.currentDirectory` pins the directory a RELATIVE `filePath`
102
+ * (and the Program's own `getCurrentDirectory()`, which also roots
103
+ * `@types` discovery) resolves against, instead of `process.cwd()`. The
104
+ * Program still serves `source` at the relative name, so
105
+ * `program.getSourceFile(filePath)` resolves to it and the result can be
106
+ * handed to `compileJSX` as `CompileOptions.program` under that same
107
+ * relative `filePath`. Used by the conformance harness
108
+ * (`packages/adapter-tests/src/harness-program.ts`) to compile fixtures
109
+ * under a relative virtual name without its type resolution depending on
110
+ * where the process was started (#3220). Omitted, behaviour is unchanged.
104
111
  */
105
112
  export function createProgramForFile(
106
113
  source: string,
107
- filePath: string
114
+ filePath: string,
115
+ hostOptions: { currentDirectory?: string } = {}
108
116
  ): { program: ts.Program; sourceFile: ts.SourceFile; checker: ts.TypeChecker } | null {
109
117
  incrementCounter('programCreations')
110
118
  try {
111
- const normalizedPath = path.resolve(filePath)
119
+ const { currentDirectory } = hostOptions
120
+ const resolveFrom = (fileName: string): string =>
121
+ currentDirectory === undefined ? path.resolve(fileName) : path.resolve(currentDirectory, fileName)
122
+ const normalizedPath = resolveFrom(filePath)
112
123
 
113
124
  const compilerOptions: ts.CompilerOptions = {
114
125
  target: ts.ScriptTarget.Latest,
@@ -125,18 +136,19 @@ export function createProgramForFile(
125
136
 
126
137
  const virtualHost: ts.CompilerHost = {
127
138
  ...defaultHost,
139
+ ...(currentDirectory === undefined ? {} : { getCurrentDirectory: () => currentDirectory }),
128
140
  getSourceFile(fileName, languageVersion) {
129
- if (path.resolve(fileName) === normalizedPath) {
141
+ if (resolveFrom(fileName) === normalizedPath) {
130
142
  return ts.createSourceFile(fileName, source, languageVersion, true, ts.ScriptKind.TSX)
131
143
  }
132
144
  return defaultHost.getSourceFile(fileName, languageVersion)
133
145
  },
134
146
  fileExists(fileName) {
135
- if (path.resolve(fileName) === normalizedPath) return true
147
+ if (resolveFrom(fileName) === normalizedPath) return true
136
148
  return defaultHost.fileExists(fileName)
137
149
  },
138
150
  readFile(fileName) {
139
- if (path.resolve(fileName) === normalizedPath) return source
151
+ if (resolveFrom(fileName) === normalizedPath) return source
140
152
  return defaultHost.readFile(fileName)
141
153
  },
142
154
  }
@@ -153,6 +165,26 @@ export function createProgramForFile(
153
165
  }
154
166
  }
155
167
 
168
+ /**
169
+ * The Program to pass as `compileJSX`'s `program` when a test harness
170
+ * compiles `source` under the relative virtual `filename`, with type
171
+ * resolution anchored at `anchorDir` instead of `process.cwd()` — or
172
+ * `undefined` when the compiler would not build a checker for this source.
173
+ *
174
+ * Without it, a harness compile resolves `@barefootjs/*` relative to the
175
+ * directory `bun test` was started from, so a `Reactive<T>` accessor read
176
+ * such as `fetchPosts.isPending()` is typed `any` from the repo root and
177
+ * its real type from a package (#3220). `anchorDir` need not exist: module
178
+ * resolution only probes its ancestors for `node_modules`. The one
179
+ * implementation for every harness that compiles under relative names:
180
+ * the conformance harness (`packages/adapter-tests/src/harness-program.ts`)
181
+ * and the docs-example suite (`doc-examples.test.ts`).
182
+ */
183
+ export function createAnchoredProgram(source: string, filename: string, anchorDir: string): ts.Program | undefined {
184
+ if (!needsTypeBasedDetection(source)) return undefined
185
+ return createProgramForFile(source, filename, { currentDirectory: anchorDir })?.program
186
+ }
187
+
156
188
  // =============================================================================
157
189
  // Main Entry Point
158
190
  // =============================================================================
@@ -1147,6 +1179,22 @@ const PRIMITIVE_CANONICAL_NAMES: Record<string, 'signal' | 'memo' | 'effect' | '
1147
1179
  // is recorded separately on the collected signal so adapters can lower the
1148
1180
  // reader value; the reactivity kind itself is just `signal`.
1149
1181
  createSearchParams: 'signal',
1182
+ // Async reactive factories (#3165) return a `[value, action]` tuple whose
1183
+ // value half is a signal getter, so they resolve to the `signal` kind too;
1184
+ // SIGNAL_FACTORY_KINDS below records which factory it was.
1185
+ createQuery: 'signal',
1186
+ createMutation: 'signal',
1187
+ }
1188
+
1189
+ /**
1190
+ * Async reactive factories → their `SignalFactoryCall` kind (#3165). The value
1191
+ * half of the tuple is collected as a signal seeded from `options.initial`;
1192
+ * the kind tells every backend that re-emits the declaration to call the
1193
+ * factory instead of `createSignal`.
1194
+ */
1195
+ const SIGNAL_FACTORY_KINDS: Record<string, SignalFactoryCall['kind']> = {
1196
+ createQuery: 'query',
1197
+ createMutation: 'mutation',
1150
1198
  }
1151
1199
 
1152
1200
  /**
@@ -1276,15 +1324,41 @@ function resolveEnvSignalKey(
1276
1324
  callExpr: ts.CallExpression,
1277
1325
  ctx: AnalyzerContext
1278
1326
  ): string | null {
1327
+ return resolveClientFactoryEntry(callExpr, ENV_SIGNAL_FACTORIES, ctx)
1328
+ }
1329
+
1330
+ /**
1331
+ * Resolve a call expression to the {@link SIGNAL_FACTORY_KINDS} kind of the
1332
+ * async reactive factory it calls (`createQuery(...)` → `'query'`), or null.
1333
+ * Same fast/slow paths as {@link resolveEnvSignalKey}.
1334
+ */
1335
+ function resolveSignalFactoryKind(
1336
+ callExpr: ts.CallExpression,
1337
+ ctx: AnalyzerContext
1338
+ ): SignalFactoryCall['kind'] | null {
1339
+ return resolveClientFactoryEntry(callExpr, SIGNAL_FACTORY_KINDS, ctx)
1340
+ }
1341
+
1342
+ /**
1343
+ * Look a call's callee up in a table keyed by `@barefootjs/client` export
1344
+ * names: the direct name, an alias resolved through the checker, or a
1345
+ * `bf.<name>` namespace access. Shared by the env-signal and async-factory
1346
+ * resolvers above.
1347
+ */
1348
+ function resolveClientFactoryEntry<T>(
1349
+ callExpr: ts.CallExpression,
1350
+ table: Record<string, T>,
1351
+ ctx: AnalyzerContext
1352
+ ): T | null {
1279
1353
  if (ts.isIdentifier(callExpr.expression)) {
1280
- const key = ENV_SIGNAL_FACTORIES[callExpr.expression.text]
1281
- if (key) return key
1354
+ const hit = table[callExpr.expression.text]
1355
+ if (hit) return hit
1282
1356
  const canonical = resolveCanonicalClientExportName(callExpr.expression, ctx)
1283
- return canonical ? (ENV_SIGNAL_FACTORIES[canonical] ?? null) : null
1357
+ return canonical ? (table[canonical] ?? null) : null
1284
1358
  }
1285
1359
  if (ts.isPropertyAccessExpression(callExpr.expression)) {
1286
- const key = ENV_SIGNAL_FACTORIES[callExpr.expression.name.text]
1287
- if (key && isBarefootClientNamespace(callExpr.expression.expression, ctx)) return key
1360
+ const hit = table[callExpr.expression.name.text]
1361
+ if (hit && isBarefootClientNamespace(callExpr.expression.expression, ctx)) return hit
1288
1362
  }
1289
1363
  return null
1290
1364
  }
@@ -1328,6 +1402,11 @@ function isSignalDeclaration(node: ts.VariableDeclaration, ctx: AnalyzerContext)
1328
1402
  function collectSignal(node: ts.VariableDeclaration, ctx: AnalyzerContext): void {
1329
1403
  const pattern = node.name as ts.ArrayBindingPattern
1330
1404
  const callExpr = node.initializer as ts.CallExpression
1405
+ const factoryKind = resolveSignalFactoryKind(callExpr, ctx)
1406
+ if (factoryKind) {
1407
+ collectFactorySignal(node, pattern, callExpr, factoryKind, ctx)
1408
+ return
1409
+ }
1331
1410
 
1332
1411
  const elements = pattern.elements
1333
1412
  // Getter-elided form: `const [, setActive] = createSignal(0)`. The first
@@ -1413,6 +1492,137 @@ function collectSignal(node: ts.VariableDeclaration, ctx: AnalyzerContext): void
1413
1492
  })
1414
1493
  }
1415
1494
 
1495
+ /**
1496
+ * Collect `const [value, action] = createQuery(fn, options)` (#3165) or
1497
+ * `createMutation(fn, options)` (#3210) as a signal whose getter is the value
1498
+ * and whose initial value is `options.initial` (a query) or `undefined` (a
1499
+ * mutation, which has no `initial`: spec/async.md §7.4). The action is
1500
+ * recorded on `factory`, never as a setter, so setter-keyed logic
1501
+ * (controlled-prop sync, handler→setter wiring, SSR setter stubs) leaves it
1502
+ * alone.
1503
+ *
1504
+ * `initial` is read structurally from an object-literal `options` with no
1505
+ * spread: its value expression when the key is present, the literal
1506
+ * `undefined` when it isn't. Any other `options`
1507
+ * shape seeds from the member read `(<options>).initial`, which each backend
1508
+ * lowers or refuses like any other expression — never a guess.
1509
+ */
1510
+ function collectFactorySignal(
1511
+ node: ts.VariableDeclaration,
1512
+ pattern: ts.ArrayBindingPattern,
1513
+ callExpr: ts.CallExpression,
1514
+ kind: SignalFactoryCall['kind'],
1515
+ ctx: AnalyzerContext,
1516
+ ): void {
1517
+ const elements = pattern.elements
1518
+ const bindingName = (el: ts.ArrayBindingElement | undefined): string | null =>
1519
+ el && ts.isBindingElement(el) && ts.isIdentifier(el.name) ? el.name.text : null
1520
+ // BF115 reports any other destructure shape; nothing is collected for it.
1521
+ if (elements.length < 1 || elements.length > 2) return
1522
+ const getterElided = ts.isOmittedExpression(elements[0])
1523
+ const valueName = getterElided ? null : bindingName(elements[0])
1524
+ if (!getterElided && valueName === null) return
1525
+ const action = elements.length === 2 ? bindingName(elements[1]) : null
1526
+ if (elements.length === 2 && action === null) return
1527
+ if (getterElided && action === null) return
1528
+
1529
+ // A mutation's value is `undefined` until its action is called; an
1530
+ // `initial` it was given anyway is refused (BF118), never read.
1531
+ const initialNode: FactoryInitialNode = kind === 'mutation'
1532
+ ? { kind: 'absent' }
1533
+ : factoryInitialNode(callExpr.arguments[1])
1534
+ const initialValue = initialNode.kind === 'expression'
1535
+ ? ctx.getJS(initialNode.node)
1536
+ : initialNode.kind === 'member-read'
1537
+ ? `(${ctx.getJS(initialNode.options)}).initial`
1538
+ : 'undefined'
1539
+ const typedInitialValue = initialNode.kind === 'expression'
1540
+ ? initialNode.node.getText(ctx.sourceFile)
1541
+ : initialNode.kind === 'member-read'
1542
+ ? `(${initialNode.options.getText(ctx.sourceFile)}).initial`
1543
+ : undefined
1544
+ const initialFreeIdentifiers = initialNode.kind === 'expression'
1545
+ ? extractFreeIdentifiersFromNode(initialNode.node)
1546
+ : initialNode.kind === 'member-read'
1547
+ ? extractFreeIdentifiersFromNode(initialNode.options)
1548
+ : new Set<string>()
1549
+
1550
+ let type: TypeInfo = { kind: 'unknown', raw: 'unknown' }
1551
+ if (callExpr.typeArguments && callExpr.typeArguments.length > 0) {
1552
+ type = typeNodeToTypeInfo(callExpr.typeArguments[0], ctx.sourceFile) ?? type
1553
+ } else if (initialNode.kind !== 'absent') {
1554
+ type = inferTypeFromValue(initialValue)
1555
+ }
1556
+
1557
+ // Destructured-arg components (#2265): the CSR `template:` arrow's
1558
+ // module-scope fallback needs `_p.<name>` for a bare destructured prop in
1559
+ // `initial`, same as a `createSignal` initial value.
1560
+ let templateInitialValue: string | undefined
1561
+ if (!ctx.propsObjectName && initialNode.kind === 'expression') {
1562
+ const propNames = new Set(ctx.propsParams.map(p => p.name))
1563
+ if (propNames.size > 0) {
1564
+ const propAliases = buildPropAliasMap(ctx.propsParams)
1565
+ templateInitialValue = rewriteBarePropRefs(initialValue, initialNode.node, propNames, undefined, propAliases)
1566
+ }
1567
+ }
1568
+
1569
+ const argTexts = callExpr.arguments.map(arg => ctx.getJS(arg))
1570
+ const requestArg = callExpr.arguments[0]
1571
+
1572
+ ctx.signals.push({
1573
+ getter: valueName ?? `__bfGet_${action}`,
1574
+ setter: null,
1575
+ getterElided: getterElided || undefined,
1576
+ initialValue,
1577
+ typedInitialValue: typedInitialValue !== undefined && typedInitialValue !== initialValue ? typedInitialValue : undefined,
1578
+ templateInitialValue,
1579
+ type,
1580
+ loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
1581
+ initialFreeIdentifiers,
1582
+ factory: {
1583
+ kind,
1584
+ callee: callExpr.expression.getText(ctx.sourceFile),
1585
+ argsText: argTexts.join(', '),
1586
+ requestText: argTexts[0] ?? '',
1587
+ requestFreeIdentifiers: requestArg ? extractFreeIdentifiersFromNode(requestArg) : new Set(),
1588
+ action,
1589
+ },
1590
+ })
1591
+ }
1592
+
1593
+ /**
1594
+ * Where an async factory's `initial` comes from (#3165): the `initial`
1595
+ * property's value in an object-literal `options` (`expression`), nothing
1596
+ * (`absent` — no `options`, or a literal without the key), or a member read
1597
+ * of `options` itself when the literal can't be read structurally (spread,
1598
+ * computed key, accessor) or `options` isn't a literal at all (`member-read`).
1599
+ */
1600
+ type FactoryInitialNode =
1601
+ | { kind: 'expression'; node: ts.Expression }
1602
+ | { kind: 'absent' }
1603
+ | { kind: 'member-read'; options: ts.Expression }
1604
+
1605
+ function factoryInitialNode(options: ts.Expression | undefined): FactoryInitialNode {
1606
+ if (!options) return { kind: 'absent' }
1607
+ let unwrapped: ts.Expression = options
1608
+ while (ts.isParenthesizedExpression(unwrapped) || ts.isAsExpression(unwrapped) || ts.isSatisfiesExpression(unwrapped)) {
1609
+ unwrapped = unwrapped.expression
1610
+ }
1611
+ if (!ts.isObjectLiteralExpression(unwrapped)) return { kind: 'member-read', options }
1612
+ let found: ts.Expression | null = null
1613
+ for (const prop of unwrapped.properties) {
1614
+ if (ts.isSpreadAssignment(prop)) return { kind: 'member-read', options }
1615
+ const name = prop.name
1616
+ if (name === undefined || ts.isComputedPropertyName(name)) return { kind: 'member-read', options }
1617
+ const key = ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name) ? name.text : null
1618
+ if (key !== 'initial') continue
1619
+ if (ts.isPropertyAssignment(prop)) found = prop.initializer
1620
+ else if (ts.isShorthandPropertyAssignment(prop)) found = prop.name
1621
+ else return { kind: 'member-read', options }
1622
+ }
1623
+ return found ? { kind: 'expression', node: found } : { kind: 'absent' }
1624
+ }
1625
+
1416
1626
  /**
1417
1627
  * Detects `const s = createSignal(...)` — the tuple is stored in an
1418
1628
  * Identifier rather than destructured. The accessor(s) appear in later
@@ -1982,21 +2192,31 @@ const MUTATING_METHOD_NAMES: ReadonlySet<string> = new Set([
1982
2192
  * binding) silently drops everything the mutation was supposed to do. See
1983
2193
  * `ConstantInfo.mutatedAfterDeclaration` for where this is consumed.
1984
2194
  */
2195
+ /**
2196
+ * The identifier a (possibly chained) member/element-access/parenthesized/
2197
+ * non-null-asserted expression is ultimately rooted at (`a.b.c`, `a?.b[0]`,
2198
+ * `(a!).b` all resolve to `a`), or `null` when the root isn't a bare
2199
+ * identifier (e.g. a call result). Shared by `extractMutatedIdentifiersFromNode`
2200
+ * below and `isArrayExprDirectPropRef` (`jsx-to-ir.ts`, #3044 pullfrog
2201
+ * review) — the same "walk a member chain to its root" question, structural
2202
+ * and side-effect-free, so one implementation serves both instead of a
2203
+ * second inline while-loop reinventing it with narrower node coverage.
2204
+ */
2205
+ export function rootIdentifierOf(expr: ts.Expression): string | null {
2206
+ let current: ts.Expression = expr
2207
+ while (true) {
2208
+ if (ts.isIdentifier(current)) return current.text
2209
+ if (ts.isParenthesizedExpression(current)) { current = current.expression; continue }
2210
+ if (ts.isNonNullExpression(current)) { current = current.expression; continue }
2211
+ if (ts.isPropertyAccessExpression(current)) { current = current.expression; continue }
2212
+ if (ts.isElementAccessExpression(current)) { current = current.expression; continue }
2213
+ return null
2214
+ }
2215
+ }
2216
+
1985
2217
  function extractMutatedIdentifiersFromNode(node: ts.Node): Set<string> {
1986
2218
  const ids = new Set<string>()
1987
2219
 
1988
- function rootIdentifierOf(expr: ts.Expression): string | null {
1989
- let current: ts.Expression = expr
1990
- while (true) {
1991
- if (ts.isIdentifier(current)) return current.text
1992
- if (ts.isParenthesizedExpression(current)) { current = current.expression; continue }
1993
- if (ts.isNonNullExpression(current)) { current = current.expression; continue }
1994
- if (ts.isPropertyAccessExpression(current)) { current = current.expression; continue }
1995
- if (ts.isElementAccessExpression(current)) { current = current.expression; continue }
1996
- return null
1997
- }
1998
- }
1999
-
2000
2220
  function visit(n: ts.Node): void {
2001
2221
  // Same init/sub-init boundary as `extractAssignedIdentifiersFromNode`:
2002
2222
  // a mutation inside a nested function literal doesn't run at init time.
@@ -2124,26 +2344,31 @@ function collectLocalDeclarations(root: ts.Node): Set<string> {
2124
2344
  // and are emitted by the compiler for 'use client' components.
2125
2345
  const CLIENT_EXPORTS = new Set([
2126
2346
  'createSignal', 'createEffect', 'createDisposableEffect', 'createMemo',
2127
- 'createSelector',
2128
2347
  'createRoot', 'onCleanup', 'onMount', 'untrack', 'batch', 'splitProps',
2129
2348
  'forwardProps', 'unwrap', '__slot',
2130
2349
  'createContext', 'useContext', 'provideContext',
2131
- 'createPortal', 'isSSRPortal', 'findSiblingSlot', 'cleanupPortalPlaceholder',
2132
- // Floating-element position tracking (#2848) — same runtime-only shape
2133
- // as the portal entries above.
2134
- 'trackPosition',
2350
+ 'createPortal', 'isSSRPortal', 'findSiblingSlot',
2135
2351
  // Request-scoped environment signal factory (router v0.5) — `createSignal`-
2136
2352
  // shaped, recognised structurally (#2057) so its getter is just a signal
2137
2353
  // getter; the compiler lowers the reader value per adapter via the signal's
2138
2354
  // `envReader` key, with no `searchParams`-name allow-list.
2139
2355
  'createSearchParams',
2356
+ // Async layer 0 (spec/async.md §7): `http` descriptors and `HttpError`
2357
+ // (#3161), and `createQuery` (#3165) / `createMutation` (#3210),
2358
+ // recognised structurally as factory signals.
2359
+ 'http', 'HttpError', 'createQuery', 'createMutation',
2140
2360
  // Pure URL-query builder (#2042) — the functional counterpart to
2141
2361
  // `searchParams`. Runs natively on the client; SSR adapters lower a
2142
2362
  // `queryHref(base, { … })` call to their query helper (go-template: `bf_query`).
2143
2363
  'queryHref',
2144
- // Pure date formatter (#2324). Runs natively on the client; SSR adapters
2145
- // lower a `formatDate(date, pattern, tz)` call to their `format_date`
2146
- // helper (spec/template-helpers.md).
2364
+ // Pure date formatter (#2324), demoted to compiler ABI in #3089: it is
2365
+ // still a REAL (now `@internal`) export — the lowering TARGET the
2366
+ // `.toLocaleDateString()` sugar rewrites to, and the emitted client JS's
2367
+ // own import — so it stays in this set to keep `WRONG_PACKAGE_IMPORT`'s
2368
+ // "is this actually exported" check truthful (same reasoning as
2369
+ // `forwardProps`/`unwrap` above, also `@internal` and also still listed).
2370
+ // An AUTHORED call is refused separately and more specifically by
2371
+ // `format-date-refusal.ts`'s BF056, which fires regardless of this entry.
2147
2372
  'formatDate',
2148
2373
  // Compile-away JSX built-ins (#1915) — importing them is what scopes the
2149
2374
  // compiler's `<Async>` / `<Region>` recognition; the import is elided on emit.
@@ -2869,6 +3094,7 @@ function collectFunction(
2869
3094
  declarationKind: 'function',
2870
3095
  isModule: _isModule || undefined,
2871
3096
  isJsxFunction: isJsxFunction || undefined,
3097
+ freeIdentifiers: extractFreeIdentifiersFromNode(node),
2872
3098
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
2873
3099
  })
2874
3100
  }
@@ -3422,6 +3648,12 @@ function collectConstant(
3422
3648
 
3423
3649
  // Compute AST-derived flags for Phase 2 optimization
3424
3650
  const containsArrow = node.initializer ? nodeContainsArrow(node.initializer) : false
3651
+ let unwrappedInitializer: ts.Expression | undefined = node.initializer
3652
+ while (unwrappedInitializer && (ts.isParenthesizedExpression(unwrappedInitializer) || ts.isAsExpression(unwrappedInitializer) || ts.isSatisfiesExpression(unwrappedInitializer))) {
3653
+ unwrappedInitializer = unwrappedInitializer.expression
3654
+ }
3655
+ const isFunctionValue = unwrappedInitializer !== undefined &&
3656
+ (ts.isArrowFunction(unwrappedInitializer) || ts.isFunctionExpression(unwrappedInitializer))
3425
3657
  const systemConstructKind = node.initializer ? getSystemConstructKind(node.initializer) : undefined
3426
3658
 
3427
3659
  // Pre-transform bare prop refs for template inlining (#807). Two
@@ -3466,7 +3698,8 @@ function collectConstant(
3466
3698
  const shadowedByNonAlias = new Set<string>()
3467
3699
  for (const s of ctx.signals) {
3468
3700
  shadowedByNonAlias.add(s.getter)
3469
- if (s.setter) shadowedByNonAlias.add(s.setter)
3701
+ const second = signalSecondBinding(s)
3702
+ if (second) shadowedByNonAlias.add(second)
3470
3703
  }
3471
3704
  for (const m of ctx.memos) shadowedByNonAlias.add(m.name)
3472
3705
  const aliases = new Set<string>()
@@ -3530,6 +3763,7 @@ function collectConstant(
3530
3763
  isJsx,
3531
3764
  isJsxFunction: isJsxFunction || undefined,
3532
3765
  containsArrow: containsArrow || undefined,
3766
+ isFunctionValue: isFunctionValue || undefined,
3533
3767
  systemConstructKind,
3534
3768
  templateValue,
3535
3769
  origin: {
@@ -3697,7 +3931,10 @@ function collectKeysFromMembers(
3697
3931
  *
3698
3932
  * `array`/`object` admit only when EVERY reachable leaf resolves — an
3699
3933
  * array's element type and an object's every property type must pass this
3700
- * same check, recursively. A union, a function, or an un-catalogued named
3934
+ * same check, recursively. A same-file object type referenced by name
3935
+ * (`Item` in `items: Item[]`) is checked through its declaration's members
3936
+ * (`LocalObjectMemberTypes`) the same way an inline object literal's are.
3937
+ * A union, a function, or any other named
3701
3938
  * type reachable ANYWHERE inside the shape declines the WHOLE member (not
3702
3939
  * just that one leaf): `collectMemberTypes` is an all-or-nothing gate per
3703
3940
  * member, so a partially-resolvable structural type must still decline —
@@ -3722,22 +3959,91 @@ function collectKeysFromMembers(
3722
3959
  * synthesized struct is exactly as faithful a representation as the type
3723
3960
  * itself claims, nothing is being guessed.
3724
3961
  */
3725
- function isResolvableMemberType(info: TypeInfo): boolean {
3962
+ function isResolvableMemberType(
3963
+ info: TypeInfo,
3964
+ localObjectMembers?: LocalObjectMemberTypes,
3965
+ visiting: ReadonlySet<string> = new Set(),
3966
+ ): boolean {
3967
+ const recurse = (t: TypeInfo): boolean => isResolvableMemberType(t, localObjectMembers, visiting)
3726
3968
  switch (info.kind) {
3727
3969
  case 'primitive':
3728
3970
  return info.primitive === 'string' || info.primitive === 'number' || info.primitive === 'boolean'
3729
- case 'interface':
3730
- return CATALOGUED_RICH_TYPE_NAMES.has(baseTypeName(info.raw))
3971
+ case 'interface': {
3972
+ if (CATALOGUED_RICH_TYPE_NAMES.has(baseTypeName(info.raw))) return true
3973
+ // A same-file object type referenced BY NAME (`initial: State`,
3974
+ // `items: Item[]`) is the same structural shape as its inline
3975
+ // spelling — see `LocalObjectMemberTypes`. A name already on the
3976
+ // resolution stack (a recursive type) declines rather than loop.
3977
+ if (!localObjectMembers || visiting.has(info.raw)) return false
3978
+ const members = localObjectMembers(info.raw)
3979
+ if (!members) return false
3980
+ const inner = new Set(visiting).add(info.raw)
3981
+ return members.every(t => isResolvableMemberType(t, localObjectMembers, inner))
3982
+ }
3731
3983
  case 'array':
3732
- return !!info.elementType && isResolvableMemberType(info.elementType)
3984
+ return !!info.elementType && recurse(info.elementType)
3733
3985
  case 'object':
3734
- return info.properties !== undefined && info.properties.every(prop => isResolvableMemberType(prop.type))
3986
+ return info.properties !== undefined && info.properties.every(prop => recurse(prop.type))
3735
3987
  // Unions, functions, and `unknown` all decline — see docstring.
3736
3988
  default:
3737
3989
  return false
3738
3990
  }
3739
3991
  }
3740
3992
 
3993
+ /**
3994
+ * Member types of a same-file, non-generic object type declared by name —
3995
+ * an `interface` with no `extends` clause, or a `type X = { … }` alias —
3996
+ * or `null` when `name` isn't one (an import, a generic, a union alias, an
3997
+ * interface with heritage, or a declaration with a non-property member such
3998
+ * as a method or index signature). #3142 follow-up: `{ initial }: {
3999
+ * initial: State }` declined to `unknown` while the `props`-object form
4000
+ * (`props: { initial: State }`, `extractPropsFromTypeMembers`) resolved
4001
+ * `State` — the same destructured-vs-props-object asymmetry #2677 closed
4002
+ * for INLINE object shapes, left open for NAMED ones. A named same-file
4003
+ * object type is exactly as representable as its inline spelling: it lands
4004
+ * in `ir.metadata.typeDefinitions`, and typed adapters already emit a
4005
+ * struct for it (go-template's `typeDefinitionToGo`), so admitting it
4006
+ * resurrects neither #2150 concern.
4007
+ */
4008
+ type LocalObjectMemberTypes = (name: string) => TypeInfo[] | null
4009
+
4010
+ function localObjectMemberTypesFor(ctx: AnalyzerContext): LocalObjectMemberTypes {
4011
+ // Each lookup walks the whole source file, and one props annotation can
4012
+ // reach the same name many times (`Item` from several `Item[]` members),
4013
+ // so answer each name once per annotation.
4014
+ const cache = new Map<string, TypeInfo[] | null>()
4015
+ const lookup = (name: string): TypeInfo[] | null => {
4016
+ // Exactly one declaration, or decline: two `interface State` blocks
4017
+ // merge into one type, and checking either half alone could admit a
4018
+ // shape whose other half carries a member this gate would refuse.
4019
+ const decls = findTypeDeclarations(name, ctx.sourceFile)
4020
+ if (decls.length !== 1) return null
4021
+ const decl = decls[0]
4022
+ if (decl.typeParameters?.length) return null
4023
+ let members: ts.NodeArray<ts.TypeElement>
4024
+ if (ts.isInterfaceDeclaration(decl)) {
4025
+ if (decl.heritageClauses?.length) return null
4026
+ members = decl.members
4027
+ } else if (ts.isTypeLiteralNode(decl.type)) {
4028
+ members = decl.type.members
4029
+ } else {
4030
+ return null
4031
+ }
4032
+ const types: TypeInfo[] = []
4033
+ for (const member of members) {
4034
+ if (!ts.isPropertySignature(member) || !member.type) return null
4035
+ const info = typeNodeToTypeInfo(member.type, ctx.sourceFile)
4036
+ if (!info) return null
4037
+ types.push(info)
4038
+ }
4039
+ return types
4040
+ }
4041
+ return (name) => {
4042
+ if (!cache.has(name)) cache.set(name, lookup(name))
4043
+ return cache.get(name) ?? null
4044
+ }
4045
+ }
4046
+
3741
4047
  /**
3742
4048
  * Build a property-name -> { type, optional } map from a props type
3743
4049
  * annotation, for destructured params (`{ value }: Props`) so they carry the
@@ -3753,9 +4059,10 @@ function isResolvableMemberType(info: TypeInfo): boolean {
3753
4059
  * #2252's nullish-flip machinery supplies the nillable representation
3754
4060
  * exactly where absence is semantically observable (#2259).
3755
4061
  * - A member resolves a type when it is a PRIMITIVE (string/number/boolean),
3756
- * a CATALOGUED rich type (`Date`), or a STRUCTURAL shape (array/object)
3757
- * built entirely out of those, recursively (#2677). Unions, functions, and
3758
- * un-catalogued named types (`Map`, `Set`, …) are left as `unknown` — see
4062
+ * a CATALOGUED rich type (`Date`), or a STRUCTURAL shape (array/object,
4063
+ * inline or a same-file object type referenced by name) built entirely
4064
+ * out of those, recursively (#2677). Unions, functions, and other named
4065
+ * types (imports, generics, `Map`, `Set`, …) are left as `unknown` — see
3759
4066
  * `isResolvableMemberType`'s own docstring for why the structural cases
3760
4067
  * are safe to admit and why those three still are not.
3761
4068
  */
@@ -3763,6 +4070,7 @@ function collectMemberTypes(
3763
4070
  typeNode: ts.TypeNode,
3764
4071
  ctx: AnalyzerContext
3765
4072
  ): Map<string, { type: TypeInfo | null; optional: boolean }> | null {
4073
+ const localObjectMembers = localObjectMemberTypesFor(ctx)
3766
4074
  const fromMembers = (
3767
4075
  members: ts.NodeArray<ts.TypeElement>
3768
4076
  ): Map<string, { type: TypeInfo | null; optional: boolean }> => {
@@ -3771,7 +4079,7 @@ function collectMemberTypes(
3771
4079
  if (ts.isPropertySignature(member) && member.name) {
3772
4080
  const info = member.type ? typeNodeToTypeInfo(member.type, ctx.sourceFile) : null
3773
4081
  map.set(member.name.getText(ctx.sourceFile), {
3774
- type: info && isResolvableMemberType(info) ? info : null,
4082
+ type: info && isResolvableMemberType(info, localObjectMembers) ? info : null,
3775
4083
  optional: !!member.questionToken,
3776
4084
  })
3777
4085
  }
@@ -3851,21 +4159,19 @@ function extractPropsFromTypeMembers(
3851
4159
  }
3852
4160
 
3853
4161
  /**
3854
- * Find a type declaration (interface or type alias) by name in the source file.
4162
+ * Every type declaration (interface or type alias) named `typeName` in the
4163
+ * source file, in source order. More than one means interface declaration
4164
+ * merging (or a name reused in nested scopes).
3855
4165
  */
3856
- function findTypeDeclaration(
4166
+ function findTypeDeclarations(
3857
4167
  typeName: string,
3858
4168
  sourceFile: ts.SourceFile
3859
- ): ts.InterfaceDeclaration | ts.TypeAliasDeclaration | undefined {
3860
- let result: ts.InterfaceDeclaration | ts.TypeAliasDeclaration | undefined
4169
+ ): Array<ts.InterfaceDeclaration | ts.TypeAliasDeclaration> {
4170
+ const result: Array<ts.InterfaceDeclaration | ts.TypeAliasDeclaration> = []
3861
4171
 
3862
4172
  function visit(node: ts.Node): void {
3863
- if (ts.isInterfaceDeclaration(node) && node.name.text === typeName) {
3864
- result = node
3865
- return
3866
- }
3867
- if (ts.isTypeAliasDeclaration(node) && node.name.text === typeName) {
3868
- result = node
4173
+ if ((ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) && node.name.text === typeName) {
4174
+ result.push(node)
3869
4175
  return
3870
4176
  }
3871
4177
  ts.forEachChild(node, visit)
@@ -3875,6 +4181,17 @@ function findTypeDeclaration(
3875
4181
  return result
3876
4182
  }
3877
4183
 
4184
+ /**
4185
+ * Find a type declaration (interface or type alias) by name in the source
4186
+ * file — the LAST one when the name is declared more than once.
4187
+ */
4188
+ function findTypeDeclaration(
4189
+ typeName: string,
4190
+ sourceFile: ts.SourceFile
4191
+ ): ts.InterfaceDeclaration | ts.TypeAliasDeclaration | undefined {
4192
+ return findTypeDeclarations(typeName, sourceFile).at(-1)
4193
+ }
4194
+
3878
4195
  // =============================================================================
3879
4196
  // Helpers
3880
4197
  // =============================================================================
@@ -4042,6 +4359,13 @@ function validateContext(ctx: AnalyzerContext): void {
4042
4359
  // failures before factory inlining landed (#931).
4043
4360
  validateReactiveFactoryCalls(ctx)
4044
4361
 
4362
+ // BF115/BF116: flag a RECOGNISED createSignal/createMemo call used with a
4363
+ // destructure arity or argument count it doesn't support — the gap
4364
+ // validateReactiveFactoryCalls above doesn't cover, since it exists to
4365
+ // validate an unrecognised callee and skips createSignal/createMemo
4366
+ // unconditionally (#3159).
4367
+ validateReactiveFactoryArity(ctx)
4368
+
4045
4369
  // BF013: flag a reactive primitive invoked through a namespace import
4046
4370
  // that the analyzer could not resolve (#2771) — same "silently dropped,
4047
4371
  // ReferenceError at hydrate" failure shape as BF011.
@@ -4364,7 +4688,8 @@ function collectResolvedNames(ctx: AnalyzerContext): Set<string> {
4364
4688
  for (const f of ctx.localFunctions) names.add(f.name)
4365
4689
  for (const s of ctx.signals) {
4366
4690
  names.add(s.getter)
4367
- if (s.setter) names.add(s.setter)
4691
+ const second = signalSecondBinding(s)
4692
+ if (second) names.add(second)
4368
4693
  }
4369
4694
  for (const m of ctx.memos) names.add(m.name)
4370
4695
  for (const p of ctx.propsParams) names.add(p.name)
@@ -4394,8 +4719,6 @@ export const BROWSER_ONLY_CLIENT_APIS = new Set([
4394
4719
  'createPortal',
4395
4720
  'isSSRPortal',
4396
4721
  'findSiblingSlot',
4397
- 'cleanupPortalPlaceholder',
4398
- 'trackPosition',
4399
4722
  ])
4400
4723
 
4401
4724
  function importsBrowserOnlyClientApi(ctx: AnalyzerContext): boolean {
@@ -6005,6 +6328,9 @@ export function validateReactiveFactoryCalls(ctx: AnalyzerContext): void {
6005
6328
  // import (`import { createSearchParams as csp }`) is accepted here too,
6006
6329
  // rather than falling through to a spurious BF110.
6007
6330
  if (resolveEnvSignalKey(decl.initializer, ctx)) continue
6331
+ // Async reactive factories (`createQuery`, #3165) return a
6332
+ // `[value, action]` tuple and are collected by `collectFactorySignal`.
6333
+ if (resolveSignalFactoryKind(decl.initializer, ctx)) continue
6008
6334
 
6009
6335
  const declinedEntry = ctx.declinedReactiveFactories.get(callee)
6010
6336
  if (declinedEntry) {
@@ -6060,6 +6386,209 @@ export function validateReactiveFactoryCalls(ctx: AnalyzerContext): void {
6060
6386
  }
6061
6387
  }
6062
6388
 
6389
+ /**
6390
+ * BF115 / BF116 (#3159): two `createSignal`/`createMemo` shapes that
6391
+ * mis-compiled silently before this pass existed, because
6392
+ * `validateReactiveFactoryCalls` above unconditionally `continue`s past any
6393
+ * array-pattern destructure whose callee is `createSignal`/`createMemo` —
6394
+ * it exists to validate an UNRECOGNISED callee, and never checked whether a
6395
+ * RECOGNISED one was actually called with a shape it supports.
6396
+ *
6397
+ * - **BF115 — tuple arity.** `createSignal(...)` returns `[getter, setter]`:
6398
+ * a 1-element destructure keeps just the getter (`setter: null`,
6399
+ * supported), but `collectSignal`'s `elements.length > 2` guard silently
6400
+ * returns with NOTHING pushed to `ctx.signals` for anything wider — the
6401
+ * whole declaration vanishes from the compiled output, and a same-name
6402
+ * prop (`const [user, setUser, extra] = createSignal(props.user)` next to
6403
+ * a `user` prop) silently mis-seeds `user` as the raw prop accessor
6404
+ * instead of the signal. `createMemo(...)` returns a single getter, not a
6405
+ * tuple, so ANY array-pattern destructure of it is a mismatch (it isn't
6406
+ * even reachable through `collectMemo`, which requires an identifier
6407
+ * binding — so today it silently produces nothing at all, not even an
6408
+ * opaque local).
6409
+ * - **BF116 — extra arguments.** `createSignal(initialValue?)` takes 0 or 1
6410
+ * argument; `createMemo(computeFn)` takes exactly 1; an env-signal factory
6411
+ * (`createSearchParams()`) takes none. `collectSignal`/
6412
+ * `collectMemo` only ever read `arguments[0]`, so any argument beyond it
6413
+ * (`createSignal(props.user, { from: 'router' })`) is silently dropped
6414
+ * from the emitted client JS with no diagnostic.
6415
+ *
6416
+ * Recognises the callee via `resolvePrimitiveKind` — the same
6417
+ * TypeChecker-backed, alias/namespace-import-safe resolution
6418
+ * `isSignalDeclaration`/`isMemoDeclaration` use — rather than the bare
6419
+ * identifier-text match `validateReactiveFactoryCalls` uses for BF110, so
6420
+ * an aliased import (`import { createSignal as sig }`) is still caught.
6421
+ *
6422
+ * This walks the analyzer's own parse of the ORIGINAL source AST (Phase 1),
6423
+ * which runs strictly before Phase 2 client-JS emission — the compiler's
6424
+ * own profile-mode `__bfId` argument (`ir-to-client-js/stringify/
6425
+ * declaration-emit.ts`, `profiler.ts`) is inserted later, during emission,
6426
+ * so it can never appear in a call this pass inspects and needs no
6427
+ * special-casing here.
6428
+ */
6429
+ function validateReactiveFactoryArity(ctx: AnalyzerContext): void {
6430
+ if (!ctx.componentNode) return
6431
+ const body = ts.isFunctionDeclaration(ctx.componentNode)
6432
+ ? ctx.componentNode.body
6433
+ : (ts.isBlock(ctx.componentNode.body) ? ctx.componentNode.body : null)
6434
+ if (!body) return
6435
+
6436
+ checkStatementsForReactiveFactoryArity(body.statements, ctx)
6437
+
6438
+ // Conditional early-return branches get their own signal collection path
6439
+ // (#1414 cell #8 — `collectBranchSignals`, called from the "if statement
6440
+ // with JSX return" case in `visitComponentBody` above): a top-level `if`
6441
+ // whose then-branch returns JSX has its *direct* statements scanned for
6442
+ // `createSignal` declarations too, so a bad-arity call there mis-compiles
6443
+ // exactly like a top-level one would, and needs the same diagnostic — not
6444
+ // just the top-level scan above, which the branch's statements are never
6445
+ // members of.
6446
+ for (const stmt of body.statements) {
6447
+ if (!ts.isIfStatement(stmt)) continue
6448
+ if (!findJsxReturnInBlock(stmt.thenStatement)) continue
6449
+ if (!ts.isBlock(stmt.thenStatement)) continue
6450
+ checkStatementsForReactiveFactoryArity(stmt.thenStatement.statements, ctx)
6451
+ }
6452
+ }
6453
+
6454
+ /**
6455
+ * BF115/BF116 over one flat list of statements — shared by the component
6456
+ * body's top-level scan and the conditional-branch scan above, both of
6457
+ * which only ever look at direct variable-statement children (never
6458
+ * recursing further), matching exactly what `collectSignal`/`collectMemo`
6459
+ * are reachable from in each case.
6460
+ */
6461
+ function checkStatementsForReactiveFactoryArity(statements: readonly ts.Statement[], ctx: AnalyzerContext): void {
6462
+ for (const stmt of statements) {
6463
+ if (!ts.isVariableStatement(stmt)) continue
6464
+ for (const decl of stmt.declarationList.declarations) {
6465
+ if (!decl.initializer || !ts.isCallExpression(decl.initializer)) continue
6466
+ const callExpr = decl.initializer
6467
+ const kind = resolvePrimitiveKind(callExpr, ctx)
6468
+ if (kind !== 'signal' && kind !== 'memo') continue
6469
+
6470
+ const loc = getSourceLocation(stmt, ctx.sourceFile, ctx.filePath)
6471
+ const calleeText = callExpr.expression.getText(ctx.sourceFile)
6472
+
6473
+ // Async reactive factories (`createQuery(fn, options?)`, #3165) return
6474
+ // `[value, action]` and take a request function plus options.
6475
+ const factoryKind = kind === 'signal' ? resolveSignalFactoryKind(callExpr, ctx) : null
6476
+ if (factoryKind !== null) {
6477
+ checkAsyncFactoryArity(decl, callExpr, calleeText, loc, ctx)
6478
+ if (factoryKind === 'mutation') checkMutationInitialOption(callExpr, calleeText, ctx)
6479
+ continue
6480
+ }
6481
+
6482
+ // BF115: tuple-destructure arity. `createMemo` never returns a tuple
6483
+ // (maxArity 0 — any array-pattern destructure of it is a mismatch);
6484
+ // `createSignal` returns 1-2 elements.
6485
+ if (ts.isArrayBindingPattern(decl.name)) {
6486
+ const elementCount = decl.name.elements.length
6487
+ const maxArity = kind === 'signal' ? 2 : 0
6488
+ if (elementCount < 1 || elementCount > maxArity) {
6489
+ ctx.errors.push(createError(ErrorCodes.REACTIVE_FACTORY_ARITY_MISMATCH, loc, {
6490
+ severity: 'error',
6491
+ message: kind === 'signal'
6492
+ ? (elementCount === 0
6493
+ ? `'${calleeText}(...)' returns a 2-element tuple '[getter, setter]' — this ` +
6494
+ `destructure binds 0 elements, so neither the getter nor the setter is ` +
6495
+ `reachable. Use 'const [get, set] = ${calleeText}(...)' or ` +
6496
+ `'const [get] = ${calleeText}(...)'.`
6497
+ : `'${calleeText}(...)' returns a 2-element tuple '[getter, setter]' (a ` +
6498
+ `1-element destructure keeps just the getter) — this destructure has ` +
6499
+ `${elementCount} elements. The extra binding(s) are silently dropped from ` +
6500
+ `the compiled output today. Use 'const [get, set] = ${calleeText}(...)' or ` +
6501
+ `'const [get] = ${calleeText}(...)'.`)
6502
+ : `'${calleeText}(...)' returns a single getter function, not a tuple — this ` +
6503
+ `destructures ${elementCount} element${elementCount === 1 ? '' : 's'} from it. ` +
6504
+ `Use 'const value = ${calleeText}(...)' instead.`,
6505
+ }))
6506
+ // Already flagged for this shape; the argument-count check below
6507
+ // would be redundant noise on a declaration already rejected.
6508
+ continue
6509
+ }
6510
+ }
6511
+
6512
+ // BF116: extra call arguments. `createSignal`/`createMemo` accept at
6513
+ // most 1; an env-signal factory (`createSearchParams()`, which also
6514
+ // resolves to kind `'signal'`) takes none — its value comes from the
6515
+ // request env, so any argument is dropped just the same.
6516
+ const isEnvSignal = kind === 'signal' && resolveEnvSignalKey(callExpr, ctx) !== null
6517
+ const maxArgs = isEnvSignal ? 0 : 1
6518
+ if (callExpr.arguments.length > maxArgs) {
6519
+ ctx.errors.push(createError(ErrorCodes.REACTIVE_FACTORY_EXTRA_ARGUMENTS, loc, {
6520
+ severity: 'error',
6521
+ message: isEnvSignal
6522
+ ? `'${calleeText}()' takes no arguments (its value is read from the request ` +
6523
+ `environment), but this call passes ${callExpr.arguments.length}. The ` +
6524
+ `argument(s) are silently dropped from the compiled client JS today; remove them.`
6525
+ : `'${calleeText}(...)' accepts at most 1 argument (${kind === 'signal' ? 'the initial value' : 'the compute function'}), ` +
6526
+ `but this call passes ${callExpr.arguments.length}. The extra argument(s) are ` +
6527
+ `silently dropped from the compiled client JS today; remove them, or fold ` +
6528
+ `whatever they configure into the ${kind === 'signal' ? 'initial value expression' : 'compute function body'}.`,
6529
+ }))
6530
+ }
6531
+ }
6532
+ }
6533
+ }
6534
+
6535
+ /**
6536
+ * BF115 / BF116 for an async reactive factory (`createQuery(fn, options?)`,
6537
+ * #3165): it returns `[value, action]` (a 1-element destructure keeps just
6538
+ * the value; `[, action]` keeps just the action) and takes the request
6539
+ * function plus an optional options object. `collectFactorySignal` only
6540
+ * reads those two arguments, so a third would be dropped from the client JS.
6541
+ */
6542
+ function checkAsyncFactoryArity(
6543
+ decl: ts.VariableDeclaration,
6544
+ callExpr: ts.CallExpression,
6545
+ calleeText: string,
6546
+ loc: SourceLocation,
6547
+ ctx: AnalyzerContext,
6548
+ ): void {
6549
+ if (ts.isArrayBindingPattern(decl.name)) {
6550
+ const elementCount = decl.name.elements.length
6551
+ if (elementCount < 1 || elementCount > 2) {
6552
+ ctx.errors.push(createError(ErrorCodes.REACTIVE_FACTORY_ARITY_MISMATCH, loc, {
6553
+ severity: 'error',
6554
+ message:
6555
+ `'${calleeText}(...)' returns a 2-element tuple '[value, action]' — this destructure has ` +
6556
+ `${elementCount} elements. Use 'const [value, action] = ${calleeText}(...)', ` +
6557
+ `'const [value] = ${calleeText}(...)' or 'const [, action] = ${calleeText}(...)'.`,
6558
+ }))
6559
+ return
6560
+ }
6561
+ }
6562
+ if (callExpr.arguments.length > 2) {
6563
+ ctx.errors.push(createError(ErrorCodes.REACTIVE_FACTORY_EXTRA_ARGUMENTS, loc, {
6564
+ severity: 'error',
6565
+ message:
6566
+ `'${calleeText}(...)' accepts at most 2 arguments (the request function and the options), ` +
6567
+ `but this call passes ${callExpr.arguments.length}. The extra argument(s) are dropped from the ` +
6568
+ `compiled client JS; remove them.`,
6569
+ }))
6570
+ }
6571
+ }
6572
+
6573
+ /**
6574
+ * BF118 (#3210): an `initial` key in `createMutation`'s options. A mutation's
6575
+ * value is `undefined` until its action is called (spec/async.md §7.4), and
6576
+ * the runtime ignores the key, so an author who writes it expects a seed
6577
+ * that never happens. Only an object-literal `options` is read, the same
6578
+ * structural read `createQuery`'s `initial` goes through; any other shape
6579
+ * carries no key the compiler can see.
6580
+ */
6581
+ function checkMutationInitialOption(callExpr: ts.CallExpression, calleeText: string, ctx: AnalyzerContext): void {
6582
+ const initialNode = factoryInitialNode(callExpr.arguments[1])
6583
+ if (initialNode.kind !== 'expression') return
6584
+ ctx.errors.push(createError(ErrorCodes.MUTATION_INITIAL_OPTION, getSourceLocation(initialNode.node, ctx.sourceFile, ctx.filePath), {
6585
+ severity: 'error',
6586
+ message:
6587
+ `'${calleeText}(...)' takes no 'initial' option: a mutation's value is undefined until its action is ` +
6588
+ `called, so this value would never be used. Use 'createQuery' for a value that needs an initial state.`,
6589
+ }))
6590
+ }
6591
+
6063
6592
  /**
6064
6593
  * BF013 (#2771): a reactive primitive called through a namespace import
6065
6594
  * (`import * as bf from '@barefootjs/client'`, `bf.createSignal(...)`)