@magiclabs.ai/magicbook-client 0.6.8-canary → 0.6.9

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/index.js ADDED
@@ -0,0 +1,4822 @@
1
+ // ../../core/data/design-request.ts
2
+ var states = [
3
+ "new",
4
+ "ingesting",
5
+ "submitted",
6
+ "storyboarding",
7
+ "deduplication",
8
+ "image-selection",
9
+ "designing",
10
+ "layouting",
11
+ "embellishing",
12
+ "polishing",
13
+ "ready",
14
+ "timeout",
15
+ "error",
16
+ "cancelled"
17
+ ];
18
+ var statesToCloseWS = ["error", "timeout", "ready", "cancelled"];
19
+ var statesToReport = ["error", "timeout"];
20
+ var isDesignRequestSubmitted = (state) => !["new", "ingesting"].includes(state);
21
+ var occasions = [
22
+ "baby",
23
+ "birthday",
24
+ "default",
25
+ "everyday",
26
+ "family",
27
+ "kids",
28
+ "life-stories",
29
+ "portfolio",
30
+ "school-memories",
31
+ "seasonal-holidays",
32
+ "special-celebrations",
33
+ "sports-and-hobbies",
34
+ "travel",
35
+ "wedding",
36
+ "year-in-review"
37
+ ];
38
+ var styles = {
39
+ 1005: { slug: "modern-black-sfly" },
40
+ 1101: { slug: "bon-voyage-sfly" },
41
+ 1103: { slug: "fun-in-the-sun-sfly" },
42
+ 1201: { slug: "modern-wedding-sfly" },
43
+ 3001: { slug: "digiscrap-sfly" },
44
+ 4034: { slug: "travel-snapshots-sfly" },
45
+ 4035: { slug: "vintage-travel-sfly" },
46
+ 5017: { slug: "natural-neutrals-sfly" },
47
+ 5033: { slug: "chalkboard-chic-sfly" },
48
+ 5079: { slug: "hello-spring-sfly" },
49
+ 5082: { slug: "familygram-sfly" },
50
+ 5085: { slug: "best-day-ever-sfly" },
51
+ 5091: { slug: "little-love-sfly" },
52
+ 5118: { slug: "a-year-in-color-sfly" },
53
+ 5120: { slug: "milestone-anniversaries-sfly" },
54
+ 5121: { slug: "the-travel-bug-sfly" },
55
+ 5122: { slug: "modern-white-sfly" },
56
+ 5127: { slug: "outdoor-wedding-sfly" },
57
+ 5134: { slug: "classic-wedding-sfly" },
58
+ 5138: { slug: "kraft-pop-sfly" },
59
+ 5142: { slug: "simply-black-sfly" },
60
+ 5144: { slug: "autumn-memories-sfly" },
61
+ 5146: { slug: "everyday-sentiments-sfly" },
62
+ 5149: { slug: "everyday-happiness-sfly" },
63
+ 5150: { slug: "its-a-girl-thing-sfly" },
64
+ 5155: { slug: "made-with-love-sfly" },
65
+ 5157: { slug: "high-school-memories-sfly" },
66
+ 5161: { slug: "rustic-wedding-sfly" },
67
+ 5165: { slug: "life-is-grand-sfly" },
68
+ 5167: { slug: "adventure-awaits-sfly" },
69
+ 5168: { slug: "disney-adventure-sfly" },
70
+ 5171: { slug: "world-travel-sfly" },
71
+ 5174: { slug: "hello-summer-sfly" },
72
+ 5183: { slug: "everything-sports-sfly" },
73
+ 5188: { slug: "everyday-watercolor-sfly" },
74
+ 5189: { slug: "holiday-memories-sfly" },
75
+ 5213: { slug: "love-and-thanks-sfly" },
76
+ 5218: { slug: "babys-first-year-sfly" },
77
+ 5219: { slug: "usa-travel-sfly" },
78
+ 5220: { slug: "vintage-wedding-sfly" },
79
+ 5226: { slug: "love-you-because-sfly" },
80
+ 5228: { slug: "reunion-sfly" },
81
+ 5238: { slug: "whimsy-chalkboard-sfly" },
82
+ 5242: { slug: "modern-indigo-sfly" },
83
+ 5250: { slug: "family-yearbook-sfly" },
84
+ 5255: { slug: "elegant-wedding-sfly" },
85
+ 5258: { slug: "family-vacation-sfly" },
86
+ 5259: { slug: "beach-travel-sfly" },
87
+ 5261: { slug: "sparkle-and-shine-sfly" },
88
+ 5262: { slug: "welcome-baby-sfly" },
89
+ 5265: { slug: "vivid-watercolor-sfly" },
90
+ 5266: { slug: "what-i-love-about-you-sfly" },
91
+ 5272: { slug: "love-grows-sfly" },
92
+ 5274: { slug: "painted-seasons-sfly" },
93
+ 5278: { slug: "vintage-disney-sfly" },
94
+ 5292: { slug: "modern-grey-sfly" },
95
+ 5297: { slug: "modern-love-story-sfly" },
96
+ 5299: { slug: "modern-travel-sfly" },
97
+ 5304: { slug: "beach-wedding-sfly" },
98
+ 5305: { slug: "rustic-farmhouse-sfly" },
99
+ 5308: { slug: "tropical-travel-sfly" },
100
+ 6e3: { slug: "travel-abroad-sfly" },
101
+ 6001: { slug: "everyday-rustic-sfly" },
102
+ 6002: { slug: "simply-modern-sfly" },
103
+ 6003: { slug: "modern-baby-sfly" },
104
+ 6004: { slug: "modern-photo-album-sfly" },
105
+ 6005: { slug: "travel-adventures-sfly" },
106
+ 6006: { slug: "watercolor-year-in-review-sfly" },
107
+ 6007: { slug: "beach-bliss-sfly" },
108
+ 6008: { slug: "simply-gray-sfly" },
109
+ 6009: { slug: "family-favorites-by-lure-design-sfly" },
110
+ 6010: { slug: "travel-gallery-sfly" },
111
+ 6011: { slug: "our-wedding-day-sfly" },
112
+ 6012: { slug: "chic-celebrations-by-float-paperie-sfly" },
113
+ 6013: { slug: "simply-bold-type-sfly" },
114
+ 6014: { slug: "colorful-florals-by-potts-design-sfly" },
115
+ 6015: { slug: "softly-rustic-sfly" },
116
+ 6016: { slug: "ombre-watercolor-sfly" },
117
+ 6017: { slug: "forever-love-by-with-merriment-sfly" },
118
+ 6018: { slug: "colorful-memories-by-britt-bass-sfly" },
119
+ 6019: { slug: "celebrate-family-by-float-paperie-sfly" },
120
+ 6020: { slug: "disney-family-adventures-sfly" },
121
+ 6021: { slug: "everyday-neutrals-sfly" },
122
+ 6022: { slug: "colorful-childhood-sfly" },
123
+ 6023: { slug: "everyday-indigo-sfly" },
124
+ 6024: { slug: "shimmer-and-shine-sfly" },
125
+ 6025: { slug: "summertime-fun-sfly" },
126
+ 6026: { slug: "pet-lover-sfly" },
127
+ 6027: { slug: "modern-wedding-story-sfly" },
128
+ 6028: { slug: "family-blessings-by-potts-design-sfly" },
129
+ 6030: { slug: "outdoor-adventures-by-sarah-hawkins-designs-sfly" },
130
+ 6031: { slug: "travel-memories-sfly" },
131
+ 6032: { slug: "tropical-travels-sfly" },
132
+ 6033: { slug: "everyday-chalkboard-by-potts-design-sfly" },
133
+ 6034: { slug: "classic-disney-sfly" },
134
+ 6035: { slug: "cheerful-color-sfly" },
135
+ 6036: { slug: "colorful-birthday-sfly" },
136
+ 6038: { slug: "classic-baby-sfly" },
137
+ 6039: { slug: "bold-year-in-review-by-float-paperie-sfly" },
138
+ 6040: { slug: "colorfully-fun-sfly" },
139
+ 6041: { slug: "colorful-year-in-review-by-sarah-hawkins-designs-sfly" },
140
+ 6042: { slug: "gilded-wedding-sfly" },
141
+ 6043: { slug: "road-trip-travel-by-sarah-hawkins-designs-sfly" },
142
+ 6044: { slug: "rustic-gilded-wedding-sfly" },
143
+ 6045: { slug: "elegantly-scripted-year-in-review-sfly" },
144
+ 6047: { slug: "2020-what-a-year-sfly" },
145
+ 6057: { slug: "best-mom-ever-sfly" },
146
+ 6052: { slug: "celebration-of-life-by-sarah-hawkins-designs-sfly" },
147
+ 6054: { slug: "colorful-school-days-by-float-paperie-sfly" },
148
+ 6051: { slug: "love-is-all-we-need-sfly" },
149
+ 6058: { slug: "graduation-celebration-sfly" },
150
+ 6056: { slug: "our-wedding-day-guestbook-sfly" },
151
+ 6055: { slug: "muted-everyday-abstract-sfly" },
152
+ 6046: { slug: "winter-memories-by-sarah-hawkins-design-sfly" },
153
+ 6053: { slug: "best-dad-ever-sfly" },
154
+ 6050: { slug: "watercolor-greenery-by-sarah-hawkins-designs-sfly" },
155
+ 6063: { slug: "watercolor-floral-wedding-by-kim-thoa-sfly" },
156
+ 6060: { slug: "watercolor-baby-girl-sfly" },
157
+ 6059: { slug: "watercolor-baby-boy-sfly" },
158
+ 6048: { slug: "simple-elegant-wedding-sfly" },
159
+ 6049: { slug: "gilded-wedding-guestbook-sfly" },
160
+ 6037: { slug: "everyday-fairytale-by-jenny-romanski-sfly" },
161
+ 6061: { slug: "best-grandparents-ever-sfly" },
162
+ 6068: { slug: "winter-getaway-sfly" },
163
+ 6067: { slug: "national-parks-travel-by-eiman-design-co-sfly" },
164
+ 6065: { slug: "go-sports-by-lure-design-sfly" },
165
+ 6066: { slug: "elegant-wedding-greenery-by-kim-thoa-sfly" },
166
+ 6064: { slug: "boho-travel-by-umaiana-studio-sfly" },
167
+ 6071: { slug: "modern-dark-neutrals-sfly" },
168
+ 6072: { slug: "modern-light-neutrals-sfly" },
169
+ 6073: { slug: "modern-celebrations-sfly" },
170
+ 6074: { slug: "bright-and-bold-kids-year-in-review-by-sarah-hawkins-designs-sfly" },
171
+ 6085: { slug: "classic-school-yearbook-sfly" },
172
+ 6084: { slug: "colorful-elementary-school-yearbook-sfly" },
173
+ 5402: { slug: "everyday-recipes-by-slightly-stationery-sfly" },
174
+ 6083: { slug: "school-days-yearbook-sfly" },
175
+ 6082: { slug: "the-story-of-me-sfly" },
176
+ 6086: { slug: "whimsical-recipes-by-slightly-stationery-sfly" },
177
+ 6101: { slug: "babys-first-sfly" },
178
+ 6103: { slug: "classic-recipes-sfly" },
179
+ 6104: { slug: "elevated-rustic-sfly" },
180
+ 6105: { slug: "boho-summer-sfly" },
181
+ 6116: { slug: "boho-baby-sfly" },
182
+ 6117: { slug: "simply-gallery-sfly" },
183
+ 6118: { slug: "this-is-love-sfly" },
184
+ 6120: { slug: "wedding-gallery-sfly" },
185
+ 6121: { slug: "watercolorwashes-sfly" },
186
+ 6124: { slug: "graduation-photo-album-sfly" },
187
+ 6125: { slug: "modern-year-in-review-photo-album-sfly" },
188
+ 6126: { slug: "black-white-photo-album-sfly" },
189
+ 6132: { slug: "travel-journal-sfly" },
190
+ 6133: { slug: "rustic-gallery-sfly" },
191
+ 6137: { slug: "summer-adventures-sfly" },
192
+ 6141: { slug: "heirloom-moments-sfly" },
193
+ 6144: { slug: "seasonal-year-in-review-sfly" },
194
+ 6143: { slug: "wanderlust-gallery-sfly" },
195
+ 6146: { slug: "wedding-elopement-gallery-sfly" },
196
+ 6062: { slug: "create-your-own-sfly" },
197
+ 6075: { slug: "together-again-sfly" },
198
+ 6078: { slug: "everyday-boho-by-umaiana-studio-sfly" },
199
+ 6089: { slug: "colorful-gradients-sfly" },
200
+ 6096: { slug: "simply-scrapbook-sfly" },
201
+ 6097: { slug: "boho-wedding-sfly" },
202
+ 6098: { slug: "black-and-white-rustic-sfly" },
203
+ 6099: { slug: "bright-color-pop-sfly" }
204
+ };
205
+ var bookSizes = ["8x8", "10x10", "12x12", "8x11", "11x8", "11x14"];
206
+ var coverTypes = ["sc", "hc", "pl"];
207
+ var pageTypes = ["sp", "sl", "dl"];
208
+ var imageDensities = ["low", "medium", "high"];
209
+ var imageFilteringLevels = ["best", "most", "all"];
210
+ var embellishmentLevels = ["none", "few", "lots"];
211
+ var textStickerLevels = ["none", "few", "lots"];
212
+ var timeoutMessage = {
213
+ state: "timeout",
214
+ slug: "timeout",
215
+ progress: 100,
216
+ message: "Design timed out"
217
+ };
218
+ var cancelledMessage = {
219
+ state: "cancelled",
220
+ slug: "cancelled",
221
+ progress: 100,
222
+ message: "Design canceled"
223
+ };
224
+
225
+ // ../../core/utils/toolbox.ts
226
+ function mergeNestedObject(obj, objToMerge) {
227
+ Object.keys(objToMerge).map((key) => {
228
+ if (typeof obj[key] === "object" && typeof objToMerge[key] === "object") {
229
+ mergeNestedObject(obj[key], objToMerge[key]);
230
+ } else {
231
+ obj[key] = objToMerge[key];
232
+ }
233
+ });
234
+ return obj;
235
+ }
236
+ function camelCaseToSnakeCase(str) {
237
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
238
+ }
239
+ function camelCaseObjectKeysToSnakeCase(camelCaseObject) {
240
+ Object.keys(camelCaseObject).map((key) => {
241
+ const snakeCaseKey = camelCaseToSnakeCase(key);
242
+ if (snakeCaseKey.includes("_")) {
243
+ camelCaseObject[snakeCaseKey] = camelCaseObject[key];
244
+ delete camelCaseObject[key];
245
+ }
246
+ if (typeof camelCaseObject[snakeCaseKey] === "object") {
247
+ camelCaseObject[snakeCaseKey] = camelCaseObjectKeysToSnakeCase(camelCaseObject[snakeCaseKey]);
248
+ }
249
+ });
250
+ return camelCaseObject;
251
+ }
252
+ function snakeCaseToCamelCase(str) {
253
+ return str.replace(/([-_][a-z])/g, ($1) => $1.toUpperCase().replace("-", "").replace("_", ""));
254
+ }
255
+ function snakeCaseObjectKeysToCamelCase(snakeCaseObject) {
256
+ Object.keys(snakeCaseObject).map((key) => {
257
+ const camelCaseKey = snakeCaseToCamelCase(key);
258
+ if (camelCaseKey !== key) {
259
+ snakeCaseObject[camelCaseKey] = snakeCaseObject[key];
260
+ delete snakeCaseObject[key];
261
+ }
262
+ if (typeof snakeCaseObject[camelCaseKey] === "object") {
263
+ snakeCaseObject[camelCaseKey] = snakeCaseObjectKeysToCamelCase(snakeCaseObject[camelCaseKey]);
264
+ }
265
+ });
266
+ return snakeCaseObject;
267
+ }
268
+ async function handleAsyncFunction(fn) {
269
+ try {
270
+ return await fn();
271
+ } catch (error) {
272
+ return Promise.reject(error);
273
+ }
274
+ }
275
+ function bindThisToFunctions(instance) {
276
+ for (const name of Object.getOwnPropertyNames(
277
+ Object.getPrototypeOf(instance)
278
+ )) {
279
+ if (typeof instance[name] === "function" && name !== "constructor") {
280
+ instance[name] = instance[name].bind(instance);
281
+ }
282
+ }
283
+ }
284
+ function cleanJSON(obj) {
285
+ return JSON.parse(JSON.stringify(obj));
286
+ }
287
+ function getStyleIdBySlug(slug) {
288
+ for (const id in styles) {
289
+ const style = styles[id];
290
+ if (style.slug === slug) {
291
+ return parseInt(id);
292
+ }
293
+ }
294
+ return void 0;
295
+ }
296
+
297
+ // ../../node_modules/.pnpm/zod@3.21.4/node_modules/zod/lib/index.mjs
298
+ var util;
299
+ (function(util2) {
300
+ util2.assertEqual = (val) => val;
301
+ function assertIs(_arg) {
302
+ }
303
+ util2.assertIs = assertIs;
304
+ function assertNever(_x) {
305
+ throw new Error();
306
+ }
307
+ util2.assertNever = assertNever;
308
+ util2.arrayToEnum = (items) => {
309
+ const obj = {};
310
+ for (const item of items) {
311
+ obj[item] = item;
312
+ }
313
+ return obj;
314
+ };
315
+ util2.getValidEnumValues = (obj) => {
316
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
317
+ const filtered = {};
318
+ for (const k of validKeys) {
319
+ filtered[k] = obj[k];
320
+ }
321
+ return util2.objectValues(filtered);
322
+ };
323
+ util2.objectValues = (obj) => {
324
+ return util2.objectKeys(obj).map(function(e) {
325
+ return obj[e];
326
+ });
327
+ };
328
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
329
+ const keys = [];
330
+ for (const key in object) {
331
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
332
+ keys.push(key);
333
+ }
334
+ }
335
+ return keys;
336
+ };
337
+ util2.find = (arr, checker) => {
338
+ for (const item of arr) {
339
+ if (checker(item))
340
+ return item;
341
+ }
342
+ return void 0;
343
+ };
344
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
345
+ function joinValues(array, separator = " | ") {
346
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
347
+ }
348
+ util2.joinValues = joinValues;
349
+ util2.jsonStringifyReplacer = (_, value) => {
350
+ if (typeof value === "bigint") {
351
+ return value.toString();
352
+ }
353
+ return value;
354
+ };
355
+ })(util || (util = {}));
356
+ var objectUtil;
357
+ (function(objectUtil2) {
358
+ objectUtil2.mergeShapes = (first, second) => {
359
+ return {
360
+ ...first,
361
+ ...second
362
+ // second overwrites first
363
+ };
364
+ };
365
+ })(objectUtil || (objectUtil = {}));
366
+ var ZodParsedType = util.arrayToEnum([
367
+ "string",
368
+ "nan",
369
+ "number",
370
+ "integer",
371
+ "float",
372
+ "boolean",
373
+ "date",
374
+ "bigint",
375
+ "symbol",
376
+ "function",
377
+ "undefined",
378
+ "null",
379
+ "array",
380
+ "object",
381
+ "unknown",
382
+ "promise",
383
+ "void",
384
+ "never",
385
+ "map",
386
+ "set"
387
+ ]);
388
+ var getParsedType = (data) => {
389
+ const t = typeof data;
390
+ switch (t) {
391
+ case "undefined":
392
+ return ZodParsedType.undefined;
393
+ case "string":
394
+ return ZodParsedType.string;
395
+ case "number":
396
+ return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
397
+ case "boolean":
398
+ return ZodParsedType.boolean;
399
+ case "function":
400
+ return ZodParsedType.function;
401
+ case "bigint":
402
+ return ZodParsedType.bigint;
403
+ case "symbol":
404
+ return ZodParsedType.symbol;
405
+ case "object":
406
+ if (Array.isArray(data)) {
407
+ return ZodParsedType.array;
408
+ }
409
+ if (data === null) {
410
+ return ZodParsedType.null;
411
+ }
412
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
413
+ return ZodParsedType.promise;
414
+ }
415
+ if (typeof Map !== "undefined" && data instanceof Map) {
416
+ return ZodParsedType.map;
417
+ }
418
+ if (typeof Set !== "undefined" && data instanceof Set) {
419
+ return ZodParsedType.set;
420
+ }
421
+ if (typeof Date !== "undefined" && data instanceof Date) {
422
+ return ZodParsedType.date;
423
+ }
424
+ return ZodParsedType.object;
425
+ default:
426
+ return ZodParsedType.unknown;
427
+ }
428
+ };
429
+ var ZodIssueCode = util.arrayToEnum([
430
+ "invalid_type",
431
+ "invalid_literal",
432
+ "custom",
433
+ "invalid_union",
434
+ "invalid_union_discriminator",
435
+ "invalid_enum_value",
436
+ "unrecognized_keys",
437
+ "invalid_arguments",
438
+ "invalid_return_type",
439
+ "invalid_date",
440
+ "invalid_string",
441
+ "too_small",
442
+ "too_big",
443
+ "invalid_intersection_types",
444
+ "not_multiple_of",
445
+ "not_finite"
446
+ ]);
447
+ var quotelessJson = (obj) => {
448
+ const json = JSON.stringify(obj, null, 2);
449
+ return json.replace(/"([^"]+)":/g, "$1:");
450
+ };
451
+ var ZodError = class extends Error {
452
+ constructor(issues) {
453
+ super();
454
+ this.issues = [];
455
+ this.addIssue = (sub) => {
456
+ this.issues = [...this.issues, sub];
457
+ };
458
+ this.addIssues = (subs = []) => {
459
+ this.issues = [...this.issues, ...subs];
460
+ };
461
+ const actualProto = new.target.prototype;
462
+ if (Object.setPrototypeOf) {
463
+ Object.setPrototypeOf(this, actualProto);
464
+ } else {
465
+ this.__proto__ = actualProto;
466
+ }
467
+ this.name = "ZodError";
468
+ this.issues = issues;
469
+ }
470
+ get errors() {
471
+ return this.issues;
472
+ }
473
+ format(_mapper) {
474
+ const mapper = _mapper || function(issue) {
475
+ return issue.message;
476
+ };
477
+ const fieldErrors = { _errors: [] };
478
+ const processError = (error) => {
479
+ for (const issue of error.issues) {
480
+ if (issue.code === "invalid_union") {
481
+ issue.unionErrors.map(processError);
482
+ } else if (issue.code === "invalid_return_type") {
483
+ processError(issue.returnTypeError);
484
+ } else if (issue.code === "invalid_arguments") {
485
+ processError(issue.argumentsError);
486
+ } else if (issue.path.length === 0) {
487
+ fieldErrors._errors.push(mapper(issue));
488
+ } else {
489
+ let curr = fieldErrors;
490
+ let i = 0;
491
+ while (i < issue.path.length) {
492
+ const el = issue.path[i];
493
+ const terminal = i === issue.path.length - 1;
494
+ if (!terminal) {
495
+ curr[el] = curr[el] || { _errors: [] };
496
+ } else {
497
+ curr[el] = curr[el] || { _errors: [] };
498
+ curr[el]._errors.push(mapper(issue));
499
+ }
500
+ curr = curr[el];
501
+ i++;
502
+ }
503
+ }
504
+ }
505
+ };
506
+ processError(this);
507
+ return fieldErrors;
508
+ }
509
+ toString() {
510
+ return this.message;
511
+ }
512
+ get message() {
513
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
514
+ }
515
+ get isEmpty() {
516
+ return this.issues.length === 0;
517
+ }
518
+ flatten(mapper = (issue) => issue.message) {
519
+ const fieldErrors = {};
520
+ const formErrors = [];
521
+ for (const sub of this.issues) {
522
+ if (sub.path.length > 0) {
523
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
524
+ fieldErrors[sub.path[0]].push(mapper(sub));
525
+ } else {
526
+ formErrors.push(mapper(sub));
527
+ }
528
+ }
529
+ return { formErrors, fieldErrors };
530
+ }
531
+ get formErrors() {
532
+ return this.flatten();
533
+ }
534
+ };
535
+ ZodError.create = (issues) => {
536
+ const error = new ZodError(issues);
537
+ return error;
538
+ };
539
+ var errorMap = (issue, _ctx) => {
540
+ let message;
541
+ switch (issue.code) {
542
+ case ZodIssueCode.invalid_type:
543
+ if (issue.received === ZodParsedType.undefined) {
544
+ message = "Required";
545
+ } else {
546
+ message = `Expected ${issue.expected}, received ${issue.received}`;
547
+ }
548
+ break;
549
+ case ZodIssueCode.invalid_literal:
550
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
551
+ break;
552
+ case ZodIssueCode.unrecognized_keys:
553
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
554
+ break;
555
+ case ZodIssueCode.invalid_union:
556
+ message = `Invalid input`;
557
+ break;
558
+ case ZodIssueCode.invalid_union_discriminator:
559
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
560
+ break;
561
+ case ZodIssueCode.invalid_enum_value:
562
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
563
+ break;
564
+ case ZodIssueCode.invalid_arguments:
565
+ message = `Invalid function arguments`;
566
+ break;
567
+ case ZodIssueCode.invalid_return_type:
568
+ message = `Invalid function return type`;
569
+ break;
570
+ case ZodIssueCode.invalid_date:
571
+ message = `Invalid date`;
572
+ break;
573
+ case ZodIssueCode.invalid_string:
574
+ if (typeof issue.validation === "object") {
575
+ if ("includes" in issue.validation) {
576
+ message = `Invalid input: must include "${issue.validation.includes}"`;
577
+ if (typeof issue.validation.position === "number") {
578
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
579
+ }
580
+ } else if ("startsWith" in issue.validation) {
581
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
582
+ } else if ("endsWith" in issue.validation) {
583
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
584
+ } else {
585
+ util.assertNever(issue.validation);
586
+ }
587
+ } else if (issue.validation !== "regex") {
588
+ message = `Invalid ${issue.validation}`;
589
+ } else {
590
+ message = "Invalid";
591
+ }
592
+ break;
593
+ case ZodIssueCode.too_small:
594
+ if (issue.type === "array")
595
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
596
+ else if (issue.type === "string")
597
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
598
+ else if (issue.type === "number")
599
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
600
+ else if (issue.type === "date")
601
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
602
+ else
603
+ message = "Invalid input";
604
+ break;
605
+ case ZodIssueCode.too_big:
606
+ if (issue.type === "array")
607
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
608
+ else if (issue.type === "string")
609
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
610
+ else if (issue.type === "number")
611
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
612
+ else if (issue.type === "bigint")
613
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
614
+ else if (issue.type === "date")
615
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
616
+ else
617
+ message = "Invalid input";
618
+ break;
619
+ case ZodIssueCode.custom:
620
+ message = `Invalid input`;
621
+ break;
622
+ case ZodIssueCode.invalid_intersection_types:
623
+ message = `Intersection results could not be merged`;
624
+ break;
625
+ case ZodIssueCode.not_multiple_of:
626
+ message = `Number must be a multiple of ${issue.multipleOf}`;
627
+ break;
628
+ case ZodIssueCode.not_finite:
629
+ message = "Number must be finite";
630
+ break;
631
+ default:
632
+ message = _ctx.defaultError;
633
+ util.assertNever(issue);
634
+ }
635
+ return { message };
636
+ };
637
+ var overrideErrorMap = errorMap;
638
+ function setErrorMap(map) {
639
+ overrideErrorMap = map;
640
+ }
641
+ function getErrorMap() {
642
+ return overrideErrorMap;
643
+ }
644
+ var makeIssue = (params) => {
645
+ const { data, path, errorMaps, issueData } = params;
646
+ const fullPath = [...path, ...issueData.path || []];
647
+ const fullIssue = {
648
+ ...issueData,
649
+ path: fullPath
650
+ };
651
+ let errorMessage = "";
652
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
653
+ for (const map of maps) {
654
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
655
+ }
656
+ return {
657
+ ...issueData,
658
+ path: fullPath,
659
+ message: issueData.message || errorMessage
660
+ };
661
+ };
662
+ var EMPTY_PATH = [];
663
+ function addIssueToContext(ctx, issueData) {
664
+ const issue = makeIssue({
665
+ issueData,
666
+ data: ctx.data,
667
+ path: ctx.path,
668
+ errorMaps: [
669
+ ctx.common.contextualErrorMap,
670
+ ctx.schemaErrorMap,
671
+ getErrorMap(),
672
+ errorMap
673
+ // then global default map
674
+ ].filter((x) => !!x)
675
+ });
676
+ ctx.common.issues.push(issue);
677
+ }
678
+ var ParseStatus = class _ParseStatus {
679
+ constructor() {
680
+ this.value = "valid";
681
+ }
682
+ dirty() {
683
+ if (this.value === "valid")
684
+ this.value = "dirty";
685
+ }
686
+ abort() {
687
+ if (this.value !== "aborted")
688
+ this.value = "aborted";
689
+ }
690
+ static mergeArray(status, results) {
691
+ const arrayValue = [];
692
+ for (const s of results) {
693
+ if (s.status === "aborted")
694
+ return INVALID;
695
+ if (s.status === "dirty")
696
+ status.dirty();
697
+ arrayValue.push(s.value);
698
+ }
699
+ return { status: status.value, value: arrayValue };
700
+ }
701
+ static async mergeObjectAsync(status, pairs) {
702
+ const syncPairs = [];
703
+ for (const pair of pairs) {
704
+ syncPairs.push({
705
+ key: await pair.key,
706
+ value: await pair.value
707
+ });
708
+ }
709
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
710
+ }
711
+ static mergeObjectSync(status, pairs) {
712
+ const finalObject = {};
713
+ for (const pair of pairs) {
714
+ const { key, value } = pair;
715
+ if (key.status === "aborted")
716
+ return INVALID;
717
+ if (value.status === "aborted")
718
+ return INVALID;
719
+ if (key.status === "dirty")
720
+ status.dirty();
721
+ if (value.status === "dirty")
722
+ status.dirty();
723
+ if (typeof value.value !== "undefined" || pair.alwaysSet) {
724
+ finalObject[key.value] = value.value;
725
+ }
726
+ }
727
+ return { status: status.value, value: finalObject };
728
+ }
729
+ };
730
+ var INVALID = Object.freeze({
731
+ status: "aborted"
732
+ });
733
+ var DIRTY = (value) => ({ status: "dirty", value });
734
+ var OK = (value) => ({ status: "valid", value });
735
+ var isAborted = (x) => x.status === "aborted";
736
+ var isDirty = (x) => x.status === "dirty";
737
+ var isValid = (x) => x.status === "valid";
738
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
739
+ var errorUtil;
740
+ (function(errorUtil2) {
741
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
742
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
743
+ })(errorUtil || (errorUtil = {}));
744
+ var ParseInputLazyPath = class {
745
+ constructor(parent, value, path, key) {
746
+ this._cachedPath = [];
747
+ this.parent = parent;
748
+ this.data = value;
749
+ this._path = path;
750
+ this._key = key;
751
+ }
752
+ get path() {
753
+ if (!this._cachedPath.length) {
754
+ if (this._key instanceof Array) {
755
+ this._cachedPath.push(...this._path, ...this._key);
756
+ } else {
757
+ this._cachedPath.push(...this._path, this._key);
758
+ }
759
+ }
760
+ return this._cachedPath;
761
+ }
762
+ };
763
+ var handleResult = (ctx, result) => {
764
+ if (isValid(result)) {
765
+ return { success: true, data: result.value };
766
+ } else {
767
+ if (!ctx.common.issues.length) {
768
+ throw new Error("Validation failed but no issues detected.");
769
+ }
770
+ return {
771
+ success: false,
772
+ get error() {
773
+ if (this._error)
774
+ return this._error;
775
+ const error = new ZodError(ctx.common.issues);
776
+ this._error = error;
777
+ return this._error;
778
+ }
779
+ };
780
+ }
781
+ };
782
+ function processCreateParams(params) {
783
+ if (!params)
784
+ return {};
785
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
786
+ if (errorMap2 && (invalid_type_error || required_error)) {
787
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
788
+ }
789
+ if (errorMap2)
790
+ return { errorMap: errorMap2, description };
791
+ const customMap = (iss, ctx) => {
792
+ if (iss.code !== "invalid_type")
793
+ return { message: ctx.defaultError };
794
+ if (typeof ctx.data === "undefined") {
795
+ return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
796
+ }
797
+ return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
798
+ };
799
+ return { errorMap: customMap, description };
800
+ }
801
+ var ZodType = class {
802
+ constructor(def) {
803
+ this.spa = this.safeParseAsync;
804
+ this._def = def;
805
+ this.parse = this.parse.bind(this);
806
+ this.safeParse = this.safeParse.bind(this);
807
+ this.parseAsync = this.parseAsync.bind(this);
808
+ this.safeParseAsync = this.safeParseAsync.bind(this);
809
+ this.spa = this.spa.bind(this);
810
+ this.refine = this.refine.bind(this);
811
+ this.refinement = this.refinement.bind(this);
812
+ this.superRefine = this.superRefine.bind(this);
813
+ this.optional = this.optional.bind(this);
814
+ this.nullable = this.nullable.bind(this);
815
+ this.nullish = this.nullish.bind(this);
816
+ this.array = this.array.bind(this);
817
+ this.promise = this.promise.bind(this);
818
+ this.or = this.or.bind(this);
819
+ this.and = this.and.bind(this);
820
+ this.transform = this.transform.bind(this);
821
+ this.brand = this.brand.bind(this);
822
+ this.default = this.default.bind(this);
823
+ this.catch = this.catch.bind(this);
824
+ this.describe = this.describe.bind(this);
825
+ this.pipe = this.pipe.bind(this);
826
+ this.isNullable = this.isNullable.bind(this);
827
+ this.isOptional = this.isOptional.bind(this);
828
+ }
829
+ get description() {
830
+ return this._def.description;
831
+ }
832
+ _getType(input) {
833
+ return getParsedType(input.data);
834
+ }
835
+ _getOrReturnCtx(input, ctx) {
836
+ return ctx || {
837
+ common: input.parent.common,
838
+ data: input.data,
839
+ parsedType: getParsedType(input.data),
840
+ schemaErrorMap: this._def.errorMap,
841
+ path: input.path,
842
+ parent: input.parent
843
+ };
844
+ }
845
+ _processInputParams(input) {
846
+ return {
847
+ status: new ParseStatus(),
848
+ ctx: {
849
+ common: input.parent.common,
850
+ data: input.data,
851
+ parsedType: getParsedType(input.data),
852
+ schemaErrorMap: this._def.errorMap,
853
+ path: input.path,
854
+ parent: input.parent
855
+ }
856
+ };
857
+ }
858
+ _parseSync(input) {
859
+ const result = this._parse(input);
860
+ if (isAsync(result)) {
861
+ throw new Error("Synchronous parse encountered promise.");
862
+ }
863
+ return result;
864
+ }
865
+ _parseAsync(input) {
866
+ const result = this._parse(input);
867
+ return Promise.resolve(result);
868
+ }
869
+ parse(data, params) {
870
+ const result = this.safeParse(data, params);
871
+ if (result.success)
872
+ return result.data;
873
+ throw result.error;
874
+ }
875
+ safeParse(data, params) {
876
+ var _a;
877
+ const ctx = {
878
+ common: {
879
+ issues: [],
880
+ async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
881
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
882
+ },
883
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
884
+ schemaErrorMap: this._def.errorMap,
885
+ parent: null,
886
+ data,
887
+ parsedType: getParsedType(data)
888
+ };
889
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
890
+ return handleResult(ctx, result);
891
+ }
892
+ async parseAsync(data, params) {
893
+ const result = await this.safeParseAsync(data, params);
894
+ if (result.success)
895
+ return result.data;
896
+ throw result.error;
897
+ }
898
+ async safeParseAsync(data, params) {
899
+ const ctx = {
900
+ common: {
901
+ issues: [],
902
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
903
+ async: true
904
+ },
905
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
906
+ schemaErrorMap: this._def.errorMap,
907
+ parent: null,
908
+ data,
909
+ parsedType: getParsedType(data)
910
+ };
911
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
912
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
913
+ return handleResult(ctx, result);
914
+ }
915
+ refine(check, message) {
916
+ const getIssueProperties = (val) => {
917
+ if (typeof message === "string" || typeof message === "undefined") {
918
+ return { message };
919
+ } else if (typeof message === "function") {
920
+ return message(val);
921
+ } else {
922
+ return message;
923
+ }
924
+ };
925
+ return this._refinement((val, ctx) => {
926
+ const result = check(val);
927
+ const setError = () => ctx.addIssue({
928
+ code: ZodIssueCode.custom,
929
+ ...getIssueProperties(val)
930
+ });
931
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
932
+ return result.then((data) => {
933
+ if (!data) {
934
+ setError();
935
+ return false;
936
+ } else {
937
+ return true;
938
+ }
939
+ });
940
+ }
941
+ if (!result) {
942
+ setError();
943
+ return false;
944
+ } else {
945
+ return true;
946
+ }
947
+ });
948
+ }
949
+ refinement(check, refinementData) {
950
+ return this._refinement((val, ctx) => {
951
+ if (!check(val)) {
952
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
953
+ return false;
954
+ } else {
955
+ return true;
956
+ }
957
+ });
958
+ }
959
+ _refinement(refinement) {
960
+ return new ZodEffects({
961
+ schema: this,
962
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
963
+ effect: { type: "refinement", refinement }
964
+ });
965
+ }
966
+ superRefine(refinement) {
967
+ return this._refinement(refinement);
968
+ }
969
+ optional() {
970
+ return ZodOptional.create(this, this._def);
971
+ }
972
+ nullable() {
973
+ return ZodNullable.create(this, this._def);
974
+ }
975
+ nullish() {
976
+ return this.nullable().optional();
977
+ }
978
+ array() {
979
+ return ZodArray.create(this, this._def);
980
+ }
981
+ promise() {
982
+ return ZodPromise.create(this, this._def);
983
+ }
984
+ or(option) {
985
+ return ZodUnion.create([this, option], this._def);
986
+ }
987
+ and(incoming) {
988
+ return ZodIntersection.create(this, incoming, this._def);
989
+ }
990
+ transform(transform) {
991
+ return new ZodEffects({
992
+ ...processCreateParams(this._def),
993
+ schema: this,
994
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
995
+ effect: { type: "transform", transform }
996
+ });
997
+ }
998
+ default(def) {
999
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1000
+ return new ZodDefault({
1001
+ ...processCreateParams(this._def),
1002
+ innerType: this,
1003
+ defaultValue: defaultValueFunc,
1004
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1005
+ });
1006
+ }
1007
+ brand() {
1008
+ return new ZodBranded({
1009
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1010
+ type: this,
1011
+ ...processCreateParams(this._def)
1012
+ });
1013
+ }
1014
+ catch(def) {
1015
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1016
+ return new ZodCatch({
1017
+ ...processCreateParams(this._def),
1018
+ innerType: this,
1019
+ catchValue: catchValueFunc,
1020
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1021
+ });
1022
+ }
1023
+ describe(description) {
1024
+ const This = this.constructor;
1025
+ return new This({
1026
+ ...this._def,
1027
+ description
1028
+ });
1029
+ }
1030
+ pipe(target) {
1031
+ return ZodPipeline.create(this, target);
1032
+ }
1033
+ isOptional() {
1034
+ return this.safeParse(void 0).success;
1035
+ }
1036
+ isNullable() {
1037
+ return this.safeParse(null).success;
1038
+ }
1039
+ };
1040
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1041
+ var cuid2Regex = /^[a-z][a-z0-9]*$/;
1042
+ var ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
1043
+ var uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
1044
+ var emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
1045
+ var emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
1046
+ var ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
1047
+ var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
1048
+ var datetimeRegex = (args) => {
1049
+ if (args.precision) {
1050
+ if (args.offset) {
1051
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1052
+ } else {
1053
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
1054
+ }
1055
+ } else if (args.precision === 0) {
1056
+ if (args.offset) {
1057
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1058
+ } else {
1059
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
1060
+ }
1061
+ } else {
1062
+ if (args.offset) {
1063
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1064
+ } else {
1065
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
1066
+ }
1067
+ }
1068
+ };
1069
+ function isValidIP(ip, version) {
1070
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1071
+ return true;
1072
+ }
1073
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1074
+ return true;
1075
+ }
1076
+ return false;
1077
+ }
1078
+ var ZodString = class _ZodString extends ZodType {
1079
+ constructor() {
1080
+ super(...arguments);
1081
+ this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
1082
+ validation,
1083
+ code: ZodIssueCode.invalid_string,
1084
+ ...errorUtil.errToObj(message)
1085
+ });
1086
+ this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
1087
+ this.trim = () => new _ZodString({
1088
+ ...this._def,
1089
+ checks: [...this._def.checks, { kind: "trim" }]
1090
+ });
1091
+ this.toLowerCase = () => new _ZodString({
1092
+ ...this._def,
1093
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1094
+ });
1095
+ this.toUpperCase = () => new _ZodString({
1096
+ ...this._def,
1097
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1098
+ });
1099
+ }
1100
+ _parse(input) {
1101
+ if (this._def.coerce) {
1102
+ input.data = String(input.data);
1103
+ }
1104
+ const parsedType = this._getType(input);
1105
+ if (parsedType !== ZodParsedType.string) {
1106
+ const ctx2 = this._getOrReturnCtx(input);
1107
+ addIssueToContext(
1108
+ ctx2,
1109
+ {
1110
+ code: ZodIssueCode.invalid_type,
1111
+ expected: ZodParsedType.string,
1112
+ received: ctx2.parsedType
1113
+ }
1114
+ //
1115
+ );
1116
+ return INVALID;
1117
+ }
1118
+ const status = new ParseStatus();
1119
+ let ctx = void 0;
1120
+ for (const check of this._def.checks) {
1121
+ if (check.kind === "min") {
1122
+ if (input.data.length < check.value) {
1123
+ ctx = this._getOrReturnCtx(input, ctx);
1124
+ addIssueToContext(ctx, {
1125
+ code: ZodIssueCode.too_small,
1126
+ minimum: check.value,
1127
+ type: "string",
1128
+ inclusive: true,
1129
+ exact: false,
1130
+ message: check.message
1131
+ });
1132
+ status.dirty();
1133
+ }
1134
+ } else if (check.kind === "max") {
1135
+ if (input.data.length > check.value) {
1136
+ ctx = this._getOrReturnCtx(input, ctx);
1137
+ addIssueToContext(ctx, {
1138
+ code: ZodIssueCode.too_big,
1139
+ maximum: check.value,
1140
+ type: "string",
1141
+ inclusive: true,
1142
+ exact: false,
1143
+ message: check.message
1144
+ });
1145
+ status.dirty();
1146
+ }
1147
+ } else if (check.kind === "length") {
1148
+ const tooBig = input.data.length > check.value;
1149
+ const tooSmall = input.data.length < check.value;
1150
+ if (tooBig || tooSmall) {
1151
+ ctx = this._getOrReturnCtx(input, ctx);
1152
+ if (tooBig) {
1153
+ addIssueToContext(ctx, {
1154
+ code: ZodIssueCode.too_big,
1155
+ maximum: check.value,
1156
+ type: "string",
1157
+ inclusive: true,
1158
+ exact: true,
1159
+ message: check.message
1160
+ });
1161
+ } else if (tooSmall) {
1162
+ addIssueToContext(ctx, {
1163
+ code: ZodIssueCode.too_small,
1164
+ minimum: check.value,
1165
+ type: "string",
1166
+ inclusive: true,
1167
+ exact: true,
1168
+ message: check.message
1169
+ });
1170
+ }
1171
+ status.dirty();
1172
+ }
1173
+ } else if (check.kind === "email") {
1174
+ if (!emailRegex.test(input.data)) {
1175
+ ctx = this._getOrReturnCtx(input, ctx);
1176
+ addIssueToContext(ctx, {
1177
+ validation: "email",
1178
+ code: ZodIssueCode.invalid_string,
1179
+ message: check.message
1180
+ });
1181
+ status.dirty();
1182
+ }
1183
+ } else if (check.kind === "emoji") {
1184
+ if (!emojiRegex.test(input.data)) {
1185
+ ctx = this._getOrReturnCtx(input, ctx);
1186
+ addIssueToContext(ctx, {
1187
+ validation: "emoji",
1188
+ code: ZodIssueCode.invalid_string,
1189
+ message: check.message
1190
+ });
1191
+ status.dirty();
1192
+ }
1193
+ } else if (check.kind === "uuid") {
1194
+ if (!uuidRegex.test(input.data)) {
1195
+ ctx = this._getOrReturnCtx(input, ctx);
1196
+ addIssueToContext(ctx, {
1197
+ validation: "uuid",
1198
+ code: ZodIssueCode.invalid_string,
1199
+ message: check.message
1200
+ });
1201
+ status.dirty();
1202
+ }
1203
+ } else if (check.kind === "cuid") {
1204
+ if (!cuidRegex.test(input.data)) {
1205
+ ctx = this._getOrReturnCtx(input, ctx);
1206
+ addIssueToContext(ctx, {
1207
+ validation: "cuid",
1208
+ code: ZodIssueCode.invalid_string,
1209
+ message: check.message
1210
+ });
1211
+ status.dirty();
1212
+ }
1213
+ } else if (check.kind === "cuid2") {
1214
+ if (!cuid2Regex.test(input.data)) {
1215
+ ctx = this._getOrReturnCtx(input, ctx);
1216
+ addIssueToContext(ctx, {
1217
+ validation: "cuid2",
1218
+ code: ZodIssueCode.invalid_string,
1219
+ message: check.message
1220
+ });
1221
+ status.dirty();
1222
+ }
1223
+ } else if (check.kind === "ulid") {
1224
+ if (!ulidRegex.test(input.data)) {
1225
+ ctx = this._getOrReturnCtx(input, ctx);
1226
+ addIssueToContext(ctx, {
1227
+ validation: "ulid",
1228
+ code: ZodIssueCode.invalid_string,
1229
+ message: check.message
1230
+ });
1231
+ status.dirty();
1232
+ }
1233
+ } else if (check.kind === "url") {
1234
+ try {
1235
+ new URL(input.data);
1236
+ } catch (_a) {
1237
+ ctx = this._getOrReturnCtx(input, ctx);
1238
+ addIssueToContext(ctx, {
1239
+ validation: "url",
1240
+ code: ZodIssueCode.invalid_string,
1241
+ message: check.message
1242
+ });
1243
+ status.dirty();
1244
+ }
1245
+ } else if (check.kind === "regex") {
1246
+ check.regex.lastIndex = 0;
1247
+ const testResult = check.regex.test(input.data);
1248
+ if (!testResult) {
1249
+ ctx = this._getOrReturnCtx(input, ctx);
1250
+ addIssueToContext(ctx, {
1251
+ validation: "regex",
1252
+ code: ZodIssueCode.invalid_string,
1253
+ message: check.message
1254
+ });
1255
+ status.dirty();
1256
+ }
1257
+ } else if (check.kind === "trim") {
1258
+ input.data = input.data.trim();
1259
+ } else if (check.kind === "includes") {
1260
+ if (!input.data.includes(check.value, check.position)) {
1261
+ ctx = this._getOrReturnCtx(input, ctx);
1262
+ addIssueToContext(ctx, {
1263
+ code: ZodIssueCode.invalid_string,
1264
+ validation: { includes: check.value, position: check.position },
1265
+ message: check.message
1266
+ });
1267
+ status.dirty();
1268
+ }
1269
+ } else if (check.kind === "toLowerCase") {
1270
+ input.data = input.data.toLowerCase();
1271
+ } else if (check.kind === "toUpperCase") {
1272
+ input.data = input.data.toUpperCase();
1273
+ } else if (check.kind === "startsWith") {
1274
+ if (!input.data.startsWith(check.value)) {
1275
+ ctx = this._getOrReturnCtx(input, ctx);
1276
+ addIssueToContext(ctx, {
1277
+ code: ZodIssueCode.invalid_string,
1278
+ validation: { startsWith: check.value },
1279
+ message: check.message
1280
+ });
1281
+ status.dirty();
1282
+ }
1283
+ } else if (check.kind === "endsWith") {
1284
+ if (!input.data.endsWith(check.value)) {
1285
+ ctx = this._getOrReturnCtx(input, ctx);
1286
+ addIssueToContext(ctx, {
1287
+ code: ZodIssueCode.invalid_string,
1288
+ validation: { endsWith: check.value },
1289
+ message: check.message
1290
+ });
1291
+ status.dirty();
1292
+ }
1293
+ } else if (check.kind === "datetime") {
1294
+ const regex = datetimeRegex(check);
1295
+ if (!regex.test(input.data)) {
1296
+ ctx = this._getOrReturnCtx(input, ctx);
1297
+ addIssueToContext(ctx, {
1298
+ code: ZodIssueCode.invalid_string,
1299
+ validation: "datetime",
1300
+ message: check.message
1301
+ });
1302
+ status.dirty();
1303
+ }
1304
+ } else if (check.kind === "ip") {
1305
+ if (!isValidIP(input.data, check.version)) {
1306
+ ctx = this._getOrReturnCtx(input, ctx);
1307
+ addIssueToContext(ctx, {
1308
+ validation: "ip",
1309
+ code: ZodIssueCode.invalid_string,
1310
+ message: check.message
1311
+ });
1312
+ status.dirty();
1313
+ }
1314
+ } else {
1315
+ util.assertNever(check);
1316
+ }
1317
+ }
1318
+ return { status: status.value, value: input.data };
1319
+ }
1320
+ _addCheck(check) {
1321
+ return new _ZodString({
1322
+ ...this._def,
1323
+ checks: [...this._def.checks, check]
1324
+ });
1325
+ }
1326
+ email(message) {
1327
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1328
+ }
1329
+ url(message) {
1330
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1331
+ }
1332
+ emoji(message) {
1333
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1334
+ }
1335
+ uuid(message) {
1336
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1337
+ }
1338
+ cuid(message) {
1339
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1340
+ }
1341
+ cuid2(message) {
1342
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1343
+ }
1344
+ ulid(message) {
1345
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1346
+ }
1347
+ ip(options) {
1348
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1349
+ }
1350
+ datetime(options) {
1351
+ var _a;
1352
+ if (typeof options === "string") {
1353
+ return this._addCheck({
1354
+ kind: "datetime",
1355
+ precision: null,
1356
+ offset: false,
1357
+ message: options
1358
+ });
1359
+ }
1360
+ return this._addCheck({
1361
+ kind: "datetime",
1362
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1363
+ offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
1364
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
1365
+ });
1366
+ }
1367
+ regex(regex, message) {
1368
+ return this._addCheck({
1369
+ kind: "regex",
1370
+ regex,
1371
+ ...errorUtil.errToObj(message)
1372
+ });
1373
+ }
1374
+ includes(value, options) {
1375
+ return this._addCheck({
1376
+ kind: "includes",
1377
+ value,
1378
+ position: options === null || options === void 0 ? void 0 : options.position,
1379
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
1380
+ });
1381
+ }
1382
+ startsWith(value, message) {
1383
+ return this._addCheck({
1384
+ kind: "startsWith",
1385
+ value,
1386
+ ...errorUtil.errToObj(message)
1387
+ });
1388
+ }
1389
+ endsWith(value, message) {
1390
+ return this._addCheck({
1391
+ kind: "endsWith",
1392
+ value,
1393
+ ...errorUtil.errToObj(message)
1394
+ });
1395
+ }
1396
+ min(minLength, message) {
1397
+ return this._addCheck({
1398
+ kind: "min",
1399
+ value: minLength,
1400
+ ...errorUtil.errToObj(message)
1401
+ });
1402
+ }
1403
+ max(maxLength, message) {
1404
+ return this._addCheck({
1405
+ kind: "max",
1406
+ value: maxLength,
1407
+ ...errorUtil.errToObj(message)
1408
+ });
1409
+ }
1410
+ length(len, message) {
1411
+ return this._addCheck({
1412
+ kind: "length",
1413
+ value: len,
1414
+ ...errorUtil.errToObj(message)
1415
+ });
1416
+ }
1417
+ get isDatetime() {
1418
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1419
+ }
1420
+ get isEmail() {
1421
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1422
+ }
1423
+ get isURL() {
1424
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1425
+ }
1426
+ get isEmoji() {
1427
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1428
+ }
1429
+ get isUUID() {
1430
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1431
+ }
1432
+ get isCUID() {
1433
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1434
+ }
1435
+ get isCUID2() {
1436
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1437
+ }
1438
+ get isULID() {
1439
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1440
+ }
1441
+ get isIP() {
1442
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1443
+ }
1444
+ get minLength() {
1445
+ let min = null;
1446
+ for (const ch of this._def.checks) {
1447
+ if (ch.kind === "min") {
1448
+ if (min === null || ch.value > min)
1449
+ min = ch.value;
1450
+ }
1451
+ }
1452
+ return min;
1453
+ }
1454
+ get maxLength() {
1455
+ let max = null;
1456
+ for (const ch of this._def.checks) {
1457
+ if (ch.kind === "max") {
1458
+ if (max === null || ch.value < max)
1459
+ max = ch.value;
1460
+ }
1461
+ }
1462
+ return max;
1463
+ }
1464
+ };
1465
+ ZodString.create = (params) => {
1466
+ var _a;
1467
+ return new ZodString({
1468
+ checks: [],
1469
+ typeName: ZodFirstPartyTypeKind.ZodString,
1470
+ coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
1471
+ ...processCreateParams(params)
1472
+ });
1473
+ };
1474
+ function floatSafeRemainder(val, step) {
1475
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1476
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1477
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1478
+ const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
1479
+ const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
1480
+ return valInt % stepInt / Math.pow(10, decCount);
1481
+ }
1482
+ var ZodNumber = class _ZodNumber extends ZodType {
1483
+ constructor() {
1484
+ super(...arguments);
1485
+ this.min = this.gte;
1486
+ this.max = this.lte;
1487
+ this.step = this.multipleOf;
1488
+ }
1489
+ _parse(input) {
1490
+ if (this._def.coerce) {
1491
+ input.data = Number(input.data);
1492
+ }
1493
+ const parsedType = this._getType(input);
1494
+ if (parsedType !== ZodParsedType.number) {
1495
+ const ctx2 = this._getOrReturnCtx(input);
1496
+ addIssueToContext(ctx2, {
1497
+ code: ZodIssueCode.invalid_type,
1498
+ expected: ZodParsedType.number,
1499
+ received: ctx2.parsedType
1500
+ });
1501
+ return INVALID;
1502
+ }
1503
+ let ctx = void 0;
1504
+ const status = new ParseStatus();
1505
+ for (const check of this._def.checks) {
1506
+ if (check.kind === "int") {
1507
+ if (!util.isInteger(input.data)) {
1508
+ ctx = this._getOrReturnCtx(input, ctx);
1509
+ addIssueToContext(ctx, {
1510
+ code: ZodIssueCode.invalid_type,
1511
+ expected: "integer",
1512
+ received: "float",
1513
+ message: check.message
1514
+ });
1515
+ status.dirty();
1516
+ }
1517
+ } else if (check.kind === "min") {
1518
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1519
+ if (tooSmall) {
1520
+ ctx = this._getOrReturnCtx(input, ctx);
1521
+ addIssueToContext(ctx, {
1522
+ code: ZodIssueCode.too_small,
1523
+ minimum: check.value,
1524
+ type: "number",
1525
+ inclusive: check.inclusive,
1526
+ exact: false,
1527
+ message: check.message
1528
+ });
1529
+ status.dirty();
1530
+ }
1531
+ } else if (check.kind === "max") {
1532
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1533
+ if (tooBig) {
1534
+ ctx = this._getOrReturnCtx(input, ctx);
1535
+ addIssueToContext(ctx, {
1536
+ code: ZodIssueCode.too_big,
1537
+ maximum: check.value,
1538
+ type: "number",
1539
+ inclusive: check.inclusive,
1540
+ exact: false,
1541
+ message: check.message
1542
+ });
1543
+ status.dirty();
1544
+ }
1545
+ } else if (check.kind === "multipleOf") {
1546
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1547
+ ctx = this._getOrReturnCtx(input, ctx);
1548
+ addIssueToContext(ctx, {
1549
+ code: ZodIssueCode.not_multiple_of,
1550
+ multipleOf: check.value,
1551
+ message: check.message
1552
+ });
1553
+ status.dirty();
1554
+ }
1555
+ } else if (check.kind === "finite") {
1556
+ if (!Number.isFinite(input.data)) {
1557
+ ctx = this._getOrReturnCtx(input, ctx);
1558
+ addIssueToContext(ctx, {
1559
+ code: ZodIssueCode.not_finite,
1560
+ message: check.message
1561
+ });
1562
+ status.dirty();
1563
+ }
1564
+ } else {
1565
+ util.assertNever(check);
1566
+ }
1567
+ }
1568
+ return { status: status.value, value: input.data };
1569
+ }
1570
+ gte(value, message) {
1571
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1572
+ }
1573
+ gt(value, message) {
1574
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1575
+ }
1576
+ lte(value, message) {
1577
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1578
+ }
1579
+ lt(value, message) {
1580
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1581
+ }
1582
+ setLimit(kind, value, inclusive, message) {
1583
+ return new _ZodNumber({
1584
+ ...this._def,
1585
+ checks: [
1586
+ ...this._def.checks,
1587
+ {
1588
+ kind,
1589
+ value,
1590
+ inclusive,
1591
+ message: errorUtil.toString(message)
1592
+ }
1593
+ ]
1594
+ });
1595
+ }
1596
+ _addCheck(check) {
1597
+ return new _ZodNumber({
1598
+ ...this._def,
1599
+ checks: [...this._def.checks, check]
1600
+ });
1601
+ }
1602
+ int(message) {
1603
+ return this._addCheck({
1604
+ kind: "int",
1605
+ message: errorUtil.toString(message)
1606
+ });
1607
+ }
1608
+ positive(message) {
1609
+ return this._addCheck({
1610
+ kind: "min",
1611
+ value: 0,
1612
+ inclusive: false,
1613
+ message: errorUtil.toString(message)
1614
+ });
1615
+ }
1616
+ negative(message) {
1617
+ return this._addCheck({
1618
+ kind: "max",
1619
+ value: 0,
1620
+ inclusive: false,
1621
+ message: errorUtil.toString(message)
1622
+ });
1623
+ }
1624
+ nonpositive(message) {
1625
+ return this._addCheck({
1626
+ kind: "max",
1627
+ value: 0,
1628
+ inclusive: true,
1629
+ message: errorUtil.toString(message)
1630
+ });
1631
+ }
1632
+ nonnegative(message) {
1633
+ return this._addCheck({
1634
+ kind: "min",
1635
+ value: 0,
1636
+ inclusive: true,
1637
+ message: errorUtil.toString(message)
1638
+ });
1639
+ }
1640
+ multipleOf(value, message) {
1641
+ return this._addCheck({
1642
+ kind: "multipleOf",
1643
+ value,
1644
+ message: errorUtil.toString(message)
1645
+ });
1646
+ }
1647
+ finite(message) {
1648
+ return this._addCheck({
1649
+ kind: "finite",
1650
+ message: errorUtil.toString(message)
1651
+ });
1652
+ }
1653
+ safe(message) {
1654
+ return this._addCheck({
1655
+ kind: "min",
1656
+ inclusive: true,
1657
+ value: Number.MIN_SAFE_INTEGER,
1658
+ message: errorUtil.toString(message)
1659
+ })._addCheck({
1660
+ kind: "max",
1661
+ inclusive: true,
1662
+ value: Number.MAX_SAFE_INTEGER,
1663
+ message: errorUtil.toString(message)
1664
+ });
1665
+ }
1666
+ get minValue() {
1667
+ let min = null;
1668
+ for (const ch of this._def.checks) {
1669
+ if (ch.kind === "min") {
1670
+ if (min === null || ch.value > min)
1671
+ min = ch.value;
1672
+ }
1673
+ }
1674
+ return min;
1675
+ }
1676
+ get maxValue() {
1677
+ let max = null;
1678
+ for (const ch of this._def.checks) {
1679
+ if (ch.kind === "max") {
1680
+ if (max === null || ch.value < max)
1681
+ max = ch.value;
1682
+ }
1683
+ }
1684
+ return max;
1685
+ }
1686
+ get isInt() {
1687
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1688
+ }
1689
+ get isFinite() {
1690
+ let max = null, min = null;
1691
+ for (const ch of this._def.checks) {
1692
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1693
+ return true;
1694
+ } else if (ch.kind === "min") {
1695
+ if (min === null || ch.value > min)
1696
+ min = ch.value;
1697
+ } else if (ch.kind === "max") {
1698
+ if (max === null || ch.value < max)
1699
+ max = ch.value;
1700
+ }
1701
+ }
1702
+ return Number.isFinite(min) && Number.isFinite(max);
1703
+ }
1704
+ };
1705
+ ZodNumber.create = (params) => {
1706
+ return new ZodNumber({
1707
+ checks: [],
1708
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1709
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
1710
+ ...processCreateParams(params)
1711
+ });
1712
+ };
1713
+ var ZodBigInt = class _ZodBigInt extends ZodType {
1714
+ constructor() {
1715
+ super(...arguments);
1716
+ this.min = this.gte;
1717
+ this.max = this.lte;
1718
+ }
1719
+ _parse(input) {
1720
+ if (this._def.coerce) {
1721
+ input.data = BigInt(input.data);
1722
+ }
1723
+ const parsedType = this._getType(input);
1724
+ if (parsedType !== ZodParsedType.bigint) {
1725
+ const ctx2 = this._getOrReturnCtx(input);
1726
+ addIssueToContext(ctx2, {
1727
+ code: ZodIssueCode.invalid_type,
1728
+ expected: ZodParsedType.bigint,
1729
+ received: ctx2.parsedType
1730
+ });
1731
+ return INVALID;
1732
+ }
1733
+ let ctx = void 0;
1734
+ const status = new ParseStatus();
1735
+ for (const check of this._def.checks) {
1736
+ if (check.kind === "min") {
1737
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1738
+ if (tooSmall) {
1739
+ ctx = this._getOrReturnCtx(input, ctx);
1740
+ addIssueToContext(ctx, {
1741
+ code: ZodIssueCode.too_small,
1742
+ type: "bigint",
1743
+ minimum: check.value,
1744
+ inclusive: check.inclusive,
1745
+ message: check.message
1746
+ });
1747
+ status.dirty();
1748
+ }
1749
+ } else if (check.kind === "max") {
1750
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1751
+ if (tooBig) {
1752
+ ctx = this._getOrReturnCtx(input, ctx);
1753
+ addIssueToContext(ctx, {
1754
+ code: ZodIssueCode.too_big,
1755
+ type: "bigint",
1756
+ maximum: check.value,
1757
+ inclusive: check.inclusive,
1758
+ message: check.message
1759
+ });
1760
+ status.dirty();
1761
+ }
1762
+ } else if (check.kind === "multipleOf") {
1763
+ if (input.data % check.value !== BigInt(0)) {
1764
+ ctx = this._getOrReturnCtx(input, ctx);
1765
+ addIssueToContext(ctx, {
1766
+ code: ZodIssueCode.not_multiple_of,
1767
+ multipleOf: check.value,
1768
+ message: check.message
1769
+ });
1770
+ status.dirty();
1771
+ }
1772
+ } else {
1773
+ util.assertNever(check);
1774
+ }
1775
+ }
1776
+ return { status: status.value, value: input.data };
1777
+ }
1778
+ gte(value, message) {
1779
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1780
+ }
1781
+ gt(value, message) {
1782
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1783
+ }
1784
+ lte(value, message) {
1785
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1786
+ }
1787
+ lt(value, message) {
1788
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1789
+ }
1790
+ setLimit(kind, value, inclusive, message) {
1791
+ return new _ZodBigInt({
1792
+ ...this._def,
1793
+ checks: [
1794
+ ...this._def.checks,
1795
+ {
1796
+ kind,
1797
+ value,
1798
+ inclusive,
1799
+ message: errorUtil.toString(message)
1800
+ }
1801
+ ]
1802
+ });
1803
+ }
1804
+ _addCheck(check) {
1805
+ return new _ZodBigInt({
1806
+ ...this._def,
1807
+ checks: [...this._def.checks, check]
1808
+ });
1809
+ }
1810
+ positive(message) {
1811
+ return this._addCheck({
1812
+ kind: "min",
1813
+ value: BigInt(0),
1814
+ inclusive: false,
1815
+ message: errorUtil.toString(message)
1816
+ });
1817
+ }
1818
+ negative(message) {
1819
+ return this._addCheck({
1820
+ kind: "max",
1821
+ value: BigInt(0),
1822
+ inclusive: false,
1823
+ message: errorUtil.toString(message)
1824
+ });
1825
+ }
1826
+ nonpositive(message) {
1827
+ return this._addCheck({
1828
+ kind: "max",
1829
+ value: BigInt(0),
1830
+ inclusive: true,
1831
+ message: errorUtil.toString(message)
1832
+ });
1833
+ }
1834
+ nonnegative(message) {
1835
+ return this._addCheck({
1836
+ kind: "min",
1837
+ value: BigInt(0),
1838
+ inclusive: true,
1839
+ message: errorUtil.toString(message)
1840
+ });
1841
+ }
1842
+ multipleOf(value, message) {
1843
+ return this._addCheck({
1844
+ kind: "multipleOf",
1845
+ value,
1846
+ message: errorUtil.toString(message)
1847
+ });
1848
+ }
1849
+ get minValue() {
1850
+ let min = null;
1851
+ for (const ch of this._def.checks) {
1852
+ if (ch.kind === "min") {
1853
+ if (min === null || ch.value > min)
1854
+ min = ch.value;
1855
+ }
1856
+ }
1857
+ return min;
1858
+ }
1859
+ get maxValue() {
1860
+ let max = null;
1861
+ for (const ch of this._def.checks) {
1862
+ if (ch.kind === "max") {
1863
+ if (max === null || ch.value < max)
1864
+ max = ch.value;
1865
+ }
1866
+ }
1867
+ return max;
1868
+ }
1869
+ };
1870
+ ZodBigInt.create = (params) => {
1871
+ var _a;
1872
+ return new ZodBigInt({
1873
+ checks: [],
1874
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
1875
+ coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
1876
+ ...processCreateParams(params)
1877
+ });
1878
+ };
1879
+ var ZodBoolean = class extends ZodType {
1880
+ _parse(input) {
1881
+ if (this._def.coerce) {
1882
+ input.data = Boolean(input.data);
1883
+ }
1884
+ const parsedType = this._getType(input);
1885
+ if (parsedType !== ZodParsedType.boolean) {
1886
+ const ctx = this._getOrReturnCtx(input);
1887
+ addIssueToContext(ctx, {
1888
+ code: ZodIssueCode.invalid_type,
1889
+ expected: ZodParsedType.boolean,
1890
+ received: ctx.parsedType
1891
+ });
1892
+ return INVALID;
1893
+ }
1894
+ return OK(input.data);
1895
+ }
1896
+ };
1897
+ ZodBoolean.create = (params) => {
1898
+ return new ZodBoolean({
1899
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
1900
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
1901
+ ...processCreateParams(params)
1902
+ });
1903
+ };
1904
+ var ZodDate = class _ZodDate extends ZodType {
1905
+ _parse(input) {
1906
+ if (this._def.coerce) {
1907
+ input.data = new Date(input.data);
1908
+ }
1909
+ const parsedType = this._getType(input);
1910
+ if (parsedType !== ZodParsedType.date) {
1911
+ const ctx2 = this._getOrReturnCtx(input);
1912
+ addIssueToContext(ctx2, {
1913
+ code: ZodIssueCode.invalid_type,
1914
+ expected: ZodParsedType.date,
1915
+ received: ctx2.parsedType
1916
+ });
1917
+ return INVALID;
1918
+ }
1919
+ if (isNaN(input.data.getTime())) {
1920
+ const ctx2 = this._getOrReturnCtx(input);
1921
+ addIssueToContext(ctx2, {
1922
+ code: ZodIssueCode.invalid_date
1923
+ });
1924
+ return INVALID;
1925
+ }
1926
+ const status = new ParseStatus();
1927
+ let ctx = void 0;
1928
+ for (const check of this._def.checks) {
1929
+ if (check.kind === "min") {
1930
+ if (input.data.getTime() < check.value) {
1931
+ ctx = this._getOrReturnCtx(input, ctx);
1932
+ addIssueToContext(ctx, {
1933
+ code: ZodIssueCode.too_small,
1934
+ message: check.message,
1935
+ inclusive: true,
1936
+ exact: false,
1937
+ minimum: check.value,
1938
+ type: "date"
1939
+ });
1940
+ status.dirty();
1941
+ }
1942
+ } else if (check.kind === "max") {
1943
+ if (input.data.getTime() > check.value) {
1944
+ ctx = this._getOrReturnCtx(input, ctx);
1945
+ addIssueToContext(ctx, {
1946
+ code: ZodIssueCode.too_big,
1947
+ message: check.message,
1948
+ inclusive: true,
1949
+ exact: false,
1950
+ maximum: check.value,
1951
+ type: "date"
1952
+ });
1953
+ status.dirty();
1954
+ }
1955
+ } else {
1956
+ util.assertNever(check);
1957
+ }
1958
+ }
1959
+ return {
1960
+ status: status.value,
1961
+ value: new Date(input.data.getTime())
1962
+ };
1963
+ }
1964
+ _addCheck(check) {
1965
+ return new _ZodDate({
1966
+ ...this._def,
1967
+ checks: [...this._def.checks, check]
1968
+ });
1969
+ }
1970
+ min(minDate, message) {
1971
+ return this._addCheck({
1972
+ kind: "min",
1973
+ value: minDate.getTime(),
1974
+ message: errorUtil.toString(message)
1975
+ });
1976
+ }
1977
+ max(maxDate, message) {
1978
+ return this._addCheck({
1979
+ kind: "max",
1980
+ value: maxDate.getTime(),
1981
+ message: errorUtil.toString(message)
1982
+ });
1983
+ }
1984
+ get minDate() {
1985
+ let min = null;
1986
+ for (const ch of this._def.checks) {
1987
+ if (ch.kind === "min") {
1988
+ if (min === null || ch.value > min)
1989
+ min = ch.value;
1990
+ }
1991
+ }
1992
+ return min != null ? new Date(min) : null;
1993
+ }
1994
+ get maxDate() {
1995
+ let max = null;
1996
+ for (const ch of this._def.checks) {
1997
+ if (ch.kind === "max") {
1998
+ if (max === null || ch.value < max)
1999
+ max = ch.value;
2000
+ }
2001
+ }
2002
+ return max != null ? new Date(max) : null;
2003
+ }
2004
+ };
2005
+ ZodDate.create = (params) => {
2006
+ return new ZodDate({
2007
+ checks: [],
2008
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
2009
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2010
+ ...processCreateParams(params)
2011
+ });
2012
+ };
2013
+ var ZodSymbol = class extends ZodType {
2014
+ _parse(input) {
2015
+ const parsedType = this._getType(input);
2016
+ if (parsedType !== ZodParsedType.symbol) {
2017
+ const ctx = this._getOrReturnCtx(input);
2018
+ addIssueToContext(ctx, {
2019
+ code: ZodIssueCode.invalid_type,
2020
+ expected: ZodParsedType.symbol,
2021
+ received: ctx.parsedType
2022
+ });
2023
+ return INVALID;
2024
+ }
2025
+ return OK(input.data);
2026
+ }
2027
+ };
2028
+ ZodSymbol.create = (params) => {
2029
+ return new ZodSymbol({
2030
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2031
+ ...processCreateParams(params)
2032
+ });
2033
+ };
2034
+ var ZodUndefined = class extends ZodType {
2035
+ _parse(input) {
2036
+ const parsedType = this._getType(input);
2037
+ if (parsedType !== ZodParsedType.undefined) {
2038
+ const ctx = this._getOrReturnCtx(input);
2039
+ addIssueToContext(ctx, {
2040
+ code: ZodIssueCode.invalid_type,
2041
+ expected: ZodParsedType.undefined,
2042
+ received: ctx.parsedType
2043
+ });
2044
+ return INVALID;
2045
+ }
2046
+ return OK(input.data);
2047
+ }
2048
+ };
2049
+ ZodUndefined.create = (params) => {
2050
+ return new ZodUndefined({
2051
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2052
+ ...processCreateParams(params)
2053
+ });
2054
+ };
2055
+ var ZodNull = class extends ZodType {
2056
+ _parse(input) {
2057
+ const parsedType = this._getType(input);
2058
+ if (parsedType !== ZodParsedType.null) {
2059
+ const ctx = this._getOrReturnCtx(input);
2060
+ addIssueToContext(ctx, {
2061
+ code: ZodIssueCode.invalid_type,
2062
+ expected: ZodParsedType.null,
2063
+ received: ctx.parsedType
2064
+ });
2065
+ return INVALID;
2066
+ }
2067
+ return OK(input.data);
2068
+ }
2069
+ };
2070
+ ZodNull.create = (params) => {
2071
+ return new ZodNull({
2072
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2073
+ ...processCreateParams(params)
2074
+ });
2075
+ };
2076
+ var ZodAny = class extends ZodType {
2077
+ constructor() {
2078
+ super(...arguments);
2079
+ this._any = true;
2080
+ }
2081
+ _parse(input) {
2082
+ return OK(input.data);
2083
+ }
2084
+ };
2085
+ ZodAny.create = (params) => {
2086
+ return new ZodAny({
2087
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2088
+ ...processCreateParams(params)
2089
+ });
2090
+ };
2091
+ var ZodUnknown = class extends ZodType {
2092
+ constructor() {
2093
+ super(...arguments);
2094
+ this._unknown = true;
2095
+ }
2096
+ _parse(input) {
2097
+ return OK(input.data);
2098
+ }
2099
+ };
2100
+ ZodUnknown.create = (params) => {
2101
+ return new ZodUnknown({
2102
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2103
+ ...processCreateParams(params)
2104
+ });
2105
+ };
2106
+ var ZodNever = class extends ZodType {
2107
+ _parse(input) {
2108
+ const ctx = this._getOrReturnCtx(input);
2109
+ addIssueToContext(ctx, {
2110
+ code: ZodIssueCode.invalid_type,
2111
+ expected: ZodParsedType.never,
2112
+ received: ctx.parsedType
2113
+ });
2114
+ return INVALID;
2115
+ }
2116
+ };
2117
+ ZodNever.create = (params) => {
2118
+ return new ZodNever({
2119
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2120
+ ...processCreateParams(params)
2121
+ });
2122
+ };
2123
+ var ZodVoid = class extends ZodType {
2124
+ _parse(input) {
2125
+ const parsedType = this._getType(input);
2126
+ if (parsedType !== ZodParsedType.undefined) {
2127
+ const ctx = this._getOrReturnCtx(input);
2128
+ addIssueToContext(ctx, {
2129
+ code: ZodIssueCode.invalid_type,
2130
+ expected: ZodParsedType.void,
2131
+ received: ctx.parsedType
2132
+ });
2133
+ return INVALID;
2134
+ }
2135
+ return OK(input.data);
2136
+ }
2137
+ };
2138
+ ZodVoid.create = (params) => {
2139
+ return new ZodVoid({
2140
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2141
+ ...processCreateParams(params)
2142
+ });
2143
+ };
2144
+ var ZodArray = class _ZodArray extends ZodType {
2145
+ _parse(input) {
2146
+ const { ctx, status } = this._processInputParams(input);
2147
+ const def = this._def;
2148
+ if (ctx.parsedType !== ZodParsedType.array) {
2149
+ addIssueToContext(ctx, {
2150
+ code: ZodIssueCode.invalid_type,
2151
+ expected: ZodParsedType.array,
2152
+ received: ctx.parsedType
2153
+ });
2154
+ return INVALID;
2155
+ }
2156
+ if (def.exactLength !== null) {
2157
+ const tooBig = ctx.data.length > def.exactLength.value;
2158
+ const tooSmall = ctx.data.length < def.exactLength.value;
2159
+ if (tooBig || tooSmall) {
2160
+ addIssueToContext(ctx, {
2161
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2162
+ minimum: tooSmall ? def.exactLength.value : void 0,
2163
+ maximum: tooBig ? def.exactLength.value : void 0,
2164
+ type: "array",
2165
+ inclusive: true,
2166
+ exact: true,
2167
+ message: def.exactLength.message
2168
+ });
2169
+ status.dirty();
2170
+ }
2171
+ }
2172
+ if (def.minLength !== null) {
2173
+ if (ctx.data.length < def.minLength.value) {
2174
+ addIssueToContext(ctx, {
2175
+ code: ZodIssueCode.too_small,
2176
+ minimum: def.minLength.value,
2177
+ type: "array",
2178
+ inclusive: true,
2179
+ exact: false,
2180
+ message: def.minLength.message
2181
+ });
2182
+ status.dirty();
2183
+ }
2184
+ }
2185
+ if (def.maxLength !== null) {
2186
+ if (ctx.data.length > def.maxLength.value) {
2187
+ addIssueToContext(ctx, {
2188
+ code: ZodIssueCode.too_big,
2189
+ maximum: def.maxLength.value,
2190
+ type: "array",
2191
+ inclusive: true,
2192
+ exact: false,
2193
+ message: def.maxLength.message
2194
+ });
2195
+ status.dirty();
2196
+ }
2197
+ }
2198
+ if (ctx.common.async) {
2199
+ return Promise.all([...ctx.data].map((item, i) => {
2200
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2201
+ })).then((result2) => {
2202
+ return ParseStatus.mergeArray(status, result2);
2203
+ });
2204
+ }
2205
+ const result = [...ctx.data].map((item, i) => {
2206
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2207
+ });
2208
+ return ParseStatus.mergeArray(status, result);
2209
+ }
2210
+ get element() {
2211
+ return this._def.type;
2212
+ }
2213
+ min(minLength, message) {
2214
+ return new _ZodArray({
2215
+ ...this._def,
2216
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2217
+ });
2218
+ }
2219
+ max(maxLength, message) {
2220
+ return new _ZodArray({
2221
+ ...this._def,
2222
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
2223
+ });
2224
+ }
2225
+ length(len, message) {
2226
+ return new _ZodArray({
2227
+ ...this._def,
2228
+ exactLength: { value: len, message: errorUtil.toString(message) }
2229
+ });
2230
+ }
2231
+ nonempty(message) {
2232
+ return this.min(1, message);
2233
+ }
2234
+ };
2235
+ ZodArray.create = (schema, params) => {
2236
+ return new ZodArray({
2237
+ type: schema,
2238
+ minLength: null,
2239
+ maxLength: null,
2240
+ exactLength: null,
2241
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2242
+ ...processCreateParams(params)
2243
+ });
2244
+ };
2245
+ function deepPartialify(schema) {
2246
+ if (schema instanceof ZodObject) {
2247
+ const newShape = {};
2248
+ for (const key in schema.shape) {
2249
+ const fieldSchema = schema.shape[key];
2250
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2251
+ }
2252
+ return new ZodObject({
2253
+ ...schema._def,
2254
+ shape: () => newShape
2255
+ });
2256
+ } else if (schema instanceof ZodArray) {
2257
+ return new ZodArray({
2258
+ ...schema._def,
2259
+ type: deepPartialify(schema.element)
2260
+ });
2261
+ } else if (schema instanceof ZodOptional) {
2262
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2263
+ } else if (schema instanceof ZodNullable) {
2264
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2265
+ } else if (schema instanceof ZodTuple) {
2266
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2267
+ } else {
2268
+ return schema;
2269
+ }
2270
+ }
2271
+ var ZodObject = class _ZodObject extends ZodType {
2272
+ constructor() {
2273
+ super(...arguments);
2274
+ this._cached = null;
2275
+ this.nonstrict = this.passthrough;
2276
+ this.augment = this.extend;
2277
+ }
2278
+ _getCached() {
2279
+ if (this._cached !== null)
2280
+ return this._cached;
2281
+ const shape = this._def.shape();
2282
+ const keys = util.objectKeys(shape);
2283
+ return this._cached = { shape, keys };
2284
+ }
2285
+ _parse(input) {
2286
+ const parsedType = this._getType(input);
2287
+ if (parsedType !== ZodParsedType.object) {
2288
+ const ctx2 = this._getOrReturnCtx(input);
2289
+ addIssueToContext(ctx2, {
2290
+ code: ZodIssueCode.invalid_type,
2291
+ expected: ZodParsedType.object,
2292
+ received: ctx2.parsedType
2293
+ });
2294
+ return INVALID;
2295
+ }
2296
+ const { status, ctx } = this._processInputParams(input);
2297
+ const { shape, keys: shapeKeys } = this._getCached();
2298
+ const extraKeys = [];
2299
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2300
+ for (const key in ctx.data) {
2301
+ if (!shapeKeys.includes(key)) {
2302
+ extraKeys.push(key);
2303
+ }
2304
+ }
2305
+ }
2306
+ const pairs = [];
2307
+ for (const key of shapeKeys) {
2308
+ const keyValidator = shape[key];
2309
+ const value = ctx.data[key];
2310
+ pairs.push({
2311
+ key: { status: "valid", value: key },
2312
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2313
+ alwaysSet: key in ctx.data
2314
+ });
2315
+ }
2316
+ if (this._def.catchall instanceof ZodNever) {
2317
+ const unknownKeys = this._def.unknownKeys;
2318
+ if (unknownKeys === "passthrough") {
2319
+ for (const key of extraKeys) {
2320
+ pairs.push({
2321
+ key: { status: "valid", value: key },
2322
+ value: { status: "valid", value: ctx.data[key] }
2323
+ });
2324
+ }
2325
+ } else if (unknownKeys === "strict") {
2326
+ if (extraKeys.length > 0) {
2327
+ addIssueToContext(ctx, {
2328
+ code: ZodIssueCode.unrecognized_keys,
2329
+ keys: extraKeys
2330
+ });
2331
+ status.dirty();
2332
+ }
2333
+ } else if (unknownKeys === "strip")
2334
+ ;
2335
+ else {
2336
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2337
+ }
2338
+ } else {
2339
+ const catchall = this._def.catchall;
2340
+ for (const key of extraKeys) {
2341
+ const value = ctx.data[key];
2342
+ pairs.push({
2343
+ key: { status: "valid", value: key },
2344
+ value: catchall._parse(
2345
+ new ParseInputLazyPath(ctx, value, ctx.path, key)
2346
+ //, ctx.child(key), value, getParsedType(value)
2347
+ ),
2348
+ alwaysSet: key in ctx.data
2349
+ });
2350
+ }
2351
+ }
2352
+ if (ctx.common.async) {
2353
+ return Promise.resolve().then(async () => {
2354
+ const syncPairs = [];
2355
+ for (const pair of pairs) {
2356
+ const key = await pair.key;
2357
+ syncPairs.push({
2358
+ key,
2359
+ value: await pair.value,
2360
+ alwaysSet: pair.alwaysSet
2361
+ });
2362
+ }
2363
+ return syncPairs;
2364
+ }).then((syncPairs) => {
2365
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2366
+ });
2367
+ } else {
2368
+ return ParseStatus.mergeObjectSync(status, pairs);
2369
+ }
2370
+ }
2371
+ get shape() {
2372
+ return this._def.shape();
2373
+ }
2374
+ strict(message) {
2375
+ errorUtil.errToObj;
2376
+ return new _ZodObject({
2377
+ ...this._def,
2378
+ unknownKeys: "strict",
2379
+ ...message !== void 0 ? {
2380
+ errorMap: (issue, ctx) => {
2381
+ var _a, _b, _c, _d;
2382
+ const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
2383
+ if (issue.code === "unrecognized_keys")
2384
+ return {
2385
+ message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
2386
+ };
2387
+ return {
2388
+ message: defaultError
2389
+ };
2390
+ }
2391
+ } : {}
2392
+ });
2393
+ }
2394
+ strip() {
2395
+ return new _ZodObject({
2396
+ ...this._def,
2397
+ unknownKeys: "strip"
2398
+ });
2399
+ }
2400
+ passthrough() {
2401
+ return new _ZodObject({
2402
+ ...this._def,
2403
+ unknownKeys: "passthrough"
2404
+ });
2405
+ }
2406
+ // const AugmentFactory =
2407
+ // <Def extends ZodObjectDef>(def: Def) =>
2408
+ // <Augmentation extends ZodRawShape>(
2409
+ // augmentation: Augmentation
2410
+ // ): ZodObject<
2411
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2412
+ // Def["unknownKeys"],
2413
+ // Def["catchall"]
2414
+ // > => {
2415
+ // return new ZodObject({
2416
+ // ...def,
2417
+ // shape: () => ({
2418
+ // ...def.shape(),
2419
+ // ...augmentation,
2420
+ // }),
2421
+ // }) as any;
2422
+ // };
2423
+ extend(augmentation) {
2424
+ return new _ZodObject({
2425
+ ...this._def,
2426
+ shape: () => ({
2427
+ ...this._def.shape(),
2428
+ ...augmentation
2429
+ })
2430
+ });
2431
+ }
2432
+ /**
2433
+ * Prior to zod@1.0.12 there was a bug in the
2434
+ * inferred type of merged objects. Please
2435
+ * upgrade if you are experiencing issues.
2436
+ */
2437
+ merge(merging) {
2438
+ const merged = new _ZodObject({
2439
+ unknownKeys: merging._def.unknownKeys,
2440
+ catchall: merging._def.catchall,
2441
+ shape: () => ({
2442
+ ...this._def.shape(),
2443
+ ...merging._def.shape()
2444
+ }),
2445
+ typeName: ZodFirstPartyTypeKind.ZodObject
2446
+ });
2447
+ return merged;
2448
+ }
2449
+ // merge<
2450
+ // Incoming extends AnyZodObject,
2451
+ // Augmentation extends Incoming["shape"],
2452
+ // NewOutput extends {
2453
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2454
+ // ? Augmentation[k]["_output"]
2455
+ // : k extends keyof Output
2456
+ // ? Output[k]
2457
+ // : never;
2458
+ // },
2459
+ // NewInput extends {
2460
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2461
+ // ? Augmentation[k]["_input"]
2462
+ // : k extends keyof Input
2463
+ // ? Input[k]
2464
+ // : never;
2465
+ // }
2466
+ // >(
2467
+ // merging: Incoming
2468
+ // ): ZodObject<
2469
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2470
+ // Incoming["_def"]["unknownKeys"],
2471
+ // Incoming["_def"]["catchall"],
2472
+ // NewOutput,
2473
+ // NewInput
2474
+ // > {
2475
+ // const merged: any = new ZodObject({
2476
+ // unknownKeys: merging._def.unknownKeys,
2477
+ // catchall: merging._def.catchall,
2478
+ // shape: () =>
2479
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2480
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2481
+ // }) as any;
2482
+ // return merged;
2483
+ // }
2484
+ setKey(key, schema) {
2485
+ return this.augment({ [key]: schema });
2486
+ }
2487
+ // merge<Incoming extends AnyZodObject>(
2488
+ // merging: Incoming
2489
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2490
+ // ZodObject<
2491
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2492
+ // Incoming["_def"]["unknownKeys"],
2493
+ // Incoming["_def"]["catchall"]
2494
+ // > {
2495
+ // // const mergedShape = objectUtil.mergeShapes(
2496
+ // // this._def.shape(),
2497
+ // // merging._def.shape()
2498
+ // // );
2499
+ // const merged: any = new ZodObject({
2500
+ // unknownKeys: merging._def.unknownKeys,
2501
+ // catchall: merging._def.catchall,
2502
+ // shape: () =>
2503
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2504
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2505
+ // }) as any;
2506
+ // return merged;
2507
+ // }
2508
+ catchall(index) {
2509
+ return new _ZodObject({
2510
+ ...this._def,
2511
+ catchall: index
2512
+ });
2513
+ }
2514
+ pick(mask) {
2515
+ const shape = {};
2516
+ util.objectKeys(mask).forEach((key) => {
2517
+ if (mask[key] && this.shape[key]) {
2518
+ shape[key] = this.shape[key];
2519
+ }
2520
+ });
2521
+ return new _ZodObject({
2522
+ ...this._def,
2523
+ shape: () => shape
2524
+ });
2525
+ }
2526
+ omit(mask) {
2527
+ const shape = {};
2528
+ util.objectKeys(this.shape).forEach((key) => {
2529
+ if (!mask[key]) {
2530
+ shape[key] = this.shape[key];
2531
+ }
2532
+ });
2533
+ return new _ZodObject({
2534
+ ...this._def,
2535
+ shape: () => shape
2536
+ });
2537
+ }
2538
+ /**
2539
+ * @deprecated
2540
+ */
2541
+ deepPartial() {
2542
+ return deepPartialify(this);
2543
+ }
2544
+ partial(mask) {
2545
+ const newShape = {};
2546
+ util.objectKeys(this.shape).forEach((key) => {
2547
+ const fieldSchema = this.shape[key];
2548
+ if (mask && !mask[key]) {
2549
+ newShape[key] = fieldSchema;
2550
+ } else {
2551
+ newShape[key] = fieldSchema.optional();
2552
+ }
2553
+ });
2554
+ return new _ZodObject({
2555
+ ...this._def,
2556
+ shape: () => newShape
2557
+ });
2558
+ }
2559
+ required(mask) {
2560
+ const newShape = {};
2561
+ util.objectKeys(this.shape).forEach((key) => {
2562
+ if (mask && !mask[key]) {
2563
+ newShape[key] = this.shape[key];
2564
+ } else {
2565
+ const fieldSchema = this.shape[key];
2566
+ let newField = fieldSchema;
2567
+ while (newField instanceof ZodOptional) {
2568
+ newField = newField._def.innerType;
2569
+ }
2570
+ newShape[key] = newField;
2571
+ }
2572
+ });
2573
+ return new _ZodObject({
2574
+ ...this._def,
2575
+ shape: () => newShape
2576
+ });
2577
+ }
2578
+ keyof() {
2579
+ return createZodEnum(util.objectKeys(this.shape));
2580
+ }
2581
+ };
2582
+ ZodObject.create = (shape, params) => {
2583
+ return new ZodObject({
2584
+ shape: () => shape,
2585
+ unknownKeys: "strip",
2586
+ catchall: ZodNever.create(),
2587
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2588
+ ...processCreateParams(params)
2589
+ });
2590
+ };
2591
+ ZodObject.strictCreate = (shape, params) => {
2592
+ return new ZodObject({
2593
+ shape: () => shape,
2594
+ unknownKeys: "strict",
2595
+ catchall: ZodNever.create(),
2596
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2597
+ ...processCreateParams(params)
2598
+ });
2599
+ };
2600
+ ZodObject.lazycreate = (shape, params) => {
2601
+ return new ZodObject({
2602
+ shape,
2603
+ unknownKeys: "strip",
2604
+ catchall: ZodNever.create(),
2605
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2606
+ ...processCreateParams(params)
2607
+ });
2608
+ };
2609
+ var ZodUnion = class extends ZodType {
2610
+ _parse(input) {
2611
+ const { ctx } = this._processInputParams(input);
2612
+ const options = this._def.options;
2613
+ function handleResults(results) {
2614
+ for (const result of results) {
2615
+ if (result.result.status === "valid") {
2616
+ return result.result;
2617
+ }
2618
+ }
2619
+ for (const result of results) {
2620
+ if (result.result.status === "dirty") {
2621
+ ctx.common.issues.push(...result.ctx.common.issues);
2622
+ return result.result;
2623
+ }
2624
+ }
2625
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2626
+ addIssueToContext(ctx, {
2627
+ code: ZodIssueCode.invalid_union,
2628
+ unionErrors
2629
+ });
2630
+ return INVALID;
2631
+ }
2632
+ if (ctx.common.async) {
2633
+ return Promise.all(options.map(async (option) => {
2634
+ const childCtx = {
2635
+ ...ctx,
2636
+ common: {
2637
+ ...ctx.common,
2638
+ issues: []
2639
+ },
2640
+ parent: null
2641
+ };
2642
+ return {
2643
+ result: await option._parseAsync({
2644
+ data: ctx.data,
2645
+ path: ctx.path,
2646
+ parent: childCtx
2647
+ }),
2648
+ ctx: childCtx
2649
+ };
2650
+ })).then(handleResults);
2651
+ } else {
2652
+ let dirty = void 0;
2653
+ const issues = [];
2654
+ for (const option of options) {
2655
+ const childCtx = {
2656
+ ...ctx,
2657
+ common: {
2658
+ ...ctx.common,
2659
+ issues: []
2660
+ },
2661
+ parent: null
2662
+ };
2663
+ const result = option._parseSync({
2664
+ data: ctx.data,
2665
+ path: ctx.path,
2666
+ parent: childCtx
2667
+ });
2668
+ if (result.status === "valid") {
2669
+ return result;
2670
+ } else if (result.status === "dirty" && !dirty) {
2671
+ dirty = { result, ctx: childCtx };
2672
+ }
2673
+ if (childCtx.common.issues.length) {
2674
+ issues.push(childCtx.common.issues);
2675
+ }
2676
+ }
2677
+ if (dirty) {
2678
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2679
+ return dirty.result;
2680
+ }
2681
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
2682
+ addIssueToContext(ctx, {
2683
+ code: ZodIssueCode.invalid_union,
2684
+ unionErrors
2685
+ });
2686
+ return INVALID;
2687
+ }
2688
+ }
2689
+ get options() {
2690
+ return this._def.options;
2691
+ }
2692
+ };
2693
+ ZodUnion.create = (types, params) => {
2694
+ return new ZodUnion({
2695
+ options: types,
2696
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2697
+ ...processCreateParams(params)
2698
+ });
2699
+ };
2700
+ var getDiscriminator = (type) => {
2701
+ if (type instanceof ZodLazy) {
2702
+ return getDiscriminator(type.schema);
2703
+ } else if (type instanceof ZodEffects) {
2704
+ return getDiscriminator(type.innerType());
2705
+ } else if (type instanceof ZodLiteral) {
2706
+ return [type.value];
2707
+ } else if (type instanceof ZodEnum) {
2708
+ return type.options;
2709
+ } else if (type instanceof ZodNativeEnum) {
2710
+ return Object.keys(type.enum);
2711
+ } else if (type instanceof ZodDefault) {
2712
+ return getDiscriminator(type._def.innerType);
2713
+ } else if (type instanceof ZodUndefined) {
2714
+ return [void 0];
2715
+ } else if (type instanceof ZodNull) {
2716
+ return [null];
2717
+ } else {
2718
+ return null;
2719
+ }
2720
+ };
2721
+ var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2722
+ _parse(input) {
2723
+ const { ctx } = this._processInputParams(input);
2724
+ if (ctx.parsedType !== ZodParsedType.object) {
2725
+ addIssueToContext(ctx, {
2726
+ code: ZodIssueCode.invalid_type,
2727
+ expected: ZodParsedType.object,
2728
+ received: ctx.parsedType
2729
+ });
2730
+ return INVALID;
2731
+ }
2732
+ const discriminator = this.discriminator;
2733
+ const discriminatorValue = ctx.data[discriminator];
2734
+ const option = this.optionsMap.get(discriminatorValue);
2735
+ if (!option) {
2736
+ addIssueToContext(ctx, {
2737
+ code: ZodIssueCode.invalid_union_discriminator,
2738
+ options: Array.from(this.optionsMap.keys()),
2739
+ path: [discriminator]
2740
+ });
2741
+ return INVALID;
2742
+ }
2743
+ if (ctx.common.async) {
2744
+ return option._parseAsync({
2745
+ data: ctx.data,
2746
+ path: ctx.path,
2747
+ parent: ctx
2748
+ });
2749
+ } else {
2750
+ return option._parseSync({
2751
+ data: ctx.data,
2752
+ path: ctx.path,
2753
+ parent: ctx
2754
+ });
2755
+ }
2756
+ }
2757
+ get discriminator() {
2758
+ return this._def.discriminator;
2759
+ }
2760
+ get options() {
2761
+ return this._def.options;
2762
+ }
2763
+ get optionsMap() {
2764
+ return this._def.optionsMap;
2765
+ }
2766
+ /**
2767
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2768
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2769
+ * have a different value for each object in the union.
2770
+ * @param discriminator the name of the discriminator property
2771
+ * @param types an array of object schemas
2772
+ * @param params
2773
+ */
2774
+ static create(discriminator, options, params) {
2775
+ const optionsMap = /* @__PURE__ */ new Map();
2776
+ for (const type of options) {
2777
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2778
+ if (!discriminatorValues) {
2779
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2780
+ }
2781
+ for (const value of discriminatorValues) {
2782
+ if (optionsMap.has(value)) {
2783
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2784
+ }
2785
+ optionsMap.set(value, type);
2786
+ }
2787
+ }
2788
+ return new _ZodDiscriminatedUnion({
2789
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2790
+ discriminator,
2791
+ options,
2792
+ optionsMap,
2793
+ ...processCreateParams(params)
2794
+ });
2795
+ }
2796
+ };
2797
+ function mergeValues(a, b) {
2798
+ const aType = getParsedType(a);
2799
+ const bType = getParsedType(b);
2800
+ if (a === b) {
2801
+ return { valid: true, data: a };
2802
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2803
+ const bKeys = util.objectKeys(b);
2804
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2805
+ const newObj = { ...a, ...b };
2806
+ for (const key of sharedKeys) {
2807
+ const sharedValue = mergeValues(a[key], b[key]);
2808
+ if (!sharedValue.valid) {
2809
+ return { valid: false };
2810
+ }
2811
+ newObj[key] = sharedValue.data;
2812
+ }
2813
+ return { valid: true, data: newObj };
2814
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2815
+ if (a.length !== b.length) {
2816
+ return { valid: false };
2817
+ }
2818
+ const newArray = [];
2819
+ for (let index = 0; index < a.length; index++) {
2820
+ const itemA = a[index];
2821
+ const itemB = b[index];
2822
+ const sharedValue = mergeValues(itemA, itemB);
2823
+ if (!sharedValue.valid) {
2824
+ return { valid: false };
2825
+ }
2826
+ newArray.push(sharedValue.data);
2827
+ }
2828
+ return { valid: true, data: newArray };
2829
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2830
+ return { valid: true, data: a };
2831
+ } else {
2832
+ return { valid: false };
2833
+ }
2834
+ }
2835
+ var ZodIntersection = class extends ZodType {
2836
+ _parse(input) {
2837
+ const { status, ctx } = this._processInputParams(input);
2838
+ const handleParsed = (parsedLeft, parsedRight) => {
2839
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2840
+ return INVALID;
2841
+ }
2842
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
2843
+ if (!merged.valid) {
2844
+ addIssueToContext(ctx, {
2845
+ code: ZodIssueCode.invalid_intersection_types
2846
+ });
2847
+ return INVALID;
2848
+ }
2849
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2850
+ status.dirty();
2851
+ }
2852
+ return { status: status.value, value: merged.data };
2853
+ };
2854
+ if (ctx.common.async) {
2855
+ return Promise.all([
2856
+ this._def.left._parseAsync({
2857
+ data: ctx.data,
2858
+ path: ctx.path,
2859
+ parent: ctx
2860
+ }),
2861
+ this._def.right._parseAsync({
2862
+ data: ctx.data,
2863
+ path: ctx.path,
2864
+ parent: ctx
2865
+ })
2866
+ ]).then(([left, right]) => handleParsed(left, right));
2867
+ } else {
2868
+ return handleParsed(this._def.left._parseSync({
2869
+ data: ctx.data,
2870
+ path: ctx.path,
2871
+ parent: ctx
2872
+ }), this._def.right._parseSync({
2873
+ data: ctx.data,
2874
+ path: ctx.path,
2875
+ parent: ctx
2876
+ }));
2877
+ }
2878
+ }
2879
+ };
2880
+ ZodIntersection.create = (left, right, params) => {
2881
+ return new ZodIntersection({
2882
+ left,
2883
+ right,
2884
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
2885
+ ...processCreateParams(params)
2886
+ });
2887
+ };
2888
+ var ZodTuple = class _ZodTuple extends ZodType {
2889
+ _parse(input) {
2890
+ const { status, ctx } = this._processInputParams(input);
2891
+ if (ctx.parsedType !== ZodParsedType.array) {
2892
+ addIssueToContext(ctx, {
2893
+ code: ZodIssueCode.invalid_type,
2894
+ expected: ZodParsedType.array,
2895
+ received: ctx.parsedType
2896
+ });
2897
+ return INVALID;
2898
+ }
2899
+ if (ctx.data.length < this._def.items.length) {
2900
+ addIssueToContext(ctx, {
2901
+ code: ZodIssueCode.too_small,
2902
+ minimum: this._def.items.length,
2903
+ inclusive: true,
2904
+ exact: false,
2905
+ type: "array"
2906
+ });
2907
+ return INVALID;
2908
+ }
2909
+ const rest = this._def.rest;
2910
+ if (!rest && ctx.data.length > this._def.items.length) {
2911
+ addIssueToContext(ctx, {
2912
+ code: ZodIssueCode.too_big,
2913
+ maximum: this._def.items.length,
2914
+ inclusive: true,
2915
+ exact: false,
2916
+ type: "array"
2917
+ });
2918
+ status.dirty();
2919
+ }
2920
+ const items = [...ctx.data].map((item, itemIndex) => {
2921
+ const schema = this._def.items[itemIndex] || this._def.rest;
2922
+ if (!schema)
2923
+ return null;
2924
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2925
+ }).filter((x) => !!x);
2926
+ if (ctx.common.async) {
2927
+ return Promise.all(items).then((results) => {
2928
+ return ParseStatus.mergeArray(status, results);
2929
+ });
2930
+ } else {
2931
+ return ParseStatus.mergeArray(status, items);
2932
+ }
2933
+ }
2934
+ get items() {
2935
+ return this._def.items;
2936
+ }
2937
+ rest(rest) {
2938
+ return new _ZodTuple({
2939
+ ...this._def,
2940
+ rest
2941
+ });
2942
+ }
2943
+ };
2944
+ ZodTuple.create = (schemas, params) => {
2945
+ if (!Array.isArray(schemas)) {
2946
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2947
+ }
2948
+ return new ZodTuple({
2949
+ items: schemas,
2950
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
2951
+ rest: null,
2952
+ ...processCreateParams(params)
2953
+ });
2954
+ };
2955
+ var ZodRecord = class _ZodRecord extends ZodType {
2956
+ get keySchema() {
2957
+ return this._def.keyType;
2958
+ }
2959
+ get valueSchema() {
2960
+ return this._def.valueType;
2961
+ }
2962
+ _parse(input) {
2963
+ const { status, ctx } = this._processInputParams(input);
2964
+ if (ctx.parsedType !== ZodParsedType.object) {
2965
+ addIssueToContext(ctx, {
2966
+ code: ZodIssueCode.invalid_type,
2967
+ expected: ZodParsedType.object,
2968
+ received: ctx.parsedType
2969
+ });
2970
+ return INVALID;
2971
+ }
2972
+ const pairs = [];
2973
+ const keyType = this._def.keyType;
2974
+ const valueType = this._def.valueType;
2975
+ for (const key in ctx.data) {
2976
+ pairs.push({
2977
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2978
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key))
2979
+ });
2980
+ }
2981
+ if (ctx.common.async) {
2982
+ return ParseStatus.mergeObjectAsync(status, pairs);
2983
+ } else {
2984
+ return ParseStatus.mergeObjectSync(status, pairs);
2985
+ }
2986
+ }
2987
+ get element() {
2988
+ return this._def.valueType;
2989
+ }
2990
+ static create(first, second, third) {
2991
+ if (second instanceof ZodType) {
2992
+ return new _ZodRecord({
2993
+ keyType: first,
2994
+ valueType: second,
2995
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
2996
+ ...processCreateParams(third)
2997
+ });
2998
+ }
2999
+ return new _ZodRecord({
3000
+ keyType: ZodString.create(),
3001
+ valueType: first,
3002
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3003
+ ...processCreateParams(second)
3004
+ });
3005
+ }
3006
+ };
3007
+ var ZodMap = class extends ZodType {
3008
+ _parse(input) {
3009
+ const { status, ctx } = this._processInputParams(input);
3010
+ if (ctx.parsedType !== ZodParsedType.map) {
3011
+ addIssueToContext(ctx, {
3012
+ code: ZodIssueCode.invalid_type,
3013
+ expected: ZodParsedType.map,
3014
+ received: ctx.parsedType
3015
+ });
3016
+ return INVALID;
3017
+ }
3018
+ const keyType = this._def.keyType;
3019
+ const valueType = this._def.valueType;
3020
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3021
+ return {
3022
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3023
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3024
+ };
3025
+ });
3026
+ if (ctx.common.async) {
3027
+ const finalMap = /* @__PURE__ */ new Map();
3028
+ return Promise.resolve().then(async () => {
3029
+ for (const pair of pairs) {
3030
+ const key = await pair.key;
3031
+ const value = await pair.value;
3032
+ if (key.status === "aborted" || value.status === "aborted") {
3033
+ return INVALID;
3034
+ }
3035
+ if (key.status === "dirty" || value.status === "dirty") {
3036
+ status.dirty();
3037
+ }
3038
+ finalMap.set(key.value, value.value);
3039
+ }
3040
+ return { status: status.value, value: finalMap };
3041
+ });
3042
+ } else {
3043
+ const finalMap = /* @__PURE__ */ new Map();
3044
+ for (const pair of pairs) {
3045
+ const key = pair.key;
3046
+ const value = pair.value;
3047
+ if (key.status === "aborted" || value.status === "aborted") {
3048
+ return INVALID;
3049
+ }
3050
+ if (key.status === "dirty" || value.status === "dirty") {
3051
+ status.dirty();
3052
+ }
3053
+ finalMap.set(key.value, value.value);
3054
+ }
3055
+ return { status: status.value, value: finalMap };
3056
+ }
3057
+ }
3058
+ };
3059
+ ZodMap.create = (keyType, valueType, params) => {
3060
+ return new ZodMap({
3061
+ valueType,
3062
+ keyType,
3063
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3064
+ ...processCreateParams(params)
3065
+ });
3066
+ };
3067
+ var ZodSet = class _ZodSet extends ZodType {
3068
+ _parse(input) {
3069
+ const { status, ctx } = this._processInputParams(input);
3070
+ if (ctx.parsedType !== ZodParsedType.set) {
3071
+ addIssueToContext(ctx, {
3072
+ code: ZodIssueCode.invalid_type,
3073
+ expected: ZodParsedType.set,
3074
+ received: ctx.parsedType
3075
+ });
3076
+ return INVALID;
3077
+ }
3078
+ const def = this._def;
3079
+ if (def.minSize !== null) {
3080
+ if (ctx.data.size < def.minSize.value) {
3081
+ addIssueToContext(ctx, {
3082
+ code: ZodIssueCode.too_small,
3083
+ minimum: def.minSize.value,
3084
+ type: "set",
3085
+ inclusive: true,
3086
+ exact: false,
3087
+ message: def.minSize.message
3088
+ });
3089
+ status.dirty();
3090
+ }
3091
+ }
3092
+ if (def.maxSize !== null) {
3093
+ if (ctx.data.size > def.maxSize.value) {
3094
+ addIssueToContext(ctx, {
3095
+ code: ZodIssueCode.too_big,
3096
+ maximum: def.maxSize.value,
3097
+ type: "set",
3098
+ inclusive: true,
3099
+ exact: false,
3100
+ message: def.maxSize.message
3101
+ });
3102
+ status.dirty();
3103
+ }
3104
+ }
3105
+ const valueType = this._def.valueType;
3106
+ function finalizeSet(elements2) {
3107
+ const parsedSet = /* @__PURE__ */ new Set();
3108
+ for (const element of elements2) {
3109
+ if (element.status === "aborted")
3110
+ return INVALID;
3111
+ if (element.status === "dirty")
3112
+ status.dirty();
3113
+ parsedSet.add(element.value);
3114
+ }
3115
+ return { status: status.value, value: parsedSet };
3116
+ }
3117
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3118
+ if (ctx.common.async) {
3119
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3120
+ } else {
3121
+ return finalizeSet(elements);
3122
+ }
3123
+ }
3124
+ min(minSize, message) {
3125
+ return new _ZodSet({
3126
+ ...this._def,
3127
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3128
+ });
3129
+ }
3130
+ max(maxSize, message) {
3131
+ return new _ZodSet({
3132
+ ...this._def,
3133
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3134
+ });
3135
+ }
3136
+ size(size, message) {
3137
+ return this.min(size, message).max(size, message);
3138
+ }
3139
+ nonempty(message) {
3140
+ return this.min(1, message);
3141
+ }
3142
+ };
3143
+ ZodSet.create = (valueType, params) => {
3144
+ return new ZodSet({
3145
+ valueType,
3146
+ minSize: null,
3147
+ maxSize: null,
3148
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3149
+ ...processCreateParams(params)
3150
+ });
3151
+ };
3152
+ var ZodFunction = class _ZodFunction extends ZodType {
3153
+ constructor() {
3154
+ super(...arguments);
3155
+ this.validate = this.implement;
3156
+ }
3157
+ _parse(input) {
3158
+ const { ctx } = this._processInputParams(input);
3159
+ if (ctx.parsedType !== ZodParsedType.function) {
3160
+ addIssueToContext(ctx, {
3161
+ code: ZodIssueCode.invalid_type,
3162
+ expected: ZodParsedType.function,
3163
+ received: ctx.parsedType
3164
+ });
3165
+ return INVALID;
3166
+ }
3167
+ function makeArgsIssue(args, error) {
3168
+ return makeIssue({
3169
+ data: args,
3170
+ path: ctx.path,
3171
+ errorMaps: [
3172
+ ctx.common.contextualErrorMap,
3173
+ ctx.schemaErrorMap,
3174
+ getErrorMap(),
3175
+ errorMap
3176
+ ].filter((x) => !!x),
3177
+ issueData: {
3178
+ code: ZodIssueCode.invalid_arguments,
3179
+ argumentsError: error
3180
+ }
3181
+ });
3182
+ }
3183
+ function makeReturnsIssue(returns, error) {
3184
+ return makeIssue({
3185
+ data: returns,
3186
+ path: ctx.path,
3187
+ errorMaps: [
3188
+ ctx.common.contextualErrorMap,
3189
+ ctx.schemaErrorMap,
3190
+ getErrorMap(),
3191
+ errorMap
3192
+ ].filter((x) => !!x),
3193
+ issueData: {
3194
+ code: ZodIssueCode.invalid_return_type,
3195
+ returnTypeError: error
3196
+ }
3197
+ });
3198
+ }
3199
+ const params = { errorMap: ctx.common.contextualErrorMap };
3200
+ const fn = ctx.data;
3201
+ if (this._def.returns instanceof ZodPromise) {
3202
+ return OK(async (...args) => {
3203
+ const error = new ZodError([]);
3204
+ const parsedArgs = await this._def.args.parseAsync(args, params).catch((e) => {
3205
+ error.addIssue(makeArgsIssue(args, e));
3206
+ throw error;
3207
+ });
3208
+ const result = await fn(...parsedArgs);
3209
+ const parsedReturns = await this._def.returns._def.type.parseAsync(result, params).catch((e) => {
3210
+ error.addIssue(makeReturnsIssue(result, e));
3211
+ throw error;
3212
+ });
3213
+ return parsedReturns;
3214
+ });
3215
+ } else {
3216
+ return OK((...args) => {
3217
+ const parsedArgs = this._def.args.safeParse(args, params);
3218
+ if (!parsedArgs.success) {
3219
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3220
+ }
3221
+ const result = fn(...parsedArgs.data);
3222
+ const parsedReturns = this._def.returns.safeParse(result, params);
3223
+ if (!parsedReturns.success) {
3224
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3225
+ }
3226
+ return parsedReturns.data;
3227
+ });
3228
+ }
3229
+ }
3230
+ parameters() {
3231
+ return this._def.args;
3232
+ }
3233
+ returnType() {
3234
+ return this._def.returns;
3235
+ }
3236
+ args(...items) {
3237
+ return new _ZodFunction({
3238
+ ...this._def,
3239
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3240
+ });
3241
+ }
3242
+ returns(returnType) {
3243
+ return new _ZodFunction({
3244
+ ...this._def,
3245
+ returns: returnType
3246
+ });
3247
+ }
3248
+ implement(func) {
3249
+ const validatedFunc = this.parse(func);
3250
+ return validatedFunc;
3251
+ }
3252
+ strictImplement(func) {
3253
+ const validatedFunc = this.parse(func);
3254
+ return validatedFunc;
3255
+ }
3256
+ static create(args, returns, params) {
3257
+ return new _ZodFunction({
3258
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3259
+ returns: returns || ZodUnknown.create(),
3260
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3261
+ ...processCreateParams(params)
3262
+ });
3263
+ }
3264
+ };
3265
+ var ZodLazy = class extends ZodType {
3266
+ get schema() {
3267
+ return this._def.getter();
3268
+ }
3269
+ _parse(input) {
3270
+ const { ctx } = this._processInputParams(input);
3271
+ const lazySchema = this._def.getter();
3272
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3273
+ }
3274
+ };
3275
+ ZodLazy.create = (getter, params) => {
3276
+ return new ZodLazy({
3277
+ getter,
3278
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3279
+ ...processCreateParams(params)
3280
+ });
3281
+ };
3282
+ var ZodLiteral = class extends ZodType {
3283
+ _parse(input) {
3284
+ if (input.data !== this._def.value) {
3285
+ const ctx = this._getOrReturnCtx(input);
3286
+ addIssueToContext(ctx, {
3287
+ received: ctx.data,
3288
+ code: ZodIssueCode.invalid_literal,
3289
+ expected: this._def.value
3290
+ });
3291
+ return INVALID;
3292
+ }
3293
+ return { status: "valid", value: input.data };
3294
+ }
3295
+ get value() {
3296
+ return this._def.value;
3297
+ }
3298
+ };
3299
+ ZodLiteral.create = (value, params) => {
3300
+ return new ZodLiteral({
3301
+ value,
3302
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3303
+ ...processCreateParams(params)
3304
+ });
3305
+ };
3306
+ function createZodEnum(values, params) {
3307
+ return new ZodEnum({
3308
+ values,
3309
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3310
+ ...processCreateParams(params)
3311
+ });
3312
+ }
3313
+ var ZodEnum = class _ZodEnum extends ZodType {
3314
+ _parse(input) {
3315
+ if (typeof input.data !== "string") {
3316
+ const ctx = this._getOrReturnCtx(input);
3317
+ const expectedValues = this._def.values;
3318
+ addIssueToContext(ctx, {
3319
+ expected: util.joinValues(expectedValues),
3320
+ received: ctx.parsedType,
3321
+ code: ZodIssueCode.invalid_type
3322
+ });
3323
+ return INVALID;
3324
+ }
3325
+ if (this._def.values.indexOf(input.data) === -1) {
3326
+ const ctx = this._getOrReturnCtx(input);
3327
+ const expectedValues = this._def.values;
3328
+ addIssueToContext(ctx, {
3329
+ received: ctx.data,
3330
+ code: ZodIssueCode.invalid_enum_value,
3331
+ options: expectedValues
3332
+ });
3333
+ return INVALID;
3334
+ }
3335
+ return OK(input.data);
3336
+ }
3337
+ get options() {
3338
+ return this._def.values;
3339
+ }
3340
+ get enum() {
3341
+ const enumValues = {};
3342
+ for (const val of this._def.values) {
3343
+ enumValues[val] = val;
3344
+ }
3345
+ return enumValues;
3346
+ }
3347
+ get Values() {
3348
+ const enumValues = {};
3349
+ for (const val of this._def.values) {
3350
+ enumValues[val] = val;
3351
+ }
3352
+ return enumValues;
3353
+ }
3354
+ get Enum() {
3355
+ const enumValues = {};
3356
+ for (const val of this._def.values) {
3357
+ enumValues[val] = val;
3358
+ }
3359
+ return enumValues;
3360
+ }
3361
+ extract(values) {
3362
+ return _ZodEnum.create(values);
3363
+ }
3364
+ exclude(values) {
3365
+ return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
3366
+ }
3367
+ };
3368
+ ZodEnum.create = createZodEnum;
3369
+ var ZodNativeEnum = class extends ZodType {
3370
+ _parse(input) {
3371
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3372
+ const ctx = this._getOrReturnCtx(input);
3373
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3374
+ const expectedValues = util.objectValues(nativeEnumValues);
3375
+ addIssueToContext(ctx, {
3376
+ expected: util.joinValues(expectedValues),
3377
+ received: ctx.parsedType,
3378
+ code: ZodIssueCode.invalid_type
3379
+ });
3380
+ return INVALID;
3381
+ }
3382
+ if (nativeEnumValues.indexOf(input.data) === -1) {
3383
+ const expectedValues = util.objectValues(nativeEnumValues);
3384
+ addIssueToContext(ctx, {
3385
+ received: ctx.data,
3386
+ code: ZodIssueCode.invalid_enum_value,
3387
+ options: expectedValues
3388
+ });
3389
+ return INVALID;
3390
+ }
3391
+ return OK(input.data);
3392
+ }
3393
+ get enum() {
3394
+ return this._def.values;
3395
+ }
3396
+ };
3397
+ ZodNativeEnum.create = (values, params) => {
3398
+ return new ZodNativeEnum({
3399
+ values,
3400
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3401
+ ...processCreateParams(params)
3402
+ });
3403
+ };
3404
+ var ZodPromise = class extends ZodType {
3405
+ unwrap() {
3406
+ return this._def.type;
3407
+ }
3408
+ _parse(input) {
3409
+ const { ctx } = this._processInputParams(input);
3410
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3411
+ addIssueToContext(ctx, {
3412
+ code: ZodIssueCode.invalid_type,
3413
+ expected: ZodParsedType.promise,
3414
+ received: ctx.parsedType
3415
+ });
3416
+ return INVALID;
3417
+ }
3418
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3419
+ return OK(promisified.then((data) => {
3420
+ return this._def.type.parseAsync(data, {
3421
+ path: ctx.path,
3422
+ errorMap: ctx.common.contextualErrorMap
3423
+ });
3424
+ }));
3425
+ }
3426
+ };
3427
+ ZodPromise.create = (schema, params) => {
3428
+ return new ZodPromise({
3429
+ type: schema,
3430
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3431
+ ...processCreateParams(params)
3432
+ });
3433
+ };
3434
+ var ZodEffects = class extends ZodType {
3435
+ innerType() {
3436
+ return this._def.schema;
3437
+ }
3438
+ sourceType() {
3439
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3440
+ }
3441
+ _parse(input) {
3442
+ const { status, ctx } = this._processInputParams(input);
3443
+ const effect = this._def.effect || null;
3444
+ if (effect.type === "preprocess") {
3445
+ const processed = effect.transform(ctx.data);
3446
+ if (ctx.common.async) {
3447
+ return Promise.resolve(processed).then((processed2) => {
3448
+ return this._def.schema._parseAsync({
3449
+ data: processed2,
3450
+ path: ctx.path,
3451
+ parent: ctx
3452
+ });
3453
+ });
3454
+ } else {
3455
+ return this._def.schema._parseSync({
3456
+ data: processed,
3457
+ path: ctx.path,
3458
+ parent: ctx
3459
+ });
3460
+ }
3461
+ }
3462
+ const checkCtx = {
3463
+ addIssue: (arg) => {
3464
+ addIssueToContext(ctx, arg);
3465
+ if (arg.fatal) {
3466
+ status.abort();
3467
+ } else {
3468
+ status.dirty();
3469
+ }
3470
+ },
3471
+ get path() {
3472
+ return ctx.path;
3473
+ }
3474
+ };
3475
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3476
+ if (effect.type === "refinement") {
3477
+ const executeRefinement = (acc) => {
3478
+ const result = effect.refinement(acc, checkCtx);
3479
+ if (ctx.common.async) {
3480
+ return Promise.resolve(result);
3481
+ }
3482
+ if (result instanceof Promise) {
3483
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3484
+ }
3485
+ return acc;
3486
+ };
3487
+ if (ctx.common.async === false) {
3488
+ const inner = this._def.schema._parseSync({
3489
+ data: ctx.data,
3490
+ path: ctx.path,
3491
+ parent: ctx
3492
+ });
3493
+ if (inner.status === "aborted")
3494
+ return INVALID;
3495
+ if (inner.status === "dirty")
3496
+ status.dirty();
3497
+ executeRefinement(inner.value);
3498
+ return { status: status.value, value: inner.value };
3499
+ } else {
3500
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3501
+ if (inner.status === "aborted")
3502
+ return INVALID;
3503
+ if (inner.status === "dirty")
3504
+ status.dirty();
3505
+ return executeRefinement(inner.value).then(() => {
3506
+ return { status: status.value, value: inner.value };
3507
+ });
3508
+ });
3509
+ }
3510
+ }
3511
+ if (effect.type === "transform") {
3512
+ if (ctx.common.async === false) {
3513
+ const base = this._def.schema._parseSync({
3514
+ data: ctx.data,
3515
+ path: ctx.path,
3516
+ parent: ctx
3517
+ });
3518
+ if (!isValid(base))
3519
+ return base;
3520
+ const result = effect.transform(base.value, checkCtx);
3521
+ if (result instanceof Promise) {
3522
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3523
+ }
3524
+ return { status: status.value, value: result };
3525
+ } else {
3526
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3527
+ if (!isValid(base))
3528
+ return base;
3529
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
3530
+ });
3531
+ }
3532
+ }
3533
+ util.assertNever(effect);
3534
+ }
3535
+ };
3536
+ ZodEffects.create = (schema, effect, params) => {
3537
+ return new ZodEffects({
3538
+ schema,
3539
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3540
+ effect,
3541
+ ...processCreateParams(params)
3542
+ });
3543
+ };
3544
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3545
+ return new ZodEffects({
3546
+ schema,
3547
+ effect: { type: "preprocess", transform: preprocess },
3548
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3549
+ ...processCreateParams(params)
3550
+ });
3551
+ };
3552
+ var ZodOptional = class extends ZodType {
3553
+ _parse(input) {
3554
+ const parsedType = this._getType(input);
3555
+ if (parsedType === ZodParsedType.undefined) {
3556
+ return OK(void 0);
3557
+ }
3558
+ return this._def.innerType._parse(input);
3559
+ }
3560
+ unwrap() {
3561
+ return this._def.innerType;
3562
+ }
3563
+ };
3564
+ ZodOptional.create = (type, params) => {
3565
+ return new ZodOptional({
3566
+ innerType: type,
3567
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3568
+ ...processCreateParams(params)
3569
+ });
3570
+ };
3571
+ var ZodNullable = class extends ZodType {
3572
+ _parse(input) {
3573
+ const parsedType = this._getType(input);
3574
+ if (parsedType === ZodParsedType.null) {
3575
+ return OK(null);
3576
+ }
3577
+ return this._def.innerType._parse(input);
3578
+ }
3579
+ unwrap() {
3580
+ return this._def.innerType;
3581
+ }
3582
+ };
3583
+ ZodNullable.create = (type, params) => {
3584
+ return new ZodNullable({
3585
+ innerType: type,
3586
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3587
+ ...processCreateParams(params)
3588
+ });
3589
+ };
3590
+ var ZodDefault = class extends ZodType {
3591
+ _parse(input) {
3592
+ const { ctx } = this._processInputParams(input);
3593
+ let data = ctx.data;
3594
+ if (ctx.parsedType === ZodParsedType.undefined) {
3595
+ data = this._def.defaultValue();
3596
+ }
3597
+ return this._def.innerType._parse({
3598
+ data,
3599
+ path: ctx.path,
3600
+ parent: ctx
3601
+ });
3602
+ }
3603
+ removeDefault() {
3604
+ return this._def.innerType;
3605
+ }
3606
+ };
3607
+ ZodDefault.create = (type, params) => {
3608
+ return new ZodDefault({
3609
+ innerType: type,
3610
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3611
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3612
+ ...processCreateParams(params)
3613
+ });
3614
+ };
3615
+ var ZodCatch = class extends ZodType {
3616
+ _parse(input) {
3617
+ const { ctx } = this._processInputParams(input);
3618
+ const newCtx = {
3619
+ ...ctx,
3620
+ common: {
3621
+ ...ctx.common,
3622
+ issues: []
3623
+ }
3624
+ };
3625
+ const result = this._def.innerType._parse({
3626
+ data: newCtx.data,
3627
+ path: newCtx.path,
3628
+ parent: {
3629
+ ...newCtx
3630
+ }
3631
+ });
3632
+ if (isAsync(result)) {
3633
+ return result.then((result2) => {
3634
+ return {
3635
+ status: "valid",
3636
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
3637
+ get error() {
3638
+ return new ZodError(newCtx.common.issues);
3639
+ },
3640
+ input: newCtx.data
3641
+ })
3642
+ };
3643
+ });
3644
+ } else {
3645
+ return {
3646
+ status: "valid",
3647
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3648
+ get error() {
3649
+ return new ZodError(newCtx.common.issues);
3650
+ },
3651
+ input: newCtx.data
3652
+ })
3653
+ };
3654
+ }
3655
+ }
3656
+ removeCatch() {
3657
+ return this._def.innerType;
3658
+ }
3659
+ };
3660
+ ZodCatch.create = (type, params) => {
3661
+ return new ZodCatch({
3662
+ innerType: type,
3663
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3664
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3665
+ ...processCreateParams(params)
3666
+ });
3667
+ };
3668
+ var ZodNaN = class extends ZodType {
3669
+ _parse(input) {
3670
+ const parsedType = this._getType(input);
3671
+ if (parsedType !== ZodParsedType.nan) {
3672
+ const ctx = this._getOrReturnCtx(input);
3673
+ addIssueToContext(ctx, {
3674
+ code: ZodIssueCode.invalid_type,
3675
+ expected: ZodParsedType.nan,
3676
+ received: ctx.parsedType
3677
+ });
3678
+ return INVALID;
3679
+ }
3680
+ return { status: "valid", value: input.data };
3681
+ }
3682
+ };
3683
+ ZodNaN.create = (params) => {
3684
+ return new ZodNaN({
3685
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3686
+ ...processCreateParams(params)
3687
+ });
3688
+ };
3689
+ var BRAND = Symbol("zod_brand");
3690
+ var ZodBranded = class extends ZodType {
3691
+ _parse(input) {
3692
+ const { ctx } = this._processInputParams(input);
3693
+ const data = ctx.data;
3694
+ return this._def.type._parse({
3695
+ data,
3696
+ path: ctx.path,
3697
+ parent: ctx
3698
+ });
3699
+ }
3700
+ unwrap() {
3701
+ return this._def.type;
3702
+ }
3703
+ };
3704
+ var ZodPipeline = class _ZodPipeline extends ZodType {
3705
+ _parse(input) {
3706
+ const { status, ctx } = this._processInputParams(input);
3707
+ if (ctx.common.async) {
3708
+ const handleAsync = async () => {
3709
+ const inResult = await this._def.in._parseAsync({
3710
+ data: ctx.data,
3711
+ path: ctx.path,
3712
+ parent: ctx
3713
+ });
3714
+ if (inResult.status === "aborted")
3715
+ return INVALID;
3716
+ if (inResult.status === "dirty") {
3717
+ status.dirty();
3718
+ return DIRTY(inResult.value);
3719
+ } else {
3720
+ return this._def.out._parseAsync({
3721
+ data: inResult.value,
3722
+ path: ctx.path,
3723
+ parent: ctx
3724
+ });
3725
+ }
3726
+ };
3727
+ return handleAsync();
3728
+ } else {
3729
+ const inResult = this._def.in._parseSync({
3730
+ data: ctx.data,
3731
+ path: ctx.path,
3732
+ parent: ctx
3733
+ });
3734
+ if (inResult.status === "aborted")
3735
+ return INVALID;
3736
+ if (inResult.status === "dirty") {
3737
+ status.dirty();
3738
+ return {
3739
+ status: "dirty",
3740
+ value: inResult.value
3741
+ };
3742
+ } else {
3743
+ return this._def.out._parseSync({
3744
+ data: inResult.value,
3745
+ path: ctx.path,
3746
+ parent: ctx
3747
+ });
3748
+ }
3749
+ }
3750
+ }
3751
+ static create(a, b) {
3752
+ return new _ZodPipeline({
3753
+ in: a,
3754
+ out: b,
3755
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
3756
+ });
3757
+ }
3758
+ };
3759
+ var custom = (check, params = {}, fatal) => {
3760
+ if (check)
3761
+ return ZodAny.create().superRefine((data, ctx) => {
3762
+ var _a, _b;
3763
+ if (!check(data)) {
3764
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3765
+ const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
3766
+ const p2 = typeof p === "string" ? { message: p } : p;
3767
+ ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
3768
+ }
3769
+ });
3770
+ return ZodAny.create();
3771
+ };
3772
+ var late = {
3773
+ object: ZodObject.lazycreate
3774
+ };
3775
+ var ZodFirstPartyTypeKind;
3776
+ (function(ZodFirstPartyTypeKind2) {
3777
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3778
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3779
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3780
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3781
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3782
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3783
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3784
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3785
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3786
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3787
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3788
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3789
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3790
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3791
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3792
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3793
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3794
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3795
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3796
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3797
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3798
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3799
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3800
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3801
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3802
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3803
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3804
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3805
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3806
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3807
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3808
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3809
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
3810
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
3811
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
3812
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3813
+ var instanceOfType = (cls, params = {
3814
+ message: `Input not instance of ${cls.name}`
3815
+ }) => custom((data) => data instanceof cls, params);
3816
+ var stringType = ZodString.create;
3817
+ var numberType = ZodNumber.create;
3818
+ var nanType = ZodNaN.create;
3819
+ var bigIntType = ZodBigInt.create;
3820
+ var booleanType = ZodBoolean.create;
3821
+ var dateType = ZodDate.create;
3822
+ var symbolType = ZodSymbol.create;
3823
+ var undefinedType = ZodUndefined.create;
3824
+ var nullType = ZodNull.create;
3825
+ var anyType = ZodAny.create;
3826
+ var unknownType = ZodUnknown.create;
3827
+ var neverType = ZodNever.create;
3828
+ var voidType = ZodVoid.create;
3829
+ var arrayType = ZodArray.create;
3830
+ var objectType = ZodObject.create;
3831
+ var strictObjectType = ZodObject.strictCreate;
3832
+ var unionType = ZodUnion.create;
3833
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
3834
+ var intersectionType = ZodIntersection.create;
3835
+ var tupleType = ZodTuple.create;
3836
+ var recordType = ZodRecord.create;
3837
+ var mapType = ZodMap.create;
3838
+ var setType = ZodSet.create;
3839
+ var functionType = ZodFunction.create;
3840
+ var lazyType = ZodLazy.create;
3841
+ var literalType = ZodLiteral.create;
3842
+ var enumType = ZodEnum.create;
3843
+ var nativeEnumType = ZodNativeEnum.create;
3844
+ var promiseType = ZodPromise.create;
3845
+ var effectsType = ZodEffects.create;
3846
+ var optionalType = ZodOptional.create;
3847
+ var nullableType = ZodNullable.create;
3848
+ var preprocessType = ZodEffects.createWithPreprocess;
3849
+ var pipelineType = ZodPipeline.create;
3850
+ var ostring = () => stringType().optional();
3851
+ var onumber = () => numberType().optional();
3852
+ var oboolean = () => booleanType().optional();
3853
+ var coerce = {
3854
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
3855
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
3856
+ boolean: (arg) => ZodBoolean.create({
3857
+ ...arg,
3858
+ coerce: true
3859
+ }),
3860
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
3861
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
3862
+ };
3863
+ var NEVER = INVALID;
3864
+ var z = /* @__PURE__ */ Object.freeze({
3865
+ __proto__: null,
3866
+ defaultErrorMap: errorMap,
3867
+ setErrorMap,
3868
+ getErrorMap,
3869
+ makeIssue,
3870
+ EMPTY_PATH,
3871
+ addIssueToContext,
3872
+ ParseStatus,
3873
+ INVALID,
3874
+ DIRTY,
3875
+ OK,
3876
+ isAborted,
3877
+ isDirty,
3878
+ isValid,
3879
+ isAsync,
3880
+ get util() {
3881
+ return util;
3882
+ },
3883
+ get objectUtil() {
3884
+ return objectUtil;
3885
+ },
3886
+ ZodParsedType,
3887
+ getParsedType,
3888
+ ZodType,
3889
+ ZodString,
3890
+ ZodNumber,
3891
+ ZodBigInt,
3892
+ ZodBoolean,
3893
+ ZodDate,
3894
+ ZodSymbol,
3895
+ ZodUndefined,
3896
+ ZodNull,
3897
+ ZodAny,
3898
+ ZodUnknown,
3899
+ ZodNever,
3900
+ ZodVoid,
3901
+ ZodArray,
3902
+ ZodObject,
3903
+ ZodUnion,
3904
+ ZodDiscriminatedUnion,
3905
+ ZodIntersection,
3906
+ ZodTuple,
3907
+ ZodRecord,
3908
+ ZodMap,
3909
+ ZodSet,
3910
+ ZodFunction,
3911
+ ZodLazy,
3912
+ ZodLiteral,
3913
+ ZodEnum,
3914
+ ZodNativeEnum,
3915
+ ZodPromise,
3916
+ ZodEffects,
3917
+ ZodTransformer: ZodEffects,
3918
+ ZodOptional,
3919
+ ZodNullable,
3920
+ ZodDefault,
3921
+ ZodCatch,
3922
+ ZodNaN,
3923
+ BRAND,
3924
+ ZodBranded,
3925
+ ZodPipeline,
3926
+ custom,
3927
+ Schema: ZodType,
3928
+ ZodSchema: ZodType,
3929
+ late,
3930
+ get ZodFirstPartyTypeKind() {
3931
+ return ZodFirstPartyTypeKind;
3932
+ },
3933
+ coerce,
3934
+ any: anyType,
3935
+ array: arrayType,
3936
+ bigint: bigIntType,
3937
+ boolean: booleanType,
3938
+ date: dateType,
3939
+ discriminatedUnion: discriminatedUnionType,
3940
+ effect: effectsType,
3941
+ "enum": enumType,
3942
+ "function": functionType,
3943
+ "instanceof": instanceOfType,
3944
+ intersection: intersectionType,
3945
+ lazy: lazyType,
3946
+ literal: literalType,
3947
+ map: mapType,
3948
+ nan: nanType,
3949
+ nativeEnum: nativeEnumType,
3950
+ never: neverType,
3951
+ "null": nullType,
3952
+ nullable: nullableType,
3953
+ number: numberType,
3954
+ object: objectType,
3955
+ oboolean,
3956
+ onumber,
3957
+ optional: optionalType,
3958
+ ostring,
3959
+ pipeline: pipelineType,
3960
+ preprocess: preprocessType,
3961
+ promise: promiseType,
3962
+ record: recordType,
3963
+ set: setType,
3964
+ strictObject: strictObjectType,
3965
+ string: stringType,
3966
+ symbol: symbolType,
3967
+ transformer: effectsType,
3968
+ tuple: tupleType,
3969
+ "undefined": undefinedType,
3970
+ union: unionType,
3971
+ unknown: unknownType,
3972
+ "void": voidType,
3973
+ NEVER,
3974
+ ZodIssueCode,
3975
+ quotelessJson,
3976
+ ZodError
3977
+ });
3978
+
3979
+ // ../../core/models/book.ts
3980
+ var BookDesignRequest = class {
3981
+ occasion;
3982
+ style;
3983
+ book_size;
3984
+ cover_type;
3985
+ page_type;
3986
+ image_density;
3987
+ image_filtering_level;
3988
+ embellishment_level;
3989
+ text_sticker_level;
3990
+ constructor(props) {
3991
+ this.occasion = props.occasion;
3992
+ this.style = props.style;
3993
+ this.book_size = props.book_size;
3994
+ this.cover_type = props.cover_type;
3995
+ this.page_type = props.page_type;
3996
+ this.image_density = props.image_density;
3997
+ this.image_filtering_level = props.image_filtering_level;
3998
+ this.embellishment_level = props.embellishment_level;
3999
+ this.text_sticker_level = props.text_sticker_level;
4000
+ }
4001
+ };
4002
+ var bookDesignRequestSchema = z.object({
4003
+ occasion: z.enum(occasions),
4004
+ style: z.string(),
4005
+ book_size: z.enum(bookSizes),
4006
+ cover_type: z.enum(coverTypes),
4007
+ page_type: z.enum(pageTypes),
4008
+ image_density: z.enum(imageDensities),
4009
+ image_filtering_level: z.enum(imageFilteringLevels),
4010
+ embellishment_level: z.enum(embellishmentLevels),
4011
+ text_sticker_level: z.enum(textStickerLevels)
4012
+ });
4013
+ var BookPropsSchema = z.object({
4014
+ id: z.string().optional(),
4015
+ title: z.string(),
4016
+ design_request: bookDesignRequestSchema,
4017
+ state: z.enum(states).optional(),
4018
+ guid: z.string().optional(),
4019
+ cancelled_at: z.string().optional()
4020
+ });
4021
+ var Book = class {
4022
+ id;
4023
+ title;
4024
+ design_request;
4025
+ state;
4026
+ guid;
4027
+ cancelled_at;
4028
+ constructor(props) {
4029
+ this.id = props.id || "";
4030
+ this.title = props.title;
4031
+ this.design_request = new BookDesignRequest(props.design_request);
4032
+ this.state = props.state;
4033
+ this.guid = props.guid;
4034
+ this.cancelled_at = props.cancelled_at;
4035
+ }
4036
+ toDesignRequestProps() {
4037
+ const props = { ...this, ...this.design_request };
4038
+ props.style = getStyleIdBySlug(props.style);
4039
+ delete props.design_request;
4040
+ return snakeCaseObjectKeysToCamelCase(props);
4041
+ }
4042
+ };
4043
+
4044
+ // ../../core/models/design-request/image.ts
4045
+ var Images = class {
4046
+ // eslint-disable-next-line no-unused-vars
4047
+ constructor(client, parentId) {
4048
+ this.client = client;
4049
+ this.parentId = parentId;
4050
+ this.images = [];
4051
+ this.length = this.images.length;
4052
+ }
4053
+ parentId;
4054
+ images;
4055
+ length;
4056
+ async add(image) {
4057
+ this.images.push(image);
4058
+ this.length = this.images.length;
4059
+ await this.client.engineAPI.images.addToBook(this.parentId, new ImageServer(image));
4060
+ return new Promise((resolve) => {
4061
+ resolve(this.length);
4062
+ });
4063
+ }
4064
+ };
4065
+ var imageServerSchema = z.object({
4066
+ id: z.string().optional(),
4067
+ handle: z.string(),
4068
+ url: z.string(),
4069
+ width: z.number(),
4070
+ height: z.number(),
4071
+ orientation: z.number(),
4072
+ taken_at: z.string(),
4073
+ camera_make: z.string().optional(),
4074
+ camera: z.string().optional(),
4075
+ filename: z.string()
4076
+ });
4077
+ var ImageServer = class {
4078
+ handle;
4079
+ url;
4080
+ width;
4081
+ height;
4082
+ orientation;
4083
+ taken_at;
4084
+ camera_make;
4085
+ camera;
4086
+ filename;
4087
+ constructor(image) {
4088
+ this.handle = image.handle;
4089
+ this.url = image.url;
4090
+ this.width = image.width;
4091
+ this.height = image.height;
4092
+ this.orientation = image.rotation;
4093
+ this.taken_at = image.captureTime;
4094
+ this.camera_make = image.cameraMake;
4095
+ this.camera = image.cameraModel;
4096
+ this.filename = image.filename;
4097
+ }
4098
+ };
4099
+
4100
+ // ../../core/models/design-request/design-options.ts
4101
+ var imageDensityOptionSchema = z.object({
4102
+ maxPageCount: z.number(),
4103
+ minPageCount: z.number(),
4104
+ maxImageCount: z.number(),
4105
+ avgImageCount: z.number(),
4106
+ minImageCount: z.number()
4107
+ });
4108
+ var imageDensityOptionsSchema = z.object({
4109
+ high: imageDensityOptionSchema,
4110
+ medium: imageDensityOptionSchema,
4111
+ low: imageDensityOptionSchema
4112
+ });
4113
+ var designOptionsSchema = z.object({
4114
+ densities: imageDensityOptionsSchema
4115
+ });
4116
+ var imageDensityOptionServerSchema = z.object({
4117
+ max_page_count: z.number(),
4118
+ min_page_count: z.number(),
4119
+ max_image_count: z.number(),
4120
+ avg_image_count: z.number(),
4121
+ min_image_count: z.number()
4122
+ });
4123
+ var imageDensityOptionsServerSchema = z.object({
4124
+ high: imageDensityOptionServerSchema,
4125
+ medium: imageDensityOptionServerSchema,
4126
+ low: imageDensityOptionServerSchema
4127
+ });
4128
+ var designOptionsServerSchema = z.object({
4129
+ densities: imageDensityOptionsServerSchema
4130
+ });
4131
+
4132
+ // ../../core/config.ts
4133
+ var defaultApiHost = "https://api.sfly-sls.magicbook.io";
4134
+ var defaultWebSocketHost = "wss://socket.sfly-sls.magicbook.io";
4135
+ var designRequestTimeout = parseInt("30000"?.toString() || "3000");
4136
+
4137
+ // ../../core/models/design-request/index.ts
4138
+ var DesignRequestOptions = {
4139
+ occasion: occasions,
4140
+ style: Object.keys(styles).map((key) => parseInt(key)),
4141
+ bookSize: bookSizes,
4142
+ coverType: coverTypes,
4143
+ pageType: pageTypes,
4144
+ imageDensity: imageDensities,
4145
+ imageFilteringLevel: imageFilteringLevels,
4146
+ embellishmentLevel: embellishmentLevels,
4147
+ textStickerLevel: textStickerLevels
4148
+ };
4149
+ var DesignRequest = class {
4150
+ // eslint-disable-next-line no-unused-vars
4151
+ constructor(parentId, client, designRequestProps) {
4152
+ this.client = client;
4153
+ this.parentId = parentId;
4154
+ this.webSocket = new WebSocket(`${this.client.webSocketHost}/?book_id=${this.parentId}`);
4155
+ this.state = designRequestProps?.state || states[0];
4156
+ this.title = designRequestProps?.title || "";
4157
+ this.occasion = designRequestProps?.occasion || occasions[0];
4158
+ this.style = designRequestProps?.style || parseInt(Object.keys(styles)[0]);
4159
+ this.bookSize = designRequestProps?.bookSize || bookSizes[0];
4160
+ this.coverType = designRequestProps?.coverType || coverTypes[0];
4161
+ this.pageType = designRequestProps?.pageType || pageTypes[0];
4162
+ this.imageDensity = designRequestProps?.imageDensity || imageDensities[0];
4163
+ this.imageFilteringLevel = designRequestProps?.imageFilteringLevel || imageFilteringLevels[0];
4164
+ this.embellishmentLevel = designRequestProps?.embellishmentLevel || embellishmentLevels[0];
4165
+ this.textStickerLevel = designRequestProps?.textStickerLevel || textStickerLevels[0];
4166
+ this.images = new Images(this.client, this.parentId);
4167
+ }
4168
+ webSocket;
4169
+ // private events: DesignRequestEvent[]
4170
+ state;
4171
+ parentId;
4172
+ title;
4173
+ occasion;
4174
+ style;
4175
+ bookSize;
4176
+ coverType;
4177
+ pageType;
4178
+ imageDensity;
4179
+ imageFilteringLevel;
4180
+ embellishmentLevel;
4181
+ textStickerLevel;
4182
+ images;
4183
+ guid;
4184
+ updateDesignRequest(designRequestProps) {
4185
+ Object.assign(this, designRequestProps);
4186
+ }
4187
+ async getOptions(imageCount) {
4188
+ const options = designOptionsSchema.parse(snakeCaseObjectKeysToCamelCase(
4189
+ await this.client.engineAPI.designOptions.retrieve(
4190
+ this.bookSize,
4191
+ imageCount || this.images.length,
4192
+ this.imageFilteringLevel
4193
+ )
4194
+ ));
4195
+ return options;
4196
+ }
4197
+ async submit(submitDesignRequestProps) {
4198
+ if (isDesignRequestSubmitted(this.state)) {
4199
+ throw new Error("Design request already submitted");
4200
+ } else {
4201
+ submitDesignRequestProps && Object.assign(this, submitDesignRequestProps);
4202
+ this.getProgress();
4203
+ this.updateDesignRequest(
4204
+ (await this.client.engineAPI.books.update(this.parentId, this.toBook())).toDesignRequestProps()
4205
+ );
4206
+ this.state = states[1];
4207
+ return this;
4208
+ }
4209
+ }
4210
+ async setGuid(guid) {
4211
+ if (!isDesignRequestSubmitted(this.state)) {
4212
+ throw new Error("Design request not submitted");
4213
+ } else {
4214
+ this.guid = guid;
4215
+ this.updateDesignRequest(
4216
+ (await this.client.engineAPI.books.update(this.parentId, this.toBook())).toDesignRequestProps()
4217
+ );
4218
+ return this.guid;
4219
+ }
4220
+ }
4221
+ async cancel() {
4222
+ if (this.state === "cancelled") {
4223
+ throw new Error("Design request already cancelled");
4224
+ } else if (this.state === "ready") {
4225
+ throw new Error("Design request already finished");
4226
+ } else if (!isDesignRequestSubmitted(this.state)) {
4227
+ throw new Error("Design request not submitted");
4228
+ } else {
4229
+ this.updateDesignRequest(
4230
+ (await this.client.engineAPI.books.cancel(this.parentId)).toDesignRequestProps()
4231
+ );
4232
+ this.state = "cancelled";
4233
+ await this.eventHandler(cancelledMessage);
4234
+ return this;
4235
+ }
4236
+ }
4237
+ async getJSON() {
4238
+ if (this.state === "ready") {
4239
+ return await this.client.engineAPI.books.retrieveGalleon(this.parentId);
4240
+ } else {
4241
+ throw new Error("Design request not ready");
4242
+ }
4243
+ }
4244
+ async eventHandler(detail, type = "MagicBook.designRequestUpdated") {
4245
+ const customEvent = new CustomEvent(type, { detail });
4246
+ window.dispatchEvent(customEvent);
4247
+ if (statesToCloseWS.includes(detail.slug)) {
4248
+ this.webSocket.close();
4249
+ if (statesToReport.includes(detail.slug)) {
4250
+ await this.client.engineAPI.books.report(this.parentId, {
4251
+ error: detail.slug === "error" ? "design" : "timeout",
4252
+ step: this.state
4253
+ });
4254
+ }
4255
+ }
4256
+ this.state = detail.slug;
4257
+ }
4258
+ timeoutHandler() {
4259
+ return setTimeout(async () => {
4260
+ await this.eventHandler(timeoutMessage);
4261
+ }, designRequestTimeout);
4262
+ }
4263
+ async getProgress() {
4264
+ let timeout;
4265
+ this.webSocket.onmessage = (event) => {
4266
+ const detail = JSON.parse(event.data);
4267
+ if (this.state !== detail.slug) {
4268
+ timeout && clearTimeout(timeout);
4269
+ timeout = this.timeoutHandler();
4270
+ this.eventHandler(detail);
4271
+ }
4272
+ };
4273
+ this.webSocket.onclose = () => clearTimeout(timeout);
4274
+ }
4275
+ toBook() {
4276
+ const designRequest = { ...this };
4277
+ delete designRequest["client"];
4278
+ delete designRequest["images"]["client"];
4279
+ delete designRequest["webSocket"];
4280
+ const styleSlug = styles[this.style].slug;
4281
+ const bookDesignRequest = camelCaseObjectKeysToSnakeCase(cleanJSON(designRequest));
4282
+ bookDesignRequest.style = styleSlug;
4283
+ return new Book({
4284
+ id: designRequest.parentId,
4285
+ guid: designRequest.guid,
4286
+ title: designRequest.title,
4287
+ design_request: bookDesignRequest,
4288
+ state: designRequest.state
4289
+ });
4290
+ }
4291
+ };
4292
+
4293
+ // ../../core/models/galleon.ts
4294
+ var imageAssignmentSchema = z.object({
4295
+ photoRefId: z.string(),
4296
+ finalCrop: z.array(z.number())
4297
+ });
4298
+ var positionSchema = z.object({
4299
+ x: z.number(),
4300
+ y: z.number(),
4301
+ width: z.number().optional(),
4302
+ height: z.number().optional(),
4303
+ rotation: z.number()
4304
+ });
4305
+ var photoMetadataSchema = z.object({
4306
+ id: z.string(),
4307
+ llx: z.number(),
4308
+ lly: z.number(),
4309
+ urx: z.number(),
4310
+ ury: z.number(),
4311
+ data: z.string().nullable(),
4312
+ title: z.string(),
4313
+ width: z.number(),
4314
+ effect: z.string(),
4315
+ height: z.number(),
4316
+ source: z.string(),
4317
+ rotation: z.number(),
4318
+ uploadTime: z.string()
4319
+ });
4320
+ var propertySchema = z.object({
4321
+ key: z.string(),
4322
+ value: z.any()
4323
+ });
4324
+ var assetSchema = z.object({
4325
+ type: z.string(),
4326
+ imageAssignment: imageAssignmentSchema.optional(),
4327
+ position: positionSchema,
4328
+ seqNum: z.number(),
4329
+ z: z.number(),
4330
+ id: z.string().optional(),
4331
+ horizJustification: z.string().optional(),
4332
+ vertJustification: z.string().optional().nullable(),
4333
+ text: z.string().optional(),
4334
+ fontId: z.string().optional(),
4335
+ fontSize: z.number().optional(),
4336
+ fontColor: z.string().optional(),
4337
+ frame: z.string().optional()
4338
+ });
4339
+ var photoStripSchema = z.object({
4340
+ url: z.string(),
4341
+ encryptId: z.string(),
4342
+ photoRefId: z.string(),
4343
+ photoId: z.string(),
4344
+ photoMetadata: photoMetadataSchema
4345
+ });
4346
+ var reportingDataSchema = z.object({
4347
+ properties: z.array(propertySchema)
4348
+ });
4349
+ var canvasSchema = z.object({
4350
+ backgroundId: z.string().nullable(),
4351
+ assets: z.array(assetSchema).optional()
4352
+ });
4353
+ var pageSchema = z.object({
4354
+ pageNum: z.number(),
4355
+ type: z.string(),
4356
+ canvas: canvasSchema
4357
+ });
4358
+ var magicShopBookSchema = z.object({
4359
+ pages: z.array(pageSchema),
4360
+ photoStrip: z.array(photoStripSchema)
4361
+ });
4362
+ var bookCreationRequestSchema = z.object({
4363
+ title: z.string(),
4364
+ binding: z.string(),
4365
+ coverSpecId: z.string(),
4366
+ styleId: z.number(),
4367
+ userId: z.string(),
4368
+ magicShopBook: magicShopBookSchema,
4369
+ reportingData: reportingDataSchema
4370
+ });
4371
+
4372
+ // ../../core/models/engine-api/endpoints/books.ts
4373
+ var BooksEndpoints = class {
4374
+ // eslint-disable-next-line no-unused-vars
4375
+ constructor(engineAPI) {
4376
+ this.engineAPI = engineAPI;
4377
+ bindThisToFunctions(this);
4378
+ }
4379
+ create() {
4380
+ return handleAsyncFunction(async () => {
4381
+ const res = await this.engineAPI.fetcher.call({
4382
+ path: "/v1/books",
4383
+ options: {
4384
+ method: "POST"
4385
+ }
4386
+ });
4387
+ BookPropsSchema.safeParse(res);
4388
+ return new Book(res);
4389
+ });
4390
+ }
4391
+ retrieve(bookId) {
4392
+ return handleAsyncFunction(async () => {
4393
+ const res = await this.engineAPI.fetcher.call({ path: `/v1/books/${bookId}` });
4394
+ BookPropsSchema.safeParse(res);
4395
+ return new Book(res);
4396
+ });
4397
+ }
4398
+ update(bookId, book) {
4399
+ return handleAsyncFunction(async () => {
4400
+ const res = await this.engineAPI.fetcher.call({
4401
+ path: `/v1/books/${bookId}`,
4402
+ options: {
4403
+ method: "PUT",
4404
+ body: cleanJSON(book)
4405
+ }
4406
+ });
4407
+ BookPropsSchema.safeParse(res);
4408
+ return new Book(res);
4409
+ });
4410
+ }
4411
+ cancel(bookId) {
4412
+ return handleAsyncFunction(async () => {
4413
+ const res = await this.engineAPI.fetcher.call({
4414
+ path: `/v1/books/${bookId}/cancel`,
4415
+ options: { method: "POST" }
4416
+ });
4417
+ BookPropsSchema.safeParse(res);
4418
+ return new Book(res);
4419
+ });
4420
+ }
4421
+ report(bookId, report) {
4422
+ return handleAsyncFunction(async () => {
4423
+ await this.engineAPI.fetcher.call({
4424
+ path: `/v1/books/${bookId}/report`,
4425
+ options: {
4426
+ method: "POST",
4427
+ body: cleanJSON(report)
4428
+ }
4429
+ });
4430
+ });
4431
+ }
4432
+ delete(bookId) {
4433
+ return handleAsyncFunction(async () => {
4434
+ await this.engineAPI.fetcher.call({
4435
+ path: `/v1/books/${bookId}`,
4436
+ options: { method: "DELETE" }
4437
+ });
4438
+ });
4439
+ }
4440
+ retrieveGalleon(bookId) {
4441
+ return handleAsyncFunction(async () => {
4442
+ const res = await this.engineAPI.fetcher.call({
4443
+ path: `/v1/books/${bookId}/format/galleon`
4444
+ });
4445
+ return bookCreationRequestSchema.parse(res);
4446
+ });
4447
+ }
4448
+ };
4449
+
4450
+ // ../../core/models/engine-api/endpoints/design-options.ts
4451
+ var DesignOptionsEndpoints = class {
4452
+ // eslint-disable-next-line no-unused-vars
4453
+ constructor(engineAPI) {
4454
+ this.engineAPI = engineAPI;
4455
+ bindThisToFunctions(this);
4456
+ }
4457
+ retrieve(bookSize, imageCount, imageFilteringLevel) {
4458
+ return handleAsyncFunction(async () => {
4459
+ const res = await this.engineAPI.fetcher.call({
4460
+ // eslint-disable-next-line max-len
4461
+ path: `/v1/designoptions/booksize/${bookSize}/imagecount/${imageCount}/imagefilteringlevel/${imageFilteringLevel}`
4462
+ });
4463
+ return designOptionsServerSchema.parse(res);
4464
+ });
4465
+ }
4466
+ };
4467
+
4468
+ // ../../core/models/fetcher.ts
4469
+ var baseOptions = {
4470
+ headers: {
4471
+ "Content-Type": "application/json"
4472
+ },
4473
+ method: "GET"
4474
+ };
4475
+ var Fetcher = class {
4476
+ baseUrl;
4477
+ options;
4478
+ constructor(baseUrl, options) {
4479
+ this.baseUrl = new URL(baseUrl);
4480
+ this.options = mergeNestedObject(baseOptions, options || {});
4481
+ }
4482
+ async call(props) {
4483
+ try {
4484
+ if (props.options?.body && typeof props.options.body !== "string") {
4485
+ props.options.body = JSON.stringify(props.options?.body);
4486
+ }
4487
+ const baseOptions2 = { ...this.options };
4488
+ const options = props.options ? mergeNestedObject(baseOptions2, props.options) : baseOptions2;
4489
+ const res = await fetch(this.cleanUrl(new URL(props.path, this.baseUrl).href), options);
4490
+ if (res.status >= 200 && res.status < 300) {
4491
+ try {
4492
+ return await res.json();
4493
+ } catch (error) {
4494
+ return {};
4495
+ }
4496
+ } else {
4497
+ let detail = res.statusText;
4498
+ try {
4499
+ detail = JSON.stringify((await res.json())?.detail);
4500
+ } catch (error) {
4501
+ }
4502
+ throw Error(`${res.status} ${detail}`);
4503
+ }
4504
+ } catch (error) {
4505
+ return Promise.reject(error);
4506
+ }
4507
+ }
4508
+ cleanUrl(url) {
4509
+ return url.replaceAll(" ", "").trim();
4510
+ }
4511
+ };
4512
+
4513
+ // ../../core/models/engine-api/endpoints/images.ts
4514
+ var ImagesEndpoints = class {
4515
+ // eslint-disable-next-line no-unused-vars
4516
+ constructor(engineAPI) {
4517
+ this.engineAPI = engineAPI;
4518
+ bindThisToFunctions(this);
4519
+ }
4520
+ list(bookId) {
4521
+ return handleAsyncFunction(async () => {
4522
+ const res = await this.engineAPI.fetcher.call({
4523
+ path: `/v1/images/book/${bookId}`
4524
+ });
4525
+ return z.array(imageServerSchema).parse(res);
4526
+ });
4527
+ }
4528
+ retrieve(imageId, bookId) {
4529
+ return handleAsyncFunction(async () => {
4530
+ const res = await this.engineAPI.fetcher.call({
4531
+ path: `/v1/images/${imageId}/book/${bookId}/`
4532
+ });
4533
+ return imageServerSchema.parse(res);
4534
+ });
4535
+ }
4536
+ update(imageId, bookId, image) {
4537
+ return handleAsyncFunction(async () => {
4538
+ const res = await this.engineAPI.fetcher.call({
4539
+ path: `/v1/images/${imageId}/book/${bookId}/`,
4540
+ options: {
4541
+ method: "PUT",
4542
+ body: cleanJSON(image)
4543
+ }
4544
+ });
4545
+ return imageServerSchema.parse(res);
4546
+ });
4547
+ }
4548
+ delete(imageId, bookId) {
4549
+ return handleAsyncFunction(async () => {
4550
+ await this.engineAPI.fetcher.call({
4551
+ path: `/v1/images/${imageId}/book/${bookId}/`,
4552
+ options: {
4553
+ method: "DELETE"
4554
+ }
4555
+ });
4556
+ });
4557
+ }
4558
+ addToBook(bookId, image) {
4559
+ return handleAsyncFunction(async () => {
4560
+ const res = await this.engineAPI.fetcher.call({
4561
+ path: `/v1/images/book/${bookId}`,
4562
+ options: {
4563
+ method: "POST",
4564
+ body: cleanJSON(image)
4565
+ }
4566
+ });
4567
+ return imageServerSchema.parse(res);
4568
+ });
4569
+ }
4570
+ };
4571
+
4572
+ // ../../core/models/spread.ts
4573
+ var spreadServerSchema = z.object({
4574
+ id: z.string().optional(),
4575
+ book_id: z.string(),
4576
+ state: z.string(),
4577
+ spread_type: z.string(),
4578
+ width: z.number().optional(),
4579
+ height: z.number().optional(),
4580
+ sequence: z.number(),
4581
+ wells: z.array(z.unknown()),
4582
+ background: z.unknown(),
4583
+ laid_out_at: z.string().nullable(),
4584
+ embellished_at: z.string().nullable(),
4585
+ polished_at: z.string().nullable(),
4586
+ metadata: z.unknown(),
4587
+ url: z.string().nullable().optional()
4588
+ });
4589
+ var spreadSchema = z.object({
4590
+ id: z.string().optional(),
4591
+ bookId: z.string(),
4592
+ state: z.string(),
4593
+ spreadType: z.string(),
4594
+ width: z.number().optional(),
4595
+ height: z.number().optional(),
4596
+ sequence: z.number(),
4597
+ wells: z.array(z.unknown()),
4598
+ background: z.unknown(),
4599
+ laidOutAt: z.string().nullable(),
4600
+ embellishedAt: z.string().nullable(),
4601
+ polishedAt: z.string().nullable(),
4602
+ metadata: z.unknown(),
4603
+ url: z.string().nullable().optional()
4604
+ });
4605
+
4606
+ // ../../core/models/engine-api/endpoints/spreads.ts
4607
+ var SpreadsEndpoints = class {
4608
+ // eslint-disable-next-line no-unused-vars
4609
+ constructor(engineAPI) {
4610
+ this.engineAPI = engineAPI;
4611
+ bindThisToFunctions(this);
4612
+ }
4613
+ list(bookId) {
4614
+ return handleAsyncFunction(async () => {
4615
+ const res = await this.engineAPI.fetcher.call({
4616
+ path: `/v1/spreads/book/${bookId}`
4617
+ });
4618
+ return z.array(spreadServerSchema).parse(res);
4619
+ });
4620
+ }
4621
+ create(bookId, spread) {
4622
+ return handleAsyncFunction(async () => {
4623
+ const res = await this.engineAPI.fetcher.call({
4624
+ path: `/v1/spreads/book/${bookId}`,
4625
+ options: {
4626
+ method: "POST",
4627
+ body: cleanJSON(spread)
4628
+ }
4629
+ });
4630
+ return spreadServerSchema.parse(res);
4631
+ });
4632
+ }
4633
+ retrieve(spreadId, bookId) {
4634
+ return handleAsyncFunction(async () => {
4635
+ const res = await this.engineAPI.fetcher.call({
4636
+ path: `/v1/spreads/${spreadId}/book/${bookId}`
4637
+ });
4638
+ return spreadServerSchema.parse(res);
4639
+ });
4640
+ }
4641
+ update(spreadId, bookId, spread) {
4642
+ return handleAsyncFunction(async () => {
4643
+ const res = await this.engineAPI.fetcher.call({
4644
+ path: `/v1/spreads/${spreadId}/book/${bookId}`,
4645
+ options: {
4646
+ method: "PUT",
4647
+ body: cleanJSON(spread)
4648
+ }
4649
+ });
4650
+ return spreadServerSchema.parse(res);
4651
+ });
4652
+ }
4653
+ delete(spreadId, bookId) {
4654
+ return handleAsyncFunction(async () => {
4655
+ await this.engineAPI.fetcher.call({
4656
+ path: `/v1/spreads/${spreadId}/book/${bookId}`,
4657
+ options: {
4658
+ method: "DELETE"
4659
+ }
4660
+ });
4661
+ });
4662
+ }
4663
+ };
4664
+
4665
+ // ../../core/models/storyboard-item.ts
4666
+ var StoryboardItemImageFaceServerSchema = z.object({
4667
+ score: z.number(),
4668
+ bounding_box: z.object({
4669
+ x: z.number(),
4670
+ y: z.number(),
4671
+ width: z.number(),
4672
+ height: z.number()
4673
+ }),
4674
+ size: z.number(),
4675
+ eyes_open_score: z.number(),
4676
+ smile_score: z.number(),
4677
+ facing_camera_score: z.number()
4678
+ });
4679
+ var StoryboardItemImageFaceSchema = z.object({
4680
+ score: z.number(),
4681
+ boundingBox: z.object({
4682
+ x: z.number(),
4683
+ y: z.number(),
4684
+ width: z.number(),
4685
+ height: z.number()
4686
+ }),
4687
+ size: z.number(),
4688
+ eyesOpenScore: z.number(),
4689
+ smileScore: z.number(),
4690
+ facingCameraScore: z.number()
4691
+ });
4692
+ var StoryboardItemImageServerSchema = z.object({
4693
+ id: z.string(),
4694
+ url: z.string(),
4695
+ category: z.string(),
4696
+ aesthetic_score: z.number(),
4697
+ faces: z.array(StoryboardItemImageFaceServerSchema),
4698
+ roi: z.object({
4699
+ x: z.number(),
4700
+ y: z.number(),
4701
+ width: z.number(),
4702
+ height: z.number()
4703
+ }),
4704
+ taken_at: z.number(),
4705
+ width: z.number(),
4706
+ height: z.number()
4707
+ });
4708
+ var StoryboardItemImageSchema = z.object({
4709
+ id: z.string(),
4710
+ url: z.string(),
4711
+ category: z.string(),
4712
+ aestheticScore: z.number(),
4713
+ faces: z.array(StoryboardItemImageFaceSchema),
4714
+ roi: z.object({
4715
+ x: z.number(),
4716
+ y: z.number(),
4717
+ width: z.number(),
4718
+ height: z.number()
4719
+ }),
4720
+ takenAt: z.number(),
4721
+ width: z.number(),
4722
+ height: z.number()
4723
+ });
4724
+ var StoryboardItemServerSchema = z.object({
4725
+ id: z.string(),
4726
+ sequence: z.number(),
4727
+ book_id: z.string(),
4728
+ similarity: z.number(),
4729
+ duplicate: z.boolean(),
4730
+ selected: z.boolean(),
4731
+ surface_weight: z.number(),
4732
+ front_cover: z.boolean().optional(),
4733
+ back_cover: z.boolean().optional(),
4734
+ scene: z.number(),
4735
+ subscene: z.number(),
4736
+ spine_break: z.boolean().optional(),
4737
+ image: StoryboardItemImageServerSchema
4738
+ });
4739
+ var StoryboardItemSchema = z.object({
4740
+ id: z.string(),
4741
+ sequence: z.number(),
4742
+ bookId: z.string(),
4743
+ similarity: z.number(),
4744
+ duplicate: z.boolean(),
4745
+ selected: z.boolean(),
4746
+ surfaceWeight: z.number(),
4747
+ frontCover: z.boolean().optional(),
4748
+ backCover: z.boolean().optional(),
4749
+ scene: z.number(),
4750
+ subscene: z.number(),
4751
+ spineBreak: z.boolean().optional(),
4752
+ image: StoryboardItemImageSchema
4753
+ });
4754
+
4755
+ // ../../core/models/engine-api/endpoints/storyboard-items.ts
4756
+ var StoryboardItemsEndpoints = class {
4757
+ // eslint-disable-next-line no-unused-vars
4758
+ constructor(engineAPI) {
4759
+ this.engineAPI = engineAPI;
4760
+ bindThisToFunctions(this);
4761
+ }
4762
+ list(bookId) {
4763
+ return handleAsyncFunction(async () => {
4764
+ const res = await this.engineAPI.fetcher.call({
4765
+ path: `/v1/storyboarditems/book/${bookId}`
4766
+ });
4767
+ return z.array(StoryboardItemServerSchema).parse(res);
4768
+ });
4769
+ }
4770
+ };
4771
+
4772
+ // ../../core/models/engine-api/index.ts
4773
+ var EngineAPI = class {
4774
+ baseUrl;
4775
+ apiKey;
4776
+ fetcher;
4777
+ constructor(baseUrl, apiKey) {
4778
+ this.baseUrl = new URL(baseUrl);
4779
+ this.apiKey = apiKey;
4780
+ const options = {
4781
+ headers: {
4782
+ "Authorization": `API-Key ${this.apiKey}`
4783
+ }
4784
+ };
4785
+ this.fetcher = new Fetcher(baseUrl, options);
4786
+ }
4787
+ books = new BooksEndpoints(this);
4788
+ designOptions = new DesignOptionsEndpoints(this);
4789
+ storyboardItems = new StoryboardItemsEndpoints(this);
4790
+ images = new ImagesEndpoints(this);
4791
+ spreads = new SpreadsEndpoints(this);
4792
+ };
4793
+
4794
+ // ../../core/models/client.ts
4795
+ var MagicBookClient = class {
4796
+ constructor(apiKey, apiHost = defaultApiHost, webSocketHost = defaultWebSocketHost) {
4797
+ this.apiKey = apiKey;
4798
+ this.apiHost = apiHost;
4799
+ this.webSocketHost = webSocketHost;
4800
+ this.engineAPI = new EngineAPI(this.apiHost, this.apiKey);
4801
+ }
4802
+ engineAPI;
4803
+ async createDesignRequest(designRequestProps) {
4804
+ const book = await this.engineAPI.books.create();
4805
+ return new DesignRequest(book.id, this, designRequestProps);
4806
+ }
4807
+ };
4808
+ export {
4809
+ DesignRequest,
4810
+ DesignRequestOptions,
4811
+ ImageServer,
4812
+ Images,
4813
+ MagicBookClient,
4814
+ designOptionsSchema,
4815
+ designOptionsServerSchema,
4816
+ imageDensityOptionSchema,
4817
+ imageDensityOptionServerSchema,
4818
+ imageDensityOptionsSchema,
4819
+ imageDensityOptionsServerSchema,
4820
+ imageServerSchema
4821
+ };
4822
+ //# sourceMappingURL=index.js.map