@march-ai/history-sdk 0.1.0

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