@zenstackhq/tanstack-query 3.0.0 → 3.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.
Files changed (56) hide show
  1. package/dist/common/client.d.ts +4 -0
  2. package/dist/common/client.js +38 -0
  3. package/dist/common/client.js.map +1 -0
  4. package/dist/common/query-key.d.ts +39 -0
  5. package/dist/common/query-key.js +38 -0
  6. package/dist/common/query-key.js.map +1 -0
  7. package/dist/common/types.d.ts +60 -0
  8. package/dist/common/types.js +2 -0
  9. package/dist/common/types.js.map +1 -0
  10. package/dist/react.d.ts +99 -150
  11. package/dist/react.js +248 -1178
  12. package/dist/react.js.map +1 -1
  13. package/dist/svelte/index.svelte.d.ts +79 -0
  14. package/dist/svelte/index.svelte.js +245 -0
  15. package/dist/vue.d.ts +313 -342
  16. package/dist/vue.js +224 -1138
  17. package/dist/vue.js.map +1 -1
  18. package/package.json +36 -48
  19. package/.turbo/turbo-build.log +0 -47
  20. package/dist/react.cjs +0 -1240
  21. package/dist/react.cjs.map +0 -1
  22. package/dist/react.d.cts +0 -616
  23. package/dist/svelte.cjs +0 -1224
  24. package/dist/svelte.cjs.map +0 -1
  25. package/dist/svelte.d.cts +0 -381
  26. package/dist/svelte.d.ts +0 -381
  27. package/dist/svelte.js +0 -1183
  28. package/dist/svelte.js.map +0 -1
  29. package/dist/types-C8iIZD-7.d.cts +0 -99
  30. package/dist/types-C8iIZD-7.d.ts +0 -99
  31. package/dist/vue.cjs +0 -1192
  32. package/dist/vue.cjs.map +0 -1
  33. package/dist/vue.d.cts +0 -382
  34. package/eslint.config.js +0 -4
  35. package/src/react.ts +0 -562
  36. package/src/svelte.ts +0 -502
  37. package/src/utils/common.ts +0 -448
  38. package/src/utils/mutator.ts +0 -441
  39. package/src/utils/nested-read-visitor.ts +0 -61
  40. package/src/utils/nested-write-visitor.ts +0 -359
  41. package/src/utils/query-analysis.ts +0 -116
  42. package/src/utils/serialization.ts +0 -39
  43. package/src/utils/types.ts +0 -43
  44. package/src/vue.ts +0 -448
  45. package/test/react-query.test.tsx +0 -1787
  46. package/test/react-typing-test.ts +0 -113
  47. package/test/schemas/basic/input.ts +0 -110
  48. package/test/schemas/basic/models.ts +0 -14
  49. package/test/schemas/basic/schema-lite.ts +0 -172
  50. package/test/schemas/basic/schema.zmodel +0 -35
  51. package/test/svelte-typing-test.ts +0 -111
  52. package/test/vue-typing-test.ts +0 -111
  53. package/tsconfig.json +0 -7
  54. package/tsconfig.test.json +0 -8
  55. package/tsup.config.ts +0 -15
  56. package/vitest.config.ts +0 -11
package/dist/react.js CHANGED
@@ -1,1197 +1,267 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/react.ts
5
- import { useInfiniteQuery, useMutation, useQuery, useQueryClient, useSuspenseInfiniteQuery, useSuspenseQuery } from "@tanstack/react-query";
6
- import { lowerCaseFirst as lowerCaseFirst2 } from "@zenstackhq/common-helpers";
7
- import { createContext, useContext } from "react";
8
-
9
- // src/utils/common.ts
10
- import { lowerCaseFirst } from "@zenstackhq/common-helpers";
11
-
12
- // src/utils/mutator.ts
13
- import { clone, enumerate as enumerate2, invariant, zip } from "@zenstackhq/common-helpers";
14
-
15
- // src/utils/nested-write-visitor.ts
16
- import { enumerate } from "@zenstackhq/common-helpers";
17
-
18
- // src/utils/types.ts
19
- var ORMWriteActions = [
20
- "create",
21
- "createMany",
22
- "createManyAndReturn",
23
- "connectOrCreate",
24
- "update",
25
- "updateMany",
26
- "updateManyAndReturn",
27
- "upsert",
28
- "connect",
29
- "disconnect",
30
- "set",
31
- "delete",
32
- "deleteMany"
33
- ];
34
-
35
- // src/utils/nested-write-visitor.ts
36
- var NestedWriteVisitor = class {
37
- static {
38
- __name(this, "NestedWriteVisitor");
39
- }
40
- schema;
41
- callback;
42
- constructor(schema, callback) {
43
- this.schema = schema;
44
- this.callback = callback;
45
- }
46
- isWriteAction(value) {
47
- return ORMWriteActions.includes(value);
48
- }
49
- /**
50
- * Start visiting
51
- *
52
- * @see NestedWriterVisitorCallback
53
- */
54
- async visit(model, action, args) {
55
- if (!args) {
56
- return;
57
- }
58
- let topData = args;
59
- switch (action) {
60
- // create has its data wrapped in 'data' field
61
- case "create":
62
- topData = topData.data;
63
- break;
64
- case "delete":
65
- case "deleteMany":
66
- topData = topData.where;
67
- break;
68
- }
69
- await this.doVisit(model, action, topData, void 0, void 0, []);
70
- }
71
- async doVisit(model, action, data, parent, field, nestingPath) {
72
- if (!data) {
73
- return;
74
- }
75
- const toplevel = field == void 0;
76
- const context = {
77
- parent,
78
- field,
79
- nestingPath: [
80
- ...nestingPath
81
- ]
82
- };
83
- const pushNewContext = /* @__PURE__ */ __name((field2, model2, where, unique = false) => {
84
- return {
85
- ...context,
86
- nestingPath: [
87
- ...context.nestingPath,
88
- {
89
- field: field2,
90
- model: model2,
91
- where,
92
- unique
93
- }
94
- ]
95
- };
96
- }, "pushNewContext");
97
- switch (action) {
98
- case "create":
99
- for (const item of this.enumerateReverse(data)) {
100
- const newContext = pushNewContext(field, model, {});
101
- let callbackResult;
102
- if (this.callback.create) {
103
- callbackResult = await this.callback.create(model, item, newContext);
104
- }
105
- if (callbackResult !== false) {
106
- const subPayload = typeof callbackResult === "object" ? callbackResult : item;
107
- await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
108
- }
109
- }
110
- break;
111
- case "createMany":
112
- case "createManyAndReturn":
113
- {
114
- const newContext = pushNewContext(field, model, {});
115
- let callbackResult;
116
- if (this.callback.createMany) {
117
- callbackResult = await this.callback.createMany(model, data, newContext);
118
- }
119
- if (callbackResult !== false) {
120
- const subPayload = typeof callbackResult === "object" ? callbackResult : data.data;
121
- await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
122
- }
123
- }
124
- break;
125
- case "connectOrCreate":
126
- for (const item of this.enumerateReverse(data)) {
127
- const newContext = pushNewContext(field, model, item.where);
128
- let callbackResult;
129
- if (this.callback.connectOrCreate) {
130
- callbackResult = await this.callback.connectOrCreate(model, item, newContext);
131
- }
132
- if (callbackResult !== false) {
133
- const subPayload = typeof callbackResult === "object" ? callbackResult : item.create;
134
- await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
135
- }
136
- }
137
- break;
138
- case "connect":
139
- if (this.callback.connect) {
140
- for (const item of this.enumerateReverse(data)) {
141
- const newContext = pushNewContext(field, model, item, true);
142
- await this.callback.connect(model, item, newContext);
143
- }
144
- }
145
- break;
146
- case "disconnect":
147
- if (this.callback.disconnect) {
148
- for (const item of this.enumerateReverse(data)) {
149
- const newContext = pushNewContext(field, model, item, typeof item === "object");
150
- await this.callback.disconnect(model, item, newContext);
151
- }
152
- }
153
- break;
154
- case "set":
155
- if (this.callback.set) {
156
- for (const item of this.enumerateReverse(data)) {
157
- const newContext = pushNewContext(field, model, item, true);
158
- await this.callback.set(model, item, newContext);
159
- }
160
- }
161
- break;
162
- case "update":
163
- for (const item of this.enumerateReverse(data)) {
164
- const newContext = pushNewContext(field, model, item.where);
165
- let callbackResult;
166
- if (this.callback.update) {
167
- callbackResult = await this.callback.update(model, item, newContext);
168
- }
169
- if (callbackResult !== false) {
170
- const subPayload = typeof callbackResult === "object" ? callbackResult : typeof item.data === "object" ? item.data : item;
171
- await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
172
- }
173
- }
174
- break;
175
- case "updateMany":
176
- case "updateManyAndReturn":
177
- for (const item of this.enumerateReverse(data)) {
178
- const newContext = pushNewContext(field, model, item.where);
179
- let callbackResult;
180
- if (this.callback.updateMany) {
181
- callbackResult = await this.callback.updateMany(model, item, newContext);
182
- }
183
- if (callbackResult !== false) {
184
- const subPayload = typeof callbackResult === "object" ? callbackResult : item;
185
- await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
186
- }
187
- }
188
- break;
189
- case "upsert": {
190
- for (const item of this.enumerateReverse(data)) {
191
- const newContext = pushNewContext(field, model, item.where);
192
- let callbackResult;
193
- if (this.callback.upsert) {
194
- callbackResult = await this.callback.upsert(model, item, newContext);
195
- }
196
- if (callbackResult !== false) {
197
- if (typeof callbackResult === "object") {
198
- await this.visitSubPayload(model, action, callbackResult, newContext.nestingPath);
199
- } else {
200
- await this.visitSubPayload(model, action, item.create, newContext.nestingPath);
201
- await this.visitSubPayload(model, action, item.update, newContext.nestingPath);
202
- }
203
- }
204
- }
205
- break;
206
- }
207
- case "delete": {
208
- if (this.callback.delete) {
209
- for (const item of this.enumerateReverse(data)) {
210
- const newContext = pushNewContext(field, model, toplevel ? item.where : item);
211
- await this.callback.delete(model, item, newContext);
212
- }
213
- }
214
- break;
215
- }
216
- case "deleteMany":
217
- if (this.callback.deleteMany) {
218
- for (const item of this.enumerateReverse(data)) {
219
- const newContext = pushNewContext(field, model, toplevel ? item.where : item);
220
- await this.callback.deleteMany(model, item, newContext);
221
- }
222
- }
223
- break;
224
- default: {
225
- throw new Error(`unhandled action type ${action}`);
226
- }
227
- }
228
- }
229
- async visitSubPayload(model, action, payload, nestingPath) {
230
- for (const item of enumerate(payload)) {
231
- if (!item || typeof item !== "object") {
232
- continue;
233
- }
234
- for (const field of Object.keys(item)) {
235
- const fieldDef = this.schema.models[model]?.fields[field];
236
- if (!fieldDef) {
237
- continue;
238
- }
239
- if (fieldDef.relation) {
240
- if (item[field]) {
241
- for (const [subAction, subData] of Object.entries(item[field])) {
242
- if (this.isWriteAction(subAction) && subData) {
243
- await this.doVisit(fieldDef.type, subAction, subData, item[field], fieldDef, [
244
- ...nestingPath
245
- ]);
246
- }
247
- }
248
- }
249
- } else {
250
- if (this.callback.field) {
251
- await this.callback.field(fieldDef, action, item[field], {
252
- parent: item,
253
- nestingPath,
254
- field: fieldDef
1
+ import { useInfiniteQuery, useMutation, useQuery, useQueryClient, useSuspenseInfiniteQuery, useSuspenseQuery, } from '@tanstack/react-query';
2
+ import { createInvalidator, createOptimisticUpdater, DEFAULT_QUERY_ENDPOINT } from '@zenstackhq/client-helpers';
3
+ import { fetcher, makeUrl, marshal } from '@zenstackhq/client-helpers/fetch';
4
+ import { lowerCaseFirst } from '@zenstackhq/common-helpers';
5
+ import { createContext, useContext } from 'react';
6
+ import { getAllQueries, invalidateQueriesMatchingPredicate } from './common/client';
7
+ import { getQueryKey } from './common/query-key';
8
+ /**
9
+ * React context for query settings.
10
+ */
11
+ export const QuerySettingsContext = createContext({
12
+ endpoint: DEFAULT_QUERY_ENDPOINT,
13
+ fetch: undefined,
14
+ });
15
+ /**
16
+ * React context provider for configuring query settings.
17
+ */
18
+ export const QuerySettingsProvider = QuerySettingsContext.Provider;
19
+ /**
20
+ * React context provider for configuring query settings.
21
+ *
22
+ * @deprecated Use {@link QuerySettingsProvider} instead.
23
+ */
24
+ export const Provider = QuerySettingsProvider;
25
+ function useHooksContext() {
26
+ const { endpoint, ...rest } = useContext(QuerySettingsContext);
27
+ return { endpoint: endpoint ?? DEFAULT_QUERY_ENDPOINT, ...rest };
28
+ }
29
+ /**
30
+ * Gets data query hooks for all models in the schema.
31
+ *
32
+ * @param schema The schema.
33
+ * @param options Options for all queries originated from this hook.
34
+ */
35
+ export function useClientQueries(schema, options) {
36
+ return Object.keys(schema.models).reduce((acc, model) => {
37
+ acc[lowerCaseFirst(model)] = useModelQueries(schema, model, options);
38
+ return acc;
39
+ }, {});
40
+ }
41
+ /**
42
+ * Gets data query hooks for a specific model in the schema.
43
+ */
44
+ export function useModelQueries(schema, model, rootOptions) {
45
+ const modelDef = Object.values(schema.models).find((m) => m.name.toLowerCase() === model.toLowerCase());
46
+ if (!modelDef) {
47
+ throw new Error(`Model "${model}" not found in schema`);
48
+ }
49
+ const modelName = modelDef.name;
50
+ return {
51
+ useFindUnique: (args, options) => {
52
+ return useInternalQuery(schema, modelName, 'findUnique', args, { ...rootOptions, ...options });
53
+ },
54
+ useSuspenseFindUnique: (args, options) => {
55
+ return useInternalSuspenseQuery(schema, modelName, 'findUnique', args, { ...rootOptions, ...options });
56
+ },
57
+ useFindFirst: (args, options) => {
58
+ return useInternalQuery(schema, modelName, 'findFirst', args, { ...rootOptions, ...options });
59
+ },
60
+ useSuspenseFindFirst: (args, options) => {
61
+ return useInternalSuspenseQuery(schema, modelName, 'findFirst', args, { ...rootOptions, ...options });
62
+ },
63
+ useFindMany: (args, options) => {
64
+ return useInternalQuery(schema, modelName, 'findMany', args, { ...rootOptions, ...options });
65
+ },
66
+ useSuspenseFindMany: (args, options) => {
67
+ return useInternalSuspenseQuery(schema, modelName, 'findMany', args, { ...rootOptions, ...options });
68
+ },
69
+ useInfiniteFindMany: (args, options) => {
70
+ return useInternalInfiniteQuery(schema, modelName, 'findMany', args, { ...rootOptions, ...options });
71
+ },
72
+ useSuspenseInfiniteFindMany: (args, options) => {
73
+ return useInternalSuspenseInfiniteQuery(schema, modelName, 'findMany', args, {
74
+ ...rootOptions,
75
+ ...options,
255
76
  });
256
- }
257
- }
258
- }
259
- }
260
- }
261
- // enumerate a (possible) array in reverse order, so that the enumeration
262
- // callback can safely delete the current item
263
- *enumerateReverse(data) {
264
- if (Array.isArray(data)) {
265
- for (let i = data.length - 1; i >= 0; i--) {
266
- yield data[i];
267
- }
268
- } else {
269
- yield data;
270
- }
271
- }
272
- };
273
-
274
- // src/utils/mutator.ts
275
- async function applyMutation(queryModel, queryOp, queryData, mutationModel, mutationOp, mutationArgs, schema, logging) {
276
- if (!queryData || typeof queryData !== "object" && !Array.isArray(queryData)) {
277
- return void 0;
278
- }
279
- if (!queryOp.startsWith("find")) {
280
- return void 0;
281
- }
282
- return await doApplyMutation(queryModel, queryData, mutationModel, mutationOp, mutationArgs, schema, logging);
283
- }
284
- __name(applyMutation, "applyMutation");
285
- async function doApplyMutation(queryModel, queryData, mutationModel, mutationOp, mutationArgs, schema, logging) {
286
- let resultData = queryData;
287
- let updated = false;
288
- const visitor = new NestedWriteVisitor(schema, {
289
- create: /* @__PURE__ */ __name((model, args) => {
290
- if (model === queryModel && Array.isArray(resultData)) {
291
- const r = createMutate(queryModel, resultData, args, schema, logging);
292
- if (r) {
293
- resultData = r;
294
- updated = true;
295
- }
296
- }
297
- }, "create"),
298
- createMany: /* @__PURE__ */ __name((model, args) => {
299
- if (model === queryModel && args?.data && Array.isArray(resultData)) {
300
- for (const oneArg of enumerate2(args.data)) {
301
- const r = createMutate(queryModel, resultData, oneArg, schema, logging);
302
- if (r) {
303
- resultData = r;
304
- updated = true;
305
- }
306
- }
307
- }
308
- }, "createMany"),
309
- update: /* @__PURE__ */ __name((model, args) => {
310
- if (model === queryModel && !Array.isArray(resultData)) {
311
- const r = updateMutate(queryModel, resultData, model, args, schema, logging);
312
- if (r) {
313
- resultData = r;
314
- updated = true;
315
- }
316
- }
317
- }, "update"),
318
- upsert: /* @__PURE__ */ __name((model, args) => {
319
- if (model === queryModel && args?.where && args?.create && args?.update) {
320
- const r = upsertMutate(queryModel, resultData, model, args, schema, logging);
321
- if (r) {
322
- resultData = r;
323
- updated = true;
324
- }
325
- }
326
- }, "upsert"),
327
- delete: /* @__PURE__ */ __name((model, args) => {
328
- if (model === queryModel) {
329
- const r = deleteMutate(queryModel, resultData, model, args, schema, logging);
330
- if (r) {
331
- resultData = r;
332
- updated = true;
333
- }
334
- }
335
- }, "delete")
336
- });
337
- await visitor.visit(mutationModel, mutationOp, mutationArgs);
338
- const modelFields = schema.models[queryModel]?.fields;
339
- invariant(modelFields, `Model ${queryModel} not found in schema`);
340
- if (Array.isArray(resultData)) {
341
- let arrayCloned = false;
342
- for (let i = 0; i < resultData.length; i++) {
343
- const item = resultData[i];
344
- if (!item || typeof item !== "object" || item.$optimistic) {
345
- continue;
346
- }
347
- const r = await doApplyMutation(queryModel, item, mutationModel, mutationOp, mutationArgs, schema, logging);
348
- if (r && typeof r === "object") {
349
- if (!arrayCloned) {
350
- resultData = [
351
- ...resultData
352
- ];
353
- arrayCloned = true;
354
- }
355
- resultData[i] = r;
356
- updated = true;
357
- }
358
- }
359
- } else if (resultData !== null && typeof resultData === "object") {
360
- const currentData = {
361
- ...resultData
77
+ },
78
+ useCreate: (options) => {
79
+ return useInternalMutation(schema, modelName, 'POST', 'create', { ...rootOptions, ...options });
80
+ },
81
+ useCreateMany: (options) => {
82
+ return useInternalMutation(schema, modelName, 'POST', 'createMany', { ...rootOptions, ...options });
83
+ },
84
+ useCreateManyAndReturn: (options) => {
85
+ return useInternalMutation(schema, modelName, 'POST', 'createManyAndReturn', {
86
+ ...rootOptions,
87
+ ...options,
88
+ });
89
+ },
90
+ useUpdate: (options) => {
91
+ return useInternalMutation(schema, modelName, 'PUT', 'update', { ...rootOptions, ...options });
92
+ },
93
+ useUpdateMany: (options) => {
94
+ return useInternalMutation(schema, modelName, 'PUT', 'updateMany', { ...rootOptions, ...options });
95
+ },
96
+ useUpdateManyAndReturn: (options) => {
97
+ return useInternalMutation(schema, modelName, 'PUT', 'updateManyAndReturn', { ...rootOptions, ...options });
98
+ },
99
+ useUpsert: (options) => {
100
+ return useInternalMutation(schema, modelName, 'POST', 'upsert', { ...rootOptions, ...options });
101
+ },
102
+ useDelete: (options) => {
103
+ return useInternalMutation(schema, modelName, 'DELETE', 'delete', { ...rootOptions, ...options });
104
+ },
105
+ useDeleteMany: (options) => {
106
+ return useInternalMutation(schema, modelName, 'DELETE', 'deleteMany', { ...rootOptions, ...options });
107
+ },
108
+ useCount: (args, options) => {
109
+ return useInternalQuery(schema, modelName, 'count', args, { ...rootOptions, ...options });
110
+ },
111
+ useSuspenseCount: (args, options) => {
112
+ return useInternalSuspenseQuery(schema, modelName, 'count', args, { ...rootOptions, ...options });
113
+ },
114
+ useAggregate: (args, options) => {
115
+ return useInternalQuery(schema, modelName, 'aggregate', args, { ...rootOptions, ...options });
116
+ },
117
+ useSuspenseAggregate: (args, options) => {
118
+ return useInternalSuspenseQuery(schema, modelName, 'aggregate', args, { ...rootOptions, ...options });
119
+ },
120
+ useGroupBy: (args, options) => {
121
+ return useInternalQuery(schema, modelName, 'groupBy', args, { ...rootOptions, ...options });
122
+ },
123
+ useSuspenseGroupBy: (args, options) => {
124
+ return useInternalSuspenseQuery(schema, modelName, 'groupBy', args, { ...rootOptions, ...options });
125
+ },
362
126
  };
363
- for (const [key, value] of Object.entries(currentData)) {
364
- const fieldDef = modelFields[key];
365
- if (!fieldDef?.relation) {
366
- continue;
367
- }
368
- const r = await doApplyMutation(fieldDef.type, value, mutationModel, mutationOp, mutationArgs, schema, logging);
369
- if (r && typeof r === "object") {
370
- resultData = {
371
- ...resultData,
372
- [key]: r
373
- };
374
- updated = true;
375
- }
376
- }
377
- }
378
- return updated ? resultData : void 0;
379
- }
380
- __name(doApplyMutation, "doApplyMutation");
381
- function createMutate(queryModel, currentData, newData, schema, logging) {
382
- if (!newData) {
383
- return void 0;
384
- }
385
- const modelFields = schema.models[queryModel]?.fields;
386
- if (!modelFields) {
387
- return void 0;
388
- }
389
- const insert = {};
390
- const newDataFields = Object.keys(newData);
391
- Object.entries(modelFields).forEach(([name, field]) => {
392
- if (field.relation && newData[name]) {
393
- assignForeignKeyFields(field, insert, newData[name]);
394
- return;
395
- }
396
- if (newDataFields.includes(name)) {
397
- insert[name] = clone(newData[name]);
398
- } else {
399
- const defaultAttr = field.attributes?.find((attr) => attr.name === "@default");
400
- if (field.type === "DateTime") {
401
- if (defaultAttr || field.attributes?.some((attr) => attr.name === "@updatedAt")) {
402
- insert[name] = /* @__PURE__ */ new Date();
403
- return;
404
- }
405
- }
406
- const defaultArg = defaultAttr?.args?.[0]?.value;
407
- if (defaultArg?.kind === "literal") {
408
- insert[name] = defaultArg.value;
409
- }
410
- }
411
- });
412
- const idFields = getIdFields(schema, queryModel);
413
- idFields.forEach((f) => {
414
- if (insert[f.name] === void 0) {
415
- if (f.type === "Int" || f.type === "BigInt") {
416
- const currMax = Array.isArray(currentData) ? Math.max(...[
417
- ...currentData
418
- ].map((item) => {
419
- const idv = parseInt(item[f.name]);
420
- return isNaN(idv) ? 0 : idv;
421
- })) : 0;
422
- insert[f.name] = currMax + 1;
423
- } else {
424
- insert[f.name] = crypto.randomUUID();
425
- }
426
- }
427
- });
428
- insert.$optimistic = true;
429
- if (logging) {
430
- console.log(`Optimistic create for ${queryModel}:`, insert);
431
- }
432
- return [
433
- insert,
434
- ...Array.isArray(currentData) ? currentData : []
435
- ];
436
- }
437
- __name(createMutate, "createMutate");
438
- function updateMutate(queryModel, currentData, mutateModel, mutateArgs, schema, logging) {
439
- if (!currentData || typeof currentData !== "object") {
440
- return void 0;
441
- }
442
- if (!mutateArgs?.where || typeof mutateArgs.where !== "object") {
443
- return void 0;
444
- }
445
- if (!mutateArgs?.data || typeof mutateArgs.data !== "object") {
446
- return void 0;
447
- }
448
- if (!idFieldsMatch(mutateModel, currentData, mutateArgs.where, schema)) {
449
- return void 0;
450
- }
451
- const modelFields = schema.models[queryModel]?.fields;
452
- if (!modelFields) {
453
- return void 0;
454
- }
455
- let updated = false;
456
- let resultData = currentData;
457
- for (const [key, value] of Object.entries(mutateArgs.data)) {
458
- const fieldInfo = modelFields[key];
459
- if (!fieldInfo) {
460
- continue;
461
- }
462
- if (fieldInfo.relation && !value?.connect) {
463
- continue;
464
- }
465
- if (!updated) {
466
- resultData = {
467
- ...currentData
468
- };
469
- }
470
- if (fieldInfo.relation) {
471
- assignForeignKeyFields(fieldInfo, resultData, value);
472
- } else {
473
- resultData[key] = clone(value);
474
- }
475
- resultData.$optimistic = true;
476
- updated = true;
477
- if (logging) {
478
- console.log(`Optimistic update for ${queryModel}:`, resultData);
479
- }
480
- }
481
- return updated ? resultData : void 0;
482
127
  }
483
- __name(updateMutate, "updateMutate");
484
- function upsertMutate(queryModel, currentData, model, args, schema, logging) {
485
- let updated = false;
486
- let resultData = currentData;
487
- if (Array.isArray(resultData)) {
488
- const foundIndex = resultData.findIndex((x) => idFieldsMatch(model, x, args.where, schema));
489
- if (foundIndex >= 0) {
490
- const updateResult = updateMutate(queryModel, resultData[foundIndex], model, {
491
- where: args.where,
492
- data: args.update
493
- }, schema, logging);
494
- if (updateResult) {
495
- resultData = [
496
- ...resultData.slice(0, foundIndex),
497
- updateResult,
498
- ...resultData.slice(foundIndex + 1)
499
- ];
500
- updated = true;
501
- }
502
- } else {
503
- const createResult = createMutate(queryModel, resultData, args.create, schema, logging);
504
- if (createResult) {
505
- resultData = createResult;
506
- updated = true;
507
- }
508
- }
509
- } else {
510
- const updateResult = updateMutate(queryModel, resultData, model, {
511
- where: args.where,
512
- data: args.update
513
- }, schema, logging);
514
- if (updateResult) {
515
- resultData = updateResult;
516
- updated = true;
517
- }
518
- }
519
- return updated ? resultData : void 0;
520
- }
521
- __name(upsertMutate, "upsertMutate");
522
- function deleteMutate(queryModel, currentData, mutateModel, mutateArgs, schema, logging) {
523
- if (!currentData || !mutateArgs) {
524
- return void 0;
525
- }
526
- if (queryModel !== mutateModel) {
527
- return void 0;
528
- }
529
- let updated = false;
530
- let result = currentData;
531
- if (Array.isArray(currentData)) {
532
- for (const item of currentData) {
533
- if (idFieldsMatch(mutateModel, item, mutateArgs, schema)) {
534
- result = result.filter((x) => x !== item);
535
- updated = true;
536
- if (logging) {
537
- console.log(`Optimistic delete for ${queryModel}:`, item);
538
- }
539
- }
540
- }
541
- } else {
542
- if (idFieldsMatch(mutateModel, currentData, mutateArgs, schema)) {
543
- result = null;
544
- updated = true;
545
- if (logging) {
546
- console.log(`Optimistic delete for ${queryModel}:`, currentData);
547
- }
548
- }
549
- }
550
- return updated ? result : void 0;
551
- }
552
- __name(deleteMutate, "deleteMutate");
553
- function idFieldsMatch(model, x, y, schema) {
554
- if (!x || !y || typeof x !== "object" || typeof y !== "object") {
555
- return false;
556
- }
557
- const idFields = getIdFields(schema, model);
558
- if (idFields.length === 0) {
559
- return false;
560
- }
561
- return idFields.every((f) => x[f.name] === y[f.name]);
562
- }
563
- __name(idFieldsMatch, "idFieldsMatch");
564
- function assignForeignKeyFields(field, resultData, mutationData) {
565
- if (!mutationData?.connect) {
566
- return;
567
- }
568
- if (!field.relation?.fields || !field.relation.references) {
569
- return;
570
- }
571
- for (const [idField, fkField] of zip(field.relation.references, field.relation.fields)) {
572
- if (idField in mutationData.connect) {
573
- resultData[fkField] = mutationData.connect[idField];
574
- }
575
- }
576
- }
577
- __name(assignForeignKeyFields, "assignForeignKeyFields");
578
- function getIdFields(schema, model) {
579
- return (schema.models[model]?.idFields ?? []).map((f) => schema.models[model].fields[f]);
580
- }
581
- __name(getIdFields, "getIdFields");
582
-
583
- // src/utils/nested-read-visitor.ts
584
- var NestedReadVisitor = class {
585
- static {
586
- __name(this, "NestedReadVisitor");
587
- }
588
- schema;
589
- callback;
590
- constructor(schema, callback) {
591
- this.schema = schema;
592
- this.callback = callback;
593
- }
594
- doVisit(model, field, kind, args) {
595
- if (this.callback.field) {
596
- const r = this.callback.field(model, field, kind, args);
597
- if (r === false) {
598
- return;
599
- }
600
- }
601
- if (!args || typeof args !== "object") {
602
- return;
603
- }
604
- let selectInclude;
605
- let nextKind;
606
- if (args.select) {
607
- selectInclude = args.select;
608
- nextKind = "select";
609
- } else if (args.include) {
610
- selectInclude = args.include;
611
- nextKind = "include";
612
- }
613
- if (selectInclude && typeof selectInclude === "object") {
614
- for (const [k, v] of Object.entries(selectInclude)) {
615
- if (k === "_count" && typeof v === "object" && v) {
616
- this.doVisit(model, field, kind, v);
617
- } else {
618
- const field2 = this.schema.models[model]?.fields[k];
619
- if (field2) {
620
- this.doVisit(field2.type, field2, nextKind, v);
621
- }
622
- }
623
- }
624
- }
625
- }
626
- visit(model, args) {
627
- this.doVisit(model, void 0, void 0, args);
628
- }
629
- };
630
-
631
- // src/utils/query-analysis.ts
632
- function getReadModels(model, schema, args) {
633
- const result = /* @__PURE__ */ new Set();
634
- result.add(model);
635
- const visitor = new NestedReadVisitor(schema, {
636
- field: /* @__PURE__ */ __name((model2) => {
637
- result.add(model2);
638
- return true;
639
- }, "field")
640
- });
641
- visitor.visit(model, args);
642
- return [
643
- ...result
644
- ];
645
- }
646
- __name(getReadModels, "getReadModels");
647
- async function getMutatedModels(model, operation, mutationArgs, schema) {
648
- const result = /* @__PURE__ */ new Set();
649
- result.add(model);
650
- if (mutationArgs) {
651
- const addModel = /* @__PURE__ */ __name((model2) => void result.add(model2), "addModel");
652
- const addCascades = /* @__PURE__ */ __name((model2) => {
653
- const cascades = /* @__PURE__ */ new Set();
654
- const visited = /* @__PURE__ */ new Set();
655
- collectDeleteCascades(model2, schema, cascades, visited);
656
- cascades.forEach((m) => addModel(m));
657
- }, "addCascades");
658
- const visitor = new NestedWriteVisitor(schema, {
659
- create: addModel,
660
- createMany: addModel,
661
- connectOrCreate: addModel,
662
- connect: addModel,
663
- disconnect: addModel,
664
- set: addModel,
665
- update: addModel,
666
- updateMany: addModel,
667
- upsert: addModel,
668
- delete: /* @__PURE__ */ __name((model2) => {
669
- addModel(model2);
670
- addCascades(model2);
671
- }, "delete"),
672
- deleteMany: /* @__PURE__ */ __name((model2) => {
673
- addModel(model2);
674
- addCascades(model2);
675
- }, "deleteMany")
128
+ export function useInternalQuery(_schema, model, operation, args, options) {
129
+ const { endpoint, fetch } = useFetchOptions(options);
130
+ const reqUrl = makeUrl(endpoint, model, operation, args);
131
+ const queryKey = getQueryKey(model, operation, args, {
132
+ infinite: false,
133
+ optimisticUpdate: options?.optimisticUpdate !== false,
676
134
  });
677
- await visitor.visit(model, operation, mutationArgs);
678
- }
679
- result.forEach((m) => {
680
- getBaseRecursively(m, schema, result);
681
- });
682
- return [
683
- ...result
684
- ];
685
- }
686
- __name(getMutatedModels, "getMutatedModels");
687
- function collectDeleteCascades(model, schema, result, visited) {
688
- if (visited.has(model)) {
689
- return;
690
- }
691
- visited.add(model);
692
- const modelDef = schema.models[model];
693
- if (!modelDef) {
694
- return;
695
- }
696
- for (const [modelName, modelDef2] of Object.entries(schema.models)) {
697
- if (!modelDef2) {
698
- continue;
699
- }
700
- for (const fieldDef of Object.values(modelDef2.fields)) {
701
- if (fieldDef.relation?.onDelete === "Cascade" && fieldDef.type === model) {
702
- if (!result.has(modelName)) {
703
- result.add(modelName);
704
- }
705
- collectDeleteCascades(modelName, schema, result, visited);
706
- }
707
- }
708
- }
709
- }
710
- __name(collectDeleteCascades, "collectDeleteCascades");
711
- function getBaseRecursively(model, schema, result) {
712
- const modelDef = schema.models[model];
713
- if (!modelDef) {
714
- return;
715
- }
716
- if (modelDef.baseModel) {
717
- result.add(modelDef.baseModel);
718
- getBaseRecursively(modelDef.baseModel, schema, result);
719
- }
720
- }
721
- __name(getBaseRecursively, "getBaseRecursively");
722
-
723
- // src/utils/serialization.ts
724
- import { Buffer as Buffer2 } from "buffer";
725
- import Decimal from "decimal.js";
726
- import SuperJSON from "superjson";
727
- SuperJSON.registerCustom({
728
- isApplicable: /* @__PURE__ */ __name((v) => v instanceof Decimal || // interop with decimal.js
729
- v?.toStringTag === "[object Decimal]", "isApplicable"),
730
- serialize: /* @__PURE__ */ __name((v) => v.toJSON(), "serialize"),
731
- deserialize: /* @__PURE__ */ __name((v) => new Decimal(v), "deserialize")
732
- }, "Decimal");
733
- SuperJSON.registerCustom({
734
- isApplicable: /* @__PURE__ */ __name((v) => Buffer2.isBuffer(v), "isApplicable"),
735
- serialize: /* @__PURE__ */ __name((v) => v.toString("base64"), "serialize"),
736
- deserialize: /* @__PURE__ */ __name((v) => Buffer2.from(v, "base64"), "deserialize")
737
- }, "Bytes");
738
- function serialize(value) {
739
- const { json, meta } = SuperJSON.serialize(value);
740
- return {
741
- data: json,
742
- meta
743
- };
744
- }
745
- __name(serialize, "serialize");
746
- function deserialize(value, meta) {
747
- return SuperJSON.deserialize({
748
- json: value,
749
- meta
750
- });
751
- }
752
- __name(deserialize, "deserialize");
753
-
754
- // src/utils/common.ts
755
- var QUERY_KEY_PREFIX = "zenstack";
756
- async function fetcher(url, options, customFetch) {
757
- const _fetch = customFetch ?? fetch;
758
- const res = await _fetch(url, options);
759
- if (!res.ok) {
760
- const errData = unmarshal(await res.text());
761
- if (errData.error?.rejectedByPolicy && errData.error?.rejectReason === "cannot-read-back") {
762
- return void 0;
763
- }
764
- const error = new Error("An error occurred while fetching the data.");
765
- error.info = errData.error;
766
- error.status = res.status;
767
- throw error;
768
- }
769
- const textResult = await res.text();
770
- try {
771
- return unmarshal(textResult).data;
772
- } catch (err) {
773
- console.error(`Unable to deserialize data:`, textResult);
774
- throw err;
775
- }
776
- }
777
- __name(fetcher, "fetcher");
778
- function getQueryKey(model, operation, args, options = {
779
- infinite: false,
780
- optimisticUpdate: true
781
- }) {
782
- const infinite = options.infinite;
783
- const optimisticUpdate2 = options.infinite ? false : options.optimisticUpdate;
784
- return [
785
- QUERY_KEY_PREFIX,
786
- model,
787
- operation,
788
- args,
789
- {
790
- infinite,
791
- optimisticUpdate: optimisticUpdate2
792
- }
793
- ];
135
+ return {
136
+ queryKey,
137
+ ...useQuery({
138
+ queryKey,
139
+ queryFn: ({ signal }) => fetcher(reqUrl, { signal }, fetch),
140
+ ...options,
141
+ }),
142
+ };
794
143
  }
795
- __name(getQueryKey, "getQueryKey");
796
- function marshal(value) {
797
- const { data, meta } = serialize(value);
798
- if (meta) {
799
- return JSON.stringify({
800
- ...data,
801
- meta: {
802
- serialization: meta
803
- }
144
+ export function useInternalSuspenseQuery(_schema, model, operation, args, options) {
145
+ const { endpoint, fetch } = useFetchOptions(options);
146
+ const reqUrl = makeUrl(endpoint, model, operation, args);
147
+ const queryKey = getQueryKey(model, operation, args, {
148
+ infinite: false,
149
+ optimisticUpdate: options?.optimisticUpdate !== false,
804
150
  });
805
- } else {
806
- return JSON.stringify(data);
807
- }
808
- }
809
- __name(marshal, "marshal");
810
- function unmarshal(value) {
811
- const parsed = JSON.parse(value);
812
- if (typeof parsed === "object" && parsed?.data && parsed?.meta?.serialization) {
813
- const deserializedData = deserialize(parsed.data, parsed.meta.serialization);
814
151
  return {
815
- ...parsed,
816
- data: deserializedData
152
+ queryKey,
153
+ ...useSuspenseQuery({
154
+ queryKey,
155
+ queryFn: ({ signal }) => fetcher(reqUrl, { signal }, fetch),
156
+ ...options,
157
+ }),
817
158
  };
818
- } else {
819
- return parsed;
820
- }
821
159
  }
822
- __name(unmarshal, "unmarshal");
823
- function makeUrl(endpoint, model, operation, args) {
824
- const baseUrl = `${endpoint}/${lowerCaseFirst(model)}/${operation}`;
825
- if (!args) {
826
- return baseUrl;
827
- }
828
- const { data, meta } = serialize(args);
829
- let result = `${baseUrl}?q=${encodeURIComponent(JSON.stringify(data))}`;
830
- if (meta) {
831
- result += `&meta=${encodeURIComponent(JSON.stringify({
832
- serialization: meta
833
- }))}`;
834
- }
835
- return result;
160
+ export function useInternalInfiniteQuery(_schema, model, operation, args, options) {
161
+ options = options ?? { getNextPageParam: () => undefined };
162
+ const { endpoint, fetch } = useFetchOptions(options);
163
+ const queryKey = getQueryKey(model, operation, args, { infinite: true, optimisticUpdate: false });
164
+ return {
165
+ queryKey,
166
+ ...useInfiniteQuery({
167
+ queryKey,
168
+ queryFn: ({ pageParam, signal }) => {
169
+ return fetcher(makeUrl(endpoint, model, operation, pageParam ?? args), { signal }, fetch);
170
+ },
171
+ initialPageParam: args,
172
+ ...options,
173
+ }),
174
+ };
836
175
  }
837
- __name(makeUrl, "makeUrl");
838
- function setupInvalidation(model, operation, schema, options, invalidate, logging = false) {
839
- const origOnSuccess = options?.onSuccess;
840
- options.onSuccess = async (...args) => {
841
- const [_, variables] = args;
842
- const predicate = await getInvalidationPredicate(model, operation, variables, schema, logging);
843
- await invalidate(predicate);
844
- return origOnSuccess?.(...args);
845
- };
176
+ export function useInternalSuspenseInfiniteQuery(_schema, model, operation, args, options) {
177
+ const { endpoint, fetch } = useFetchOptions(options);
178
+ const queryKey = getQueryKey(model, operation, args, { infinite: true, optimisticUpdate: false });
179
+ return {
180
+ queryKey,
181
+ ...useSuspenseInfiniteQuery({
182
+ queryKey,
183
+ queryFn: ({ pageParam, signal }) => {
184
+ return fetcher(makeUrl(endpoint, model, operation, pageParam ?? args), { signal }, fetch);
185
+ },
186
+ initialPageParam: args,
187
+ ...options,
188
+ }),
189
+ };
846
190
  }
847
- __name(setupInvalidation, "setupInvalidation");
848
- async function getInvalidationPredicate(model, operation, mutationArgs, schema, logging = false) {
849
- const mutatedModels = await getMutatedModels(model, operation, mutationArgs, schema);
850
- return ({ queryKey }) => {
851
- const [_, queryModel, , args] = queryKey;
852
- if (mutatedModels.includes(queryModel)) {
853
- if (logging) {
854
- console.log(`Invalidating query ${JSON.stringify(queryKey)} due to mutation "${model}.${operation}"`);
855
- }
856
- return true;
857
- }
858
- if (args) {
859
- if (findNestedRead(queryModel, mutatedModels, schema, args)) {
860
- if (logging) {
861
- console.log(`Invalidating query ${JSON.stringify(queryKey)} due to mutation "${model}.${operation}"`);
191
+ /**
192
+ * Creates a react-query mutation
193
+ *
194
+ * @private
195
+ *
196
+ * @param model The name of the model under mutation.
197
+ * @param method The HTTP method.
198
+ * @param operation The mutation operation (e.g. `create`).
199
+ * @param options The react-query options.
200
+ * @param checkReadBack Whether to check for read back errors and return undefined if found.
201
+ */
202
+ export function useInternalMutation(schema, model, method, operation, options) {
203
+ const { endpoint, fetch, logging } = useFetchOptions(options);
204
+ const queryClient = useQueryClient();
205
+ const mutationFn = (data) => {
206
+ const reqUrl = method === 'DELETE' ? makeUrl(endpoint, model, operation, data) : makeUrl(endpoint, model, operation);
207
+ const fetchInit = {
208
+ method,
209
+ ...(method !== 'DELETE' && {
210
+ headers: {
211
+ 'content-type': 'application/json',
212
+ },
213
+ body: marshal(data),
214
+ }),
215
+ };
216
+ return fetcher(reqUrl, fetchInit, fetch);
217
+ };
218
+ const finalOptions = { ...options, mutationFn };
219
+ const invalidateQueries = options?.invalidateQueries !== false;
220
+ const optimisticUpdate = !!options?.optimisticUpdate;
221
+ if (!optimisticUpdate) {
222
+ // if optimistic update is not enabled, invalidate related queries on success
223
+ if (invalidateQueries) {
224
+ const invalidator = createInvalidator(model, operation, schema, (predicate) => invalidateQueriesMatchingPredicate(queryClient, predicate), logging);
225
+ const origOnSuccess = finalOptions.onSuccess;
226
+ finalOptions.onSuccess = async (...args) => {
227
+ // execute invalidator prior to user-provided onSuccess
228
+ await invalidator(...args);
229
+ // call user-provided onSuccess
230
+ await origOnSuccess?.(...args);
231
+ };
862
232
  }
863
- return true;
864
- }
865
233
  }
866
- return false;
867
- };
868
- }
869
- __name(getInvalidationPredicate, "getInvalidationPredicate");
870
- function findNestedRead(visitingModel, targetModels, schema, args) {
871
- const modelsRead = getReadModels(visitingModel, schema, args);
872
- return targetModels.some((m) => modelsRead.includes(m));
873
- }
874
- __name(findNestedRead, "findNestedRead");
875
- function setupOptimisticUpdate(model, operation, schema, options, queryCache, setCache, invalidate, logging = false) {
876
- const origOnMutate = options?.onMutate;
877
- const origOnSettled = options?.onSettled;
878
- options.onMutate = async (...args) => {
879
- const [variables] = args;
880
- await optimisticUpdate(model, operation, variables, options, schema, queryCache, setCache, logging);
881
- return origOnMutate?.(...args);
882
- };
883
- options.onSettled = async (...args) => {
884
- if (invalidate) {
885
- const [, , variables] = args;
886
- const predicate = await getInvalidationPredicate(model, operation, variables, schema, logging);
887
- await invalidate(predicate);
888
- }
889
- return origOnSettled?.(...args);
890
- };
891
- }
892
- __name(setupOptimisticUpdate, "setupOptimisticUpdate");
893
- async function optimisticUpdate(mutationModel, mutationOp, mutationArgs, options, schema, queryCache, setCache, logging = false) {
894
- for (const cacheItem of queryCache) {
895
- const { queryKey, state: { data, error } } = cacheItem;
896
- if (!isZenStackQueryKey(queryKey)) {
897
- continue;
898
- }
899
- if (error) {
900
- if (logging) {
901
- console.warn(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to error:`, error);
902
- }
903
- continue;
904
- }
905
- const [_, queryModel, queryOperation, queryArgs, queryOptions] = queryKey;
906
- if (!queryOptions?.optimisticUpdate) {
907
- if (logging) {
908
- console.log(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to opt-out`);
909
- }
910
- continue;
911
- }
912
- if (options.optimisticDataProvider) {
913
- const providerResult = await options.optimisticDataProvider({
914
- queryModel,
915
- queryOperation,
916
- queryArgs,
917
- currentData: data,
918
- mutationArgs
919
- });
920
- if (providerResult?.kind === "Skip") {
921
- if (logging) {
922
- console.log(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to provider`);
923
- }
924
- continue;
925
- } else if (providerResult?.kind === "Update") {
926
- if (logging) {
927
- console.log(`Optimistically updating query ${JSON.stringify(queryKey)} due to provider`);
234
+ else {
235
+ // schedule optimistic update on mutate
236
+ const optimisticUpdater = createOptimisticUpdater(model, operation, schema, { optimisticDataProvider: finalOptions.optimisticDataProvider }, () => getAllQueries(queryClient), logging);
237
+ const origOnMutate = finalOptions.onMutate;
238
+ finalOptions.onMutate = async (...args) => {
239
+ // execute optimistic update
240
+ await optimisticUpdater(...args);
241
+ // call user-provided onMutate
242
+ return origOnMutate?.(...args);
243
+ };
244
+ if (invalidateQueries) {
245
+ // invalidate related queries on settled (success or error)
246
+ const invalidator = createInvalidator(model, operation, schema, (predicate) => invalidateQueriesMatchingPredicate(queryClient, predicate), logging);
247
+ const origOnSettled = finalOptions.onSettled;
248
+ finalOptions.onSettled = async (...args) => {
249
+ // execute invalidator prior to user-provided onSettled
250
+ await invalidator(...args);
251
+ // call user-provided onSettled
252
+ return origOnSettled?.(...args);
253
+ };
928
254
  }
929
- setCache(queryKey, providerResult.data);
930
- continue;
931
- }
932
- }
933
- const mutatedData = await applyMutation(queryModel, queryOperation, data, mutationModel, mutationOp, mutationArgs, schema, logging);
934
- if (mutatedData !== void 0) {
935
- if (logging) {
936
- console.log(`Optimistically updating query ${JSON.stringify(queryKey)} due to mutation "${mutationModel}.${mutationOp}"`);
937
- }
938
- setCache(queryKey, mutatedData);
939
255
  }
940
- }
941
- }
942
- __name(optimisticUpdate, "optimisticUpdate");
943
- function isZenStackQueryKey(queryKey) {
944
- if (queryKey.length < 5) {
945
- return false;
946
- }
947
- if (queryKey[0] !== QUERY_KEY_PREFIX) {
948
- return false;
949
- }
950
- return true;
951
- }
952
- __name(isZenStackQueryKey, "isZenStackQueryKey");
953
-
954
- // src/react.ts
955
- var DEFAULT_QUERY_ENDPOINT = "/api/model";
956
- var QuerySettingsContext = createContext({
957
- endpoint: DEFAULT_QUERY_ENDPOINT,
958
- fetch: void 0
959
- });
960
- var QuerySettingsProvider = QuerySettingsContext.Provider;
961
- var Provider = QuerySettingsProvider;
962
- function useHooksContext() {
963
- const { endpoint, ...rest } = useContext(QuerySettingsContext);
964
- return {
965
- endpoint: endpoint ?? DEFAULT_QUERY_ENDPOINT,
966
- ...rest
967
- };
968
- }
969
- __name(useHooksContext, "useHooksContext");
970
- function useClientQueries(schema) {
971
- return Object.keys(schema.models).reduce((acc, model) => {
972
- acc[lowerCaseFirst2(model)] = useModelQueries(schema, model);
973
- return acc;
974
- }, {});
975
- }
976
- __name(useClientQueries, "useClientQueries");
977
- function useModelQueries(schema, model) {
978
- const modelDef = Object.values(schema.models).find((m) => m.name.toLowerCase() === model.toLowerCase());
979
- if (!modelDef) {
980
- throw new Error(`Model "${model}" not found in schema`);
981
- }
982
- const modelName = modelDef.name;
983
- return {
984
- useFindUnique: /* @__PURE__ */ __name((args, options) => {
985
- return useInternalQuery(schema, modelName, "findUnique", args, options);
986
- }, "useFindUnique"),
987
- useSuspenseFindUnique: /* @__PURE__ */ __name((args, options) => {
988
- return useInternalSuspenseQuery(schema, modelName, "findUnique", args, options);
989
- }, "useSuspenseFindUnique"),
990
- useFindFirst: /* @__PURE__ */ __name((args, options) => {
991
- return useInternalQuery(schema, modelName, "findFirst", args, options);
992
- }, "useFindFirst"),
993
- useSuspenseFindFirst: /* @__PURE__ */ __name((args, options) => {
994
- return useInternalSuspenseQuery(schema, modelName, "findFirst", args, options);
995
- }, "useSuspenseFindFirst"),
996
- useFindMany: /* @__PURE__ */ __name((args, options) => {
997
- return useInternalQuery(schema, modelName, "findMany", args, options);
998
- }, "useFindMany"),
999
- useSuspenseFindMany: /* @__PURE__ */ __name((args, options) => {
1000
- return useInternalSuspenseQuery(schema, modelName, "findMany", args, options);
1001
- }, "useSuspenseFindMany"),
1002
- useInfiniteFindMany: /* @__PURE__ */ __name((args, options) => {
1003
- return useInternalInfiniteQuery(schema, modelName, "findMany", args, options);
1004
- }, "useInfiniteFindMany"),
1005
- useSuspenseInfiniteFindMany: /* @__PURE__ */ __name((args, options) => {
1006
- return useInternalSuspenseInfiniteQuery(schema, modelName, "findMany", args, options);
1007
- }, "useSuspenseInfiniteFindMany"),
1008
- useCreate: /* @__PURE__ */ __name((options) => {
1009
- return useInternalMutation(schema, modelName, "POST", "create", options);
1010
- }, "useCreate"),
1011
- useCreateMany: /* @__PURE__ */ __name((options) => {
1012
- return useInternalMutation(schema, modelName, "POST", "createMany", options);
1013
- }, "useCreateMany"),
1014
- useCreateManyAndReturn: /* @__PURE__ */ __name((options) => {
1015
- return useInternalMutation(schema, modelName, "POST", "createManyAndReturn", options);
1016
- }, "useCreateManyAndReturn"),
1017
- useUpdate: /* @__PURE__ */ __name((options) => {
1018
- return useInternalMutation(schema, modelName, "PUT", "update", options);
1019
- }, "useUpdate"),
1020
- useUpdateMany: /* @__PURE__ */ __name((options) => {
1021
- return useInternalMutation(schema, modelName, "PUT", "updateMany", options);
1022
- }, "useUpdateMany"),
1023
- useUpdateManyAndReturn: /* @__PURE__ */ __name((options) => {
1024
- return useInternalMutation(schema, modelName, "PUT", "updateManyAndReturn", options);
1025
- }, "useUpdateManyAndReturn"),
1026
- useUpsert: /* @__PURE__ */ __name((options) => {
1027
- return useInternalMutation(schema, modelName, "POST", "upsert", options);
1028
- }, "useUpsert"),
1029
- useDelete: /* @__PURE__ */ __name((options) => {
1030
- return useInternalMutation(schema, modelName, "DELETE", "delete", options);
1031
- }, "useDelete"),
1032
- useDeleteMany: /* @__PURE__ */ __name((options) => {
1033
- return useInternalMutation(schema, modelName, "DELETE", "deleteMany", options);
1034
- }, "useDeleteMany"),
1035
- useCount: /* @__PURE__ */ __name((args, options) => {
1036
- return useInternalQuery(schema, modelName, "count", args, options);
1037
- }, "useCount"),
1038
- useSuspenseCount: /* @__PURE__ */ __name((args, options) => {
1039
- return useInternalSuspenseQuery(schema, modelName, "count", args, options);
1040
- }, "useSuspenseCount"),
1041
- useAggregate: /* @__PURE__ */ __name((args, options) => {
1042
- return useInternalQuery(schema, modelName, "aggregate", args, options);
1043
- }, "useAggregate"),
1044
- useSuspenseAggregate: /* @__PURE__ */ __name((args, options) => {
1045
- return useInternalSuspenseQuery(schema, modelName, "aggregate", args, options);
1046
- }, "useSuspenseAggregate"),
1047
- useGroupBy: /* @__PURE__ */ __name((args, options) => {
1048
- return useInternalQuery(schema, modelName, "groupBy", args, options);
1049
- }, "useGroupBy"),
1050
- useSuspenseGroupBy: /* @__PURE__ */ __name((args, options) => {
1051
- return useInternalSuspenseQuery(schema, modelName, "groupBy", args, options);
1052
- }, "useSuspenseGroupBy")
1053
- };
256
+ return useMutation(finalOptions);
1054
257
  }
1055
- __name(useModelQueries, "useModelQueries");
1056
- function useInternalQuery(_schema, model, operation, args, options) {
1057
- const { endpoint, fetch: fetch2 } = useHooksContext();
1058
- const reqUrl = makeUrl(endpoint, model, operation, args);
1059
- const queryKey = getQueryKey(model, operation, args, {
1060
- infinite: false,
1061
- optimisticUpdate: options?.optimisticUpdate !== false
1062
- });
1063
- return {
1064
- queryKey,
1065
- ...useQuery({
1066
- queryKey,
1067
- queryFn: /* @__PURE__ */ __name(({ signal }) => fetcher(reqUrl, {
1068
- signal
1069
- }, fetch2), "queryFn"),
1070
- ...options
1071
- })
1072
- };
1073
- }
1074
- __name(useInternalQuery, "useInternalQuery");
1075
- function useInternalSuspenseQuery(_schema, model, operation, args, options) {
1076
- const { endpoint, fetch: fetch2 } = useHooksContext();
1077
- const reqUrl = makeUrl(endpoint, model, operation, args);
1078
- const queryKey = getQueryKey(model, operation, args, {
1079
- infinite: false,
1080
- optimisticUpdate: options?.optimisticUpdate !== false
1081
- });
1082
- return {
1083
- queryKey,
1084
- ...useSuspenseQuery({
1085
- queryKey,
1086
- queryFn: /* @__PURE__ */ __name(({ signal }) => fetcher(reqUrl, {
1087
- signal
1088
- }, fetch2), "queryFn"),
1089
- ...options
1090
- })
1091
- };
1092
- }
1093
- __name(useInternalSuspenseQuery, "useInternalSuspenseQuery");
1094
- function useInternalInfiniteQuery(_schema, model, operation, args, options) {
1095
- options = options ?? {
1096
- getNextPageParam: /* @__PURE__ */ __name(() => void 0, "getNextPageParam")
1097
- };
1098
- const { endpoint, fetch: fetch2 } = useHooksContext();
1099
- const queryKey = getQueryKey(model, operation, args, {
1100
- infinite: true,
1101
- optimisticUpdate: false
1102
- });
1103
- return {
1104
- queryKey,
1105
- ...useInfiniteQuery({
1106
- queryKey,
1107
- queryFn: /* @__PURE__ */ __name(({ pageParam, signal }) => {
1108
- return fetcher(makeUrl(endpoint, model, operation, pageParam ?? args), {
1109
- signal
1110
- }, fetch2);
1111
- }, "queryFn"),
1112
- initialPageParam: args,
1113
- ...options
1114
- })
1115
- };
1116
- }
1117
- __name(useInternalInfiniteQuery, "useInternalInfiniteQuery");
1118
- function useInternalSuspenseInfiniteQuery(_schema, model, operation, args, options) {
1119
- const { endpoint, fetch: fetch2 } = useHooksContext();
1120
- const queryKey = getQueryKey(model, operation, args, {
1121
- infinite: true,
1122
- optimisticUpdate: false
1123
- });
1124
- return {
1125
- queryKey,
1126
- ...useSuspenseInfiniteQuery({
1127
- queryKey,
1128
- queryFn: /* @__PURE__ */ __name(({ pageParam, signal }) => {
1129
- return fetcher(makeUrl(endpoint, model, operation, pageParam ?? args), {
1130
- signal
1131
- }, fetch2);
1132
- }, "queryFn"),
1133
- initialPageParam: args,
1134
- ...options
1135
- })
1136
- };
1137
- }
1138
- __name(useInternalSuspenseInfiniteQuery, "useInternalSuspenseInfiniteQuery");
1139
- function useInternalMutation(schema, model, method, operation, options) {
1140
- const { endpoint, fetch: fetch2, logging } = useHooksContext();
1141
- const queryClient = useQueryClient();
1142
- const mutationFn = /* @__PURE__ */ __name((data) => {
1143
- const reqUrl = method === "DELETE" ? makeUrl(endpoint, model, operation, data) : makeUrl(endpoint, model, operation);
1144
- const fetchInit = {
1145
- method,
1146
- ...method !== "DELETE" && {
1147
- headers: {
1148
- "content-type": "application/json"
1149
- },
1150
- body: marshal(data)
1151
- }
258
+ function useFetchOptions(options) {
259
+ const { endpoint, fetch, logging } = useHooksContext();
260
+ // options take precedence over context
261
+ return {
262
+ endpoint: options?.endpoint ?? endpoint,
263
+ fetch: options?.fetch ?? fetch,
264
+ logging: options?.logging ?? logging,
1152
265
  };
1153
- return fetcher(reqUrl, fetchInit, fetch2);
1154
- }, "mutationFn");
1155
- const finalOptions = {
1156
- ...options,
1157
- mutationFn
1158
- };
1159
- const invalidateQueries = options?.invalidateQueries !== false;
1160
- const optimisticUpdate2 = !!options?.optimisticUpdate;
1161
- if (operation) {
1162
- if (invalidateQueries) {
1163
- setupInvalidation(model, operation, schema, finalOptions, (predicate) => queryClient.invalidateQueries({
1164
- predicate
1165
- }), logging);
1166
- }
1167
- if (optimisticUpdate2) {
1168
- setupOptimisticUpdate(model, operation, schema, finalOptions, queryClient.getQueryCache().getAll(), (queryKey, data) => {
1169
- queryClient.setQueryData(queryKey, data);
1170
- queryClient.cancelQueries({
1171
- queryKey
1172
- }, {
1173
- revert: false,
1174
- silent: true
1175
- });
1176
- }, invalidateQueries ? (predicate) => queryClient.invalidateQueries({
1177
- predicate
1178
- }) : void 0, logging);
1179
- }
1180
- }
1181
- return useMutation(finalOptions);
1182
266
  }
1183
- __name(useInternalMutation, "useInternalMutation");
1184
- export {
1185
- DEFAULT_QUERY_ENDPOINT,
1186
- Provider,
1187
- QuerySettingsContext,
1188
- QuerySettingsProvider,
1189
- useClientQueries,
1190
- useInternalInfiniteQuery,
1191
- useInternalMutation,
1192
- useInternalQuery,
1193
- useInternalSuspenseInfiniteQuery,
1194
- useInternalSuspenseQuery,
1195
- useModelQueries
1196
- };
1197
267
  //# sourceMappingURL=react.js.map