@ampcode/sdk 0.0.0-placeholder → 0.1.0-20260513070248-g548495c

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