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