@reinconsole/erc8004 0.1.0

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