@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
@@ -0,0 +1,311 @@
1
+ /**
2
+ * BF115 / BF116 (#3159): `createSignal`/`createMemo` called with a
3
+ * destructure arity or argument count the primitive doesn't support.
4
+ *
5
+ * Context: `validateReactiveFactoryCalls` (BF110) exists to diagnose a
6
+ * destructure of an UNRECOGNISED callee — it unconditionally `continue`s
7
+ * past `createSignal`/`createMemo`, so a RECOGNISED callee used with a bad
8
+ * shape fell through with no diagnostic:
9
+ *
10
+ * - `const [user, setUser, extra] = createSignal(props.user)` — a
11
+ * 3-element destructure of `createSignal` (which returns a 2-element
12
+ * `[getter, setter]` tuple) was not recognised as a signal at all.
13
+ * `user` fell through to the "same-name prop" fallback and silently
14
+ * became the raw prop accessor `_p.user()` instead of the signal
15
+ * getter — a real read/write split whose failure mode is "the UI just
16
+ * doesn't update," not a compile error.
17
+ * - `createSignal(props.user, { from: 'router' })` / `createMemo(fn, x)`
18
+ * — an extra argument was silently dropped from the emitted client JS.
19
+ *
20
+ * Both are now loud, per CLAUDE.md's known-limitation policy (`silent` →
21
+ * `refusal`/compile error).
22
+ */
23
+
24
+ import { describe, test, expect } from 'bun:test'
25
+ import { compileJSX } from '../compiler'
26
+ import { TestAdapter } from '../adapters/test-adapter'
27
+
28
+ const adapter = new TestAdapter()
29
+
30
+ describe('BF115: createSignal/createMemo tuple-destructure arity (#3159)', () => {
31
+ test('a 3-element destructure of createSignal is a compile error, not a silent prop fallback', () => {
32
+ const source = `
33
+ 'use client'
34
+ import { createSignal } from '@barefootjs/client'
35
+
36
+ export function Profile({ user }: { user: string }) {
37
+ const [user2, setUser, extra] = createSignal(user)
38
+ return <button onClick={() => setUser('x')}>{user2()}</button>
39
+ }
40
+ `
41
+ const result = compileJSX(source, 'Profile.tsx', { adapter })
42
+ const bf115 = result.errors.find(e => e.code === 'BF115')
43
+ expect(bf115).toBeDefined()
44
+ expect(bf115!.severity).toBe('error')
45
+ expect(bf115!.message).toContain('createSignal')
46
+ })
47
+
48
+ test('the exact same-name-prop collision shape from the issue is caught', () => {
49
+ // `user` names both a prop AND the over-arity destructure's first
50
+ // binding — the shape that silently mis-seeds `user` as `_p.user()`.
51
+ const source = `
52
+ 'use client'
53
+ import { createSignal } from '@barefootjs/client'
54
+
55
+ export function Profile({ user }: { user: string }) {
56
+ const [user, setUser, extra] = createSignal(user)
57
+ return <button onClick={() => setUser('x')}>{user()}</button>
58
+ }
59
+ `
60
+ const result = compileJSX(source, 'Profile.tsx', { adapter })
61
+ const bf115 = result.errors.find(e => e.code === 'BF115')
62
+ expect(bf115).toBeDefined()
63
+ })
64
+
65
+ test('a 1-element destructure (getter-only) is still valid — no BF115', () => {
66
+ const source = `
67
+ 'use client'
68
+ import { createSignal } from '@barefootjs/client'
69
+
70
+ export function Counter() {
71
+ const [count] = createSignal(0)
72
+ return <span>{count()}</span>
73
+ }
74
+ `
75
+ const result = compileJSX(source, 'Counter.tsx', { adapter })
76
+ expect(result.errors.find(e => e.code === 'BF115')).toBeUndefined()
77
+ })
78
+
79
+ test('a normal 2-element destructure is still valid — no BF115', () => {
80
+ const source = `
81
+ 'use client'
82
+ import { createSignal } from '@barefootjs/client'
83
+
84
+ export function Counter() {
85
+ const [count, setCount] = createSignal(0)
86
+ return <button onClick={() => setCount(count() + 1)}>{count()}</button>
87
+ }
88
+ `
89
+ const result = compileJSX(source, 'Counter.tsx', { adapter })
90
+ expect(result.errors.find(e => e.code === 'BF115')).toBeUndefined()
91
+ })
92
+
93
+ test('an array-pattern destructure of createMemo (which returns a single getter) is BF115', () => {
94
+ const source = `
95
+ 'use client'
96
+ import { createSignal, createMemo } from '@barefootjs/client'
97
+
98
+ export function Doubled() {
99
+ const [count, setCount] = createSignal(1)
100
+ const [doubled] = createMemo(() => count() * 2)
101
+ return <span onClick={() => setCount(2)}>{doubled()}</span>
102
+ }
103
+ `
104
+ const result = compileJSX(source, 'Doubled.tsx', { adapter })
105
+ const bf115 = result.errors.find(e => e.code === 'BF115')
106
+ expect(bf115).toBeDefined()
107
+ expect(bf115!.message).toContain('createMemo')
108
+ })
109
+
110
+ test('the getter-elided form `const [, setActive]` is still valid — no BF115', () => {
111
+ const source = `
112
+ 'use client'
113
+ import { createSignal } from '@barefootjs/client'
114
+
115
+ export function Toggle() {
116
+ const [, setActive] = createSignal(false)
117
+ return <button onClick={() => setActive(true)}>Go</button>
118
+ }
119
+ `
120
+ const result = compileJSX(source, 'Toggle.tsx', { adapter })
121
+ expect(result.errors.find(e => e.code === 'BF115')).toBeUndefined()
122
+ })
123
+
124
+ test('a 0-element destructure gets an accurate message, not the "extra binding(s)" text', () => {
125
+ const source = `
126
+ 'use client'
127
+ import { createSignal } from '@barefootjs/client'
128
+
129
+ export function Counter() {
130
+ const [] = createSignal(0)
131
+ return <span>static</span>
132
+ }
133
+ `
134
+ const result = compileJSX(source, 'Counter.tsx', { adapter })
135
+ const bf115 = result.errors.find(e => e.code === 'BF115')
136
+ expect(bf115).toBeDefined()
137
+ // The old wording ("extra binding(s) are silently dropped") makes no
138
+ // sense when nothing at all is bound — nothing is "extra".
139
+ expect(bf115!.message).not.toContain('extra binding')
140
+ expect(bf115!.message).toContain('0 elements')
141
+ })
142
+
143
+ test('a bad-arity createSignal destructure inside a conditional-return branch is still caught (#1414 branch signals)', () => {
144
+ // `collectBranchSignals` gives a top-level `if` whose then-branch returns
145
+ // JSX its own signal-collection scope — the same silent-drop bug BF115
146
+ // exists for at the top level reproduces here too if the diagnostic only
147
+ // ever looks at the component's own top-level statements.
148
+ const source = `
149
+ 'use client'
150
+ import { createSignal } from '@barefootjs/client'
151
+
152
+ export function Profile({ flag, user }: { flag: boolean; user: string }) {
153
+ if (flag) {
154
+ const [user2, setUser, extra] = createSignal(user)
155
+ return <button onClick={() => setUser('x')}>{user2()}</button>
156
+ }
157
+ return <div>static</div>
158
+ }
159
+ `
160
+ const result = compileJSX(source, 'Profile.tsx', { adapter })
161
+ const bf115 = result.errors.find(e => e.code === 'BF115')
162
+ expect(bf115).toBeDefined()
163
+ expect(bf115!.message).toContain('createSignal')
164
+ })
165
+
166
+ // Alias resolution itself (`import { createSignal as sig }`) is covered by
167
+ // `primitive-resolver-alias.test.ts`, which requires a real `ts.Program`
168
+ // to exercise the TypeChecker-backed slow path. This check delegates to
169
+ // the same `resolvePrimitiveKind` those tests pin, rather than a bespoke
170
+ // bare-text match — see the doc comment on `validateReactiveFactoryArity`.
171
+ })
172
+
173
+ describe('BF116: createSignal/createMemo extra call arguments (#3159)', () => {
174
+ test('an extra argument to createSignal is a compile error, not a silent drop', () => {
175
+ const source = `
176
+ 'use client'
177
+ import { createSignal } from '@barefootjs/client'
178
+
179
+ export function Profile({ user }: { user: string }) {
180
+ const [value, setValue] = createSignal(user, { from: 'router' })
181
+ return <button onClick={() => setValue('x')}>{value()}</button>
182
+ }
183
+ `
184
+ const result = compileJSX(source, 'Profile.tsx', { adapter })
185
+ const bf116 = result.errors.find(e => e.code === 'BF116')
186
+ expect(bf116).toBeDefined()
187
+ expect(bf116!.severity).toBe('error')
188
+ expect(bf116!.message).toContain('createSignal')
189
+ })
190
+
191
+ test('an extra argument to createMemo is a compile error', () => {
192
+ const source = `
193
+ 'use client'
194
+ import { createSignal, createMemo } from '@barefootjs/client'
195
+
196
+ export function Doubled() {
197
+ const [count, setCount] = createSignal(1)
198
+ const doubled = createMemo(() => count() * 2, { deep: true })
199
+ return <span onClick={() => setCount(2)}>{doubled()}</span>
200
+ }
201
+ `
202
+ const result = compileJSX(source, 'Doubled.tsx', { adapter })
203
+ const bf116 = result.errors.find(e => e.code === 'BF116')
204
+ expect(bf116).toBeDefined()
205
+ expect(bf116!.message).toContain('createMemo')
206
+ })
207
+
208
+ test('createSignal with zero arguments is still valid — no BF116', () => {
209
+ const source = `
210
+ 'use client'
211
+ import { createSignal } from '@barefootjs/client'
212
+
213
+ export function Counter() {
214
+ const [count, setCount] = createSignal<number>()
215
+ return <button onClick={() => setCount(1)}>{count()}</button>
216
+ }
217
+ `
218
+ const result = compileJSX(source, 'Counter.tsx', { adapter })
219
+ expect(result.errors.find(e => e.code === 'BF116')).toBeUndefined()
220
+ })
221
+
222
+ test('createSignal with exactly one argument is still valid — no BF116', () => {
223
+ const source = `
224
+ 'use client'
225
+ import { createSignal } from '@barefootjs/client'
226
+
227
+ export function Counter() {
228
+ const [count, setCount] = createSignal(0)
229
+ return <button onClick={() => setCount(count() + 1)}>{count()}</button>
230
+ }
231
+ `
232
+ const result = compileJSX(source, 'Counter.tsx', { adapter })
233
+ expect(result.errors.find(e => e.code === 'BF116')).toBeUndefined()
234
+ })
235
+
236
+ // `createSearchParams` resolves to kind 'signal' too, but takes no
237
+ // arguments at all — its value comes from the request env — so the
238
+ // 1-argument allowance `createSignal` gets must not cover it.
239
+ test('any argument to createSearchParams is a compile error', () => {
240
+ const source = `
241
+ 'use client'
242
+ import { createSearchParams } from '@barefootjs/client'
243
+
244
+ export function Sort() {
245
+ const [sp, setSp] = createSearchParams('sort=date')
246
+ return <button onClick={() => setSp({ sort: 'price' })}>{sp().get('sort')}</button>
247
+ }
248
+ `
249
+ const result = compileJSX(source, 'Sort.tsx', { adapter })
250
+ const bf116 = result.errors.find(e => e.code === 'BF116')
251
+ expect(bf116).toBeDefined()
252
+ expect(bf116!.severity).toBe('error')
253
+ expect(bf116!.message).toContain('createSearchParams')
254
+ expect(bf116!.message).toContain('takes no arguments')
255
+ })
256
+
257
+ test('createSearchParams with zero arguments is still valid — no BF116', () => {
258
+ const source = `
259
+ 'use client'
260
+ import { createSearchParams } from '@barefootjs/client'
261
+
262
+ export function Sort() {
263
+ const [sp, setSp] = createSearchParams()
264
+ return <button onClick={() => setSp({ sort: 'price' })}>{sp().get('sort')}</button>
265
+ }
266
+ `
267
+ const result = compileJSX(source, 'Sort.tsx', { adapter })
268
+ expect(result.errors.find(e => e.code === 'BF116')).toBeUndefined()
269
+ })
270
+ })
271
+
272
+ // Async factories (`createQuery` #3165, `createMutation` #3210) return
273
+ // `[value, action]` and take a request function plus options, so the same
274
+ // pass checks them against 2 elements and 2 arguments.
275
+ describe('BF115 / BF116: async factories (#3165, #3210)', () => {
276
+ const compileWith = (factory: string, binding: string, args: string) =>
277
+ compileJSX(
278
+ `
279
+ 'use client'
280
+ import { ${factory}, http } from '@barefootjs/client'
281
+
282
+ export function C() {
283
+ const ${binding} = ${factory}(${args})
284
+ return <p>x</p>
285
+ }
286
+ `,
287
+ 'C.tsx',
288
+ { adapter },
289
+ )
290
+
291
+ for (const factory of ['createQuery', 'createMutation']) {
292
+ test(`${factory}: a 3-element destructure is BF115, naming the [value, action] shape`, () => {
293
+ const result = compileWith(factory, '[a, b, c]', "() => http.post('/x')")
294
+ const bf115 = result.errors.find(e => e.code === 'BF115')
295
+ expect(bf115).toBeDefined()
296
+ expect(bf115!.message).toContain(`'${factory}(...)' returns a 2-element tuple '[value, action]'`)
297
+ })
298
+
299
+ test(`${factory}: a third argument is BF116`, () => {
300
+ const result = compileWith(factory, '[a]', "() => http.post('/x'), {}, 'extra'")
301
+ expect(result.errors.map(e => e.code)).toEqual(['BF116'])
302
+ })
303
+
304
+ test(`${factory}: [value, action], [value] and [, action] with two arguments are valid`, () => {
305
+ for (const binding of ['[a, b]', '[a]', '[, b]']) {
306
+ const result = compileWith(factory, binding, "() => http.post('/x'), {}")
307
+ expect(result.errors.map(e => e.code)).toEqual([])
308
+ }
309
+ })
310
+ }
311
+ })
@@ -182,9 +182,11 @@ export function Overlay() {
182
182
  // resolution does not widen what is recognized. These two tests pin that
183
183
  // scope limit only. A portal element inside a `.map()` row is broken
184
184
  // either way — the second test's row-declared callback is still
185
- // recognized and still breaks the row's hydration — which is a
186
- // pre-existing, separately tracked defect: the control pins today's
187
- // behaviour as a known gap, not as intended behaviour.
185
+ // recognized and still breaks the row's hydration — which is the
186
+ // registered known limitation `loop-row-ref-portal`
187
+ // (`packages/adapter-tests/limitations/loop-row-ref-portal.ts`, fixture
188
+ // `row-portal-ref`): the control pins today's behaviour as a known gap,
189
+ // not as intended behaviour.
188
190
  test('does not flag a .map() row ref naming a portal callback declared in the component body', () => {
189
191
  const ir = root(`
190
192
  'use client'
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Structural recognition for a query/mutation action's reactive accessors
3
+ * (#3166, part B of #3158): `action.isPending()` / `action.error()` where
4
+ * `action` is the action binding of a recognised async factory
5
+ * (`const [, fetchPosts] = createQuery(…)`, #3165's `SignalInfo.factory`).
6
+ *
7
+ * This is the ONE place that recognises the shape, fed directly by #3165's
8
+ * binding metadata (`SignalInfo.factory.action`) rather than a name
9
+ * heuristic — never re-derived per call site — and the ONE place that
10
+ * decides where a recognised read may be seeded
11
+ * ({@link seedableActionAccessorRead}). Two consumers call that gate:
12
+ *
13
+ * - `seedActionAccessorReads` (below, run by `jsx-to-ir.ts` right after the
14
+ * parse-attach walk): substitutes a gated read with its seed, both in the
15
+ * structured `ParsedExpr` every DSL adapter lowers from and in the
16
+ * `templateCondition` / `templateExpr` text the CSR module-scope fallback
17
+ * template reads.
18
+ * - `async-action-refusal.ts` (BF117): lifts the refusal for exactly the
19
+ * positions the gate admits; every other read refuses as before #3166.
20
+ *
21
+ * Both walk the same positions (`walkTemplatePositions`), so the lift and
22
+ * the seed cannot disagree about which position is which.
23
+ *
24
+ * Where the seed is sound. The SSR seed (spec/async.md §7.3) is `false` for
25
+ * `isPending()` and `undefined` for `error()`; Hono (the reference) really
26
+ * calls a stub returning exactly those, while a DSL adapter renders the
27
+ * substituted `ParsedExpr` literal `false`. A position is gated in only where
28
+ * the two provably render the same bytes:
29
+ *
30
+ * - a `condition` (`IRConditional` / `IRIfStatement`), for both accessors —
31
+ * only truthiness is observed, and `false` ≡ `undefined` there;
32
+ * - an intrinsic element's ARIA boolean-state attribute
33
+ * ({@link ARIA_BOOLEAN_STATE_ATTRS}), for `isPending()` only — Hono renders
34
+ * `aria-busy={false}` as `aria-busy="false"`, and every DSL adapter
35
+ * stringifies a boolean there JS-style (`bool_str`);
36
+ * - an intrinsic element's HTML boolean attribute (`disabled`, `readonly`, …;
37
+ * the shared `isBooleanAttr` every adapter imports), for `isPending()` only
38
+ * (#3210) — Hono omits `disabled={false}`, and every DSL adapter renders a
39
+ * boolean attribute present-or-absent from the expression's truthiness.
40
+ *
41
+ * Everything else stays refused by BF117 exactly as before #3166, because the
42
+ * seed would silently diverge there: a text child (`{fetchPosts.error()}` —
43
+ * Hono renders nothing, a DSL adapter `false`), `error()` in any attribute
44
+ * (Hono omits an `undefined` attribute; the `false` literal renders it), and
45
+ * `isPending()` in any other attribute (Mojolicious / Xslate render the
46
+ * literal as `0` outside the ARIA boolean set and the HTML boolean
47
+ * attributes). A structured template
48
+ * attribute's ternary condition (`class={fetchPosts.isPending() ? 'a' : 'b'}`)
49
+ * is a truthiness test too, but its condition is raw text every adapter lowers
50
+ * on its own, so there is nothing to substitute — it stays refused rather
51
+ * than lifted with no seed behind it.
52
+ *
53
+ * `createMutation` (#3210) reuses this unchanged — `SignalFactoryCall.kind`
54
+ * only distinguishes how the value seeds, never how the action's accessors
55
+ * do, so nothing here is query-specific.
56
+ *
57
+ * Scope: only the accessor called as the WHOLE template-position expression
58
+ * is recognised. A compound use (`!fetchPosts.isPending()`,
59
+ * `fetchPosts.isPending() && x`) is not substituted here and stays refused
60
+ * by BF117 exactly as before #3166 — recognising it structurally too is
61
+ * future work, not a silent gap: nothing that used to compile now compiles
62
+ * differently, and nothing that used to refuse now silently mis-renders.
63
+ */
64
+
65
+ import type { ParsedExpr } from './expression-parser.ts'
66
+ import { isBooleanAttr } from './html-constants.ts'
67
+ import type { IRNode, SignalInfo } from './types.ts'
68
+ import { walkTemplatePositions, type TemplatePosition } from './template-position-walk.ts'
69
+
70
+ /** Reactive accessors every recognised action carries (spec/async.md §7.1/§7.3). */
71
+ export type ActionAccessorName = 'isPending' | 'error'
72
+
73
+ /**
74
+ * Exported so every consumer that needs the accessor-name set (not just the
75
+ * whole-expression-call recognition below) reads the same one — mirrors the
76
+ * `Reactive` members of `QueryAction` in `packages/client/src/create-query.ts`:
77
+ * an accessor added there must be added here.
78
+ */
79
+ export const ACTION_ACCESSOR_NAMES: ReadonlySet<string> = new Set(['isPending', 'error'])
80
+
81
+ export interface ActionAccessorRead {
82
+ action: string
83
+ accessor: ActionAccessorName
84
+ }
85
+
86
+ /** The action bindings a component's recognised async factories produced (#3165). */
87
+ export function collectActionNames(signals: readonly Pick<SignalInfo, 'factory'>[]): ReadonlySet<string> {
88
+ const actions = new Set<string>()
89
+ for (const signal of signals) {
90
+ if (signal.factory?.action) actions.add(signal.factory.action)
91
+ }
92
+ return actions
93
+ }
94
+
95
+ /**
96
+ * Recognises `<action>()` — a zero-arg call whose callee is a non-computed
97
+ * member access on an identifier in `actions`, naming `isPending` or
98
+ * `error`. Structural: never matches on the property name alone without the
99
+ * object also being a real recognised action binding.
100
+ */
101
+ export function matchActionAccessorCall(
102
+ expr: ParsedExpr,
103
+ actions: ReadonlySet<string>,
104
+ ): ActionAccessorRead | null {
105
+ if (expr.kind !== 'call' || expr.args.length !== 0) return null
106
+ const callee = expr.callee
107
+ if (callee.kind !== 'member' || callee.computed) return null
108
+ if (callee.object.kind !== 'identifier') return null
109
+ if (!actions.has(callee.object.name)) return null
110
+ if (!ACTION_ACCESSOR_NAMES.has(callee.property)) return null
111
+ return { action: callee.object.name, accessor: callee.property as ActionAccessorName }
112
+ }
113
+
114
+ /**
115
+ * The direct sub-expressions of `expr`, each with the arrow parameters it is
116
+ * evaluated under (`params`, set only for an arrow's body). The one traversal
117
+ * of a `ParsedExpr` for action reads: BF117's refusal walk
118
+ * (`async-action-refusal.ts`) and {@link collectActionAccessorReads} both
119
+ * recurse through it, so they cannot disagree about which sub-expressions a
120
+ * read can hide in, or which names an arrow parameter shadows.
121
+ */
122
+ export function parsedExprChildren(expr: ParsedExpr): Array<{ expr: ParsedExpr; params?: readonly string[] }> {
123
+ const all = (...exprs: ParsedExpr[]) => exprs.map((e) => ({ expr: e }))
124
+ switch (expr.kind) {
125
+ case 'member':
126
+ return all(expr.object)
127
+ case 'call':
128
+ return all(expr.callee, ...expr.args)
129
+ case 'index-access':
130
+ return all(expr.object, expr.index)
131
+ case 'binary':
132
+ case 'logical':
133
+ return all(expr.left, expr.right)
134
+ case 'unary':
135
+ return all(expr.argument)
136
+ case 'conditional':
137
+ return all(expr.test, expr.consequent, expr.alternate)
138
+ case 'template-literal':
139
+ return all(...expr.parts.flatMap((p) => (p.type === 'expression' ? [p.expr] : [])))
140
+ case 'array-literal':
141
+ return all(...expr.elements)
142
+ case 'object-literal':
143
+ return all(...expr.properties.map((p) => (p.kind === 'spread' ? p.expr : p.value)))
144
+ case 'array-method':
145
+ return all(expr.object, ...expr.args, ...(expr.method === 'flat' && expr.depthExpr ? [expr.depthExpr] : []))
146
+ case 'arrow':
147
+ return [{ expr: expr.body, params: expr.params }]
148
+ case 'identifier':
149
+ case 'literal':
150
+ case 'regex':
151
+ case 'unsupported':
152
+ return []
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Every `<action>.isPending()` / `<action>.error()` read in `expr`, in
158
+ * first-seen order and without duplicates (`bf debug graph`, #3167). An action
159
+ * name an enclosing arrow parameter rebinds, or that `isBound` reports bound
160
+ * (a loop row's parameter), is not the action.
161
+ */
162
+ export function collectActionAccessorReads(
163
+ expr: ParsedExpr,
164
+ actions: ReadonlySet<string>,
165
+ isBound: (name: string) => boolean = () => false,
166
+ ): ActionAccessorRead[] {
167
+ const reads: ActionAccessorRead[] = []
168
+ if (actions.size === 0) return reads
169
+ const visit = (e: ParsedExpr, bound: ReadonlySet<string>): void => {
170
+ const read = matchActionAccessorCall(e, actions)
171
+ if (read && !bound.has(read.action) && !isBound(read.action)) {
172
+ if (!reads.some((r) => r.action === read.action && r.accessor === read.accessor)) reads.push(read)
173
+ return
174
+ }
175
+ for (const child of parsedExprChildren(e)) {
176
+ visit(child.expr, child.params ? new Set([...bound, ...child.params]) : bound)
177
+ }
178
+ }
179
+ visit(expr, new Set())
180
+ return reads
181
+ }
182
+
183
+ /**
184
+ * ARIA boolean-state attributes: the attribute names on which every DSL
185
+ * adapter stringifies a boolean value JS-style (`"true"` / `"false"`), which
186
+ * is what Hono renders for `aria-*={false}`. Must stay a subset of each DSL
187
+ * adapter's own `isAriaBooleanAttr` set (Mojolicious / Xslate render a bare
188
+ * `false` literal as `0` on any other attribute); `action-accessor.test.ts`
189
+ * pins that across every adapter, so an adapter dropping a name fails there
190
+ * instead of silently diverging.
191
+ */
192
+ export const ARIA_BOOLEAN_STATE_ATTRS: ReadonlySet<string> = new Set([
193
+ 'aria-atomic',
194
+ 'aria-busy',
195
+ 'aria-checked',
196
+ 'aria-disabled',
197
+ 'aria-expanded',
198
+ 'aria-hidden',
199
+ 'aria-modal',
200
+ 'aria-multiline',
201
+ 'aria-multiselectable',
202
+ 'aria-pressed',
203
+ 'aria-readonly',
204
+ 'aria-required',
205
+ 'aria-selected',
206
+ ])
207
+
208
+ /**
209
+ * THE gate (see the file header): the recognised accessor read at this
210
+ * template position, if its seed renders there exactly as Hono renders the
211
+ * real stub's value — otherwise `null`, and the read stays refused (BF117).
212
+ * `seedActionAccessorReads` seeds exactly what this admits, and BF117 lifts
213
+ * exactly what this admits; neither re-decides it.
214
+ */
215
+ export function seedableActionAccessorRead(
216
+ position: Pick<TemplatePosition, 'expr' | 'role' | 'attrName'>,
217
+ actions: ReadonlySet<string>,
218
+ ): ActionAccessorRead | null {
219
+ const read = matchActionAccessorCall(position.expr, actions)
220
+ if (!read) return null
221
+ switch (position.role) {
222
+ case 'condition':
223
+ return read
224
+ case 'element-attr':
225
+ return read.accessor === 'isPending' &&
226
+ position.attrName !== undefined &&
227
+ (ARIA_BOOLEAN_STATE_ATTRS.has(position.attrName) || isBooleanAttr(position.attrName))
228
+ ? read
229
+ : null
230
+ default:
231
+ return null
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Seed every gated accessor read in `root` in place: the position's
237
+ * `ParsedExpr` (what DSL adapters lower) becomes {@link actionAccessorSeedParsed},
238
+ * and its CSR fallback text (`templateCondition` / `templateExpr`) becomes
239
+ * {@link actionAccessorSeedText}. Runs once, after `parsed` is attached and
240
+ * before any refusal pass or adapter reads the IR.
241
+ */
242
+ export function seedActionAccessorReads(root: IRNode, signals: readonly Pick<SignalInfo, 'factory'>[]): void {
243
+ const actions = collectActionNames(signals)
244
+ if (actions.size === 0) return
245
+ walkTemplatePositions(root, (position) => {
246
+ const read = seedableActionAccessorRead(position, actions)
247
+ if (!read || !position.host) return
248
+ const parsed = actionAccessorSeedParsed(read.accessor)
249
+ const text = actionAccessorSeedText(read.accessor)
250
+ if (position.host.kind === 'condition') {
251
+ position.host.node.parsedCondition = parsed
252
+ position.host.node.templateCondition = text
253
+ } else {
254
+ position.host.value.parsed = parsed
255
+ position.host.value.templateExpr = text
256
+ }
257
+ })
258
+ }
259
+
260
+ /**
261
+ * The SSR seed for a recognised accessor (spec/async.md §7.3): `isPending()`
262
+ * is `false`; `error()` is `undefined`. Represented as the `ParsedExpr`
263
+ * boolean literal `false` for the structured tree every DSL adapter's
264
+ * expression lowering reads (`IRConditional.parsedCondition` /
265
+ * `ExpressionAttr.parsed`). That is only equivalent to the real value where
266
+ * {@link seedableActionAccessorRead} admits the position: a truthiness test
267
+ * (`false` ≡ `undefined`), or `isPending()` (really `false`) in an ARIA
268
+ * boolean-state attribute or an HTML boolean attribute. Unlike the `null` literal, `false` is valid in
269
+ * every position every adapter's grammar accepts, including a bare
270
+ * `{{if …}}` command (Go's `text/template` rejects a bare `nil` there — "nil
271
+ * is not a command"). `ParsedExpr`'s `literal` kind has no `undefined`
272
+ * variant regardless, so something has to stand in for it; an `error()` read
273
+ * rendered as a VALUE would need a real "omit" seed, which is why the gate
274
+ * refuses it instead.
275
+ */
276
+ export function actionAccessorSeedParsed(_accessor: ActionAccessorName): ParsedExpr {
277
+ return { kind: 'literal', value: false, literalType: 'boolean' }
278
+ }
279
+
280
+ /**
281
+ * The SSR seed as JS source text — for the CSR module-scope fallback
282
+ * template (`templateCondition` / `templateExpr`), which cannot close over
283
+ * the action's real accessor (it is a local inside `initX`, never in scope
284
+ * at module level, the same reason a signal getter call is substituted with
285
+ * its initial value there instead of being called live).
286
+ */
287
+ export function actionAccessorSeedText(accessor: ActionAccessorName): string {
288
+ return accessor === 'isPending' ? 'false' : 'undefined'
289
+ }
@@ -172,6 +172,23 @@ export abstract class JsxAdapter extends BaseAdapter {
172
172
  lines.push(` const ${signal.getter} = () => ${initialValue}`)
173
173
  }
174
174
 
175
+ // An async factory's action (#3165): the request function never runs on
176
+ // the server, so a reference that survives into SSR (e.g. forwarded to a
177
+ // child as a prop) gets a no-op. Since #3166, `action.isPending()` /
178
+ // `action.error()` are ordinary, IR-visible seeded values
179
+ // (`false` / `undefined`, spec/async.md §7.3) rather than refused —
180
+ // this SSR stub is what a template position's `fetchPosts.isPending()`
181
+ // actually calls at render time (this file's execution model runs the
182
+ // real JS text, unlike a DSL adapter's `parsedCondition`-based
183
+ // substitution), so it must carry working accessors, not just be
184
+ // callable itself.
185
+ const action = signal.factory?.action
186
+ if (action && identifierPattern(action).test(setterRefText)) {
187
+ lines.push(preserveTypes
188
+ ? ` const ${action}: any = Object.assign(() => {}, { isPending: () => false, error: () => undefined })`
189
+ : ` const ${action} = Object.assign(() => {}, { isPending: () => false, error: () => undefined })`)
190
+ }
191
+
175
192
  // Create a no-op setter for SSR — omit entirely if not referenced anywhere
176
193
  if (signal.setter) {
177
194
  const setterUsed = identifierPattern(signal.setter).test(setterRefText)