@molecule/app-query-solid 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.
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Solid primitives for `@molecule/app-query`.
3
+ *
4
+ * **Load page data with {@link useQuery}, not `fetch` inside a `createEffect`.** A hand-written
5
+ * load effect that cancels its request on cleanup (a `cancelled` flag, or an `AbortController`)
6
+ * re-runs its cleanup on EVERY re-run whenever one of its tracked dependencies is a function
7
+ * created inline each run — `const [messages, setError] = useApiErrors()` returning arrow
8
+ * functions is the usual source. The effect's own guard (`if (loaded === slug) return`) then
9
+ * returns without refetching, so the response is discarded whenever it arrives after a
10
+ * re-run: always on a remote server, never on localhost, which is why the page passes locally
11
+ * and fails on the live URL. `useQuery` subscribes once per key, keeps its request stable
12
+ * across updates, and aborts it only when the key changes or the page unmounts.
13
+ *
14
+ * {@link useQuery} observes one document from the app's shared cache and
15
+ * returns cached data on the first read; {@link usePrefetch} and
16
+ * {@link intentPrefetchProps} warm a document when a person is about to
17
+ * open it. Together they make a detail page open with no loading state.
18
+ *
19
+ * This package needs a bonded client: install `@molecule/app-query` with a bond
20
+ * (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
21
+ * `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
22
+ *
23
+ * **Keep displayed records on the query cache.** Render `query.data` directly. A custom
24
+ * mutation handler publishes its saved response with `query.setData(saved)`; every observer
25
+ * and the next visit receive it, and subsequent refreshes still update the view. A local
26
+ * signal copy hydrated only once per record hides later query answers. Editable form
27
+ * drafts remain local until saved. Prefer {@link createQueryResource} for a complete resource;
28
+ * its writes already publish the response and refresh its tracked collections.
29
+ *
30
+ * @example
31
+ * ```tsx
32
+ * import { Match, Show, Switch } from 'solid-js'
33
+ * import { getClient, isHttpError } from '@molecule/app-http'
34
+ * import { t } from '@molecule/app-i18n'
35
+ * import { intentPrefetchProps, useQuery } from '@molecule/app-query-solid'
36
+ *
37
+ * interface PackageDocument {
38
+ * name: string
39
+ * description: string
40
+ * }
41
+ *
42
+ * const packageQuery = (name: string) => ({
43
+ * key: ['package', name],
44
+ * fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
45
+ * try {
46
+ * const response = await getClient().get<PackageDocument | null>(
47
+ * `/data/packages/${encodeURIComponent(name)}.json`,
48
+ * { signal },
49
+ * )
50
+ * return response.data
51
+ * } catch (error) {
52
+ * if (isHttpError(error) && error.status === 404) return null
53
+ * throw error
54
+ * }
55
+ * },
56
+ * })
57
+ *
58
+ * function PackageLink(props: { name: string }) {
59
+ * return (
60
+ * <a href={`/packages/${props.name}`} {...intentPrefetchProps(packageQuery(props.name))}>
61
+ * {props.name}
62
+ * </a>
63
+ * )
64
+ * }
65
+ *
66
+ * function PackagePage(props: { name: string }) {
67
+ * // The options are an accessor, so a changed name (route param, input) re-keys
68
+ * // the observer on the same mounted component, the way React re-renders useQuery.
69
+ * const query = useQuery(() => packageQuery(props.name))
70
+ * const loaded = (): PackageDocument | null => {
71
+ * if (query.status === 'error') return null
72
+ * if (query.status === 'idle' || query.status === 'loading') return null
73
+ * if (query.data === undefined || query.data === null) return null
74
+ * return query.data
75
+ * }
76
+ * return (
77
+ * <Switch>
78
+ * <Match when={query.status === 'error'}>
79
+ * <p role="alert">
80
+ * {t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' })}
81
+ * </p>
82
+ * </Match>
83
+ * <Match when={query.status === 'idle' || query.status === 'loading'}>
84
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
85
+ * </Match>
86
+ * <Match when={query.data === undefined || query.data === null}>
87
+ * <p>{t('packages.notFound', undefined, { defaultValue: 'Package not found.' })}</p>
88
+ * </Match>
89
+ * <Match when={loaded()} keyed>
90
+ * {(doc) => (
91
+ * <article>
92
+ * <h1>{doc.name}</h1>
93
+ * <p>{doc.description}</p>
94
+ * </article>
95
+ * )}
96
+ * </Match>
97
+ * </Switch>
98
+ * )
99
+ * }
100
+ * ```
101
+ *
102
+ * @example
103
+ * A list whose page and filter live in the URL: derive the key from the route and pass
104
+ * `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
105
+ * until the next page answers. The app's HTTP client sends the session, so the viewer is part of
106
+ * what the answer depends on: key on it and pass the same value as `principal` — an account
107
+ * switch then drops the previous account's rows at once. Pass `null` while the session is still
108
+ * being restored (`status === 'loading'`; the HTTP client holds the request until then anyway),
109
+ * so restoring a session never swaps a key that already rendered rows.
110
+ *
111
+ * ```tsx
112
+ * import { For, Show } from 'solid-js'
113
+ * import { unwrapList } from '@molecule/app-http'
114
+ * import { useAuth, useHttpClient, useListRoute, useTranslation } from '@molecule/app-solid'
115
+ * import { useQuery } from '@molecule/app-query-solid'
116
+ *
117
+ * interface Invoice {
118
+ * id: string
119
+ * number: string
120
+ * }
121
+ *
122
+ * function InvoiceList() {
123
+ * const http = useHttpClient()
124
+ * const { t } = useTranslation()
125
+ * const { status, user } = useAuth<{ id: string }>()
126
+ * const list = useListRoute({ pageSize: 20, filters: { status: {} } })
127
+ * const viewer = (): string => (user() ? String(user().id) : 'anonymous')
128
+ * const query = useQuery(
129
+ * () =>
130
+ * status() === 'loading' || !list.canLoad
131
+ * ? null
132
+ * : {
133
+ * key: ['invoices', viewer(), list.filters, list.page],
134
+ * principal: viewer(),
135
+ * keepPreviousData: true,
136
+ * fetch: async (signal: AbortSignal) =>
137
+ * unwrapList<Invoice>(
138
+ * await http.get('/api/invoices', {
139
+ * signal,
140
+ * params: { ...list.filters, limit: list.pageSize, offset: list.offset },
141
+ * }),
142
+ * ),
143
+ * },
144
+ * )
145
+ *
146
+ * // Status renders outside the item list (it is not an item), and the empty state
147
+ * // describes only the key on screen, never a retained previous page.
148
+ * return (
149
+ * <section>
150
+ * <Show when={query.isFetching || status() === 'loading'}>
151
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
152
+ * </Show>
153
+ * <Show when={query.status === 'error'}>
154
+ * <p role="alert">
155
+ * {t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}
156
+ * </p>
157
+ * </Show>
158
+ * <ul>
159
+ * <For each={query.data ?? []}>
160
+ * {(invoice) => (
161
+ * <li>
162
+ * <a href={`/invoices/${invoice.id}`}>{invoice.number}</a>
163
+ * </li>
164
+ * )}
165
+ * </For>
166
+ * </ul>
167
+ * <Show when={!query.isPreviousData && query.data?.length === 0}>
168
+ * <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
169
+ * </Show>
170
+ * <a href={list.href({ page: list.page + 1 })}>
171
+ * {t('common.next', undefined, { defaultValue: 'Next page' })}
172
+ * </a>
173
+ * </section>
174
+ * )
175
+ * }
176
+ * ```
177
+ *
178
+ * @example
179
+ * A mutation or a failed load has to change a page that is ALREADY mounted, and
180
+ * the cache never starts that request by itself: `set()` paints a mutation's own
181
+ * response, `invalidate()` marks what it affects for the next mount, and an
182
+ * explicit `fetch()` retries into the mounted page.
183
+ *
184
+ * ```tsx
185
+ * import { getClient } from '@molecule/app-http'
186
+ * import { t } from '@molecule/app-i18n'
187
+ * import { getQueryClient } from '@molecule/app-query'
188
+ *
189
+ * // The key names what the document actually depends on — here the signed-in
190
+ * // principal, the filter and the page. Another principal's feed is a
191
+ * // different document, so an invalidation scoped to this one leaves it alone.
192
+ * const feedKey = (principal: string, filter: string, page: number) =>
193
+ * ['feed', principal, filter, page] as const
194
+ *
195
+ * const feedOptions = (principal: string, filter: string, page: number) => ({
196
+ * key: feedKey(principal, filter, page),
197
+ * fetch: async (signal: AbortSignal) =>
198
+ * (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
199
+ * })
200
+ *
201
+ * async function setFollowing(principal: string, authorId: string, follow: boolean) {
202
+ * const client = getQueryClient()
203
+ * const http = getClient()
204
+ * const { data: body } = follow
205
+ * ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
206
+ * : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
207
+ * // The response IS the document: paint it now, with no second round trip.
208
+ * // (If it were only a count or a flag, skip set() and invalidate() instead.)
209
+ * client.set(feedKey(principal, 'following', 1), body.feed)
210
+ * // Future reads of every feed this principal owns are stale.
211
+ * client.invalidate(['feed', principal])
212
+ * }
213
+ *
214
+ * function Retry(props: { principal: string }) {
215
+ * return (
216
+ * <button
217
+ * onClick={() => {
218
+ * // invalidate() alone would leave the mounted page on its error;
219
+ * // an explicit fetch retries into it. useQuery shows the outcome.
220
+ * void getQueryClient()
221
+ * .fetch(feedOptions(props.principal, 'following', 1))
222
+ * // The mounted useQuery observer presents this failure via status/error.
223
+ * .catch((_error) => {})
224
+ * }}
225
+ * >
226
+ * {t('common.retry', undefined, { defaultValue: 'Retry' })}
227
+ * </button>
228
+ * )
229
+ * }
230
+ * ```
231
+ *
232
+ * @example
233
+ * One API resource described once, for every page that reads or changes it.
234
+ * `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
235
+ * as functions that put the server's record into the cache and fetch the lists on screen again,
236
+ * so a page never mirrors a response into a local signal. A flag the API models as a sub-path
237
+ * (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
238
+ * record and is the `commit` of `useOptimisticValue`.
239
+ *
240
+ * ```tsx
241
+ * import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
242
+ * import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-solid'
243
+ * import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-solid'
244
+ *
245
+ * interface Invoice {
246
+ * id: string
247
+ * number: string
248
+ * flagged: boolean
249
+ * }
250
+ *
251
+ * export const invoices = createQueryResource<Invoice>({
252
+ * name: 'invoices',
253
+ * path: '/invoices',
254
+ * http: getClient,
255
+ * readList: (response) => unwrapList<Invoice>(response),
256
+ * readOne: (response) => unwrapSingle<Invoice>(response),
257
+ * })
258
+ *
259
+ * function InvoicePage(props: { id: string }) {
260
+ * const { user } = useAuth<{ id: string }>()
261
+ * const { t } = useTranslation()
262
+ * const viewer = (): string => {
263
+ * const current = user()
264
+ * return current ? String(current.id) : 'anonymous'
265
+ * }
266
+ * const query = useQuery(() => invoices.detail(viewer(), props.id))
267
+ * return (
268
+ * <QueryContent
269
+ * query={query}
270
+ * pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
271
+ * missing={<p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>}
272
+ * error={() => <p role="alert">{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}</p>}
273
+ * >
274
+ * {(invoice) => <FlagButton invoice={invoice} viewer={viewer()} />}
275
+ * </QueryContent>
276
+ * )
277
+ * }
278
+ *
279
+ * function FlagButton(props: { invoice: Invoice; viewer: string }) {
280
+ * const { t } = useTranslation()
281
+ * const flag = useOptimisticValue({
282
+ * value: props.invoice.flagged,
283
+ * commit: async (on) => (await invoices.toggle(props.viewer, props.invoice.id, 'flag', on)).flagged,
284
+ * })
285
+ * return (
286
+ * <button type="button" aria-pressed={flag.value()} onClick={() => flag.update((on) => !on)}>
287
+ * {flag.value()
288
+ * ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
289
+ * : t('invoice.flag', undefined, { defaultValue: 'Flag' })} {props.invoice.number}
290
+ * </button>
291
+ * )
292
+ * }
293
+ * ```
294
+ *
295
+ * @example
296
+ * A pager needs the whole response, including its total. Keep that read on the same resource
297
+ * as its mutations, including alternate list paths; a separate hand-written `QueryOptions`
298
+ * is outside the resource's refresh tracking.
299
+ *
300
+ * ```typescript
301
+ * import { getClient } from '@molecule/app-http'
302
+ * import { createQueryResource } from '@molecule/app-query-solid'
303
+ *
304
+ * interface TicketPage { tickets: { id: string; subject: string }[]; total: number }
305
+ * const tickets = createQueryResource<TicketPage['tickets'][number]>({
306
+ * name: 'tickets', path: '/tickets', http: getClient,
307
+ * readOne: (response) => response.data as TicketPage['tickets'][number],
308
+ * })
309
+ * const page = tickets.listPage('agent-1', { limit: 10, offset: 20 },
310
+ * (response) => response.data as TicketPage)
311
+ * // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
312
+ * // and tickets.refresh('agent-1') refresh this page too.
313
+ * // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
314
+ * // Use one canonical page reader per path; list() still returns only its own rows.
315
+ * // For immediate deletion from an opaque page, add a fifth argument:
316
+ * // (page, id) => {
317
+ * // const rows = page.tickets.filter((row) => String(row.id) !== id)
318
+ * // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
319
+ * // }
320
+ * ```
321
+ * A resource mutation also waits out a pre-mutation list request before fetching again;
322
+ * joining that older in-flight read alone would leave the new record absent.
323
+ * Successful deletion removes a row immediately, including one just created through the
324
+ * resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
325
+ * successful create can recreate the identity. Opaque listPage envelopes need their own
326
+ * removeFromPage adapter; no row or total property is guessed.
327
+ *
328
+ * @remarks
329
+ * - **`useQuery` reads the cache synchronously on the first render.** A
330
+ * document prefetched from a hovered link, or seeded with `client.set()`
331
+ * from a server-rendered JSON island, renders at once — no spinner, no
332
+ * layout shift. Render loading from `status === 'idle' || status === 'loading'`;
333
+ * `undefined` data can also accompany a completed error. A completed `null`
334
+ * response is missing, not pending. The detail example treats only HTTP 404
335
+ * or a successful null response as missing; other errors stay load failures.
336
+ * The app's bonded HTTP client rejects non-2xx responses. Native `fetch`
337
+ * resolves them, so a custom fetcher must check `response.ok` before JSON.
338
+ * - **A component body runs once in Solid: pass the options as an accessor.**
339
+ * `useQuery(() => packageQuery(props.name))` follows a changed name (route
340
+ * param, input, parent state) on the same mounted hook, the way React
341
+ * re-renders `useQuery` with a new options object. Options built once from
342
+ * props are read once — a later prop change would not re-key the observer.
343
+ * - **Mount a detail region and its actions only after its initial document arrives.**
344
+ * A visible container is not a loaded document: a caller may wait for that container and
345
+ * read its text once, or click its button, while `data` is still undefined. Put the loading
346
+ * message outside the detail region, as in `PackagePage` above. Keep record-dependent
347
+ * controls absent or natively disabled until the record exists; returning early inside
348
+ * an enabled click handler loses that click. `client.set()` protects a cache mutation
349
+ * from an older read, but cannot recover a click whose handler never sent the mutation.
350
+ * - **The key is the identity.** Building `options` inside the accessor is
351
+ * fine; the hook resubscribes only when the key's value changes, not when
352
+ * the `fetch` closure does.
353
+ * - **A key change normally resets to the new key's state.** For a list's own
354
+ * page/filter/view change, opt into `keepPreviousData` with a `principal`;
355
+ * `isPreviousData` tells you the rows on screen belong to the key you just
356
+ * left. A completed response (including an empty list) replaces them, and a
357
+ * changed principal drops them, so an account switch never shows the previous
358
+ * account's rows. Do not emulate this with a local signal mirror of the
359
+ * query data — that mirror is what serves stale rows under a new page, or
360
+ * blanks the list on an update.
361
+ * - **The key names the viewer whenever the answer can depend on it.** The
362
+ * app's HTTP client sends the session, so the server may filter or
363
+ * personalize even a list that guests can see (a `favorited` or `following`
364
+ * flag), and the cache serves a key's document to whoever observes it,
365
+ * across sign-in and sign-out. Key such a list on the viewer
366
+ * (`user() ? String(user().id) : 'anonymous'`), pass the same value as
367
+ * `principal`, and pass `null` while the session is still being restored
368
+ * (`status === 'loading'`; the HTTP client holds the request until then
369
+ * anyway), so restoring a session never swaps a key that already rendered
370
+ * rows. A viewer-free key with `principal: 'public'` is only for an endpoint
371
+ * that answers every viewer the same. A protected `useListRoute` view also
372
+ * passes `null` while `canLoad` is false.
373
+ * - **Render loading, empty and error status outside the item list**, and never
374
+ * give a placeholder the item's own class or element shape: a list read by
375
+ * the item class (or by `:first-child`) must contain only real items. An
376
+ * empty array is a loaded empty state, not a missing response; render it
377
+ * only when `isPreviousData` is not set, because a retained document belongs
378
+ * to the key you just left.
379
+ * - `intentPrefetchProps` spreads three handlers onto a link. It is a plain
380
+ * function (not a primitive), so it works inside `<For>` too.
381
+ * - Prefetching respects the browser's data-saver setting and skips 2G
382
+ * connections (`shouldPrefetch()` in the core) — do not bypass that for
383
+ * "important" links; the person can still click.
384
+ * - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
385
+ * entry and updates every observer of that key. After a mutation whose response is not the
386
+ * whole document, `await query.refetch()` reloads the displayed list. It resolves with the
387
+ * resulting state (including `status: 'error'` on failure); a disabled query stays idle.
388
+ * Prefer `client.set(key, response)` when the mutation already returned the whole document.
389
+ * - Errors are not thrown from the hook; read `status === 'error'` and
390
+ * `error`. `client.invalidate()` does NOT refetch a mounted page — it only
391
+ * marks documents stale, so the page keeps its error (or its old document)
392
+ * until the app retries with `client.fetch(options)` or the page subscribes
393
+ * again (a key change or a re-mount).
394
+ * - After a mutation, `client.set(key, response)` paints the server's own
395
+ * answer at once and supersedes an older fetch already in flight for that
396
+ * key, so its response cannot undo the mutation. An existing `fetch()` caller
397
+ * still settles independently of the cache write; read `client.get(key)` for the newest document.
398
+ * `client.invalidate(prefix)` marks the affected reads stale for their next
399
+ * mount. Which key and which scope is the app's decision: the cache does not
400
+ * infer it from auth or form state.
401
+ *
402
+ * Render resource-dependent lists and controls through {@link QueryContent}. Its child function
403
+ * receives only loaded, non-null data; loading and error content never mount item actions.
404
+ * It renders cached content during refresh and treats an empty list, false and zero as data.
405
+ * Put the list, or the record's own container (its card, header or profile block), inside the
406
+ * child and every status line (loading, error, `isFetching` refresh) beside it, never inside it:
407
+ * a reader that finds the container and reads its paragraph must read the record, not "Loading…".
408
+ *
409
+ * ```tsx
410
+ * <QueryContent query={query} pending={<p role="status">{loadingLabel}</p>}
411
+ * missing={<p>{missingLabel}</p>} error={() => <p role="alert">{errorLabel}</p>}>
412
+ * {(record) => <RecordActions record={record} />}
413
+ * </QueryContent>
414
+ * ```
415
+ *
416
+ * Keep every resource identity in the query key. A boundary cannot correct a query that supplies
417
+ * another record's cached data. For a list, map real rows inside the child; never style a status
418
+ * placeholder as a row. QueryContent is headless and owns no translations or styling.
419
+ *
420
+ * @module
421
+ */
422
+ export * from './query-content.js';
423
+ export * from './resource.js';
424
+ export * from './types.js';
425
+ export * from './use-prefetch.js';
426
+ export * from './use-query.js';
427
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoaG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,mBAAmB,CAAA;AACjC,cAAc,gBAAgB,CAAA"}