@trpc/tanstack-react-query 11.3.1 → 11.3.2-canary.4

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.
Files changed (41) hide show
  1. package/dist/index.cjs +465 -0
  2. package/dist/index.d.cts +420 -0
  3. package/dist/index.d.cts.map +1 -0
  4. package/dist/index.d.mts +420 -0
  5. package/dist/index.d.mts.map +1 -0
  6. package/dist/index.mjs +442 -3
  7. package/dist/index.mjs.map +1 -0
  8. package/package.json +21 -17
  9. package/dist/index.d.ts +0 -10
  10. package/dist/index.d.ts.map +0 -1
  11. package/dist/index.js +0 -11
  12. package/dist/internals/Context.d.ts +0 -21
  13. package/dist/internals/Context.d.ts.map +0 -1
  14. package/dist/internals/Context.js +0 -67
  15. package/dist/internals/Context.mjs +0 -46
  16. package/dist/internals/createOptionsProxy.d.ts +0 -161
  17. package/dist/internals/createOptionsProxy.d.ts.map +0 -1
  18. package/dist/internals/createOptionsProxy.js +0 -113
  19. package/dist/internals/createOptionsProxy.mjs +0 -111
  20. package/dist/internals/infiniteQueryOptions.d.ts +0 -61
  21. package/dist/internals/infiniteQueryOptions.d.ts.map +0 -1
  22. package/dist/internals/infiniteQueryOptions.js +0 -39
  23. package/dist/internals/infiniteQueryOptions.mjs +0 -37
  24. package/dist/internals/mutationOptions.d.ts +0 -43
  25. package/dist/internals/mutationOptions.d.ts.map +0 -1
  26. package/dist/internals/mutationOptions.js +0 -40
  27. package/dist/internals/mutationOptions.mjs +0 -38
  28. package/dist/internals/queryOptions.d.ts +0 -58
  29. package/dist/internals/queryOptions.d.ts.map +0 -1
  30. package/dist/internals/queryOptions.js +0 -43
  31. package/dist/internals/queryOptions.mjs +0 -41
  32. package/dist/internals/subscriptionOptions.d.ts +0 -73
  33. package/dist/internals/subscriptionOptions.d.ts.map +0 -1
  34. package/dist/internals/subscriptionOptions.js +0 -181
  35. package/dist/internals/subscriptionOptions.mjs +0 -159
  36. package/dist/internals/types.d.ts +0 -83
  37. package/dist/internals/types.d.ts.map +0 -1
  38. package/dist/internals/utils.d.ts +0 -36
  39. package/dist/internals/utils.d.ts.map +0 -1
  40. package/dist/internals/utils.js +0 -118
  41. package/dist/internals/utils.mjs +0 -111
package/dist/index.cjs ADDED
@@ -0,0 +1,465 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ const react = __toESM(require("react"));
25
+ const __trpc_client = __toESM(require("@trpc/client"));
26
+ const __trpc_server = __toESM(require("@trpc/server"));
27
+ const __tanstack_react_query = __toESM(require("@tanstack/react-query"));
28
+ const __trpc_server_unstable_core_do_not_import = __toESM(require("@trpc/server/unstable-core-do-not-import"));
29
+ const react_jsx_runtime = __toESM(require("react/jsx-runtime"));
30
+
31
+ //#region src/internals/utils.ts
32
+ /**
33
+ * @internal
34
+ */
35
+ function createTRPCOptionsResult(value) {
36
+ const path = value.path.join(".");
37
+ return { path };
38
+ }
39
+ /**
40
+ * @internal
41
+ */
42
+ function getClientArgs(queryKey, opts, infiniteParams) {
43
+ const path = queryKey[0];
44
+ let input = queryKey[1]?.input;
45
+ if (infiniteParams) input = {
46
+ ...input ?? {},
47
+ ...infiniteParams.pageParam !== void 0 ? { cursor: infiniteParams.pageParam } : {},
48
+ direction: infiniteParams.direction
49
+ };
50
+ return [
51
+ path.join("."),
52
+ input,
53
+ opts?.trpc
54
+ ];
55
+ }
56
+ /**
57
+ * @internal
58
+ */
59
+ async function buildQueryFromAsyncIterable(asyncIterable, queryClient, queryKey) {
60
+ const queryCache = queryClient.getQueryCache();
61
+ const query = queryCache.build(queryClient, { queryKey });
62
+ query.setState({
63
+ data: [],
64
+ status: "success"
65
+ });
66
+ const aggregate = [];
67
+ for await (const value of asyncIterable) {
68
+ aggregate.push(value);
69
+ query.setState({ data: [...aggregate] });
70
+ }
71
+ return aggregate;
72
+ }
73
+ /**
74
+ * To allow easy interactions with groups of related queries, such as
75
+ * invalidating all queries of a router, we use an array as the path when
76
+ * storing in tanstack query.
77
+ *
78
+ * @internal
79
+ */
80
+ function getQueryKeyInternal(path, input, type) {
81
+ const splitPath = path.flatMap((part) => part.split("."));
82
+ if (!input && (!type || type === "any")) return splitPath.length ? [splitPath] : [];
83
+ if (type === "infinite" && (0, __trpc_server_unstable_core_do_not_import.isObject)(input) && ("direction" in input || "cursor" in input)) {
84
+ const { cursor: _, direction: __,...inputWithoutCursorAndDirection } = input;
85
+ return [splitPath, {
86
+ input: inputWithoutCursorAndDirection,
87
+ type: "infinite"
88
+ }];
89
+ }
90
+ return [splitPath, {
91
+ ...typeof input !== "undefined" && input !== __tanstack_react_query.skipToken && { input },
92
+ ...type && type !== "any" && { type }
93
+ }];
94
+ }
95
+ /**
96
+ * @internal
97
+ */
98
+ function getMutationKeyInternal(path) {
99
+ const splitPath = path.flatMap((part) => part.split("."));
100
+ return splitPath.length ? [splitPath] : [];
101
+ }
102
+ /**
103
+ * @internal
104
+ */
105
+ function unwrapLazyArg(valueOrLazy) {
106
+ return (0, __trpc_server_unstable_core_do_not_import.isFunction)(valueOrLazy) ? valueOrLazy() : valueOrLazy;
107
+ }
108
+
109
+ //#endregion
110
+ //#region src/internals/infiniteQueryOptions.ts
111
+ function trpcInfiniteQueryOptions(args) {
112
+ const { input, query, path, queryKey, opts } = args;
113
+ const inputIsSkipToken = input === __tanstack_react_query.skipToken;
114
+ const queryFn = async (queryFnContext) => {
115
+ const actualOpts = {
116
+ ...opts,
117
+ trpc: {
118
+ ...opts?.trpc,
119
+ ...opts?.trpc?.abortOnUnmount ? { signal: queryFnContext.signal } : { signal: null }
120
+ }
121
+ };
122
+ const result = await query(...getClientArgs(queryKey, actualOpts, {
123
+ direction: queryFnContext.direction,
124
+ pageParam: queryFnContext.pageParam
125
+ }));
126
+ return result;
127
+ };
128
+ return Object.assign((0, __tanstack_react_query.infiniteQueryOptions)({
129
+ ...opts,
130
+ queryKey,
131
+ queryFn: inputIsSkipToken ? __tanstack_react_query.skipToken : queryFn,
132
+ initialPageParam: opts?.initialCursor ?? input?.cursor
133
+ }), { trpc: createTRPCOptionsResult({ path }) });
134
+ }
135
+
136
+ //#endregion
137
+ //#region src/internals/mutationOptions.ts
138
+ /**
139
+ * @internal
140
+ */
141
+ function trpcMutationOptions(args) {
142
+ const { mutate, path, opts, overrides } = args;
143
+ const queryClient = unwrapLazyArg(args.queryClient);
144
+ const mutationKey = getMutationKeyInternal(path);
145
+ const defaultOpts = queryClient.defaultMutationOptions(queryClient.getMutationDefaults(mutationKey));
146
+ const mutationSuccessOverride = overrides?.onSuccess ?? ((options) => options.originalFn());
147
+ const mutationFn = async (input) => {
148
+ const result = await mutate(...getClientArgs([path, { input }], opts));
149
+ return result;
150
+ };
151
+ return {
152
+ ...opts,
153
+ mutationKey,
154
+ mutationFn,
155
+ onSuccess(...args$1) {
156
+ const originalFn = () => opts?.onSuccess?.(...args$1) ?? defaultOpts?.onSuccess?.(...args$1);
157
+ return mutationSuccessOverride({
158
+ originalFn,
159
+ queryClient,
160
+ meta: opts?.meta ?? defaultOpts?.meta ?? {}
161
+ });
162
+ },
163
+ trpc: createTRPCOptionsResult({ path })
164
+ };
165
+ }
166
+
167
+ //#endregion
168
+ //#region src/internals/queryOptions.ts
169
+ /**
170
+ * @internal
171
+ */
172
+ function trpcQueryOptions(args) {
173
+ const { input, query, path, queryKey, opts } = args;
174
+ const queryClient = unwrapLazyArg(args.queryClient);
175
+ const inputIsSkipToken = input === __tanstack_react_query.skipToken;
176
+ const queryFn = async (queryFnContext) => {
177
+ const actualOpts = {
178
+ ...opts,
179
+ trpc: {
180
+ ...opts?.trpc,
181
+ ...opts?.trpc?.abortOnUnmount ? { signal: queryFnContext.signal } : { signal: null }
182
+ }
183
+ };
184
+ const queryKey$1 = queryFnContext.queryKey;
185
+ const result = await query(...getClientArgs(queryKey$1, actualOpts));
186
+ if ((0, __trpc_server_unstable_core_do_not_import.isAsyncIterable)(result)) return buildQueryFromAsyncIterable(result, queryClient, queryKey$1);
187
+ return result;
188
+ };
189
+ return Object.assign((0, __tanstack_react_query.queryOptions)({
190
+ ...opts,
191
+ queryKey,
192
+ queryFn: inputIsSkipToken ? __tanstack_react_query.skipToken : queryFn
193
+ }), { trpc: createTRPCOptionsResult({ path }) });
194
+ }
195
+
196
+ //#endregion
197
+ //#region src/internals/subscriptionOptions.ts
198
+ /**
199
+ * @internal
200
+ */
201
+ const trpcSubscriptionOptions = (args) => {
202
+ const { subscribe, path, queryKey, opts = {} } = args;
203
+ const input = queryKey[1]?.input;
204
+ const enabled = "enabled" in opts ? !!opts.enabled : input !== __tanstack_react_query.skipToken;
205
+ const _subscribe = (innerOpts) => {
206
+ return subscribe(path.join("."), input ?? void 0, innerOpts);
207
+ };
208
+ return {
209
+ ...opts,
210
+ enabled,
211
+ subscribe: _subscribe,
212
+ queryKey,
213
+ trpc: createTRPCOptionsResult({ path })
214
+ };
215
+ };
216
+ function useSubscription(opts) {
217
+ const optsRef = react.useRef(opts);
218
+ optsRef.current = opts;
219
+ const trackedProps = react.useRef(new Set([]));
220
+ const addTrackedProp = react.useCallback((key) => {
221
+ trackedProps.current.add(key);
222
+ }, []);
223
+ const currentSubscriptionRef = react.useRef(() => {});
224
+ const reset = react.useCallback(() => {
225
+ currentSubscriptionRef.current?.();
226
+ updateState(getInitialState);
227
+ if (!opts.enabled) return;
228
+ const subscription = opts.subscribe({
229
+ onStarted: () => {
230
+ optsRef.current.onStarted?.();
231
+ updateState((prev) => ({
232
+ ...prev,
233
+ status: "pending",
234
+ error: null
235
+ }));
236
+ },
237
+ onData: (data) => {
238
+ optsRef.current.onData?.(data);
239
+ updateState((prev) => ({
240
+ ...prev,
241
+ status: "pending",
242
+ data,
243
+ error: null
244
+ }));
245
+ },
246
+ onError: (error) => {
247
+ optsRef.current.onError?.(error);
248
+ updateState((prev) => ({
249
+ ...prev,
250
+ status: "error",
251
+ error
252
+ }));
253
+ },
254
+ onConnectionStateChange: (result) => {
255
+ optsRef.current.onConnectionStateChange?.(result);
256
+ updateState((prev) => {
257
+ switch (result.state) {
258
+ case "connecting": return {
259
+ ...prev,
260
+ status: "connecting",
261
+ error: result.error
262
+ };
263
+ case "pending": return prev;
264
+ case "idle": return {
265
+ ...prev,
266
+ status: "idle",
267
+ data: void 0,
268
+ error: null
269
+ };
270
+ }
271
+ });
272
+ }
273
+ });
274
+ currentSubscriptionRef.current = () => {
275
+ subscription.unsubscribe();
276
+ };
277
+ }, [(0, __tanstack_react_query.hashKey)(opts.queryKey), opts.enabled]);
278
+ const getInitialState = react.useCallback(() => {
279
+ return opts.enabled ? {
280
+ data: void 0,
281
+ error: null,
282
+ status: "connecting",
283
+ reset
284
+ } : {
285
+ data: void 0,
286
+ error: null,
287
+ status: "idle",
288
+ reset
289
+ };
290
+ }, [opts.enabled, reset]);
291
+ const resultRef = react.useRef(getInitialState());
292
+ const [state, setState] = react.useState(trackResult(resultRef.current, addTrackedProp));
293
+ state.reset = reset;
294
+ const updateState = react.useCallback((callback) => {
295
+ const prev = resultRef.current;
296
+ const next = resultRef.current = callback(prev);
297
+ let shouldUpdate = false;
298
+ for (const key of trackedProps.current) if (prev[key] !== next[key]) {
299
+ shouldUpdate = true;
300
+ break;
301
+ }
302
+ if (shouldUpdate) setState(trackResult(next, addTrackedProp));
303
+ }, [addTrackedProp]);
304
+ react.useEffect(() => {
305
+ if (!opts.enabled) return;
306
+ reset();
307
+ return () => {
308
+ currentSubscriptionRef.current?.();
309
+ };
310
+ }, [reset, opts.enabled]);
311
+ return state;
312
+ }
313
+ function trackResult(result, onTrackResult) {
314
+ const trackedResult = new Proxy(result, { get(target, prop) {
315
+ onTrackResult(prop);
316
+ return target[prop];
317
+ } });
318
+ return trackedResult;
319
+ }
320
+
321
+ //#endregion
322
+ //#region src/internals/createOptionsProxy.ts
323
+ /**
324
+ * Create a typed proxy from your router types. Can also be used on the server.
325
+ *
326
+ * @see https://trpc.io/docs/client/tanstack-react-query/setup#3b-setup-without-react-context
327
+ * @see https://trpc.io/docs/client/tanstack-react-query/server-components#5-create-a-trpc-caller-for-server-components
328
+ */
329
+ function createTRPCOptionsProxy(opts) {
330
+ const callIt = (type) => {
331
+ return (path, input, trpcOpts) => {
332
+ if ("router" in opts) return Promise.resolve(unwrapLazyArg(opts.ctx)).then((ctx) => (0, __trpc_server.callTRPCProcedure)({
333
+ router: opts.router,
334
+ path,
335
+ getRawInput: async () => input,
336
+ ctx,
337
+ type,
338
+ signal: void 0
339
+ }));
340
+ const untypedClient = opts.client instanceof __trpc_client.TRPCUntypedClient ? opts.client : (0, __trpc_client.getUntypedClient)(opts.client);
341
+ return untypedClient[type](path, input, trpcOpts);
342
+ };
343
+ };
344
+ return (0, __trpc_server.createTRPCRecursiveProxy)(({ args, path: _path }) => {
345
+ const path = [..._path];
346
+ const utilName = path.pop();
347
+ const [arg1, arg2] = args;
348
+ const contextMap = {
349
+ "~types": void 0,
350
+ pathKey: () => {
351
+ return getQueryKeyInternal(path);
352
+ },
353
+ pathFilter: () => {
354
+ return {
355
+ ...arg1,
356
+ queryKey: getQueryKeyInternal(path)
357
+ };
358
+ },
359
+ queryOptions: () => {
360
+ return trpcQueryOptions({
361
+ input: arg1,
362
+ opts: arg2,
363
+ path,
364
+ queryClient: opts.queryClient,
365
+ queryKey: getQueryKeyInternal(path, arg1, "query"),
366
+ query: callIt("query")
367
+ });
368
+ },
369
+ queryKey: () => {
370
+ return getQueryKeyInternal(path, arg1, "query");
371
+ },
372
+ queryFilter: () => {
373
+ return {
374
+ ...arg2,
375
+ queryKey: getQueryKeyInternal(path, arg1, "query")
376
+ };
377
+ },
378
+ infiniteQueryOptions: () => {
379
+ return trpcInfiniteQueryOptions({
380
+ input: arg1,
381
+ opts: arg2,
382
+ path,
383
+ queryClient: opts.queryClient,
384
+ queryKey: getQueryKeyInternal(path, arg1, "infinite"),
385
+ query: callIt("query")
386
+ });
387
+ },
388
+ infiniteQueryKey: () => {
389
+ return getQueryKeyInternal(path, arg1, "infinite");
390
+ },
391
+ infiniteQueryFilter: () => {
392
+ return {
393
+ ...arg2,
394
+ queryKey: getQueryKeyInternal(path, arg1, "infinite")
395
+ };
396
+ },
397
+ mutationOptions: () => {
398
+ return trpcMutationOptions({
399
+ opts: arg1,
400
+ path,
401
+ queryClient: opts.queryClient,
402
+ mutate: callIt("mutation"),
403
+ overrides: opts.overrides?.mutations
404
+ });
405
+ },
406
+ mutationKey: () => {
407
+ return getMutationKeyInternal(path);
408
+ },
409
+ subscriptionOptions: () => {
410
+ return trpcSubscriptionOptions({
411
+ opts: arg2,
412
+ path,
413
+ queryKey: getQueryKeyInternal(path, arg1, "any"),
414
+ subscribe: callIt("subscription")
415
+ });
416
+ }
417
+ };
418
+ return contextMap[utilName]();
419
+ });
420
+ }
421
+
422
+ //#endregion
423
+ //#region src/internals/Context.tsx
424
+ /**
425
+ * Create a set of type-safe provider-consumers
426
+ *
427
+ * @see https://trpc.io/docs/client/tanstack-react-query/setup#3a-setup-the-trpc-context-provider
428
+ */
429
+ function createTRPCContext() {
430
+ const TRPCClientContext = react.createContext(null);
431
+ const TRPCContext = react.createContext(null);
432
+ function TRPCProvider(props) {
433
+ const value = react.useMemo(() => createTRPCOptionsProxy({
434
+ client: props.trpcClient,
435
+ queryClient: props.queryClient
436
+ }), [props.trpcClient, props.queryClient]);
437
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TRPCClientContext.Provider, {
438
+ value: props.trpcClient,
439
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TRPCContext.Provider, {
440
+ value,
441
+ children: props.children
442
+ })
443
+ });
444
+ }
445
+ function useTRPC() {
446
+ const utils = react.useContext(TRPCContext);
447
+ if (!utils) throw new Error("useTRPC() can only be used inside of a <TRPCProvider>");
448
+ return utils;
449
+ }
450
+ function useTRPCClient() {
451
+ const client = react.useContext(TRPCClientContext);
452
+ if (!client) throw new Error("useTRPCClient() can only be used inside of a <TRPCProvider>");
453
+ return client;
454
+ }
455
+ return {
456
+ TRPCProvider,
457
+ useTRPC,
458
+ useTRPCClient
459
+ };
460
+ }
461
+
462
+ //#endregion
463
+ exports.createTRPCContext = createTRPCContext;
464
+ exports.createTRPCOptionsProxy = createTRPCOptionsProxy;
465
+ exports.useSubscription = useSubscription;