@molecule/app-query-svelte 0.0.0-stage → 1.1.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.
@@ -0,0 +1,26 @@
1
+ import type { QueryContentProps } from './types.js';
2
+ declare function $$render<T>(): {
3
+ props: QueryContentProps<T>;
4
+ exports: {};
5
+ bindings: "";
6
+ slots: {};
7
+ events: {};
8
+ };
9
+ declare class __sveltets_Render<T> {
10
+ props(): ReturnType<typeof $$render<T>>['props'];
11
+ events(): ReturnType<typeof $$render<T>>['events'];
12
+ slots(): ReturnType<typeof $$render<T>>['slots'];
13
+ bindings(): "";
14
+ exports(): {};
15
+ }
16
+ interface $$IsomorphicComponent {
17
+ new <T>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<T>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<T>['props']>, ReturnType<__sveltets_Render<T>['events']>, ReturnType<__sveltets_Render<T>['slots']>> & {
18
+ $$bindings?: ReturnType<__sveltets_Render<T>['bindings']>;
19
+ } & ReturnType<__sveltets_Render<T>['exports']>;
20
+ <T>(internal: unknown, props: ReturnType<__sveltets_Render<T>['props']> & {}): ReturnType<__sveltets_Render<T>['exports']>;
21
+ z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
22
+ }
23
+ declare const QueryContent: $$IsomorphicComponent;
24
+ type QueryContent<T> = InstanceType<typeof QueryContent<T>>;
25
+ export default QueryContent;
26
+ //# sourceMappingURL=QueryContent.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"QueryContent.svelte.d.ts","sourceRoot":"","sources":["../src/QueryContent.svelte"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACpD,iBAAS,QAAQ,CAAC,CAAC;WA8CU,iBAAiB,CAAC,CAAC,CAAC;;;;;EAA4E;AAC7H,cAAM,iBAAiB,CAAC,CAAC;IACrB,KAAK,IAAI,UAAU,CAAC,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAChD,MAAM,IAAI,UAAU,CAAC,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;IAClD,KAAK,IAAI,UAAU,CAAC,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAChD,QAAQ;IACR,OAAO;CACV;AAED,UAAU,qBAAqB;IAC3B,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,QAAQ,EAAE,2BAA2B,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,QAAQ,EAAE,eAAe,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG;QAAE,UAAU,CAAC,EAAE,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAA;KAAE,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;IAC5X,CAAC,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;IAC3H,YAAY,CAAC,EAAE,UAAU,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC;CACjE;AACD,QAAA,MAAM,YAAY,EAAE,qBAAmC,CAAC;AACtC,KAAK,YAAY,CAAC,CAAC,IAAI,YAAY,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9D,eAAe,YAAY,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The package's components: the Svelte counterpart of `@molecule/app-query-react`'s
3
+ * `QueryContent`, under the same React name.
4
+ *
5
+ * @module
6
+ */
7
+ export { default as QueryContent } from './QueryContent.svelte';
8
+ //# sourceMappingURL=components.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"components.d.ts","sourceRoot":"","sources":["../src/components.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,uBAAuB,CAAA"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The package's components: the Svelte counterpart of `@molecule/app-query-react`'s
3
+ * `QueryContent`, under the same React name.
4
+ *
5
+ * @module
6
+ */
7
+ export { default as QueryContent } from './QueryContent.svelte';
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Svelte hooks for `@molecule/app-query` — the Svelte counterpart of
3
+ * `@molecule/app-query-react`, with the same props and the same DOM: read a
4
+ * cached document synchronously, observe it, and prefetch on intent.
5
+ *
6
+ * **Load page data with {@link useQuery}, not `fetch` inside an effect.** A hand-written
7
+ * load effect that cancels its request on cleanup re-runs that cleanup whenever one of its
8
+ * dependencies is a function created inline each render, and then discards the response whenever
9
+ * it arrives after one — always on a remote server, never on localhost, which is why the page
10
+ * passes locally and fails on the live URL. `useQuery` subscribes once per key, keeps its request
11
+ * stable across updates, and aborts it only when the key changes or the component is destroyed.
12
+ *
13
+ * {@link useQuery} observes one document from the app's shared cache and
14
+ * delivers cached data on the first read; {@link usePrefetch} and
15
+ * {@link intentPrefetchProps} warm a document when a person is about to open
16
+ * it. Together they make a detail page open with no loading state.
17
+ *
18
+ * This package needs a bonded client: install `@molecule/app-query` with a bond
19
+ * (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
20
+ * `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
21
+ *
22
+ * @example
23
+ * A detail page: the document is fetched once per key, cached documents paint at once, and only
24
+ * an HTTP 404 or a completed `null` is "missing" — other errors stay load failures.
25
+ *
26
+ * ```svelte
27
+ * <script lang="ts">
28
+ * import { isHttpError, getClient } from '@molecule/app-http'
29
+ * import { useTranslation } from '@molecule/app-svelte'
30
+ * import { intentPrefetchProps, useQuery } from '@molecule/app-query-svelte'
31
+ *
32
+ * interface PackageDocument {
33
+ * name: string
34
+ * description: string
35
+ * }
36
+ *
37
+ * const packageQuery = (name: string) => ({
38
+ * key: ['package', name],
39
+ * fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
40
+ * try {
41
+ * const response = await getClient().get<PackageDocument | null>(
42
+ * `/data/packages/${encodeURIComponent(name)}.json`,
43
+ * { signal },
44
+ * )
45
+ * return response.data
46
+ * } catch (error) {
47
+ * if (isHttpError(error) && error.status === 404) return null
48
+ * throw error
49
+ * }
50
+ * },
51
+ * })
52
+ *
53
+ * let { name } = $props()
54
+ * const { t } = useTranslation()
55
+ * const query = useQuery(packageQuery(name))
56
+ * </script>
57
+ *
58
+ * {#if $query.status === 'error'}
59
+ * <p role="alert">{t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' })}</p>
60
+ * {:else if $query.status === 'idle' || $query.status === 'loading'}
61
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
62
+ * {:else if $query.data == null}
63
+ * <p>{t('packages.notFound', undefined, { defaultValue: 'Package not found.' })}</p>
64
+ * {:else}
65
+ * <article><h1>{$query.data.name}</h1><p>{$query.data.description}</p></article>
66
+ * {/if}
67
+ *
68
+ * <a href={`/packages/${name}`} {...intentPrefetchProps(packageQuery(name))}>{name}</a>
69
+ * ```
70
+ *
71
+ * @example
72
+ * A list whose page and filter live in the URL: derive the key from the route and pass
73
+ * `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
74
+ * until the next page answers. Key the list on the viewer and pass the same value as `principal`
75
+ * — an account switch then drops the previous account's rows at once. Pass `null` while the
76
+ * session is still being restored, so restoring a session never swaps a key that already
77
+ * rendered rows. The options arrive as a readable store, so a changed page or filter
78
+ * re-observes on the same component.
79
+ *
80
+ * ```svelte
81
+ * <script lang="ts">
82
+ * import { derived } from 'svelte/store'
83
+ * import { unwrapList } from '@molecule/app-http'
84
+ * import { useTranslation } from '@molecule/app-svelte'
85
+ * import { useQuery } from '@molecule/app-query-svelte'
86
+ * import { useAuth, useHttpClient, useListRoute } from '@molecule/app-svelte'
87
+ *
88
+ * interface Invoice {
89
+ * id: string
90
+ * number: string
91
+ * }
92
+ *
93
+ * const http = useHttpClient()
94
+ * const { t } = useTranslation()
95
+ * const auth = useAuth<{ id: string }>()
96
+ * const list = useListRoute({ pageSize: 20, filters: { status: {} } })
97
+ * const viewer = $derived($auth.user ? String($auth.user.id) : 'anonymous')
98
+ * const query = useQuery(
99
+ * derived(list.page, (page) => ({
100
+ * key: ['invoices', viewer, $list.filters, page],
101
+ * principal: viewer,
102
+ * keepPreviousData: true,
103
+ * fetch: async (signal: AbortSignal) =>
104
+ * unwrapList<Invoice>(
105
+ * await http.get('/api/invoices', {
106
+ * signal,
107
+ * params: { ...$list.filters, limit: $list.pageSize, offset: $list.offset },
108
+ * }),
109
+ * ),
110
+ * })),
111
+ * )
112
+ * </script>
113
+ *
114
+ * <section>
115
+ * {#if $query.status === 'loading' || $query.isFetching}
116
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
117
+ * {/if}
118
+ * {#if $query.status === 'error'}
119
+ * <p role="alert">{t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}</p>
120
+ * {/if}
121
+ * <ul>
122
+ * {#each $query.data ?? [] as invoice (invoice.id)}
123
+ * <li><a href={`/invoices/${invoice.id}`}>{invoice.number}</a></li>
124
+ * {/each}
125
+ * </ul>
126
+ * {#if !$query.isPreviousData && $query.data?.length === 0}
127
+ * <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
128
+ * {/if}
129
+ * <a href={$list.href({ page: $list.page + 1 })}>
130
+ * {t('common.next', undefined, { defaultValue: 'Next page' })}
131
+ * </a>
132
+ * </section>
133
+ * ```
134
+ *
135
+ * @example
136
+ * A mutation or a failed load has to change a page that is ALREADY mounted, and
137
+ * the cache never starts that request by itself: `set()` paints a mutation's own
138
+ * response, `invalidate()` marks what it affects for the next mount, and an
139
+ * explicit `fetch()` retries into the mounted page.
140
+ *
141
+ * ```svelte
142
+ * <script lang="ts">
143
+ * import { getClient } from '@molecule/app-http'
144
+ * import { getQueryClient } from '@molecule/app-query'
145
+ *
146
+ * // The key names what the document actually depends on — here the signed-in
147
+ * // principal, the filter and the page. Another principal's feed is a
148
+ * // different document, so an invalidation scoped to this one leaves it alone.
149
+ * const feedKey = (principal: string, filter: string, page: number) =>
150
+ * ['feed', principal, filter, page] as const
151
+ *
152
+ * const feedOptions = (principal: string, filter: string, page: number) => ({
153
+ * key: feedKey(principal, filter, page),
154
+ * fetch: async (signal: AbortSignal) =>
155
+ * (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
156
+ * })
157
+ *
158
+ * async function setFollowing(principal: string, authorId: string, follow: boolean) {
159
+ * const client = getQueryClient()
160
+ * const http = getClient()
161
+ * const { data: body } = follow
162
+ * ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
163
+ * : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
164
+ * // The response IS the document: paint it now, with no second round trip.
165
+ * client.set(feedKey(principal, 'following', 1), body.feed)
166
+ * // Future reads of every feed this principal owns are stale.
167
+ * client.invalidate(['feed', principal])
168
+ * }
169
+ * </script>
170
+ * ```
171
+ *
172
+ * @example
173
+ * One API resource described once, for every page that reads or changes it.
174
+ * `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
175
+ * as functions that put the server's record into the cache and fetch the lists on screen again,
176
+ * so a page never mirrors a response into local state. A flag the API models as a sub-path
177
+ * (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
178
+ * record and is the `commit` of `OptimisticToggleButton` (or of `useOptimisticValue` from
179
+ * `@molecule/app-svelte` for custom controls). Render resource-dependent lists and controls
180
+ * through {@link QueryContent}: its child snippet receives only loaded, non-null data, so
181
+ * loading and error content never mount item actions.
182
+ *
183
+ * ```svelte
184
+ * <!-- InvoicePage.svelte -->
185
+ * <script module lang="ts">
186
+ * import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
187
+ * import { createQueryResource } from '@molecule/app-query-svelte'
188
+ *
189
+ * interface Invoice {
190
+ * id: string
191
+ * number: string
192
+ * flagged: boolean
193
+ * }
194
+ *
195
+ * // The list and detail reads are useQuery options; the writes paint the
196
+ * // server's own record and refresh the lists on screen.
197
+ * export const invoices = createQueryResource<Invoice>({
198
+ * name: 'invoices',
199
+ * path: '/invoices',
200
+ * http: getClient,
201
+ * readList: (response) => unwrapList<Invoice>(response),
202
+ * readOne: (response) => unwrapSingle<Invoice>(response),
203
+ * })
204
+ * </script>
205
+ *
206
+ * <script lang="ts">
207
+ * import { QueryContent, useQuery } from '@molecule/app-query-svelte'
208
+ * import { OptimisticToggleButton } from '@molecule/app-ui-svelte'
209
+ * import { useTranslation } from '@molecule/app-svelte'
210
+ *
211
+ * let { id }: { id: string } = $props()
212
+ * const { t } = useTranslation()
213
+ * const viewer = 'reader'
214
+ * const query = useQuery(invoices.detail(viewer, id))
215
+ * </script>
216
+ *
217
+ * <QueryContent query={query}>
218
+ * {#snippet pending()}
219
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
220
+ * {/snippet}
221
+ * {#snippet missing()}
222
+ * <p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>
223
+ * {/snippet}
224
+ * {#snippet children(invoice)}
225
+ * <!-- Mounted only with the loaded record. The change shows at once and
226
+ * saves in order; `toggle` waits out older list reads, and an inverse
227
+ * click during that interval queues after the running save. -->
228
+ * <OptimisticToggleButton
229
+ * value={invoice.flagged}
230
+ * commit={async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged}
231
+ * activeLabel={t('invoice.unflag', undefined, { defaultValue: 'Unflag' })}
232
+ * inactiveLabel={t('invoice.flag', undefined, { defaultValue: 'Flag' })}
233
+ * />
234
+ * {/snippet}
235
+ * </QueryContent>
236
+ * ```
237
+ *
238
+ * @remarks
239
+ * - **`useQuery` reads the cache synchronously on the first read.** A
240
+ * document prefetched from a hovered link, or seeded with `client.set()`,
241
+ * renders at once — no spinner, no layout shift. Render loading from
242
+ * `status === 'idle' || status === 'loading'`; `undefined` data can also
243
+ * accompany a completed error. A completed `null` response is missing, not
244
+ * pending. The app's bonded HTTP client rejects non-2xx responses. Native
245
+ * `fetch` resolves them, so a custom fetcher must check `response.ok`
246
+ * before JSON.
247
+ * - **Pass the options as a readable store when they change on a live
248
+ * component** — a route param, a session id, a page number:
249
+ * `useQuery(storeOfOptions)` follows a changed key on the same component,
250
+ * the way React re-renders `useQuery` with new options.
251
+ * - **Mount a detail region and its actions only after its initial document
252
+ * arrives.** A visible container is not a loaded document: a caller may wait
253
+ * for that container and read its text once, or click its button, while
254
+ * `data` is still undefined. Put the loading message outside the detail
255
+ * region, and keep record-dependent controls absent until the record exists.
256
+ * - **The key is the identity.** Building `options` inline is fine; the hook
257
+ * resubscribes only when the key's value changes, not when the `fetch`
258
+ * closure does.
259
+ * - **A key change normally resets to the new key's state.** For a list's own
260
+ * page/filter/view change, opt into `keepPreviousData` with a `principal`;
261
+ * `isPreviousData` tells you the rows on screen belong to the key you just
262
+ * left. A completed response (including an empty list) replaces them, and a
263
+ * changed principal drops them, so an account switch never shows the previous
264
+ * account's rows. Do not emulate this with a local copy of the query data.
265
+ * - **Render loading, empty and error status outside the item list**, and never
266
+ * give a placeholder the item's own class or element shape. An empty array is
267
+ * a loaded empty state, not a missing response; render it only when
268
+ * `isPreviousData` is not set.
269
+ * - `intentPrefetchProps` spreads three Svelte event handlers onto a link. It
270
+ * is a plain function (not a hook), so it works inside `{#each}` too.
271
+ * - Prefetching respects the browser's data-saver setting and skips 2G
272
+ * connections (`shouldPrefetch()` in the core) — do not bypass that for
273
+ * "important" links; the person can still click.
274
+ * - **Refresh a mounted document with `query.refetch()`.** It fetches even a
275
+ * fresh cache entry and updates every observer of that key. After a mutation
276
+ * whose response is not the whole document, `await query.refetch()` reloads
277
+ * the displayed list. It resolves with the resulting state (including
278
+ * `status: 'error'` on failure); a disabled query stays idle. Prefer
279
+ * `client.set(key, response)` when the mutation already returned the whole
280
+ * document.
281
+ * - Errors are not thrown from the hook; read `status === 'error'` and
282
+ * `error`. `client.invalidate()` does NOT refetch a mounted page — it only
283
+ * marks documents stale, so the page keeps its error (or its old document)
284
+ * until the app retries with `client.fetch(options)` or the page subscribes
285
+ * again (a key change or a re-mount).
286
+ * - After a mutation, `client.set(key, response)` paints the server's own
287
+ * answer at once and supersedes an older fetch already in flight for that
288
+ * key, so its response cannot undo the mutation.
289
+ * - Keep every resource identity in the query key. A boundary cannot correct a
290
+ * query that supplies another record's cached data. QueryContent is headless
291
+ * and owns no translations or styling.
292
+ *
293
+ * @module
294
+ */
295
+ export * from './components.js';
296
+ export * from './resource.js';
297
+ export * from './types.js';
298
+ export * from './usePrefetch.js';
299
+ export * from './useQuery.js';
300
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqSG;AAEH,cAAc,iBAAiB,CAAA;AAC/B,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Svelte hooks for `@molecule/app-query` — the Svelte counterpart of
3
+ * `@molecule/app-query-react`, with the same props and the same DOM: read a
4
+ * cached document synchronously, observe it, and prefetch on intent.
5
+ *
6
+ * **Load page data with {@link useQuery}, not `fetch` inside an effect.** A hand-written
7
+ * load effect that cancels its request on cleanup re-runs that cleanup whenever one of its
8
+ * dependencies is a function created inline each render, and then discards the response whenever
9
+ * it arrives after one — always on a remote server, never on localhost, which is why the page
10
+ * passes locally and fails on the live URL. `useQuery` subscribes once per key, keeps its request
11
+ * stable across updates, and aborts it only when the key changes or the component is destroyed.
12
+ *
13
+ * {@link useQuery} observes one document from the app's shared cache and
14
+ * delivers cached data on the first read; {@link usePrefetch} and
15
+ * {@link intentPrefetchProps} warm a document when a person is about to open
16
+ * it. Together they make a detail page open with no loading state.
17
+ *
18
+ * This package needs a bonded client: install `@molecule/app-query` with a bond
19
+ * (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
20
+ * `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
21
+ *
22
+ * @example
23
+ * A detail page: the document is fetched once per key, cached documents paint at once, and only
24
+ * an HTTP 404 or a completed `null` is "missing" — other errors stay load failures.
25
+ *
26
+ * ```svelte
27
+ * <script lang="ts">
28
+ * import { isHttpError, getClient } from '@molecule/app-http'
29
+ * import { useTranslation } from '@molecule/app-svelte'
30
+ * import { intentPrefetchProps, useQuery } from '@molecule/app-query-svelte'
31
+ *
32
+ * interface PackageDocument {
33
+ * name: string
34
+ * description: string
35
+ * }
36
+ *
37
+ * const packageQuery = (name: string) => ({
38
+ * key: ['package', name],
39
+ * fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
40
+ * try {
41
+ * const response = await getClient().get<PackageDocument | null>(
42
+ * `/data/packages/${encodeURIComponent(name)}.json`,
43
+ * { signal },
44
+ * )
45
+ * return response.data
46
+ * } catch (error) {
47
+ * if (isHttpError(error) && error.status === 404) return null
48
+ * throw error
49
+ * }
50
+ * },
51
+ * })
52
+ *
53
+ * let { name } = $props()
54
+ * const { t } = useTranslation()
55
+ * const query = useQuery(packageQuery(name))
56
+ * </script>
57
+ *
58
+ * {#if $query.status === 'error'}
59
+ * <p role="alert">{t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' })}</p>
60
+ * {:else if $query.status === 'idle' || $query.status === 'loading'}
61
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
62
+ * {:else if $query.data == null}
63
+ * <p>{t('packages.notFound', undefined, { defaultValue: 'Package not found.' })}</p>
64
+ * {:else}
65
+ * <article><h1>{$query.data.name}</h1><p>{$query.data.description}</p></article>
66
+ * {/if}
67
+ *
68
+ * <a href={`/packages/${name}`} {...intentPrefetchProps(packageQuery(name))}>{name}</a>
69
+ * ```
70
+ *
71
+ * @example
72
+ * A list whose page and filter live in the URL: derive the key from the route and pass
73
+ * `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
74
+ * until the next page answers. Key the list on the viewer and pass the same value as `principal`
75
+ * — an account switch then drops the previous account's rows at once. Pass `null` while the
76
+ * session is still being restored, so restoring a session never swaps a key that already
77
+ * rendered rows. The options arrive as a readable store, so a changed page or filter
78
+ * re-observes on the same component.
79
+ *
80
+ * ```svelte
81
+ * <script lang="ts">
82
+ * import { derived } from 'svelte/store'
83
+ * import { unwrapList } from '@molecule/app-http'
84
+ * import { useTranslation } from '@molecule/app-svelte'
85
+ * import { useQuery } from '@molecule/app-query-svelte'
86
+ * import { useAuth, useHttpClient, useListRoute } from '@molecule/app-svelte'
87
+ *
88
+ * interface Invoice {
89
+ * id: string
90
+ * number: string
91
+ * }
92
+ *
93
+ * const http = useHttpClient()
94
+ * const { t } = useTranslation()
95
+ * const auth = useAuth<{ id: string }>()
96
+ * const list = useListRoute({ pageSize: 20, filters: { status: {} } })
97
+ * const viewer = $derived($auth.user ? String($auth.user.id) : 'anonymous')
98
+ * const query = useQuery(
99
+ * derived(list.page, (page) => ({
100
+ * key: ['invoices', viewer, $list.filters, page],
101
+ * principal: viewer,
102
+ * keepPreviousData: true,
103
+ * fetch: async (signal: AbortSignal) =>
104
+ * unwrapList<Invoice>(
105
+ * await http.get('/api/invoices', {
106
+ * signal,
107
+ * params: { ...$list.filters, limit: $list.pageSize, offset: $list.offset },
108
+ * }),
109
+ * ),
110
+ * })),
111
+ * )
112
+ * </script>
113
+ *
114
+ * <section>
115
+ * {#if $query.status === 'loading' || $query.isFetching}
116
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
117
+ * {/if}
118
+ * {#if $query.status === 'error'}
119
+ * <p role="alert">{t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}</p>
120
+ * {/if}
121
+ * <ul>
122
+ * {#each $query.data ?? [] as invoice (invoice.id)}
123
+ * <li><a href={`/invoices/${invoice.id}`}>{invoice.number}</a></li>
124
+ * {/each}
125
+ * </ul>
126
+ * {#if !$query.isPreviousData && $query.data?.length === 0}
127
+ * <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
128
+ * {/if}
129
+ * <a href={$list.href({ page: $list.page + 1 })}>
130
+ * {t('common.next', undefined, { defaultValue: 'Next page' })}
131
+ * </a>
132
+ * </section>
133
+ * ```
134
+ *
135
+ * @example
136
+ * A mutation or a failed load has to change a page that is ALREADY mounted, and
137
+ * the cache never starts that request by itself: `set()` paints a mutation's own
138
+ * response, `invalidate()` marks what it affects for the next mount, and an
139
+ * explicit `fetch()` retries into the mounted page.
140
+ *
141
+ * ```svelte
142
+ * <script lang="ts">
143
+ * import { getClient } from '@molecule/app-http'
144
+ * import { getQueryClient } from '@molecule/app-query'
145
+ *
146
+ * // The key names what the document actually depends on — here the signed-in
147
+ * // principal, the filter and the page. Another principal's feed is a
148
+ * // different document, so an invalidation scoped to this one leaves it alone.
149
+ * const feedKey = (principal: string, filter: string, page: number) =>
150
+ * ['feed', principal, filter, page] as const
151
+ *
152
+ * const feedOptions = (principal: string, filter: string, page: number) => ({
153
+ * key: feedKey(principal, filter, page),
154
+ * fetch: async (signal: AbortSignal) =>
155
+ * (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
156
+ * })
157
+ *
158
+ * async function setFollowing(principal: string, authorId: string, follow: boolean) {
159
+ * const client = getQueryClient()
160
+ * const http = getClient()
161
+ * const { data: body } = follow
162
+ * ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
163
+ * : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
164
+ * // The response IS the document: paint it now, with no second round trip.
165
+ * client.set(feedKey(principal, 'following', 1), body.feed)
166
+ * // Future reads of every feed this principal owns are stale.
167
+ * client.invalidate(['feed', principal])
168
+ * }
169
+ * </script>
170
+ * ```
171
+ *
172
+ * @example
173
+ * One API resource described once, for every page that reads or changes it.
174
+ * `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
175
+ * as functions that put the server's record into the cache and fetch the lists on screen again,
176
+ * so a page never mirrors a response into local state. A flag the API models as a sub-path
177
+ * (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
178
+ * record and is the `commit` of `OptimisticToggleButton` (or of `useOptimisticValue` from
179
+ * `@molecule/app-svelte` for custom controls). Render resource-dependent lists and controls
180
+ * through {@link QueryContent}: its child snippet receives only loaded, non-null data, so
181
+ * loading and error content never mount item actions.
182
+ *
183
+ * ```svelte
184
+ * <!-- InvoicePage.svelte -->
185
+ * <script module lang="ts">
186
+ * import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
187
+ * import { createQueryResource } from '@molecule/app-query-svelte'
188
+ *
189
+ * interface Invoice {
190
+ * id: string
191
+ * number: string
192
+ * flagged: boolean
193
+ * }
194
+ *
195
+ * // The list and detail reads are useQuery options; the writes paint the
196
+ * // server's own record and refresh the lists on screen.
197
+ * export const invoices = createQueryResource<Invoice>({
198
+ * name: 'invoices',
199
+ * path: '/invoices',
200
+ * http: getClient,
201
+ * readList: (response) => unwrapList<Invoice>(response),
202
+ * readOne: (response) => unwrapSingle<Invoice>(response),
203
+ * })
204
+ * </script>
205
+ *
206
+ * <script lang="ts">
207
+ * import { QueryContent, useQuery } from '@molecule/app-query-svelte'
208
+ * import { OptimisticToggleButton } from '@molecule/app-ui-svelte'
209
+ * import { useTranslation } from '@molecule/app-svelte'
210
+ *
211
+ * let { id }: { id: string } = $props()
212
+ * const { t } = useTranslation()
213
+ * const viewer = 'reader'
214
+ * const query = useQuery(invoices.detail(viewer, id))
215
+ * </script>
216
+ *
217
+ * <QueryContent query={query}>
218
+ * {#snippet pending()}
219
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
220
+ * {/snippet}
221
+ * {#snippet missing()}
222
+ * <p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>
223
+ * {/snippet}
224
+ * {#snippet children(invoice)}
225
+ * <!-- Mounted only with the loaded record. The change shows at once and
226
+ * saves in order; `toggle` waits out older list reads, and an inverse
227
+ * click during that interval queues after the running save. -->
228
+ * <OptimisticToggleButton
229
+ * value={invoice.flagged}
230
+ * commit={async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged}
231
+ * activeLabel={t('invoice.unflag', undefined, { defaultValue: 'Unflag' })}
232
+ * inactiveLabel={t('invoice.flag', undefined, { defaultValue: 'Flag' })}
233
+ * />
234
+ * {/snippet}
235
+ * </QueryContent>
236
+ * ```
237
+ *
238
+ * @remarks
239
+ * - **`useQuery` reads the cache synchronously on the first read.** A
240
+ * document prefetched from a hovered link, or seeded with `client.set()`,
241
+ * renders at once — no spinner, no layout shift. Render loading from
242
+ * `status === 'idle' || status === 'loading'`; `undefined` data can also
243
+ * accompany a completed error. A completed `null` response is missing, not
244
+ * pending. The app's bonded HTTP client rejects non-2xx responses. Native
245
+ * `fetch` resolves them, so a custom fetcher must check `response.ok`
246
+ * before JSON.
247
+ * - **Pass the options as a readable store when they change on a live
248
+ * component** — a route param, a session id, a page number:
249
+ * `useQuery(storeOfOptions)` follows a changed key on the same component,
250
+ * the way React re-renders `useQuery` with new options.
251
+ * - **Mount a detail region and its actions only after its initial document
252
+ * arrives.** A visible container is not a loaded document: a caller may wait
253
+ * for that container and read its text once, or click its button, while
254
+ * `data` is still undefined. Put the loading message outside the detail
255
+ * region, and keep record-dependent controls absent until the record exists.
256
+ * - **The key is the identity.** Building `options` inline is fine; the hook
257
+ * resubscribes only when the key's value changes, not when the `fetch`
258
+ * closure does.
259
+ * - **A key change normally resets to the new key's state.** For a list's own
260
+ * page/filter/view change, opt into `keepPreviousData` with a `principal`;
261
+ * `isPreviousData` tells you the rows on screen belong to the key you just
262
+ * left. A completed response (including an empty list) replaces them, and a
263
+ * changed principal drops them, so an account switch never shows the previous
264
+ * account's rows. Do not emulate this with a local copy of the query data.
265
+ * - **Render loading, empty and error status outside the item list**, and never
266
+ * give a placeholder the item's own class or element shape. An empty array is
267
+ * a loaded empty state, not a missing response; render it only when
268
+ * `isPreviousData` is not set.
269
+ * - `intentPrefetchProps` spreads three Svelte event handlers onto a link. It
270
+ * is a plain function (not a hook), so it works inside `{#each}` too.
271
+ * - Prefetching respects the browser's data-saver setting and skips 2G
272
+ * connections (`shouldPrefetch()` in the core) — do not bypass that for
273
+ * "important" links; the person can still click.
274
+ * - **Refresh a mounted document with `query.refetch()`.** It fetches even a
275
+ * fresh cache entry and updates every observer of that key. After a mutation
276
+ * whose response is not the whole document, `await query.refetch()` reloads
277
+ * the displayed list. It resolves with the resulting state (including
278
+ * `status: 'error'` on failure); a disabled query stays idle. Prefer
279
+ * `client.set(key, response)` when the mutation already returned the whole
280
+ * document.
281
+ * - Errors are not thrown from the hook; read `status === 'error'` and
282
+ * `error`. `client.invalidate()` does NOT refetch a mounted page — it only
283
+ * marks documents stale, so the page keeps its error (or its old document)
284
+ * until the app retries with `client.fetch(options)` or the page subscribes
285
+ * again (a key change or a re-mount).
286
+ * - After a mutation, `client.set(key, response)` paints the server's own
287
+ * answer at once and supersedes an older fetch already in flight for that
288
+ * key, so its response cannot undo the mutation.
289
+ * - Keep every resource identity in the query key. A boundary cannot correct a
290
+ * query that supplies another record's cached data. QueryContent is headless
291
+ * and owns no translations or styling.
292
+ *
293
+ * @module
294
+ */
295
+ export * from './components.js';
296
+ export * from './resource.js';
297
+ export * from './types.js';
298
+ export * from './usePrefetch.js';
299
+ export * from './useQuery.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * One API resource on the shared query cache. `createQueryResource` is
3
+ * framework-neutral, so it lives in `@molecule/app-query` (with its full
4
+ * documentation); this package re-exports it so Svelte pages import it next to
5
+ * `useQuery` and `QueryContent`.
6
+ *
7
+ * @module
8
+ */
9
+ export type { QueryResource, QueryResourceConfig, ResourceHttp, ResourceResponse, } from '@molecule/app-query';
10
+ export { createQueryResource } from '@molecule/app-query';
11
+ //# sourceMappingURL=resource.d.ts.map