zodvex 0.2.4 → 0.3.1

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.
package/dist/index.mjs DELETED
@@ -1,1001 +0,0 @@
1
- import { NoOp } from 'convex-helpers/server/customFunctions';
2
- export { customCtx } from 'convex-helpers/server/customFunctions';
3
- import { z } from 'zod';
4
- import { v, ConvexError } from 'convex/values';
5
- import { Table } from 'convex-helpers/server';
6
-
7
- var metadata = /* @__PURE__ */ new WeakMap();
8
- var registryHelpers = {
9
- getMetadata: (type) => metadata.get(type),
10
- setMetadata: (type, meta) => metadata.set(type, meta)
11
- };
12
- function zid(tableName) {
13
- const baseSchema = z.string().refine((val) => typeof val === "string" && val.length > 0, {
14
- message: `Invalid ID for table "${tableName}"`
15
- }).transform((val) => {
16
- return val;
17
- }).brand(`ConvexId_${tableName}`).describe(`convexId:${tableName}`);
18
- registryHelpers.setMetadata(baseSchema, {
19
- isConvexId: true,
20
- tableName
21
- });
22
- const branded = baseSchema;
23
- branded._tableName = tableName;
24
- return branded;
25
- }
26
- var baseCodecs = [];
27
- function registerBaseCodec(codec) {
28
- baseCodecs.unshift(codec);
29
- }
30
- function findBaseCodec(schema) {
31
- return baseCodecs.find((codec) => codec.check(schema));
32
- }
33
- registerBaseCodec({
34
- check: (schema) => schema instanceof z.ZodDate,
35
- toValidator: () => v.float64(),
36
- fromConvex: (value) => {
37
- if (typeof value === "number") {
38
- return new Date(value);
39
- }
40
- return value;
41
- },
42
- toConvex: (value) => {
43
- if (value instanceof Date) {
44
- return value.getTime();
45
- }
46
- return value;
47
- }
48
- });
49
- function asZodType(schema) {
50
- return schema;
51
- }
52
- function isDateSchema(schema) {
53
- if (schema instanceof z.ZodDate) return true;
54
- if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {
55
- return isDateSchema(asZodType(schema.unwrap()));
56
- }
57
- return false;
58
- }
59
- function convertEnumType(actualValidator) {
60
- const options = actualValidator.options;
61
- if (options && Array.isArray(options) && options.length > 0) {
62
- const validLiterals = options.filter((opt) => opt !== void 0 && opt !== null).map((opt) => v.literal(opt));
63
- if (validLiterals.length === 1) {
64
- const [first] = validLiterals;
65
- return first;
66
- } else if (validLiterals.length >= 2) {
67
- const [first, second, ...rest] = validLiterals;
68
- return v.union(
69
- first,
70
- second,
71
- ...rest
72
- );
73
- } else {
74
- return v.any();
75
- }
76
- } else {
77
- return v.any();
78
- }
79
- }
80
- function convertNullableType(actualValidator, visited, zodToConvexInternal2) {
81
- const innerSchema = actualValidator.unwrap();
82
- if (innerSchema && innerSchema instanceof z.ZodType) {
83
- if (innerSchema instanceof z.ZodOptional) {
84
- const innerInnerSchema = innerSchema.unwrap();
85
- const innerInnerValidator = zodToConvexInternal2(innerInnerSchema, visited);
86
- return {
87
- validator: v.union(innerInnerValidator, v.null()),
88
- isOptional: true
89
- // Mark as optional so it gets wrapped later
90
- };
91
- } else {
92
- const innerValidator = zodToConvexInternal2(innerSchema, visited);
93
- return {
94
- validator: v.union(innerValidator, v.null()),
95
- isOptional: false
96
- };
97
- }
98
- } else {
99
- return {
100
- validator: v.any(),
101
- isOptional: false
102
- };
103
- }
104
- }
105
- function convertRecordType(actualValidator, visited, zodToConvexInternal2) {
106
- let valueType = actualValidator._def?.valueType;
107
- if (!valueType) {
108
- valueType = actualValidator._def?.keyType;
109
- }
110
- if (valueType && valueType instanceof z.ZodType) {
111
- const isZodOptional = valueType instanceof z.ZodOptional || valueType instanceof z.ZodDefault || valueType instanceof z.ZodDefault && valueType.def.innerType instanceof z.ZodOptional;
112
- if (isZodOptional) {
113
- let innerType;
114
- let recordDefaultValue = void 0;
115
- let recordHasDefault = false;
116
- if (valueType instanceof z.ZodDefault) {
117
- recordHasDefault = true;
118
- recordDefaultValue = valueType.def.defaultValue;
119
- const innerFromDefault = valueType.def.innerType;
120
- if (innerFromDefault instanceof z.ZodOptional) {
121
- innerType = innerFromDefault.unwrap();
122
- } else {
123
- innerType = innerFromDefault;
124
- }
125
- } else if (valueType instanceof z.ZodOptional) {
126
- innerType = valueType.unwrap();
127
- } else {
128
- innerType = valueType;
129
- }
130
- const innerConvex = zodToConvexInternal2(innerType, visited);
131
- const unionValidator = v.union(innerConvex, v.null());
132
- if (recordHasDefault) {
133
- unionValidator._zodDefault = recordDefaultValue;
134
- }
135
- return v.record(v.string(), unionValidator);
136
- } else {
137
- return v.record(v.string(), zodToConvexInternal2(valueType, visited));
138
- }
139
- } else {
140
- return v.record(v.string(), v.any());
141
- }
142
- }
143
- function convertDiscriminatedUnionType(actualValidator, visited, zodToConvexInternal2) {
144
- const options = actualValidator.def?.options || actualValidator.def?.optionsMap?.values();
145
- if (options) {
146
- const opts = Array.isArray(options) ? options : Array.from(options);
147
- if (opts.length >= 2) {
148
- const convexOptions = opts.map((opt) => {
149
- const branchVisited = new Set(visited);
150
- return zodToConvexInternal2(opt, branchVisited);
151
- });
152
- const [first, second, ...rest] = convexOptions;
153
- return v.union(
154
- first,
155
- second,
156
- ...rest
157
- );
158
- } else {
159
- return v.any();
160
- }
161
- } else {
162
- return v.any();
163
- }
164
- }
165
- function convertUnionType(actualValidator, visited, zodToConvexInternal2) {
166
- const options = actualValidator.options;
167
- if (options && Array.isArray(options) && options.length > 0) {
168
- if (options.length === 1) {
169
- return zodToConvexInternal2(options[0], visited);
170
- } else {
171
- const convexOptions = options.map((opt) => {
172
- const branchVisited = new Set(visited);
173
- return zodToConvexInternal2(opt, branchVisited);
174
- });
175
- if (convexOptions.length >= 2) {
176
- const [first, second, ...rest] = convexOptions;
177
- return v.union(
178
- first,
179
- second,
180
- ...rest
181
- );
182
- } else {
183
- return v.any();
184
- }
185
- }
186
- } else {
187
- return v.any();
188
- }
189
- }
190
- function isZid(schema) {
191
- const metadata2 = registryHelpers.getMetadata(schema);
192
- return metadata2?.isConvexId === true && metadata2?.tableName && typeof metadata2.tableName === "string";
193
- }
194
- function makeUnion(members) {
195
- const nonNull = members.filter(Boolean);
196
- if (nonNull.length === 0) return v.any();
197
- if (nonNull.length === 1) return nonNull[0];
198
- return v.union(nonNull[0], nonNull[1], ...nonNull.slice(2));
199
- }
200
- function getObjectShape(obj) {
201
- if (obj instanceof z.ZodObject) {
202
- return obj.shape;
203
- }
204
- if (obj && typeof obj === "object" && typeof obj.shape === "object") {
205
- return obj.shape;
206
- }
207
- return {};
208
- }
209
-
210
- // src/mapping/core.ts
211
- function zodToConvexInternal(zodValidator, visited = /* @__PURE__ */ new Set()) {
212
- if (!zodValidator) {
213
- return v.any();
214
- }
215
- if (visited.has(zodValidator)) {
216
- return v.any();
217
- }
218
- visited.add(zodValidator);
219
- let actualValidator = zodValidator;
220
- let isOptional = false;
221
- let defaultValue = void 0;
222
- let hasDefault = false;
223
- if (zodValidator instanceof z.ZodDefault) {
224
- hasDefault = true;
225
- defaultValue = zodValidator.def?.defaultValue;
226
- actualValidator = zodValidator.def?.innerType;
227
- }
228
- if (actualValidator instanceof z.ZodOptional) {
229
- isOptional = true;
230
- actualValidator = actualValidator.unwrap();
231
- if (actualValidator instanceof z.ZodDefault) {
232
- hasDefault = true;
233
- defaultValue = actualValidator.def?.defaultValue;
234
- actualValidator = actualValidator.def?.innerType;
235
- }
236
- }
237
- let convexValidator;
238
- if (isZid(actualValidator)) {
239
- const metadata2 = registryHelpers.getMetadata(actualValidator);
240
- const tableName = metadata2?.tableName || "unknown";
241
- convexValidator = v.id(tableName);
242
- } else {
243
- const defType = actualValidator.def?.type;
244
- switch (defType) {
245
- case "string":
246
- convexValidator = v.string();
247
- break;
248
- case "number":
249
- convexValidator = v.float64();
250
- break;
251
- case "bigint":
252
- convexValidator = v.int64();
253
- break;
254
- case "boolean":
255
- convexValidator = v.boolean();
256
- break;
257
- case "date":
258
- convexValidator = v.float64();
259
- break;
260
- case "null":
261
- convexValidator = v.null();
262
- break;
263
- case "nan":
264
- convexValidator = v.float64();
265
- break;
266
- case "array": {
267
- if (actualValidator instanceof z.ZodArray) {
268
- const element = actualValidator.element;
269
- if (element && element instanceof z.ZodType) {
270
- convexValidator = v.array(zodToConvexInternal(element, visited));
271
- } else {
272
- convexValidator = v.array(v.any());
273
- }
274
- } else {
275
- convexValidator = v.array(v.any());
276
- }
277
- break;
278
- }
279
- case "object": {
280
- if (actualValidator instanceof z.ZodObject) {
281
- const shape = actualValidator.shape;
282
- const convexShape = {};
283
- for (const [key, value] of Object.entries(shape)) {
284
- if (value && value instanceof z.ZodType) {
285
- convexShape[key] = zodToConvexInternal(value, visited);
286
- }
287
- }
288
- convexValidator = v.object(convexShape);
289
- } else {
290
- convexValidator = v.object({});
291
- }
292
- break;
293
- }
294
- case "union": {
295
- if (actualValidator instanceof z.ZodUnion) {
296
- convexValidator = convertUnionType(actualValidator, visited, zodToConvexInternal);
297
- } else {
298
- convexValidator = v.any();
299
- }
300
- break;
301
- }
302
- case "discriminatedUnion": {
303
- convexValidator = convertDiscriminatedUnionType(
304
- actualValidator,
305
- visited,
306
- zodToConvexInternal
307
- );
308
- break;
309
- }
310
- case "literal": {
311
- if (actualValidator instanceof z.ZodLiteral) {
312
- const literalValue = actualValidator.value;
313
- if (literalValue !== void 0 && literalValue !== null) {
314
- convexValidator = v.literal(literalValue);
315
- } else {
316
- convexValidator = v.any();
317
- }
318
- } else {
319
- convexValidator = v.any();
320
- }
321
- break;
322
- }
323
- case "enum": {
324
- if (actualValidator instanceof z.ZodEnum) {
325
- convexValidator = convertEnumType(actualValidator);
326
- } else {
327
- convexValidator = v.any();
328
- }
329
- break;
330
- }
331
- case "record": {
332
- if (actualValidator instanceof z.ZodRecord) {
333
- convexValidator = convertRecordType(actualValidator, visited, zodToConvexInternal);
334
- } else {
335
- convexValidator = v.record(v.string(), v.any());
336
- }
337
- break;
338
- }
339
- case "transform":
340
- case "pipe": {
341
- const codec = findBaseCodec(actualValidator);
342
- if (codec) {
343
- convexValidator = codec.toValidator(actualValidator);
344
- } else {
345
- const metadata2 = registryHelpers.getMetadata(actualValidator);
346
- if (metadata2?.brand && metadata2?.originalSchema) {
347
- convexValidator = zodToConvexInternal(metadata2.originalSchema, visited);
348
- } else {
349
- convexValidator = v.any();
350
- }
351
- }
352
- break;
353
- }
354
- case "nullable": {
355
- if (actualValidator instanceof z.ZodNullable) {
356
- const result = convertNullableType(actualValidator, visited, zodToConvexInternal);
357
- convexValidator = result.validator;
358
- if (result.isOptional) {
359
- isOptional = true;
360
- }
361
- } else {
362
- convexValidator = v.any();
363
- }
364
- break;
365
- }
366
- case "tuple": {
367
- if (actualValidator instanceof z.ZodTuple) {
368
- const items = actualValidator.def?.items;
369
- if (items && items.length > 0) {
370
- const convexShape = {};
371
- items.forEach((item, index) => {
372
- convexShape[`_${index}`] = zodToConvexInternal(item, visited);
373
- });
374
- convexValidator = v.object(convexShape);
375
- } else {
376
- convexValidator = v.object({});
377
- }
378
- } else {
379
- convexValidator = v.object({});
380
- }
381
- break;
382
- }
383
- case "lazy": {
384
- if (actualValidator instanceof z.ZodLazy) {
385
- try {
386
- const getter = actualValidator.def?.getter;
387
- if (getter) {
388
- const resolvedSchema = getter();
389
- if (resolvedSchema && resolvedSchema instanceof z.ZodType) {
390
- convexValidator = zodToConvexInternal(resolvedSchema, visited);
391
- } else {
392
- convexValidator = v.any();
393
- }
394
- } else {
395
- convexValidator = v.any();
396
- }
397
- } catch {
398
- convexValidator = v.any();
399
- }
400
- } else {
401
- convexValidator = v.any();
402
- }
403
- break;
404
- }
405
- case "any":
406
- convexValidator = v.any();
407
- break;
408
- case "unknown":
409
- convexValidator = v.any();
410
- break;
411
- case "undefined":
412
- case "void":
413
- case "never":
414
- convexValidator = v.any();
415
- break;
416
- case "intersection":
417
- convexValidator = v.any();
418
- break;
419
- default:
420
- if (process.env.NODE_ENV !== "production") {
421
- console.warn(
422
- `[zodvex] Unrecognized Zod type "${defType}" encountered. Falling back to v.any().`,
423
- "Schema:",
424
- actualValidator
425
- );
426
- }
427
- convexValidator = v.any();
428
- break;
429
- }
430
- }
431
- const finalValidator = isOptional || hasDefault ? v.optional(convexValidator) : convexValidator;
432
- if (hasDefault && typeof finalValidator === "object" && finalValidator !== null) {
433
- finalValidator._zodDefault = defaultValue;
434
- }
435
- return finalValidator;
436
- }
437
- function zodToConvex(zod) {
438
- if (typeof zod === "object" && zod !== null && !(zod instanceof z.ZodType)) {
439
- return zodToConvexFields(zod);
440
- }
441
- return zodToConvexInternal(zod);
442
- }
443
- function zodToConvexFields(zod) {
444
- const fields = zod instanceof z.ZodObject ? zod.shape : zod;
445
- const result = {};
446
- for (const [key, value] of Object.entries(fields)) {
447
- result[key] = zodToConvexInternal(value);
448
- }
449
- return result;
450
- }
451
-
452
- // src/codec.ts
453
- function asZodType2(schema) {
454
- return schema;
455
- }
456
- function convexCodec(schema) {
457
- const validator = zodToConvex(schema);
458
- return {
459
- validator,
460
- encode: (value) => toConvexJS(schema, value),
461
- decode: (value) => fromConvexJS(value, schema),
462
- pick: (keys) => {
463
- if (!(schema instanceof z.ZodObject)) {
464
- throw new Error("pick() can only be called on object schemas");
465
- }
466
- const pickObj = Array.isArray(keys) ? keys.reduce((acc, k) => ({ ...acc, [k]: true }), {}) : keys;
467
- const pickedSchema = schema.pick(pickObj);
468
- return convexCodec(pickedSchema);
469
- }
470
- };
471
- }
472
- function toConvexJS(schema, value) {
473
- if (!schema || arguments.length === 1) {
474
- value = schema;
475
- return basicToConvex(value);
476
- }
477
- return schemaToConvex(value, schema);
478
- }
479
- function basicToConvex(value) {
480
- if (value === void 0) return void 0;
481
- if (value === null) return null;
482
- if (value instanceof Date) return value.getTime();
483
- if (Array.isArray(value)) {
484
- return value.map(basicToConvex);
485
- }
486
- if (value && typeof value === "object") {
487
- const result = {};
488
- for (const [k, v8] of Object.entries(value)) {
489
- if (v8 !== void 0) {
490
- result[k] = basicToConvex(v8);
491
- }
492
- }
493
- return result;
494
- }
495
- return value;
496
- }
497
- function schemaToConvex(value, schema) {
498
- if (value === void 0 || value === null) return value;
499
- const codec = findBaseCodec(schema);
500
- if (codec) {
501
- return codec.toConvex(value, schema);
502
- }
503
- if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable || schema instanceof z.ZodDefault) {
504
- const inner = schema.unwrap();
505
- return schemaToConvex(value, asZodType2(inner));
506
- }
507
- if (schema instanceof z.ZodDate && value instanceof Date) {
508
- return value.getTime();
509
- }
510
- if (schema instanceof z.ZodArray) {
511
- if (!Array.isArray(value)) return value;
512
- return value.map((item) => schemaToConvex(item, schema.element));
513
- }
514
- if (schema instanceof z.ZodObject) {
515
- if (!value || typeof value !== "object") return value;
516
- const shape = schema.shape;
517
- const result = {};
518
- for (const [k, v8] of Object.entries(value)) {
519
- if (v8 !== void 0) {
520
- result[k] = shape[k] ? schemaToConvex(v8, shape[k]) : basicToConvex(v8);
521
- }
522
- }
523
- return result;
524
- }
525
- if (schema instanceof z.ZodUnion) {
526
- for (const option of schema.options) {
527
- try {
528
- ;
529
- option.parse(value);
530
- return schemaToConvex(value, option);
531
- } catch {
532
- }
533
- }
534
- }
535
- if (schema instanceof z.ZodRecord) {
536
- if (!value || typeof value !== "object") return value;
537
- const result = {};
538
- for (const [k, v8] of Object.entries(value)) {
539
- if (v8 !== void 0) {
540
- result[k] = schemaToConvex(v8, schema.valueType);
541
- }
542
- }
543
- return result;
544
- }
545
- return basicToConvex(value);
546
- }
547
- function fromConvexJS(value, schema) {
548
- if (value === void 0 || value === null) return value;
549
- const codec = findBaseCodec(schema);
550
- if (codec) {
551
- return codec.fromConvex(value, schema);
552
- }
553
- if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable || schema instanceof z.ZodDefault) {
554
- const inner = schema.unwrap();
555
- return fromConvexJS(value, asZodType2(inner));
556
- }
557
- if (schema instanceof z.ZodDate && typeof value === "number") {
558
- return new Date(value);
559
- }
560
- if (isDateSchema(schema) && typeof value === "number") {
561
- return new Date(value);
562
- }
563
- if (schema instanceof z.ZodArray) {
564
- if (!Array.isArray(value)) return value;
565
- return value.map((item) => fromConvexJS(item, schema.element));
566
- }
567
- if (schema instanceof z.ZodObject) {
568
- if (!value || typeof value !== "object") return value;
569
- const shape = schema.shape;
570
- const result = {};
571
- for (const [k, v8] of Object.entries(value)) {
572
- result[k] = shape[k] ? fromConvexJS(v8, shape[k]) : v8;
573
- }
574
- return result;
575
- }
576
- if (schema instanceof z.ZodUnion) {
577
- for (const option of schema.options) {
578
- try {
579
- const decoded = fromConvexJS(value, option);
580
- option.parse(decoded);
581
- return decoded;
582
- } catch {
583
- }
584
- }
585
- }
586
- if (schema instanceof z.ZodRecord) {
587
- if (!value || typeof value !== "object") return value;
588
- const result = {};
589
- for (const [k, v8] of Object.entries(value)) {
590
- result[k] = fromConvexJS(v8, schema.valueType);
591
- }
592
- return result;
593
- }
594
- if (schema instanceof z.ZodTransform) {
595
- return value;
596
- }
597
- return value;
598
- }
599
- function pick(obj, keys) {
600
- const result = {};
601
- for (const key of keys) {
602
- if (key in obj) result[key] = obj[key];
603
- }
604
- return result;
605
- }
606
- function returnsAs() {
607
- return (v8) => v8;
608
- }
609
- function formatZodIssues(error, context) {
610
- return {
611
- error: "ZodValidationError",
612
- context,
613
- issues: error.issues.map((issue) => ({
614
- path: Array.isArray(issue.path) ? issue.path.join(".") : String(issue.path ?? ""),
615
- code: issue.code,
616
- message: issue.message
617
- })),
618
- // Keep a flattened snapshot for easier debugging without cyclic refs
619
- flatten: JSON.parse(JSON.stringify(error.flatten?.() ?? {}))
620
- };
621
- }
622
- function handleZodValidationError(e, context) {
623
- if (e instanceof z.ZodError) {
624
- throw new ConvexError(formatZodIssues(e, context));
625
- }
626
- throw e;
627
- }
628
- function zPaginated(item) {
629
- return z.object({
630
- page: z.array(item),
631
- isDone: z.boolean(),
632
- continueCursor: z.string().nullable().optional()
633
- });
634
- }
635
- function mapDateFieldToNumber(field) {
636
- if (field instanceof z.ZodDate) {
637
- return z.number();
638
- }
639
- if (field instanceof z.ZodOptional && field.unwrap() instanceof z.ZodDate) {
640
- return z.number().optional();
641
- }
642
- if (field instanceof z.ZodNullable && field.unwrap() instanceof z.ZodDate) {
643
- return z.number().nullable();
644
- }
645
- if (field instanceof z.ZodDefault) {
646
- const inner = field.removeDefault();
647
- if (inner instanceof z.ZodDate) {
648
- return z.number().optional();
649
- }
650
- }
651
- return field;
652
- }
653
- function toKeys(mask) {
654
- if (Array.isArray(mask)) return mask.map(String);
655
- return Object.keys(mask).filter((k) => !!mask[k]);
656
- }
657
- function pickShape(schemaOrShape, mask) {
658
- const keys = toKeys(mask);
659
- const shape = schemaOrShape instanceof z.ZodObject ? getObjectShape(schemaOrShape) : schemaOrShape || {};
660
- const out = {};
661
- for (const k of keys) {
662
- if (k in shape) out[k] = shape[k];
663
- }
664
- return out;
665
- }
666
- function safePick(schema, mask) {
667
- return z.object(pickShape(schema, mask));
668
- }
669
- function safeOmit(schema, mask) {
670
- const shape = getObjectShape(schema);
671
- const omit = new Set(toKeys(mask));
672
- const keep = Object.keys(shape).filter((k) => !omit.has(k));
673
- const picked = pickShape(schema, keep);
674
- return z.object(picked);
675
- }
676
-
677
- // src/custom.ts
678
- function customFnBuilder(builder, customization) {
679
- const customInput = customization.input ?? NoOp.input;
680
- const inputArgs = customization.args ?? NoOp.args;
681
- return function customBuilder(fn) {
682
- const { args, handler = fn, returns: maybeObject, ...extra } = fn;
683
- const returns = maybeObject && !(maybeObject instanceof z.ZodType) ? z.object(maybeObject) : maybeObject;
684
- const returnValidator = returns && !fn.skipConvexValidation ? { returns: zodToConvex(returns) } : void 0;
685
- if (args && !fn.skipConvexValidation) {
686
- let argsValidator = args;
687
- let argsSchema;
688
- if (argsValidator instanceof z.ZodType) {
689
- if (argsValidator instanceof z.ZodObject) {
690
- argsSchema = argsValidator;
691
- argsValidator = argsValidator.shape;
692
- } else {
693
- throw new Error(
694
- "Unsupported non-object Zod schema for args; please provide an args schema using z.object({...}), e.g. z.object({ foo: z.string() })"
695
- );
696
- }
697
- } else {
698
- argsSchema = z.object(argsValidator);
699
- }
700
- const convexValidator = zodToConvexFields(argsValidator);
701
- return builder({
702
- args: { ...convexValidator, ...inputArgs },
703
- ...returnValidator,
704
- handler: async (ctx, allArgs) => {
705
- const added = await customInput(
706
- ctx,
707
- pick(allArgs, Object.keys(inputArgs)),
708
- extra
709
- );
710
- const argKeys = Object.keys(argsValidator);
711
- const rawArgs = pick(allArgs, argKeys);
712
- const decoded = fromConvexJS(rawArgs, argsSchema);
713
- const parsed = argsSchema.safeParse(decoded);
714
- if (!parsed.success) {
715
- handleZodValidationError(parsed.error, "args");
716
- }
717
- const finalCtx = { ...ctx, ...added?.ctx ?? {} };
718
- const baseArgs = parsed.data;
719
- const addedArgs = added?.args ?? {};
720
- const finalArgs = { ...baseArgs, ...addedArgs };
721
- const ret = await handler(finalCtx, finalArgs);
722
- if (returns && !fn.skipConvexValidation) {
723
- let validated;
724
- try {
725
- validated = returns.parse(ret);
726
- } catch (e) {
727
- handleZodValidationError(e, "returns");
728
- }
729
- if (added?.onSuccess) {
730
- await added.onSuccess({
731
- ctx,
732
- args: parsed.data,
733
- result: validated
734
- });
735
- }
736
- return toConvexJS(returns, validated);
737
- }
738
- if (added?.onSuccess) {
739
- await added.onSuccess({ ctx, args: parsed.data, result: ret });
740
- }
741
- return ret;
742
- }
743
- });
744
- }
745
- return builder({
746
- args: inputArgs,
747
- ...returnValidator,
748
- handler: async (ctx, allArgs) => {
749
- const added = await customInput(
750
- ctx,
751
- pick(allArgs, Object.keys(inputArgs)),
752
- extra
753
- );
754
- const finalCtx = { ...ctx, ...added?.ctx ?? {} };
755
- const baseArgs = allArgs;
756
- const addedArgs = added?.args ?? {};
757
- const finalArgs = { ...baseArgs, ...addedArgs };
758
- const ret = await handler(finalCtx, finalArgs);
759
- if (returns && !fn.skipConvexValidation) {
760
- let validated;
761
- try {
762
- validated = returns.parse(ret);
763
- } catch (e) {
764
- handleZodValidationError(e, "returns");
765
- }
766
- if (added?.onSuccess) {
767
- await added.onSuccess({ ctx, args: allArgs, result: validated });
768
- }
769
- return toConvexJS(returns, validated);
770
- }
771
- if (added?.onSuccess) {
772
- await added.onSuccess({ ctx, args: allArgs, result: ret });
773
- }
774
- return ret;
775
- }
776
- });
777
- };
778
- }
779
- function zCustomQuery(query, customization) {
780
- return customFnBuilder(query, customization);
781
- }
782
- function zCustomMutation(mutation, customization) {
783
- return customFnBuilder(
784
- mutation,
785
- customization
786
- );
787
- }
788
- function zCustomAction(action, customization) {
789
- return customFnBuilder(
790
- action,
791
- customization
792
- );
793
- }
794
- var customCheckCache = /* @__PURE__ */ new WeakMap();
795
- function containsCustom(schema, maxDepth = 50, currentDepth = 0) {
796
- const cached = customCheckCache.get(schema);
797
- if (cached !== void 0) {
798
- return cached;
799
- }
800
- if (currentDepth > maxDepth) {
801
- return false;
802
- }
803
- let result = false;
804
- if (schema._def?.typeName === "ZodCustom") {
805
- result = true;
806
- } else if (schema instanceof z.ZodUnion) {
807
- result = schema.options.some(
808
- (opt) => containsCustom(opt, maxDepth, currentDepth + 1)
809
- );
810
- } else if (schema instanceof z.ZodOptional) {
811
- result = containsCustom(schema.unwrap(), maxDepth, currentDepth + 1);
812
- } else if (schema instanceof z.ZodNullable) {
813
- result = containsCustom(schema.unwrap(), maxDepth, currentDepth + 1);
814
- } else if (schema instanceof z.ZodDefault) {
815
- result = containsCustom(schema.removeDefault(), maxDepth, currentDepth + 1);
816
- }
817
- customCheckCache.set(schema, result);
818
- return result;
819
- }
820
- function zQuery(query, input, handler, options) {
821
- let zodSchema;
822
- let args;
823
- if (input instanceof z.ZodObject) {
824
- const zodObj = input;
825
- zodSchema = zodObj;
826
- args = zodToConvexFields(getObjectShape(zodObj));
827
- } else if (input instanceof z.ZodType) {
828
- zodSchema = z.object({ value: input });
829
- args = { value: zodToConvex(input) };
830
- } else {
831
- zodSchema = z.object(input);
832
- args = zodToConvexFields(input);
833
- }
834
- const returns = options?.returns && !containsCustom(options.returns) ? zodToConvex(options.returns) : void 0;
835
- return query({
836
- args,
837
- returns,
838
- handler: async (ctx, argsObject) => {
839
- const decoded = fromConvexJS(argsObject, zodSchema);
840
- let parsed;
841
- try {
842
- parsed = zodSchema.parse(decoded);
843
- } catch (e) {
844
- handleZodValidationError(e, "args");
845
- }
846
- const raw = await handler(ctx, parsed);
847
- if (options?.returns) {
848
- try {
849
- const validated = options.returns.parse(raw);
850
- return toConvexJS(options.returns, validated);
851
- } catch (e) {
852
- handleZodValidationError(e, "returns");
853
- }
854
- }
855
- return toConvexJS(raw);
856
- }
857
- });
858
- }
859
- function zMutation(mutation, input, handler, options) {
860
- let zodSchema;
861
- let args;
862
- if (input instanceof z.ZodObject) {
863
- const zodObj = input;
864
- zodSchema = zodObj;
865
- args = zodToConvexFields(getObjectShape(zodObj));
866
- } else if (input instanceof z.ZodType) {
867
- zodSchema = z.object({ value: input });
868
- args = { value: zodToConvex(input) };
869
- } else {
870
- zodSchema = z.object(input);
871
- args = zodToConvexFields(input);
872
- }
873
- const returns = options?.returns && !containsCustom(options.returns) ? zodToConvex(options.returns) : void 0;
874
- return mutation({
875
- args,
876
- returns,
877
- handler: async (ctx, argsObject) => {
878
- const decoded = fromConvexJS(argsObject, zodSchema);
879
- let parsed;
880
- try {
881
- parsed = zodSchema.parse(decoded);
882
- } catch (e) {
883
- handleZodValidationError(e, "args");
884
- }
885
- const raw = await handler(ctx, parsed);
886
- if (options?.returns) {
887
- try {
888
- const validated = options.returns.parse(raw);
889
- return toConvexJS(options.returns, validated);
890
- } catch (e) {
891
- handleZodValidationError(e, "returns");
892
- }
893
- }
894
- return toConvexJS(raw);
895
- }
896
- });
897
- }
898
- function zAction(action, input, handler, options) {
899
- let zodSchema;
900
- let args;
901
- if (input instanceof z.ZodObject) {
902
- const zodObj = input;
903
- zodSchema = zodObj;
904
- args = zodToConvexFields(getObjectShape(zodObj));
905
- } else if (input instanceof z.ZodType) {
906
- zodSchema = z.object({ value: input });
907
- args = { value: zodToConvex(input) };
908
- } else {
909
- zodSchema = z.object(input);
910
- args = zodToConvexFields(input);
911
- }
912
- const returns = options?.returns && !containsCustom(options.returns) ? zodToConvex(options.returns) : void 0;
913
- return action({
914
- args,
915
- returns,
916
- handler: async (ctx, argsObject) => {
917
- const decoded = fromConvexJS(argsObject, zodSchema);
918
- let parsed;
919
- try {
920
- parsed = zodSchema.parse(decoded);
921
- } catch (e) {
922
- handleZodValidationError(e, "args");
923
- }
924
- const raw = await handler(ctx, parsed);
925
- if (options?.returns) {
926
- try {
927
- const validated = options.returns.parse(raw);
928
- return toConvexJS(options.returns, validated);
929
- } catch (e) {
930
- handleZodValidationError(e, "returns");
931
- }
932
- }
933
- return toConvexJS(raw);
934
- }
935
- });
936
- }
937
-
938
- // src/builders.ts
939
- function zQueryBuilder(builder) {
940
- return (config) => {
941
- return zQuery(builder, config.args ?? {}, config.handler, {
942
- returns: config.returns
943
- });
944
- };
945
- }
946
- function zMutationBuilder(builder) {
947
- return (config) => {
948
- return zMutation(builder, config.args ?? {}, config.handler, {
949
- returns: config.returns
950
- });
951
- };
952
- }
953
- function zActionBuilder(builder) {
954
- return (config) => {
955
- return zAction(builder, config.args ?? {}, config.handler, {
956
- returns: config.returns
957
- });
958
- };
959
- }
960
- function zCustomQueryBuilder(query, customization) {
961
- return customFnBuilder(
962
- query,
963
- customization
964
- );
965
- }
966
- function zCustomMutationBuilder(mutation, customization) {
967
- return customFnBuilder(
968
- mutation,
969
- customization
970
- );
971
- }
972
- function zCustomActionBuilder(action, customization) {
973
- return customFnBuilder(
974
- action,
975
- customization
976
- );
977
- }
978
- function zodDoc(tableName, schema) {
979
- return schema.extend({
980
- _id: zid(tableName),
981
- _creationTime: z.number()
982
- });
983
- }
984
- function zodDocOrNull(tableName, schema) {
985
- return z.union([zodDoc(tableName, schema), z.null()]);
986
- }
987
- function zodTable(name, shape) {
988
- const convexFields = zodToConvexFields(shape);
989
- const table = Table(name, convexFields);
990
- const zDoc = zodDoc(name, z.object(shape));
991
- const docArray = z.array(zDoc);
992
- return Object.assign(table, {
993
- shape,
994
- zDoc,
995
- docArray
996
- });
997
- }
998
-
999
- export { convexCodec, customFnBuilder, findBaseCodec, formatZodIssues, fromConvexJS, getObjectShape, handleZodValidationError, isDateSchema, makeUnion, mapDateFieldToNumber, pick, pickShape, registerBaseCodec, registryHelpers, returnsAs, safeOmit, safePick, toConvexJS, zActionBuilder, zCustomAction, zCustomActionBuilder, zCustomMutation, zCustomMutationBuilder, zCustomQuery, zCustomQueryBuilder, zMutationBuilder, zPaginated, zQueryBuilder, zid, zodDoc, zodDocOrNull, zodTable, zodToConvex, zodToConvexFields };
1000
- //# sourceMappingURL=index.mjs.map
1001
- //# sourceMappingURL=index.mjs.map