@littlelittlecloud/dak-cli 0.2.0-20260410.ebef854

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