@pyreon/query 0.6.0 → 0.7.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.
@@ -1,626 +1,356 @@
1
- import { CancelledError, InfiniteQueryObserver, MutationCache, MutationObserver, QueriesObserver, QueryCache, QueryClient, QueryObserver, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, hashKey, hydrate, isCancelledError, keepPreviousData } from "@tanstack/query-core";
2
- import { createContext, onMount, onUnmount, provide, useContext } from "@pyreon/core";
3
- import { batch, effect, signal } from "@pyreon/reactivity";
1
+ import { CancelledError, DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryObserverOptions, InfiniteQueryObserverResult, InvalidateOptions, InvalidateQueryFilters, MutateFunction, MutationCache, MutationFilters, MutationFilters as MutationFilters$1, MutationObserverOptions, MutationObserverResult, QueryCache, QueryClient, QueryClient as QueryClient$1, QueryClientConfig, QueryFilters, QueryFilters as QueryFilters$1, QueryKey, QueryKey as QueryKey$1, QueryObserverOptions, QueryObserverResult, RefetchOptions, RefetchQueryFilters, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, hashKey, hydrate, isCancelledError, keepPreviousData } from "@tanstack/query-core";
2
+ import * as _pyreon_core0 from "@pyreon/core";
3
+ import { Props, VNode, VNodeChild } from "@pyreon/core";
4
+ import { Signal } from "@pyreon/reactivity";
4
5
 
5
- //#region src/query-client.ts
6
-
7
- /**
8
- * Provides a QueryClient to all descendant components via context.
9
- * Wrap your app root with this to enable useQuery / useMutation throughout the tree.
10
- *
11
- * @example
12
- * const client = new QueryClient()
13
- * mount(h(QueryClientProvider, { client }, h(App, null)), el)
14
- */
15
- function QueryClientProvider(props) {
16
- provide(QueryClientContext, props.client);
17
- onMount(() => {
18
- props.client.mount();
19
- return () => props.client.unmount();
20
- });
21
- const ch = props.children;
22
- return typeof ch === "function" ? ch() : ch;
6
+ //#region src/query-client.d.ts
7
+ interface QueryClientProviderProps extends Props {
8
+ client: QueryClient$1;
9
+ children?: VNodeChild;
23
10
  }
11
+ declare const QueryClientContext: _pyreon_core0.Context<QueryClient$1 | null>;
24
12
  /**
25
- * Returns the nearest QueryClient provided by <QueryClientProvider>.
26
- * Throws if called outside of one.
27
- */
28
- function useQueryClient() {
29
- const client = useContext(QueryClientContext);
30
- if (!client) throw new Error("[@pyreon/query] No QueryClient found. Wrap your app with <QueryClientProvider client={client}>.");
31
- return client;
32
- }
33
-
34
- //#endregion
35
- //#region src/use-infinite-query.ts
13
+ * Provides a QueryClient to all descendant components via context.
14
+ * Wrap your app root with this to enable useQuery / useMutation throughout the tree.
15
+ *
16
+ * @example
17
+ * const client = new QueryClient()
18
+ * mount(h(QueryClientProvider, { client }, h(App, null)), el)
19
+ */
20
+ declare function QueryClientProvider(props: QueryClientProviderProps): VNode;
36
21
  /**
37
- * Subscribe to a paginated / infinite-scroll query.
38
- * Returns fine-grained reactive signals plus `fetchNextPage`, `fetchPreviousPage`,
39
- * `hasNextPage` and `hasPreviousPage`.
40
- *
41
- * @example
42
- * const query = useInfiniteQuery(() => ({
43
- * queryKey: ['posts'],
44
- * queryFn: ({ pageParam }) => fetchPosts(pageParam as number),
45
- * initialPageParam: 0,
46
- * getNextPageParam: (lastPage) => lastPage.nextCursor,
47
- * }))
48
- * // query.data()?.pages — array of pages
49
- * // h('button', { onClick: () => query.fetchNextPage() }, 'Load more')
50
- */
51
- function useInfiniteQuery(options) {
52
- const observer = new InfiniteQueryObserver(useQueryClient(), options());
53
- const initial = observer.getCurrentResult();
54
- const resultSig = signal(initial);
55
- const dataSig = signal(initial.data);
56
- const errorSig = signal(initial.error ?? null);
57
- const statusSig = signal(initial.status);
58
- const isPending = signal(initial.isPending);
59
- const isLoading = signal(initial.isLoading);
60
- const isFetching = signal(initial.isFetching);
61
- const isFetchingNextPage = signal(initial.isFetchingNextPage);
62
- const isFetchingPreviousPage = signal(initial.isFetchingPreviousPage);
63
- const isError = signal(initial.isError);
64
- const isSuccess = signal(initial.isSuccess);
65
- const hasNextPage = signal(initial.hasNextPage);
66
- const hasPreviousPage = signal(initial.hasPreviousPage);
67
- const unsub = observer.subscribe(r => {
68
- batch(() => {
69
- resultSig.set(r);
70
- dataSig.set(r.data);
71
- errorSig.set(r.error ?? null);
72
- statusSig.set(r.status);
73
- isPending.set(r.isPending);
74
- isLoading.set(r.isLoading);
75
- isFetching.set(r.isFetching);
76
- isFetchingNextPage.set(r.isFetchingNextPage);
77
- isFetchingPreviousPage.set(r.isFetchingPreviousPage);
78
- isError.set(r.isError);
79
- isSuccess.set(r.isSuccess);
80
- hasNextPage.set(r.hasNextPage);
81
- hasPreviousPage.set(r.hasPreviousPage);
82
- });
83
- });
84
- effect(() => {
85
- observer.setOptions(options());
86
- });
87
- onUnmount(() => unsub());
88
- return {
89
- result: resultSig,
90
- data: dataSig,
91
- error: errorSig,
92
- status: statusSig,
93
- isPending,
94
- isLoading,
95
- isFetching,
96
- isFetchingNextPage,
97
- isFetchingPreviousPage,
98
- isError,
99
- isSuccess,
100
- hasNextPage,
101
- hasPreviousPage,
102
- fetchNextPage: () => observer.fetchNextPage(),
103
- fetchPreviousPage: () => observer.fetchPreviousPage(),
104
- refetch: () => observer.refetch()
105
- };
106
- }
107
-
22
+ * Returns the nearest QueryClient provided by <QueryClientProvider>.
23
+ * Throws if called outside of one.
24
+ */
25
+ declare function useQueryClient(): QueryClient$1;
108
26
  //#endregion
109
- //#region src/use-is-fetching.ts
110
- /**
111
- * Returns a signal that tracks how many queries are currently in-flight.
112
- * Useful for global loading indicators.
113
- *
114
- * @example
115
- * const fetching = useIsFetching()
116
- * // h('span', null, () => fetching() > 0 ? 'Loading…' : '')
117
- */
118
- function useIsFetching(filters) {
119
- const client = useQueryClient();
120
- const count = signal(client.isFetching(filters));
121
- const unsub = client.getQueryCache().subscribe(() => {
122
- count.set(client.isFetching(filters));
123
- });
124
- onUnmount(() => unsub());
125
- return count;
27
+ //#region src/use-infinite-query.d.ts
28
+ interface UseInfiniteQueryResult<TQueryFnData, TError = DefaultError> {
29
+ /** Raw signal full observer result. */
30
+ result: Signal<InfiniteQueryObserverResult<InfiniteData<TQueryFnData>, TError>>;
31
+ data: Signal<InfiniteData<TQueryFnData> | undefined>;
32
+ error: Signal<TError | null>;
33
+ status: Signal<'pending' | 'error' | 'success'>;
34
+ isPending: Signal<boolean>;
35
+ isLoading: Signal<boolean>;
36
+ isFetching: Signal<boolean>;
37
+ isFetchingNextPage: Signal<boolean>;
38
+ isFetchingPreviousPage: Signal<boolean>;
39
+ isError: Signal<boolean>;
40
+ isSuccess: Signal<boolean>;
41
+ hasNextPage: Signal<boolean>;
42
+ hasPreviousPage: Signal<boolean>;
43
+ fetchNextPage: () => Promise<InfiniteQueryObserverResult<InfiniteData<TQueryFnData>, TError>>;
44
+ fetchPreviousPage: () => Promise<InfiniteQueryObserverResult<InfiniteData<TQueryFnData>, TError>>;
45
+ refetch: () => Promise<QueryObserverResult<InfiniteData<TQueryFnData>, TError>>;
126
46
  }
127
47
  /**
128
- * Returns a signal that tracks how many mutations are currently in-flight.
129
- *
130
- * @example
131
- * const mutating = useIsMutating()
132
- * // h('span', null, () => mutating() > 0 ? 'Saving…' : '')
133
- */
134
- function useIsMutating(filters) {
135
- const client = useQueryClient();
136
- const count = signal(client.isMutating(filters));
137
- const unsub = client.getMutationCache().subscribe(() => {
138
- count.set(client.isMutating(filters));
139
- });
140
- onUnmount(() => unsub());
141
- return count;
142
- }
143
-
48
+ * Subscribe to a paginated / infinite-scroll query.
49
+ * Returns fine-grained reactive signals plus `fetchNextPage`, `fetchPreviousPage`,
50
+ * `hasNextPage` and `hasPreviousPage`.
51
+ *
52
+ * @example
53
+ * const query = useInfiniteQuery(() => ({
54
+ * queryKey: ['posts'],
55
+ * queryFn: ({ pageParam }) => fetchPosts(pageParam as number),
56
+ * initialPageParam: 0,
57
+ * getNextPageParam: (lastPage) => lastPage.nextCursor,
58
+ * }))
59
+ * // query.data()?.pages — array of pages
60
+ * // h('button', { onClick: () => query.fetchNextPage() }, 'Load more')
61
+ */
62
+ declare function useInfiniteQuery<TQueryFnData = unknown, TError = DefaultError, TQueryKey extends QueryKey$1 = QueryKey$1, TPageParam = unknown>(options: () => InfiniteQueryObserverOptions<TQueryFnData, TError, InfiniteData<TQueryFnData>, TQueryKey, TPageParam>): UseInfiniteQueryResult<TQueryFnData, TError>;
144
63
  //#endregion
145
- //#region src/use-mutation.ts
64
+ //#region src/use-is-fetching.d.ts
146
65
  /**
147
- * Run a mutation (create / update / delete). Returns reactive signals for
148
- * pending / success / error state plus `mutate` and `mutateAsync` functions.
149
- *
150
- * @example
151
- * const mutation = useMutation({
152
- * mutationFn: (data: CreatePostInput) =>
153
- * fetch('/api/posts', { method: 'POST', body: JSON.stringify(data) }).then(r => r.json()),
154
- * onSuccess: () => client.invalidateQueries({ queryKey: ['posts'] }),
155
- * })
156
- * // h('button', { onClick: () => mutation.mutate({ title: 'New' }) }, 'Create')
157
- */
158
- function useMutation(options) {
159
- const observer = new MutationObserver(useQueryClient(), options);
160
- const initial = observer.getCurrentResult();
161
- const resultSig = signal(initial);
162
- const dataSig = signal(initial.data);
163
- const errorSig = signal(initial.error ?? null);
164
- const statusSig = signal(initial.status);
165
- const isPending = signal(initial.isPending);
166
- const isSuccess = signal(initial.isSuccess);
167
- const isError = signal(initial.isError);
168
- const isIdle = signal(initial.isIdle);
169
- const unsub = observer.subscribe(r => {
170
- batch(() => {
171
- resultSig.set(r);
172
- dataSig.set(r.data);
173
- errorSig.set(r.error ?? null);
174
- statusSig.set(r.status);
175
- isPending.set(r.isPending);
176
- isSuccess.set(r.isSuccess);
177
- isError.set(r.isError);
178
- isIdle.set(r.isIdle);
179
- });
180
- });
181
- onUnmount(() => unsub());
182
- return {
183
- result: resultSig,
184
- data: dataSig,
185
- error: errorSig,
186
- status: statusSig,
187
- isPending,
188
- isSuccess,
189
- isError,
190
- isIdle,
191
- mutate: (vars, callbackOptions) => {
192
- observer.mutate(vars, callbackOptions).catch(() => {});
193
- },
194
- mutateAsync: (vars, callbackOptions) => observer.mutate(vars, callbackOptions),
195
- reset: () => observer.reset()
196
- };
197
- }
198
-
199
- //#endregion
200
- //#region src/use-queries.ts
66
+ * Returns a signal that tracks how many queries are currently in-flight.
67
+ * Useful for global loading indicators.
68
+ *
69
+ * @example
70
+ * const fetching = useIsFetching()
71
+ * // h('span', null, () => fetching() > 0 ? 'Loading…' : '')
72
+ */
73
+ declare function useIsFetching(filters?: QueryFilters$1): Signal<number>;
201
74
  /**
202
- * Subscribe to multiple queries in parallel. Returns a single signal containing
203
- * the array of results — index-aligned with the `queries` array.
204
- *
205
- * `queries` is a reactive function so signal-based keys trigger re-evaluation
206
- * automatically.
207
- *
208
- * @example
209
- * const userIds = signal([1, 2, 3])
210
- * const results = useQueries(() =>
211
- * userIds().map(id => ({
212
- * queryKey: ['user', id],
213
- * queryFn: () => fetchUser(id),
214
- * }))
215
- * )
216
- * // results() — QueryObserverResult[]
217
- * // results()[0].data — first user
218
- */
219
- function useQueries(queries) {
220
- const observer = new QueriesObserver(useQueryClient(), queries());
221
- const resultSig = signal(observer.getCurrentResult());
222
- const unsub = observer.subscribe(results => {
223
- resultSig.set(results);
224
- });
225
- effect(() => {
226
- observer.setQueries(queries());
227
- });
228
- onUnmount(() => {
229
- unsub();
230
- observer.destroy();
231
- });
232
- return resultSig;
233
- }
234
-
75
+ * Returns a signal that tracks how many mutations are currently in-flight.
76
+ *
77
+ * @example
78
+ * const mutating = useIsMutating()
79
+ * // h('span', null, () => mutating() > 0 ? 'Saving…' : '')
80
+ */
81
+ declare function useIsMutating(filters?: MutationFilters$1): Signal<number>;
235
82
  //#endregion
236
- //#region src/use-query.ts
237
- /**
238
- * Subscribe to a query. Returns fine-grained reactive signals for data,
239
- * error and status — each signal only notifies effects that depend on it.
240
- *
241
- * `options` is a function so it can read Pyreon signals — when a signal changes
242
- * (e.g. a reactive query key), the observer is updated and refetches automatically.
243
- *
244
- * @example
245
- * const userId = signal(1)
246
- * const query = useQuery(() => ({
247
- * queryKey: ['user', userId()],
248
- * queryFn: () => fetch(`/api/users/${userId()}`).then(r => r.json()),
249
- * }))
250
- * // In template: () => query.data()?.name
251
- */
252
- function useQuery(options) {
253
- const observer = new QueryObserver(useQueryClient(), options());
254
- const initial = observer.getCurrentResult();
255
- const resultSig = signal(initial);
256
- const dataSig = signal(initial.data);
257
- const errorSig = signal(initial.error ?? null);
258
- const statusSig = signal(initial.status);
259
- const isPending = signal(initial.isPending);
260
- const isLoading = signal(initial.isLoading);
261
- const isFetching = signal(initial.isFetching);
262
- const isError = signal(initial.isError);
263
- const isSuccess = signal(initial.isSuccess);
264
- const unsub = observer.subscribe(r => {
265
- batch(() => {
266
- resultSig.set(r);
267
- dataSig.set(r.data);
268
- errorSig.set(r.error ?? null);
269
- statusSig.set(r.status);
270
- isPending.set(r.isPending);
271
- isLoading.set(r.isLoading);
272
- isFetching.set(r.isFetching);
273
- isError.set(r.isError);
274
- isSuccess.set(r.isSuccess);
275
- });
276
- });
277
- effect(() => {
278
- observer.setOptions(options());
279
- });
280
- onUnmount(() => unsub());
281
- return {
282
- result: resultSig,
283
- data: dataSig,
284
- error: errorSig,
285
- status: statusSig,
286
- isPending,
287
- isLoading,
288
- isFetching,
289
- isError,
290
- isSuccess,
291
- refetch: () => observer.refetch()
292
- };
83
+ //#region src/use-mutation.d.ts
84
+ interface UseMutationResult<TData, TError = DefaultError, TVariables = void, TContext = unknown> {
85
+ /** Raw signal full observer result. Fine-grained accessors below are preferred. */
86
+ result: Signal<MutationObserverResult<TData, TError, TVariables, TContext>>;
87
+ data: Signal<TData | undefined>;
88
+ error: Signal<TError | null>;
89
+ status: Signal<'idle' | 'pending' | 'success' | 'error'>;
90
+ isPending: Signal<boolean>;
91
+ isSuccess: Signal<boolean>;
92
+ isError: Signal<boolean>;
93
+ isIdle: Signal<boolean>;
94
+ /** Fire the mutation (fire-and-forget). Errors are captured in the error signal. */
95
+ mutate: (variables: TVariables, options?: Parameters<MutateFunction<TData, TError, TVariables, TContext>>[1]) => void;
96
+ /** Like mutate but returns a promise — use for try/catch error handling. */
97
+ mutateAsync: MutateFunction<TData, TError, TVariables, TContext>;
98
+ /** Reset the mutation state back to idle. */
99
+ reset: () => void;
293
100
  }
294
-
101
+ /**
102
+ * Run a mutation (create / update / delete). Returns reactive signals for
103
+ * pending / success / error state plus `mutate` and `mutateAsync` functions.
104
+ *
105
+ * @example
106
+ * const mutation = useMutation({
107
+ * mutationFn: (data: CreatePostInput) =>
108
+ * fetch('/api/posts', { method: 'POST', body: JSON.stringify(data) }).then(r => r.json()),
109
+ * onSuccess: () => client.invalidateQueries({ queryKey: ['posts'] }),
110
+ * })
111
+ * // h('button', { onClick: () => mutation.mutate({ title: 'New' }) }, 'Create')
112
+ */
113
+ declare function useMutation<TData = unknown, TError = DefaultError, TVariables = void, TContext = unknown>(options: MutationObserverOptions<TData, TError, TVariables, TContext>): UseMutationResult<TData, TError, TVariables, TContext>;
295
114
  //#endregion
296
- //#region src/use-query-error-reset-boundary.ts
297
-
115
+ //#region src/use-queries.d.ts
116
+ type UseQueriesOptions<TQueryKey extends QueryKey$1 = QueryKey$1> = QueryObserverOptions<unknown, DefaultError, unknown, unknown, TQueryKey>;
298
117
  /**
299
- * Wraps a subtree so that `useQueryErrorResetBoundary()` descendants can reset
300
- * all errored queries within this boundary.
301
- *
302
- * Pair with Pyreon's `ErrorBoundary` to retry failed queries when the user
303
- * dismisses the error fallback:
304
- *
305
- * @example
306
- * h(QueryErrorResetBoundary, null,
307
- * h(ErrorBoundary, {
308
- * fallback: (err, boundaryReset) => {
309
- * const { reset } = useQueryErrorResetBoundary()
310
- * return h('button', {
311
- * onClick: () => { reset(); boundaryReset() },
312
- * }, 'Retry')
313
- * },
314
- * }, h(MyComponent, null)),
315
- * )
316
- */
317
- function QueryErrorResetBoundary(props) {
318
- const client = useQueryClient();
319
- provide(QueryErrorResetBoundaryContext, {
320
- reset: () => {
321
- client.refetchQueries({
322
- predicate: query => query.state.status === "error"
323
- });
324
- }
325
- });
326
- const ch = props.children;
327
- return typeof ch === "function" ? ch() : ch;
118
+ * Subscribe to multiple queries in parallel. Returns a single signal containing
119
+ * the array of results index-aligned with the `queries` array.
120
+ *
121
+ * `queries` is a reactive function so signal-based keys trigger re-evaluation
122
+ * automatically.
123
+ *
124
+ * @example
125
+ * const userIds = signal([1, 2, 3])
126
+ * const results = useQueries(() =>
127
+ * userIds().map(id => ({
128
+ * queryKey: ['user', id],
129
+ * queryFn: () => fetchUser(id),
130
+ * }))
131
+ * )
132
+ * // results() — QueryObserverResult[]
133
+ * // results()[0].data — first user
134
+ */
135
+ declare function useQueries(queries: () => UseQueriesOptions[]): Signal<QueryObserverResult[]>;
136
+ //#endregion
137
+ //#region src/use-query.d.ts
138
+ interface UseQueryResult<TData, TError = DefaultError> {
139
+ /** Raw signal — the full observer result. Fine-grained accessors below are preferred. */
140
+ result: Signal<QueryObserverResult<TData, TError>>;
141
+ data: Signal<TData | undefined>;
142
+ error: Signal<TError | null>;
143
+ status: Signal<'pending' | 'error' | 'success'>;
144
+ isPending: Signal<boolean>;
145
+ isLoading: Signal<boolean>;
146
+ isFetching: Signal<boolean>;
147
+ isError: Signal<boolean>;
148
+ isSuccess: Signal<boolean>;
149
+ /** Manually trigger a refetch. */
150
+ refetch: () => Promise<QueryObserverResult<TData, TError>>;
328
151
  }
329
152
  /**
330
- * Returns the `reset` function provided by the nearest `QueryErrorResetBoundary`.
331
- * If called outside a boundary, falls back to resetting all errored queries
332
- * on the current `QueryClient`.
333
- *
334
- * @example
335
- * // Inside an ErrorBoundary fallback:
336
- * const { reset } = useQueryErrorResetBoundary()
337
- * h('button', { onClick: () => { reset(); boundaryReset() } }, 'Retry')
338
- */
339
- function useQueryErrorResetBoundary() {
340
- const boundary = useContext(QueryErrorResetBoundaryContext);
341
- const client = useQueryClient();
342
- if (boundary) return boundary;
343
- return {
344
- reset: () => {
345
- client.refetchQueries({
346
- predicate: query => query.state.status === "error"
347
- });
348
- }
349
- };
350
- }
351
-
153
+ * Subscribe to a query. Returns fine-grained reactive signals for data,
154
+ * error and status each signal only notifies effects that depend on it.
155
+ *
156
+ * `options` is a function so it can read Pyreon signals — when a signal changes
157
+ * (e.g. a reactive query key), the observer is updated and refetches automatically.
158
+ *
159
+ * @example
160
+ * const userId = signal(1)
161
+ * const query = useQuery(() => ({
162
+ * queryKey: ['user', userId()],
163
+ * queryFn: () => fetch(`/api/users/${userId()}`).then(r => r.json()),
164
+ * }))
165
+ * // In template: () => query.data()?.name
166
+ */
167
+ declare function useQuery<TData = unknown, TError = DefaultError, TKey extends QueryKey$1 = QueryKey$1>(options: () => QueryObserverOptions<TData, TError, TData, TData, TKey>): UseQueryResult<TData, TError>;
352
168
  //#endregion
353
- //#region src/use-subscription.ts
169
+ //#region src/use-query-error-reset-boundary.d.ts
170
+ interface ErrorResetBoundaryValue {
171
+ reset: () => void;
172
+ }
173
+ interface QueryErrorResetBoundaryProps extends Props {
174
+ children?: VNodeChild;
175
+ }
176
+ /**
177
+ * Wraps a subtree so that `useQueryErrorResetBoundary()` descendants can reset
178
+ * all errored queries within this boundary.
179
+ *
180
+ * Pair with Pyreon's `ErrorBoundary` to retry failed queries when the user
181
+ * dismisses the error fallback:
182
+ *
183
+ * @example
184
+ * h(QueryErrorResetBoundary, null,
185
+ * h(ErrorBoundary, {
186
+ * fallback: (err, boundaryReset) => {
187
+ * const { reset } = useQueryErrorResetBoundary()
188
+ * return h('button', {
189
+ * onClick: () => { reset(); boundaryReset() },
190
+ * }, 'Retry')
191
+ * },
192
+ * }, h(MyComponent, null)),
193
+ * )
194
+ */
195
+ declare function QueryErrorResetBoundary(props: QueryErrorResetBoundaryProps): VNode;
354
196
  /**
355
- * Reactive WebSocket subscription that integrates with TanStack Query.
356
- * Automatically manages connection lifecycle, reconnection, and cleanup.
357
- *
358
- * Use the `onMessage` callback to invalidate or update query cache
359
- * when the server pushes data.
360
- *
361
- * @example
362
- * ```ts
363
- * const sub = useSubscription({
364
- * url: 'wss://api.example.com/ws',
365
- * onMessage: (event, queryClient) => {
366
- * const data = JSON.parse(event.data)
367
- * if (data.type === 'order-updated') {
368
- * queryClient.invalidateQueries({ queryKey: ['orders'] })
369
- * }
370
- * },
371
- * })
372
- * // sub.status() — 'connecting' | 'connected' | 'disconnected' | 'error'
373
- * // sub.send(JSON.stringify({ type: 'subscribe', channel: 'orders' }))
374
- * ```
375
- */
376
- function useSubscription(options) {
377
- const queryClient = useQueryClient();
378
- const status = signal("disconnected");
379
- let ws = null;
380
- let reconnectAttempts = 0;
381
- let reconnectTimer = null;
382
- let intentionalClose = false;
383
- const reconnectEnabled = options.reconnect !== false;
384
- const baseDelay = options.reconnectDelay ?? 1e3;
385
- const maxAttempts = options.maxReconnectAttempts ?? 10;
386
- function getUrl() {
387
- return typeof options.url === "function" ? options.url() : options.url;
388
- }
389
- function isEnabled() {
390
- if (options.enabled === void 0) return true;
391
- return typeof options.enabled === "function" ? options.enabled() : options.enabled;
392
- }
393
- function connect() {
394
- if (ws) {
395
- ws.onopen = null;
396
- ws.onmessage = null;
397
- ws.onclose = null;
398
- ws.onerror = null;
399
- if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) ws.close();
400
- }
401
- if (!isEnabled()) {
402
- status.set("disconnected");
403
- return;
404
- }
405
- status.set("connecting");
406
- try {
407
- ws = options.protocols ? new WebSocket(getUrl(), options.protocols) : new WebSocket(getUrl());
408
- } catch {
409
- status.set("error");
410
- scheduleReconnect();
411
- return;
412
- }
413
- ws.onopen = event => {
414
- batch(() => {
415
- status.set("connected");
416
- reconnectAttempts = 0;
417
- });
418
- options.onOpen?.(event);
419
- };
420
- ws.onmessage = event => {
421
- options.onMessage(event, queryClient);
422
- };
423
- ws.onclose = event => {
424
- status.set("disconnected");
425
- options.onClose?.(event);
426
- if (!intentionalClose && reconnectEnabled) scheduleReconnect();
427
- };
428
- ws.onerror = event => {
429
- status.set("error");
430
- options.onError?.(event);
431
- };
432
- }
433
- function scheduleReconnect() {
434
- if (!reconnectEnabled) return;
435
- if (maxAttempts > 0 && reconnectAttempts >= maxAttempts) return;
436
- const delay = baseDelay * 2 ** reconnectAttempts;
437
- reconnectAttempts++;
438
- reconnectTimer = setTimeout(() => {
439
- reconnectTimer = null;
440
- if (!intentionalClose && isEnabled()) connect();
441
- }, delay);
442
- }
443
- function send(data) {
444
- if (ws?.readyState === WebSocket.OPEN) ws.send(data);
445
- }
446
- function close() {
447
- intentionalClose = true;
448
- if (reconnectTimer !== null) {
449
- clearTimeout(reconnectTimer);
450
- reconnectTimer = null;
451
- }
452
- if (ws) {
453
- ws.onopen = null;
454
- ws.onmessage = null;
455
- ws.onclose = null;
456
- ws.onerror = null;
457
- if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) ws.close();
458
- ws = null;
459
- }
460
- status.set("disconnected");
461
- }
462
- function manualReconnect() {
463
- intentionalClose = false;
464
- reconnectAttempts = 0;
465
- connect();
466
- }
467
- effect(() => {
468
- if (typeof options.url === "function") options.url();
469
- if (typeof options.enabled === "function") options.enabled();
470
- intentionalClose = false;
471
- reconnectAttempts = 0;
472
- connect();
473
- });
474
- onUnmount(() => close());
475
- return {
476
- status,
477
- send,
478
- close,
479
- reconnect: manualReconnect
480
- };
197
+ * Returns the `reset` function provided by the nearest `QueryErrorResetBoundary`.
198
+ * If called outside a boundary, falls back to resetting all errored queries
199
+ * on the current `QueryClient`.
200
+ *
201
+ * @example
202
+ * // Inside an ErrorBoundary fallback:
203
+ * const { reset } = useQueryErrorResetBoundary()
204
+ * h('button', { onClick: () => { reset(); boundaryReset() } }, 'Retry')
205
+ */
206
+ declare function useQueryErrorResetBoundary(): ErrorResetBoundaryValue;
207
+ //#endregion
208
+ //#region src/use-subscription.d.ts
209
+ type SubscriptionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
210
+ interface UseSubscriptionOptions {
211
+ /** WebSocket URL — can be a signal for reactive URLs */
212
+ url: string | (() => string);
213
+ /** WebSocket sub-protocols */
214
+ protocols?: string | string[];
215
+ /** Called when a message is received — use queryClient to invalidate or update cache */
216
+ onMessage: (event: MessageEvent, queryClient: QueryClient$1) => void;
217
+ /** Called when the connection opens */
218
+ onOpen?: (event: Event) => void;
219
+ /** Called when the connection closes */
220
+ onClose?: (event: CloseEvent) => void;
221
+ /** Called when a connection error occurs */
222
+ onError?: (event: Event) => void;
223
+ /** Whether to automatically reconnect — default: true */
224
+ reconnect?: boolean;
225
+ /** Initial reconnect delay in ms — doubles on each retry, default: 1000 */
226
+ reconnectDelay?: number;
227
+ /** Maximum reconnect attempts default: 10, 0 = unlimited */
228
+ maxReconnectAttempts?: number;
229
+ /** Whether the subscription is enabled default: true */
230
+ enabled?: boolean | (() => boolean);
481
231
  }
482
-
232
+ interface UseSubscriptionResult {
233
+ /** Current connection status */
234
+ status: Signal<SubscriptionStatus>;
235
+ /** Send data through the WebSocket */
236
+ send: (data: string | ArrayBufferLike | Blob | ArrayBufferView) => void;
237
+ /** Manually close the connection */
238
+ close: () => void;
239
+ /** Manually reconnect */
240
+ reconnect: () => void;
241
+ }
242
+ /**
243
+ * Reactive WebSocket subscription that integrates with TanStack Query.
244
+ * Automatically manages connection lifecycle, reconnection, and cleanup.
245
+ *
246
+ * Use the `onMessage` callback to invalidate or update query cache
247
+ * when the server pushes data.
248
+ *
249
+ * @example
250
+ * ```ts
251
+ * const sub = useSubscription({
252
+ * url: 'wss://api.example.com/ws',
253
+ * onMessage: (event, queryClient) => {
254
+ * const data = JSON.parse(event.data)
255
+ * if (data.type === 'order-updated') {
256
+ * queryClient.invalidateQueries({ queryKey: ['orders'] })
257
+ * }
258
+ * },
259
+ * })
260
+ * // sub.status() — 'connecting' | 'connected' | 'disconnected' | 'error'
261
+ * // sub.send(JSON.stringify({ type: 'subscribe', channel: 'orders' }))
262
+ * ```
263
+ */
264
+ declare function useSubscription(options: UseSubscriptionOptions): UseSubscriptionResult;
483
265
  //#endregion
484
- //#region src/use-suspense-query.ts
266
+ //#region src/use-suspense-query.d.ts
485
267
  /**
486
- * Pyreon-native Suspense boundary for queries. Shows `fallback` while any query
487
- * is pending. On error, renders the `error` fallback or re-throws to the
488
- * nearest Pyreon `ErrorBoundary`.
489
- *
490
- * Pair with `useSuspenseQuery` / `useSuspenseInfiniteQuery` to get non-undefined
491
- * `data` types inside children.
492
- *
493
- * @example
494
- * const userQuery = useSuspenseQuery(() => ({ queryKey: ['user'], queryFn: fetchUser }))
495
- *
496
- * h(QuerySuspense, {
497
- * query: userQuery,
498
- * fallback: h(Spinner, null),
499
- * error: (err) => h('p', null, `Failed: ${err}`),
500
- * }, () => h(UserProfile, { user: userQuery.data() }))
501
- */
502
- function QuerySuspense(props) {
503
- return () => {
504
- const queries = Array.isArray(props.query) ? props.query : [props.query];
505
- for (const q of queries) if (q.isError()) {
506
- const err = q.error();
507
- if (props.error) return props.error(err);
508
- throw err;
509
- }
510
- if (queries.some(q => q.isPending())) {
511
- const fb = props.fallback;
512
- return typeof fb === "function" ? fb() : fb ?? null;
513
- }
514
- const ch = props.children;
515
- return typeof ch === "function" ? ch() : ch;
516
- };
268
+ * Like `UseQueryResult` but `data` is `Signal<TData>` (never undefined).
269
+ * Only use inside a `QuerySuspense` boundary which guarantees the query has
270
+ * succeeded before children are rendered.
271
+ */
272
+ interface UseSuspenseQueryResult<TData, TError = DefaultError> {
273
+ result: Signal<QueryObserverResult<TData, TError>>;
274
+ /** Always TData — never undefined inside a QuerySuspense boundary. */
275
+ data: Signal<TData>;
276
+ error: Signal<TError | null>;
277
+ status: Signal<'pending' | 'error' | 'success'>;
278
+ isPending: Signal<boolean>;
279
+ isFetching: Signal<boolean>;
280
+ isError: Signal<boolean>;
281
+ isSuccess: Signal<boolean>;
282
+ refetch: () => Promise<QueryObserverResult<TData, TError>>;
517
283
  }
518
- /**
519
- * Like `useQuery` but `data` is typed as `Signal<TData>` (never undefined).
520
- * Designed for use inside a `QuerySuspense` boundary, which guarantees
521
- * children only render after the query succeeds.
522
- *
523
- * @example
524
- * const user = useSuspenseQuery(() => ({ queryKey: ['user', id()], queryFn: fetchUser }))
525
- *
526
- * h(QuerySuspense, { query: user, fallback: h(Spinner, null) },
527
- * () => h(UserCard, { name: user.data().name }),
528
- * )
529
- */
530
- function useSuspenseQuery(options) {
531
- const observer = new QueryObserver(useQueryClient(), options());
532
- const initial = observer.getCurrentResult();
533
- const resultSig = signal(initial);
534
- const dataSig = signal(initial.data);
535
- const errorSig = signal(initial.error ?? null);
536
- const statusSig = signal(initial.status);
537
- const isPending = signal(initial.isPending);
538
- const isFetching = signal(initial.isFetching);
539
- const isError = signal(initial.isError);
540
- const isSuccess = signal(initial.isSuccess);
541
- const unsub = observer.subscribe(r => {
542
- batch(() => {
543
- resultSig.set(r);
544
- if (r.data !== void 0) dataSig.set(r.data);
545
- errorSig.set(r.error ?? null);
546
- statusSig.set(r.status);
547
- isPending.set(r.isPending);
548
- isFetching.set(r.isFetching);
549
- isError.set(r.isError);
550
- isSuccess.set(r.isSuccess);
551
- });
552
- });
553
- effect(() => {
554
- observer.setOptions(options());
555
- });
556
- onUnmount(() => unsub());
557
- return {
558
- result: resultSig,
559
- data: dataSig,
560
- error: errorSig,
561
- status: statusSig,
562
- isPending,
563
- isFetching,
564
- isError,
565
- isSuccess,
566
- refetch: () => observer.refetch()
567
- };
284
+ interface UseSuspenseInfiniteQueryResult<TQueryFnData, TError = DefaultError> {
285
+ result: Signal<InfiniteQueryObserverResult<InfiniteData<TQueryFnData>, TError>>;
286
+ /** Always InfiniteData<TQueryFnData> never undefined inside a QuerySuspense boundary. */
287
+ data: Signal<InfiniteData<TQueryFnData>>;
288
+ error: Signal<TError | null>;
289
+ status: Signal<'pending' | 'error' | 'success'>;
290
+ isFetching: Signal<boolean>;
291
+ isFetchingNextPage: Signal<boolean>;
292
+ isFetchingPreviousPage: Signal<boolean>;
293
+ isError: Signal<boolean>;
294
+ isSuccess: Signal<boolean>;
295
+ hasNextPage: Signal<boolean>;
296
+ hasPreviousPage: Signal<boolean>;
297
+ fetchNextPage: () => Promise<InfiniteQueryObserverResult<InfiniteData<TQueryFnData>, TError>>;
298
+ fetchPreviousPage: () => Promise<InfiniteQueryObserverResult<InfiniteData<TQueryFnData>, TError>>;
299
+ refetch: () => Promise<QueryObserverResult<InfiniteData<TQueryFnData>, TError>>;
568
300
  }
569
- /**
570
- * Like `useInfiniteQuery` but `data` is typed as `Signal<InfiniteData<TData>>`
571
- * (never undefined). Use inside a `QuerySuspense` boundary.
572
- */
573
- function useSuspenseInfiniteQuery(options) {
574
- const observer = new InfiniteQueryObserver(useQueryClient(), options());
575
- const initial = observer.getCurrentResult();
576
- const resultSig = signal(initial);
577
- const dataSig = signal(initial.data);
578
- const errorSig = signal(initial.error ?? null);
579
- const statusSig = signal(initial.status);
580
- const isFetching = signal(initial.isFetching);
581
- const isFetchingNextPage = signal(initial.isFetchingNextPage);
582
- const isFetchingPreviousPage = signal(initial.isFetchingPreviousPage);
583
- const isError = signal(initial.isError);
584
- const isSuccess = signal(initial.isSuccess);
585
- const hasNextPage = signal(initial.hasNextPage);
586
- const hasPreviousPage = signal(initial.hasPreviousPage);
587
- const unsub = observer.subscribe(r => {
588
- batch(() => {
589
- resultSig.set(r);
590
- if (r.data !== void 0) dataSig.set(r.data);
591
- errorSig.set(r.error ?? null);
592
- statusSig.set(r.status);
593
- isFetching.set(r.isFetching);
594
- isFetchingNextPage.set(r.isFetchingNextPage);
595
- isFetchingPreviousPage.set(r.isFetchingPreviousPage);
596
- isError.set(r.isError);
597
- isSuccess.set(r.isSuccess);
598
- hasNextPage.set(r.hasNextPage);
599
- hasPreviousPage.set(r.hasPreviousPage);
600
- });
601
- });
602
- effect(() => {
603
- observer.setOptions(options());
604
- });
605
- onUnmount(() => unsub());
606
- return {
607
- result: resultSig,
608
- data: dataSig,
609
- error: errorSig,
610
- status: statusSig,
611
- isFetching,
612
- isFetchingNextPage,
613
- isFetchingPreviousPage,
614
- isError,
615
- isSuccess,
616
- hasNextPage,
617
- hasPreviousPage,
618
- fetchNextPage: () => observer.fetchNextPage(),
619
- fetchPreviousPage: () => observer.fetchPreviousPage(),
620
- refetch: () => observer.refetch()
621
- };
301
+ type AnyQueryLike = {
302
+ isPending: Signal<boolean>;
303
+ isError: Signal<boolean>;
304
+ error: Signal<unknown>;
305
+ };
306
+ interface QuerySuspenseProps {
307
+ /**
308
+ * A single query result (or array of them) to gate on.
309
+ * Children only render when ALL queries have succeeded.
310
+ */
311
+ query: AnyQueryLike | AnyQueryLike[];
312
+ /** Rendered while any query is pending. */
313
+ fallback?: VNodeChild;
314
+ /** Rendered when any query has errored. Defaults to re-throwing to nearest ErrorBoundary. */
315
+ error?: (err: unknown) => VNodeChild;
316
+ children: VNodeChild;
622
317
  }
623
-
318
+ /**
319
+ * Pyreon-native Suspense boundary for queries. Shows `fallback` while any query
320
+ * is pending. On error, renders the `error` fallback or re-throws to the
321
+ * nearest Pyreon `ErrorBoundary`.
322
+ *
323
+ * Pair with `useSuspenseQuery` / `useSuspenseInfiniteQuery` to get non-undefined
324
+ * `data` types inside children.
325
+ *
326
+ * @example
327
+ * const userQuery = useSuspenseQuery(() => ({ queryKey: ['user'], queryFn: fetchUser }))
328
+ *
329
+ * h(QuerySuspense, {
330
+ * query: userQuery,
331
+ * fallback: h(Spinner, null),
332
+ * error: (err) => h('p', null, `Failed: ${err}`),
333
+ * }, () => h(UserProfile, { user: userQuery.data() }))
334
+ */
335
+ declare function QuerySuspense(props: QuerySuspenseProps): VNodeChild;
336
+ /**
337
+ * Like `useQuery` but `data` is typed as `Signal<TData>` (never undefined).
338
+ * Designed for use inside a `QuerySuspense` boundary, which guarantees
339
+ * children only render after the query succeeds.
340
+ *
341
+ * @example
342
+ * const user = useSuspenseQuery(() => ({ queryKey: ['user', id()], queryFn: fetchUser }))
343
+ *
344
+ * h(QuerySuspense, { query: user, fallback: h(Spinner, null) },
345
+ * () => h(UserCard, { name: user.data().name }),
346
+ * )
347
+ */
348
+ declare function useSuspenseQuery<TData = unknown, TError = DefaultError, TKey extends QueryKey$1 = QueryKey$1>(options: () => QueryObserverOptions<TData, TError, TData, TData, TKey>): UseSuspenseQueryResult<TData, TError>;
349
+ /**
350
+ * Like `useInfiniteQuery` but `data` is typed as `Signal<InfiniteData<TData>>`
351
+ * (never undefined). Use inside a `QuerySuspense` boundary.
352
+ */
353
+ declare function useSuspenseInfiniteQuery<TQueryFnData = unknown, TError = DefaultError, TQueryKey extends QueryKey$1 = QueryKey$1, TPageParam = unknown>(options: () => InfiniteQueryObserverOptions<TQueryFnData, TError, InfiniteData<TQueryFnData>, TQueryKey, TPageParam>): UseSuspenseInfiniteQueryResult<TQueryFnData, TError>;
624
354
  //#endregion
625
- export { CancelledError, MutationCache, QueryCache, QueryClient, QueryClientContext, QueryClientProvider, QueryErrorResetBoundary, QuerySuspense, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, hashKey, hydrate, isCancelledError, keepPreviousData, useInfiniteQuery, useIsFetching, useIsMutating, useMutation, useQueries, useQuery, useQueryClient, useQueryErrorResetBoundary, useSubscription, useSuspenseInfiniteQuery, useSuspenseQuery };
626
- //# sourceMappingURL=index.d.ts.map
355
+ export { CancelledError, type DehydratedState, type FetchQueryOptions, type InvalidateOptions, type InvalidateQueryFilters, MutationCache, type MutationFilters, QueryCache, QueryClient, type QueryClientConfig, QueryClientContext, QueryClientProvider, type QueryClientProviderProps, QueryErrorResetBoundary, type QueryErrorResetBoundaryProps, type QueryFilters, type QueryKey, QuerySuspense, type QuerySuspenseProps, type RefetchOptions, type RefetchQueryFilters, type SubscriptionStatus, type UseInfiniteQueryResult, type UseMutationResult, type UseQueriesOptions, type UseQueryResult, type UseSubscriptionOptions, type UseSubscriptionResult, type UseSuspenseInfiniteQueryResult, type UseSuspenseQueryResult, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, hashKey, hydrate, isCancelledError, keepPreviousData, useInfiniteQuery, useIsFetching, useIsMutating, useMutation, useQueries, useQuery, useQueryClient, useQueryErrorResetBoundary, useSubscription, useSuspenseInfiniteQuery, useSuspenseQuery };
356
+ //# sourceMappingURL=index2.d.ts.map