csdn-im 0.1.4

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