@molecule/app-query-vue 0.0.0-stage → 0.0.1-stage

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.
package/README.md CHANGED
@@ -1,3 +1,877 @@
1
- # Temporary Holding Version
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-11-14T15:07:24.568Z
7
+ -->
2
8
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
9
+ # @molecule/app-query-vue
10
+
11
+ Vue composables for `@molecule/app-query` — the Vue counterpart of
12
+ `@molecule/app-query-react`, with the same exports, the same props, the same
13
+ cache behavior and the same DOM for the same input.
14
+
15
+ **Load page data with {@link useQuery}, not `fetch` inside a `watch`.** A hand-written load
16
+ watcher that cancels its request on cleanup (a `cancelled` flag, or an `AbortController`)
17
+ re-runs its cleanup on EVERY re-run whenever one of its sources is a function created inline
18
+ each run — `const { setError } = useApiErrors()` returning arrow functions is the usual
19
+ source. The watcher's own guard (`if (loaded === slug) return`) then returns without
20
+ refetching, so the response is discarded whenever it arrives after a re-run: always on a
21
+ remote server, never on localhost, which is why the page passes locally and fails on the
22
+ live URL. `useQuery` subscribes once per key, keeps its request stable across re-renders,
23
+ and aborts it only when the key changes or the component unmounts.
24
+
25
+ {@link useQuery} observes one document from the app's shared cache and
26
+ returns cached data on the first read; {@link usePrefetch} and
27
+ {@link intentPrefetchProps} warm a document when a person is about to
28
+ open it. Together they make a detail page open with no loading state.
29
+
30
+ This package needs a bonded client: install `@molecule/app-query` with a bond
31
+ (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
32
+ `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
33
+
34
+ **Keep displayed records on the query cache.** Render `query.value.data` directly. A custom
35
+ mutation handler publishes its saved response with `query.setData(saved)`; every observer
36
+ and the next visit receive it, and subsequent refreshes still update the view. A local
37
+ `ref` copy hydrated only once per record hides later query answers. Editable form
38
+ drafts remain local until saved. Prefer {@link createQueryResource} for a complete resource;
39
+ its writes already publish the response and refresh its tracked collections.
40
+
41
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
42
+ > It is written to be read by coding agents as much as by people, and is generated from this
43
+ > package's source — edit `src/index.ts` JSDoc, not this file.
44
+
45
+ ## Quick Start
46
+
47
+ ```ts
48
+ import { getClient, isHttpError } from '@molecule/app-http'
49
+ import { useTranslation } from '@molecule/app-vue'
50
+ import { defineComponent, h } from 'vue'
51
+ import { intentPrefetchProps, useQuery } from '@molecule/app-query-vue'
52
+
53
+ interface PackageDocument {
54
+ name: string
55
+ description: string
56
+ }
57
+
58
+ const packageQuery = (name: string) => ({
59
+ key: ['package', name],
60
+ fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
61
+ try {
62
+ const response = await getClient().get<PackageDocument | null>(
63
+ `/data/packages/${encodeURIComponent(name)}.json`,
64
+ { signal },
65
+ )
66
+ return response.data
67
+ } catch (error) {
68
+ if (isHttpError(error) && error.status === 404) return null
69
+ throw error
70
+ }
71
+ },
72
+ })
73
+
74
+ const PackageLink = defineComponent({
75
+ props: { name: { type: String, required: true } },
76
+ setup(props) {
77
+ return () =>
78
+ h(
79
+ 'a',
80
+ { href: `/packages/${props.name}`, ...intentPrefetchProps(packageQuery(props.name)) },
81
+ props.name,
82
+ )
83
+ },
84
+ })
85
+
86
+ const PackagePage = defineComponent({
87
+ props: { name: { type: String, required: true } },
88
+ setup(props) {
89
+ const { t } = useTranslation()
90
+ // Options as a getter: a changed `name` (a new route param) moves this same
91
+ // observer to the new key — React re-renders `useQuery` with new options instead.
92
+ const query = useQuery<PackageDocument | null>(() => packageQuery(props.name))
93
+ return () => {
94
+ const { data, status } = query.value
95
+ if (status === 'error') {
96
+ return h(
97
+ 'p',
98
+ { role: 'alert' },
99
+ t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' }),
100
+ )
101
+ }
102
+ if (status === 'idle' || status === 'loading') {
103
+ return h(
104
+ 'p',
105
+ { role: 'status' },
106
+ t('common.loading', undefined, { defaultValue: 'Loading…' }),
107
+ )
108
+ }
109
+ if (data == null) {
110
+ return h('p', {}, t('packages.notFound', undefined, { defaultValue: 'Package not found.' }))
111
+ }
112
+ return h('article', {}, [h('h1', {}, data.name), h('p', {}, data.description)])
113
+ }
114
+ },
115
+ })
116
+ ```
117
+
118
+ A list whose page and filter live in the URL: derive the key from the route and pass
119
+ `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
120
+ until the next page answers. The app's HTTP client sends the session, so the viewer is part of
121
+ what the answer depends on: key on it and pass the same value as `principal` — an account
122
+ switch then drops the previous account's rows at once. Pass `null` while the session is still
123
+ being restored (`status === 'loading'`; the HTTP client holds the request until then anyway),
124
+ so restoring a session never swaps a key that already rendered rows.
125
+
126
+ ```ts
127
+ import { unwrapList } from '@molecule/app-http'
128
+ import { useAuth, useHttpClient, useTranslation } from '@molecule/app-vue'
129
+ import { computed, defineComponent, h, type PropType } from 'vue'
130
+ import { useQuery } from '@molecule/app-query-vue'
131
+
132
+ interface Invoice {
133
+ id: string
134
+ number: string
135
+ }
136
+
137
+ export const InvoiceList = defineComponent({
138
+ props: {
139
+ page: { type: Number, default: 1 },
140
+ statusFilter: { type: String as PropType<string>, default: '' },
141
+ },
142
+ setup(props) {
143
+ const http = useHttpClient()
144
+ const { t } = useTranslation()
145
+ const { status: authStatus, user } = useAuth<{ id: string }>()
146
+ const query = useQuery(
147
+ computed(() => {
148
+ const viewer = user.value ? String(user.value.id) : 'anonymous'
149
+ return authStatus.value === 'loading'
150
+ ? null
151
+ : {
152
+ key: ['invoices', viewer, props.statusFilter, props.page],
153
+ principal: viewer,
154
+ keepPreviousData: true,
155
+ fetch: async (signal: AbortSignal) =>
156
+ unwrapList<Invoice>(
157
+ await http.get('/api/invoices', {
158
+ signal,
159
+ params: {
160
+ status: props.statusFilter,
161
+ limit: 20,
162
+ offset: (props.page - 1) * 20,
163
+ },
164
+ }),
165
+ ),
166
+ }
167
+ }),
168
+ )
169
+
170
+ // Status renders outside the item list (it is not an item), and the empty state
171
+ // describes only the key on screen, never a retained previous page.
172
+ return () => {
173
+ const state = query.value
174
+ return h('section', {}, [
175
+ state.status === 'loading' || state.isFetching
176
+ ? h('p', { role: 'status' }, t('common.loading', undefined, { defaultValue: 'Loading…' }))
177
+ : null,
178
+ state.status === 'error'
179
+ ? h(
180
+ 'p',
181
+ { role: 'alert' },
182
+ t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' }),
183
+ )
184
+ : null,
185
+ h(
186
+ 'ul',
187
+ {},
188
+ (state.data ?? []).map((invoice) =>
189
+ h('li', { key: invoice.id }, [
190
+ h('a', { href: `/invoices/${invoice.id}` }, invoice.number),
191
+ ]),
192
+ ),
193
+ ),
194
+ !state.isPreviousData && state.data?.length === 0
195
+ ? h('p', {}, t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' }))
196
+ : null,
197
+ ])
198
+ }
199
+ },
200
+ })
201
+ ```
202
+
203
+ A mutation or a failed load has to change a page that is ALREADY mounted, and
204
+ the cache never starts that request by itself: `set()` paints a mutation's own
205
+ response, `invalidate()` marks what it affects for the next mount, and an
206
+ explicit `fetch()` retries into the mounted page.
207
+
208
+ ```ts
209
+ import { getQueryClient } from '@molecule/app-query'
210
+ import { getClient } from '@molecule/app-http'
211
+ import { t } from '@molecule/app-i18n'
212
+ import { defineComponent, h } from 'vue'
213
+
214
+ // The key names what the document actually depends on — here the signed-in
215
+ // principal, the filter and the page. Another principal's feed is a
216
+ // different document, so an invalidation scoped to this one leaves it alone.
217
+ const feedKey = (principal: string, filter: string, page: number) =>
218
+ ['feed', principal, filter, page] as const
219
+
220
+ const feedOptions = (principal: string, filter: string, page: number) => ({
221
+ key: feedKey(principal, filter, page),
222
+ fetch: async (signal: AbortSignal) =>
223
+ (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
224
+ })
225
+
226
+ async function setFollowing(principal: string, authorId: string, follow: boolean) {
227
+ const client = getQueryClient()
228
+ const http = getClient()
229
+ const { data: body } = follow
230
+ ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
231
+ : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
232
+ // The response IS the document: paint it now, with no second round trip.
233
+ // (If it were only a count or a flag, skip set() and invalidate() instead.)
234
+ client.set(feedKey(principal, 'following', 1), body.feed)
235
+ // Future reads of every feed this principal owns are stale.
236
+ client.invalidate(['feed', principal])
237
+ }
238
+
239
+ const Retry = defineComponent({
240
+ props: { principal: { type: String, required: true } },
241
+ setup(props) {
242
+ return () =>
243
+ h(
244
+ 'button',
245
+ {
246
+ type: 'button',
247
+ onClick: () => {
248
+ // invalidate() alone would leave the mounted page on its error;
249
+ // an explicit fetch retries into it. useQuery shows the outcome.
250
+ void getQueryClient()
251
+ .fetch(feedOptions(props.principal, 'following', 1))
252
+ // The mounted useQuery observer presents this failure via status/error.
253
+ .catch((_error) => {})
254
+ },
255
+ },
256
+ t('common.retry', undefined, { defaultValue: 'Retry' }),
257
+ )
258
+ },
259
+ })
260
+ ```
261
+
262
+ One API resource described once, for every page that reads or changes it.
263
+ `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
264
+ as functions that put the server's record into the cache and fetch the lists on screen again,
265
+ so a page never mirrors a response into a local `ref`. A flag the API models as a sub-path
266
+ (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
267
+ record and is the `commit` of `useOptimisticValue`.
268
+
269
+ ```ts
270
+ import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
271
+ import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-vue'
272
+ import { defineComponent, h, type PropType } from 'vue'
273
+ import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-vue'
274
+
275
+ interface Invoice {
276
+ id: string
277
+ number: string
278
+ flagged: boolean
279
+ }
280
+
281
+ export const invoices = createQueryResource<Invoice>({
282
+ name: 'invoices',
283
+ path: '/invoices',
284
+ http: getClient,
285
+ readList: (response) => unwrapList<Invoice>(response),
286
+ readOne: (response) => unwrapSingle<Invoice>(response),
287
+ })
288
+
289
+ const InvoicePage = defineComponent({
290
+ props: { id: { type: String as PropType<string>, required: true } },
291
+ setup(props) {
292
+ const { user } = useAuth<{ id: string }>()
293
+ const { t } = useTranslation()
294
+ const query = useQuery(() =>
295
+ invoices.detail(user.value ? String(user.value.id) : 'anonymous', props.id),
296
+ )
297
+ return () => {
298
+ const viewer = user.value ? String(user.value.id) : 'anonymous'
299
+ return h(QueryContent<Invoice | null>, {
300
+ query: query.value,
301
+ pending: h(
302
+ 'p',
303
+ { role: 'status' },
304
+ t('common.loading', undefined, { defaultValue: 'Loading…' }),
305
+ ),
306
+ missing: h(
307
+ 'p',
308
+ { role: 'alert' },
309
+ t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' }),
310
+ ),
311
+ error: () =>
312
+ h(
313
+ 'p',
314
+ { role: 'alert' },
315
+ t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' }),
316
+ ),
317
+ children: (invoice) => h(FlagButton, { key: invoice.id, invoice, viewer }),
318
+ })
319
+ }
320
+ },
321
+ })
322
+
323
+ const FlagButton = defineComponent({
324
+ props: {
325
+ invoice: { type: Object as PropType<Invoice>, required: true },
326
+ viewer: { type: String, required: true },
327
+ },
328
+ setup(props) {
329
+ const { t } = useTranslation()
330
+ const flag = useOptimisticValue({
331
+ value: props.invoice.flagged,
332
+ commit: async (on) =>
333
+ (await invoices.toggle(props.viewer, props.invoice.id, 'flag', on)).flagged,
334
+ })
335
+ // While a save is pending the optimistic value leads; when it settles,
336
+ // the saved record on the cache leads. That is the Vue composition of the
337
+ // same behavior React gets by re-rendering `value: invoice.flagged` —
338
+ // a failed save rolls back to the record the cache still holds.
339
+ return () => {
340
+ const flagged = flag.pending.value ? flag.value.value : props.invoice.flagged
341
+ return h(
342
+ 'button',
343
+ {
344
+ type: 'button',
345
+ 'aria-pressed': flagged,
346
+ onClick: () => flag.update((on) => !on),
347
+ },
348
+ [
349
+ flagged
350
+ ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
351
+ : t('invoice.flag', undefined, { defaultValue: 'Flag' }),
352
+ ' ',
353
+ props.invoice.number,
354
+ ],
355
+ )
356
+ }
357
+ },
358
+ })
359
+ ```
360
+
361
+ A pager needs the whole response, including its total. Keep that read on the same resource
362
+ as its mutations, including alternate list paths; a separate hand-written `QueryOptions`
363
+ is outside the resource's refresh tracking.
364
+
365
+ ```typescript
366
+ import { getClient } from '@molecule/app-http'
367
+ import { createQueryResource } from '@molecule/app-query-vue'
368
+
369
+ interface TicketPage {
370
+ tickets: { id: string; subject: string }[]
371
+ total: number
372
+ }
373
+ const tickets = createQueryResource<TicketPage['tickets'][number]>({
374
+ name: 'tickets',
375
+ path: '/tickets',
376
+ http: getClient,
377
+ readOne: (response) => response.data as TicketPage['tickets'][number],
378
+ })
379
+ const page = tickets.listPage(
380
+ 'agent-1',
381
+ { limit: 10, offset: 20 },
382
+ (response) => response.data as TicketPage,
383
+ )
384
+ // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
385
+ // and tickets.refresh('agent-1') refresh this page too.
386
+ // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
387
+ // Use one canonical page reader per path; list() still returns only its own rows.
388
+ // For immediate deletion from an opaque page, add a fifth argument:
389
+ // (page, id) => {
390
+ // const rows = page.tickets.filter((row) => String(row.id) !== id)
391
+ // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
392
+ // }
393
+ ```
394
+
395
+ A resource mutation also waits out a pre-mutation list request before fetching again;
396
+ joining that older in-flight read alone would leave the new record absent.
397
+ Successful deletion removes a row immediately, including one just created through the
398
+ resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
399
+ successful create can recreate the identity. Opaque listPage envelopes need their own
400
+ removeFromPage adapter; no row or total property is guessed.
401
+
402
+ ## Type
403
+
404
+ `feature`
405
+
406
+ ## Installation
407
+
408
+ ```bash
409
+ npm install @molecule/app-query-vue @molecule/app-query vue
410
+ ```
411
+
412
+ ## API
413
+
414
+ ### Interfaces
415
+
416
+ #### `ResourceResponse`
417
+
418
+ The part of an HTTP response a resource reads.
419
+
420
+ ```typescript
421
+ interface ResourceResponse {
422
+ /** The parsed response body. */
423
+ data: unknown
424
+ }
425
+ ```
426
+
427
+ #### `ResourceHttp`
428
+
429
+ The HTTP client a resource calls: the app's own bonded client (`getClient()` from
430
+ `@molecule/app-http`) has this shape. Only what a resource uses is named here.
431
+
432
+ ```typescript
433
+ interface ResourceHttp {
434
+ /** Reads `path`; `signal` cancels it and `params` become the query string. */
435
+ get(
436
+ path: string,
437
+ options?: { signal?: AbortSignal; params?: Record<string, unknown> },
438
+ ): Promise<ResourceResponse>
439
+ /** Creates at `path`. */
440
+ post(path: string, body?: unknown): Promise<ResourceResponse>
441
+ /** Replaces at `path`. */
442
+ put(path: string, body?: unknown): Promise<ResourceResponse>
443
+ /** Changes part of the record at `path`. */
444
+ patch(path: string, body?: unknown): Promise<ResourceResponse>
445
+ /** Removes at `path`. */
446
+ delete(path: string): Promise<ResourceResponse>
447
+ }
448
+ ```
449
+
450
+ #### `QueryResourceConfig`
451
+
452
+ What {@link createQueryResource} needs to know about one resource.
453
+
454
+ ```typescript
455
+ interface QueryResourceConfig<T> {
456
+ /** The first element of every cache key of this resource, e.g. `'invoices'`. */
457
+ name: string
458
+ /** The collection's path under the API base, e.g. `'/invoices'`. */
459
+ path: string
460
+ /** The app's HTTP client, read on every call so a client bonded later is the one used. */
461
+ http: () => ResourceHttp
462
+ /** The field a record is addressed by in a URL. Defaults to `'id'`. */
463
+ id?: keyof T & string
464
+ /** The HTTP method the API updates a record with. Defaults to `'put'`. */
465
+ updateMethod?: 'put' | 'patch'
466
+ /** Reads the records out of a list response. Defaults to the body itself. */
467
+ readList?: (response: ResourceResponse) => T[]
468
+ /** Reads the record out of a detail or write response. Defaults to the body itself. */
469
+ readOne?: (response: ResourceResponse) => T | null
470
+ }
471
+ ```
472
+
473
+ #### `QueryResource`
474
+
475
+ The reads and writes {@link createQueryResource} returns.
476
+
477
+ ```typescript
478
+ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
479
+ /**
480
+ * `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
481
+ * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
482
+ */
483
+ list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
484
+ /**
485
+ * Options for a collection's whole page (rows plus totals), or a filtered collection path.
486
+ * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
487
+ * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
488
+ * Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
489
+ * immediately and keep stale list responses from restoring them.
490
+ */
491
+ listPage<Page>(
492
+ viewer: string,
493
+ params: Record<string, unknown>,
494
+ readPage: (response: ResourceResponse) => Page,
495
+ path?: string,
496
+ removeFromPage?: (page: Page, id: string) => Page,
497
+ ): QueryOptions<Page>
498
+ /**
499
+ * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
500
+ * observes nothing). A missing record resolves to null, not to an error.
501
+ */
502
+ detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null
503
+ /** Creates a record, shows it in the cache and refreshes the lists on screen. */
504
+ create(viewer: string, input: Create): Promise<T>
505
+ /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
506
+ update(viewer: string, id: string, input: Update): Promise<T>
507
+ /** Removes a record from detail and tracked row lists, then refreshes those lists. */
508
+ remove(viewer: string, id: string): Promise<void>
509
+ /**
510
+ * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
511
+ * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
512
+ * of `useOptimisticValue`.
513
+ * The saved detail is published before tracked lists finish refreshing; this promise waits
514
+ * for those refreshes. Render the shared controller's value and let it queue inverse clicks
515
+ * during that interval. A page-local busy guard can drop a click on the newly changed label.
516
+ */
517
+ toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
518
+ /** Fetches the lists on screen again, after a change this resource did not make itself. */
519
+ refresh(viewer: string): Promise<void>
520
+ }
521
+ ```
522
+
523
+ #### `QueryContentSlots`
524
+
525
+ The slots {@link QueryContent} accepts alongside its props: every node-valued
526
+ prop also arrives as a same-named slot, and `children` as the default slot.
527
+
528
+ ```typescript
529
+ interface QueryContentSlots<T> {
530
+ /** The loaded-data branch, which receives `{ data }` (the document). */
531
+ default?: (slotProps: { data: NonNullable<T> }) => VNodeChild
532
+ /** Idle/loading content (the `pending` prop). */
533
+ pending?: () => VNodeChild
534
+ /** Loaded-null content (the `missing` prop). */
535
+ missing?: () => VNodeChild
536
+ }
537
+ ```
538
+
539
+ #### `UseQueryResult`
540
+
541
+ A mounted query's state and its explicit cache and refresh actions.
542
+
543
+ ```typescript
544
+ interface UseQueryResult<T> extends QueryState<T> {
545
+ /**
546
+ * Publish a saved document to this key and all its observers. Render `data`
547
+ * directly instead of copying it to a local ref: later cache updates then
548
+ * remain visible. A function receives this key's current cached document,
549
+ * never retained previous-page data. Returning `undefined` leaves the cache
550
+ * unchanged. A disabled (`null`) query does nothing, including not calling an
551
+ * updater. Like Vue's reactive writes, an updater runs against the cache as
552
+ * it is when the call lands. A saved callback stays bound to its original
553
+ * key. The write supersedes older in-flight reads, using the bonded client's
554
+ * `set` contract.
555
+ */
556
+ setData: (value: T | ((previous: T | undefined) => T | undefined)) => void
557
+ /**
558
+ * Fetch this key again, even when its cached document is fresh. Observers
559
+ * receive the updated state. Resolves with that state, including an error
560
+ * when the request fails; a disabled (`null`) query resolves idle without a
561
+ * request.
562
+ */
563
+ refetch: () => Promise<QueryState<T>>
564
+ }
565
+ ```
566
+
567
+ #### `QueryContentProps`
568
+
569
+ A loaded document owns its controls; absent documents expose only status
570
+ content.
571
+
572
+ ```typescript
573
+ interface QueryContentProps<T> {
574
+ /** State from useQuery, or any compatible query observer. */
575
+ query: Pick<QueryState<T>, 'data' | 'status' | 'error'>
576
+ /**
577
+ * Mounted only with a real document, including false, zero and an empty
578
+ * list. A render function (React's render-prop name) or the default slot,
579
+ * which receives the document as its scoped-slot prop `{ data }`.
580
+ */
581
+ children: (data: NonNullable<T>) => VNodeChild
582
+ /** Initial idle/loading content. Render a status node, never a fake item or action. */
583
+ pending?: VNodeChild
584
+ /** Content for a loaded null record. Null is distinct from an unfinished request. */
585
+ missing?: VNodeChild
586
+ /** A failed initial read. Cached data stays visible if its refresh fails. */
587
+ error?: (error: unknown) => VNodeChild
588
+ }
589
+ ```
590
+
591
+ #### `IntentPrefetchProps`
592
+
593
+ The handlers {@link intentPrefetchProps} returns. The names are Vue's
594
+ listener spellings of pointer enter, focus and touch start, so they spread
595
+ onto an element rendered with `h()` (or a component that forwards attrs) and
596
+ attach as real DOM listeners.
597
+
598
+ ```typescript
599
+ interface IntentPrefetchProps {
600
+ onPointerenter: () => void
601
+ onFocus: () => void
602
+ onTouchstart: () => void
603
+ }
604
+ ```
605
+
606
+ ### Types
607
+
608
+ #### `QueryOptionsInput`
609
+
610
+ What {@link useQuery} observes: the same options object React's hook takes,
611
+ or a ref/getter of one. Passing a ref or getter lets one mounted composable
612
+ follow a changed key on the SAME instance — the Vue counterpart of React
613
+ re-rendering `useQuery` with a new options object.
614
+
615
+ ```typescript
616
+ type QueryOptionsInput<T> = MaybeRefOrGetter<QueryOptions<T> | null>
617
+ ```
618
+
619
+ ### Functions
620
+
621
+ #### `prefetchQuery(options)`
622
+
623
+ Warms the cache for a document, when the connection can afford it (see
624
+ `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
625
+ in-flight document is skipped, and failures are swallowed.
626
+
627
+ ```typescript
628
+ function prefetchQuery<T>(options: QueryOptions<T>): void
629
+ ```
630
+
631
+ - `options` — Key, fetch, freshness.
632
+
633
+ #### `createQueryResource(config)`
634
+
635
+ Describe one API resource once and get its reads and writes on the shared cache.
636
+
637
+ A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
638
+ re-solve the same problems on every screen: a late answer for the previous page lands
639
+ over the current one, and a list still shows what it showed before a comment was added.
640
+ Here the reads are `useQuery` options (one key per
641
+ viewer, page and filter; the previous rows stay until the next answer) and every write puts
642
+ the server's own record into the cache and fetches the lists on screen again.
643
+
644
+ The factory supplies data operations. Mount a keyed
645
+ control inside `QueryContent` (your framework's query package: `@molecule/app-query-react`,
646
+ `-vue`, …) so it receives a loaded record and stays mounted during refresh.
647
+ For a server-backed toggle, use `useOptimisticValue` from your framework binding
648
+ (`@molecule/app-react`, `@molecule/app-vue`, …), or `OptimisticToggleButton` from its UI
649
+ package (`@molecule/app-ui-react`, …) for a boolean. Pass `toggle` as its
650
+ commit adapter, return the saved flag/count, and render the controller's value for the action
651
+ label too. Do not block clicks while that commit is pending. The resource example in
652
+ `@molecule/app-query-react` composes these APIs; a custom handler must provide the same
653
+ readiness and ordering itself.
654
+
655
+ Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
656
+ and the query provider are whatever the app bonded.
657
+
658
+ ```typescript
659
+ function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
660
+ config: QueryResourceConfig<T>,
661
+ ): QueryResource<T, Create, Update>
662
+ ```
663
+
664
+ - `config` — The resource's name, path, HTTP client and response readers.
665
+
666
+ **Returns:** List and detail query options, and create, update, remove, toggle and refresh.
667
+
668
+ #### `usePrefetch()`
669
+
670
+ A stable `prefetch(options)` function for event handlers.
671
+
672
+ ```typescript
673
+ function usePrefetch(): <T>(options: QueryOptions<T>) => void
674
+ ```
675
+
676
+ **Returns:** The prefetch function, one per mounted composable.
677
+
678
+ #### `intentPrefetchProps(options)`
679
+
680
+ Event handlers that warm a document at the first sign of intent: the
681
+ pointer arriving, keyboard focus, or a touch starting. Spread them onto a
682
+ link: `h('a', { href, ...intentPrefetchProps(packageQuery(name)) }, name)`.
683
+
684
+ ```typescript
685
+ function intentPrefetchProps<T>(options: QueryOptions<T>): IntentPrefetchProps
686
+ ```
687
+
688
+ - `options` — Key, fetch, freshness.
689
+
690
+ **Returns:** The handlers.
691
+
692
+ #### `useQuery(options)`
693
+
694
+ The document for `options.key`, kept current: cached data is returned on the
695
+ very first read (so a warmed page never flashes a loading state), a stale or
696
+ missing document is fetched, and every change updates the returned ref.
697
+ Pass `null` to observe nothing. A key change resets to that key's state; the
698
+ hook never hands a caller another key's document — unless the caller opts
699
+ into {@link QueryOptions.keepPreviousData}, and then only within one
700
+ {@link QueryOptions.principal}.
701
+
702
+ Pass the options as a `ref` or getter to follow a changed key on the SAME
703
+ instance — a computed of the route, the viewer or the page. That is the Vue
704
+ counterpart of React re-rendering `useQuery` with a new options object: the
705
+ request stays stable while the key holds, a parent state change neither
706
+ restarts it nor cancels it, so a response that arrives after one still
707
+ lands. It is aborted only when the key changes or the component unmounts
708
+ (the `signal` given to `options.fetch`). Use this instead of a hand-written
709
+ `watch` + `fetch`: a watcher whose cleanup sets a `cancelled` flag, and
710
+ whose source includes a function rebuilt each run, cancels its own request
711
+ on every re-run and then skips the refetch.
712
+ An explicit `refetch()` is an awaited cache fetch; it can finish after the
713
+ observer unmounts, like an explicit `client.fetch(options)` caller.
714
+
715
+ For a LIST, put the route's page, filter and selected view in the key and
716
+ pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
717
+ then keeps the rows already on screen until the new page answers, instead of
718
+ rendering a loading state over an empty list. The key names everything the
719
+ answer depends on, and the app's HTTP client sends the session, so a list
720
+ the server can filter or personalize per viewer puts the viewer in its key
721
+ and passes the same value as `principal` (`'anonymous'` when signed out): an
722
+ account switch then drops the previous account's document immediately. Only
723
+ an endpoint that answers every viewer the same takes a viewer-free key with
724
+ `principal: 'public'`.
725
+
726
+ For custom mutation handlers, `setData(saved)` publishes the server's
727
+ response to this key and every observer. Use `setData(current => next)` for
728
+ a local cache update. Render `data` directly; a component-local copy stops
729
+ observing later server responses. Prefer `createQueryResource` when the
730
+ API's reads and writes can share one resource definition. Mount
731
+ record-dependent actions inside `QueryContent` (or an explicit non-null data
732
+ branch), so a visible action cannot return early because its initial record
733
+ is still missing. Keep loaded actions mounted during refreshes.
734
+ Server-backed toggles use `useOptimisticValue` from `@molecule/app-vue` to
735
+ keep their displayed label and queued clicks on the same state while a save
736
+ finishes.
737
+
738
+ ```typescript
739
+ function useQuery<T>(queryOptions: QueryOptionsInput<T>): Ref<UseQueryResult<T>>
740
+ ```
741
+
742
+ - `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`. A ref or getter of either, so one mounted composable can follow a changed key.
743
+
744
+ **Returns:** A ref of the document's state with `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
745
+
746
+ ### Constants
747
+
748
+ #### `QueryContent`
749
+
750
+ The loaded-data branch receives a non-null document. Pending, failed initial
751
+ reads and missing records never mount that branch, so its actions cannot
752
+ swallow an early click. Cached data remains mounted during refresh, including
753
+ a failed refresh. Status fallbacks belong outside the list or record
754
+ container rendered by `children`, and so does a refresh line; the default
755
+ fallbacks render nothing.
756
+
757
+ The loaded branch is the `children` render function, or the default slot
758
+ (which receives `{ data }`); `pending` and `missing` are node props or
759
+ same-named slots. It is the Vue counterpart of `@molecule/app-query-react`'s
760
+ `QueryContent`: the same props, the same branch rules, and the same DOM for
761
+ the same input. Use it with `h(QueryContent, { query, children, … })` — the
762
+ document's type flows from the `query` prop into `children`.
763
+
764
+ ```typescript
765
+ const QueryContent: (<T>(
766
+ props: QueryContentProps<T>,
767
+ ctx: { slots: QueryContentSlots<T> },
768
+ ) => VNodeChild) & { props: string[] }
769
+ ```
770
+
771
+ - `props` — Query state, loaded content and optional status fallbacks.
772
+ - `ctx` — The functional-component context; its slots carry the same-named alternatives to the node props and the default slot for `children`.
773
+
774
+ **Returns:** Loaded content or the appropriate fallback.
775
+
776
+ ## Injection Notes
777
+
778
+ ### Requirements
779
+
780
+ Peer dependencies:
781
+
782
+ - `@molecule/app-query` ^1.2.0
783
+ - `vue` ^3.4.0
784
+
785
+ ### Runtime Dependencies
786
+
787
+ - `@molecule/app-query`
788
+ - `vue`
789
+
790
+ - **`useQuery` reads the cache synchronously on the first read.** A
791
+ document prefetched from a hovered link, or seeded with `client.set()`
792
+ from a server-rendered JSON island, renders at once — no spinner, no
793
+ layout shift. Render loading from `status === 'idle' || status === 'loading'`;
794
+ `undefined` data can also accompany a completed error. A completed `null`
795
+ response is missing, not pending. The detail example treats only HTTP 404
796
+ or a successful null response as missing; other errors stay load failures.
797
+ The app's bonded HTTP client rejects non-2xx responses. Native `fetch`
798
+ resolves them, so a custom fetcher must check `response.ok` before JSON.
799
+ - **Mount a detail region and its actions only after its initial document arrives.**
800
+ A visible container is not a loaded document: a caller may wait for that container and
801
+ read its text once, or click its button, while `data` is still undefined. Put the loading
802
+ message outside the detail region, as in `PackagePage` above. Keep record-dependent
803
+ controls absent or natively disabled until the record exists; returning early inside
804
+ an enabled click handler loses that click. `client.set()` protects a cache mutation
805
+ from an older read, but cannot recover a click whose handler never sent the mutation.
806
+ - **The key is the identity.** Building `options` inline is fine; the
807
+ composable resubscribes only when the key's value changes, not when the
808
+ `fetch` closure does.
809
+ - **A key change normally resets to the new key's state.** For a list's own
810
+ page/filter/view change, opt into `keepPreviousData` with a `principal`;
811
+ `isPreviousData` tells you the rows on screen belong to the key you just
812
+ left. A completed response (including an empty list) replaces them, and a
813
+ changed principal drops them, so an account switch never shows the previous
814
+ account's rows. Do not emulate this with a local `ref` mirror of the
815
+ query data — that mirror is what serves stale rows under a new page, or
816
+ blanks the list on a re-render.
817
+ - **The key names the viewer whenever the answer can depend on it.** The
818
+ app's HTTP client sends the session, so the server may filter or
819
+ personalize even a list that guests can see (a `favorited` or `following`
820
+ flag), and the cache serves a key's document to whoever observes it,
821
+ across sign-in and sign-out. Key such a list on the viewer
822
+ (`user ? String(user.id) : 'anonymous'`), pass the same value as
823
+ `principal`, and pass `null` while the session is still being restored
824
+ (`status === 'loading'`; the HTTP client holds the request until then
825
+ anyway), so restoring a session never swaps a key that already rendered
826
+ rows. A viewer-free key with `principal: 'public'` is only for an endpoint
827
+ that answers every viewer the same.
828
+ - **Render loading, empty and error status outside the item list**, and never
829
+ give a placeholder the item's own class or element shape: a list read by
830
+ the item class (or by `:first-child`) must contain only real items. An
831
+ empty array is a loaded empty state, not a missing response; render it
832
+ only when `isPreviousData` is not set, because a retained document belongs
833
+ to the key you just left.
834
+ - `intentPrefetchProps` spreads three handlers onto a link. It is a plain
835
+ function (not a composable), so it works inside `.map()` too. The names
836
+ are Vue's listener spellings (`onPointerenter`, `onFocus`, `onTouchstart`).
837
+ - Prefetching respects the browser's data-saver setting and skips 2G
838
+ connections (`shouldPrefetch()` in the core) — do not bypass that for
839
+ "important" links; the person can still click.
840
+ - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
841
+ entry and updates every observer of that key. After a mutation whose response is not the
842
+ whole document, `await query.refetch()` reloads the displayed list. It resolves with the
843
+ resulting state (including `status: 'error'` on failure); a disabled query stays idle.
844
+ Prefer `client.set(key, response)` when the mutation already returned the whole document.
845
+ - Errors are not thrown from the composable; read `status === 'error'` and
846
+ `error`. `client.invalidate()` does NOT refetch a mounted page — it only
847
+ marks documents stale, so the page keeps its error (or its old document)
848
+ until the app retries with `client.fetch(options)` or the page subscribes
849
+ again (a key change or a re-mount).
850
+ - After a mutation, `client.set(key, response)` paints the server's own
851
+ answer at once and supersedes an older fetch already in flight for that
852
+ key, so its response cannot undo the mutation. An existing `fetch()` caller
853
+ still settles independently of the cache write; read `client.get(key)` for the newest document.
854
+ `client.invalidate(prefix)` marks the affected reads stale for their next
855
+ mount. Which key and which scope is the app's decision: the cache does not
856
+ infer it from auth or form state.
857
+
858
+ Render resource-dependent lists and controls through {@link QueryContent}. Its `children`
859
+ function (or default slot) receives only loaded, non-null data; loading and error content
860
+ never mount item actions.
861
+ It renders cached content during refresh and treats an empty list, false and zero as data.
862
+ Put the list, or the record's own container (its card, header or profile block), inside the
863
+ `children` and every status line (loading, error, `isFetching` refresh) beside it, never inside it:
864
+ a reader that finds the container and reads its paragraph must read the record, not "Loading…".
865
+
866
+ ```ts
867
+ h(
868
+ QueryContent,
869
+ { query: query.value, pending: h('p', { role: 'status' }, loadingLabel) },
870
+ // missing: h('p', {}, missingLabel), error: () => h('p', { role: 'alert' }, errorLabel),
871
+ { default: ({ data: record }) => [h(RecordActions, { record })] },
872
+ )
873
+ ```
874
+
875
+ Keep every resource identity in the query key. A boundary cannot correct a query that supplies
876
+ another record's cached data. For a list, map real rows inside the child; never style a status
877
+ placeholder as a row. QueryContent is headless and owns no translations or styling.