@zenstackhq/tanstack-query 2.21.0 → 3.0.0-beta.17

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