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