@orpc/tanstack-query 2.0.0-beta.49 → 2.0.0-beta.50

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,59 +1,54 @@
1
- import type { AnyNestedClient, Client, InferClientContext, InferClientError } from '@orpc/client';
2
- import type { Public } from '@orpc/shared';
3
- import type { OperationKeyBaseOptions } from './key.ts';
4
- import type { RouterUtilsPlugin } from './plugin.ts';
5
- import type { ProcedureUtilsInfiniteInterceptor, ProcedureUtilsLiveInterceptor, ProcedureUtilsMutationInterceptor, ProcedureUtilsOptions, ProcedureUtilsQueryInterceptor, ProcedureUtilsStreamedInterceptor } from './procedure-utils.ts';
6
- import { ProcedureUtils } from './procedure-utils.ts';
7
- import { SharedUtils } from './shared-utils.ts';
1
+ import { OperationKeyBaseOptions } from "./key.js";
2
+ import { RouterUtilsPlugin } from "./plugin.js";
3
+ import { ProcedureUtils, ProcedureUtilsInfiniteInterceptor, ProcedureUtilsLiveInterceptor, ProcedureUtilsMutationInterceptor, ProcedureUtilsOptions, ProcedureUtilsQueryInterceptor, ProcedureUtilsStreamedInterceptor } from "./procedure-utils.js";
4
+ import { SharedUtils } from "./shared-utils.js";
5
+ import { Public } from "@orpc/shared";
6
+ import { AnyNestedClient, Client, InferClientContext, InferClientError } from "@orpc/client";
8
7
  /**
9
8
  * The utils shape derived from a client: procedure clients map to procedure
10
9
  * utils, and routers map recursively to nested utils.
11
10
  *
12
11
  * @see {@link https://orpc.dev/docs/integrations/tanstack-query | TanStack Query Integration}
13
12
  */
14
- export type RouterUtils<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Public<ProcedureUtils<UClientContext, UInput, UOutput, UError>> : {
15
- [K in keyof T]: T[K] extends AnyNestedClient ? RouterUtils<T[K]> : never;
16
- } & Public<SharedUtils<unknown>>;
17
- export type RouterUtilsScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ProcedureUtilsOptions<UClientContext, UInput, UOutput, UError> : {
18
- [K in keyof T]?: (T[K] extends AnyNestedClient ? RouterUtilsScoped<T[K]> : never) | undefined;
19
- };
13
+ export type RouterUtils<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Public<ProcedureUtils<UClientContext, UInput, UOutput, UError>> : { [K in keyof T]: T[K] extends AnyNestedClient ? RouterUtils<T[K]> : never; } & Public<SharedUtils<unknown>>;
14
+ export type RouterUtilsScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ProcedureUtilsOptions<UClientContext, UInput, UOutput, UError> : { [K in keyof T]?: (T[K] extends AnyNestedClient ? RouterUtilsScoped<T[K]> : never) | undefined; };
20
15
  export interface RouterUtilsOptions<T extends AnyNestedClient> extends OperationKeyBaseOptions {
21
- /**
22
- * Base path for all query keys.
23
- *
24
- * @internal
25
- */
26
- path?: string[] | undefined;
27
- /**
28
- * Interceptors that intercept queryFn inside .queryOptions
29
- */
30
- queryInterceptors?: ProcedureUtilsQueryInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
31
- /**
32
- * Interceptors that intercept queryFn inside .streamedOptions
33
- */
34
- streamedInterceptors?: ProcedureUtilsStreamedInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
35
- /**
36
- * Interceptors that intercept queryFn inside .liveOptions
37
- */
38
- liveInterceptors?: ProcedureUtilsLiveInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
39
- /**
40
- * Interceptors that intercept queryFn inside .infiniteOptions
41
- */
42
- infiniteInterceptors?: ProcedureUtilsInfiniteInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
43
- /**
44
- * Interceptors that intercept mutationFn inside .mutationOptions
45
- */
46
- mutationInterceptors?: ProcedureUtilsMutationInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
47
- /**
48
- * Per-procedure options following the shape of the router.
49
- * Allows fine-grained configuration of individual procedure utils
50
- * without affecting the rest of the router.
51
- */
52
- scoped?: RouterUtilsScoped<T> | undefined;
53
- /**
54
- * Plugins to extend router utils behavior.
55
- */
56
- plugins?: RouterUtilsPlugin<T>[] | undefined;
16
+ /**
17
+ * Base path for all query keys.
18
+ *
19
+ * @internal
20
+ */
21
+ path?: string[] | undefined;
22
+ /**
23
+ * Interceptors that intercept queryFn inside .queryOptions
24
+ */
25
+ queryInterceptors?: ProcedureUtilsQueryInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
26
+ /**
27
+ * Interceptors that intercept queryFn inside .streamedOptions
28
+ */
29
+ streamedInterceptors?: ProcedureUtilsStreamedInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
30
+ /**
31
+ * Interceptors that intercept queryFn inside .liveOptions
32
+ */
33
+ liveInterceptors?: ProcedureUtilsLiveInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
34
+ /**
35
+ * Interceptors that intercept queryFn inside .infiniteOptions
36
+ */
37
+ infiniteInterceptors?: ProcedureUtilsInfiniteInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
38
+ /**
39
+ * Interceptors that intercept mutationFn inside .mutationOptions
40
+ */
41
+ mutationInterceptors?: ProcedureUtilsMutationInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
42
+ /**
43
+ * Per-procedure options following the shape of the router.
44
+ * Allows fine-grained configuration of individual procedure utils
45
+ * without affecting the rest of the router.
46
+ */
47
+ scoped?: RouterUtilsScoped<T> | undefined;
48
+ /**
49
+ * Plugins to extend router utils behavior.
50
+ */
51
+ plugins?: RouterUtilsPlugin<T>[] | undefined;
57
52
  }
58
53
  /**
59
54
  * Creates TanStack Query utils from a client, exposing query/mutation
@@ -64,4 +59,4 @@ export interface RouterUtilsOptions<T extends AnyNestedClient> extends Operation
64
59
  *
65
60
  * @see {@link https://orpc.dev/docs/integrations/tanstack-query | TanStack Query Integration}
66
61
  */
67
- export declare function createRouterUtils<T extends AnyNestedClient>(client: T, options?: NoInfer<RouterUtilsOptions<T>>): RouterUtils<T>;
62
+ export declare function createRouterUtils<T extends AnyNestedClient>(client: T, options?: NoInfer<RouterUtilsOptions<T>>): RouterUtils<T>;
@@ -1,69 +1,54 @@
1
- import { RECURSIVE_CLIENT_UNWRAP_KEYS } from '@orpc/client';
2
- import { bindMethods, isNonPrimitive, pick, toArray } from '@orpc/shared';
3
- import { CompositeRouterUtilsPlugin } from './plugin.js';
4
- import { isProcedureUtilsOptions, mergeProcedureUtilsOptions, ProcedureUtils, } from './procedure-utils.js';
5
- import { SharedUtils } from './shared-utils.js';
1
+ import { CompositeRouterUtilsPlugin } from "./plugin.js";
2
+ import { ProcedureUtils, isProcedureUtilsOptions, mergeProcedureUtilsOptions } from "./procedure-utils.js";
3
+ import { SharedUtils } from "./shared-utils.js";
4
+ import { bindMethods, isNonPrimitive, pick, toArray } from "@orpc/shared";
5
+ import { RECURSIVE_CLIENT_UNWRAP_KEYS } from "@orpc/client";
6
+ // src/router-utils.ts
6
7
  /**
7
- * Creates TanStack Query utils from a client, exposing query/mutation
8
- * option builders for every procedure in the router.
9
- *
10
- * @remarks
11
- * **Note**: Both client-side and server-side clients are supported.
12
- *
13
- * @see {@link https://orpc.dev/docs/integrations/tanstack-query | TanStack Query Integration}
14
- */
15
- export function createRouterUtils(client, options = {}) {
16
- const plugin = new CompositeRouterUtilsPlugin(options.plugins);
17
- options = plugin.init(options);
18
- return createRouterUtilsInternal(client, options, plugin);
8
+ * Creates TanStack Query utils from a client, exposing query/mutation
9
+ * option builders for every procedure in the router.
10
+ *
11
+ * @remarks
12
+ * **Note**: Both client-side and server-side clients are supported.
13
+ *
14
+ * @see {@link https://orpc.dev/docs/integrations/tanstack-query | TanStack Query Integration}
15
+ */
16
+ function createRouterUtils(client, options = {}) {
17
+ const plugin = new CompositeRouterUtilsPlugin(options.plugins);
18
+ options = plugin.init(options);
19
+ return createRouterUtilsInternal(client, options, plugin);
19
20
  }
20
21
  function createRouterUtilsInternal(client, options, plugin) {
21
- const path = toArray(options.path);
22
- const utils = typeof client === 'function' &&
23
- (options.scoped === undefined || isProcedureUtilsOptions(options.scoped))
24
- ? bindMethods(new ProcedureUtils(path, client, plugin.initProcedureOptions(path, mergeProcedureUtilsOptions(pick(options, [
25
- 'prefix',
26
- 'serializer',
27
- 'queryInterceptors',
28
- 'streamedInterceptors',
29
- 'liveInterceptors',
30
- 'infiniteInterceptors',
31
- 'mutationInterceptors',
32
- ]), options.scoped ?? {}))), { unbound: ['call'] })
33
- : bindMethods(new SharedUtils(path, options));
34
- const cache = new Map();
35
- const recursive = new Proxy(utils, {
36
- get(target, prop) {
37
- const value = Reflect.get(target, prop);
38
- if (RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
39
- return value ?? Reflect.get(Object.prototype, prop);
40
- }
41
- const nextClient = Reflect.get(client, prop);
42
- if (typeof prop !== 'string' || !isNonPrimitive(nextClient)) {
43
- return value;
44
- }
45
- let result = cache.get(prop);
46
- if (result === undefined) {
47
- const nextUtils = createRouterUtilsInternal(nextClient, {
48
- ...options,
49
- path: [...path, prop],
50
- scoped: options.scoped?.[prop],
51
- }, plugin);
52
- result =
53
- typeof value !== 'function'
54
- ? nextUtils
55
- : new Proxy(value, {
56
- get(target, prop) {
57
- if (typeof prop !== 'string' || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
58
- return Reflect.get(target, prop);
59
- }
60
- return Reflect.get(nextUtils, prop);
61
- },
62
- });
63
- cache.set(prop, result);
64
- }
65
- return result;
66
- },
67
- });
68
- return recursive;
22
+ const path = toArray(options.path);
23
+ const utils = typeof client === "function" && (options.scoped === void 0 || isProcedureUtilsOptions(options.scoped)) ? bindMethods(new ProcedureUtils(path, client, plugin.initProcedureOptions(path, mergeProcedureUtilsOptions(pick(options, [
24
+ "prefix",
25
+ "serializer",
26
+ "queryInterceptors",
27
+ "streamedInterceptors",
28
+ "liveInterceptors",
29
+ "infiniteInterceptors",
30
+ "mutationInterceptors"
31
+ ]), options.scoped ?? {}))), { unbound: ["call"] }) : bindMethods(new SharedUtils(path, options));
32
+ const cache = /* @__PURE__ */ new Map();
33
+ return new Proxy(utils, { get(target, prop) {
34
+ const value = Reflect.get(target, prop);
35
+ if (RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) return value ?? Reflect.get(Object.prototype, prop);
36
+ const nextClient = Reflect.get(client, prop);
37
+ if (typeof prop !== "string" || !isNonPrimitive(nextClient)) return value;
38
+ let result = cache.get(prop);
39
+ if (result === void 0) {
40
+ const nextUtils = createRouterUtilsInternal(nextClient, {
41
+ ...options,
42
+ path: [...path, prop],
43
+ scoped: options.scoped?.[prop]
44
+ }, plugin);
45
+ result = typeof value !== "function" ? nextUtils : new Proxy(value, { get(target, prop) {
46
+ if (typeof prop !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) return Reflect.get(target, prop);
47
+ return Reflect.get(nextUtils, prop);
48
+ } });
49
+ cache.set(prop, result);
50
+ }
51
+ return result;
52
+ } });
69
53
  }
54
+ export { createRouterUtils };
@@ -1,11 +1,11 @@
1
- import type { OperationKey, OperationKeyBaseOptions, OperationKeyOptions } from './key.ts';
2
- import type { OperationType } from './types.ts';
1
+ import { OperationKey, OperationKeyBaseOptions, OperationKeyOptions } from "./key.js";
2
+ import { OperationType } from "./types.js";
3
3
  export declare class SharedUtils<TInput> {
4
- protected readonly path: string[];
5
- protected readonly options: OperationKeyBaseOptions;
6
- constructor(path: string[], options: OperationKeyBaseOptions);
7
- /**
8
- * Generate a **partial matching** key for actions like revalidating queries, checking mutation status, etc.
9
- */
10
- key<TType extends OperationType>(options?: Omit<OperationKeyOptions<TType, TInput>, keyof OperationKeyBaseOptions>): OperationKey<TType, TInput>;
11
- }
4
+ protected readonly path: string[];
5
+ protected readonly options: OperationKeyBaseOptions;
6
+ constructor(path: string[], options: OperationKeyBaseOptions);
7
+ /**
8
+ * Generate a **partial matching** key for actions like revalidating queries, checking mutation status, etc.
9
+ */
10
+ key<TType extends OperationType>(options?: Omit<OperationKeyOptions<TType, TInput>, keyof OperationKeyBaseOptions>): OperationKey<TType, TInput>;
11
+ }
@@ -1,19 +1,21 @@
1
- import { generateOperationKey } from './key.js';
2
- export class SharedUtils {
3
- path;
4
- options;
5
- constructor(path, options) {
6
- this.path = path;
7
- this.options = options;
8
- }
9
- /**
10
- * Generate a **partial matching** key for actions like revalidating queries, checking mutation status, etc.
11
- */
12
- key(options = {}) {
13
- return generateOperationKey(this.path, {
14
- ...options,
15
- prefix: this.options.prefix,
16
- serializer: this.options.serializer,
17
- });
18
- }
19
- }
1
+ import { generateOperationKey } from "./key.js";
2
+ // src/shared-utils.ts
3
+ var SharedUtils = class {
4
+ path;
5
+ options;
6
+ constructor(path, options) {
7
+ this.path = path;
8
+ this.options = options;
9
+ }
10
+ /**
11
+ * Generate a **partial matching** key for actions like revalidating queries, checking mutation status, etc.
12
+ */
13
+ key(options = {}) {
14
+ return generateOperationKey(this.path, {
15
+ ...options,
16
+ prefix: this.options.prefix,
17
+ serializer: this.options.serializer
18
+ });
19
+ }
20
+ };
21
+ export { SharedUtils };
package/dist/ssr.d.ts CHANGED
@@ -1,27 +1,26 @@
1
- import type { AnyNestedClient, InferClientContext, InferClientError, RPCJsonSerialization } from '@orpc/client';
2
- import { RPCJsonSerializer } from '@orpc/client';
3
- import type { Public } from '@orpc/shared';
4
- import type { RouterUtilsPlugin } from './plugin.ts';
5
- import type { ProcedureUtilsOptions } from './procedure-utils.ts';
1
+ import { RouterUtilsPlugin } from "./plugin.js";
2
+ import { ProcedureUtilsOptions } from "./procedure-utils.js";
3
+ import { Public } from "@orpc/shared";
4
+ import { AnyNestedClient, InferClientContext, InferClientError, RPCJsonSerialization, RPCJsonSerializer } from "@orpc/client";
6
5
  /**
7
6
  * Creates `dehydrate` and `hydrate` query client defaults that preserve oRPC types.
8
7
  *
9
8
  * @see {@link https://orpc.dev/docs/integrations/tanstack-query#custom-serializers | TanStack Query Integration - Custom Serializers}
10
9
  */
11
10
  export declare function createHydrationOptions(serializer?: Public<RPCJsonSerializer>): {
12
- dehydrate: {
13
- serializeData: (data: unknown) => RPCJsonSerialization;
14
- };
15
- hydrate: {
16
- deserializeData: (data: RPCJsonSerialization) => unknown;
17
- };
11
+ dehydrate: {
12
+ serializeData: (data: unknown) => RPCJsonSerialization;
13
+ };
14
+ hydrate: {
15
+ deserializeData: (data: RPCJsonSerialization) => unknown;
16
+ };
18
17
  };
19
18
  export interface StreamQuerySSRUtilsPluginOptions {
20
- /**
21
- * Whether utils run on the server, where streamed and live queries settle at their first data.
22
- * Defaults to TanStack Query's `environmentManager.isServer()`.
23
- */
24
- isServer?: boolean | undefined;
19
+ /**
20
+ * Whether utils run on the server, where streamed and live queries settle at their first data.
21
+ * Defaults to TanStack Query's `environmentManager.isServer()`.
22
+ */
23
+ isServer?: boolean | undefined;
25
24
  }
26
25
  /**
27
26
  * Router utils plugin for SSR of streamed and live queries: sets `.streamedOptions` and `.liveOptions` defaults
@@ -30,8 +29,8 @@ export interface StreamQuerySSRUtilsPluginOptions {
30
29
  * @see {@link https://orpc.dev/docs/integrations/tanstack-query#streamed-and-live-queries | TanStack Query Integration - Streamed and Live Queries}
31
30
  */
32
31
  export declare class StreamQuerySSRUtilsPlugin<T extends AnyNestedClient = AnyNestedClient> implements RouterUtilsPlugin<T> {
33
- private readonly options;
34
- readonly name = "~stream-query-ssr";
35
- constructor(options?: StreamQuerySSRUtilsPluginOptions);
36
- initProcedureOptions(_path: string[], options: ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>): ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>;
37
- }
32
+ private readonly options;
33
+ readonly name = "~stream-query-ssr";
34
+ constructor(options?: StreamQuerySSRUtilsPluginOptions);
35
+ initProcedureOptions(_path: string[], options: ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>): ProcedureUtilsOptions<InferClientContext<T>, any, any, InferClientError<T>>;
36
+ }
package/dist/ssr.js CHANGED
@@ -1,45 +1,47 @@
1
- import { RPCJsonSerializer } from '@orpc/client';
2
- import { environmentManager } from '@tanstack/query-core';
3
- import { mergeProcedureUtilsOptions } from './procedure-utils.js';
1
+ import { mergeProcedureUtilsOptions } from "./procedure-utils.js";
2
+ import { RPCJsonSerializer } from "@orpc/client";
3
+ import { environmentManager } from "@tanstack/query-core";
4
+ // src/ssr.ts
4
5
  /**
5
- * Creates `dehydrate` and `hydrate` query client defaults that preserve oRPC types.
6
- *
7
- * @see {@link https://orpc.dev/docs/integrations/tanstack-query#custom-serializers | TanStack Query Integration - Custom Serializers}
8
- */
9
- export function createHydrationOptions(serializer = new RPCJsonSerializer()) {
10
- return {
11
- dehydrate: {
12
- serializeData(data) {
13
- const { json, meta } = serializer.serializeJson(data);
14
- return { json, meta };
15
- },
16
- },
17
- hydrate: {
18
- deserializeData(data) {
19
- return serializer.deserializeJson(data);
20
- },
21
- },
22
- };
6
+ * Creates `dehydrate` and `hydrate` query client defaults that preserve oRPC types.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/integrations/tanstack-query#custom-serializers | TanStack Query Integration - Custom Serializers}
9
+ */
10
+ function createHydrationOptions(serializer = new RPCJsonSerializer()) {
11
+ return {
12
+ dehydrate: { serializeData(data) {
13
+ const { json, meta } = serializer.serializeJson(data);
14
+ return {
15
+ json,
16
+ meta
17
+ };
18
+ } },
19
+ hydrate: { deserializeData(data) {
20
+ return serializer.deserializeJson(data);
21
+ } }
22
+ };
23
23
  }
24
24
  /**
25
- * Router utils plugin for SSR of streamed and live queries: sets `.streamedOptions` and `.liveOptions` defaults
26
- * so they settle at their first data on the server, and reopen their stream on mount in the browser.
27
- *
28
- * @see {@link https://orpc.dev/docs/integrations/tanstack-query#streamed-and-live-queries | TanStack Query Integration - Streamed and Live Queries}
29
- */
30
- export class StreamQuerySSRUtilsPlugin {
31
- options;
32
- name = '~stream-query-ssr';
33
- constructor(options = {}) {
34
- this.options = options;
35
- }
36
- initProcedureOptions(_path, options) {
37
- // read when utils are built, so `environmentManager.setIsServer` applies even after the plugin is created
38
- const defaults = (this.options.isServer ?? environmentManager.isServer())
39
- ? // the render must finish even with observers (vue, svelte), which must not reopen the settled stream
40
- { settleOnFirstData: true, refetchOnMount: false }
41
- : // hydrated data reopens its stream on mount, despite a `staleTime`
42
- { refetchOnMount: 'always' };
43
- return mergeProcedureUtilsOptions({ streamedOptions: defaults, liveOptions: defaults }, options);
44
- }
45
- }
25
+ * Router utils plugin for SSR of streamed and live queries: sets `.streamedOptions` and `.liveOptions` defaults
26
+ * so they settle at their first data on the server, and reopen their stream on mount in the browser.
27
+ *
28
+ * @see {@link https://orpc.dev/docs/integrations/tanstack-query#streamed-and-live-queries | TanStack Query Integration - Streamed and Live Queries}
29
+ */
30
+ var StreamQuerySSRUtilsPlugin = class {
31
+ options;
32
+ name = "~stream-query-ssr";
33
+ constructor(options = {}) {
34
+ this.options = options;
35
+ }
36
+ initProcedureOptions(_path, options) {
37
+ const defaults = this.options.isServer ?? environmentManager.isServer() ? {
38
+ settleOnFirstData: true,
39
+ refetchOnMount: false
40
+ } : { refetchOnMount: "always" };
41
+ return mergeProcedureUtilsOptions({
42
+ streamedOptions: defaults,
43
+ liveOptions: defaults
44
+ }, options);
45
+ }
46
+ };
47
+ export { StreamQuerySSRUtilsPlugin, createHydrationOptions };
@@ -1,38 +1,32 @@
1
- import type { Promisable } from '@orpc/shared';
2
- import type { QueryFunction, QueryFunctionContext, QueryKey } from '@tanstack/query-core';
1
+ import "@orpc/shared";
2
+ import "@tanstack/query-core";
3
3
  export interface SerializableStreamedQueryOptions {
4
- /**
5
- * What a fetch does with existing data once its stream connects.
6
- * Until then the data stays, so a query with data never returns to `pending`.
7
- *
8
- * - `'reset'`: the data becomes `[]`, then each chunk is appended.
9
- * - `'append'`: the data is kept (trimmed to `maxChunks`), and each chunk is appended.
10
- *
11
- * @default 'reset'
12
- */
13
- refetchMode?: 'append' | 'reset' | undefined;
14
- /**
15
- * Limits the number of data chunks stored in the query result.
16
- * Older chunks are removed when the limit is reached.
17
- *
18
- * @default Number.POSITIVE_INFINITY (unlimited)
19
- */
20
- maxChunks?: number | undefined;
4
+ /**
5
+ * What a fetch does with existing data once its stream connects.
6
+ * Until then the data stays, so a query with data never returns to `pending`.
7
+ *
8
+ * - `'reset'`: the data becomes `[]`, then each chunk is appended.
9
+ * - `'append'`: the data is kept (trimmed to `maxChunks`), and each chunk is appended.
10
+ *
11
+ * @default 'reset'
12
+ */
13
+ refetchMode?: "append" | "reset" | undefined;
14
+ /**
15
+ * Limits the number of data chunks stored in the query result.
16
+ * Older chunks are removed when the limit is reached.
17
+ *
18
+ * @default Number.POSITIVE_INFINITY (unlimited)
19
+ */
20
+ maxChunks?: number | undefined;
21
21
  }
22
22
  export interface SettleOnFirstDataOptions {
23
- /**
24
- * Settles the fetch at its first data (streamed: when the stream connects; live: on the first event)
25
- * instead of following the stream to its end. The stream is closed and the data kept.
26
- * Use it only where nothing watches the stream, such as server rendering:
27
- * a refetch while a query is mounted would also settle, closing its stream.
28
- *
29
- * @default false
30
- */
31
- settleOnFirstData?: boolean | undefined;
32
- }
33
- /**
34
- * A variant of `streamedQuery` where:
35
- * - Options are serializable
36
- * - The output is predictable
37
- */
38
- export declare function serializableStreamedQuery<TQueryFnData = unknown, TQueryKey extends QueryKey = QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => Promisable<AsyncIterable<TQueryFnData>>, { refetchMode, maxChunks, settleOnFirstData, }?: SerializableStreamedQueryOptions & SettleOnFirstDataOptions): QueryFunction<TQueryFnData[], TQueryKey>;
23
+ /**
24
+ * Settles the fetch at its first data (streamed: when the stream connects; live: on the first event)
25
+ * instead of following the stream to its end. The stream is closed and the data kept.
26
+ * Use it only where nothing watches the stream, such as server rendering:
27
+ * a refetch while a query is mounted would also settle, closing its stream.
28
+ *
29
+ * @default false
30
+ */
31
+ settleOnFirstData?: boolean | undefined;
32
+ }
@@ -1,52 +1,38 @@
1
- import { throwIfAborted } from '@orpc/shared';
1
+ import { listenAbort, takeLast, throwIfAborted } from "@orpc/shared";
2
+ // src/stream-query.ts
2
3
  /**
3
- * A variant of `streamedQuery` where:
4
- * - Options are serializable
5
- * - The output is predictable
6
- */
7
- export function serializableStreamedQuery(queryFn, { refetchMode = 'reset', maxChunks = Number.POSITIVE_INFINITY, settleOnFirstData = false, } = {}) {
8
- return async (context) => {
9
- const { client, queryKey, signal } = context;
10
- // a stream cut short (cancelled, or its last observer left) reopens when observed again;
11
- // marked at abort, so the writes of a fetch that replaces this one clear it
12
- const markStale = () => client.getQueryCache().find({ queryKey, exact: true })?.invalidate();
13
- if (signal.aborted) {
14
- markStale();
15
- }
16
- signal.addEventListener('abort', markStale, { once: true });
17
- try {
18
- const stream = await queryFn(context);
19
- // close without reading, so a generator the query no longer wants never starts
20
- if (signal.aborted) {
21
- await stream[Symbol.asyncIterator]().return?.();
22
- throw signal.reason;
23
- }
24
- let data = client.setQueryData(queryKey, (current) => refetchMode === 'append' && current ? limitArraySize(current, maxChunks) : []);
25
- if (settleOnFirstData) {
26
- await stream[Symbol.asyncIterator]().return?.();
27
- return data;
28
- }
29
- for await (const chunk of stream) {
30
- throwIfAborted(signal);
31
- // read the cache, so writes made during the stream are kept
32
- data = client.setQueryData(queryKey, (current = []) => limitArraySize([...current, chunk], maxChunks));
33
- }
34
- // the returned data is written again, so return the cache to keep later writes
35
- const cached = client.getQueryData(queryKey);
36
- if (cached === undefined) {
37
- return data;
38
- }
39
- // only an array is trimmed; another value written after the stream (e.g. `null`) is kept as is
40
- return Array.isArray(cached) ? limitArraySize(cached, maxChunks) : cached;
41
- }
42
- finally {
43
- signal.removeEventListener('abort', markStale);
44
- }
45
- };
46
- }
47
- function limitArraySize(items, maxSize) {
48
- if (items.length <= maxSize) {
49
- return items;
50
- }
51
- return items.slice(items.length - maxSize);
4
+ * A variant of `streamedQuery` where:
5
+ * - Options are serializable
6
+ * - The output is predictable
7
+ */
8
+ function serializableStreamedQuery(queryFn, { refetchMode = "reset", maxChunks = Number.POSITIVE_INFINITY, settleOnFirstData = false } = {}) {
9
+ return async (context) => {
10
+ const { client, queryKey, signal } = context;
11
+ const unlisten = listenAbort(signal, () => client.getQueryCache().find({
12
+ queryKey,
13
+ exact: true
14
+ })?.invalidate());
15
+ try {
16
+ const stream = await queryFn(context);
17
+ if (signal.aborted) {
18
+ await stream[Symbol.asyncIterator]().return?.();
19
+ throw signal.reason;
20
+ }
21
+ let data = client.setQueryData(queryKey, (current) => refetchMode === "append" && current ? takeLast(current, maxChunks) : []);
22
+ if (settleOnFirstData) {
23
+ await stream[Symbol.asyncIterator]().return?.();
24
+ return data;
25
+ }
26
+ for await (const chunk of stream) {
27
+ throwIfAborted(signal);
28
+ data = client.setQueryData(queryKey, (current) => takeLast([...current ?? [], chunk], maxChunks));
29
+ }
30
+ const cached = client.getQueryData(queryKey);
31
+ if (cached === void 0) return data;
32
+ return Array.isArray(cached) ? takeLast(cached, maxChunks) : cached;
33
+ } finally {
34
+ unlisten();
35
+ }
36
+ };
52
37
  }
38
+ export { serializableStreamedQuery };
@@ -1,5 +1,5 @@
1
- import type { RPCJsonSerializer } from '@orpc/client';
2
- import type { Public } from '@orpc/shared';
1
+ import { Public } from "@orpc/shared";
2
+ import { RPCJsonSerializer } from "@orpc/client";
3
3
  export type StructuralSharing = <T>(oldData: unknown, newData: T) => T;
4
4
  /**
5
5
  * Creates a `structuralSharing` function that works like TanStack Query's default, but also keeps
@@ -11,4 +11,4 @@ export type StructuralSharing = <T>(oldData: unknown, newData: T) => T;
11
11
  *
12
12
  * @see {@link https://orpc.dev/docs/integrations/tanstack-query#structural-sharing | TanStack Query Integration - Structural Sharing}
13
13
  */
14
- export declare function createStructuralSharing(serializer?: Public<RPCJsonSerializer>): StructuralSharing;
14
+ export declare function createStructuralSharing(serializer?: Public<RPCJsonSerializer>): StructuralSharing;