@tencent-ai/cloud-agent-sdk 0.1.6 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,3841 +3,6 @@ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).export
3
3
 
4
4
  //#endregion
5
5
 
6
- //#region ../agent-provider/node_modules/zod/v3/helpers/util.cjs
7
- var require_util = /* @__PURE__ */ __commonJSMin(((exports) => {
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0;
10
- var util;
11
- (function(util) {
12
- util.assertEqual = (_) => {};
13
- function assertIs(_arg) {}
14
- util.assertIs = assertIs;
15
- function assertNever(_x) {
16
- throw new Error();
17
- }
18
- util.assertNever = assertNever;
19
- util.arrayToEnum = (items) => {
20
- const obj = {};
21
- for (const item of items) obj[item] = item;
22
- return obj;
23
- };
24
- util.getValidEnumValues = (obj) => {
25
- const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
26
- const filtered = {};
27
- for (const k of validKeys) filtered[k] = obj[k];
28
- return util.objectValues(filtered);
29
- };
30
- util.objectValues = (obj) => {
31
- return util.objectKeys(obj).map(function(e) {
32
- return obj[e];
33
- });
34
- };
35
- util.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
36
- const keys = [];
37
- for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
38
- return keys;
39
- };
40
- util.find = (arr, checker) => {
41
- for (const item of arr) if (checker(item)) return item;
42
- };
43
- util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
44
- function joinValues(array, separator = " | ") {
45
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
46
- }
47
- util.joinValues = joinValues;
48
- util.jsonStringifyReplacer = (_, value) => {
49
- if (typeof value === "bigint") return value.toString();
50
- return value;
51
- };
52
- })(util || (exports.util = util = {}));
53
- var objectUtil;
54
- (function(objectUtil) {
55
- objectUtil.mergeShapes = (first, second) => {
56
- return {
57
- ...first,
58
- ...second
59
- };
60
- };
61
- })(objectUtil || (exports.objectUtil = objectUtil = {}));
62
- exports.ZodParsedType = util.arrayToEnum([
63
- "string",
64
- "nan",
65
- "number",
66
- "integer",
67
- "float",
68
- "boolean",
69
- "date",
70
- "bigint",
71
- "symbol",
72
- "function",
73
- "undefined",
74
- "null",
75
- "array",
76
- "object",
77
- "unknown",
78
- "promise",
79
- "void",
80
- "never",
81
- "map",
82
- "set"
83
- ]);
84
- const getParsedType = (data) => {
85
- switch (typeof data) {
86
- case "undefined": return exports.ZodParsedType.undefined;
87
- case "string": return exports.ZodParsedType.string;
88
- case "number": return Number.isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number;
89
- case "boolean": return exports.ZodParsedType.boolean;
90
- case "function": return exports.ZodParsedType.function;
91
- case "bigint": return exports.ZodParsedType.bigint;
92
- case "symbol": return exports.ZodParsedType.symbol;
93
- case "object":
94
- if (Array.isArray(data)) return exports.ZodParsedType.array;
95
- if (data === null) return exports.ZodParsedType.null;
96
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") return exports.ZodParsedType.promise;
97
- if (typeof Map !== "undefined" && data instanceof Map) return exports.ZodParsedType.map;
98
- if (typeof Set !== "undefined" && data instanceof Set) return exports.ZodParsedType.set;
99
- if (typeof Date !== "undefined" && data instanceof Date) return exports.ZodParsedType.date;
100
- return exports.ZodParsedType.object;
101
- default: return exports.ZodParsedType.unknown;
102
- }
103
- };
104
- exports.getParsedType = getParsedType;
105
- }));
106
-
107
- //#endregion
108
- //#region ../agent-provider/node_modules/zod/v3/ZodError.cjs
109
- var require_ZodError = /* @__PURE__ */ __commonJSMin(((exports) => {
110
- Object.defineProperty(exports, "__esModule", { value: true });
111
- exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;
112
- const util_js_1 = require_util();
113
- exports.ZodIssueCode = util_js_1.util.arrayToEnum([
114
- "invalid_type",
115
- "invalid_literal",
116
- "custom",
117
- "invalid_union",
118
- "invalid_union_discriminator",
119
- "invalid_enum_value",
120
- "unrecognized_keys",
121
- "invalid_arguments",
122
- "invalid_return_type",
123
- "invalid_date",
124
- "invalid_string",
125
- "too_small",
126
- "too_big",
127
- "invalid_intersection_types",
128
- "not_multiple_of",
129
- "not_finite"
130
- ]);
131
- const quotelessJson = (obj) => {
132
- return JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:");
133
- };
134
- exports.quotelessJson = quotelessJson;
135
- var ZodError = class ZodError extends Error {
136
- get errors() {
137
- return this.issues;
138
- }
139
- constructor(issues) {
140
- super();
141
- this.issues = [];
142
- this.addIssue = (sub) => {
143
- this.issues = [...this.issues, sub];
144
- };
145
- this.addIssues = (subs = []) => {
146
- this.issues = [...this.issues, ...subs];
147
- };
148
- const actualProto = new.target.prototype;
149
- if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
150
- else this.__proto__ = actualProto;
151
- this.name = "ZodError";
152
- this.issues = issues;
153
- }
154
- format(_mapper) {
155
- const mapper = _mapper || function(issue) {
156
- return issue.message;
157
- };
158
- const fieldErrors = { _errors: [] };
159
- const processError = (error) => {
160
- for (const issue of error.issues) if (issue.code === "invalid_union") issue.unionErrors.map(processError);
161
- else if (issue.code === "invalid_return_type") processError(issue.returnTypeError);
162
- else if (issue.code === "invalid_arguments") processError(issue.argumentsError);
163
- else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
164
- else {
165
- let curr = fieldErrors;
166
- let i = 0;
167
- while (i < issue.path.length) {
168
- const el = issue.path[i];
169
- if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
170
- else {
171
- curr[el] = curr[el] || { _errors: [] };
172
- curr[el]._errors.push(mapper(issue));
173
- }
174
- curr = curr[el];
175
- i++;
176
- }
177
- }
178
- };
179
- processError(this);
180
- return fieldErrors;
181
- }
182
- static assert(value) {
183
- if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
184
- }
185
- toString() {
186
- return this.message;
187
- }
188
- get message() {
189
- return JSON.stringify(this.issues, util_js_1.util.jsonStringifyReplacer, 2);
190
- }
191
- get isEmpty() {
192
- return this.issues.length === 0;
193
- }
194
- flatten(mapper = (issue) => issue.message) {
195
- const fieldErrors = {};
196
- const formErrors = [];
197
- for (const sub of this.issues) if (sub.path.length > 0) {
198
- const firstEl = sub.path[0];
199
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
200
- fieldErrors[firstEl].push(mapper(sub));
201
- } else formErrors.push(mapper(sub));
202
- return {
203
- formErrors,
204
- fieldErrors
205
- };
206
- }
207
- get formErrors() {
208
- return this.flatten();
209
- }
210
- };
211
- exports.ZodError = ZodError;
212
- ZodError.create = (issues) => {
213
- return new ZodError(issues);
214
- };
215
- }));
216
-
217
- //#endregion
218
- //#region ../agent-provider/node_modules/zod/v3/locales/en.cjs
219
- var require_en = /* @__PURE__ */ __commonJSMin(((exports) => {
220
- Object.defineProperty(exports, "__esModule", { value: true });
221
- const ZodError_js_1 = require_ZodError();
222
- const util_js_1 = require_util();
223
- const errorMap = (issue, _ctx) => {
224
- let message;
225
- switch (issue.code) {
226
- case ZodError_js_1.ZodIssueCode.invalid_type:
227
- if (issue.received === util_js_1.ZodParsedType.undefined) message = "Required";
228
- else message = `Expected ${issue.expected}, received ${issue.received}`;
229
- break;
230
- case ZodError_js_1.ZodIssueCode.invalid_literal:
231
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_js_1.util.jsonStringifyReplacer)}`;
232
- break;
233
- case ZodError_js_1.ZodIssueCode.unrecognized_keys:
234
- message = `Unrecognized key(s) in object: ${util_js_1.util.joinValues(issue.keys, ", ")}`;
235
- break;
236
- case ZodError_js_1.ZodIssueCode.invalid_union:
237
- message = `Invalid input`;
238
- break;
239
- case ZodError_js_1.ZodIssueCode.invalid_union_discriminator:
240
- message = `Invalid discriminator value. Expected ${util_js_1.util.joinValues(issue.options)}`;
241
- break;
242
- case ZodError_js_1.ZodIssueCode.invalid_enum_value:
243
- message = `Invalid enum value. Expected ${util_js_1.util.joinValues(issue.options)}, received '${issue.received}'`;
244
- break;
245
- case ZodError_js_1.ZodIssueCode.invalid_arguments:
246
- message = `Invalid function arguments`;
247
- break;
248
- case ZodError_js_1.ZodIssueCode.invalid_return_type:
249
- message = `Invalid function return type`;
250
- break;
251
- case ZodError_js_1.ZodIssueCode.invalid_date:
252
- message = `Invalid date`;
253
- break;
254
- case ZodError_js_1.ZodIssueCode.invalid_string:
255
- if (typeof issue.validation === "object") if ("includes" in issue.validation) {
256
- message = `Invalid input: must include "${issue.validation.includes}"`;
257
- if (typeof issue.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
258
- } else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`;
259
- else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`;
260
- else util_js_1.util.assertNever(issue.validation);
261
- else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
262
- else message = "Invalid";
263
- break;
264
- case ZodError_js_1.ZodIssueCode.too_small:
265
- if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
266
- else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
267
- else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
268
- else if (issue.type === "bigint") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
269
- else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
270
- else message = "Invalid input";
271
- break;
272
- case ZodError_js_1.ZodIssueCode.too_big:
273
- if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
274
- else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
275
- else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
276
- else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
277
- else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
278
- else message = "Invalid input";
279
- break;
280
- case ZodError_js_1.ZodIssueCode.custom:
281
- message = `Invalid input`;
282
- break;
283
- case ZodError_js_1.ZodIssueCode.invalid_intersection_types:
284
- message = `Intersection results could not be merged`;
285
- break;
286
- case ZodError_js_1.ZodIssueCode.not_multiple_of:
287
- message = `Number must be a multiple of ${issue.multipleOf}`;
288
- break;
289
- case ZodError_js_1.ZodIssueCode.not_finite:
290
- message = "Number must be finite";
291
- break;
292
- default:
293
- message = _ctx.defaultError;
294
- util_js_1.util.assertNever(issue);
295
- }
296
- return { message };
297
- };
298
- exports.default = errorMap;
299
- }));
300
-
301
- //#endregion
302
- //#region ../agent-provider/node_modules/zod/v3/errors.cjs
303
- var require_errors$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
304
- var __importDefault = exports && exports.__importDefault || function(mod) {
305
- return mod && mod.__esModule ? mod : { "default": mod };
306
- };
307
- Object.defineProperty(exports, "__esModule", { value: true });
308
- exports.defaultErrorMap = void 0;
309
- exports.setErrorMap = setErrorMap;
310
- exports.getErrorMap = getErrorMap;
311
- const en_js_1 = __importDefault(require_en());
312
- exports.defaultErrorMap = en_js_1.default;
313
- let overrideErrorMap = en_js_1.default;
314
- function setErrorMap(map) {
315
- overrideErrorMap = map;
316
- }
317
- function getErrorMap() {
318
- return overrideErrorMap;
319
- }
320
- }));
321
-
322
- //#endregion
323
- //#region ../agent-provider/node_modules/zod/v3/helpers/parseUtil.cjs
324
- var require_parseUtil = /* @__PURE__ */ __commonJSMin(((exports) => {
325
- var __importDefault = exports && exports.__importDefault || function(mod) {
326
- return mod && mod.__esModule ? mod : { "default": mod };
327
- };
328
- Object.defineProperty(exports, "__esModule", { value: true });
329
- exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.EMPTY_PATH = exports.makeIssue = void 0;
330
- exports.addIssueToContext = addIssueToContext;
331
- const errors_js_1 = require_errors$1();
332
- const en_js_1 = __importDefault(require_en());
333
- const makeIssue = (params) => {
334
- const { data, path, errorMaps, issueData } = params;
335
- const fullPath = [...path, ...issueData.path || []];
336
- const fullIssue = {
337
- ...issueData,
338
- path: fullPath
339
- };
340
- if (issueData.message !== void 0) return {
341
- ...issueData,
342
- path: fullPath,
343
- message: issueData.message
344
- };
345
- let errorMessage = "";
346
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
347
- for (const map of maps) errorMessage = map(fullIssue, {
348
- data,
349
- defaultError: errorMessage
350
- }).message;
351
- return {
352
- ...issueData,
353
- path: fullPath,
354
- message: errorMessage
355
- };
356
- };
357
- exports.makeIssue = makeIssue;
358
- exports.EMPTY_PATH = [];
359
- function addIssueToContext(ctx, issueData) {
360
- const overrideMap = (0, errors_js_1.getErrorMap)();
361
- const issue = (0, exports.makeIssue)({
362
- issueData,
363
- data: ctx.data,
364
- path: ctx.path,
365
- errorMaps: [
366
- ctx.common.contextualErrorMap,
367
- ctx.schemaErrorMap,
368
- overrideMap,
369
- overrideMap === en_js_1.default ? void 0 : en_js_1.default
370
- ].filter((x) => !!x)
371
- });
372
- ctx.common.issues.push(issue);
373
- }
374
- var ParseStatus = class ParseStatus {
375
- constructor() {
376
- this.value = "valid";
377
- }
378
- dirty() {
379
- if (this.value === "valid") this.value = "dirty";
380
- }
381
- abort() {
382
- if (this.value !== "aborted") this.value = "aborted";
383
- }
384
- static mergeArray(status, results) {
385
- const arrayValue = [];
386
- for (const s of results) {
387
- if (s.status === "aborted") return exports.INVALID;
388
- if (s.status === "dirty") status.dirty();
389
- arrayValue.push(s.value);
390
- }
391
- return {
392
- status: status.value,
393
- value: arrayValue
394
- };
395
- }
396
- static async mergeObjectAsync(status, pairs) {
397
- const syncPairs = [];
398
- for (const pair of pairs) {
399
- const key = await pair.key;
400
- const value = await pair.value;
401
- syncPairs.push({
402
- key,
403
- value
404
- });
405
- }
406
- return ParseStatus.mergeObjectSync(status, syncPairs);
407
- }
408
- static mergeObjectSync(status, pairs) {
409
- const finalObject = {};
410
- for (const pair of pairs) {
411
- const { key, value } = pair;
412
- if (key.status === "aborted") return exports.INVALID;
413
- if (value.status === "aborted") return exports.INVALID;
414
- if (key.status === "dirty") status.dirty();
415
- if (value.status === "dirty") status.dirty();
416
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
417
- }
418
- return {
419
- status: status.value,
420
- value: finalObject
421
- };
422
- }
423
- };
424
- exports.ParseStatus = ParseStatus;
425
- exports.INVALID = Object.freeze({ status: "aborted" });
426
- const DIRTY = (value) => ({
427
- status: "dirty",
428
- value
429
- });
430
- exports.DIRTY = DIRTY;
431
- const OK = (value) => ({
432
- status: "valid",
433
- value
434
- });
435
- exports.OK = OK;
436
- const isAborted = (x) => x.status === "aborted";
437
- exports.isAborted = isAborted;
438
- const isDirty = (x) => x.status === "dirty";
439
- exports.isDirty = isDirty;
440
- const isValid = (x) => x.status === "valid";
441
- exports.isValid = isValid;
442
- const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
443
- exports.isAsync = isAsync;
444
- }));
445
-
446
- //#endregion
447
- //#region ../agent-provider/node_modules/zod/v3/helpers/typeAliases.cjs
448
- var require_typeAliases = /* @__PURE__ */ __commonJSMin(((exports) => {
449
- Object.defineProperty(exports, "__esModule", { value: true });
450
- }));
451
-
452
- //#endregion
453
- //#region ../agent-provider/node_modules/zod/v3/helpers/errorUtil.cjs
454
- var require_errorUtil = /* @__PURE__ */ __commonJSMin(((exports) => {
455
- Object.defineProperty(exports, "__esModule", { value: true });
456
- exports.errorUtil = void 0;
457
- var errorUtil;
458
- (function(errorUtil) {
459
- errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
460
- errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
461
- })(errorUtil || (exports.errorUtil = errorUtil = {}));
462
- }));
463
-
464
- //#endregion
465
- //#region ../agent-provider/node_modules/zod/v3/types.cjs
466
- var require_types$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
467
- Object.defineProperty(exports, "__esModule", { value: true });
468
- exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
469
- exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = void 0;
470
- exports.datetimeRegex = datetimeRegex;
471
- exports.custom = custom;
472
- const ZodError_js_1 = require_ZodError();
473
- const errors_js_1 = require_errors$1();
474
- const errorUtil_js_1 = require_errorUtil();
475
- const parseUtil_js_1 = require_parseUtil();
476
- const util_js_1 = require_util();
477
- var ParseInputLazyPath = class {
478
- constructor(parent, value, path, key) {
479
- this._cachedPath = [];
480
- this.parent = parent;
481
- this.data = value;
482
- this._path = path;
483
- this._key = key;
484
- }
485
- get path() {
486
- if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
487
- else this._cachedPath.push(...this._path, this._key);
488
- return this._cachedPath;
489
- }
490
- };
491
- const handleResult = (ctx, result) => {
492
- if ((0, parseUtil_js_1.isValid)(result)) return {
493
- success: true,
494
- data: result.value
495
- };
496
- else {
497
- if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
498
- return {
499
- success: false,
500
- get error() {
501
- if (this._error) return this._error;
502
- this._error = new ZodError_js_1.ZodError(ctx.common.issues);
503
- return this._error;
504
- }
505
- };
506
- }
507
- };
508
- function processCreateParams(params) {
509
- if (!params) return {};
510
- const { errorMap, invalid_type_error, required_error, description } = params;
511
- if (errorMap && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
512
- if (errorMap) return {
513
- errorMap,
514
- description
515
- };
516
- const customMap = (iss, ctx) => {
517
- const { message } = params;
518
- if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError };
519
- if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError };
520
- if (iss.code !== "invalid_type") return { message: ctx.defaultError };
521
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
522
- };
523
- return {
524
- errorMap: customMap,
525
- description
526
- };
527
- }
528
- var ZodType = class {
529
- get description() {
530
- return this._def.description;
531
- }
532
- _getType(input) {
533
- return (0, util_js_1.getParsedType)(input.data);
534
- }
535
- _getOrReturnCtx(input, ctx) {
536
- return ctx || {
537
- common: input.parent.common,
538
- data: input.data,
539
- parsedType: (0, util_js_1.getParsedType)(input.data),
540
- schemaErrorMap: this._def.errorMap,
541
- path: input.path,
542
- parent: input.parent
543
- };
544
- }
545
- _processInputParams(input) {
546
- return {
547
- status: new parseUtil_js_1.ParseStatus(),
548
- ctx: {
549
- common: input.parent.common,
550
- data: input.data,
551
- parsedType: (0, util_js_1.getParsedType)(input.data),
552
- schemaErrorMap: this._def.errorMap,
553
- path: input.path,
554
- parent: input.parent
555
- }
556
- };
557
- }
558
- _parseSync(input) {
559
- const result = this._parse(input);
560
- if ((0, parseUtil_js_1.isAsync)(result)) throw new Error("Synchronous parse encountered promise.");
561
- return result;
562
- }
563
- _parseAsync(input) {
564
- const result = this._parse(input);
565
- return Promise.resolve(result);
566
- }
567
- parse(data, params) {
568
- const result = this.safeParse(data, params);
569
- if (result.success) return result.data;
570
- throw result.error;
571
- }
572
- safeParse(data, params) {
573
- const ctx = {
574
- common: {
575
- issues: [],
576
- async: params?.async ?? false,
577
- contextualErrorMap: params?.errorMap
578
- },
579
- path: params?.path || [],
580
- schemaErrorMap: this._def.errorMap,
581
- parent: null,
582
- data,
583
- parsedType: (0, util_js_1.getParsedType)(data)
584
- };
585
- return handleResult(ctx, this._parseSync({
586
- data,
587
- path: ctx.path,
588
- parent: ctx
589
- }));
590
- }
591
- "~validate"(data) {
592
- const ctx = {
593
- common: {
594
- issues: [],
595
- async: !!this["~standard"].async
596
- },
597
- path: [],
598
- schemaErrorMap: this._def.errorMap,
599
- parent: null,
600
- data,
601
- parsedType: (0, util_js_1.getParsedType)(data)
602
- };
603
- if (!this["~standard"].async) try {
604
- const result = this._parseSync({
605
- data,
606
- path: [],
607
- parent: ctx
608
- });
609
- return (0, parseUtil_js_1.isValid)(result) ? { value: result.value } : { issues: ctx.common.issues };
610
- } catch (err) {
611
- if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
612
- ctx.common = {
613
- issues: [],
614
- async: true
615
- };
616
- }
617
- return this._parseAsync({
618
- data,
619
- path: [],
620
- parent: ctx
621
- }).then((result) => (0, parseUtil_js_1.isValid)(result) ? { value: result.value } : { issues: ctx.common.issues });
622
- }
623
- async parseAsync(data, params) {
624
- const result = await this.safeParseAsync(data, params);
625
- if (result.success) return result.data;
626
- throw result.error;
627
- }
628
- async safeParseAsync(data, params) {
629
- const ctx = {
630
- common: {
631
- issues: [],
632
- contextualErrorMap: params?.errorMap,
633
- async: true
634
- },
635
- path: params?.path || [],
636
- schemaErrorMap: this._def.errorMap,
637
- parent: null,
638
- data,
639
- parsedType: (0, util_js_1.getParsedType)(data)
640
- };
641
- const maybeAsyncResult = this._parse({
642
- data,
643
- path: ctx.path,
644
- parent: ctx
645
- });
646
- return handleResult(ctx, await ((0, parseUtil_js_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)));
647
- }
648
- refine(check, message) {
649
- const getIssueProperties = (val) => {
650
- if (typeof message === "string" || typeof message === "undefined") return { message };
651
- else if (typeof message === "function") return message(val);
652
- else return message;
653
- };
654
- return this._refinement((val, ctx) => {
655
- const result = check(val);
656
- const setError = () => ctx.addIssue({
657
- code: ZodError_js_1.ZodIssueCode.custom,
658
- ...getIssueProperties(val)
659
- });
660
- if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data) => {
661
- if (!data) {
662
- setError();
663
- return false;
664
- } else return true;
665
- });
666
- if (!result) {
667
- setError();
668
- return false;
669
- } else return true;
670
- });
671
- }
672
- refinement(check, refinementData) {
673
- return this._refinement((val, ctx) => {
674
- if (!check(val)) {
675
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
676
- return false;
677
- } else return true;
678
- });
679
- }
680
- _refinement(refinement) {
681
- return new ZodEffects({
682
- schema: this,
683
- typeName: ZodFirstPartyTypeKind.ZodEffects,
684
- effect: {
685
- type: "refinement",
686
- refinement
687
- }
688
- });
689
- }
690
- superRefine(refinement) {
691
- return this._refinement(refinement);
692
- }
693
- constructor(def) {
694
- /** Alias of safeParseAsync */
695
- this.spa = this.safeParseAsync;
696
- this._def = def;
697
- this.parse = this.parse.bind(this);
698
- this.safeParse = this.safeParse.bind(this);
699
- this.parseAsync = this.parseAsync.bind(this);
700
- this.safeParseAsync = this.safeParseAsync.bind(this);
701
- this.spa = this.spa.bind(this);
702
- this.refine = this.refine.bind(this);
703
- this.refinement = this.refinement.bind(this);
704
- this.superRefine = this.superRefine.bind(this);
705
- this.optional = this.optional.bind(this);
706
- this.nullable = this.nullable.bind(this);
707
- this.nullish = this.nullish.bind(this);
708
- this.array = this.array.bind(this);
709
- this.promise = this.promise.bind(this);
710
- this.or = this.or.bind(this);
711
- this.and = this.and.bind(this);
712
- this.transform = this.transform.bind(this);
713
- this.brand = this.brand.bind(this);
714
- this.default = this.default.bind(this);
715
- this.catch = this.catch.bind(this);
716
- this.describe = this.describe.bind(this);
717
- this.pipe = this.pipe.bind(this);
718
- this.readonly = this.readonly.bind(this);
719
- this.isNullable = this.isNullable.bind(this);
720
- this.isOptional = this.isOptional.bind(this);
721
- this["~standard"] = {
722
- version: 1,
723
- vendor: "zod",
724
- validate: (data) => this["~validate"](data)
725
- };
726
- }
727
- optional() {
728
- return ZodOptional.create(this, this._def);
729
- }
730
- nullable() {
731
- return ZodNullable.create(this, this._def);
732
- }
733
- nullish() {
734
- return this.nullable().optional();
735
- }
736
- array() {
737
- return ZodArray.create(this);
738
- }
739
- promise() {
740
- return ZodPromise.create(this, this._def);
741
- }
742
- or(option) {
743
- return ZodUnion.create([this, option], this._def);
744
- }
745
- and(incoming) {
746
- return ZodIntersection.create(this, incoming, this._def);
747
- }
748
- transform(transform) {
749
- return new ZodEffects({
750
- ...processCreateParams(this._def),
751
- schema: this,
752
- typeName: ZodFirstPartyTypeKind.ZodEffects,
753
- effect: {
754
- type: "transform",
755
- transform
756
- }
757
- });
758
- }
759
- default(def) {
760
- const defaultValueFunc = typeof def === "function" ? def : () => def;
761
- return new ZodDefault({
762
- ...processCreateParams(this._def),
763
- innerType: this,
764
- defaultValue: defaultValueFunc,
765
- typeName: ZodFirstPartyTypeKind.ZodDefault
766
- });
767
- }
768
- brand() {
769
- return new ZodBranded({
770
- typeName: ZodFirstPartyTypeKind.ZodBranded,
771
- type: this,
772
- ...processCreateParams(this._def)
773
- });
774
- }
775
- catch(def) {
776
- const catchValueFunc = typeof def === "function" ? def : () => def;
777
- return new ZodCatch({
778
- ...processCreateParams(this._def),
779
- innerType: this,
780
- catchValue: catchValueFunc,
781
- typeName: ZodFirstPartyTypeKind.ZodCatch
782
- });
783
- }
784
- describe(description) {
785
- const This = this.constructor;
786
- return new This({
787
- ...this._def,
788
- description
789
- });
790
- }
791
- pipe(target) {
792
- return ZodPipeline.create(this, target);
793
- }
794
- readonly() {
795
- return ZodReadonly.create(this);
796
- }
797
- isOptional() {
798
- return this.safeParse(void 0).success;
799
- }
800
- isNullable() {
801
- return this.safeParse(null).success;
802
- }
803
- };
804
- exports.ZodType = ZodType;
805
- exports.Schema = ZodType;
806
- exports.ZodSchema = ZodType;
807
- const cuidRegex = /^c[^\s-]{8,}$/i;
808
- const cuid2Regex = /^[0-9a-z]+$/;
809
- const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
810
- const 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;
811
- const nanoidRegex = /^[a-z0-9_-]{21}$/i;
812
- const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
813
- const 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)?)??$/;
814
- const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
815
- const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
816
- let emojiRegex;
817
- const 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])$/;
818
- const 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])$/;
819
- const 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]))$/;
820
- const 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])$/;
821
- const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
822
- const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
823
- const 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])))`;
824
- const dateRegex = new RegExp(`^${dateRegexSource}$`);
825
- function timeRegexSource(args) {
826
- let secondsRegexSource = `[0-5]\\d`;
827
- if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
828
- else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
829
- const secondsQuantifier = args.precision ? "+" : "?";
830
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
831
- }
832
- function timeRegex(args) {
833
- return new RegExp(`^${timeRegexSource(args)}$`);
834
- }
835
- function datetimeRegex(args) {
836
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
837
- const opts = [];
838
- opts.push(args.local ? `Z?` : `Z`);
839
- if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`);
840
- regex = `${regex}(${opts.join("|")})`;
841
- return new RegExp(`^${regex}$`);
842
- }
843
- function isValidIP(ip, version) {
844
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) return true;
845
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) return true;
846
- return false;
847
- }
848
- function isValidJWT(jwt, alg) {
849
- if (!jwtRegex.test(jwt)) return false;
850
- try {
851
- const [header] = jwt.split(".");
852
- if (!header) return false;
853
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
854
- const decoded = JSON.parse(atob(base64));
855
- if (typeof decoded !== "object" || decoded === null) return false;
856
- if ("typ" in decoded && decoded?.typ !== "JWT") return false;
857
- if (!decoded.alg) return false;
858
- if (alg && decoded.alg !== alg) return false;
859
- return true;
860
- } catch {
861
- return false;
862
- }
863
- }
864
- function isValidCidr(ip, version) {
865
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) return true;
866
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) return true;
867
- return false;
868
- }
869
- var ZodString = class ZodString extends ZodType {
870
- _parse(input) {
871
- if (this._def.coerce) input.data = String(input.data);
872
- if (this._getType(input) !== util_js_1.ZodParsedType.string) {
873
- const ctx = this._getOrReturnCtx(input);
874
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
875
- code: ZodError_js_1.ZodIssueCode.invalid_type,
876
- expected: util_js_1.ZodParsedType.string,
877
- received: ctx.parsedType
878
- });
879
- return parseUtil_js_1.INVALID;
880
- }
881
- const status = new parseUtil_js_1.ParseStatus();
882
- let ctx = void 0;
883
- for (const check of this._def.checks) if (check.kind === "min") {
884
- if (input.data.length < check.value) {
885
- ctx = this._getOrReturnCtx(input, ctx);
886
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
887
- code: ZodError_js_1.ZodIssueCode.too_small,
888
- minimum: check.value,
889
- type: "string",
890
- inclusive: true,
891
- exact: false,
892
- message: check.message
893
- });
894
- status.dirty();
895
- }
896
- } else if (check.kind === "max") {
897
- if (input.data.length > check.value) {
898
- ctx = this._getOrReturnCtx(input, ctx);
899
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
900
- code: ZodError_js_1.ZodIssueCode.too_big,
901
- maximum: check.value,
902
- type: "string",
903
- inclusive: true,
904
- exact: false,
905
- message: check.message
906
- });
907
- status.dirty();
908
- }
909
- } else if (check.kind === "length") {
910
- const tooBig = input.data.length > check.value;
911
- const tooSmall = input.data.length < check.value;
912
- if (tooBig || tooSmall) {
913
- ctx = this._getOrReturnCtx(input, ctx);
914
- if (tooBig) (0, parseUtil_js_1.addIssueToContext)(ctx, {
915
- code: ZodError_js_1.ZodIssueCode.too_big,
916
- maximum: check.value,
917
- type: "string",
918
- inclusive: true,
919
- exact: true,
920
- message: check.message
921
- });
922
- else if (tooSmall) (0, parseUtil_js_1.addIssueToContext)(ctx, {
923
- code: ZodError_js_1.ZodIssueCode.too_small,
924
- minimum: check.value,
925
- type: "string",
926
- inclusive: true,
927
- exact: true,
928
- message: check.message
929
- });
930
- status.dirty();
931
- }
932
- } else if (check.kind === "email") {
933
- if (!emailRegex.test(input.data)) {
934
- ctx = this._getOrReturnCtx(input, ctx);
935
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
936
- validation: "email",
937
- code: ZodError_js_1.ZodIssueCode.invalid_string,
938
- message: check.message
939
- });
940
- status.dirty();
941
- }
942
- } else if (check.kind === "emoji") {
943
- if (!emojiRegex) emojiRegex = new RegExp(_emojiRegex, "u");
944
- if (!emojiRegex.test(input.data)) {
945
- ctx = this._getOrReturnCtx(input, ctx);
946
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
947
- validation: "emoji",
948
- code: ZodError_js_1.ZodIssueCode.invalid_string,
949
- message: check.message
950
- });
951
- status.dirty();
952
- }
953
- } else if (check.kind === "uuid") {
954
- if (!uuidRegex.test(input.data)) {
955
- ctx = this._getOrReturnCtx(input, ctx);
956
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
957
- validation: "uuid",
958
- code: ZodError_js_1.ZodIssueCode.invalid_string,
959
- message: check.message
960
- });
961
- status.dirty();
962
- }
963
- } else if (check.kind === "nanoid") {
964
- if (!nanoidRegex.test(input.data)) {
965
- ctx = this._getOrReturnCtx(input, ctx);
966
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
967
- validation: "nanoid",
968
- code: ZodError_js_1.ZodIssueCode.invalid_string,
969
- message: check.message
970
- });
971
- status.dirty();
972
- }
973
- } else if (check.kind === "cuid") {
974
- if (!cuidRegex.test(input.data)) {
975
- ctx = this._getOrReturnCtx(input, ctx);
976
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
977
- validation: "cuid",
978
- code: ZodError_js_1.ZodIssueCode.invalid_string,
979
- message: check.message
980
- });
981
- status.dirty();
982
- }
983
- } else if (check.kind === "cuid2") {
984
- if (!cuid2Regex.test(input.data)) {
985
- ctx = this._getOrReturnCtx(input, ctx);
986
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
987
- validation: "cuid2",
988
- code: ZodError_js_1.ZodIssueCode.invalid_string,
989
- message: check.message
990
- });
991
- status.dirty();
992
- }
993
- } else if (check.kind === "ulid") {
994
- if (!ulidRegex.test(input.data)) {
995
- ctx = this._getOrReturnCtx(input, ctx);
996
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
997
- validation: "ulid",
998
- code: ZodError_js_1.ZodIssueCode.invalid_string,
999
- message: check.message
1000
- });
1001
- status.dirty();
1002
- }
1003
- } else if (check.kind === "url") try {
1004
- new URL(input.data);
1005
- } catch {
1006
- ctx = this._getOrReturnCtx(input, ctx);
1007
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1008
- validation: "url",
1009
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1010
- message: check.message
1011
- });
1012
- status.dirty();
1013
- }
1014
- else if (check.kind === "regex") {
1015
- check.regex.lastIndex = 0;
1016
- if (!check.regex.test(input.data)) {
1017
- ctx = this._getOrReturnCtx(input, ctx);
1018
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1019
- validation: "regex",
1020
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1021
- message: check.message
1022
- });
1023
- status.dirty();
1024
- }
1025
- } else if (check.kind === "trim") input.data = input.data.trim();
1026
- else if (check.kind === "includes") {
1027
- if (!input.data.includes(check.value, check.position)) {
1028
- ctx = this._getOrReturnCtx(input, ctx);
1029
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1030
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1031
- validation: {
1032
- includes: check.value,
1033
- position: check.position
1034
- },
1035
- message: check.message
1036
- });
1037
- status.dirty();
1038
- }
1039
- } else if (check.kind === "toLowerCase") input.data = input.data.toLowerCase();
1040
- else if (check.kind === "toUpperCase") input.data = input.data.toUpperCase();
1041
- else if (check.kind === "startsWith") {
1042
- if (!input.data.startsWith(check.value)) {
1043
- ctx = this._getOrReturnCtx(input, ctx);
1044
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1045
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1046
- validation: { startsWith: check.value },
1047
- message: check.message
1048
- });
1049
- status.dirty();
1050
- }
1051
- } else if (check.kind === "endsWith") {
1052
- if (!input.data.endsWith(check.value)) {
1053
- ctx = this._getOrReturnCtx(input, ctx);
1054
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1055
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1056
- validation: { endsWith: check.value },
1057
- message: check.message
1058
- });
1059
- status.dirty();
1060
- }
1061
- } else if (check.kind === "datetime") {
1062
- if (!datetimeRegex(check).test(input.data)) {
1063
- ctx = this._getOrReturnCtx(input, ctx);
1064
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1065
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1066
- validation: "datetime",
1067
- message: check.message
1068
- });
1069
- status.dirty();
1070
- }
1071
- } else if (check.kind === "date") {
1072
- if (!dateRegex.test(input.data)) {
1073
- ctx = this._getOrReturnCtx(input, ctx);
1074
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1075
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1076
- validation: "date",
1077
- message: check.message
1078
- });
1079
- status.dirty();
1080
- }
1081
- } else if (check.kind === "time") {
1082
- if (!timeRegex(check).test(input.data)) {
1083
- ctx = this._getOrReturnCtx(input, ctx);
1084
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1085
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1086
- validation: "time",
1087
- message: check.message
1088
- });
1089
- status.dirty();
1090
- }
1091
- } else if (check.kind === "duration") {
1092
- if (!durationRegex.test(input.data)) {
1093
- ctx = this._getOrReturnCtx(input, ctx);
1094
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1095
- validation: "duration",
1096
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1097
- message: check.message
1098
- });
1099
- status.dirty();
1100
- }
1101
- } else if (check.kind === "ip") {
1102
- if (!isValidIP(input.data, check.version)) {
1103
- ctx = this._getOrReturnCtx(input, ctx);
1104
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1105
- validation: "ip",
1106
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1107
- message: check.message
1108
- });
1109
- status.dirty();
1110
- }
1111
- } else if (check.kind === "jwt") {
1112
- if (!isValidJWT(input.data, check.alg)) {
1113
- ctx = this._getOrReturnCtx(input, ctx);
1114
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1115
- validation: "jwt",
1116
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1117
- message: check.message
1118
- });
1119
- status.dirty();
1120
- }
1121
- } else if (check.kind === "cidr") {
1122
- if (!isValidCidr(input.data, check.version)) {
1123
- ctx = this._getOrReturnCtx(input, ctx);
1124
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1125
- validation: "cidr",
1126
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1127
- message: check.message
1128
- });
1129
- status.dirty();
1130
- }
1131
- } else if (check.kind === "base64") {
1132
- if (!base64Regex.test(input.data)) {
1133
- ctx = this._getOrReturnCtx(input, ctx);
1134
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1135
- validation: "base64",
1136
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1137
- message: check.message
1138
- });
1139
- status.dirty();
1140
- }
1141
- } else if (check.kind === "base64url") {
1142
- if (!base64urlRegex.test(input.data)) {
1143
- ctx = this._getOrReturnCtx(input, ctx);
1144
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1145
- validation: "base64url",
1146
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1147
- message: check.message
1148
- });
1149
- status.dirty();
1150
- }
1151
- } else util_js_1.util.assertNever(check);
1152
- return {
1153
- status: status.value,
1154
- value: input.data
1155
- };
1156
- }
1157
- _regex(regex, validation, message) {
1158
- return this.refinement((data) => regex.test(data), {
1159
- validation,
1160
- code: ZodError_js_1.ZodIssueCode.invalid_string,
1161
- ...errorUtil_js_1.errorUtil.errToObj(message)
1162
- });
1163
- }
1164
- _addCheck(check) {
1165
- return new ZodString({
1166
- ...this._def,
1167
- checks: [...this._def.checks, check]
1168
- });
1169
- }
1170
- email(message) {
1171
- return this._addCheck({
1172
- kind: "email",
1173
- ...errorUtil_js_1.errorUtil.errToObj(message)
1174
- });
1175
- }
1176
- url(message) {
1177
- return this._addCheck({
1178
- kind: "url",
1179
- ...errorUtil_js_1.errorUtil.errToObj(message)
1180
- });
1181
- }
1182
- emoji(message) {
1183
- return this._addCheck({
1184
- kind: "emoji",
1185
- ...errorUtil_js_1.errorUtil.errToObj(message)
1186
- });
1187
- }
1188
- uuid(message) {
1189
- return this._addCheck({
1190
- kind: "uuid",
1191
- ...errorUtil_js_1.errorUtil.errToObj(message)
1192
- });
1193
- }
1194
- nanoid(message) {
1195
- return this._addCheck({
1196
- kind: "nanoid",
1197
- ...errorUtil_js_1.errorUtil.errToObj(message)
1198
- });
1199
- }
1200
- cuid(message) {
1201
- return this._addCheck({
1202
- kind: "cuid",
1203
- ...errorUtil_js_1.errorUtil.errToObj(message)
1204
- });
1205
- }
1206
- cuid2(message) {
1207
- return this._addCheck({
1208
- kind: "cuid2",
1209
- ...errorUtil_js_1.errorUtil.errToObj(message)
1210
- });
1211
- }
1212
- ulid(message) {
1213
- return this._addCheck({
1214
- kind: "ulid",
1215
- ...errorUtil_js_1.errorUtil.errToObj(message)
1216
- });
1217
- }
1218
- base64(message) {
1219
- return this._addCheck({
1220
- kind: "base64",
1221
- ...errorUtil_js_1.errorUtil.errToObj(message)
1222
- });
1223
- }
1224
- base64url(message) {
1225
- return this._addCheck({
1226
- kind: "base64url",
1227
- ...errorUtil_js_1.errorUtil.errToObj(message)
1228
- });
1229
- }
1230
- jwt(options) {
1231
- return this._addCheck({
1232
- kind: "jwt",
1233
- ...errorUtil_js_1.errorUtil.errToObj(options)
1234
- });
1235
- }
1236
- ip(options) {
1237
- return this._addCheck({
1238
- kind: "ip",
1239
- ...errorUtil_js_1.errorUtil.errToObj(options)
1240
- });
1241
- }
1242
- cidr(options) {
1243
- return this._addCheck({
1244
- kind: "cidr",
1245
- ...errorUtil_js_1.errorUtil.errToObj(options)
1246
- });
1247
- }
1248
- datetime(options) {
1249
- if (typeof options === "string") return this._addCheck({
1250
- kind: "datetime",
1251
- precision: null,
1252
- offset: false,
1253
- local: false,
1254
- message: options
1255
- });
1256
- return this._addCheck({
1257
- kind: "datetime",
1258
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1259
- offset: options?.offset ?? false,
1260
- local: options?.local ?? false,
1261
- ...errorUtil_js_1.errorUtil.errToObj(options?.message)
1262
- });
1263
- }
1264
- date(message) {
1265
- return this._addCheck({
1266
- kind: "date",
1267
- message
1268
- });
1269
- }
1270
- time(options) {
1271
- if (typeof options === "string") return this._addCheck({
1272
- kind: "time",
1273
- precision: null,
1274
- message: options
1275
- });
1276
- return this._addCheck({
1277
- kind: "time",
1278
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1279
- ...errorUtil_js_1.errorUtil.errToObj(options?.message)
1280
- });
1281
- }
1282
- duration(message) {
1283
- return this._addCheck({
1284
- kind: "duration",
1285
- ...errorUtil_js_1.errorUtil.errToObj(message)
1286
- });
1287
- }
1288
- regex(regex, message) {
1289
- return this._addCheck({
1290
- kind: "regex",
1291
- regex,
1292
- ...errorUtil_js_1.errorUtil.errToObj(message)
1293
- });
1294
- }
1295
- includes(value, options) {
1296
- return this._addCheck({
1297
- kind: "includes",
1298
- value,
1299
- position: options?.position,
1300
- ...errorUtil_js_1.errorUtil.errToObj(options?.message)
1301
- });
1302
- }
1303
- startsWith(value, message) {
1304
- return this._addCheck({
1305
- kind: "startsWith",
1306
- value,
1307
- ...errorUtil_js_1.errorUtil.errToObj(message)
1308
- });
1309
- }
1310
- endsWith(value, message) {
1311
- return this._addCheck({
1312
- kind: "endsWith",
1313
- value,
1314
- ...errorUtil_js_1.errorUtil.errToObj(message)
1315
- });
1316
- }
1317
- min(minLength, message) {
1318
- return this._addCheck({
1319
- kind: "min",
1320
- value: minLength,
1321
- ...errorUtil_js_1.errorUtil.errToObj(message)
1322
- });
1323
- }
1324
- max(maxLength, message) {
1325
- return this._addCheck({
1326
- kind: "max",
1327
- value: maxLength,
1328
- ...errorUtil_js_1.errorUtil.errToObj(message)
1329
- });
1330
- }
1331
- length(len, message) {
1332
- return this._addCheck({
1333
- kind: "length",
1334
- value: len,
1335
- ...errorUtil_js_1.errorUtil.errToObj(message)
1336
- });
1337
- }
1338
- /**
1339
- * Equivalent to `.min(1)`
1340
- */
1341
- nonempty(message) {
1342
- return this.min(1, errorUtil_js_1.errorUtil.errToObj(message));
1343
- }
1344
- trim() {
1345
- return new ZodString({
1346
- ...this._def,
1347
- checks: [...this._def.checks, { kind: "trim" }]
1348
- });
1349
- }
1350
- toLowerCase() {
1351
- return new ZodString({
1352
- ...this._def,
1353
- checks: [...this._def.checks, { kind: "toLowerCase" }]
1354
- });
1355
- }
1356
- toUpperCase() {
1357
- return new ZodString({
1358
- ...this._def,
1359
- checks: [...this._def.checks, { kind: "toUpperCase" }]
1360
- });
1361
- }
1362
- get isDatetime() {
1363
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
1364
- }
1365
- get isDate() {
1366
- return !!this._def.checks.find((ch) => ch.kind === "date");
1367
- }
1368
- get isTime() {
1369
- return !!this._def.checks.find((ch) => ch.kind === "time");
1370
- }
1371
- get isDuration() {
1372
- return !!this._def.checks.find((ch) => ch.kind === "duration");
1373
- }
1374
- get isEmail() {
1375
- return !!this._def.checks.find((ch) => ch.kind === "email");
1376
- }
1377
- get isURL() {
1378
- return !!this._def.checks.find((ch) => ch.kind === "url");
1379
- }
1380
- get isEmoji() {
1381
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1382
- }
1383
- get isUUID() {
1384
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1385
- }
1386
- get isNANOID() {
1387
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1388
- }
1389
- get isCUID() {
1390
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1391
- }
1392
- get isCUID2() {
1393
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1394
- }
1395
- get isULID() {
1396
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1397
- }
1398
- get isIP() {
1399
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1400
- }
1401
- get isCIDR() {
1402
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1403
- }
1404
- get isBase64() {
1405
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1406
- }
1407
- get isBase64url() {
1408
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1409
- }
1410
- get minLength() {
1411
- let min = null;
1412
- for (const ch of this._def.checks) if (ch.kind === "min") {
1413
- if (min === null || ch.value > min) min = ch.value;
1414
- }
1415
- return min;
1416
- }
1417
- get maxLength() {
1418
- let max = null;
1419
- for (const ch of this._def.checks) if (ch.kind === "max") {
1420
- if (max === null || ch.value < max) max = ch.value;
1421
- }
1422
- return max;
1423
- }
1424
- };
1425
- exports.ZodString = ZodString;
1426
- ZodString.create = (params) => {
1427
- return new ZodString({
1428
- checks: [],
1429
- typeName: ZodFirstPartyTypeKind.ZodString,
1430
- coerce: params?.coerce ?? false,
1431
- ...processCreateParams(params)
1432
- });
1433
- };
1434
- function floatSafeRemainder(val, step) {
1435
- const valDecCount = (val.toString().split(".")[1] || "").length;
1436
- const stepDecCount = (step.toString().split(".")[1] || "").length;
1437
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1438
- return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
1439
- }
1440
- var ZodNumber = class ZodNumber extends ZodType {
1441
- constructor() {
1442
- super(...arguments);
1443
- this.min = this.gte;
1444
- this.max = this.lte;
1445
- this.step = this.multipleOf;
1446
- }
1447
- _parse(input) {
1448
- if (this._def.coerce) input.data = Number(input.data);
1449
- if (this._getType(input) !== util_js_1.ZodParsedType.number) {
1450
- const ctx = this._getOrReturnCtx(input);
1451
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1452
- code: ZodError_js_1.ZodIssueCode.invalid_type,
1453
- expected: util_js_1.ZodParsedType.number,
1454
- received: ctx.parsedType
1455
- });
1456
- return parseUtil_js_1.INVALID;
1457
- }
1458
- let ctx = void 0;
1459
- const status = new parseUtil_js_1.ParseStatus();
1460
- for (const check of this._def.checks) if (check.kind === "int") {
1461
- if (!util_js_1.util.isInteger(input.data)) {
1462
- ctx = this._getOrReturnCtx(input, ctx);
1463
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1464
- code: ZodError_js_1.ZodIssueCode.invalid_type,
1465
- expected: "integer",
1466
- received: "float",
1467
- message: check.message
1468
- });
1469
- status.dirty();
1470
- }
1471
- } else if (check.kind === "min") {
1472
- if (check.inclusive ? input.data < check.value : input.data <= check.value) {
1473
- ctx = this._getOrReturnCtx(input, ctx);
1474
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1475
- code: ZodError_js_1.ZodIssueCode.too_small,
1476
- minimum: check.value,
1477
- type: "number",
1478
- inclusive: check.inclusive,
1479
- exact: false,
1480
- message: check.message
1481
- });
1482
- status.dirty();
1483
- }
1484
- } else if (check.kind === "max") {
1485
- if (check.inclusive ? input.data > check.value : input.data >= check.value) {
1486
- ctx = this._getOrReturnCtx(input, ctx);
1487
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1488
- code: ZodError_js_1.ZodIssueCode.too_big,
1489
- maximum: check.value,
1490
- type: "number",
1491
- inclusive: check.inclusive,
1492
- exact: false,
1493
- message: check.message
1494
- });
1495
- status.dirty();
1496
- }
1497
- } else if (check.kind === "multipleOf") {
1498
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1499
- ctx = this._getOrReturnCtx(input, ctx);
1500
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1501
- code: ZodError_js_1.ZodIssueCode.not_multiple_of,
1502
- multipleOf: check.value,
1503
- message: check.message
1504
- });
1505
- status.dirty();
1506
- }
1507
- } else if (check.kind === "finite") {
1508
- if (!Number.isFinite(input.data)) {
1509
- ctx = this._getOrReturnCtx(input, ctx);
1510
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1511
- code: ZodError_js_1.ZodIssueCode.not_finite,
1512
- message: check.message
1513
- });
1514
- status.dirty();
1515
- }
1516
- } else util_js_1.util.assertNever(check);
1517
- return {
1518
- status: status.value,
1519
- value: input.data
1520
- };
1521
- }
1522
- gte(value, message) {
1523
- return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message));
1524
- }
1525
- gt(value, message) {
1526
- return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message));
1527
- }
1528
- lte(value, message) {
1529
- return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message));
1530
- }
1531
- lt(value, message) {
1532
- return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message));
1533
- }
1534
- setLimit(kind, value, inclusive, message) {
1535
- return new ZodNumber({
1536
- ...this._def,
1537
- checks: [...this._def.checks, {
1538
- kind,
1539
- value,
1540
- inclusive,
1541
- message: errorUtil_js_1.errorUtil.toString(message)
1542
- }]
1543
- });
1544
- }
1545
- _addCheck(check) {
1546
- return new ZodNumber({
1547
- ...this._def,
1548
- checks: [...this._def.checks, check]
1549
- });
1550
- }
1551
- int(message) {
1552
- return this._addCheck({
1553
- kind: "int",
1554
- message: errorUtil_js_1.errorUtil.toString(message)
1555
- });
1556
- }
1557
- positive(message) {
1558
- return this._addCheck({
1559
- kind: "min",
1560
- value: 0,
1561
- inclusive: false,
1562
- message: errorUtil_js_1.errorUtil.toString(message)
1563
- });
1564
- }
1565
- negative(message) {
1566
- return this._addCheck({
1567
- kind: "max",
1568
- value: 0,
1569
- inclusive: false,
1570
- message: errorUtil_js_1.errorUtil.toString(message)
1571
- });
1572
- }
1573
- nonpositive(message) {
1574
- return this._addCheck({
1575
- kind: "max",
1576
- value: 0,
1577
- inclusive: true,
1578
- message: errorUtil_js_1.errorUtil.toString(message)
1579
- });
1580
- }
1581
- nonnegative(message) {
1582
- return this._addCheck({
1583
- kind: "min",
1584
- value: 0,
1585
- inclusive: true,
1586
- message: errorUtil_js_1.errorUtil.toString(message)
1587
- });
1588
- }
1589
- multipleOf(value, message) {
1590
- return this._addCheck({
1591
- kind: "multipleOf",
1592
- value,
1593
- message: errorUtil_js_1.errorUtil.toString(message)
1594
- });
1595
- }
1596
- finite(message) {
1597
- return this._addCheck({
1598
- kind: "finite",
1599
- message: errorUtil_js_1.errorUtil.toString(message)
1600
- });
1601
- }
1602
- safe(message) {
1603
- return this._addCheck({
1604
- kind: "min",
1605
- inclusive: true,
1606
- value: Number.MIN_SAFE_INTEGER,
1607
- message: errorUtil_js_1.errorUtil.toString(message)
1608
- })._addCheck({
1609
- kind: "max",
1610
- inclusive: true,
1611
- value: Number.MAX_SAFE_INTEGER,
1612
- message: errorUtil_js_1.errorUtil.toString(message)
1613
- });
1614
- }
1615
- get minValue() {
1616
- let min = null;
1617
- for (const ch of this._def.checks) if (ch.kind === "min") {
1618
- if (min === null || ch.value > min) min = ch.value;
1619
- }
1620
- return min;
1621
- }
1622
- get maxValue() {
1623
- let max = null;
1624
- for (const ch of this._def.checks) if (ch.kind === "max") {
1625
- if (max === null || ch.value < max) max = ch.value;
1626
- }
1627
- return max;
1628
- }
1629
- get isInt() {
1630
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util_js_1.util.isInteger(ch.value));
1631
- }
1632
- get isFinite() {
1633
- let max = null;
1634
- let min = null;
1635
- for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
1636
- else if (ch.kind === "min") {
1637
- if (min === null || ch.value > min) min = ch.value;
1638
- } else if (ch.kind === "max") {
1639
- if (max === null || ch.value < max) max = ch.value;
1640
- }
1641
- return Number.isFinite(min) && Number.isFinite(max);
1642
- }
1643
- };
1644
- exports.ZodNumber = ZodNumber;
1645
- ZodNumber.create = (params) => {
1646
- return new ZodNumber({
1647
- checks: [],
1648
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1649
- coerce: params?.coerce || false,
1650
- ...processCreateParams(params)
1651
- });
1652
- };
1653
- var ZodBigInt = class ZodBigInt extends ZodType {
1654
- constructor() {
1655
- super(...arguments);
1656
- this.min = this.gte;
1657
- this.max = this.lte;
1658
- }
1659
- _parse(input) {
1660
- if (this._def.coerce) try {
1661
- input.data = BigInt(input.data);
1662
- } catch {
1663
- return this._getInvalidInput(input);
1664
- }
1665
- if (this._getType(input) !== util_js_1.ZodParsedType.bigint) return this._getInvalidInput(input);
1666
- let ctx = void 0;
1667
- const status = new parseUtil_js_1.ParseStatus();
1668
- for (const check of this._def.checks) if (check.kind === "min") {
1669
- if (check.inclusive ? input.data < check.value : input.data <= check.value) {
1670
- ctx = this._getOrReturnCtx(input, ctx);
1671
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1672
- code: ZodError_js_1.ZodIssueCode.too_small,
1673
- type: "bigint",
1674
- minimum: check.value,
1675
- inclusive: check.inclusive,
1676
- message: check.message
1677
- });
1678
- status.dirty();
1679
- }
1680
- } else if (check.kind === "max") {
1681
- if (check.inclusive ? input.data > check.value : input.data >= check.value) {
1682
- ctx = this._getOrReturnCtx(input, ctx);
1683
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1684
- code: ZodError_js_1.ZodIssueCode.too_big,
1685
- type: "bigint",
1686
- maximum: check.value,
1687
- inclusive: check.inclusive,
1688
- message: check.message
1689
- });
1690
- status.dirty();
1691
- }
1692
- } else if (check.kind === "multipleOf") {
1693
- if (input.data % check.value !== BigInt(0)) {
1694
- ctx = this._getOrReturnCtx(input, ctx);
1695
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1696
- code: ZodError_js_1.ZodIssueCode.not_multiple_of,
1697
- multipleOf: check.value,
1698
- message: check.message
1699
- });
1700
- status.dirty();
1701
- }
1702
- } else util_js_1.util.assertNever(check);
1703
- return {
1704
- status: status.value,
1705
- value: input.data
1706
- };
1707
- }
1708
- _getInvalidInput(input) {
1709
- const ctx = this._getOrReturnCtx(input);
1710
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1711
- code: ZodError_js_1.ZodIssueCode.invalid_type,
1712
- expected: util_js_1.ZodParsedType.bigint,
1713
- received: ctx.parsedType
1714
- });
1715
- return parseUtil_js_1.INVALID;
1716
- }
1717
- gte(value, message) {
1718
- return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message));
1719
- }
1720
- gt(value, message) {
1721
- return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message));
1722
- }
1723
- lte(value, message) {
1724
- return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message));
1725
- }
1726
- lt(value, message) {
1727
- return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message));
1728
- }
1729
- setLimit(kind, value, inclusive, message) {
1730
- return new ZodBigInt({
1731
- ...this._def,
1732
- checks: [...this._def.checks, {
1733
- kind,
1734
- value,
1735
- inclusive,
1736
- message: errorUtil_js_1.errorUtil.toString(message)
1737
- }]
1738
- });
1739
- }
1740
- _addCheck(check) {
1741
- return new ZodBigInt({
1742
- ...this._def,
1743
- checks: [...this._def.checks, check]
1744
- });
1745
- }
1746
- positive(message) {
1747
- return this._addCheck({
1748
- kind: "min",
1749
- value: BigInt(0),
1750
- inclusive: false,
1751
- message: errorUtil_js_1.errorUtil.toString(message)
1752
- });
1753
- }
1754
- negative(message) {
1755
- return this._addCheck({
1756
- kind: "max",
1757
- value: BigInt(0),
1758
- inclusive: false,
1759
- message: errorUtil_js_1.errorUtil.toString(message)
1760
- });
1761
- }
1762
- nonpositive(message) {
1763
- return this._addCheck({
1764
- kind: "max",
1765
- value: BigInt(0),
1766
- inclusive: true,
1767
- message: errorUtil_js_1.errorUtil.toString(message)
1768
- });
1769
- }
1770
- nonnegative(message) {
1771
- return this._addCheck({
1772
- kind: "min",
1773
- value: BigInt(0),
1774
- inclusive: true,
1775
- message: errorUtil_js_1.errorUtil.toString(message)
1776
- });
1777
- }
1778
- multipleOf(value, message) {
1779
- return this._addCheck({
1780
- kind: "multipleOf",
1781
- value,
1782
- message: errorUtil_js_1.errorUtil.toString(message)
1783
- });
1784
- }
1785
- get minValue() {
1786
- let min = null;
1787
- for (const ch of this._def.checks) if (ch.kind === "min") {
1788
- if (min === null || ch.value > min) min = ch.value;
1789
- }
1790
- return min;
1791
- }
1792
- get maxValue() {
1793
- let max = null;
1794
- for (const ch of this._def.checks) if (ch.kind === "max") {
1795
- if (max === null || ch.value < max) max = ch.value;
1796
- }
1797
- return max;
1798
- }
1799
- };
1800
- exports.ZodBigInt = ZodBigInt;
1801
- ZodBigInt.create = (params) => {
1802
- return new ZodBigInt({
1803
- checks: [],
1804
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
1805
- coerce: params?.coerce ?? false,
1806
- ...processCreateParams(params)
1807
- });
1808
- };
1809
- var ZodBoolean = class extends ZodType {
1810
- _parse(input) {
1811
- if (this._def.coerce) input.data = Boolean(input.data);
1812
- if (this._getType(input) !== util_js_1.ZodParsedType.boolean) {
1813
- const ctx = this._getOrReturnCtx(input);
1814
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1815
- code: ZodError_js_1.ZodIssueCode.invalid_type,
1816
- expected: util_js_1.ZodParsedType.boolean,
1817
- received: ctx.parsedType
1818
- });
1819
- return parseUtil_js_1.INVALID;
1820
- }
1821
- return (0, parseUtil_js_1.OK)(input.data);
1822
- }
1823
- };
1824
- exports.ZodBoolean = ZodBoolean;
1825
- ZodBoolean.create = (params) => {
1826
- return new ZodBoolean({
1827
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
1828
- coerce: params?.coerce || false,
1829
- ...processCreateParams(params)
1830
- });
1831
- };
1832
- var ZodDate = class ZodDate extends ZodType {
1833
- _parse(input) {
1834
- if (this._def.coerce) input.data = new Date(input.data);
1835
- if (this._getType(input) !== util_js_1.ZodParsedType.date) {
1836
- const ctx = this._getOrReturnCtx(input);
1837
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1838
- code: ZodError_js_1.ZodIssueCode.invalid_type,
1839
- expected: util_js_1.ZodParsedType.date,
1840
- received: ctx.parsedType
1841
- });
1842
- return parseUtil_js_1.INVALID;
1843
- }
1844
- if (Number.isNaN(input.data.getTime())) {
1845
- const ctx = this._getOrReturnCtx(input);
1846
- (0, parseUtil_js_1.addIssueToContext)(ctx, { code: ZodError_js_1.ZodIssueCode.invalid_date });
1847
- return parseUtil_js_1.INVALID;
1848
- }
1849
- const status = new parseUtil_js_1.ParseStatus();
1850
- let ctx = void 0;
1851
- for (const check of this._def.checks) if (check.kind === "min") {
1852
- if (input.data.getTime() < check.value) {
1853
- ctx = this._getOrReturnCtx(input, ctx);
1854
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1855
- code: ZodError_js_1.ZodIssueCode.too_small,
1856
- message: check.message,
1857
- inclusive: true,
1858
- exact: false,
1859
- minimum: check.value,
1860
- type: "date"
1861
- });
1862
- status.dirty();
1863
- }
1864
- } else if (check.kind === "max") {
1865
- if (input.data.getTime() > check.value) {
1866
- ctx = this._getOrReturnCtx(input, ctx);
1867
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1868
- code: ZodError_js_1.ZodIssueCode.too_big,
1869
- message: check.message,
1870
- inclusive: true,
1871
- exact: false,
1872
- maximum: check.value,
1873
- type: "date"
1874
- });
1875
- status.dirty();
1876
- }
1877
- } else util_js_1.util.assertNever(check);
1878
- return {
1879
- status: status.value,
1880
- value: new Date(input.data.getTime())
1881
- };
1882
- }
1883
- _addCheck(check) {
1884
- return new ZodDate({
1885
- ...this._def,
1886
- checks: [...this._def.checks, check]
1887
- });
1888
- }
1889
- min(minDate, message) {
1890
- return this._addCheck({
1891
- kind: "min",
1892
- value: minDate.getTime(),
1893
- message: errorUtil_js_1.errorUtil.toString(message)
1894
- });
1895
- }
1896
- max(maxDate, message) {
1897
- return this._addCheck({
1898
- kind: "max",
1899
- value: maxDate.getTime(),
1900
- message: errorUtil_js_1.errorUtil.toString(message)
1901
- });
1902
- }
1903
- get minDate() {
1904
- let min = null;
1905
- for (const ch of this._def.checks) if (ch.kind === "min") {
1906
- if (min === null || ch.value > min) min = ch.value;
1907
- }
1908
- return min != null ? new Date(min) : null;
1909
- }
1910
- get maxDate() {
1911
- let max = null;
1912
- for (const ch of this._def.checks) if (ch.kind === "max") {
1913
- if (max === null || ch.value < max) max = ch.value;
1914
- }
1915
- return max != null ? new Date(max) : null;
1916
- }
1917
- };
1918
- exports.ZodDate = ZodDate;
1919
- ZodDate.create = (params) => {
1920
- return new ZodDate({
1921
- checks: [],
1922
- coerce: params?.coerce || false,
1923
- typeName: ZodFirstPartyTypeKind.ZodDate,
1924
- ...processCreateParams(params)
1925
- });
1926
- };
1927
- var ZodSymbol = class extends ZodType {
1928
- _parse(input) {
1929
- if (this._getType(input) !== util_js_1.ZodParsedType.symbol) {
1930
- const ctx = this._getOrReturnCtx(input);
1931
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1932
- code: ZodError_js_1.ZodIssueCode.invalid_type,
1933
- expected: util_js_1.ZodParsedType.symbol,
1934
- received: ctx.parsedType
1935
- });
1936
- return parseUtil_js_1.INVALID;
1937
- }
1938
- return (0, parseUtil_js_1.OK)(input.data);
1939
- }
1940
- };
1941
- exports.ZodSymbol = ZodSymbol;
1942
- ZodSymbol.create = (params) => {
1943
- return new ZodSymbol({
1944
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
1945
- ...processCreateParams(params)
1946
- });
1947
- };
1948
- var ZodUndefined = class extends ZodType {
1949
- _parse(input) {
1950
- if (this._getType(input) !== util_js_1.ZodParsedType.undefined) {
1951
- const ctx = this._getOrReturnCtx(input);
1952
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1953
- code: ZodError_js_1.ZodIssueCode.invalid_type,
1954
- expected: util_js_1.ZodParsedType.undefined,
1955
- received: ctx.parsedType
1956
- });
1957
- return parseUtil_js_1.INVALID;
1958
- }
1959
- return (0, parseUtil_js_1.OK)(input.data);
1960
- }
1961
- };
1962
- exports.ZodUndefined = ZodUndefined;
1963
- ZodUndefined.create = (params) => {
1964
- return new ZodUndefined({
1965
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
1966
- ...processCreateParams(params)
1967
- });
1968
- };
1969
- var ZodNull = class extends ZodType {
1970
- _parse(input) {
1971
- if (this._getType(input) !== util_js_1.ZodParsedType.null) {
1972
- const ctx = this._getOrReturnCtx(input);
1973
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
1974
- code: ZodError_js_1.ZodIssueCode.invalid_type,
1975
- expected: util_js_1.ZodParsedType.null,
1976
- received: ctx.parsedType
1977
- });
1978
- return parseUtil_js_1.INVALID;
1979
- }
1980
- return (0, parseUtil_js_1.OK)(input.data);
1981
- }
1982
- };
1983
- exports.ZodNull = ZodNull;
1984
- ZodNull.create = (params) => {
1985
- return new ZodNull({
1986
- typeName: ZodFirstPartyTypeKind.ZodNull,
1987
- ...processCreateParams(params)
1988
- });
1989
- };
1990
- var ZodAny = class extends ZodType {
1991
- constructor() {
1992
- super(...arguments);
1993
- this._any = true;
1994
- }
1995
- _parse(input) {
1996
- return (0, parseUtil_js_1.OK)(input.data);
1997
- }
1998
- };
1999
- exports.ZodAny = ZodAny;
2000
- ZodAny.create = (params) => {
2001
- return new ZodAny({
2002
- typeName: ZodFirstPartyTypeKind.ZodAny,
2003
- ...processCreateParams(params)
2004
- });
2005
- };
2006
- var ZodUnknown = class extends ZodType {
2007
- constructor() {
2008
- super(...arguments);
2009
- this._unknown = true;
2010
- }
2011
- _parse(input) {
2012
- return (0, parseUtil_js_1.OK)(input.data);
2013
- }
2014
- };
2015
- exports.ZodUnknown = ZodUnknown;
2016
- ZodUnknown.create = (params) => {
2017
- return new ZodUnknown({
2018
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2019
- ...processCreateParams(params)
2020
- });
2021
- };
2022
- var ZodNever = class extends ZodType {
2023
- _parse(input) {
2024
- const ctx = this._getOrReturnCtx(input);
2025
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2026
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2027
- expected: util_js_1.ZodParsedType.never,
2028
- received: ctx.parsedType
2029
- });
2030
- return parseUtil_js_1.INVALID;
2031
- }
2032
- };
2033
- exports.ZodNever = ZodNever;
2034
- ZodNever.create = (params) => {
2035
- return new ZodNever({
2036
- typeName: ZodFirstPartyTypeKind.ZodNever,
2037
- ...processCreateParams(params)
2038
- });
2039
- };
2040
- var ZodVoid = class extends ZodType {
2041
- _parse(input) {
2042
- if (this._getType(input) !== util_js_1.ZodParsedType.undefined) {
2043
- const ctx = this._getOrReturnCtx(input);
2044
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2045
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2046
- expected: util_js_1.ZodParsedType.void,
2047
- received: ctx.parsedType
2048
- });
2049
- return parseUtil_js_1.INVALID;
2050
- }
2051
- return (0, parseUtil_js_1.OK)(input.data);
2052
- }
2053
- };
2054
- exports.ZodVoid = ZodVoid;
2055
- ZodVoid.create = (params) => {
2056
- return new ZodVoid({
2057
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2058
- ...processCreateParams(params)
2059
- });
2060
- };
2061
- var ZodArray = class ZodArray extends ZodType {
2062
- _parse(input) {
2063
- const { ctx, status } = this._processInputParams(input);
2064
- const def = this._def;
2065
- if (ctx.parsedType !== util_js_1.ZodParsedType.array) {
2066
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2067
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2068
- expected: util_js_1.ZodParsedType.array,
2069
- received: ctx.parsedType
2070
- });
2071
- return parseUtil_js_1.INVALID;
2072
- }
2073
- if (def.exactLength !== null) {
2074
- const tooBig = ctx.data.length > def.exactLength.value;
2075
- const tooSmall = ctx.data.length < def.exactLength.value;
2076
- if (tooBig || tooSmall) {
2077
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2078
- code: tooBig ? ZodError_js_1.ZodIssueCode.too_big : ZodError_js_1.ZodIssueCode.too_small,
2079
- minimum: tooSmall ? def.exactLength.value : void 0,
2080
- maximum: tooBig ? def.exactLength.value : void 0,
2081
- type: "array",
2082
- inclusive: true,
2083
- exact: true,
2084
- message: def.exactLength.message
2085
- });
2086
- status.dirty();
2087
- }
2088
- }
2089
- if (def.minLength !== null) {
2090
- if (ctx.data.length < def.minLength.value) {
2091
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2092
- code: ZodError_js_1.ZodIssueCode.too_small,
2093
- minimum: def.minLength.value,
2094
- type: "array",
2095
- inclusive: true,
2096
- exact: false,
2097
- message: def.minLength.message
2098
- });
2099
- status.dirty();
2100
- }
2101
- }
2102
- if (def.maxLength !== null) {
2103
- if (ctx.data.length > def.maxLength.value) {
2104
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2105
- code: ZodError_js_1.ZodIssueCode.too_big,
2106
- maximum: def.maxLength.value,
2107
- type: "array",
2108
- inclusive: true,
2109
- exact: false,
2110
- message: def.maxLength.message
2111
- });
2112
- status.dirty();
2113
- }
2114
- }
2115
- if (ctx.common.async) return Promise.all([...ctx.data].map((item, i) => {
2116
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2117
- })).then((result) => {
2118
- return parseUtil_js_1.ParseStatus.mergeArray(status, result);
2119
- });
2120
- const result = [...ctx.data].map((item, i) => {
2121
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2122
- });
2123
- return parseUtil_js_1.ParseStatus.mergeArray(status, result);
2124
- }
2125
- get element() {
2126
- return this._def.type;
2127
- }
2128
- min(minLength, message) {
2129
- return new ZodArray({
2130
- ...this._def,
2131
- minLength: {
2132
- value: minLength,
2133
- message: errorUtil_js_1.errorUtil.toString(message)
2134
- }
2135
- });
2136
- }
2137
- max(maxLength, message) {
2138
- return new ZodArray({
2139
- ...this._def,
2140
- maxLength: {
2141
- value: maxLength,
2142
- message: errorUtil_js_1.errorUtil.toString(message)
2143
- }
2144
- });
2145
- }
2146
- length(len, message) {
2147
- return new ZodArray({
2148
- ...this._def,
2149
- exactLength: {
2150
- value: len,
2151
- message: errorUtil_js_1.errorUtil.toString(message)
2152
- }
2153
- });
2154
- }
2155
- nonempty(message) {
2156
- return this.min(1, message);
2157
- }
2158
- };
2159
- exports.ZodArray = ZodArray;
2160
- ZodArray.create = (schema, params) => {
2161
- return new ZodArray({
2162
- type: schema,
2163
- minLength: null,
2164
- maxLength: null,
2165
- exactLength: null,
2166
- typeName: ZodFirstPartyTypeKind.ZodArray,
2167
- ...processCreateParams(params)
2168
- });
2169
- };
2170
- function deepPartialify(schema) {
2171
- if (schema instanceof ZodObject) {
2172
- const newShape = {};
2173
- for (const key in schema.shape) {
2174
- const fieldSchema = schema.shape[key];
2175
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2176
- }
2177
- return new ZodObject({
2178
- ...schema._def,
2179
- shape: () => newShape
2180
- });
2181
- } else if (schema instanceof ZodArray) return new ZodArray({
2182
- ...schema._def,
2183
- type: deepPartialify(schema.element)
2184
- });
2185
- else if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap()));
2186
- else if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap()));
2187
- else if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2188
- else return schema;
2189
- }
2190
- var ZodObject = class ZodObject extends ZodType {
2191
- constructor() {
2192
- super(...arguments);
2193
- this._cached = null;
2194
- /**
2195
- * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
2196
- * If you want to pass through unknown properties, use `.passthrough()` instead.
2197
- */
2198
- this.nonstrict = this.passthrough;
2199
- /**
2200
- * @deprecated Use `.extend` instead
2201
- * */
2202
- this.augment = this.extend;
2203
- }
2204
- _getCached() {
2205
- if (this._cached !== null) return this._cached;
2206
- const shape = this._def.shape();
2207
- this._cached = {
2208
- shape,
2209
- keys: util_js_1.util.objectKeys(shape)
2210
- };
2211
- return this._cached;
2212
- }
2213
- _parse(input) {
2214
- if (this._getType(input) !== util_js_1.ZodParsedType.object) {
2215
- const ctx = this._getOrReturnCtx(input);
2216
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2217
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2218
- expected: util_js_1.ZodParsedType.object,
2219
- received: ctx.parsedType
2220
- });
2221
- return parseUtil_js_1.INVALID;
2222
- }
2223
- const { status, ctx } = this._processInputParams(input);
2224
- const { shape, keys: shapeKeys } = this._getCached();
2225
- const extraKeys = [];
2226
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2227
- for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key);
2228
- }
2229
- const pairs = [];
2230
- for (const key of shapeKeys) {
2231
- const keyValidator = shape[key];
2232
- const value = ctx.data[key];
2233
- pairs.push({
2234
- key: {
2235
- status: "valid",
2236
- value: key
2237
- },
2238
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2239
- alwaysSet: key in ctx.data
2240
- });
2241
- }
2242
- if (this._def.catchall instanceof ZodNever) {
2243
- const unknownKeys = this._def.unknownKeys;
2244
- if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({
2245
- key: {
2246
- status: "valid",
2247
- value: key
2248
- },
2249
- value: {
2250
- status: "valid",
2251
- value: ctx.data[key]
2252
- }
2253
- });
2254
- else if (unknownKeys === "strict") {
2255
- if (extraKeys.length > 0) {
2256
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2257
- code: ZodError_js_1.ZodIssueCode.unrecognized_keys,
2258
- keys: extraKeys
2259
- });
2260
- status.dirty();
2261
- }
2262
- } else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2263
- } else {
2264
- const catchall = this._def.catchall;
2265
- for (const key of extraKeys) {
2266
- const value = ctx.data[key];
2267
- pairs.push({
2268
- key: {
2269
- status: "valid",
2270
- value: key
2271
- },
2272
- value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2273
- alwaysSet: key in ctx.data
2274
- });
2275
- }
2276
- }
2277
- if (ctx.common.async) return Promise.resolve().then(async () => {
2278
- const syncPairs = [];
2279
- for (const pair of pairs) {
2280
- const key = await pair.key;
2281
- const value = await pair.value;
2282
- syncPairs.push({
2283
- key,
2284
- value,
2285
- alwaysSet: pair.alwaysSet
2286
- });
2287
- }
2288
- return syncPairs;
2289
- }).then((syncPairs) => {
2290
- return parseUtil_js_1.ParseStatus.mergeObjectSync(status, syncPairs);
2291
- });
2292
- else return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs);
2293
- }
2294
- get shape() {
2295
- return this._def.shape();
2296
- }
2297
- strict(message) {
2298
- errorUtil_js_1.errorUtil.errToObj;
2299
- return new ZodObject({
2300
- ...this._def,
2301
- unknownKeys: "strict",
2302
- ...message !== void 0 ? { errorMap: (issue, ctx) => {
2303
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2304
- if (issue.code === "unrecognized_keys") return { message: errorUtil_js_1.errorUtil.errToObj(message).message ?? defaultError };
2305
- return { message: defaultError };
2306
- } } : {}
2307
- });
2308
- }
2309
- strip() {
2310
- return new ZodObject({
2311
- ...this._def,
2312
- unknownKeys: "strip"
2313
- });
2314
- }
2315
- passthrough() {
2316
- return new ZodObject({
2317
- ...this._def,
2318
- unknownKeys: "passthrough"
2319
- });
2320
- }
2321
- extend(augmentation) {
2322
- return new ZodObject({
2323
- ...this._def,
2324
- shape: () => ({
2325
- ...this._def.shape(),
2326
- ...augmentation
2327
- })
2328
- });
2329
- }
2330
- /**
2331
- * Prior to zod@1.0.12 there was a bug in the
2332
- * inferred type of merged objects. Please
2333
- * upgrade if you are experiencing issues.
2334
- */
2335
- merge(merging) {
2336
- return new ZodObject({
2337
- unknownKeys: merging._def.unknownKeys,
2338
- catchall: merging._def.catchall,
2339
- shape: () => ({
2340
- ...this._def.shape(),
2341
- ...merging._def.shape()
2342
- }),
2343
- typeName: ZodFirstPartyTypeKind.ZodObject
2344
- });
2345
- }
2346
- setKey(key, schema) {
2347
- return this.augment({ [key]: schema });
2348
- }
2349
- catchall(index) {
2350
- return new ZodObject({
2351
- ...this._def,
2352
- catchall: index
2353
- });
2354
- }
2355
- pick(mask) {
2356
- const shape = {};
2357
- for (const key of util_js_1.util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
2358
- return new ZodObject({
2359
- ...this._def,
2360
- shape: () => shape
2361
- });
2362
- }
2363
- omit(mask) {
2364
- const shape = {};
2365
- for (const key of util_js_1.util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key];
2366
- return new ZodObject({
2367
- ...this._def,
2368
- shape: () => shape
2369
- });
2370
- }
2371
- /**
2372
- * @deprecated
2373
- */
2374
- deepPartial() {
2375
- return deepPartialify(this);
2376
- }
2377
- partial(mask) {
2378
- const newShape = {};
2379
- for (const key of util_js_1.util.objectKeys(this.shape)) {
2380
- const fieldSchema = this.shape[key];
2381
- if (mask && !mask[key]) newShape[key] = fieldSchema;
2382
- else newShape[key] = fieldSchema.optional();
2383
- }
2384
- return new ZodObject({
2385
- ...this._def,
2386
- shape: () => newShape
2387
- });
2388
- }
2389
- required(mask) {
2390
- const newShape = {};
2391
- for (const key of util_js_1.util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key];
2392
- else {
2393
- let newField = this.shape[key];
2394
- while (newField instanceof ZodOptional) newField = newField._def.innerType;
2395
- newShape[key] = newField;
2396
- }
2397
- return new ZodObject({
2398
- ...this._def,
2399
- shape: () => newShape
2400
- });
2401
- }
2402
- keyof() {
2403
- return createZodEnum(util_js_1.util.objectKeys(this.shape));
2404
- }
2405
- };
2406
- exports.ZodObject = ZodObject;
2407
- ZodObject.create = (shape, params) => {
2408
- return new ZodObject({
2409
- shape: () => shape,
2410
- unknownKeys: "strip",
2411
- catchall: ZodNever.create(),
2412
- typeName: ZodFirstPartyTypeKind.ZodObject,
2413
- ...processCreateParams(params)
2414
- });
2415
- };
2416
- ZodObject.strictCreate = (shape, params) => {
2417
- return new ZodObject({
2418
- shape: () => shape,
2419
- unknownKeys: "strict",
2420
- catchall: ZodNever.create(),
2421
- typeName: ZodFirstPartyTypeKind.ZodObject,
2422
- ...processCreateParams(params)
2423
- });
2424
- };
2425
- ZodObject.lazycreate = (shape, params) => {
2426
- return new ZodObject({
2427
- shape,
2428
- unknownKeys: "strip",
2429
- catchall: ZodNever.create(),
2430
- typeName: ZodFirstPartyTypeKind.ZodObject,
2431
- ...processCreateParams(params)
2432
- });
2433
- };
2434
- var ZodUnion = class extends ZodType {
2435
- _parse(input) {
2436
- const { ctx } = this._processInputParams(input);
2437
- const options = this._def.options;
2438
- function handleResults(results) {
2439
- for (const result of results) if (result.result.status === "valid") return result.result;
2440
- for (const result of results) if (result.result.status === "dirty") {
2441
- ctx.common.issues.push(...result.ctx.common.issues);
2442
- return result.result;
2443
- }
2444
- const unionErrors = results.map((result) => new ZodError_js_1.ZodError(result.ctx.common.issues));
2445
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2446
- code: ZodError_js_1.ZodIssueCode.invalid_union,
2447
- unionErrors
2448
- });
2449
- return parseUtil_js_1.INVALID;
2450
- }
2451
- if (ctx.common.async) return Promise.all(options.map(async (option) => {
2452
- const childCtx = {
2453
- ...ctx,
2454
- common: {
2455
- ...ctx.common,
2456
- issues: []
2457
- },
2458
- parent: null
2459
- };
2460
- return {
2461
- result: await option._parseAsync({
2462
- data: ctx.data,
2463
- path: ctx.path,
2464
- parent: childCtx
2465
- }),
2466
- ctx: childCtx
2467
- };
2468
- })).then(handleResults);
2469
- else {
2470
- let dirty = void 0;
2471
- const issues = [];
2472
- for (const option of options) {
2473
- const childCtx = {
2474
- ...ctx,
2475
- common: {
2476
- ...ctx.common,
2477
- issues: []
2478
- },
2479
- parent: null
2480
- };
2481
- const result = option._parseSync({
2482
- data: ctx.data,
2483
- path: ctx.path,
2484
- parent: childCtx
2485
- });
2486
- if (result.status === "valid") return result;
2487
- else if (result.status === "dirty" && !dirty) dirty = {
2488
- result,
2489
- ctx: childCtx
2490
- };
2491
- if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
2492
- }
2493
- if (dirty) {
2494
- ctx.common.issues.push(...dirty.ctx.common.issues);
2495
- return dirty.result;
2496
- }
2497
- const unionErrors = issues.map((issues) => new ZodError_js_1.ZodError(issues));
2498
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2499
- code: ZodError_js_1.ZodIssueCode.invalid_union,
2500
- unionErrors
2501
- });
2502
- return parseUtil_js_1.INVALID;
2503
- }
2504
- }
2505
- get options() {
2506
- return this._def.options;
2507
- }
2508
- };
2509
- exports.ZodUnion = ZodUnion;
2510
- ZodUnion.create = (types, params) => {
2511
- return new ZodUnion({
2512
- options: types,
2513
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2514
- ...processCreateParams(params)
2515
- });
2516
- };
2517
- const getDiscriminator = (type) => {
2518
- if (type instanceof ZodLazy) return getDiscriminator(type.schema);
2519
- else if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
2520
- else if (type instanceof ZodLiteral) return [type.value];
2521
- else if (type instanceof ZodEnum) return type.options;
2522
- else if (type instanceof ZodNativeEnum) return util_js_1.util.objectValues(type.enum);
2523
- else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
2524
- else if (type instanceof ZodUndefined) return [void 0];
2525
- else if (type instanceof ZodNull) return [null];
2526
- else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())];
2527
- else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())];
2528
- else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
2529
- else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
2530
- else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
2531
- else return [];
2532
- };
2533
- var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
2534
- _parse(input) {
2535
- const { ctx } = this._processInputParams(input);
2536
- if (ctx.parsedType !== util_js_1.ZodParsedType.object) {
2537
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2538
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2539
- expected: util_js_1.ZodParsedType.object,
2540
- received: ctx.parsedType
2541
- });
2542
- return parseUtil_js_1.INVALID;
2543
- }
2544
- const discriminator = this.discriminator;
2545
- const discriminatorValue = ctx.data[discriminator];
2546
- const option = this.optionsMap.get(discriminatorValue);
2547
- if (!option) {
2548
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2549
- code: ZodError_js_1.ZodIssueCode.invalid_union_discriminator,
2550
- options: Array.from(this.optionsMap.keys()),
2551
- path: [discriminator]
2552
- });
2553
- return parseUtil_js_1.INVALID;
2554
- }
2555
- if (ctx.common.async) return option._parseAsync({
2556
- data: ctx.data,
2557
- path: ctx.path,
2558
- parent: ctx
2559
- });
2560
- else return option._parseSync({
2561
- data: ctx.data,
2562
- path: ctx.path,
2563
- parent: ctx
2564
- });
2565
- }
2566
- get discriminator() {
2567
- return this._def.discriminator;
2568
- }
2569
- get options() {
2570
- return this._def.options;
2571
- }
2572
- get optionsMap() {
2573
- return this._def.optionsMap;
2574
- }
2575
- /**
2576
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2577
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2578
- * have a different value for each object in the union.
2579
- * @param discriminator the name of the discriminator property
2580
- * @param types an array of object schemas
2581
- * @param params
2582
- */
2583
- static create(discriminator, options, params) {
2584
- const optionsMap = /* @__PURE__ */ new Map();
2585
- for (const type of options) {
2586
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2587
- if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2588
- for (const value of discriminatorValues) {
2589
- if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2590
- optionsMap.set(value, type);
2591
- }
2592
- }
2593
- return new ZodDiscriminatedUnion({
2594
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2595
- discriminator,
2596
- options,
2597
- optionsMap,
2598
- ...processCreateParams(params)
2599
- });
2600
- }
2601
- };
2602
- exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion;
2603
- function mergeValues(a, b) {
2604
- const aType = (0, util_js_1.getParsedType)(a);
2605
- const bType = (0, util_js_1.getParsedType)(b);
2606
- if (a === b) return {
2607
- valid: true,
2608
- data: a
2609
- };
2610
- else if (aType === util_js_1.ZodParsedType.object && bType === util_js_1.ZodParsedType.object) {
2611
- const bKeys = util_js_1.util.objectKeys(b);
2612
- const sharedKeys = util_js_1.util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2613
- const newObj = {
2614
- ...a,
2615
- ...b
2616
- };
2617
- for (const key of sharedKeys) {
2618
- const sharedValue = mergeValues(a[key], b[key]);
2619
- if (!sharedValue.valid) return { valid: false };
2620
- newObj[key] = sharedValue.data;
2621
- }
2622
- return {
2623
- valid: true,
2624
- data: newObj
2625
- };
2626
- } else if (aType === util_js_1.ZodParsedType.array && bType === util_js_1.ZodParsedType.array) {
2627
- if (a.length !== b.length) return { valid: false };
2628
- const newArray = [];
2629
- for (let index = 0; index < a.length; index++) {
2630
- const itemA = a[index];
2631
- const itemB = b[index];
2632
- const sharedValue = mergeValues(itemA, itemB);
2633
- if (!sharedValue.valid) return { valid: false };
2634
- newArray.push(sharedValue.data);
2635
- }
2636
- return {
2637
- valid: true,
2638
- data: newArray
2639
- };
2640
- } else if (aType === util_js_1.ZodParsedType.date && bType === util_js_1.ZodParsedType.date && +a === +b) return {
2641
- valid: true,
2642
- data: a
2643
- };
2644
- else return { valid: false };
2645
- }
2646
- var ZodIntersection = class extends ZodType {
2647
- _parse(input) {
2648
- const { status, ctx } = this._processInputParams(input);
2649
- const handleParsed = (parsedLeft, parsedRight) => {
2650
- if ((0, parseUtil_js_1.isAborted)(parsedLeft) || (0, parseUtil_js_1.isAborted)(parsedRight)) return parseUtil_js_1.INVALID;
2651
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2652
- if (!merged.valid) {
2653
- (0, parseUtil_js_1.addIssueToContext)(ctx, { code: ZodError_js_1.ZodIssueCode.invalid_intersection_types });
2654
- return parseUtil_js_1.INVALID;
2655
- }
2656
- if ((0, parseUtil_js_1.isDirty)(parsedLeft) || (0, parseUtil_js_1.isDirty)(parsedRight)) status.dirty();
2657
- return {
2658
- status: status.value,
2659
- value: merged.data
2660
- };
2661
- };
2662
- if (ctx.common.async) return Promise.all([this._def.left._parseAsync({
2663
- data: ctx.data,
2664
- path: ctx.path,
2665
- parent: ctx
2666
- }), this._def.right._parseAsync({
2667
- data: ctx.data,
2668
- path: ctx.path,
2669
- parent: ctx
2670
- })]).then(([left, right]) => handleParsed(left, right));
2671
- else return handleParsed(this._def.left._parseSync({
2672
- data: ctx.data,
2673
- path: ctx.path,
2674
- parent: ctx
2675
- }), this._def.right._parseSync({
2676
- data: ctx.data,
2677
- path: ctx.path,
2678
- parent: ctx
2679
- }));
2680
- }
2681
- };
2682
- exports.ZodIntersection = ZodIntersection;
2683
- ZodIntersection.create = (left, right, params) => {
2684
- return new ZodIntersection({
2685
- left,
2686
- right,
2687
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
2688
- ...processCreateParams(params)
2689
- });
2690
- };
2691
- var ZodTuple = class ZodTuple extends ZodType {
2692
- _parse(input) {
2693
- const { status, ctx } = this._processInputParams(input);
2694
- if (ctx.parsedType !== util_js_1.ZodParsedType.array) {
2695
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2696
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2697
- expected: util_js_1.ZodParsedType.array,
2698
- received: ctx.parsedType
2699
- });
2700
- return parseUtil_js_1.INVALID;
2701
- }
2702
- if (ctx.data.length < this._def.items.length) {
2703
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2704
- code: ZodError_js_1.ZodIssueCode.too_small,
2705
- minimum: this._def.items.length,
2706
- inclusive: true,
2707
- exact: false,
2708
- type: "array"
2709
- });
2710
- return parseUtil_js_1.INVALID;
2711
- }
2712
- if (!this._def.rest && ctx.data.length > this._def.items.length) {
2713
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2714
- code: ZodError_js_1.ZodIssueCode.too_big,
2715
- maximum: this._def.items.length,
2716
- inclusive: true,
2717
- exact: false,
2718
- type: "array"
2719
- });
2720
- status.dirty();
2721
- }
2722
- const items = [...ctx.data].map((item, itemIndex) => {
2723
- const schema = this._def.items[itemIndex] || this._def.rest;
2724
- if (!schema) return null;
2725
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2726
- }).filter((x) => !!x);
2727
- if (ctx.common.async) return Promise.all(items).then((results) => {
2728
- return parseUtil_js_1.ParseStatus.mergeArray(status, results);
2729
- });
2730
- else return parseUtil_js_1.ParseStatus.mergeArray(status, items);
2731
- }
2732
- get items() {
2733
- return this._def.items;
2734
- }
2735
- rest(rest) {
2736
- return new ZodTuple({
2737
- ...this._def,
2738
- rest
2739
- });
2740
- }
2741
- };
2742
- exports.ZodTuple = ZodTuple;
2743
- ZodTuple.create = (schemas, params) => {
2744
- if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2745
- return new ZodTuple({
2746
- items: schemas,
2747
- typeName: ZodFirstPartyTypeKind.ZodTuple,
2748
- rest: null,
2749
- ...processCreateParams(params)
2750
- });
2751
- };
2752
- var ZodRecord = class ZodRecord extends ZodType {
2753
- get keySchema() {
2754
- return this._def.keyType;
2755
- }
2756
- get valueSchema() {
2757
- return this._def.valueType;
2758
- }
2759
- _parse(input) {
2760
- const { status, ctx } = this._processInputParams(input);
2761
- if (ctx.parsedType !== util_js_1.ZodParsedType.object) {
2762
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2763
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2764
- expected: util_js_1.ZodParsedType.object,
2765
- received: ctx.parsedType
2766
- });
2767
- return parseUtil_js_1.INVALID;
2768
- }
2769
- const pairs = [];
2770
- const keyType = this._def.keyType;
2771
- const valueType = this._def.valueType;
2772
- for (const key in ctx.data) pairs.push({
2773
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2774
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
2775
- alwaysSet: key in ctx.data
2776
- });
2777
- if (ctx.common.async) return parseUtil_js_1.ParseStatus.mergeObjectAsync(status, pairs);
2778
- else return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs);
2779
- }
2780
- get element() {
2781
- return this._def.valueType;
2782
- }
2783
- static create(first, second, third) {
2784
- if (second instanceof ZodType) return new ZodRecord({
2785
- keyType: first,
2786
- valueType: second,
2787
- typeName: ZodFirstPartyTypeKind.ZodRecord,
2788
- ...processCreateParams(third)
2789
- });
2790
- return new ZodRecord({
2791
- keyType: ZodString.create(),
2792
- valueType: first,
2793
- typeName: ZodFirstPartyTypeKind.ZodRecord,
2794
- ...processCreateParams(second)
2795
- });
2796
- }
2797
- };
2798
- exports.ZodRecord = ZodRecord;
2799
- var ZodMap = class extends ZodType {
2800
- get keySchema() {
2801
- return this._def.keyType;
2802
- }
2803
- get valueSchema() {
2804
- return this._def.valueType;
2805
- }
2806
- _parse(input) {
2807
- const { status, ctx } = this._processInputParams(input);
2808
- if (ctx.parsedType !== util_js_1.ZodParsedType.map) {
2809
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2810
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2811
- expected: util_js_1.ZodParsedType.map,
2812
- received: ctx.parsedType
2813
- });
2814
- return parseUtil_js_1.INVALID;
2815
- }
2816
- const keyType = this._def.keyType;
2817
- const valueType = this._def.valueType;
2818
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
2819
- return {
2820
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
2821
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
2822
- };
2823
- });
2824
- if (ctx.common.async) {
2825
- const finalMap = /* @__PURE__ */ new Map();
2826
- return Promise.resolve().then(async () => {
2827
- for (const pair of pairs) {
2828
- const key = await pair.key;
2829
- const value = await pair.value;
2830
- if (key.status === "aborted" || value.status === "aborted") return parseUtil_js_1.INVALID;
2831
- if (key.status === "dirty" || value.status === "dirty") status.dirty();
2832
- finalMap.set(key.value, value.value);
2833
- }
2834
- return {
2835
- status: status.value,
2836
- value: finalMap
2837
- };
2838
- });
2839
- } else {
2840
- const finalMap = /* @__PURE__ */ new Map();
2841
- for (const pair of pairs) {
2842
- const key = pair.key;
2843
- const value = pair.value;
2844
- if (key.status === "aborted" || value.status === "aborted") return parseUtil_js_1.INVALID;
2845
- if (key.status === "dirty" || value.status === "dirty") status.dirty();
2846
- finalMap.set(key.value, value.value);
2847
- }
2848
- return {
2849
- status: status.value,
2850
- value: finalMap
2851
- };
2852
- }
2853
- }
2854
- };
2855
- exports.ZodMap = ZodMap;
2856
- ZodMap.create = (keyType, valueType, params) => {
2857
- return new ZodMap({
2858
- valueType,
2859
- keyType,
2860
- typeName: ZodFirstPartyTypeKind.ZodMap,
2861
- ...processCreateParams(params)
2862
- });
2863
- };
2864
- var ZodSet = class ZodSet extends ZodType {
2865
- _parse(input) {
2866
- const { status, ctx } = this._processInputParams(input);
2867
- if (ctx.parsedType !== util_js_1.ZodParsedType.set) {
2868
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2869
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2870
- expected: util_js_1.ZodParsedType.set,
2871
- received: ctx.parsedType
2872
- });
2873
- return parseUtil_js_1.INVALID;
2874
- }
2875
- const def = this._def;
2876
- if (def.minSize !== null) {
2877
- if (ctx.data.size < def.minSize.value) {
2878
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2879
- code: ZodError_js_1.ZodIssueCode.too_small,
2880
- minimum: def.minSize.value,
2881
- type: "set",
2882
- inclusive: true,
2883
- exact: false,
2884
- message: def.minSize.message
2885
- });
2886
- status.dirty();
2887
- }
2888
- }
2889
- if (def.maxSize !== null) {
2890
- if (ctx.data.size > def.maxSize.value) {
2891
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2892
- code: ZodError_js_1.ZodIssueCode.too_big,
2893
- maximum: def.maxSize.value,
2894
- type: "set",
2895
- inclusive: true,
2896
- exact: false,
2897
- message: def.maxSize.message
2898
- });
2899
- status.dirty();
2900
- }
2901
- }
2902
- const valueType = this._def.valueType;
2903
- function finalizeSet(elements) {
2904
- const parsedSet = /* @__PURE__ */ new Set();
2905
- for (const element of elements) {
2906
- if (element.status === "aborted") return parseUtil_js_1.INVALID;
2907
- if (element.status === "dirty") status.dirty();
2908
- parsedSet.add(element.value);
2909
- }
2910
- return {
2911
- status: status.value,
2912
- value: parsedSet
2913
- };
2914
- }
2915
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
2916
- if (ctx.common.async) return Promise.all(elements).then((elements) => finalizeSet(elements));
2917
- else return finalizeSet(elements);
2918
- }
2919
- min(minSize, message) {
2920
- return new ZodSet({
2921
- ...this._def,
2922
- minSize: {
2923
- value: minSize,
2924
- message: errorUtil_js_1.errorUtil.toString(message)
2925
- }
2926
- });
2927
- }
2928
- max(maxSize, message) {
2929
- return new ZodSet({
2930
- ...this._def,
2931
- maxSize: {
2932
- value: maxSize,
2933
- message: errorUtil_js_1.errorUtil.toString(message)
2934
- }
2935
- });
2936
- }
2937
- size(size, message) {
2938
- return this.min(size, message).max(size, message);
2939
- }
2940
- nonempty(message) {
2941
- return this.min(1, message);
2942
- }
2943
- };
2944
- exports.ZodSet = ZodSet;
2945
- ZodSet.create = (valueType, params) => {
2946
- return new ZodSet({
2947
- valueType,
2948
- minSize: null,
2949
- maxSize: null,
2950
- typeName: ZodFirstPartyTypeKind.ZodSet,
2951
- ...processCreateParams(params)
2952
- });
2953
- };
2954
- var ZodFunction = class ZodFunction extends ZodType {
2955
- constructor() {
2956
- super(...arguments);
2957
- this.validate = this.implement;
2958
- }
2959
- _parse(input) {
2960
- const { ctx } = this._processInputParams(input);
2961
- if (ctx.parsedType !== util_js_1.ZodParsedType.function) {
2962
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
2963
- code: ZodError_js_1.ZodIssueCode.invalid_type,
2964
- expected: util_js_1.ZodParsedType.function,
2965
- received: ctx.parsedType
2966
- });
2967
- return parseUtil_js_1.INVALID;
2968
- }
2969
- function makeArgsIssue(args, error) {
2970
- return (0, parseUtil_js_1.makeIssue)({
2971
- data: args,
2972
- path: ctx.path,
2973
- errorMaps: [
2974
- ctx.common.contextualErrorMap,
2975
- ctx.schemaErrorMap,
2976
- (0, errors_js_1.getErrorMap)(),
2977
- errors_js_1.defaultErrorMap
2978
- ].filter((x) => !!x),
2979
- issueData: {
2980
- code: ZodError_js_1.ZodIssueCode.invalid_arguments,
2981
- argumentsError: error
2982
- }
2983
- });
2984
- }
2985
- function makeReturnsIssue(returns, error) {
2986
- return (0, parseUtil_js_1.makeIssue)({
2987
- data: returns,
2988
- path: ctx.path,
2989
- errorMaps: [
2990
- ctx.common.contextualErrorMap,
2991
- ctx.schemaErrorMap,
2992
- (0, errors_js_1.getErrorMap)(),
2993
- errors_js_1.defaultErrorMap
2994
- ].filter((x) => !!x),
2995
- issueData: {
2996
- code: ZodError_js_1.ZodIssueCode.invalid_return_type,
2997
- returnTypeError: error
2998
- }
2999
- });
3000
- }
3001
- const params = { errorMap: ctx.common.contextualErrorMap };
3002
- const fn = ctx.data;
3003
- if (this._def.returns instanceof ZodPromise) {
3004
- const me = this;
3005
- return (0, parseUtil_js_1.OK)(async function(...args) {
3006
- const error = new ZodError_js_1.ZodError([]);
3007
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3008
- error.addIssue(makeArgsIssue(args, e));
3009
- throw error;
3010
- });
3011
- const result = await Reflect.apply(fn, this, parsedArgs);
3012
- return await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3013
- error.addIssue(makeReturnsIssue(result, e));
3014
- throw error;
3015
- });
3016
- });
3017
- } else {
3018
- const me = this;
3019
- return (0, parseUtil_js_1.OK)(function(...args) {
3020
- const parsedArgs = me._def.args.safeParse(args, params);
3021
- if (!parsedArgs.success) throw new ZodError_js_1.ZodError([makeArgsIssue(args, parsedArgs.error)]);
3022
- const result = Reflect.apply(fn, this, parsedArgs.data);
3023
- const parsedReturns = me._def.returns.safeParse(result, params);
3024
- if (!parsedReturns.success) throw new ZodError_js_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3025
- return parsedReturns.data;
3026
- });
3027
- }
3028
- }
3029
- parameters() {
3030
- return this._def.args;
3031
- }
3032
- returnType() {
3033
- return this._def.returns;
3034
- }
3035
- args(...items) {
3036
- return new ZodFunction({
3037
- ...this._def,
3038
- args: ZodTuple.create(items).rest(ZodUnknown.create())
3039
- });
3040
- }
3041
- returns(returnType) {
3042
- return new ZodFunction({
3043
- ...this._def,
3044
- returns: returnType
3045
- });
3046
- }
3047
- implement(func) {
3048
- return this.parse(func);
3049
- }
3050
- strictImplement(func) {
3051
- return this.parse(func);
3052
- }
3053
- static create(args, returns, params) {
3054
- return new ZodFunction({
3055
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3056
- returns: returns || ZodUnknown.create(),
3057
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3058
- ...processCreateParams(params)
3059
- });
3060
- }
3061
- };
3062
- exports.ZodFunction = ZodFunction;
3063
- var ZodLazy = class extends ZodType {
3064
- get schema() {
3065
- return this._def.getter();
3066
- }
3067
- _parse(input) {
3068
- const { ctx } = this._processInputParams(input);
3069
- return this._def.getter()._parse({
3070
- data: ctx.data,
3071
- path: ctx.path,
3072
- parent: ctx
3073
- });
3074
- }
3075
- };
3076
- exports.ZodLazy = ZodLazy;
3077
- ZodLazy.create = (getter, params) => {
3078
- return new ZodLazy({
3079
- getter,
3080
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3081
- ...processCreateParams(params)
3082
- });
3083
- };
3084
- var ZodLiteral = class extends ZodType {
3085
- _parse(input) {
3086
- if (input.data !== this._def.value) {
3087
- const ctx = this._getOrReturnCtx(input);
3088
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
3089
- received: ctx.data,
3090
- code: ZodError_js_1.ZodIssueCode.invalid_literal,
3091
- expected: this._def.value
3092
- });
3093
- return parseUtil_js_1.INVALID;
3094
- }
3095
- return {
3096
- status: "valid",
3097
- value: input.data
3098
- };
3099
- }
3100
- get value() {
3101
- return this._def.value;
3102
- }
3103
- };
3104
- exports.ZodLiteral = ZodLiteral;
3105
- ZodLiteral.create = (value, params) => {
3106
- return new ZodLiteral({
3107
- value,
3108
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3109
- ...processCreateParams(params)
3110
- });
3111
- };
3112
- function createZodEnum(values, params) {
3113
- return new ZodEnum({
3114
- values,
3115
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3116
- ...processCreateParams(params)
3117
- });
3118
- }
3119
- var ZodEnum = class ZodEnum extends ZodType {
3120
- _parse(input) {
3121
- if (typeof input.data !== "string") {
3122
- const ctx = this._getOrReturnCtx(input);
3123
- const expectedValues = this._def.values;
3124
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
3125
- expected: util_js_1.util.joinValues(expectedValues),
3126
- received: ctx.parsedType,
3127
- code: ZodError_js_1.ZodIssueCode.invalid_type
3128
- });
3129
- return parseUtil_js_1.INVALID;
3130
- }
3131
- if (!this._cache) this._cache = new Set(this._def.values);
3132
- if (!this._cache.has(input.data)) {
3133
- const ctx = this._getOrReturnCtx(input);
3134
- const expectedValues = this._def.values;
3135
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
3136
- received: ctx.data,
3137
- code: ZodError_js_1.ZodIssueCode.invalid_enum_value,
3138
- options: expectedValues
3139
- });
3140
- return parseUtil_js_1.INVALID;
3141
- }
3142
- return (0, parseUtil_js_1.OK)(input.data);
3143
- }
3144
- get options() {
3145
- return this._def.values;
3146
- }
3147
- get enum() {
3148
- const enumValues = {};
3149
- for (const val of this._def.values) enumValues[val] = val;
3150
- return enumValues;
3151
- }
3152
- get Values() {
3153
- const enumValues = {};
3154
- for (const val of this._def.values) enumValues[val] = val;
3155
- return enumValues;
3156
- }
3157
- get Enum() {
3158
- const enumValues = {};
3159
- for (const val of this._def.values) enumValues[val] = val;
3160
- return enumValues;
3161
- }
3162
- extract(values, newDef = this._def) {
3163
- return ZodEnum.create(values, {
3164
- ...this._def,
3165
- ...newDef
3166
- });
3167
- }
3168
- exclude(values, newDef = this._def) {
3169
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3170
- ...this._def,
3171
- ...newDef
3172
- });
3173
- }
3174
- };
3175
- exports.ZodEnum = ZodEnum;
3176
- ZodEnum.create = createZodEnum;
3177
- var ZodNativeEnum = class extends ZodType {
3178
- _parse(input) {
3179
- const nativeEnumValues = util_js_1.util.getValidEnumValues(this._def.values);
3180
- const ctx = this._getOrReturnCtx(input);
3181
- if (ctx.parsedType !== util_js_1.ZodParsedType.string && ctx.parsedType !== util_js_1.ZodParsedType.number) {
3182
- const expectedValues = util_js_1.util.objectValues(nativeEnumValues);
3183
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
3184
- expected: util_js_1.util.joinValues(expectedValues),
3185
- received: ctx.parsedType,
3186
- code: ZodError_js_1.ZodIssueCode.invalid_type
3187
- });
3188
- return parseUtil_js_1.INVALID;
3189
- }
3190
- if (!this._cache) this._cache = new Set(util_js_1.util.getValidEnumValues(this._def.values));
3191
- if (!this._cache.has(input.data)) {
3192
- const expectedValues = util_js_1.util.objectValues(nativeEnumValues);
3193
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
3194
- received: ctx.data,
3195
- code: ZodError_js_1.ZodIssueCode.invalid_enum_value,
3196
- options: expectedValues
3197
- });
3198
- return parseUtil_js_1.INVALID;
3199
- }
3200
- return (0, parseUtil_js_1.OK)(input.data);
3201
- }
3202
- get enum() {
3203
- return this._def.values;
3204
- }
3205
- };
3206
- exports.ZodNativeEnum = ZodNativeEnum;
3207
- ZodNativeEnum.create = (values, params) => {
3208
- return new ZodNativeEnum({
3209
- values,
3210
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3211
- ...processCreateParams(params)
3212
- });
3213
- };
3214
- var ZodPromise = class extends ZodType {
3215
- unwrap() {
3216
- return this._def.type;
3217
- }
3218
- _parse(input) {
3219
- const { ctx } = this._processInputParams(input);
3220
- if (ctx.parsedType !== util_js_1.ZodParsedType.promise && ctx.common.async === false) {
3221
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
3222
- code: ZodError_js_1.ZodIssueCode.invalid_type,
3223
- expected: util_js_1.ZodParsedType.promise,
3224
- received: ctx.parsedType
3225
- });
3226
- return parseUtil_js_1.INVALID;
3227
- }
3228
- const promisified = ctx.parsedType === util_js_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3229
- return (0, parseUtil_js_1.OK)(promisified.then((data) => {
3230
- return this._def.type.parseAsync(data, {
3231
- path: ctx.path,
3232
- errorMap: ctx.common.contextualErrorMap
3233
- });
3234
- }));
3235
- }
3236
- };
3237
- exports.ZodPromise = ZodPromise;
3238
- ZodPromise.create = (schema, params) => {
3239
- return new ZodPromise({
3240
- type: schema,
3241
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3242
- ...processCreateParams(params)
3243
- });
3244
- };
3245
- var ZodEffects = class extends ZodType {
3246
- innerType() {
3247
- return this._def.schema;
3248
- }
3249
- sourceType() {
3250
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3251
- }
3252
- _parse(input) {
3253
- const { status, ctx } = this._processInputParams(input);
3254
- const effect = this._def.effect || null;
3255
- const checkCtx = {
3256
- addIssue: (arg) => {
3257
- (0, parseUtil_js_1.addIssueToContext)(ctx, arg);
3258
- if (arg.fatal) status.abort();
3259
- else status.dirty();
3260
- },
3261
- get path() {
3262
- return ctx.path;
3263
- }
3264
- };
3265
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3266
- if (effect.type === "preprocess") {
3267
- const processed = effect.transform(ctx.data, checkCtx);
3268
- if (ctx.common.async) return Promise.resolve(processed).then(async (processed) => {
3269
- if (status.value === "aborted") return parseUtil_js_1.INVALID;
3270
- const result = await this._def.schema._parseAsync({
3271
- data: processed,
3272
- path: ctx.path,
3273
- parent: ctx
3274
- });
3275
- if (result.status === "aborted") return parseUtil_js_1.INVALID;
3276
- if (result.status === "dirty") return (0, parseUtil_js_1.DIRTY)(result.value);
3277
- if (status.value === "dirty") return (0, parseUtil_js_1.DIRTY)(result.value);
3278
- return result;
3279
- });
3280
- else {
3281
- if (status.value === "aborted") return parseUtil_js_1.INVALID;
3282
- const result = this._def.schema._parseSync({
3283
- data: processed,
3284
- path: ctx.path,
3285
- parent: ctx
3286
- });
3287
- if (result.status === "aborted") return parseUtil_js_1.INVALID;
3288
- if (result.status === "dirty") return (0, parseUtil_js_1.DIRTY)(result.value);
3289
- if (status.value === "dirty") return (0, parseUtil_js_1.DIRTY)(result.value);
3290
- return result;
3291
- }
3292
- }
3293
- if (effect.type === "refinement") {
3294
- const executeRefinement = (acc) => {
3295
- const result = effect.refinement(acc, checkCtx);
3296
- if (ctx.common.async) return Promise.resolve(result);
3297
- if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3298
- return acc;
3299
- };
3300
- if (ctx.common.async === false) {
3301
- const inner = this._def.schema._parseSync({
3302
- data: ctx.data,
3303
- path: ctx.path,
3304
- parent: ctx
3305
- });
3306
- if (inner.status === "aborted") return parseUtil_js_1.INVALID;
3307
- if (inner.status === "dirty") status.dirty();
3308
- executeRefinement(inner.value);
3309
- return {
3310
- status: status.value,
3311
- value: inner.value
3312
- };
3313
- } else return this._def.schema._parseAsync({
3314
- data: ctx.data,
3315
- path: ctx.path,
3316
- parent: ctx
3317
- }).then((inner) => {
3318
- if (inner.status === "aborted") return parseUtil_js_1.INVALID;
3319
- if (inner.status === "dirty") status.dirty();
3320
- return executeRefinement(inner.value).then(() => {
3321
- return {
3322
- status: status.value,
3323
- value: inner.value
3324
- };
3325
- });
3326
- });
3327
- }
3328
- if (effect.type === "transform") if (ctx.common.async === false) {
3329
- const base = this._def.schema._parseSync({
3330
- data: ctx.data,
3331
- path: ctx.path,
3332
- parent: ctx
3333
- });
3334
- if (!(0, parseUtil_js_1.isValid)(base)) return parseUtil_js_1.INVALID;
3335
- const result = effect.transform(base.value, checkCtx);
3336
- if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3337
- return {
3338
- status: status.value,
3339
- value: result
3340
- };
3341
- } else return this._def.schema._parseAsync({
3342
- data: ctx.data,
3343
- path: ctx.path,
3344
- parent: ctx
3345
- }).then((base) => {
3346
- if (!(0, parseUtil_js_1.isValid)(base)) return parseUtil_js_1.INVALID;
3347
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3348
- status: status.value,
3349
- value: result
3350
- }));
3351
- });
3352
- util_js_1.util.assertNever(effect);
3353
- }
3354
- };
3355
- exports.ZodEffects = ZodEffects;
3356
- exports.ZodTransformer = ZodEffects;
3357
- ZodEffects.create = (schema, effect, params) => {
3358
- return new ZodEffects({
3359
- schema,
3360
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3361
- effect,
3362
- ...processCreateParams(params)
3363
- });
3364
- };
3365
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3366
- return new ZodEffects({
3367
- schema,
3368
- effect: {
3369
- type: "preprocess",
3370
- transform: preprocess
3371
- },
3372
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3373
- ...processCreateParams(params)
3374
- });
3375
- };
3376
- var ZodOptional = class extends ZodType {
3377
- _parse(input) {
3378
- if (this._getType(input) === util_js_1.ZodParsedType.undefined) return (0, parseUtil_js_1.OK)(void 0);
3379
- return this._def.innerType._parse(input);
3380
- }
3381
- unwrap() {
3382
- return this._def.innerType;
3383
- }
3384
- };
3385
- exports.ZodOptional = ZodOptional;
3386
- ZodOptional.create = (type, params) => {
3387
- return new ZodOptional({
3388
- innerType: type,
3389
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3390
- ...processCreateParams(params)
3391
- });
3392
- };
3393
- var ZodNullable = class extends ZodType {
3394
- _parse(input) {
3395
- if (this._getType(input) === util_js_1.ZodParsedType.null) return (0, parseUtil_js_1.OK)(null);
3396
- return this._def.innerType._parse(input);
3397
- }
3398
- unwrap() {
3399
- return this._def.innerType;
3400
- }
3401
- };
3402
- exports.ZodNullable = ZodNullable;
3403
- ZodNullable.create = (type, params) => {
3404
- return new ZodNullable({
3405
- innerType: type,
3406
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3407
- ...processCreateParams(params)
3408
- });
3409
- };
3410
- var ZodDefault = class extends ZodType {
3411
- _parse(input) {
3412
- const { ctx } = this._processInputParams(input);
3413
- let data = ctx.data;
3414
- if (ctx.parsedType === util_js_1.ZodParsedType.undefined) data = this._def.defaultValue();
3415
- return this._def.innerType._parse({
3416
- data,
3417
- path: ctx.path,
3418
- parent: ctx
3419
- });
3420
- }
3421
- removeDefault() {
3422
- return this._def.innerType;
3423
- }
3424
- };
3425
- exports.ZodDefault = ZodDefault;
3426
- ZodDefault.create = (type, params) => {
3427
- return new ZodDefault({
3428
- innerType: type,
3429
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3430
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3431
- ...processCreateParams(params)
3432
- });
3433
- };
3434
- var ZodCatch = class extends ZodType {
3435
- _parse(input) {
3436
- const { ctx } = this._processInputParams(input);
3437
- const newCtx = {
3438
- ...ctx,
3439
- common: {
3440
- ...ctx.common,
3441
- issues: []
3442
- }
3443
- };
3444
- const result = this._def.innerType._parse({
3445
- data: newCtx.data,
3446
- path: newCtx.path,
3447
- parent: { ...newCtx }
3448
- });
3449
- if ((0, parseUtil_js_1.isAsync)(result)) return result.then((result) => {
3450
- return {
3451
- status: "valid",
3452
- value: result.status === "valid" ? result.value : this._def.catchValue({
3453
- get error() {
3454
- return new ZodError_js_1.ZodError(newCtx.common.issues);
3455
- },
3456
- input: newCtx.data
3457
- })
3458
- };
3459
- });
3460
- else return {
3461
- status: "valid",
3462
- value: result.status === "valid" ? result.value : this._def.catchValue({
3463
- get error() {
3464
- return new ZodError_js_1.ZodError(newCtx.common.issues);
3465
- },
3466
- input: newCtx.data
3467
- })
3468
- };
3469
- }
3470
- removeCatch() {
3471
- return this._def.innerType;
3472
- }
3473
- };
3474
- exports.ZodCatch = ZodCatch;
3475
- ZodCatch.create = (type, params) => {
3476
- return new ZodCatch({
3477
- innerType: type,
3478
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3479
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3480
- ...processCreateParams(params)
3481
- });
3482
- };
3483
- var ZodNaN = class extends ZodType {
3484
- _parse(input) {
3485
- if (this._getType(input) !== util_js_1.ZodParsedType.nan) {
3486
- const ctx = this._getOrReturnCtx(input);
3487
- (0, parseUtil_js_1.addIssueToContext)(ctx, {
3488
- code: ZodError_js_1.ZodIssueCode.invalid_type,
3489
- expected: util_js_1.ZodParsedType.nan,
3490
- received: ctx.parsedType
3491
- });
3492
- return parseUtil_js_1.INVALID;
3493
- }
3494
- return {
3495
- status: "valid",
3496
- value: input.data
3497
- };
3498
- }
3499
- };
3500
- exports.ZodNaN = ZodNaN;
3501
- ZodNaN.create = (params) => {
3502
- return new ZodNaN({
3503
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3504
- ...processCreateParams(params)
3505
- });
3506
- };
3507
- exports.BRAND = Symbol("zod_brand");
3508
- var ZodBranded = class extends ZodType {
3509
- _parse(input) {
3510
- const { ctx } = this._processInputParams(input);
3511
- const data = ctx.data;
3512
- return this._def.type._parse({
3513
- data,
3514
- path: ctx.path,
3515
- parent: ctx
3516
- });
3517
- }
3518
- unwrap() {
3519
- return this._def.type;
3520
- }
3521
- };
3522
- exports.ZodBranded = ZodBranded;
3523
- var ZodPipeline = class ZodPipeline extends ZodType {
3524
- _parse(input) {
3525
- const { status, ctx } = this._processInputParams(input);
3526
- if (ctx.common.async) {
3527
- const handleAsync = async () => {
3528
- const inResult = await this._def.in._parseAsync({
3529
- data: ctx.data,
3530
- path: ctx.path,
3531
- parent: ctx
3532
- });
3533
- if (inResult.status === "aborted") return parseUtil_js_1.INVALID;
3534
- if (inResult.status === "dirty") {
3535
- status.dirty();
3536
- return (0, parseUtil_js_1.DIRTY)(inResult.value);
3537
- } else return this._def.out._parseAsync({
3538
- data: inResult.value,
3539
- path: ctx.path,
3540
- parent: ctx
3541
- });
3542
- };
3543
- return handleAsync();
3544
- } else {
3545
- const inResult = this._def.in._parseSync({
3546
- data: ctx.data,
3547
- path: ctx.path,
3548
- parent: ctx
3549
- });
3550
- if (inResult.status === "aborted") return parseUtil_js_1.INVALID;
3551
- if (inResult.status === "dirty") {
3552
- status.dirty();
3553
- return {
3554
- status: "dirty",
3555
- value: inResult.value
3556
- };
3557
- } else return this._def.out._parseSync({
3558
- data: inResult.value,
3559
- path: ctx.path,
3560
- parent: ctx
3561
- });
3562
- }
3563
- }
3564
- static create(a, b) {
3565
- return new ZodPipeline({
3566
- in: a,
3567
- out: b,
3568
- typeName: ZodFirstPartyTypeKind.ZodPipeline
3569
- });
3570
- }
3571
- };
3572
- exports.ZodPipeline = ZodPipeline;
3573
- var ZodReadonly = class extends ZodType {
3574
- _parse(input) {
3575
- const result = this._def.innerType._parse(input);
3576
- const freeze = (data) => {
3577
- if ((0, parseUtil_js_1.isValid)(data)) data.value = Object.freeze(data.value);
3578
- return data;
3579
- };
3580
- return (0, parseUtil_js_1.isAsync)(result) ? result.then((data) => freeze(data)) : freeze(result);
3581
- }
3582
- unwrap() {
3583
- return this._def.innerType;
3584
- }
3585
- };
3586
- exports.ZodReadonly = ZodReadonly;
3587
- ZodReadonly.create = (type, params) => {
3588
- return new ZodReadonly({
3589
- innerType: type,
3590
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3591
- ...processCreateParams(params)
3592
- });
3593
- };
3594
- function cleanParams(params, data) {
3595
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3596
- return typeof p === "string" ? { message: p } : p;
3597
- }
3598
- function custom(check, _params = {}, fatal) {
3599
- if (check) return ZodAny.create().superRefine((data, ctx) => {
3600
- const r = check(data);
3601
- if (r instanceof Promise) return r.then((r) => {
3602
- if (!r) {
3603
- const params = cleanParams(_params, data);
3604
- const _fatal = params.fatal ?? fatal ?? true;
3605
- ctx.addIssue({
3606
- code: "custom",
3607
- ...params,
3608
- fatal: _fatal
3609
- });
3610
- }
3611
- });
3612
- if (!r) {
3613
- const params = cleanParams(_params, data);
3614
- const _fatal = params.fatal ?? fatal ?? true;
3615
- ctx.addIssue({
3616
- code: "custom",
3617
- ...params,
3618
- fatal: _fatal
3619
- });
3620
- }
3621
- });
3622
- return ZodAny.create();
3623
- }
3624
- exports.late = { object: ZodObject.lazycreate };
3625
- var ZodFirstPartyTypeKind;
3626
- (function(ZodFirstPartyTypeKind) {
3627
- ZodFirstPartyTypeKind["ZodString"] = "ZodString";
3628
- ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
3629
- ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
3630
- ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
3631
- ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
3632
- ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
3633
- ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
3634
- ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
3635
- ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
3636
- ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
3637
- ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
3638
- ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
3639
- ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
3640
- ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
3641
- ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
3642
- ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
3643
- ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3644
- ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
3645
- ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
3646
- ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
3647
- ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
3648
- ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
3649
- ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
3650
- ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
3651
- ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
3652
- ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
3653
- ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
3654
- ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
3655
- ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
3656
- ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
3657
- ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
3658
- ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
3659
- ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
3660
- ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
3661
- ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
3662
- ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
3663
- })(ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind = {}));
3664
- const instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params);
3665
- exports.instanceof = instanceOfType;
3666
- const stringType = ZodString.create;
3667
- exports.string = stringType;
3668
- const numberType = ZodNumber.create;
3669
- exports.number = numberType;
3670
- const nanType = ZodNaN.create;
3671
- exports.nan = nanType;
3672
- const bigIntType = ZodBigInt.create;
3673
- exports.bigint = bigIntType;
3674
- const booleanType = ZodBoolean.create;
3675
- exports.boolean = booleanType;
3676
- const dateType = ZodDate.create;
3677
- exports.date = dateType;
3678
- const symbolType = ZodSymbol.create;
3679
- exports.symbol = symbolType;
3680
- const undefinedType = ZodUndefined.create;
3681
- exports.undefined = undefinedType;
3682
- const nullType = ZodNull.create;
3683
- exports.null = nullType;
3684
- const anyType = ZodAny.create;
3685
- exports.any = anyType;
3686
- const unknownType = ZodUnknown.create;
3687
- exports.unknown = unknownType;
3688
- const neverType = ZodNever.create;
3689
- exports.never = neverType;
3690
- const voidType = ZodVoid.create;
3691
- exports.void = voidType;
3692
- const arrayType = ZodArray.create;
3693
- exports.array = arrayType;
3694
- const objectType = ZodObject.create;
3695
- exports.object = objectType;
3696
- const strictObjectType = ZodObject.strictCreate;
3697
- exports.strictObject = strictObjectType;
3698
- const unionType = ZodUnion.create;
3699
- exports.union = unionType;
3700
- const discriminatedUnionType = ZodDiscriminatedUnion.create;
3701
- exports.discriminatedUnion = discriminatedUnionType;
3702
- const intersectionType = ZodIntersection.create;
3703
- exports.intersection = intersectionType;
3704
- const tupleType = ZodTuple.create;
3705
- exports.tuple = tupleType;
3706
- const recordType = ZodRecord.create;
3707
- exports.record = recordType;
3708
- const mapType = ZodMap.create;
3709
- exports.map = mapType;
3710
- const setType = ZodSet.create;
3711
- exports.set = setType;
3712
- const functionType = ZodFunction.create;
3713
- exports.function = functionType;
3714
- const lazyType = ZodLazy.create;
3715
- exports.lazy = lazyType;
3716
- const literalType = ZodLiteral.create;
3717
- exports.literal = literalType;
3718
- const enumType = ZodEnum.create;
3719
- exports.enum = enumType;
3720
- const nativeEnumType = ZodNativeEnum.create;
3721
- exports.nativeEnum = nativeEnumType;
3722
- const promiseType = ZodPromise.create;
3723
- exports.promise = promiseType;
3724
- const effectsType = ZodEffects.create;
3725
- exports.effect = effectsType;
3726
- exports.transformer = effectsType;
3727
- const optionalType = ZodOptional.create;
3728
- exports.optional = optionalType;
3729
- const nullableType = ZodNullable.create;
3730
- exports.nullable = nullableType;
3731
- const preprocessType = ZodEffects.createWithPreprocess;
3732
- exports.preprocess = preprocessType;
3733
- const pipelineType = ZodPipeline.create;
3734
- exports.pipeline = pipelineType;
3735
- const ostring = () => stringType().optional();
3736
- exports.ostring = ostring;
3737
- const onumber = () => numberType().optional();
3738
- exports.onumber = onumber;
3739
- const oboolean = () => booleanType().optional();
3740
- exports.oboolean = oboolean;
3741
- exports.coerce = {
3742
- string: ((arg) => ZodString.create({
3743
- ...arg,
3744
- coerce: true
3745
- })),
3746
- number: ((arg) => ZodNumber.create({
3747
- ...arg,
3748
- coerce: true
3749
- })),
3750
- boolean: ((arg) => ZodBoolean.create({
3751
- ...arg,
3752
- coerce: true
3753
- })),
3754
- bigint: ((arg) => ZodBigInt.create({
3755
- ...arg,
3756
- coerce: true
3757
- })),
3758
- date: ((arg) => ZodDate.create({
3759
- ...arg,
3760
- coerce: true
3761
- }))
3762
- };
3763
- exports.NEVER = parseUtil_js_1.INVALID;
3764
- }));
3765
-
3766
- //#endregion
3767
- //#region ../agent-provider/node_modules/zod/v3/external.cjs
3768
- var require_external = /* @__PURE__ */ __commonJSMin(((exports) => {
3769
- var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
3770
- if (k2 === void 0) k2 = k;
3771
- var desc = Object.getOwnPropertyDescriptor(m, k);
3772
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
3773
- enumerable: true,
3774
- get: function() {
3775
- return m[k];
3776
- }
3777
- };
3778
- Object.defineProperty(o, k2, desc);
3779
- }) : (function(o, m, k, k2) {
3780
- if (k2 === void 0) k2 = k;
3781
- o[k2] = m[k];
3782
- }));
3783
- var __exportStar = exports && exports.__exportStar || function(m, exports$6) {
3784
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$6, p)) __createBinding(exports$6, m, p);
3785
- };
3786
- Object.defineProperty(exports, "__esModule", { value: true });
3787
- __exportStar(require_errors$1(), exports);
3788
- __exportStar(require_parseUtil(), exports);
3789
- __exportStar(require_typeAliases(), exports);
3790
- __exportStar(require_util(), exports);
3791
- __exportStar(require_types$4(), exports);
3792
- __exportStar(require_ZodError(), exports);
3793
- }));
3794
-
3795
- //#endregion
3796
- //#region ../agent-provider/node_modules/zod/index.cjs
3797
- var require_zod = /* @__PURE__ */ __commonJSMin(((exports) => {
3798
- var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
3799
- if (k2 === void 0) k2 = k;
3800
- var desc = Object.getOwnPropertyDescriptor(m, k);
3801
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
3802
- enumerable: true,
3803
- get: function() {
3804
- return m[k];
3805
- }
3806
- };
3807
- Object.defineProperty(o, k2, desc);
3808
- }) : (function(o, m, k, k2) {
3809
- if (k2 === void 0) k2 = k;
3810
- o[k2] = m[k];
3811
- }));
3812
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
3813
- Object.defineProperty(o, "default", {
3814
- enumerable: true,
3815
- value: v
3816
- });
3817
- }) : function(o, v) {
3818
- o["default"] = v;
3819
- });
3820
- var __importStar = exports && exports.__importStar || function(mod) {
3821
- if (mod && mod.__esModule) return mod;
3822
- var result = {};
3823
- if (mod != null) {
3824
- for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
3825
- }
3826
- __setModuleDefault(result, mod);
3827
- return result;
3828
- };
3829
- var __exportStar = exports && exports.__exportStar || function(m, exports$5) {
3830
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$5, p)) __createBinding(exports$5, m, p);
3831
- };
3832
- Object.defineProperty(exports, "__esModule", { value: true });
3833
- exports.z = void 0;
3834
- const z = __importStar(require_external());
3835
- exports.z = z;
3836
- __exportStar(require_external(), exports);
3837
- exports.default = z;
3838
- }));
3839
-
3840
- //#endregion
3841
6
  //#region ../agent-provider/lib/common/_legacy/tool-schemas.js
3842
7
  var require_tool_schemas = /* @__PURE__ */ __commonJSMin(((exports) => {
3843
8
  /**
@@ -3850,7 +15,7 @@ var require_tool_schemas = /* @__PURE__ */ __commonJSMin(((exports) => {
3850
15
  exports.ToolOutputSchemas = exports.ToolInputSchemas = void 0;
3851
16
  exports.validateToolInput = validateToolInput;
3852
17
  exports.validateToolOutput = validateToolOutput;
3853
- const zod_1 = require_zod();
18
+ const zod_1 = require("zod");
3854
19
  /**
3855
20
  * 工具输入 Schema 定义
3856
21
  * 用于验证和约束 rawInput
@@ -7325,7 +3490,8 @@ var require_types$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
7325
3490
  exports.ExtensionMethod = {
7326
3491
  ARTIFACT: "_codebuddy.ai/artifact",
7327
3492
  QUESTION: "_codebuddy.ai/question",
7328
- CHECKPOINT: "_codebuddy.ai/checkpoint"
3493
+ CHECKPOINT: "_codebuddy.ai/checkpoint",
3494
+ USAGE: "_codebuddy.ai/usage"
7329
3495
  };
7330
3496
  /**
7331
3497
  * All known extension methods
@@ -7333,7 +3499,8 @@ var require_types$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
7333
3499
  exports.KNOWN_EXTENSIONS = [
7334
3500
  exports.ExtensionMethod.ARTIFACT,
7335
3501
  exports.ExtensionMethod.QUESTION,
7336
- exports.ExtensionMethod.CHECKPOINT
3502
+ exports.ExtensionMethod.CHECKPOINT,
3503
+ exports.ExtensionMethod.USAGE
7337
3504
  ];
7338
3505
  }));
7339
3506
 
@@ -7936,14 +4103,14 @@ var require_artifacts = /* @__PURE__ */ __commonJSMin(((exports) => {
7936
4103
  const { event } = notification;
7937
4104
  if (event === "deleted") {
7938
4105
  const { artifact } = notification;
7939
- const existing = this.artifacts.get(artifact.id);
7940
- (_a = this.logger) === null || _a === void 0 || _a.debug(`Artifact deleted: ${artifact.id}`);
7941
- this.artifacts.delete(artifact.id);
4106
+ const existing = this.artifacts.get(artifact.uri);
4107
+ (_a = this.logger) === null || _a === void 0 || _a.debug(`Artifact deleted: ${artifact.uri}`);
4108
+ this.artifacts.delete(artifact.uri);
7942
4109
  if (existing) this.notifyCallbacks(existing, event);
7943
4110
  } else {
7944
4111
  const { artifact } = notification;
7945
- (_b = this.logger) === null || _b === void 0 || _b.debug(`Artifact ${event}: ${artifact.id} (${artifact.type})`);
7946
- this.artifacts.set(artifact.id, artifact);
4112
+ (_b = this.logger) === null || _b === void 0 || _b.debug(`Artifact ${event}: ${artifact.uri} (${artifact.type})`);
4113
+ this.artifacts.set(artifact.uri, artifact);
7947
4114
  this.notifyCallbacks(artifact, event);
7948
4115
  }
7949
4116
  }
@@ -7956,10 +4123,10 @@ var require_artifacts = /* @__PURE__ */ __commonJSMin(((exports) => {
7956
4123
  }
7957
4124
  }
7958
4125
  /**
7959
- * Get an artifact by ID (used internally for deleted event handling)
4126
+ * Get an artifact by URI (used internally for deleted event handling)
7960
4127
  */
7961
- get(id) {
7962
- return this.artifacts.get(id);
4128
+ get(uri) {
4129
+ return this.artifacts.get(uri);
7963
4130
  }
7964
4131
  /**
7965
4132
  * Clear all artifacts
@@ -8152,33 +4319,14 @@ var require_permissions = /* @__PURE__ */ __commonJSMin(((exports) => {
8152
4319
  var require_questions = /* @__PURE__ */ __commonJSMin(((exports) => {
8153
4320
  /**
8154
4321
  * Question Manager for Streamable HTTP ACP Client
8155
- * Handles ask_followup_question tool input requests with timeout support
8156
- *
8157
- * This provides a strongly-typed API for the "question" input type,
8158
- * while the underlying protocol uses the generic _codebuddy.ai/tool_input extMethod.
4322
+ * Handles ask_followup_question requests with timeout support
8159
4323
  */
8160
4324
  Object.defineProperty(exports, "__esModule", { value: true });
8161
4325
  exports.QuestionManager = void 0;
8162
4326
  const constants_js_1 = require_constants();
8163
4327
  const errors_js_1 = require_errors();
8164
4328
  /**
8165
- * Converts ToolInputRequest to QuestionRequest for client-facing API
8166
- */
8167
- function toQuestionRequest(params) {
8168
- const schema = params.schema;
8169
- return {
8170
- sessionId: params.sessionId,
8171
- toolCallId: params.toolCallId,
8172
- questions: schema.questions,
8173
- timeout: params.timeout,
8174
- _meta: params._meta
8175
- };
8176
- }
8177
- /**
8178
4329
  * Manages question requests from the agent (ask_followup_question tool)
8179
- *
8180
- * Provides strongly-typed methods for handling questions while internally
8181
- * using the generic ToolInputRequest/ToolInputResponse protocol types.
8182
4330
  */
8183
4331
  var QuestionManager = class {
8184
4332
  constructor(config = {}) {
@@ -8197,27 +4345,27 @@ var require_questions = /* @__PURE__ */ __commonJSMin(((exports) => {
8197
4345
  this.callbacks = callbacks;
8198
4346
  }
8199
4347
  /**
8200
- * Handle a tool input request from the agent
8201
- * This is called internally when receiving _codebuddy.ai/tool_input extMethod
4348
+ * Handle a question request from the agent
4349
+ * Called when receiving _codebuddy.ai/question extMethod
8202
4350
  */
8203
- async handleRequest(params) {
4351
+ async handleRequest(request) {
8204
4352
  var _a;
8205
- const toolCallId = params.toolCallId;
4353
+ const toolCallId = request.toolCallId;
8206
4354
  (_a = this.config.logger) === null || _a === void 0 || _a.debug(`Question request received: ${toolCallId}`);
8207
4355
  return new Promise((resolve, reject) => {
8208
4356
  var _a, _b, _c;
8209
4357
  const pending = {
8210
- params,
4358
+ request,
8211
4359
  resolve,
8212
4360
  reject,
8213
4361
  createdAt: Date.now()
8214
4362
  };
8215
- const timeout = (_a = params.timeout) !== null && _a !== void 0 ? _a : this.config.timeout;
4363
+ const timeout = (_a = request.timeout) !== null && _a !== void 0 ? _a : this.config.timeout;
8216
4364
  if (timeout && timeout > 0) pending.timeoutId = setTimeout(() => {
8217
4365
  this.handleTimeout(toolCallId);
8218
4366
  }, timeout);
8219
4367
  this.pending.set(toolCallId, pending);
8220
- if (params.inputType === "question") (_c = (_b = this.callbacks).onRequest) === null || _c === void 0 || _c.call(_b, toolCallId, toQuestionRequest(params));
4368
+ (_c = (_b = this.callbacks).onRequest) === null || _c === void 0 || _c.call(_b, toolCallId, request);
8221
4369
  });
8222
4370
  }
8223
4371
  /**
@@ -8229,10 +4377,10 @@ var require_questions = /* @__PURE__ */ __commonJSMin(((exports) => {
8229
4377
  if (!pending) return;
8230
4378
  (_a = this.config.logger) === null || _a === void 0 || _a.warn(`Question request timed out: ${toolCallId}`);
8231
4379
  (_c = (_b = this.callbacks).onTimeout) === null || _c === void 0 || _c.call(_b, toolCallId);
8232
- if (this.config.autoCancelOnTimeout) pending.resolve({ outcome: {
4380
+ if (this.config.autoCancelOnTimeout) pending.resolve({
8233
4381
  outcome: "cancelled",
8234
4382
  reason: "timeout"
8235
- } });
4383
+ });
8236
4384
  else pending.reject(new errors_js_1.TimeoutError("question", (_d = this.config.timeout) !== null && _d !== void 0 ? _d : constants_js_1.DEFAULT_QUESTION_TIMEOUT));
8237
4385
  this.pending.delete(toolCallId);
8238
4386
  }
@@ -8249,10 +4397,10 @@ var require_questions = /* @__PURE__ */ __commonJSMin(((exports) => {
8249
4397
  }
8250
4398
  if (pending.timeoutId) clearTimeout(pending.timeoutId);
8251
4399
  (_b = this.config.logger) === null || _b === void 0 || _b.debug(`Question answered: ${toolCallId}`);
8252
- pending.resolve({ outcome: {
4400
+ pending.resolve({
8253
4401
  outcome: "submitted",
8254
- data: answers
8255
- } });
4402
+ answers
4403
+ });
8256
4404
  this.pending.delete(toolCallId);
8257
4405
  (_d = (_c = this.callbacks).onAnswered) === null || _d === void 0 || _d.call(_c, toolCallId, answers);
8258
4406
  return true;
@@ -8270,10 +4418,10 @@ var require_questions = /* @__PURE__ */ __commonJSMin(((exports) => {
8270
4418
  }
8271
4419
  if (pending.timeoutId) clearTimeout(pending.timeoutId);
8272
4420
  (_b = this.config.logger) === null || _b === void 0 || _b.debug(`Question cancelled: ${toolCallId}${reason ? ` - ${reason}` : ""}`);
8273
- pending.resolve({ outcome: {
4421
+ pending.resolve({
8274
4422
  outcome: "cancelled",
8275
4423
  reason
8276
- } });
4424
+ });
8277
4425
  this.pending.delete(toolCallId);
8278
4426
  (_d = (_c = this.callbacks).onCancelled) === null || _d === void 0 || _d.call(_c, toolCallId, reason);
8279
4427
  return true;
@@ -8283,8 +4431,8 @@ var require_questions = /* @__PURE__ */ __commonJSMin(((exports) => {
8283
4431
  */
8284
4432
  getPending() {
8285
4433
  const result = /* @__PURE__ */ new Map();
8286
- for (const [id, pending] of this.pending) if (pending.params.inputType === "question") result.set(id, {
8287
- request: toQuestionRequest(pending.params),
4434
+ for (const [id, pending] of this.pending) result.set(id, {
4435
+ request: pending.request,
8288
4436
  createdAt: pending.createdAt
8289
4437
  });
8290
4438
  return result;
@@ -8294,9 +4442,9 @@ var require_questions = /* @__PURE__ */ __commonJSMin(((exports) => {
8294
4442
  */
8295
4443
  getPendingById(toolCallId) {
8296
4444
  const pending = this.pending.get(toolCallId);
8297
- if (!pending || pending.params.inputType !== "question") return void 0;
4445
+ if (!pending) return void 0;
8298
4446
  return {
8299
- request: toQuestionRequest(pending.params),
4447
+ request: pending.request,
8300
4448
  createdAt: pending.createdAt
8301
4449
  };
8302
4450
  }
@@ -8319,10 +4467,10 @@ var require_questions = /* @__PURE__ */ __commonJSMin(((exports) => {
8319
4467
  var _a, _b, _c;
8320
4468
  for (const [toolCallId, pending] of this.pending) {
8321
4469
  if (pending.timeoutId) clearTimeout(pending.timeoutId);
8322
- pending.resolve({ outcome: {
4470
+ pending.resolve({
8323
4471
  outcome: "cancelled",
8324
4472
  reason: "cleared"
8325
- } });
4473
+ });
8326
4474
  (_b = (_a = this.callbacks).onCancelled) === null || _b === void 0 || _b.call(_a, toolCallId, "cleared");
8327
4475
  }
8328
4476
  this.pending.clear();
@@ -8689,7 +4837,7 @@ var require_client$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
8689
4837
  await this.handleExtNotification(method, params);
8690
4838
  },
8691
4839
  extMethod: async (method, params) => {
8692
- return this.handleExtMethod(method, params);
4840
+ return await this.handleExtMethod(method, params);
8693
4841
  }
8694
4842
  };
8695
4843
  }
@@ -8867,18 +5015,17 @@ var require_client$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
8867
5015
  return this.permissionManager.handleRequest(params);
8868
5016
  }
8869
5017
  async handleExtNotification(method, params) {
8870
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
5018
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
8871
5019
  if (method === constants_js_1.ExtensionMethod.ARTIFACT) {
8872
5020
  const notification = params;
8873
5021
  const artifactData = notification.artifact;
8874
5022
  console.log("[ACP-Client] Received artifact notification:", {
8875
5023
  event: notification.event,
8876
- artifactId: artifactData === null || artifactData === void 0 ? void 0 : artifactData.id,
8877
- artifactType: artifactData === null || artifactData === void 0 ? void 0 : artifactData.type,
8878
- rawMeta: artifactData === null || artifactData === void 0 ? void 0 : artifactData._meta
5024
+ artifactUri: artifactData === null || artifactData === void 0 ? void 0 : artifactData.uri,
5025
+ artifactType: artifactData === null || artifactData === void 0 ? void 0 : artifactData.type
8879
5026
  });
8880
5027
  if (notification.event === "deleted") {
8881
- const existing = this.artifactManager.get(notification.artifact.id);
5028
+ const existing = this.artifactManager.get(notification.artifact.uri);
8882
5029
  this.artifactManager.handleNotification(notification);
8883
5030
  if (existing) {
8884
5031
  await ((_b = (_a = this.options).onArtifact) === null || _b === void 0 ? void 0 : _b.call(_a, existing, "deleted"));
@@ -8887,30 +5034,28 @@ var require_client$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
8887
5034
  } else {
8888
5035
  const { artifact, event } = notification;
8889
5036
  this.artifactManager.handleNotification(notification);
8890
- const normalizedArtifact = this.artifactManager.get(artifact.id) || artifact;
8891
- console.log("[ACP-Client] Normalized artifact:", {
5037
+ const storedArtifact = this.artifactManager.get(artifact.uri) || artifact;
5038
+ console.log("[ACP-Client] Stored artifact:", {
8892
5039
  event,
8893
- artifactId: normalizedArtifact.id,
8894
- artifactType: normalizedArtifact.type,
8895
- normalizedMeta: normalizedArtifact._meta,
8896
- hasContent: !!((_c = normalizedArtifact._meta) === null || _c === void 0 ? void 0 : _c.content),
8897
- hasOverview: !!((_d = normalizedArtifact._meta) === null || _d === void 0 ? void 0 : _d.overview)
5040
+ artifactUri: storedArtifact.uri,
5041
+ artifactType: storedArtifact.type,
5042
+ hasText: storedArtifact.type === "plan" ? !!storedArtifact.text : void 0
8898
5043
  });
8899
- await ((_f = (_e = this.options).onArtifact) === null || _f === void 0 ? void 0 : _f.call(_e, normalizedArtifact, event));
5044
+ await ((_d = (_c = this.options).onArtifact) === null || _d === void 0 ? void 0 : _d.call(_c, storedArtifact, event));
8900
5045
  if (event === "created") {
8901
5046
  console.log("[ACP-Client] Emitting artifactCreated event");
8902
- this.emitter.emit("artifactCreated", normalizedArtifact);
8903
- if (normalizedArtifact.type === "plan") await ((_h = (_g = this.options).onPlanReady) === null || _h === void 0 ? void 0 : _h.call(_g, normalizedArtifact));
5047
+ this.emitter.emit("artifactCreated", storedArtifact);
5048
+ if (storedArtifact.type === "plan") await ((_f = (_e = this.options).onPlanReady) === null || _f === void 0 ? void 0 : _f.call(_e, storedArtifact));
8904
5049
  } else {
8905
5050
  console.log("[ACP-Client] Emitting artifactUpdated event");
8906
- this.emitter.emit("artifactUpdated", normalizedArtifact);
5051
+ this.emitter.emit("artifactUpdated", storedArtifact);
8907
5052
  }
8908
5053
  }
8909
5054
  return;
8910
5055
  }
8911
- if (method === "_codebuddy.ai/usage_update") {
5056
+ if (method === constants_js_1.ExtensionMethod.USAGE) {
8912
5057
  const usage = (0, extensions_js_1.parseUsageUpdate)(params);
8913
- await ((_k = (_j = this.options).onUsageUpdate) === null || _k === void 0 ? void 0 : _k.call(_j, usage));
5058
+ await ((_h = (_g = this.options).onUsageUpdate) === null || _h === void 0 ? void 0 : _h.call(_g, usage));
8914
5059
  this.emitter.emit("usageUpdate", usage);
8915
5060
  return;
8916
5061
  }
@@ -8920,17 +5065,17 @@ var require_client$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
8920
5065
  else if (notification.event === "updated") this.emitter.emit("checkpointUpdated", notification.checkpoint);
8921
5066
  return;
8922
5067
  }
8923
- await ((_m = (_l = this.options).onExtNotification) === null || _m === void 0 ? void 0 : _m.call(_l, method, params));
5068
+ await ((_k = (_j = this.options).onExtNotification) === null || _k === void 0 ? void 0 : _k.call(_j, method, params));
8924
5069
  await this.extensionManager.handleNotification(method, params);
8925
5070
  }
8926
5071
  async handleExtMethod(method, params) {
8927
5072
  var _a;
8928
- if (method === constants_js_1.ExtensionMethod.QUESTION) {
8929
- const request = params;
8930
- return await this.questionManager.handleRequest(request);
8931
- }
5073
+ if (method === constants_js_1.ExtensionMethod.QUESTION) return this.questionManager.handleRequest(params);
8932
5074
  (_a = this.options.logger) === null || _a === void 0 || _a.warn(`Unknown extension method: ${method}`);
8933
- return {};
5075
+ return {
5076
+ outcome: "cancelled",
5077
+ reason: "unknown method"
5078
+ };
8934
5079
  }
8935
5080
  ensureInitialized(operation) {
8936
5081
  if (this.state !== "initialized") throw new errors_js_1.InvalidStateError(operation, this.state, ["initialized"]);
@@ -9176,9 +5321,8 @@ var require_cloud_connection = /* @__PURE__ */ __commonJSMin(((exports) => {
9176
5321
  onArtifact: (artifact, event) => {
9177
5322
  console.log("[CloudConnection] onArtifact callback:", {
9178
5323
  event,
9179
- artifactId: artifact.id,
9180
- artifactType: artifact.type,
9181
- metaKeys: artifact._meta ? Object.keys(artifact._meta) : []
5324
+ artifactUri: artifact.uri,
5325
+ artifactType: artifact.type
9182
5326
  });
9183
5327
  if (event === "created") this.emit("artifactCreated", artifact);
9184
5328
  else if (event === "updated") this.emit("artifactUpdated", artifact);
@@ -10660,11 +6804,11 @@ var require_local_connection = /* @__PURE__ */ __commonJSMin(((exports) => {
10660
6804
  const artifact = params.artifact;
10661
6805
  console.log("[LocalConnection] Emitting artifact event:", {
10662
6806
  event,
10663
- artifactId: artifact === null || artifact === void 0 ? void 0 : artifact.id
6807
+ artifactUri: artifact === null || artifact === void 0 ? void 0 : artifact.uri
10664
6808
  });
10665
- if (artifact === null || artifact === void 0 ? void 0 : artifact.id) {
10666
- if (event === "created" || event === "updated") this.artifactCache.set(artifact.id, artifact);
10667
- else if (event === "deleted") this.artifactCache.delete(artifact.id);
6809
+ if (artifact === null || artifact === void 0 ? void 0 : artifact.uri) {
6810
+ if (event === "created" || event === "updated") this.artifactCache.set(artifact.uri, artifact);
6811
+ else if (event === "deleted") this.artifactCache.delete(artifact.uri);
10668
6812
  }
10669
6813
  if (event === "created") this.emit("artifactCreated", artifact);
10670
6814
  else if (event === "updated") this.emit("artifactUpdated", artifact);
@@ -10868,8 +7012,8 @@ var require_local_connection = /* @__PURE__ */ __commonJSMin(((exports) => {
10868
7012
  getArtifacts() {
10869
7013
  return new Map(this.artifactCache);
10870
7014
  }
10871
- getArtifact(id) {
10872
- return this.artifactCache.get(id);
7015
+ getArtifact(uri) {
7016
+ return this.artifactCache.get(uri);
10873
7017
  }
10874
7018
  getArtifactsByType(type) {
10875
7019
  return Array.from(this.artifactCache.values()).filter((artifact) => artifact.type === type);
@@ -11584,25 +7728,8 @@ var require_local_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
11584
7728
  * @returns 包含归档的 session ID 的对象
11585
7729
  */
11586
7730
  async archive(sessionId) {
11587
- var _a, _b;
11588
- this.log(`archive() called with: ${sessionId}`);
11589
- try {
11590
- const response = await this.channel.callMethod("__backend__", {
11591
- type: "backend",
11592
- requestId: `req-${Date.now()}-${Math.random().toString(36).slice(2)}`,
11593
- params: {
11594
- type: "backend:archive-session-request",
11595
- params: { sessionId }
11596
- }
11597
- }, 5e3);
11598
- if (!((_a = response.data) === null || _a === void 0 ? void 0 : _a.success)) throw new Error(((_b = response.data) === null || _b === void 0 ? void 0 : _b.error) || "Archive failed");
11599
- this.sessionCwdMap.delete(sessionId);
11600
- this.log(`Session archived: ${sessionId}`);
11601
- return { id: sessionId };
11602
- } catch (error) {
11603
- this.log(`Failed to archive session ${sessionId}:`, error);
11604
- throw error;
11605
- }
7731
+ await this.delete(sessionId);
7732
+ return { id: sessionId };
11606
7733
  }
11607
7734
  /**
11608
7735
  * 注册 sessionId → cwd 映射
@@ -11710,6 +7837,41 @@ var require_local_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
11710
7837
  }
11711
7838
  }
11712
7839
  /**
7840
+ * 选择文件夹
7841
+ * 通过 BackendService 的 __backend__ session 处理
7842
+ *
7843
+ * @param params 文件夹选择参数
7844
+ * @returns 选择结果
7845
+ */
7846
+ async pickFolder(params) {
7847
+ var _a;
7848
+ this.log("Picking folder:", params);
7849
+ try {
7850
+ const response = await this.channel.callMethod("__backend__", {
7851
+ type: "backend",
7852
+ requestId: `req-${Date.now()}-${Math.random().toString(36).slice(2)}`,
7853
+ params: {
7854
+ type: "backend:pick-folder",
7855
+ params
7856
+ }
7857
+ }, 3e4);
7858
+ this.log("pickFolder() response:", response.data);
7859
+ const data = response.data;
7860
+ return {
7861
+ folderPaths: (data === null || data === void 0 ? void 0 : data.paths) || [],
7862
+ canceled: (_a = data === null || data === void 0 ? void 0 : data.cancelled) !== null && _a !== void 0 ? _a : true,
7863
+ error: data === null || data === void 0 ? void 0 : data.error
7864
+ };
7865
+ } catch (error) {
7866
+ this.log("pickFolder() failed:", error);
7867
+ return {
7868
+ folderPaths: [],
7869
+ canceled: true,
7870
+ error: error instanceof Error ? error.message : "Unknown error"
7871
+ };
7872
+ }
7873
+ }
7874
+ /**
11713
7875
  * 获取当前工作区列表
11714
7876
  * 这是 LocalAgentProvider 特有的能力,通过 shared ACP client 发送请求,
11715
7877
  * 使用 __workspace__ session ID,由 Main Process 直接处理
@@ -12306,22 +8468,20 @@ var require_session = /* @__PURE__ */ __commonJSMin(((exports) => {
12306
8468
  });
12307
8469
  connection.on("artifactCreated", (artifact) => {
12308
8470
  console.log("[Session] Forwarding artifactCreated:", {
12309
- artifactId: artifact.id,
12310
- artifactType: artifact.type,
12311
- metaKeys: artifact._meta ? Object.keys(artifact._meta) : []
8471
+ artifactUri: artifact.uri,
8472
+ artifactType: artifact.type
12312
8473
  });
12313
8474
  this.emit("artifactCreated", artifact);
12314
8475
  });
12315
8476
  connection.on("artifactUpdated", (artifact) => {
12316
8477
  console.log("[Session] Forwarding artifactUpdated:", {
12317
- artifactId: artifact.id,
12318
- artifactType: artifact.type,
12319
- metaKeys: artifact._meta ? Object.keys(artifact._meta) : []
8478
+ artifactUri: artifact.uri,
8479
+ artifactType: artifact.type
12320
8480
  });
12321
8481
  this.emit("artifactUpdated", artifact);
12322
8482
  });
12323
8483
  connection.on("artifactDeleted", (artifact) => {
12324
- console.log("[Session] Forwarding artifactDeleted:", { artifactId: artifact.id });
8484
+ console.log("[Session] Forwarding artifactDeleted:", { artifactUri: artifact.uri });
12325
8485
  this.emit("artifactDeleted", artifact);
12326
8486
  });
12327
8487
  connection.on("permissionRequest", (request) => {
@@ -12691,6 +8851,31 @@ var require_client$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
12691
8851
  };
12692
8852
  }
12693
8853
  },
8854
+ pickFolder: async (params) => {
8855
+ var _a, _b;
8856
+ try {
8857
+ if (this.provider && this.provider.pickFolder) {
8858
+ const result = await this.provider.pickFolder(params);
8859
+ (_a = this.logger) === null || _a === void 0 || _a.info("Folder picker completed", {
8860
+ folderPaths: result.folderPaths,
8861
+ canceled: result.canceled
8862
+ });
8863
+ return result;
8864
+ }
8865
+ return {
8866
+ folderPaths: [],
8867
+ canceled: true,
8868
+ error: "Provider does not support pickFolder"
8869
+ };
8870
+ } catch (error) {
8871
+ (_b = this.logger) === null || _b === void 0 || _b.error("Failed to pick folder", error);
8872
+ return {
8873
+ folderPaths: [],
8874
+ canceled: true,
8875
+ error: error instanceof Error ? error.message : "Unknown error"
8876
+ };
8877
+ }
8878
+ },
12694
8879
  models: this.createModelsResource()
12695
8880
  };
12696
8881
  }
@@ -14685,6 +10870,28 @@ var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
14685
10870
  * 定义 IBackendProvider 接口和配置
14686
10871
  */
14687
10872
  Object.defineProperty(exports, "__esModule", { value: true });
10873
+ exports.CommodityCode = void 0;
10874
+ /**
10875
+ * 套餐代码
10876
+ */
10877
+ /**
10878
+ * TCACA_code_001_PqouKr6QWV CodeBuddy海外版免费包
10879
+ * TCACA_code_002_AkiJS3ZHF5 CodeBuddy海外版Pro版本包-包月/CodeBuddy Pro Plan - Monthly:
10880
+ * TCACA_code_006_DbXS0lrypC CodeBuddy海外版一次性免费赠送2周的Pro版本包/CodeBuddy One-time Free 2-Week Pro Plan Trial
10881
+ * TCACA_code_007_nzdH5h4Nl0 CodeBuddy海外版运营裂变包/CodeBuddy Growth Plan
10882
+ * TCACA_code_003_FAnt7lcmRT CodeBuddy海外版Pro版本包-包年/CodeBuddy Pro Plan - Yearly
10883
+ * TCACA_code_008_cfWoLwvjU4 赠送月包
10884
+ */
10885
+ var CommodityCode;
10886
+ (function(CommodityCode) {
10887
+ CommodityCode["free"] = "TCACA_code_001_PqouKr6QWV";
10888
+ CommodityCode["proMon"] = "TCACA_code_002_AkiJS3ZHF5";
10889
+ CommodityCode["gift"] = "TCACA_code_006_DbXS0lrypC";
10890
+ CommodityCode["activity"] = "TCACA_code_007_nzdH5h4Nl0";
10891
+ CommodityCode["proYear"] = "TCACA_code_003_FAnt7lcmRT";
10892
+ CommodityCode["freeMon"] = "TCACA_code_008_cfWoLwvjU4";
10893
+ CommodityCode["extra"] = "TCACA_code_009_0XmEQc2xOf";
10894
+ })(CommodityCode || (exports.CommodityCode = CommodityCode = {}));
14688
10895
  }));
14689
10896
 
14690
10897
  //#endregion
@@ -14750,10 +10957,11 @@ var require_backend_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
14750
10957
  Object.defineProperty(exports, "__esModule", { value: true });
14751
10958
  exports.BackendProvider = void 0;
14752
10959
  exports.createBackendProvider = createBackendProvider;
10960
+ const types_1 = require_types();
14753
10961
  /** 获取当前域名的登录页面 URL */
14754
10962
  const getLoginUrl = () => `${window.location.origin}/login`;
14755
10963
  /** 获取当前域名的账号选择页面 URL */
14756
- const getSelectAccountUrl = () => `${window.location.origin}/select`;
10964
+ const getSelectAccountUrl = () => `${window.location.origin}/login/select`;
14757
10965
  /** localStorage 中存储选中账号 ID 的 key */
14758
10966
  const SELECTED_ACCOUNT_KEY = "CODEBUDDY_IDE_SELECTED_ACCOUNT_ID";
14759
10967
  /**
@@ -14897,7 +11105,7 @@ var require_backend_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
14897
11105
  if (account.type === "personal") return account.uid === selectedAccountId;
14898
11106
  return account.enterpriseId === selectedAccountId;
14899
11107
  });
14900
- if (selectedAccount) {
11108
+ if (selectedAccount) try {
14901
11109
  const plan = await this.getCurrentPlan();
14902
11110
  const editionType = this.getEditionDisplayType(selectedAccount.type, plan.isPro);
14903
11111
  console.log("account", {
@@ -14910,6 +11118,8 @@ var require_backend_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
14910
11118
  ...plan,
14911
11119
  editionType
14912
11120
  };
11121
+ } catch (error) {
11122
+ return { ...selectedAccount };
14913
11123
  }
14914
11124
  }
14915
11125
  if (accounts.length === 1) {
@@ -14930,7 +11140,7 @@ var require_backend_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
14930
11140
  };
14931
11141
  }
14932
11142
  const redirectUrl = encodeURIComponent(window.location.href);
14933
- window.location.href = `${getSelectAccountUrl()}?redirect_uri=${redirectUrl}`;
11143
+ window.location.href = `${getSelectAccountUrl()}?platform=website&state=0&redirect_uri=${redirectUrl}`;
14934
11144
  return null;
14935
11145
  } catch (error) {
14936
11146
  console.error("[BackendProvider] getAccount failed:", error);
@@ -14985,8 +11195,8 @@ var require_backend_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
14985
11195
  const result = await response.json();
14986
11196
  const resources = ((_b = (_a = result === null || result === void 0 ? void 0 : result.Response) === null || _a === void 0 ? void 0 : _a.Data) === null || _b === void 0 ? void 0 : _b.Accounts) || (result === null || result === void 0 ? void 0 : result.Accounts) || [];
14987
11197
  if (!resources || resources.length === 0) return defaultPlan;
14988
- const proPlan = resources.find((r) => r.PackageCode === "proYear" || r.PackageCode === "proMon");
14989
- const trialPlan = resources.find((r) => r.PackageCode === "gift");
11198
+ const proPlan = resources.find((r) => r.PackageCode === types_1.CommodityCode.proYear || r.PackageCode === types_1.CommodityCode.proMon);
11199
+ const trialPlan = resources.find((r) => r.PackageCode === types_1.CommodityCode.gift);
14990
11200
  const activePlan = proPlan || trialPlan;
14991
11201
  if (activePlan) return {
14992
11202
  isPro: !!proPlan,
@@ -15020,7 +11230,7 @@ var require_backend_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
15020
11230
  */
15021
11231
  async login() {
15022
11232
  const redirectUrl = encodeURIComponent(window.location.href);
15023
- window.location.href = `${getLoginUrl()}?redirect_uri=${redirectUrl}&platform=website`;
11233
+ window.location.href = `${getLoginUrl()}?platform=website&state=0&redirect_uri=${redirectUrl}`;
15024
11234
  }
15025
11235
  /**
15026
11236
  * 登出账号
@@ -15497,4 +11707,5 @@ Object.defineProperty(exports, 'isCloudAgentState', {
15497
11707
  get: function () {
15498
11708
  return import_common.isCloudAgentState;
15499
11709
  }
15500
- });
11710
+ });
11711
+ //# sourceMappingURL=index.cjs.map