@atproto/xrpc 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4119 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ Client: () => Client,
24
+ ResponseType: () => ResponseType,
25
+ ResponseTypeNames: () => ResponseTypeNames,
26
+ ResponseTypeStrings: () => ResponseTypeStrings,
27
+ ServiceClient: () => ServiceClient,
28
+ XRPCError: () => XRPCError,
29
+ XRPCResponse: () => XRPCResponse,
30
+ default: () => src_default,
31
+ errorResponseBody: () => errorResponseBody
32
+ });
33
+ module.exports = __toCommonJS(src_exports);
34
+
35
+ // ../../node_modules/zod/lib/index.mjs
36
+ var util;
37
+ (function(util2) {
38
+ util2.assertEqual = (val) => val;
39
+ function assertIs(_arg) {
40
+ }
41
+ util2.assertIs = assertIs;
42
+ function assertNever(_x) {
43
+ throw new Error();
44
+ }
45
+ util2.assertNever = assertNever;
46
+ util2.arrayToEnum = (items) => {
47
+ const obj = {};
48
+ for (const item of items) {
49
+ obj[item] = item;
50
+ }
51
+ return obj;
52
+ };
53
+ util2.getValidEnumValues = (obj) => {
54
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
55
+ const filtered = {};
56
+ for (const k of validKeys) {
57
+ filtered[k] = obj[k];
58
+ }
59
+ return util2.objectValues(filtered);
60
+ };
61
+ util2.objectValues = (obj) => {
62
+ return util2.objectKeys(obj).map(function(e) {
63
+ return obj[e];
64
+ });
65
+ };
66
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
67
+ const keys = [];
68
+ for (const key in object2) {
69
+ if (Object.prototype.hasOwnProperty.call(object2, key)) {
70
+ keys.push(key);
71
+ }
72
+ }
73
+ return keys;
74
+ };
75
+ util2.find = (arr, checker) => {
76
+ for (const item of arr) {
77
+ if (checker(item))
78
+ return item;
79
+ }
80
+ return void 0;
81
+ };
82
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
83
+ function joinValues(array2, separator = " | ") {
84
+ return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
85
+ }
86
+ util2.joinValues = joinValues;
87
+ util2.jsonStringifyReplacer = (_, value) => {
88
+ if (typeof value === "bigint") {
89
+ return value.toString();
90
+ }
91
+ return value;
92
+ };
93
+ })(util || (util = {}));
94
+ var ZodParsedType = util.arrayToEnum([
95
+ "string",
96
+ "nan",
97
+ "number",
98
+ "integer",
99
+ "float",
100
+ "boolean",
101
+ "date",
102
+ "bigint",
103
+ "symbol",
104
+ "function",
105
+ "undefined",
106
+ "null",
107
+ "array",
108
+ "object",
109
+ "unknown",
110
+ "promise",
111
+ "void",
112
+ "never",
113
+ "map",
114
+ "set"
115
+ ]);
116
+ var getParsedType = (data) => {
117
+ const t = typeof data;
118
+ switch (t) {
119
+ case "undefined":
120
+ return ZodParsedType.undefined;
121
+ case "string":
122
+ return ZodParsedType.string;
123
+ case "number":
124
+ return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
125
+ case "boolean":
126
+ return ZodParsedType.boolean;
127
+ case "function":
128
+ return ZodParsedType.function;
129
+ case "bigint":
130
+ return ZodParsedType.bigint;
131
+ case "object":
132
+ if (Array.isArray(data)) {
133
+ return ZodParsedType.array;
134
+ }
135
+ if (data === null) {
136
+ return ZodParsedType.null;
137
+ }
138
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
139
+ return ZodParsedType.promise;
140
+ }
141
+ if (typeof Map !== "undefined" && data instanceof Map) {
142
+ return ZodParsedType.map;
143
+ }
144
+ if (typeof Set !== "undefined" && data instanceof Set) {
145
+ return ZodParsedType.set;
146
+ }
147
+ if (typeof Date !== "undefined" && data instanceof Date) {
148
+ return ZodParsedType.date;
149
+ }
150
+ return ZodParsedType.object;
151
+ default:
152
+ return ZodParsedType.unknown;
153
+ }
154
+ };
155
+ var ZodIssueCode = util.arrayToEnum([
156
+ "invalid_type",
157
+ "invalid_literal",
158
+ "custom",
159
+ "invalid_union",
160
+ "invalid_union_discriminator",
161
+ "invalid_enum_value",
162
+ "unrecognized_keys",
163
+ "invalid_arguments",
164
+ "invalid_return_type",
165
+ "invalid_date",
166
+ "invalid_string",
167
+ "too_small",
168
+ "too_big",
169
+ "invalid_intersection_types",
170
+ "not_multiple_of"
171
+ ]);
172
+ var quotelessJson = (obj) => {
173
+ const json = JSON.stringify(obj, null, 2);
174
+ return json.replace(/"([^"]+)":/g, "$1:");
175
+ };
176
+ var ZodError = class extends Error {
177
+ constructor(issues) {
178
+ super();
179
+ this.issues = [];
180
+ this.addIssue = (sub) => {
181
+ this.issues = [...this.issues, sub];
182
+ };
183
+ this.addIssues = (subs = []) => {
184
+ this.issues = [...this.issues, ...subs];
185
+ };
186
+ const actualProto = new.target.prototype;
187
+ if (Object.setPrototypeOf) {
188
+ Object.setPrototypeOf(this, actualProto);
189
+ } else {
190
+ this.__proto__ = actualProto;
191
+ }
192
+ this.name = "ZodError";
193
+ this.issues = issues;
194
+ }
195
+ get errors() {
196
+ return this.issues;
197
+ }
198
+ format(_mapper) {
199
+ const mapper = _mapper || function(issue) {
200
+ return issue.message;
201
+ };
202
+ const fieldErrors = { _errors: [] };
203
+ const processError = (error) => {
204
+ for (const issue of error.issues) {
205
+ if (issue.code === "invalid_union") {
206
+ issue.unionErrors.map(processError);
207
+ } else if (issue.code === "invalid_return_type") {
208
+ processError(issue.returnTypeError);
209
+ } else if (issue.code === "invalid_arguments") {
210
+ processError(issue.argumentsError);
211
+ } else if (issue.path.length === 0) {
212
+ fieldErrors._errors.push(mapper(issue));
213
+ } else {
214
+ let curr = fieldErrors;
215
+ let i = 0;
216
+ while (i < issue.path.length) {
217
+ const el = issue.path[i];
218
+ const terminal = i === issue.path.length - 1;
219
+ if (!terminal) {
220
+ curr[el] = curr[el] || { _errors: [] };
221
+ } else {
222
+ curr[el] = curr[el] || { _errors: [] };
223
+ curr[el]._errors.push(mapper(issue));
224
+ }
225
+ curr = curr[el];
226
+ i++;
227
+ }
228
+ }
229
+ }
230
+ };
231
+ processError(this);
232
+ return fieldErrors;
233
+ }
234
+ toString() {
235
+ return this.message;
236
+ }
237
+ get message() {
238
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
239
+ }
240
+ get isEmpty() {
241
+ return this.issues.length === 0;
242
+ }
243
+ flatten(mapper = (issue) => issue.message) {
244
+ const fieldErrors = {};
245
+ const formErrors = [];
246
+ for (const sub of this.issues) {
247
+ if (sub.path.length > 0) {
248
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
249
+ fieldErrors[sub.path[0]].push(mapper(sub));
250
+ } else {
251
+ formErrors.push(mapper(sub));
252
+ }
253
+ }
254
+ return { formErrors, fieldErrors };
255
+ }
256
+ get formErrors() {
257
+ return this.flatten();
258
+ }
259
+ };
260
+ ZodError.create = (issues) => {
261
+ const error = new ZodError(issues);
262
+ return error;
263
+ };
264
+ var errorMap = (issue, _ctx) => {
265
+ let message;
266
+ switch (issue.code) {
267
+ case ZodIssueCode.invalid_type:
268
+ if (issue.received === ZodParsedType.undefined) {
269
+ message = "Required";
270
+ } else {
271
+ message = `Expected ${issue.expected}, received ${issue.received}`;
272
+ }
273
+ break;
274
+ case ZodIssueCode.invalid_literal:
275
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
276
+ break;
277
+ case ZodIssueCode.unrecognized_keys:
278
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
279
+ break;
280
+ case ZodIssueCode.invalid_union:
281
+ message = `Invalid input`;
282
+ break;
283
+ case ZodIssueCode.invalid_union_discriminator:
284
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
285
+ break;
286
+ case ZodIssueCode.invalid_enum_value:
287
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
288
+ break;
289
+ case ZodIssueCode.invalid_arguments:
290
+ message = `Invalid function arguments`;
291
+ break;
292
+ case ZodIssueCode.invalid_return_type:
293
+ message = `Invalid function return type`;
294
+ break;
295
+ case ZodIssueCode.invalid_date:
296
+ message = `Invalid date`;
297
+ break;
298
+ case ZodIssueCode.invalid_string:
299
+ if (typeof issue.validation === "object") {
300
+ if ("startsWith" in issue.validation) {
301
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
302
+ } else if ("endsWith" in issue.validation) {
303
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
304
+ } else {
305
+ util.assertNever(issue.validation);
306
+ }
307
+ } else if (issue.validation !== "regex") {
308
+ message = `Invalid ${issue.validation}`;
309
+ } else {
310
+ message = "Invalid";
311
+ }
312
+ break;
313
+ case ZodIssueCode.too_small:
314
+ if (issue.type === "array")
315
+ message = `Array must contain ${issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
316
+ else if (issue.type === "string")
317
+ message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
318
+ else if (issue.type === "number")
319
+ message = `Number must be greater than ${issue.inclusive ? `or equal to ` : ``}${issue.minimum}`;
320
+ else if (issue.type === "date")
321
+ message = `Date must be greater than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.minimum)}`;
322
+ else
323
+ message = "Invalid input";
324
+ break;
325
+ case ZodIssueCode.too_big:
326
+ if (issue.type === "array")
327
+ message = `Array must contain ${issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
328
+ else if (issue.type === "string")
329
+ message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
330
+ else if (issue.type === "number")
331
+ message = `Number must be less than ${issue.inclusive ? `or equal to ` : ``}${issue.maximum}`;
332
+ else if (issue.type === "date")
333
+ message = `Date must be smaller than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.maximum)}`;
334
+ else
335
+ message = "Invalid input";
336
+ break;
337
+ case ZodIssueCode.custom:
338
+ message = `Invalid input`;
339
+ break;
340
+ case ZodIssueCode.invalid_intersection_types:
341
+ message = `Intersection results could not be merged`;
342
+ break;
343
+ case ZodIssueCode.not_multiple_of:
344
+ message = `Number must be a multiple of ${issue.multipleOf}`;
345
+ break;
346
+ default:
347
+ message = _ctx.defaultError;
348
+ util.assertNever(issue);
349
+ }
350
+ return { message };
351
+ };
352
+ var overrideErrorMap = errorMap;
353
+ function setErrorMap(map) {
354
+ overrideErrorMap = map;
355
+ }
356
+ function getErrorMap() {
357
+ return overrideErrorMap;
358
+ }
359
+ var makeIssue = (params2) => {
360
+ const { data, path, errorMaps, issueData } = params2;
361
+ const fullPath = [...path, ...issueData.path || []];
362
+ const fullIssue = {
363
+ ...issueData,
364
+ path: fullPath
365
+ };
366
+ let errorMessage = "";
367
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
368
+ for (const map of maps) {
369
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
370
+ }
371
+ return {
372
+ ...issueData,
373
+ path: fullPath,
374
+ message: issueData.message || errorMessage
375
+ };
376
+ };
377
+ var EMPTY_PATH = [];
378
+ function addIssueToContext(ctx, issueData) {
379
+ const issue = makeIssue({
380
+ issueData,
381
+ data: ctx.data,
382
+ path: ctx.path,
383
+ errorMaps: [
384
+ ctx.common.contextualErrorMap,
385
+ ctx.schemaErrorMap,
386
+ getErrorMap(),
387
+ errorMap
388
+ ].filter((x) => !!x)
389
+ });
390
+ ctx.common.issues.push(issue);
391
+ }
392
+ var ParseStatus = class {
393
+ constructor() {
394
+ this.value = "valid";
395
+ }
396
+ dirty() {
397
+ if (this.value === "valid")
398
+ this.value = "dirty";
399
+ }
400
+ abort() {
401
+ if (this.value !== "aborted")
402
+ this.value = "aborted";
403
+ }
404
+ static mergeArray(status, results) {
405
+ const arrayValue = [];
406
+ for (const s of results) {
407
+ if (s.status === "aborted")
408
+ return INVALID;
409
+ if (s.status === "dirty")
410
+ status.dirty();
411
+ arrayValue.push(s.value);
412
+ }
413
+ return { status: status.value, value: arrayValue };
414
+ }
415
+ static async mergeObjectAsync(status, pairs) {
416
+ const syncPairs = [];
417
+ for (const pair of pairs) {
418
+ syncPairs.push({
419
+ key: await pair.key,
420
+ value: await pair.value
421
+ });
422
+ }
423
+ return ParseStatus.mergeObjectSync(status, syncPairs);
424
+ }
425
+ static mergeObjectSync(status, pairs) {
426
+ const finalObject = {};
427
+ for (const pair of pairs) {
428
+ const { key, value } = pair;
429
+ if (key.status === "aborted")
430
+ return INVALID;
431
+ if (value.status === "aborted")
432
+ return INVALID;
433
+ if (key.status === "dirty")
434
+ status.dirty();
435
+ if (value.status === "dirty")
436
+ status.dirty();
437
+ if (typeof value.value !== "undefined" || pair.alwaysSet) {
438
+ finalObject[key.value] = value.value;
439
+ }
440
+ }
441
+ return { status: status.value, value: finalObject };
442
+ }
443
+ };
444
+ var INVALID = Object.freeze({
445
+ status: "aborted"
446
+ });
447
+ var DIRTY = (value) => ({ status: "dirty", value });
448
+ var OK = (value) => ({ status: "valid", value });
449
+ var isAborted = (x) => x.status === "aborted";
450
+ var isDirty = (x) => x.status === "dirty";
451
+ var isValid = (x) => x.status === "valid";
452
+ var isAsync = (x) => typeof Promise !== void 0 && x instanceof Promise;
453
+ var errorUtil;
454
+ (function(errorUtil2) {
455
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
456
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
457
+ })(errorUtil || (errorUtil = {}));
458
+ var ParseInputLazyPath = class {
459
+ constructor(parent, value, path, key) {
460
+ this.parent = parent;
461
+ this.data = value;
462
+ this._path = path;
463
+ this._key = key;
464
+ }
465
+ get path() {
466
+ return this._path.concat(this._key);
467
+ }
468
+ };
469
+ var handleResult = (ctx, result) => {
470
+ if (isValid(result)) {
471
+ return { success: true, data: result.value };
472
+ } else {
473
+ if (!ctx.common.issues.length) {
474
+ throw new Error("Validation failed but no issues detected.");
475
+ }
476
+ const error = new ZodError(ctx.common.issues);
477
+ return { success: false, error };
478
+ }
479
+ };
480
+ function processCreateParams(params2) {
481
+ if (!params2)
482
+ return {};
483
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params2;
484
+ if (errorMap2 && (invalid_type_error || required_error)) {
485
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
486
+ }
487
+ if (errorMap2)
488
+ return { errorMap: errorMap2, description };
489
+ const customMap = (iss, ctx) => {
490
+ if (iss.code !== "invalid_type")
491
+ return { message: ctx.defaultError };
492
+ if (typeof ctx.data === "undefined") {
493
+ return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
494
+ }
495
+ return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
496
+ };
497
+ return { errorMap: customMap, description };
498
+ }
499
+ var ZodType = class {
500
+ constructor(def) {
501
+ this.spa = this.safeParseAsync;
502
+ this.superRefine = this._refinement;
503
+ this._def = def;
504
+ this.parse = this.parse.bind(this);
505
+ this.safeParse = this.safeParse.bind(this);
506
+ this.parseAsync = this.parseAsync.bind(this);
507
+ this.safeParseAsync = this.safeParseAsync.bind(this);
508
+ this.spa = this.spa.bind(this);
509
+ this.refine = this.refine.bind(this);
510
+ this.refinement = this.refinement.bind(this);
511
+ this.superRefine = this.superRefine.bind(this);
512
+ this.optional = this.optional.bind(this);
513
+ this.nullable = this.nullable.bind(this);
514
+ this.nullish = this.nullish.bind(this);
515
+ this.array = this.array.bind(this);
516
+ this.promise = this.promise.bind(this);
517
+ this.or = this.or.bind(this);
518
+ this.and = this.and.bind(this);
519
+ this.transform = this.transform.bind(this);
520
+ this.default = this.default.bind(this);
521
+ this.describe = this.describe.bind(this);
522
+ this.isNullable = this.isNullable.bind(this);
523
+ this.isOptional = this.isOptional.bind(this);
524
+ }
525
+ get description() {
526
+ return this._def.description;
527
+ }
528
+ _getType(input) {
529
+ return getParsedType(input.data);
530
+ }
531
+ _getOrReturnCtx(input, ctx) {
532
+ return ctx || {
533
+ common: input.parent.common,
534
+ data: input.data,
535
+ parsedType: getParsedType(input.data),
536
+ schemaErrorMap: this._def.errorMap,
537
+ path: input.path,
538
+ parent: input.parent
539
+ };
540
+ }
541
+ _processInputParams(input) {
542
+ return {
543
+ status: new ParseStatus(),
544
+ ctx: {
545
+ common: input.parent.common,
546
+ data: input.data,
547
+ parsedType: getParsedType(input.data),
548
+ schemaErrorMap: this._def.errorMap,
549
+ path: input.path,
550
+ parent: input.parent
551
+ }
552
+ };
553
+ }
554
+ _parseSync(input) {
555
+ const result = this._parse(input);
556
+ if (isAsync(result)) {
557
+ throw new Error("Synchronous parse encountered promise.");
558
+ }
559
+ return result;
560
+ }
561
+ _parseAsync(input) {
562
+ const result = this._parse(input);
563
+ return Promise.resolve(result);
564
+ }
565
+ parse(data, params2) {
566
+ const result = this.safeParse(data, params2);
567
+ if (result.success)
568
+ return result.data;
569
+ throw result.error;
570
+ }
571
+ safeParse(data, params2) {
572
+ var _a;
573
+ const ctx = {
574
+ common: {
575
+ issues: [],
576
+ async: (_a = params2 === null || params2 === void 0 ? void 0 : params2.async) !== null && _a !== void 0 ? _a : false,
577
+ contextualErrorMap: params2 === null || params2 === void 0 ? void 0 : params2.errorMap
578
+ },
579
+ path: (params2 === null || params2 === void 0 ? void 0 : params2.path) || [],
580
+ schemaErrorMap: this._def.errorMap,
581
+ parent: null,
582
+ data,
583
+ parsedType: getParsedType(data)
584
+ };
585
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
586
+ return handleResult(ctx, result);
587
+ }
588
+ async parseAsync(data, params2) {
589
+ const result = await this.safeParseAsync(data, params2);
590
+ if (result.success)
591
+ return result.data;
592
+ throw result.error;
593
+ }
594
+ async safeParseAsync(data, params2) {
595
+ const ctx = {
596
+ common: {
597
+ issues: [],
598
+ contextualErrorMap: params2 === null || params2 === void 0 ? void 0 : params2.errorMap,
599
+ async: true
600
+ },
601
+ path: (params2 === null || params2 === void 0 ? void 0 : params2.path) || [],
602
+ schemaErrorMap: this._def.errorMap,
603
+ parent: null,
604
+ data,
605
+ parsedType: getParsedType(data)
606
+ };
607
+ const maybeAsyncResult = this._parse({ data, path: [], parent: ctx });
608
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
609
+ return handleResult(ctx, result);
610
+ }
611
+ refine(check, message) {
612
+ const getIssueProperties = (val) => {
613
+ if (typeof message === "string" || typeof message === "undefined") {
614
+ return { message };
615
+ } else if (typeof message === "function") {
616
+ return message(val);
617
+ } else {
618
+ return message;
619
+ }
620
+ };
621
+ return this._refinement((val, ctx) => {
622
+ const result = check(val);
623
+ const setError = () => ctx.addIssue({
624
+ code: ZodIssueCode.custom,
625
+ ...getIssueProperties(val)
626
+ });
627
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
628
+ return result.then((data) => {
629
+ if (!data) {
630
+ setError();
631
+ return false;
632
+ } else {
633
+ return true;
634
+ }
635
+ });
636
+ }
637
+ if (!result) {
638
+ setError();
639
+ return false;
640
+ } else {
641
+ return true;
642
+ }
643
+ });
644
+ }
645
+ refinement(check, refinementData) {
646
+ return this._refinement((val, ctx) => {
647
+ if (!check(val)) {
648
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
649
+ return false;
650
+ } else {
651
+ return true;
652
+ }
653
+ });
654
+ }
655
+ _refinement(refinement) {
656
+ return new ZodEffects({
657
+ schema: this,
658
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
659
+ effect: { type: "refinement", refinement }
660
+ });
661
+ }
662
+ optional() {
663
+ return ZodOptional.create(this);
664
+ }
665
+ nullable() {
666
+ return ZodNullable.create(this);
667
+ }
668
+ nullish() {
669
+ return this.optional().nullable();
670
+ }
671
+ array() {
672
+ return ZodArray.create(this);
673
+ }
674
+ promise() {
675
+ return ZodPromise.create(this);
676
+ }
677
+ or(option) {
678
+ return ZodUnion.create([this, option]);
679
+ }
680
+ and(incoming) {
681
+ return ZodIntersection.create(this, incoming);
682
+ }
683
+ transform(transform) {
684
+ return new ZodEffects({
685
+ schema: this,
686
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
687
+ effect: { type: "transform", transform }
688
+ });
689
+ }
690
+ default(def) {
691
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
692
+ return new ZodDefault({
693
+ innerType: this,
694
+ defaultValue: defaultValueFunc,
695
+ typeName: ZodFirstPartyTypeKind.ZodDefault
696
+ });
697
+ }
698
+ brand() {
699
+ return new ZodBranded({
700
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
701
+ type: this,
702
+ ...processCreateParams(void 0)
703
+ });
704
+ }
705
+ describe(description) {
706
+ const This = this.constructor;
707
+ return new This({
708
+ ...this._def,
709
+ description
710
+ });
711
+ }
712
+ isOptional() {
713
+ return this.safeParse(void 0).success;
714
+ }
715
+ isNullable() {
716
+ return this.safeParse(null).success;
717
+ }
718
+ };
719
+ var cuidRegex = /^c[^\s-]{8,}$/i;
720
+ var uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
721
+ var emailRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
722
+ var ZodString = class extends ZodType {
723
+ constructor() {
724
+ super(...arguments);
725
+ this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
726
+ validation,
727
+ code: ZodIssueCode.invalid_string,
728
+ ...errorUtil.errToObj(message)
729
+ });
730
+ this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
731
+ this.trim = () => new ZodString({
732
+ ...this._def,
733
+ checks: [...this._def.checks, { kind: "trim" }]
734
+ });
735
+ }
736
+ _parse(input) {
737
+ const parsedType = this._getType(input);
738
+ if (parsedType !== ZodParsedType.string) {
739
+ const ctx2 = this._getOrReturnCtx(input);
740
+ addIssueToContext(
741
+ ctx2,
742
+ {
743
+ code: ZodIssueCode.invalid_type,
744
+ expected: ZodParsedType.string,
745
+ received: ctx2.parsedType
746
+ }
747
+ );
748
+ return INVALID;
749
+ }
750
+ const status = new ParseStatus();
751
+ let ctx = void 0;
752
+ for (const check of this._def.checks) {
753
+ if (check.kind === "min") {
754
+ if (input.data.length < check.value) {
755
+ ctx = this._getOrReturnCtx(input, ctx);
756
+ addIssueToContext(ctx, {
757
+ code: ZodIssueCode.too_small,
758
+ minimum: check.value,
759
+ type: "string",
760
+ inclusive: true,
761
+ message: check.message
762
+ });
763
+ status.dirty();
764
+ }
765
+ } else if (check.kind === "max") {
766
+ if (input.data.length > check.value) {
767
+ ctx = this._getOrReturnCtx(input, ctx);
768
+ addIssueToContext(ctx, {
769
+ code: ZodIssueCode.too_big,
770
+ maximum: check.value,
771
+ type: "string",
772
+ inclusive: true,
773
+ message: check.message
774
+ });
775
+ status.dirty();
776
+ }
777
+ } else if (check.kind === "email") {
778
+ if (!emailRegex.test(input.data)) {
779
+ ctx = this._getOrReturnCtx(input, ctx);
780
+ addIssueToContext(ctx, {
781
+ validation: "email",
782
+ code: ZodIssueCode.invalid_string,
783
+ message: check.message
784
+ });
785
+ status.dirty();
786
+ }
787
+ } else if (check.kind === "uuid") {
788
+ if (!uuidRegex.test(input.data)) {
789
+ ctx = this._getOrReturnCtx(input, ctx);
790
+ addIssueToContext(ctx, {
791
+ validation: "uuid",
792
+ code: ZodIssueCode.invalid_string,
793
+ message: check.message
794
+ });
795
+ status.dirty();
796
+ }
797
+ } else if (check.kind === "cuid") {
798
+ if (!cuidRegex.test(input.data)) {
799
+ ctx = this._getOrReturnCtx(input, ctx);
800
+ addIssueToContext(ctx, {
801
+ validation: "cuid",
802
+ code: ZodIssueCode.invalid_string,
803
+ message: check.message
804
+ });
805
+ status.dirty();
806
+ }
807
+ } else if (check.kind === "url") {
808
+ try {
809
+ new URL(input.data);
810
+ } catch (_a) {
811
+ ctx = this._getOrReturnCtx(input, ctx);
812
+ addIssueToContext(ctx, {
813
+ validation: "url",
814
+ code: ZodIssueCode.invalid_string,
815
+ message: check.message
816
+ });
817
+ status.dirty();
818
+ }
819
+ } else if (check.kind === "regex") {
820
+ check.regex.lastIndex = 0;
821
+ const testResult = check.regex.test(input.data);
822
+ if (!testResult) {
823
+ ctx = this._getOrReturnCtx(input, ctx);
824
+ addIssueToContext(ctx, {
825
+ validation: "regex",
826
+ code: ZodIssueCode.invalid_string,
827
+ message: check.message
828
+ });
829
+ status.dirty();
830
+ }
831
+ } else if (check.kind === "trim") {
832
+ input.data = input.data.trim();
833
+ } else if (check.kind === "startsWith") {
834
+ if (!input.data.startsWith(check.value)) {
835
+ ctx = this._getOrReturnCtx(input, ctx);
836
+ addIssueToContext(ctx, {
837
+ code: ZodIssueCode.invalid_string,
838
+ validation: { startsWith: check.value },
839
+ message: check.message
840
+ });
841
+ status.dirty();
842
+ }
843
+ } else if (check.kind === "endsWith") {
844
+ if (!input.data.endsWith(check.value)) {
845
+ ctx = this._getOrReturnCtx(input, ctx);
846
+ addIssueToContext(ctx, {
847
+ code: ZodIssueCode.invalid_string,
848
+ validation: { endsWith: check.value },
849
+ message: check.message
850
+ });
851
+ status.dirty();
852
+ }
853
+ } else {
854
+ util.assertNever(check);
855
+ }
856
+ }
857
+ return { status: status.value, value: input.data };
858
+ }
859
+ _addCheck(check) {
860
+ return new ZodString({
861
+ ...this._def,
862
+ checks: [...this._def.checks, check]
863
+ });
864
+ }
865
+ email(message) {
866
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
867
+ }
868
+ url(message) {
869
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
870
+ }
871
+ uuid(message) {
872
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
873
+ }
874
+ cuid(message) {
875
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
876
+ }
877
+ regex(regex, message) {
878
+ return this._addCheck({
879
+ kind: "regex",
880
+ regex,
881
+ ...errorUtil.errToObj(message)
882
+ });
883
+ }
884
+ startsWith(value, message) {
885
+ return this._addCheck({
886
+ kind: "startsWith",
887
+ value,
888
+ ...errorUtil.errToObj(message)
889
+ });
890
+ }
891
+ endsWith(value, message) {
892
+ return this._addCheck({
893
+ kind: "endsWith",
894
+ value,
895
+ ...errorUtil.errToObj(message)
896
+ });
897
+ }
898
+ min(minLength, message) {
899
+ return this._addCheck({
900
+ kind: "min",
901
+ value: minLength,
902
+ ...errorUtil.errToObj(message)
903
+ });
904
+ }
905
+ max(maxLength, message) {
906
+ return this._addCheck({
907
+ kind: "max",
908
+ value: maxLength,
909
+ ...errorUtil.errToObj(message)
910
+ });
911
+ }
912
+ length(len, message) {
913
+ return this.min(len, message).max(len, message);
914
+ }
915
+ get isEmail() {
916
+ return !!this._def.checks.find((ch) => ch.kind === "email");
917
+ }
918
+ get isURL() {
919
+ return !!this._def.checks.find((ch) => ch.kind === "url");
920
+ }
921
+ get isUUID() {
922
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
923
+ }
924
+ get isCUID() {
925
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
926
+ }
927
+ get minLength() {
928
+ let min = null;
929
+ for (const ch of this._def.checks) {
930
+ if (ch.kind === "min") {
931
+ if (min === null || ch.value > min)
932
+ min = ch.value;
933
+ }
934
+ }
935
+ return min;
936
+ }
937
+ get maxLength() {
938
+ let max = null;
939
+ for (const ch of this._def.checks) {
940
+ if (ch.kind === "max") {
941
+ if (max === null || ch.value < max)
942
+ max = ch.value;
943
+ }
944
+ }
945
+ return max;
946
+ }
947
+ };
948
+ ZodString.create = (params2) => {
949
+ return new ZodString({
950
+ checks: [],
951
+ typeName: ZodFirstPartyTypeKind.ZodString,
952
+ ...processCreateParams(params2)
953
+ });
954
+ };
955
+ function floatSafeRemainder(val, step) {
956
+ const valDecCount = (val.toString().split(".")[1] || "").length;
957
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
958
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
959
+ const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
960
+ const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
961
+ return valInt % stepInt / Math.pow(10, decCount);
962
+ }
963
+ var ZodNumber = class extends ZodType {
964
+ constructor() {
965
+ super(...arguments);
966
+ this.min = this.gte;
967
+ this.max = this.lte;
968
+ this.step = this.multipleOf;
969
+ }
970
+ _parse(input) {
971
+ const parsedType = this._getType(input);
972
+ if (parsedType !== ZodParsedType.number) {
973
+ const ctx2 = this._getOrReturnCtx(input);
974
+ addIssueToContext(ctx2, {
975
+ code: ZodIssueCode.invalid_type,
976
+ expected: ZodParsedType.number,
977
+ received: ctx2.parsedType
978
+ });
979
+ return INVALID;
980
+ }
981
+ let ctx = void 0;
982
+ const status = new ParseStatus();
983
+ for (const check of this._def.checks) {
984
+ if (check.kind === "int") {
985
+ if (!util.isInteger(input.data)) {
986
+ ctx = this._getOrReturnCtx(input, ctx);
987
+ addIssueToContext(ctx, {
988
+ code: ZodIssueCode.invalid_type,
989
+ expected: "integer",
990
+ received: "float",
991
+ message: check.message
992
+ });
993
+ status.dirty();
994
+ }
995
+ } else if (check.kind === "min") {
996
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
997
+ if (tooSmall) {
998
+ ctx = this._getOrReturnCtx(input, ctx);
999
+ addIssueToContext(ctx, {
1000
+ code: ZodIssueCode.too_small,
1001
+ minimum: check.value,
1002
+ type: "number",
1003
+ inclusive: check.inclusive,
1004
+ message: check.message
1005
+ });
1006
+ status.dirty();
1007
+ }
1008
+ } else if (check.kind === "max") {
1009
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1010
+ if (tooBig) {
1011
+ ctx = this._getOrReturnCtx(input, ctx);
1012
+ addIssueToContext(ctx, {
1013
+ code: ZodIssueCode.too_big,
1014
+ maximum: check.value,
1015
+ type: "number",
1016
+ inclusive: check.inclusive,
1017
+ message: check.message
1018
+ });
1019
+ status.dirty();
1020
+ }
1021
+ } else if (check.kind === "multipleOf") {
1022
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1023
+ ctx = this._getOrReturnCtx(input, ctx);
1024
+ addIssueToContext(ctx, {
1025
+ code: ZodIssueCode.not_multiple_of,
1026
+ multipleOf: check.value,
1027
+ message: check.message
1028
+ });
1029
+ status.dirty();
1030
+ }
1031
+ } else {
1032
+ util.assertNever(check);
1033
+ }
1034
+ }
1035
+ return { status: status.value, value: input.data };
1036
+ }
1037
+ gte(value, message) {
1038
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1039
+ }
1040
+ gt(value, message) {
1041
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1042
+ }
1043
+ lte(value, message) {
1044
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1045
+ }
1046
+ lt(value, message) {
1047
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1048
+ }
1049
+ setLimit(kind, value, inclusive, message) {
1050
+ return new ZodNumber({
1051
+ ...this._def,
1052
+ checks: [
1053
+ ...this._def.checks,
1054
+ {
1055
+ kind,
1056
+ value,
1057
+ inclusive,
1058
+ message: errorUtil.toString(message)
1059
+ }
1060
+ ]
1061
+ });
1062
+ }
1063
+ _addCheck(check) {
1064
+ return new ZodNumber({
1065
+ ...this._def,
1066
+ checks: [...this._def.checks, check]
1067
+ });
1068
+ }
1069
+ int(message) {
1070
+ return this._addCheck({
1071
+ kind: "int",
1072
+ message: errorUtil.toString(message)
1073
+ });
1074
+ }
1075
+ positive(message) {
1076
+ return this._addCheck({
1077
+ kind: "min",
1078
+ value: 0,
1079
+ inclusive: false,
1080
+ message: errorUtil.toString(message)
1081
+ });
1082
+ }
1083
+ negative(message) {
1084
+ return this._addCheck({
1085
+ kind: "max",
1086
+ value: 0,
1087
+ inclusive: false,
1088
+ message: errorUtil.toString(message)
1089
+ });
1090
+ }
1091
+ nonpositive(message) {
1092
+ return this._addCheck({
1093
+ kind: "max",
1094
+ value: 0,
1095
+ inclusive: true,
1096
+ message: errorUtil.toString(message)
1097
+ });
1098
+ }
1099
+ nonnegative(message) {
1100
+ return this._addCheck({
1101
+ kind: "min",
1102
+ value: 0,
1103
+ inclusive: true,
1104
+ message: errorUtil.toString(message)
1105
+ });
1106
+ }
1107
+ multipleOf(value, message) {
1108
+ return this._addCheck({
1109
+ kind: "multipleOf",
1110
+ value,
1111
+ message: errorUtil.toString(message)
1112
+ });
1113
+ }
1114
+ get minValue() {
1115
+ let min = null;
1116
+ for (const ch of this._def.checks) {
1117
+ if (ch.kind === "min") {
1118
+ if (min === null || ch.value > min)
1119
+ min = ch.value;
1120
+ }
1121
+ }
1122
+ return min;
1123
+ }
1124
+ get maxValue() {
1125
+ let max = null;
1126
+ for (const ch of this._def.checks) {
1127
+ if (ch.kind === "max") {
1128
+ if (max === null || ch.value < max)
1129
+ max = ch.value;
1130
+ }
1131
+ }
1132
+ return max;
1133
+ }
1134
+ get isInt() {
1135
+ return !!this._def.checks.find((ch) => ch.kind === "int");
1136
+ }
1137
+ };
1138
+ ZodNumber.create = (params2) => {
1139
+ return new ZodNumber({
1140
+ checks: [],
1141
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1142
+ ...processCreateParams(params2)
1143
+ });
1144
+ };
1145
+ var ZodBigInt = class extends ZodType {
1146
+ _parse(input) {
1147
+ const parsedType = this._getType(input);
1148
+ if (parsedType !== ZodParsedType.bigint) {
1149
+ const ctx = this._getOrReturnCtx(input);
1150
+ addIssueToContext(ctx, {
1151
+ code: ZodIssueCode.invalid_type,
1152
+ expected: ZodParsedType.bigint,
1153
+ received: ctx.parsedType
1154
+ });
1155
+ return INVALID;
1156
+ }
1157
+ return OK(input.data);
1158
+ }
1159
+ };
1160
+ ZodBigInt.create = (params2) => {
1161
+ return new ZodBigInt({
1162
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
1163
+ ...processCreateParams(params2)
1164
+ });
1165
+ };
1166
+ var ZodBoolean = class extends ZodType {
1167
+ _parse(input) {
1168
+ const parsedType = this._getType(input);
1169
+ if (parsedType !== ZodParsedType.boolean) {
1170
+ const ctx = this._getOrReturnCtx(input);
1171
+ addIssueToContext(ctx, {
1172
+ code: ZodIssueCode.invalid_type,
1173
+ expected: ZodParsedType.boolean,
1174
+ received: ctx.parsedType
1175
+ });
1176
+ return INVALID;
1177
+ }
1178
+ return OK(input.data);
1179
+ }
1180
+ };
1181
+ ZodBoolean.create = (params2) => {
1182
+ return new ZodBoolean({
1183
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
1184
+ ...processCreateParams(params2)
1185
+ });
1186
+ };
1187
+ var ZodDate = class extends ZodType {
1188
+ _parse(input) {
1189
+ const parsedType = this._getType(input);
1190
+ if (parsedType !== ZodParsedType.date) {
1191
+ const ctx2 = this._getOrReturnCtx(input);
1192
+ addIssueToContext(ctx2, {
1193
+ code: ZodIssueCode.invalid_type,
1194
+ expected: ZodParsedType.date,
1195
+ received: ctx2.parsedType
1196
+ });
1197
+ return INVALID;
1198
+ }
1199
+ if (isNaN(input.data.getTime())) {
1200
+ const ctx2 = this._getOrReturnCtx(input);
1201
+ addIssueToContext(ctx2, {
1202
+ code: ZodIssueCode.invalid_date
1203
+ });
1204
+ return INVALID;
1205
+ }
1206
+ const status = new ParseStatus();
1207
+ let ctx = void 0;
1208
+ for (const check of this._def.checks) {
1209
+ if (check.kind === "min") {
1210
+ if (input.data.getTime() < check.value) {
1211
+ ctx = this._getOrReturnCtx(input, ctx);
1212
+ addIssueToContext(ctx, {
1213
+ code: ZodIssueCode.too_small,
1214
+ message: check.message,
1215
+ inclusive: true,
1216
+ minimum: check.value,
1217
+ type: "date"
1218
+ });
1219
+ status.dirty();
1220
+ }
1221
+ } else if (check.kind === "max") {
1222
+ if (input.data.getTime() > check.value) {
1223
+ ctx = this._getOrReturnCtx(input, ctx);
1224
+ addIssueToContext(ctx, {
1225
+ code: ZodIssueCode.too_big,
1226
+ message: check.message,
1227
+ inclusive: true,
1228
+ maximum: check.value,
1229
+ type: "date"
1230
+ });
1231
+ status.dirty();
1232
+ }
1233
+ } else {
1234
+ util.assertNever(check);
1235
+ }
1236
+ }
1237
+ return {
1238
+ status: status.value,
1239
+ value: new Date(input.data.getTime())
1240
+ };
1241
+ }
1242
+ _addCheck(check) {
1243
+ return new ZodDate({
1244
+ ...this._def,
1245
+ checks: [...this._def.checks, check]
1246
+ });
1247
+ }
1248
+ min(minDate, message) {
1249
+ return this._addCheck({
1250
+ kind: "min",
1251
+ value: minDate.getTime(),
1252
+ message: errorUtil.toString(message)
1253
+ });
1254
+ }
1255
+ max(maxDate, message) {
1256
+ return this._addCheck({
1257
+ kind: "max",
1258
+ value: maxDate.getTime(),
1259
+ message: errorUtil.toString(message)
1260
+ });
1261
+ }
1262
+ get minDate() {
1263
+ let min = null;
1264
+ for (const ch of this._def.checks) {
1265
+ if (ch.kind === "min") {
1266
+ if (min === null || ch.value > min)
1267
+ min = ch.value;
1268
+ }
1269
+ }
1270
+ return min != null ? new Date(min) : null;
1271
+ }
1272
+ get maxDate() {
1273
+ let max = null;
1274
+ for (const ch of this._def.checks) {
1275
+ if (ch.kind === "max") {
1276
+ if (max === null || ch.value < max)
1277
+ max = ch.value;
1278
+ }
1279
+ }
1280
+ return max != null ? new Date(max) : null;
1281
+ }
1282
+ };
1283
+ ZodDate.create = (params2) => {
1284
+ return new ZodDate({
1285
+ checks: [],
1286
+ typeName: ZodFirstPartyTypeKind.ZodDate,
1287
+ ...processCreateParams(params2)
1288
+ });
1289
+ };
1290
+ var ZodUndefined = class extends ZodType {
1291
+ _parse(input) {
1292
+ const parsedType = this._getType(input);
1293
+ if (parsedType !== ZodParsedType.undefined) {
1294
+ const ctx = this._getOrReturnCtx(input);
1295
+ addIssueToContext(ctx, {
1296
+ code: ZodIssueCode.invalid_type,
1297
+ expected: ZodParsedType.undefined,
1298
+ received: ctx.parsedType
1299
+ });
1300
+ return INVALID;
1301
+ }
1302
+ return OK(input.data);
1303
+ }
1304
+ };
1305
+ ZodUndefined.create = (params2) => {
1306
+ return new ZodUndefined({
1307
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
1308
+ ...processCreateParams(params2)
1309
+ });
1310
+ };
1311
+ var ZodNull = class extends ZodType {
1312
+ _parse(input) {
1313
+ const parsedType = this._getType(input);
1314
+ if (parsedType !== ZodParsedType.null) {
1315
+ const ctx = this._getOrReturnCtx(input);
1316
+ addIssueToContext(ctx, {
1317
+ code: ZodIssueCode.invalid_type,
1318
+ expected: ZodParsedType.null,
1319
+ received: ctx.parsedType
1320
+ });
1321
+ return INVALID;
1322
+ }
1323
+ return OK(input.data);
1324
+ }
1325
+ };
1326
+ ZodNull.create = (params2) => {
1327
+ return new ZodNull({
1328
+ typeName: ZodFirstPartyTypeKind.ZodNull,
1329
+ ...processCreateParams(params2)
1330
+ });
1331
+ };
1332
+ var ZodAny = class extends ZodType {
1333
+ constructor() {
1334
+ super(...arguments);
1335
+ this._any = true;
1336
+ }
1337
+ _parse(input) {
1338
+ return OK(input.data);
1339
+ }
1340
+ };
1341
+ ZodAny.create = (params2) => {
1342
+ return new ZodAny({
1343
+ typeName: ZodFirstPartyTypeKind.ZodAny,
1344
+ ...processCreateParams(params2)
1345
+ });
1346
+ };
1347
+ var ZodUnknown = class extends ZodType {
1348
+ constructor() {
1349
+ super(...arguments);
1350
+ this._unknown = true;
1351
+ }
1352
+ _parse(input) {
1353
+ return OK(input.data);
1354
+ }
1355
+ };
1356
+ ZodUnknown.create = (params2) => {
1357
+ return new ZodUnknown({
1358
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
1359
+ ...processCreateParams(params2)
1360
+ });
1361
+ };
1362
+ var ZodNever = class extends ZodType {
1363
+ _parse(input) {
1364
+ const ctx = this._getOrReturnCtx(input);
1365
+ addIssueToContext(ctx, {
1366
+ code: ZodIssueCode.invalid_type,
1367
+ expected: ZodParsedType.never,
1368
+ received: ctx.parsedType
1369
+ });
1370
+ return INVALID;
1371
+ }
1372
+ };
1373
+ ZodNever.create = (params2) => {
1374
+ return new ZodNever({
1375
+ typeName: ZodFirstPartyTypeKind.ZodNever,
1376
+ ...processCreateParams(params2)
1377
+ });
1378
+ };
1379
+ var ZodVoid = class extends ZodType {
1380
+ _parse(input) {
1381
+ const parsedType = this._getType(input);
1382
+ if (parsedType !== ZodParsedType.undefined) {
1383
+ const ctx = this._getOrReturnCtx(input);
1384
+ addIssueToContext(ctx, {
1385
+ code: ZodIssueCode.invalid_type,
1386
+ expected: ZodParsedType.void,
1387
+ received: ctx.parsedType
1388
+ });
1389
+ return INVALID;
1390
+ }
1391
+ return OK(input.data);
1392
+ }
1393
+ };
1394
+ ZodVoid.create = (params2) => {
1395
+ return new ZodVoid({
1396
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
1397
+ ...processCreateParams(params2)
1398
+ });
1399
+ };
1400
+ var ZodArray = class extends ZodType {
1401
+ _parse(input) {
1402
+ const { ctx, status } = this._processInputParams(input);
1403
+ const def = this._def;
1404
+ if (ctx.parsedType !== ZodParsedType.array) {
1405
+ addIssueToContext(ctx, {
1406
+ code: ZodIssueCode.invalid_type,
1407
+ expected: ZodParsedType.array,
1408
+ received: ctx.parsedType
1409
+ });
1410
+ return INVALID;
1411
+ }
1412
+ if (def.minLength !== null) {
1413
+ if (ctx.data.length < def.minLength.value) {
1414
+ addIssueToContext(ctx, {
1415
+ code: ZodIssueCode.too_small,
1416
+ minimum: def.minLength.value,
1417
+ type: "array",
1418
+ inclusive: true,
1419
+ message: def.minLength.message
1420
+ });
1421
+ status.dirty();
1422
+ }
1423
+ }
1424
+ if (def.maxLength !== null) {
1425
+ if (ctx.data.length > def.maxLength.value) {
1426
+ addIssueToContext(ctx, {
1427
+ code: ZodIssueCode.too_big,
1428
+ maximum: def.maxLength.value,
1429
+ type: "array",
1430
+ inclusive: true,
1431
+ message: def.maxLength.message
1432
+ });
1433
+ status.dirty();
1434
+ }
1435
+ }
1436
+ if (ctx.common.async) {
1437
+ return Promise.all(ctx.data.map((item, i) => {
1438
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
1439
+ })).then((result2) => {
1440
+ return ParseStatus.mergeArray(status, result2);
1441
+ });
1442
+ }
1443
+ const result = ctx.data.map((item, i) => {
1444
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
1445
+ });
1446
+ return ParseStatus.mergeArray(status, result);
1447
+ }
1448
+ get element() {
1449
+ return this._def.type;
1450
+ }
1451
+ min(minLength, message) {
1452
+ return new ZodArray({
1453
+ ...this._def,
1454
+ minLength: { value: minLength, message: errorUtil.toString(message) }
1455
+ });
1456
+ }
1457
+ max(maxLength, message) {
1458
+ return new ZodArray({
1459
+ ...this._def,
1460
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
1461
+ });
1462
+ }
1463
+ length(len, message) {
1464
+ return this.min(len, message).max(len, message);
1465
+ }
1466
+ nonempty(message) {
1467
+ return this.min(1, message);
1468
+ }
1469
+ };
1470
+ ZodArray.create = (schema, params2) => {
1471
+ return new ZodArray({
1472
+ type: schema,
1473
+ minLength: null,
1474
+ maxLength: null,
1475
+ typeName: ZodFirstPartyTypeKind.ZodArray,
1476
+ ...processCreateParams(params2)
1477
+ });
1478
+ };
1479
+ var objectUtil;
1480
+ (function(objectUtil2) {
1481
+ objectUtil2.mergeShapes = (first, second) => {
1482
+ return {
1483
+ ...first,
1484
+ ...second
1485
+ };
1486
+ };
1487
+ })(objectUtil || (objectUtil = {}));
1488
+ var AugmentFactory = (def) => (augmentation) => {
1489
+ return new ZodObject({
1490
+ ...def,
1491
+ shape: () => ({
1492
+ ...def.shape(),
1493
+ ...augmentation
1494
+ })
1495
+ });
1496
+ };
1497
+ function deepPartialify(schema) {
1498
+ if (schema instanceof ZodObject) {
1499
+ const newShape = {};
1500
+ for (const key in schema.shape) {
1501
+ const fieldSchema = schema.shape[key];
1502
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
1503
+ }
1504
+ return new ZodObject({
1505
+ ...schema._def,
1506
+ shape: () => newShape
1507
+ });
1508
+ } else if (schema instanceof ZodArray) {
1509
+ return ZodArray.create(deepPartialify(schema.element));
1510
+ } else if (schema instanceof ZodOptional) {
1511
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
1512
+ } else if (schema instanceof ZodNullable) {
1513
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
1514
+ } else if (schema instanceof ZodTuple) {
1515
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
1516
+ } else {
1517
+ return schema;
1518
+ }
1519
+ }
1520
+ var ZodObject = class extends ZodType {
1521
+ constructor() {
1522
+ super(...arguments);
1523
+ this._cached = null;
1524
+ this.nonstrict = this.passthrough;
1525
+ this.augment = AugmentFactory(this._def);
1526
+ this.extend = AugmentFactory(this._def);
1527
+ }
1528
+ _getCached() {
1529
+ if (this._cached !== null)
1530
+ return this._cached;
1531
+ const shape = this._def.shape();
1532
+ const keys = util.objectKeys(shape);
1533
+ return this._cached = { shape, keys };
1534
+ }
1535
+ _parse(input) {
1536
+ const parsedType = this._getType(input);
1537
+ if (parsedType !== ZodParsedType.object) {
1538
+ const ctx2 = this._getOrReturnCtx(input);
1539
+ addIssueToContext(ctx2, {
1540
+ code: ZodIssueCode.invalid_type,
1541
+ expected: ZodParsedType.object,
1542
+ received: ctx2.parsedType
1543
+ });
1544
+ return INVALID;
1545
+ }
1546
+ const { status, ctx } = this._processInputParams(input);
1547
+ const { shape, keys: shapeKeys } = this._getCached();
1548
+ const extraKeys = [];
1549
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
1550
+ for (const key in ctx.data) {
1551
+ if (!shapeKeys.includes(key)) {
1552
+ extraKeys.push(key);
1553
+ }
1554
+ }
1555
+ }
1556
+ const pairs = [];
1557
+ for (const key of shapeKeys) {
1558
+ const keyValidator = shape[key];
1559
+ const value = ctx.data[key];
1560
+ pairs.push({
1561
+ key: { status: "valid", value: key },
1562
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
1563
+ alwaysSet: key in ctx.data
1564
+ });
1565
+ }
1566
+ if (this._def.catchall instanceof ZodNever) {
1567
+ const unknownKeys = this._def.unknownKeys;
1568
+ if (unknownKeys === "passthrough") {
1569
+ for (const key of extraKeys) {
1570
+ pairs.push({
1571
+ key: { status: "valid", value: key },
1572
+ value: { status: "valid", value: ctx.data[key] }
1573
+ });
1574
+ }
1575
+ } else if (unknownKeys === "strict") {
1576
+ if (extraKeys.length > 0) {
1577
+ addIssueToContext(ctx, {
1578
+ code: ZodIssueCode.unrecognized_keys,
1579
+ keys: extraKeys
1580
+ });
1581
+ status.dirty();
1582
+ }
1583
+ } else if (unknownKeys === "strip")
1584
+ ;
1585
+ else {
1586
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
1587
+ }
1588
+ } else {
1589
+ const catchall = this._def.catchall;
1590
+ for (const key of extraKeys) {
1591
+ const value = ctx.data[key];
1592
+ pairs.push({
1593
+ key: { status: "valid", value: key },
1594
+ value: catchall._parse(
1595
+ new ParseInputLazyPath(ctx, value, ctx.path, key)
1596
+ ),
1597
+ alwaysSet: key in ctx.data
1598
+ });
1599
+ }
1600
+ }
1601
+ if (ctx.common.async) {
1602
+ return Promise.resolve().then(async () => {
1603
+ const syncPairs = [];
1604
+ for (const pair of pairs) {
1605
+ const key = await pair.key;
1606
+ syncPairs.push({
1607
+ key,
1608
+ value: await pair.value,
1609
+ alwaysSet: pair.alwaysSet
1610
+ });
1611
+ }
1612
+ return syncPairs;
1613
+ }).then((syncPairs) => {
1614
+ return ParseStatus.mergeObjectSync(status, syncPairs);
1615
+ });
1616
+ } else {
1617
+ return ParseStatus.mergeObjectSync(status, pairs);
1618
+ }
1619
+ }
1620
+ get shape() {
1621
+ return this._def.shape();
1622
+ }
1623
+ strict(message) {
1624
+ errorUtil.errToObj;
1625
+ return new ZodObject({
1626
+ ...this._def,
1627
+ unknownKeys: "strict",
1628
+ ...message !== void 0 ? {
1629
+ errorMap: (issue, ctx) => {
1630
+ var _a, _b, _c, _d;
1631
+ const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
1632
+ if (issue.code === "unrecognized_keys")
1633
+ return {
1634
+ message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
1635
+ };
1636
+ return {
1637
+ message: defaultError
1638
+ };
1639
+ }
1640
+ } : {}
1641
+ });
1642
+ }
1643
+ strip() {
1644
+ return new ZodObject({
1645
+ ...this._def,
1646
+ unknownKeys: "strip"
1647
+ });
1648
+ }
1649
+ passthrough() {
1650
+ return new ZodObject({
1651
+ ...this._def,
1652
+ unknownKeys: "passthrough"
1653
+ });
1654
+ }
1655
+ setKey(key, schema) {
1656
+ return this.augment({ [key]: schema });
1657
+ }
1658
+ merge(merging) {
1659
+ const merged = new ZodObject({
1660
+ unknownKeys: merging._def.unknownKeys,
1661
+ catchall: merging._def.catchall,
1662
+ shape: () => objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
1663
+ typeName: ZodFirstPartyTypeKind.ZodObject
1664
+ });
1665
+ return merged;
1666
+ }
1667
+ catchall(index) {
1668
+ return new ZodObject({
1669
+ ...this._def,
1670
+ catchall: index
1671
+ });
1672
+ }
1673
+ pick(mask) {
1674
+ const shape = {};
1675
+ util.objectKeys(mask).map((key) => {
1676
+ if (this.shape[key])
1677
+ shape[key] = this.shape[key];
1678
+ });
1679
+ return new ZodObject({
1680
+ ...this._def,
1681
+ shape: () => shape
1682
+ });
1683
+ }
1684
+ omit(mask) {
1685
+ const shape = {};
1686
+ util.objectKeys(this.shape).map((key) => {
1687
+ if (util.objectKeys(mask).indexOf(key) === -1) {
1688
+ shape[key] = this.shape[key];
1689
+ }
1690
+ });
1691
+ return new ZodObject({
1692
+ ...this._def,
1693
+ shape: () => shape
1694
+ });
1695
+ }
1696
+ deepPartial() {
1697
+ return deepPartialify(this);
1698
+ }
1699
+ partial(mask) {
1700
+ const newShape = {};
1701
+ if (mask) {
1702
+ util.objectKeys(this.shape).map((key) => {
1703
+ if (util.objectKeys(mask).indexOf(key) === -1) {
1704
+ newShape[key] = this.shape[key];
1705
+ } else {
1706
+ newShape[key] = this.shape[key].optional();
1707
+ }
1708
+ });
1709
+ return new ZodObject({
1710
+ ...this._def,
1711
+ shape: () => newShape
1712
+ });
1713
+ } else {
1714
+ for (const key in this.shape) {
1715
+ const fieldSchema = this.shape[key];
1716
+ newShape[key] = fieldSchema.optional();
1717
+ }
1718
+ }
1719
+ return new ZodObject({
1720
+ ...this._def,
1721
+ shape: () => newShape
1722
+ });
1723
+ }
1724
+ required() {
1725
+ const newShape = {};
1726
+ for (const key in this.shape) {
1727
+ const fieldSchema = this.shape[key];
1728
+ let newField = fieldSchema;
1729
+ while (newField instanceof ZodOptional) {
1730
+ newField = newField._def.innerType;
1731
+ }
1732
+ newShape[key] = newField;
1733
+ }
1734
+ return new ZodObject({
1735
+ ...this._def,
1736
+ shape: () => newShape
1737
+ });
1738
+ }
1739
+ keyof() {
1740
+ return createZodEnum(util.objectKeys(this.shape));
1741
+ }
1742
+ };
1743
+ ZodObject.create = (shape, params2) => {
1744
+ return new ZodObject({
1745
+ shape: () => shape,
1746
+ unknownKeys: "strip",
1747
+ catchall: ZodNever.create(),
1748
+ typeName: ZodFirstPartyTypeKind.ZodObject,
1749
+ ...processCreateParams(params2)
1750
+ });
1751
+ };
1752
+ ZodObject.strictCreate = (shape, params2) => {
1753
+ return new ZodObject({
1754
+ shape: () => shape,
1755
+ unknownKeys: "strict",
1756
+ catchall: ZodNever.create(),
1757
+ typeName: ZodFirstPartyTypeKind.ZodObject,
1758
+ ...processCreateParams(params2)
1759
+ });
1760
+ };
1761
+ ZodObject.lazycreate = (shape, params2) => {
1762
+ return new ZodObject({
1763
+ shape,
1764
+ unknownKeys: "strip",
1765
+ catchall: ZodNever.create(),
1766
+ typeName: ZodFirstPartyTypeKind.ZodObject,
1767
+ ...processCreateParams(params2)
1768
+ });
1769
+ };
1770
+ var ZodUnion = class extends ZodType {
1771
+ _parse(input) {
1772
+ const { ctx } = this._processInputParams(input);
1773
+ const options = this._def.options;
1774
+ function handleResults(results) {
1775
+ for (const result of results) {
1776
+ if (result.result.status === "valid") {
1777
+ return result.result;
1778
+ }
1779
+ }
1780
+ for (const result of results) {
1781
+ if (result.result.status === "dirty") {
1782
+ ctx.common.issues.push(...result.ctx.common.issues);
1783
+ return result.result;
1784
+ }
1785
+ }
1786
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
1787
+ addIssueToContext(ctx, {
1788
+ code: ZodIssueCode.invalid_union,
1789
+ unionErrors
1790
+ });
1791
+ return INVALID;
1792
+ }
1793
+ if (ctx.common.async) {
1794
+ return Promise.all(options.map(async (option) => {
1795
+ const childCtx = {
1796
+ ...ctx,
1797
+ common: {
1798
+ ...ctx.common,
1799
+ issues: []
1800
+ },
1801
+ parent: null
1802
+ };
1803
+ return {
1804
+ result: await option._parseAsync({
1805
+ data: ctx.data,
1806
+ path: ctx.path,
1807
+ parent: childCtx
1808
+ }),
1809
+ ctx: childCtx
1810
+ };
1811
+ })).then(handleResults);
1812
+ } else {
1813
+ let dirty = void 0;
1814
+ const issues = [];
1815
+ for (const option of options) {
1816
+ const childCtx = {
1817
+ ...ctx,
1818
+ common: {
1819
+ ...ctx.common,
1820
+ issues: []
1821
+ },
1822
+ parent: null
1823
+ };
1824
+ const result = option._parseSync({
1825
+ data: ctx.data,
1826
+ path: ctx.path,
1827
+ parent: childCtx
1828
+ });
1829
+ if (result.status === "valid") {
1830
+ return result;
1831
+ } else if (result.status === "dirty" && !dirty) {
1832
+ dirty = { result, ctx: childCtx };
1833
+ }
1834
+ if (childCtx.common.issues.length) {
1835
+ issues.push(childCtx.common.issues);
1836
+ }
1837
+ }
1838
+ if (dirty) {
1839
+ ctx.common.issues.push(...dirty.ctx.common.issues);
1840
+ return dirty.result;
1841
+ }
1842
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
1843
+ addIssueToContext(ctx, {
1844
+ code: ZodIssueCode.invalid_union,
1845
+ unionErrors
1846
+ });
1847
+ return INVALID;
1848
+ }
1849
+ }
1850
+ get options() {
1851
+ return this._def.options;
1852
+ }
1853
+ };
1854
+ ZodUnion.create = (types, params2) => {
1855
+ return new ZodUnion({
1856
+ options: types,
1857
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
1858
+ ...processCreateParams(params2)
1859
+ });
1860
+ };
1861
+ var ZodDiscriminatedUnion = class extends ZodType {
1862
+ _parse(input) {
1863
+ const { ctx } = this._processInputParams(input);
1864
+ if (ctx.parsedType !== ZodParsedType.object) {
1865
+ addIssueToContext(ctx, {
1866
+ code: ZodIssueCode.invalid_type,
1867
+ expected: ZodParsedType.object,
1868
+ received: ctx.parsedType
1869
+ });
1870
+ return INVALID;
1871
+ }
1872
+ const discriminator = this.discriminator;
1873
+ const discriminatorValue = ctx.data[discriminator];
1874
+ const option = this.options.get(discriminatorValue);
1875
+ if (!option) {
1876
+ addIssueToContext(ctx, {
1877
+ code: ZodIssueCode.invalid_union_discriminator,
1878
+ options: this.validDiscriminatorValues,
1879
+ path: [discriminator]
1880
+ });
1881
+ return INVALID;
1882
+ }
1883
+ if (ctx.common.async) {
1884
+ return option._parseAsync({
1885
+ data: ctx.data,
1886
+ path: ctx.path,
1887
+ parent: ctx
1888
+ });
1889
+ } else {
1890
+ return option._parseSync({
1891
+ data: ctx.data,
1892
+ path: ctx.path,
1893
+ parent: ctx
1894
+ });
1895
+ }
1896
+ }
1897
+ get discriminator() {
1898
+ return this._def.discriminator;
1899
+ }
1900
+ get validDiscriminatorValues() {
1901
+ return Array.from(this.options.keys());
1902
+ }
1903
+ get options() {
1904
+ return this._def.options;
1905
+ }
1906
+ static create(discriminator, types, params2) {
1907
+ const options = /* @__PURE__ */ new Map();
1908
+ try {
1909
+ types.forEach((type) => {
1910
+ const discriminatorValue = type.shape[discriminator].value;
1911
+ options.set(discriminatorValue, type);
1912
+ });
1913
+ } catch (e) {
1914
+ throw new Error("The discriminator value could not be extracted from all the provided schemas");
1915
+ }
1916
+ if (options.size !== types.length) {
1917
+ throw new Error("Some of the discriminator values are not unique");
1918
+ }
1919
+ return new ZodDiscriminatedUnion({
1920
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
1921
+ discriminator,
1922
+ options,
1923
+ ...processCreateParams(params2)
1924
+ });
1925
+ }
1926
+ };
1927
+ function mergeValues(a, b) {
1928
+ const aType = getParsedType(a);
1929
+ const bType = getParsedType(b);
1930
+ if (a === b) {
1931
+ return { valid: true, data: a };
1932
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
1933
+ const bKeys = util.objectKeys(b);
1934
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
1935
+ const newObj = { ...a, ...b };
1936
+ for (const key of sharedKeys) {
1937
+ const sharedValue = mergeValues(a[key], b[key]);
1938
+ if (!sharedValue.valid) {
1939
+ return { valid: false };
1940
+ }
1941
+ newObj[key] = sharedValue.data;
1942
+ }
1943
+ return { valid: true, data: newObj };
1944
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
1945
+ if (a.length !== b.length) {
1946
+ return { valid: false };
1947
+ }
1948
+ const newArray = [];
1949
+ for (let index = 0; index < a.length; index++) {
1950
+ const itemA = a[index];
1951
+ const itemB = b[index];
1952
+ const sharedValue = mergeValues(itemA, itemB);
1953
+ if (!sharedValue.valid) {
1954
+ return { valid: false };
1955
+ }
1956
+ newArray.push(sharedValue.data);
1957
+ }
1958
+ return { valid: true, data: newArray };
1959
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
1960
+ return { valid: true, data: a };
1961
+ } else {
1962
+ return { valid: false };
1963
+ }
1964
+ }
1965
+ var ZodIntersection = class extends ZodType {
1966
+ _parse(input) {
1967
+ const { status, ctx } = this._processInputParams(input);
1968
+ const handleParsed = (parsedLeft, parsedRight) => {
1969
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
1970
+ return INVALID;
1971
+ }
1972
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
1973
+ if (!merged.valid) {
1974
+ addIssueToContext(ctx, {
1975
+ code: ZodIssueCode.invalid_intersection_types
1976
+ });
1977
+ return INVALID;
1978
+ }
1979
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
1980
+ status.dirty();
1981
+ }
1982
+ return { status: status.value, value: merged.data };
1983
+ };
1984
+ if (ctx.common.async) {
1985
+ return Promise.all([
1986
+ this._def.left._parseAsync({
1987
+ data: ctx.data,
1988
+ path: ctx.path,
1989
+ parent: ctx
1990
+ }),
1991
+ this._def.right._parseAsync({
1992
+ data: ctx.data,
1993
+ path: ctx.path,
1994
+ parent: ctx
1995
+ })
1996
+ ]).then(([left, right]) => handleParsed(left, right));
1997
+ } else {
1998
+ return handleParsed(this._def.left._parseSync({
1999
+ data: ctx.data,
2000
+ path: ctx.path,
2001
+ parent: ctx
2002
+ }), this._def.right._parseSync({
2003
+ data: ctx.data,
2004
+ path: ctx.path,
2005
+ parent: ctx
2006
+ }));
2007
+ }
2008
+ }
2009
+ };
2010
+ ZodIntersection.create = (left, right, params2) => {
2011
+ return new ZodIntersection({
2012
+ left,
2013
+ right,
2014
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
2015
+ ...processCreateParams(params2)
2016
+ });
2017
+ };
2018
+ var ZodTuple = class extends ZodType {
2019
+ _parse(input) {
2020
+ const { status, ctx } = this._processInputParams(input);
2021
+ if (ctx.parsedType !== ZodParsedType.array) {
2022
+ addIssueToContext(ctx, {
2023
+ code: ZodIssueCode.invalid_type,
2024
+ expected: ZodParsedType.array,
2025
+ received: ctx.parsedType
2026
+ });
2027
+ return INVALID;
2028
+ }
2029
+ if (ctx.data.length < this._def.items.length) {
2030
+ addIssueToContext(ctx, {
2031
+ code: ZodIssueCode.too_small,
2032
+ minimum: this._def.items.length,
2033
+ inclusive: true,
2034
+ type: "array"
2035
+ });
2036
+ return INVALID;
2037
+ }
2038
+ const rest = this._def.rest;
2039
+ if (!rest && ctx.data.length > this._def.items.length) {
2040
+ addIssueToContext(ctx, {
2041
+ code: ZodIssueCode.too_big,
2042
+ maximum: this._def.items.length,
2043
+ inclusive: true,
2044
+ type: "array"
2045
+ });
2046
+ status.dirty();
2047
+ }
2048
+ const items = ctx.data.map((item, itemIndex) => {
2049
+ const schema = this._def.items[itemIndex] || this._def.rest;
2050
+ if (!schema)
2051
+ return null;
2052
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2053
+ }).filter((x) => !!x);
2054
+ if (ctx.common.async) {
2055
+ return Promise.all(items).then((results) => {
2056
+ return ParseStatus.mergeArray(status, results);
2057
+ });
2058
+ } else {
2059
+ return ParseStatus.mergeArray(status, items);
2060
+ }
2061
+ }
2062
+ get items() {
2063
+ return this._def.items;
2064
+ }
2065
+ rest(rest) {
2066
+ return new ZodTuple({
2067
+ ...this._def,
2068
+ rest
2069
+ });
2070
+ }
2071
+ };
2072
+ ZodTuple.create = (schemas, params2) => {
2073
+ if (!Array.isArray(schemas)) {
2074
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2075
+ }
2076
+ return new ZodTuple({
2077
+ items: schemas,
2078
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
2079
+ rest: null,
2080
+ ...processCreateParams(params2)
2081
+ });
2082
+ };
2083
+ var ZodRecord = class extends ZodType {
2084
+ get keySchema() {
2085
+ return this._def.keyType;
2086
+ }
2087
+ get valueSchema() {
2088
+ return this._def.valueType;
2089
+ }
2090
+ _parse(input) {
2091
+ const { status, ctx } = this._processInputParams(input);
2092
+ if (ctx.parsedType !== ZodParsedType.object) {
2093
+ addIssueToContext(ctx, {
2094
+ code: ZodIssueCode.invalid_type,
2095
+ expected: ZodParsedType.object,
2096
+ received: ctx.parsedType
2097
+ });
2098
+ return INVALID;
2099
+ }
2100
+ const pairs = [];
2101
+ const keyType = this._def.keyType;
2102
+ const valueType = this._def.valueType;
2103
+ for (const key in ctx.data) {
2104
+ pairs.push({
2105
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2106
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key))
2107
+ });
2108
+ }
2109
+ if (ctx.common.async) {
2110
+ return ParseStatus.mergeObjectAsync(status, pairs);
2111
+ } else {
2112
+ return ParseStatus.mergeObjectSync(status, pairs);
2113
+ }
2114
+ }
2115
+ get element() {
2116
+ return this._def.valueType;
2117
+ }
2118
+ static create(first, second, third) {
2119
+ if (second instanceof ZodType) {
2120
+ return new ZodRecord({
2121
+ keyType: first,
2122
+ valueType: second,
2123
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
2124
+ ...processCreateParams(third)
2125
+ });
2126
+ }
2127
+ return new ZodRecord({
2128
+ keyType: ZodString.create(),
2129
+ valueType: first,
2130
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
2131
+ ...processCreateParams(second)
2132
+ });
2133
+ }
2134
+ };
2135
+ var ZodMap = class extends ZodType {
2136
+ _parse(input) {
2137
+ const { status, ctx } = this._processInputParams(input);
2138
+ if (ctx.parsedType !== ZodParsedType.map) {
2139
+ addIssueToContext(ctx, {
2140
+ code: ZodIssueCode.invalid_type,
2141
+ expected: ZodParsedType.map,
2142
+ received: ctx.parsedType
2143
+ });
2144
+ return INVALID;
2145
+ }
2146
+ const keyType = this._def.keyType;
2147
+ const valueType = this._def.valueType;
2148
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
2149
+ return {
2150
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
2151
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
2152
+ };
2153
+ });
2154
+ if (ctx.common.async) {
2155
+ const finalMap = /* @__PURE__ */ new Map();
2156
+ return Promise.resolve().then(async () => {
2157
+ for (const pair of pairs) {
2158
+ const key = await pair.key;
2159
+ const value = await pair.value;
2160
+ if (key.status === "aborted" || value.status === "aborted") {
2161
+ return INVALID;
2162
+ }
2163
+ if (key.status === "dirty" || value.status === "dirty") {
2164
+ status.dirty();
2165
+ }
2166
+ finalMap.set(key.value, value.value);
2167
+ }
2168
+ return { status: status.value, value: finalMap };
2169
+ });
2170
+ } else {
2171
+ const finalMap = /* @__PURE__ */ new Map();
2172
+ for (const pair of pairs) {
2173
+ const key = pair.key;
2174
+ const value = pair.value;
2175
+ if (key.status === "aborted" || value.status === "aborted") {
2176
+ return INVALID;
2177
+ }
2178
+ if (key.status === "dirty" || value.status === "dirty") {
2179
+ status.dirty();
2180
+ }
2181
+ finalMap.set(key.value, value.value);
2182
+ }
2183
+ return { status: status.value, value: finalMap };
2184
+ }
2185
+ }
2186
+ };
2187
+ ZodMap.create = (keyType, valueType, params2) => {
2188
+ return new ZodMap({
2189
+ valueType,
2190
+ keyType,
2191
+ typeName: ZodFirstPartyTypeKind.ZodMap,
2192
+ ...processCreateParams(params2)
2193
+ });
2194
+ };
2195
+ var ZodSet = class extends ZodType {
2196
+ _parse(input) {
2197
+ const { status, ctx } = this._processInputParams(input);
2198
+ if (ctx.parsedType !== ZodParsedType.set) {
2199
+ addIssueToContext(ctx, {
2200
+ code: ZodIssueCode.invalid_type,
2201
+ expected: ZodParsedType.set,
2202
+ received: ctx.parsedType
2203
+ });
2204
+ return INVALID;
2205
+ }
2206
+ const def = this._def;
2207
+ if (def.minSize !== null) {
2208
+ if (ctx.data.size < def.minSize.value) {
2209
+ addIssueToContext(ctx, {
2210
+ code: ZodIssueCode.too_small,
2211
+ minimum: def.minSize.value,
2212
+ type: "set",
2213
+ inclusive: true,
2214
+ message: def.minSize.message
2215
+ });
2216
+ status.dirty();
2217
+ }
2218
+ }
2219
+ if (def.maxSize !== null) {
2220
+ if (ctx.data.size > def.maxSize.value) {
2221
+ addIssueToContext(ctx, {
2222
+ code: ZodIssueCode.too_big,
2223
+ maximum: def.maxSize.value,
2224
+ type: "set",
2225
+ inclusive: true,
2226
+ message: def.maxSize.message
2227
+ });
2228
+ status.dirty();
2229
+ }
2230
+ }
2231
+ const valueType = this._def.valueType;
2232
+ function finalizeSet(elements2) {
2233
+ const parsedSet = /* @__PURE__ */ new Set();
2234
+ for (const element of elements2) {
2235
+ if (element.status === "aborted")
2236
+ return INVALID;
2237
+ if (element.status === "dirty")
2238
+ status.dirty();
2239
+ parsedSet.add(element.value);
2240
+ }
2241
+ return { status: status.value, value: parsedSet };
2242
+ }
2243
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
2244
+ if (ctx.common.async) {
2245
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
2246
+ } else {
2247
+ return finalizeSet(elements);
2248
+ }
2249
+ }
2250
+ min(minSize, message) {
2251
+ return new ZodSet({
2252
+ ...this._def,
2253
+ minSize: { value: minSize, message: errorUtil.toString(message) }
2254
+ });
2255
+ }
2256
+ max(maxSize, message) {
2257
+ return new ZodSet({
2258
+ ...this._def,
2259
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
2260
+ });
2261
+ }
2262
+ size(size, message) {
2263
+ return this.min(size, message).max(size, message);
2264
+ }
2265
+ nonempty(message) {
2266
+ return this.min(1, message);
2267
+ }
2268
+ };
2269
+ ZodSet.create = (valueType, params2) => {
2270
+ return new ZodSet({
2271
+ valueType,
2272
+ minSize: null,
2273
+ maxSize: null,
2274
+ typeName: ZodFirstPartyTypeKind.ZodSet,
2275
+ ...processCreateParams(params2)
2276
+ });
2277
+ };
2278
+ var ZodFunction = class extends ZodType {
2279
+ constructor() {
2280
+ super(...arguments);
2281
+ this.validate = this.implement;
2282
+ }
2283
+ _parse(input) {
2284
+ const { ctx } = this._processInputParams(input);
2285
+ if (ctx.parsedType !== ZodParsedType.function) {
2286
+ addIssueToContext(ctx, {
2287
+ code: ZodIssueCode.invalid_type,
2288
+ expected: ZodParsedType.function,
2289
+ received: ctx.parsedType
2290
+ });
2291
+ return INVALID;
2292
+ }
2293
+ function makeArgsIssue(args, error) {
2294
+ return makeIssue({
2295
+ data: args,
2296
+ path: ctx.path,
2297
+ errorMaps: [
2298
+ ctx.common.contextualErrorMap,
2299
+ ctx.schemaErrorMap,
2300
+ getErrorMap(),
2301
+ errorMap
2302
+ ].filter((x) => !!x),
2303
+ issueData: {
2304
+ code: ZodIssueCode.invalid_arguments,
2305
+ argumentsError: error
2306
+ }
2307
+ });
2308
+ }
2309
+ function makeReturnsIssue(returns, error) {
2310
+ return makeIssue({
2311
+ data: returns,
2312
+ path: ctx.path,
2313
+ errorMaps: [
2314
+ ctx.common.contextualErrorMap,
2315
+ ctx.schemaErrorMap,
2316
+ getErrorMap(),
2317
+ errorMap
2318
+ ].filter((x) => !!x),
2319
+ issueData: {
2320
+ code: ZodIssueCode.invalid_return_type,
2321
+ returnTypeError: error
2322
+ }
2323
+ });
2324
+ }
2325
+ const params2 = { errorMap: ctx.common.contextualErrorMap };
2326
+ const fn = ctx.data;
2327
+ if (this._def.returns instanceof ZodPromise) {
2328
+ return OK(async (...args) => {
2329
+ const error = new ZodError([]);
2330
+ const parsedArgs = await this._def.args.parseAsync(args, params2).catch((e) => {
2331
+ error.addIssue(makeArgsIssue(args, e));
2332
+ throw error;
2333
+ });
2334
+ const result = await fn(...parsedArgs);
2335
+ const parsedReturns = await this._def.returns._def.type.parseAsync(result, params2).catch((e) => {
2336
+ error.addIssue(makeReturnsIssue(result, e));
2337
+ throw error;
2338
+ });
2339
+ return parsedReturns;
2340
+ });
2341
+ } else {
2342
+ return OK((...args) => {
2343
+ const parsedArgs = this._def.args.safeParse(args, params2);
2344
+ if (!parsedArgs.success) {
2345
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
2346
+ }
2347
+ const result = fn(...parsedArgs.data);
2348
+ const parsedReturns = this._def.returns.safeParse(result, params2);
2349
+ if (!parsedReturns.success) {
2350
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
2351
+ }
2352
+ return parsedReturns.data;
2353
+ });
2354
+ }
2355
+ }
2356
+ parameters() {
2357
+ return this._def.args;
2358
+ }
2359
+ returnType() {
2360
+ return this._def.returns;
2361
+ }
2362
+ args(...items) {
2363
+ return new ZodFunction({
2364
+ ...this._def,
2365
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
2366
+ });
2367
+ }
2368
+ returns(returnType) {
2369
+ return new ZodFunction({
2370
+ ...this._def,
2371
+ returns: returnType
2372
+ });
2373
+ }
2374
+ implement(func) {
2375
+ const validatedFunc = this.parse(func);
2376
+ return validatedFunc;
2377
+ }
2378
+ strictImplement(func) {
2379
+ const validatedFunc = this.parse(func);
2380
+ return validatedFunc;
2381
+ }
2382
+ static create(args, returns, params2) {
2383
+ return new ZodFunction({
2384
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
2385
+ returns: returns || ZodUnknown.create(),
2386
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
2387
+ ...processCreateParams(params2)
2388
+ });
2389
+ }
2390
+ };
2391
+ var ZodLazy = class extends ZodType {
2392
+ get schema() {
2393
+ return this._def.getter();
2394
+ }
2395
+ _parse(input) {
2396
+ const { ctx } = this._processInputParams(input);
2397
+ const lazySchema = this._def.getter();
2398
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
2399
+ }
2400
+ };
2401
+ ZodLazy.create = (getter, params2) => {
2402
+ return new ZodLazy({
2403
+ getter,
2404
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
2405
+ ...processCreateParams(params2)
2406
+ });
2407
+ };
2408
+ var ZodLiteral = class extends ZodType {
2409
+ _parse(input) {
2410
+ if (input.data !== this._def.value) {
2411
+ const ctx = this._getOrReturnCtx(input);
2412
+ addIssueToContext(ctx, {
2413
+ code: ZodIssueCode.invalid_literal,
2414
+ expected: this._def.value
2415
+ });
2416
+ return INVALID;
2417
+ }
2418
+ return { status: "valid", value: input.data };
2419
+ }
2420
+ get value() {
2421
+ return this._def.value;
2422
+ }
2423
+ };
2424
+ ZodLiteral.create = (value, params2) => {
2425
+ return new ZodLiteral({
2426
+ value,
2427
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
2428
+ ...processCreateParams(params2)
2429
+ });
2430
+ };
2431
+ function createZodEnum(values, params2) {
2432
+ return new ZodEnum({
2433
+ values,
2434
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
2435
+ ...processCreateParams(params2)
2436
+ });
2437
+ }
2438
+ var ZodEnum = class extends ZodType {
2439
+ _parse(input) {
2440
+ if (typeof input.data !== "string") {
2441
+ const ctx = this._getOrReturnCtx(input);
2442
+ const expectedValues = this._def.values;
2443
+ addIssueToContext(ctx, {
2444
+ expected: util.joinValues(expectedValues),
2445
+ received: ctx.parsedType,
2446
+ code: ZodIssueCode.invalid_type
2447
+ });
2448
+ return INVALID;
2449
+ }
2450
+ if (this._def.values.indexOf(input.data) === -1) {
2451
+ const ctx = this._getOrReturnCtx(input);
2452
+ const expectedValues = this._def.values;
2453
+ addIssueToContext(ctx, {
2454
+ received: ctx.data,
2455
+ code: ZodIssueCode.invalid_enum_value,
2456
+ options: expectedValues
2457
+ });
2458
+ return INVALID;
2459
+ }
2460
+ return OK(input.data);
2461
+ }
2462
+ get options() {
2463
+ return this._def.values;
2464
+ }
2465
+ get enum() {
2466
+ const enumValues = {};
2467
+ for (const val of this._def.values) {
2468
+ enumValues[val] = val;
2469
+ }
2470
+ return enumValues;
2471
+ }
2472
+ get Values() {
2473
+ const enumValues = {};
2474
+ for (const val of this._def.values) {
2475
+ enumValues[val] = val;
2476
+ }
2477
+ return enumValues;
2478
+ }
2479
+ get Enum() {
2480
+ const enumValues = {};
2481
+ for (const val of this._def.values) {
2482
+ enumValues[val] = val;
2483
+ }
2484
+ return enumValues;
2485
+ }
2486
+ };
2487
+ ZodEnum.create = createZodEnum;
2488
+ var ZodNativeEnum = class extends ZodType {
2489
+ _parse(input) {
2490
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
2491
+ const ctx = this._getOrReturnCtx(input);
2492
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
2493
+ const expectedValues = util.objectValues(nativeEnumValues);
2494
+ addIssueToContext(ctx, {
2495
+ expected: util.joinValues(expectedValues),
2496
+ received: ctx.parsedType,
2497
+ code: ZodIssueCode.invalid_type
2498
+ });
2499
+ return INVALID;
2500
+ }
2501
+ if (nativeEnumValues.indexOf(input.data) === -1) {
2502
+ const expectedValues = util.objectValues(nativeEnumValues);
2503
+ addIssueToContext(ctx, {
2504
+ received: ctx.data,
2505
+ code: ZodIssueCode.invalid_enum_value,
2506
+ options: expectedValues
2507
+ });
2508
+ return INVALID;
2509
+ }
2510
+ return OK(input.data);
2511
+ }
2512
+ get enum() {
2513
+ return this._def.values;
2514
+ }
2515
+ };
2516
+ ZodNativeEnum.create = (values, params2) => {
2517
+ return new ZodNativeEnum({
2518
+ values,
2519
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
2520
+ ...processCreateParams(params2)
2521
+ });
2522
+ };
2523
+ var ZodPromise = class extends ZodType {
2524
+ _parse(input) {
2525
+ const { ctx } = this._processInputParams(input);
2526
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
2527
+ addIssueToContext(ctx, {
2528
+ code: ZodIssueCode.invalid_type,
2529
+ expected: ZodParsedType.promise,
2530
+ received: ctx.parsedType
2531
+ });
2532
+ return INVALID;
2533
+ }
2534
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
2535
+ return OK(promisified.then((data) => {
2536
+ return this._def.type.parseAsync(data, {
2537
+ path: ctx.path,
2538
+ errorMap: ctx.common.contextualErrorMap
2539
+ });
2540
+ }));
2541
+ }
2542
+ };
2543
+ ZodPromise.create = (schema, params2) => {
2544
+ return new ZodPromise({
2545
+ type: schema,
2546
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
2547
+ ...processCreateParams(params2)
2548
+ });
2549
+ };
2550
+ var ZodEffects = class extends ZodType {
2551
+ innerType() {
2552
+ return this._def.schema;
2553
+ }
2554
+ _parse(input) {
2555
+ const { status, ctx } = this._processInputParams(input);
2556
+ const effect = this._def.effect || null;
2557
+ if (effect.type === "preprocess") {
2558
+ const processed = effect.transform(ctx.data);
2559
+ if (ctx.common.async) {
2560
+ return Promise.resolve(processed).then((processed2) => {
2561
+ return this._def.schema._parseAsync({
2562
+ data: processed2,
2563
+ path: ctx.path,
2564
+ parent: ctx
2565
+ });
2566
+ });
2567
+ } else {
2568
+ return this._def.schema._parseSync({
2569
+ data: processed,
2570
+ path: ctx.path,
2571
+ parent: ctx
2572
+ });
2573
+ }
2574
+ }
2575
+ const checkCtx = {
2576
+ addIssue: (arg) => {
2577
+ addIssueToContext(ctx, arg);
2578
+ if (arg.fatal) {
2579
+ status.abort();
2580
+ } else {
2581
+ status.dirty();
2582
+ }
2583
+ },
2584
+ get path() {
2585
+ return ctx.path;
2586
+ }
2587
+ };
2588
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
2589
+ if (effect.type === "refinement") {
2590
+ const executeRefinement = (acc) => {
2591
+ const result = effect.refinement(acc, checkCtx);
2592
+ if (ctx.common.async) {
2593
+ return Promise.resolve(result);
2594
+ }
2595
+ if (result instanceof Promise) {
2596
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
2597
+ }
2598
+ return acc;
2599
+ };
2600
+ if (ctx.common.async === false) {
2601
+ const inner = this._def.schema._parseSync({
2602
+ data: ctx.data,
2603
+ path: ctx.path,
2604
+ parent: ctx
2605
+ });
2606
+ if (inner.status === "aborted")
2607
+ return INVALID;
2608
+ if (inner.status === "dirty")
2609
+ status.dirty();
2610
+ executeRefinement(inner.value);
2611
+ return { status: status.value, value: inner.value };
2612
+ } else {
2613
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
2614
+ if (inner.status === "aborted")
2615
+ return INVALID;
2616
+ if (inner.status === "dirty")
2617
+ status.dirty();
2618
+ return executeRefinement(inner.value).then(() => {
2619
+ return { status: status.value, value: inner.value };
2620
+ });
2621
+ });
2622
+ }
2623
+ }
2624
+ if (effect.type === "transform") {
2625
+ if (ctx.common.async === false) {
2626
+ const base = this._def.schema._parseSync({
2627
+ data: ctx.data,
2628
+ path: ctx.path,
2629
+ parent: ctx
2630
+ });
2631
+ if (!isValid(base))
2632
+ return base;
2633
+ const result = effect.transform(base.value, checkCtx);
2634
+ if (result instanceof Promise) {
2635
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
2636
+ }
2637
+ return { status: status.value, value: result };
2638
+ } else {
2639
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
2640
+ if (!isValid(base))
2641
+ return base;
2642
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
2643
+ });
2644
+ }
2645
+ }
2646
+ util.assertNever(effect);
2647
+ }
2648
+ };
2649
+ ZodEffects.create = (schema, effect, params2) => {
2650
+ return new ZodEffects({
2651
+ schema,
2652
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
2653
+ effect,
2654
+ ...processCreateParams(params2)
2655
+ });
2656
+ };
2657
+ ZodEffects.createWithPreprocess = (preprocess, schema, params2) => {
2658
+ return new ZodEffects({
2659
+ schema,
2660
+ effect: { type: "preprocess", transform: preprocess },
2661
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
2662
+ ...processCreateParams(params2)
2663
+ });
2664
+ };
2665
+ var ZodOptional = class extends ZodType {
2666
+ _parse(input) {
2667
+ const parsedType = this._getType(input);
2668
+ if (parsedType === ZodParsedType.undefined) {
2669
+ return OK(void 0);
2670
+ }
2671
+ return this._def.innerType._parse(input);
2672
+ }
2673
+ unwrap() {
2674
+ return this._def.innerType;
2675
+ }
2676
+ };
2677
+ ZodOptional.create = (type, params2) => {
2678
+ return new ZodOptional({
2679
+ innerType: type,
2680
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
2681
+ ...processCreateParams(params2)
2682
+ });
2683
+ };
2684
+ var ZodNullable = class extends ZodType {
2685
+ _parse(input) {
2686
+ const parsedType = this._getType(input);
2687
+ if (parsedType === ZodParsedType.null) {
2688
+ return OK(null);
2689
+ }
2690
+ return this._def.innerType._parse(input);
2691
+ }
2692
+ unwrap() {
2693
+ return this._def.innerType;
2694
+ }
2695
+ };
2696
+ ZodNullable.create = (type, params2) => {
2697
+ return new ZodNullable({
2698
+ innerType: type,
2699
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
2700
+ ...processCreateParams(params2)
2701
+ });
2702
+ };
2703
+ var ZodDefault = class extends ZodType {
2704
+ _parse(input) {
2705
+ const { ctx } = this._processInputParams(input);
2706
+ let data = ctx.data;
2707
+ if (ctx.parsedType === ZodParsedType.undefined) {
2708
+ data = this._def.defaultValue();
2709
+ }
2710
+ return this._def.innerType._parse({
2711
+ data,
2712
+ path: ctx.path,
2713
+ parent: ctx
2714
+ });
2715
+ }
2716
+ removeDefault() {
2717
+ return this._def.innerType;
2718
+ }
2719
+ };
2720
+ ZodDefault.create = (type, params2) => {
2721
+ return new ZodOptional({
2722
+ innerType: type,
2723
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
2724
+ ...processCreateParams(params2)
2725
+ });
2726
+ };
2727
+ var ZodNaN = class extends ZodType {
2728
+ _parse(input) {
2729
+ const parsedType = this._getType(input);
2730
+ if (parsedType !== ZodParsedType.nan) {
2731
+ const ctx = this._getOrReturnCtx(input);
2732
+ addIssueToContext(ctx, {
2733
+ code: ZodIssueCode.invalid_type,
2734
+ expected: ZodParsedType.nan,
2735
+ received: ctx.parsedType
2736
+ });
2737
+ return INVALID;
2738
+ }
2739
+ return { status: "valid", value: input.data };
2740
+ }
2741
+ };
2742
+ ZodNaN.create = (params2) => {
2743
+ return new ZodNaN({
2744
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
2745
+ ...processCreateParams(params2)
2746
+ });
2747
+ };
2748
+ var BRAND = Symbol("zod_brand");
2749
+ var ZodBranded = class extends ZodType {
2750
+ _parse(input) {
2751
+ const { ctx } = this._processInputParams(input);
2752
+ const data = ctx.data;
2753
+ return this._def.type._parse({
2754
+ data,
2755
+ path: ctx.path,
2756
+ parent: ctx
2757
+ });
2758
+ }
2759
+ unwrap() {
2760
+ return this._def.type;
2761
+ }
2762
+ };
2763
+ var custom = (check, params2 = {}, fatal) => {
2764
+ if (check)
2765
+ return ZodAny.create().superRefine((data, ctx) => {
2766
+ if (!check(data)) {
2767
+ const p = typeof params2 === "function" ? params2(data) : params2;
2768
+ const p2 = typeof p === "string" ? { message: p } : p;
2769
+ ctx.addIssue({ code: "custom", ...p2, fatal });
2770
+ }
2771
+ });
2772
+ return ZodAny.create();
2773
+ };
2774
+ var late = {
2775
+ object: ZodObject.lazycreate
2776
+ };
2777
+ var ZodFirstPartyTypeKind;
2778
+ (function(ZodFirstPartyTypeKind2) {
2779
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
2780
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
2781
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
2782
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
2783
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
2784
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
2785
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
2786
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
2787
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
2788
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
2789
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
2790
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
2791
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
2792
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
2793
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
2794
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
2795
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
2796
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
2797
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
2798
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
2799
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
2800
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
2801
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
2802
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
2803
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
2804
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
2805
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
2806
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
2807
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
2808
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
2809
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
2810
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
2811
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
2812
+ var instanceOfType = (cls, params2 = {
2813
+ message: `Input not instance of ${cls.name}`
2814
+ }) => custom((data) => data instanceof cls, params2, true);
2815
+ var stringType = ZodString.create;
2816
+ var numberType = ZodNumber.create;
2817
+ var nanType = ZodNaN.create;
2818
+ var bigIntType = ZodBigInt.create;
2819
+ var booleanType = ZodBoolean.create;
2820
+ var dateType = ZodDate.create;
2821
+ var undefinedType = ZodUndefined.create;
2822
+ var nullType = ZodNull.create;
2823
+ var anyType = ZodAny.create;
2824
+ var unknownType = ZodUnknown.create;
2825
+ var neverType = ZodNever.create;
2826
+ var voidType = ZodVoid.create;
2827
+ var arrayType = ZodArray.create;
2828
+ var objectType = ZodObject.create;
2829
+ var strictObjectType = ZodObject.strictCreate;
2830
+ var unionType = ZodUnion.create;
2831
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
2832
+ var intersectionType = ZodIntersection.create;
2833
+ var tupleType = ZodTuple.create;
2834
+ var recordType = ZodRecord.create;
2835
+ var mapType = ZodMap.create;
2836
+ var setType = ZodSet.create;
2837
+ var functionType = ZodFunction.create;
2838
+ var lazyType = ZodLazy.create;
2839
+ var literalType = ZodLiteral.create;
2840
+ var enumType = ZodEnum.create;
2841
+ var nativeEnumType = ZodNativeEnum.create;
2842
+ var promiseType = ZodPromise.create;
2843
+ var effectsType = ZodEffects.create;
2844
+ var optionalType = ZodOptional.create;
2845
+ var nullableType = ZodNullable.create;
2846
+ var preprocessType = ZodEffects.createWithPreprocess;
2847
+ var ostring = () => stringType().optional();
2848
+ var onumber = () => numberType().optional();
2849
+ var oboolean = () => booleanType().optional();
2850
+ var NEVER = INVALID;
2851
+ var mod = /* @__PURE__ */ Object.freeze({
2852
+ __proto__: null,
2853
+ getParsedType,
2854
+ ZodParsedType,
2855
+ defaultErrorMap: errorMap,
2856
+ setErrorMap,
2857
+ getErrorMap,
2858
+ makeIssue,
2859
+ EMPTY_PATH,
2860
+ addIssueToContext,
2861
+ ParseStatus,
2862
+ INVALID,
2863
+ DIRTY,
2864
+ OK,
2865
+ isAborted,
2866
+ isDirty,
2867
+ isValid,
2868
+ isAsync,
2869
+ ZodType,
2870
+ ZodString,
2871
+ ZodNumber,
2872
+ ZodBigInt,
2873
+ ZodBoolean,
2874
+ ZodDate,
2875
+ ZodUndefined,
2876
+ ZodNull,
2877
+ ZodAny,
2878
+ ZodUnknown,
2879
+ ZodNever,
2880
+ ZodVoid,
2881
+ ZodArray,
2882
+ get objectUtil() {
2883
+ return objectUtil;
2884
+ },
2885
+ ZodObject,
2886
+ ZodUnion,
2887
+ ZodDiscriminatedUnion,
2888
+ ZodIntersection,
2889
+ ZodTuple,
2890
+ ZodRecord,
2891
+ ZodMap,
2892
+ ZodSet,
2893
+ ZodFunction,
2894
+ ZodLazy,
2895
+ ZodLiteral,
2896
+ ZodEnum,
2897
+ ZodNativeEnum,
2898
+ ZodPromise,
2899
+ ZodEffects,
2900
+ ZodTransformer: ZodEffects,
2901
+ ZodOptional,
2902
+ ZodNullable,
2903
+ ZodDefault,
2904
+ ZodNaN,
2905
+ BRAND,
2906
+ ZodBranded,
2907
+ custom,
2908
+ Schema: ZodType,
2909
+ ZodSchema: ZodType,
2910
+ late,
2911
+ get ZodFirstPartyTypeKind() {
2912
+ return ZodFirstPartyTypeKind;
2913
+ },
2914
+ any: anyType,
2915
+ array: arrayType,
2916
+ bigint: bigIntType,
2917
+ boolean: booleanType,
2918
+ date: dateType,
2919
+ discriminatedUnion: discriminatedUnionType,
2920
+ effect: effectsType,
2921
+ "enum": enumType,
2922
+ "function": functionType,
2923
+ "instanceof": instanceOfType,
2924
+ intersection: intersectionType,
2925
+ lazy: lazyType,
2926
+ literal: literalType,
2927
+ map: mapType,
2928
+ nan: nanType,
2929
+ nativeEnum: nativeEnumType,
2930
+ never: neverType,
2931
+ "null": nullType,
2932
+ nullable: nullableType,
2933
+ number: numberType,
2934
+ object: objectType,
2935
+ oboolean,
2936
+ onumber,
2937
+ optional: optionalType,
2938
+ ostring,
2939
+ preprocess: preprocessType,
2940
+ promise: promiseType,
2941
+ record: recordType,
2942
+ set: setType,
2943
+ strictObject: strictObjectType,
2944
+ string: stringType,
2945
+ transformer: effectsType,
2946
+ tuple: tupleType,
2947
+ "undefined": undefinedType,
2948
+ union: unionType,
2949
+ unknown: unknownType,
2950
+ "void": voidType,
2951
+ NEVER,
2952
+ ZodIssueCode,
2953
+ quotelessJson,
2954
+ ZodError
2955
+ });
2956
+
2957
+ // src/types.ts
2958
+ var errorResponseBody = mod.object({
2959
+ error: mod.string().optional(),
2960
+ message: mod.string().optional()
2961
+ });
2962
+ var ResponseType = /* @__PURE__ */ ((ResponseType2) => {
2963
+ ResponseType2[ResponseType2["Unknown"] = 1] = "Unknown";
2964
+ ResponseType2[ResponseType2["InvalidResponse"] = 2] = "InvalidResponse";
2965
+ ResponseType2[ResponseType2["Success"] = 200] = "Success";
2966
+ ResponseType2[ResponseType2["InvalidRequest"] = 400] = "InvalidRequest";
2967
+ ResponseType2[ResponseType2["AuthRequired"] = 401] = "AuthRequired";
2968
+ ResponseType2[ResponseType2["Forbidden"] = 403] = "Forbidden";
2969
+ ResponseType2[ResponseType2["XRPCNotSupported"] = 404] = "XRPCNotSupported";
2970
+ ResponseType2[ResponseType2["PayloadTooLarge"] = 413] = "PayloadTooLarge";
2971
+ ResponseType2[ResponseType2["RateLimitExceeded"] = 429] = "RateLimitExceeded";
2972
+ ResponseType2[ResponseType2["InternalServerError"] = 500] = "InternalServerError";
2973
+ ResponseType2[ResponseType2["MethodNotImplemented"] = 501] = "MethodNotImplemented";
2974
+ ResponseType2[ResponseType2["UpstreamFailure"] = 502] = "UpstreamFailure";
2975
+ ResponseType2[ResponseType2["NotEnoughResouces"] = 503] = "NotEnoughResouces";
2976
+ ResponseType2[ResponseType2["UpstreamTimeout"] = 504] = "UpstreamTimeout";
2977
+ return ResponseType2;
2978
+ })(ResponseType || {});
2979
+ var ResponseTypeNames = {
2980
+ [2 /* InvalidResponse */]: "InvalidResponse",
2981
+ [200 /* Success */]: "Success",
2982
+ [400 /* InvalidRequest */]: "InvalidRequest",
2983
+ [401 /* AuthRequired */]: "AuthenticationRequired",
2984
+ [403 /* Forbidden */]: "Forbidden",
2985
+ [404 /* XRPCNotSupported */]: "XRPCNotSupported",
2986
+ [413 /* PayloadTooLarge */]: "PayloadTooLarge",
2987
+ [429 /* RateLimitExceeded */]: "RateLimitExceeded",
2988
+ [500 /* InternalServerError */]: "InternalServerError",
2989
+ [501 /* MethodNotImplemented */]: "MethodNotImplemented",
2990
+ [502 /* UpstreamFailure */]: "UpstreamFailure",
2991
+ [503 /* NotEnoughResouces */]: "NotEnoughResouces",
2992
+ [504 /* UpstreamTimeout */]: "UpstreamTimeout"
2993
+ };
2994
+ var ResponseTypeStrings = {
2995
+ [2 /* InvalidResponse */]: "Invalid Response",
2996
+ [200 /* Success */]: "Success",
2997
+ [400 /* InvalidRequest */]: "Invalid Request",
2998
+ [401 /* AuthRequired */]: "Authentication Required",
2999
+ [403 /* Forbidden */]: "Forbidden",
3000
+ [404 /* XRPCNotSupported */]: "XRPC Not Supported",
3001
+ [413 /* PayloadTooLarge */]: "Payload Too Large",
3002
+ [429 /* RateLimitExceeded */]: "Rate Limit Exceeded",
3003
+ [500 /* InternalServerError */]: "Internal Server Error",
3004
+ [501 /* MethodNotImplemented */]: "Method Not Implemented",
3005
+ [502 /* UpstreamFailure */]: "Upstream Failure",
3006
+ [503 /* NotEnoughResouces */]: "Not Enough Resouces",
3007
+ [504 /* UpstreamTimeout */]: "Upstream Timeout"
3008
+ };
3009
+ var XRPCResponse = class {
3010
+ constructor(data, headers) {
3011
+ this.data = data;
3012
+ this.headers = headers;
3013
+ this.success = true;
3014
+ }
3015
+ };
3016
+ var XRPCError = class extends Error {
3017
+ constructor(status, error, message) {
3018
+ super(message || error || ResponseTypeStrings[status]);
3019
+ this.status = status;
3020
+ this.error = error;
3021
+ this.success = false;
3022
+ if (!this.error) {
3023
+ this.error = ResponseTypeNames[status];
3024
+ }
3025
+ }
3026
+ };
3027
+
3028
+ // ../nsid/src/index.ts
3029
+ var SEGMENT_RE = /^[a-zA-Z]([a-zA-Z0-9-])*$/;
3030
+ var NSID = class {
3031
+ constructor(nsid) {
3032
+ this.segments = [];
3033
+ const segments = nsid.split(".");
3034
+ if (segments.length <= 2) {
3035
+ throw new Error(`Invalid NSID: ${nsid}`);
3036
+ }
3037
+ for (let i = 0; i < segments.length; i++) {
3038
+ const segment = segments[i];
3039
+ if (SEGMENT_RE.test(segment)) {
3040
+ continue;
3041
+ }
3042
+ if (i === segments.length - 1 && segment === "*") {
3043
+ continue;
3044
+ }
3045
+ throw new Error(`Invalid NSID: invalid character in segment "${segment}"`);
3046
+ }
3047
+ this.segments = segments;
3048
+ }
3049
+ static parse(nsid) {
3050
+ return new NSID(nsid);
3051
+ }
3052
+ static create(authority, name) {
3053
+ const segments = [...authority.split(".").reverse(), name].join(".");
3054
+ return new NSID(segments);
3055
+ }
3056
+ static isValid(nsid) {
3057
+ try {
3058
+ NSID.parse(nsid);
3059
+ return true;
3060
+ } catch (e) {
3061
+ return false;
3062
+ }
3063
+ }
3064
+ get authority() {
3065
+ return this.segments.slice(0, this.segments.length - 1).reverse().join(".");
3066
+ }
3067
+ get name() {
3068
+ return this.segments.at(this.segments.length - 1);
3069
+ }
3070
+ toString() {
3071
+ return this.segments.join(".");
3072
+ }
3073
+ };
3074
+
3075
+ // ../lexicon/src/types.ts
3076
+ var lexBoolean = mod.object({
3077
+ type: mod.literal("boolean"),
3078
+ description: mod.string().optional(),
3079
+ default: mod.boolean().optional(),
3080
+ const: mod.boolean().optional()
3081
+ });
3082
+ var lexNumber = mod.object({
3083
+ type: mod.literal("number"),
3084
+ description: mod.string().optional(),
3085
+ default: mod.number().optional(),
3086
+ minimum: mod.number().optional(),
3087
+ maximum: mod.number().optional(),
3088
+ enum: mod.number().array().optional(),
3089
+ const: mod.number().optional()
3090
+ });
3091
+ var lexInteger = mod.object({
3092
+ type: mod.literal("integer"),
3093
+ description: mod.string().optional(),
3094
+ default: mod.number().int().optional(),
3095
+ minimum: mod.number().int().optional(),
3096
+ maximum: mod.number().int().optional(),
3097
+ enum: mod.number().int().array().optional(),
3098
+ const: mod.number().int().optional()
3099
+ });
3100
+ var lexString = mod.object({
3101
+ type: mod.literal("string"),
3102
+ description: mod.string().optional(),
3103
+ default: mod.string().optional(),
3104
+ minLength: mod.number().int().optional(),
3105
+ maxLength: mod.number().int().optional(),
3106
+ enum: mod.string().array().optional(),
3107
+ const: mod.string().optional(),
3108
+ knownValues: mod.string().array().optional()
3109
+ });
3110
+ var lexDatetime = mod.object({
3111
+ type: mod.literal("datetime"),
3112
+ description: mod.string().optional()
3113
+ });
3114
+ var lexUnknown = mod.object({
3115
+ type: mod.literal("unknown"),
3116
+ description: mod.string().optional()
3117
+ });
3118
+ var lexPrimitive = mod.union([
3119
+ lexBoolean,
3120
+ lexNumber,
3121
+ lexInteger,
3122
+ lexString,
3123
+ lexDatetime,
3124
+ lexUnknown
3125
+ ]);
3126
+ var lexRef = mod.object({
3127
+ type: mod.literal("ref"),
3128
+ description: mod.string().optional(),
3129
+ ref: mod.string()
3130
+ });
3131
+ var lexRefUnion = mod.object({
3132
+ type: mod.literal("union"),
3133
+ description: mod.string().optional(),
3134
+ refs: mod.string().array(),
3135
+ closed: mod.boolean().optional()
3136
+ });
3137
+ var lexRefVariant = mod.union([lexRef, lexRefUnion]);
3138
+ var lexBlob = mod.object({
3139
+ type: mod.literal("blob"),
3140
+ description: mod.string().optional(),
3141
+ accept: mod.string().array().optional(),
3142
+ maxSize: mod.number().optional()
3143
+ });
3144
+ var lexImage = mod.object({
3145
+ type: mod.literal("image"),
3146
+ description: mod.string().optional(),
3147
+ accept: mod.string().array().optional(),
3148
+ maxSize: mod.number().optional(),
3149
+ maxWidth: mod.number().int().optional(),
3150
+ maxHeight: mod.number().int().optional()
3151
+ });
3152
+ var lexVideo = mod.object({
3153
+ type: mod.literal("video"),
3154
+ description: mod.string().optional(),
3155
+ accept: mod.string().array().optional(),
3156
+ maxSize: mod.number().optional(),
3157
+ maxWidth: mod.number().int().optional(),
3158
+ maxHeight: mod.number().int().optional(),
3159
+ maxLength: mod.number().int().optional()
3160
+ });
3161
+ var lexAudio = mod.object({
3162
+ type: mod.literal("audio"),
3163
+ description: mod.string().optional(),
3164
+ accept: mod.string().array().optional(),
3165
+ maxSize: mod.number().optional(),
3166
+ maxLength: mod.number().int().optional()
3167
+ });
3168
+ var lexBlobVariant = mod.union([lexBlob, lexImage, lexVideo, lexAudio]);
3169
+ var lexArray = mod.object({
3170
+ type: mod.literal("array"),
3171
+ description: mod.string().optional(),
3172
+ items: mod.union([lexPrimitive, lexBlobVariant, lexRefVariant]),
3173
+ minLength: mod.number().int().optional(),
3174
+ maxLength: mod.number().int().optional()
3175
+ });
3176
+ var lexToken = mod.object({
3177
+ type: mod.literal("token"),
3178
+ description: mod.string().optional()
3179
+ });
3180
+ var lexObject = mod.object({
3181
+ type: mod.literal("object"),
3182
+ description: mod.string().optional(),
3183
+ required: mod.string().array().optional(),
3184
+ properties: mod.record(mod.union([lexRefVariant, lexArray, lexBlobVariant, lexPrimitive])).optional()
3185
+ });
3186
+ var lexXrpcParameters = mod.object({
3187
+ type: mod.literal("params"),
3188
+ description: mod.string().optional(),
3189
+ required: mod.string().array().optional(),
3190
+ properties: mod.record(lexPrimitive)
3191
+ });
3192
+ var lexXrpcBody = mod.object({
3193
+ description: mod.string().optional(),
3194
+ encoding: mod.string(),
3195
+ schema: mod.union([lexRefVariant, lexObject]).optional()
3196
+ });
3197
+ var lexXrpcError = mod.object({
3198
+ name: mod.string(),
3199
+ description: mod.string().optional()
3200
+ });
3201
+ var lexXrpcQuery = mod.object({
3202
+ type: mod.literal("query"),
3203
+ description: mod.string().optional(),
3204
+ parameters: lexXrpcParameters.optional(),
3205
+ output: lexXrpcBody.optional(),
3206
+ errors: lexXrpcError.array().optional()
3207
+ });
3208
+ var lexXrpcProcedure = mod.object({
3209
+ type: mod.literal("procedure"),
3210
+ description: mod.string().optional(),
3211
+ parameters: lexXrpcParameters.optional(),
3212
+ input: lexXrpcBody.optional(),
3213
+ output: lexXrpcBody.optional(),
3214
+ errors: lexXrpcError.array().optional()
3215
+ });
3216
+ var lexRecord = mod.object({
3217
+ type: mod.literal("record"),
3218
+ description: mod.string().optional(),
3219
+ key: mod.string().optional(),
3220
+ record: lexObject
3221
+ });
3222
+ var lexUserType = mod.union([
3223
+ lexRecord,
3224
+ lexXrpcQuery,
3225
+ lexXrpcProcedure,
3226
+ lexBlob,
3227
+ lexImage,
3228
+ lexVideo,
3229
+ lexAudio,
3230
+ lexArray,
3231
+ lexToken,
3232
+ lexObject,
3233
+ lexBoolean,
3234
+ lexNumber,
3235
+ lexInteger,
3236
+ lexString,
3237
+ lexDatetime,
3238
+ lexUnknown
3239
+ ]);
3240
+ var lexiconDoc = mod.object({
3241
+ lexicon: mod.literal(1),
3242
+ id: mod.string().refine((v) => NSID.isValid(v), {
3243
+ message: "Must be a valid NSID"
3244
+ }),
3245
+ revision: mod.number().optional(),
3246
+ description: mod.string().optional(),
3247
+ defs: mod.record(lexUserType)
3248
+ }).superRefine((doc, ctx) => {
3249
+ for (const defId in doc.defs) {
3250
+ const def = doc.defs[defId];
3251
+ if (defId !== "main" && (def.type === "record" || def.type === "procedure" || def.type === "query")) {
3252
+ ctx.addIssue({
3253
+ code: mod.ZodIssueCode.custom,
3254
+ message: `Records, procedures, and queries must be the main definition.`
3255
+ });
3256
+ }
3257
+ }
3258
+ });
3259
+ function isObj(obj) {
3260
+ return !!obj && typeof obj === "object";
3261
+ }
3262
+ function hasProp(data, prop) {
3263
+ return prop in data;
3264
+ }
3265
+ var discriminatedObject = mod.object({ $type: mod.string() });
3266
+ function isDiscriminatedObject(value) {
3267
+ return discriminatedObject.safeParse(value).success;
3268
+ }
3269
+ var LexiconDocMalformedError = class extends Error {
3270
+ constructor(message, schemaDef, issues) {
3271
+ super(message);
3272
+ this.schemaDef = schemaDef;
3273
+ this.issues = issues;
3274
+ this.schemaDef = schemaDef;
3275
+ this.issues = issues;
3276
+ }
3277
+ };
3278
+ var ValidationError = class extends Error {
3279
+ };
3280
+ var InvalidLexiconError = class extends Error {
3281
+ };
3282
+ var LexiconDefNotFoundError = class extends Error {
3283
+ };
3284
+
3285
+ // ../lexicon/src/validators/primitives.ts
3286
+ function validate(lexicons, path, def, value) {
3287
+ switch (def.type) {
3288
+ case "boolean":
3289
+ return boolean(lexicons, path, def, value);
3290
+ case "number":
3291
+ return number(lexicons, path, def, value);
3292
+ case "integer":
3293
+ return integer(lexicons, path, def, value);
3294
+ case "string":
3295
+ return string(lexicons, path, def, value);
3296
+ case "datetime":
3297
+ return datetime(lexicons, path, def, value);
3298
+ case "unknown":
3299
+ return unknown(lexicons, path, def, value);
3300
+ default:
3301
+ return {
3302
+ success: false,
3303
+ error: new ValidationError(`Unexpected lexicon type: ${def.type}`)
3304
+ };
3305
+ }
3306
+ }
3307
+ function boolean(lexicons, path, def, value) {
3308
+ def = def;
3309
+ const type = typeof value;
3310
+ if (type == "undefined") {
3311
+ if (typeof def.default === "boolean") {
3312
+ return { success: true };
3313
+ }
3314
+ return {
3315
+ success: false,
3316
+ error: new ValidationError(`${path} must be a boolean`)
3317
+ };
3318
+ } else if (type !== "boolean") {
3319
+ return {
3320
+ success: false,
3321
+ error: new ValidationError(`${path} must be a boolean`)
3322
+ };
3323
+ }
3324
+ if (typeof def.const === "boolean") {
3325
+ if (value !== def.const) {
3326
+ return {
3327
+ success: false,
3328
+ error: new ValidationError(`${path} must be ${def.const}`)
3329
+ };
3330
+ }
3331
+ }
3332
+ return { success: true };
3333
+ }
3334
+ function number(lexicons, path, def, value) {
3335
+ def = def;
3336
+ const type = typeof value;
3337
+ if (type == "undefined") {
3338
+ if (typeof def.default === "number") {
3339
+ return { success: true };
3340
+ }
3341
+ return {
3342
+ success: false,
3343
+ error: new ValidationError(`${path} must be a number`)
3344
+ };
3345
+ } else if (type !== "number") {
3346
+ return {
3347
+ success: false,
3348
+ error: new ValidationError(`${path} must be a number`)
3349
+ };
3350
+ }
3351
+ if (typeof def.const === "number") {
3352
+ if (value !== def.const) {
3353
+ return {
3354
+ success: false,
3355
+ error: new ValidationError(`${path} must be ${def.const}`)
3356
+ };
3357
+ }
3358
+ }
3359
+ if (Array.isArray(def.enum)) {
3360
+ if (!def.enum.includes(value)) {
3361
+ return {
3362
+ success: false,
3363
+ error: new ValidationError(
3364
+ `${path} must be one of (${def.enum.join("|")})`
3365
+ )
3366
+ };
3367
+ }
3368
+ }
3369
+ if (typeof def.maximum === "number") {
3370
+ if (value > def.maximum) {
3371
+ return {
3372
+ success: false,
3373
+ error: new ValidationError(
3374
+ `${path} can not be greater than ${def.maximum}`
3375
+ )
3376
+ };
3377
+ }
3378
+ }
3379
+ if (typeof def.minimum === "number") {
3380
+ if (value < def.minimum) {
3381
+ return {
3382
+ success: false,
3383
+ error: new ValidationError(
3384
+ `${path} can not be less than ${def.minimum}`
3385
+ )
3386
+ };
3387
+ }
3388
+ }
3389
+ return { success: true };
3390
+ }
3391
+ function integer(lexicons, path, def, value) {
3392
+ def = def;
3393
+ const numRes = number(lexicons, path, def, value);
3394
+ if (!numRes.success) {
3395
+ return numRes;
3396
+ }
3397
+ if (!Number.isInteger(value)) {
3398
+ return {
3399
+ success: false,
3400
+ error: new ValidationError(`${path} must be an integer`)
3401
+ };
3402
+ }
3403
+ return { success: true };
3404
+ }
3405
+ function string(lexicons, path, def, value) {
3406
+ def = def;
3407
+ const type = typeof value;
3408
+ if (type == "undefined") {
3409
+ if (typeof def.default === "string") {
3410
+ return { success: true };
3411
+ }
3412
+ return {
3413
+ success: false,
3414
+ error: new ValidationError(`${path} must be a string`)
3415
+ };
3416
+ } else if (type !== "string") {
3417
+ return {
3418
+ success: false,
3419
+ error: new ValidationError(`${path} must be a string`)
3420
+ };
3421
+ }
3422
+ if (typeof def.const === "string") {
3423
+ if (value !== def.const) {
3424
+ return {
3425
+ success: false,
3426
+ error: new ValidationError(`${path} must be ${def.const}`)
3427
+ };
3428
+ }
3429
+ }
3430
+ if (Array.isArray(def.enum)) {
3431
+ if (!def.enum.includes(value)) {
3432
+ return {
3433
+ success: false,
3434
+ error: new ValidationError(
3435
+ `${path} must be one of (${def.enum.join("|")})`
3436
+ )
3437
+ };
3438
+ }
3439
+ }
3440
+ if (typeof def.maxLength === "number") {
3441
+ if (value.length > def.maxLength) {
3442
+ return {
3443
+ success: false,
3444
+ error: new ValidationError(
3445
+ `${path} must not be longer than ${def.maxLength} characters`
3446
+ )
3447
+ };
3448
+ }
3449
+ }
3450
+ if (typeof def.minLength === "number") {
3451
+ if (value.length < def.minLength) {
3452
+ return {
3453
+ success: false,
3454
+ error: new ValidationError(
3455
+ `${path} must not be shorter than ${def.minLength} characters`
3456
+ )
3457
+ };
3458
+ }
3459
+ }
3460
+ return { success: true };
3461
+ }
3462
+ function datetime(lexicons, path, def, value) {
3463
+ def = def;
3464
+ const type = typeof value;
3465
+ if (type !== "string") {
3466
+ return {
3467
+ success: false,
3468
+ error: new ValidationError(`${path} must be a string`)
3469
+ };
3470
+ }
3471
+ {
3472
+ try {
3473
+ const date = new Date(Date.parse(value));
3474
+ if (value !== date.toISOString()) {
3475
+ throw new ValidationError(
3476
+ `${path} must be an iso8601 formatted datetime`
3477
+ );
3478
+ }
3479
+ } catch {
3480
+ throw new ValidationError(`${path} must be an iso8601 formatted datetime`);
3481
+ }
3482
+ }
3483
+ return { success: true };
3484
+ }
3485
+ function unknown(lexicons, path, def, value) {
3486
+ if (!value || typeof value !== "object") {
3487
+ return {
3488
+ success: false,
3489
+ error: new ValidationError(`${path} must be an object`)
3490
+ };
3491
+ }
3492
+ return { success: true };
3493
+ }
3494
+
3495
+ // ../lexicon/src/validators/blob.ts
3496
+ function blob(lexicons, path, def, value) {
3497
+ if (!isObj(value)) {
3498
+ return {
3499
+ success: false,
3500
+ error: new ValidationError(`${path} should be an object`)
3501
+ };
3502
+ }
3503
+ if (!hasProp(value, "cid") || typeof value.cid !== "string") {
3504
+ return {
3505
+ success: false,
3506
+ error: new ValidationError(`${path}/cid should be a string`)
3507
+ };
3508
+ }
3509
+ if (!hasProp(value, "mimeType") || typeof value.mimeType !== "string") {
3510
+ return {
3511
+ success: false,
3512
+ error: new ValidationError(`${path}/mimeType should be a string`)
3513
+ };
3514
+ }
3515
+ return { success: true };
3516
+ }
3517
+ function image(lexicons, path, def, value) {
3518
+ return blob(lexicons, path, def, value);
3519
+ }
3520
+ function video(lexicons, path, def, value) {
3521
+ return blob(lexicons, path, def, value);
3522
+ }
3523
+ function audio(lexicons, path, def, value) {
3524
+ return blob(lexicons, path, def, value);
3525
+ }
3526
+
3527
+ // ../lexicon/src/validators/complex.ts
3528
+ function validate2(lexicons, path, def, value) {
3529
+ switch (def.type) {
3530
+ case "boolean":
3531
+ return boolean(lexicons, path, def, value);
3532
+ case "number":
3533
+ return number(lexicons, path, def, value);
3534
+ case "integer":
3535
+ return integer(lexicons, path, def, value);
3536
+ case "string":
3537
+ return string(lexicons, path, def, value);
3538
+ case "datetime":
3539
+ return datetime(lexicons, path, def, value);
3540
+ case "unknown":
3541
+ return unknown(lexicons, path, def, value);
3542
+ case "object":
3543
+ return object(lexicons, path, def, value);
3544
+ case "array":
3545
+ return array(lexicons, path, def, value);
3546
+ case "blob":
3547
+ return blob(lexicons, path, def, value);
3548
+ case "image":
3549
+ return image(lexicons, path, def, value);
3550
+ case "video":
3551
+ return video(lexicons, path, def, value);
3552
+ case "audio":
3553
+ return audio(lexicons, path, def, value);
3554
+ default:
3555
+ return {
3556
+ success: false,
3557
+ error: new ValidationError(`Unexpected lexicon type: ${def.type}`)
3558
+ };
3559
+ }
3560
+ }
3561
+ function array(lexicons, path, def, value) {
3562
+ def = def;
3563
+ if (!Array.isArray(value)) {
3564
+ return {
3565
+ success: false,
3566
+ error: new ValidationError(`${path} must be an array`)
3567
+ };
3568
+ }
3569
+ if (typeof def.maxLength === "number") {
3570
+ if (value.length > def.maxLength) {
3571
+ return {
3572
+ success: false,
3573
+ error: new ValidationError(
3574
+ `${path} must not have more than ${def.maxLength} elements`
3575
+ )
3576
+ };
3577
+ }
3578
+ }
3579
+ if (typeof def.minLength === "number") {
3580
+ if (value.length < def.minLength) {
3581
+ return {
3582
+ success: false,
3583
+ error: new ValidationError(
3584
+ `${path} must not have fewer than ${def.minLength} elements`
3585
+ )
3586
+ };
3587
+ }
3588
+ }
3589
+ const itemsDef = def.items;
3590
+ for (let i = 0; i < value.length; i++) {
3591
+ const itemValue = value[i];
3592
+ const itemPath = `${path}/${i}`;
3593
+ const res = validateOneOf(lexicons, itemPath, itemsDef, itemValue);
3594
+ if (!res.success) {
3595
+ return res;
3596
+ }
3597
+ }
3598
+ return { success: true };
3599
+ }
3600
+ function object(lexicons, path, def, value) {
3601
+ def = def;
3602
+ if (!value || typeof value !== "object") {
3603
+ return {
3604
+ success: false,
3605
+ error: new ValidationError(`${path} must be an object`)
3606
+ };
3607
+ }
3608
+ if (Array.isArray(def.required)) {
3609
+ for (const key of def.required) {
3610
+ if (!(key in value)) {
3611
+ return {
3612
+ success: false,
3613
+ error: new ValidationError(`${path} must have the property "${key}"`)
3614
+ };
3615
+ }
3616
+ }
3617
+ }
3618
+ if (typeof def.properties === "object") {
3619
+ for (const key in def.properties) {
3620
+ const propValue = value[key];
3621
+ if (typeof propValue === "undefined") {
3622
+ continue;
3623
+ }
3624
+ const propDef = def.properties[key];
3625
+ const propPath = `${path}/${key}`;
3626
+ const res = validateOneOf(lexicons, propPath, propDef, propValue);
3627
+ if (!res.success) {
3628
+ return res;
3629
+ }
3630
+ }
3631
+ }
3632
+ return { success: true };
3633
+ }
3634
+
3635
+ // ../lexicon/src/util.ts
3636
+ function toLexUri(str, baseUri) {
3637
+ if (str.startsWith("lex:")) {
3638
+ return str;
3639
+ }
3640
+ if (str.startsWith("#")) {
3641
+ if (!baseUri) {
3642
+ throw new Error(`Unable to resolve uri without anchor: ${str}`);
3643
+ }
3644
+ return `${baseUri}${str}`;
3645
+ }
3646
+ return `lex:${str}`;
3647
+ }
3648
+ function validateOneOf(lexicons, path, def, value, mustBeObj = false) {
3649
+ let error;
3650
+ let concreteDefs;
3651
+ if (def.type === "union") {
3652
+ if (!isDiscriminatedObject(value)) {
3653
+ return {
3654
+ success: false,
3655
+ error: new ValidationError(
3656
+ `${path} must be an object which includes the "$type" property`
3657
+ )
3658
+ };
3659
+ }
3660
+ if (!def.refs.includes(toLexUri(value.$type))) {
3661
+ if (def.closed) {
3662
+ return {
3663
+ success: false,
3664
+ error: new ValidationError(
3665
+ `${path} $type must be one of ${def.refs.join(", ")}`
3666
+ )
3667
+ };
3668
+ }
3669
+ return { success: true };
3670
+ } else {
3671
+ concreteDefs = toConcreteTypes(lexicons, {
3672
+ type: "ref",
3673
+ ref: value.$type
3674
+ });
3675
+ }
3676
+ } else {
3677
+ concreteDefs = toConcreteTypes(lexicons, def);
3678
+ }
3679
+ for (const concreteDef of concreteDefs) {
3680
+ const result = mustBeObj ? object(lexicons, path, concreteDef, value) : validate2(lexicons, path, concreteDef, value);
3681
+ if (result.success) {
3682
+ return result;
3683
+ }
3684
+ error ?? (error = result.error);
3685
+ }
3686
+ if (concreteDefs.length > 1) {
3687
+ return {
3688
+ success: false,
3689
+ error: new ValidationError(
3690
+ `${path} did not match any of the expected definitions`
3691
+ )
3692
+ };
3693
+ }
3694
+ return { success: false, error };
3695
+ }
3696
+ function assertValidOneOf(lexicons, path, def, value, mustBeObj = false) {
3697
+ const res = validateOneOf(lexicons, path, def, value, mustBeObj);
3698
+ if (!res.success) {
3699
+ throw res.error;
3700
+ }
3701
+ }
3702
+ function toConcreteTypes(lexicons, def) {
3703
+ if (def.type === "ref") {
3704
+ return [lexicons.getDefOrThrow(def.ref)];
3705
+ } else if (def.type === "union") {
3706
+ return def.refs.map((ref) => lexicons.getDefOrThrow(ref)).flat();
3707
+ } else {
3708
+ return [def];
3709
+ }
3710
+ }
3711
+
3712
+ // ../lexicon/src/validators/xrpc.ts
3713
+ function params(lexicons, path, def, value) {
3714
+ def = def;
3715
+ if (!value || typeof value !== "object") {
3716
+ value = {};
3717
+ }
3718
+ if (Array.isArray(def.required)) {
3719
+ for (const key of def.required) {
3720
+ if (!(key in value)) {
3721
+ return {
3722
+ success: false,
3723
+ error: new ValidationError(`${path} must have the property "${key}"`)
3724
+ };
3725
+ }
3726
+ }
3727
+ }
3728
+ for (const key in def.properties) {
3729
+ if (typeof value[key] === "undefined") {
3730
+ continue;
3731
+ }
3732
+ const paramDef = def.properties[key];
3733
+ const res = validate(
3734
+ lexicons,
3735
+ key,
3736
+ paramDef,
3737
+ value[key]
3738
+ );
3739
+ if (!res.success) {
3740
+ return res;
3741
+ }
3742
+ }
3743
+ return { success: true };
3744
+ }
3745
+
3746
+ // ../lexicon/src/validation.ts
3747
+ function assertValidRecord(lexicons, def, value) {
3748
+ const res = object(lexicons, "Record", def.record, value);
3749
+ if (!res.success)
3750
+ throw res.error;
3751
+ }
3752
+ function assertValidXrpcParams(lexicons, def, value) {
3753
+ if (def.parameters) {
3754
+ const res = params(lexicons, "Params", def.parameters, value);
3755
+ if (!res.success)
3756
+ throw res.error;
3757
+ }
3758
+ }
3759
+ function assertValidXrpcInput(lexicons, def, value) {
3760
+ if (def.input?.schema) {
3761
+ assertValidOneOf(lexicons, "Input", def.input.schema, value, true);
3762
+ }
3763
+ }
3764
+ function assertValidXrpcOutput(lexicons, def, value) {
3765
+ if (def.output?.schema) {
3766
+ assertValidOneOf(lexicons, "Output", def.output.schema, value, true);
3767
+ }
3768
+ }
3769
+
3770
+ // ../lexicon/src/lexicons.ts
3771
+ var Lexicons = class {
3772
+ constructor(docs) {
3773
+ this.docs = /* @__PURE__ */ new Map();
3774
+ this.defs = /* @__PURE__ */ new Map();
3775
+ if (docs?.length) {
3776
+ for (const doc of docs) {
3777
+ this.add(doc);
3778
+ }
3779
+ }
3780
+ }
3781
+ add(doc) {
3782
+ try {
3783
+ lexiconDoc.parse(doc);
3784
+ } catch (e) {
3785
+ if (e instanceof ZodError) {
3786
+ throw new LexiconDocMalformedError(
3787
+ `Failed to parse schema definition ${doc.id}`,
3788
+ doc,
3789
+ e.issues
3790
+ );
3791
+ } else {
3792
+ throw e;
3793
+ }
3794
+ }
3795
+ const validatedDoc = doc;
3796
+ const uri = toLexUri(validatedDoc.id);
3797
+ if (this.docs.has(uri)) {
3798
+ throw new Error(`${uri} has already been registered`);
3799
+ }
3800
+ resolveRefUris(validatedDoc, uri);
3801
+ this.docs.set(uri, validatedDoc);
3802
+ for (const [defUri, def] of iterDefs(validatedDoc)) {
3803
+ this.defs.set(defUri, def);
3804
+ }
3805
+ }
3806
+ remove(uri) {
3807
+ uri = toLexUri(uri);
3808
+ const doc = this.docs.get(uri);
3809
+ if (!doc) {
3810
+ throw new Error(`Unable to remove "${uri}": does not exist`);
3811
+ }
3812
+ for (const [defUri, _def] of iterDefs(doc)) {
3813
+ this.defs.delete(defUri);
3814
+ }
3815
+ this.docs.delete(uri);
3816
+ }
3817
+ get(uri) {
3818
+ uri = toLexUri(uri);
3819
+ return this.docs.get(uri);
3820
+ }
3821
+ getDef(uri) {
3822
+ uri = toLexUri(uri);
3823
+ return this.defs.get(uri);
3824
+ }
3825
+ getDefOrThrow(uri, types) {
3826
+ const def = this.getDef(uri);
3827
+ if (!def) {
3828
+ throw new LexiconDefNotFoundError(`Lexicon not found: ${uri}`);
3829
+ }
3830
+ if (types && !types.includes(def.type)) {
3831
+ throw new InvalidLexiconError(
3832
+ `Not a ${types.join(" or ")} lexicon: ${uri}`
3833
+ );
3834
+ }
3835
+ return def;
3836
+ }
3837
+ assertValidRecord(lexUri, value) {
3838
+ lexUri = toLexUri(lexUri);
3839
+ const def = this.getDefOrThrow(lexUri, ["record"]);
3840
+ if (!isObj(value)) {
3841
+ throw new ValidationError(`Record must be an object`);
3842
+ }
3843
+ if (!hasProp(value, "$type") || typeof value.$type !== "string") {
3844
+ throw new ValidationError(`Record/$type must be a string`);
3845
+ }
3846
+ const $type = value.$type || "";
3847
+ if (toLexUri($type) !== lexUri) {
3848
+ throw new ValidationError(
3849
+ `Invalid $type: must be ${lexUri}, got ${$type}`
3850
+ );
3851
+ }
3852
+ assertValidRecord(this, def, value);
3853
+ }
3854
+ assertValidXrpcParams(lexUri, value) {
3855
+ lexUri = toLexUri(lexUri);
3856
+ const def = this.getDefOrThrow(lexUri, ["query", "procedure"]);
3857
+ assertValidXrpcParams(this, def, value);
3858
+ }
3859
+ assertValidXrpcInput(lexUri, value) {
3860
+ lexUri = toLexUri(lexUri);
3861
+ const def = this.getDefOrThrow(lexUri, ["procedure"]);
3862
+ assertValidXrpcInput(this, def, value);
3863
+ }
3864
+ assertValidXrpcOutput(lexUri, value) {
3865
+ lexUri = toLexUri(lexUri);
3866
+ const def = this.getDefOrThrow(lexUri, ["query", "procedure"]);
3867
+ assertValidXrpcOutput(this, def, value);
3868
+ }
3869
+ };
3870
+ function* iterDefs(doc) {
3871
+ for (const defId in doc.defs) {
3872
+ yield [`lex:${doc.id}#${defId}`, doc.defs[defId]];
3873
+ if (defId === "main") {
3874
+ yield [`lex:${doc.id}`, doc.defs[defId]];
3875
+ }
3876
+ }
3877
+ }
3878
+ function resolveRefUris(obj, baseUri) {
3879
+ for (const k in obj) {
3880
+ if (obj.type === "ref") {
3881
+ obj.ref = toLexUri(obj.ref, baseUri);
3882
+ } else if (obj.type === "union") {
3883
+ obj.refs = obj.refs.map((ref) => toLexUri(ref, baseUri));
3884
+ } else if (Array.isArray(obj[k])) {
3885
+ obj[k] = obj[k].map((item) => {
3886
+ if (typeof item === "string") {
3887
+ return item.startsWith("#") ? toLexUri(item, baseUri) : item;
3888
+ } else if (item && typeof item === "object") {
3889
+ return resolveRefUris(item, baseUri);
3890
+ }
3891
+ return item;
3892
+ });
3893
+ } else if (obj[k] && typeof obj[k] === "object") {
3894
+ obj[k] = resolveRefUris(obj[k], baseUri);
3895
+ }
3896
+ }
3897
+ return obj;
3898
+ }
3899
+
3900
+ // src/util.ts
3901
+ function getMethodSchemaHTTPMethod(schema) {
3902
+ if (schema.type === "procedure") {
3903
+ return "post";
3904
+ }
3905
+ return "get";
3906
+ }
3907
+ function constructMethodCallUri(nsid, schema, serviceUri, params2) {
3908
+ const uri = new URL(serviceUri);
3909
+ uri.pathname = `/xrpc/${nsid}`;
3910
+ if (params2) {
3911
+ for (const [key, value] of Object.entries(params2)) {
3912
+ const paramSchema = schema.parameters?.properties?.[key];
3913
+ if (!paramSchema) {
3914
+ throw new Error(`Invalid query parameter: ${key}`);
3915
+ }
3916
+ if (value !== void 0) {
3917
+ uri.searchParams.set(key, encodeQueryParam(paramSchema.type, value));
3918
+ }
3919
+ }
3920
+ }
3921
+ return uri.toString();
3922
+ }
3923
+ function encodeQueryParam(type, value) {
3924
+ if (type === "string" || type === "unknown") {
3925
+ return String(value);
3926
+ }
3927
+ if (type === "number") {
3928
+ return String(Number(value));
3929
+ } else if (type === "integer") {
3930
+ return String(Number(value) | 0);
3931
+ } else if (type === "boolean") {
3932
+ return value ? "true" : "false";
3933
+ } else if (type === "datetime") {
3934
+ if (value instanceof Date) {
3935
+ return value.toISOString();
3936
+ }
3937
+ return String(value);
3938
+ }
3939
+ throw new Error(`Unsupported query param type: ${type}`);
3940
+ }
3941
+ function constructMethodCallHeaders(schema, data, opts) {
3942
+ const headers = opts?.headers || {};
3943
+ if (schema.type === "procedure") {
3944
+ if (opts?.encoding) {
3945
+ headers["Content-Type"] = opts.encoding;
3946
+ }
3947
+ if (data && typeof data === "object") {
3948
+ if (!headers["Content-Type"]) {
3949
+ headers["Content-Type"] = "application/json";
3950
+ }
3951
+ }
3952
+ }
3953
+ return headers;
3954
+ }
3955
+ function encodeMethodCallBody(headers, data) {
3956
+ if (!headers["Content-Type"] || typeof data === "undefined") {
3957
+ return void 0;
3958
+ }
3959
+ if (data instanceof ArrayBuffer) {
3960
+ return data;
3961
+ }
3962
+ if (headers["Content-Type"].startsWith("text/")) {
3963
+ return new TextEncoder().encode(data.toString());
3964
+ }
3965
+ if (headers["Content-Type"].startsWith("application/json")) {
3966
+ return new TextEncoder().encode(JSON.stringify(data));
3967
+ }
3968
+ return data;
3969
+ }
3970
+ function httpResponseCodeToEnum(status) {
3971
+ let resCode;
3972
+ if (status in ResponseType) {
3973
+ resCode = status;
3974
+ } else if (status >= 100 && status < 200) {
3975
+ resCode = 404 /* XRPCNotSupported */;
3976
+ } else if (status >= 200 && status < 300) {
3977
+ resCode = 200 /* Success */;
3978
+ } else if (status >= 300 && status < 400) {
3979
+ resCode = 404 /* XRPCNotSupported */;
3980
+ } else if (status >= 400 && status < 500) {
3981
+ resCode = 400 /* InvalidRequest */;
3982
+ } else {
3983
+ resCode = 500 /* InternalServerError */;
3984
+ }
3985
+ return resCode;
3986
+ }
3987
+ function httpResponseBodyParse(mimeType, data) {
3988
+ if (mimeType) {
3989
+ if (mimeType.includes("application/json") && data?.byteLength) {
3990
+ try {
3991
+ const str = new TextDecoder().decode(data);
3992
+ return JSON.parse(str);
3993
+ } catch (e) {
3994
+ throw new XRPCError(
3995
+ 2 /* InvalidResponse */,
3996
+ `Failed to parse response body: ${String(e)}`
3997
+ );
3998
+ }
3999
+ }
4000
+ if (mimeType.startsWith("text/") && data?.byteLength) {
4001
+ try {
4002
+ return new TextDecoder().decode(data);
4003
+ } catch (e) {
4004
+ throw new XRPCError(
4005
+ 2 /* InvalidResponse */,
4006
+ `Failed to parse response body: ${String(e)}`
4007
+ );
4008
+ }
4009
+ }
4010
+ }
4011
+ return data;
4012
+ }
4013
+
4014
+ // src/client.ts
4015
+ var Client = class {
4016
+ constructor() {
4017
+ this.fetch = defaultFetchHandler;
4018
+ this.lex = new Lexicons();
4019
+ }
4020
+ async call(serviceUri, methodNsid, params2, data, opts) {
4021
+ return this.service(serviceUri).call(methodNsid, params2, data, opts);
4022
+ }
4023
+ service(serviceUri) {
4024
+ return new ServiceClient(this, serviceUri);
4025
+ }
4026
+ addLexicon(doc) {
4027
+ this.lex.add(doc);
4028
+ }
4029
+ addLexicons(docs) {
4030
+ for (const doc of docs) {
4031
+ this.addLexicon(doc);
4032
+ }
4033
+ }
4034
+ removeLexicon(uri) {
4035
+ this.lex.remove(uri);
4036
+ }
4037
+ };
4038
+ var ServiceClient = class {
4039
+ constructor(baseClient, serviceUri) {
4040
+ this.headers = {};
4041
+ this.baseClient = baseClient;
4042
+ this.uri = typeof serviceUri === "string" ? new URL(serviceUri) : serviceUri;
4043
+ }
4044
+ setHeader(key, value) {
4045
+ this.headers[key] = value;
4046
+ }
4047
+ unsetHeader(key) {
4048
+ delete this.headers[key];
4049
+ }
4050
+ async call(methodNsid, params2, data, opts) {
4051
+ const def = this.baseClient.lex.getDefOrThrow(methodNsid);
4052
+ if (!def || def.type !== "query" && def.type !== "procedure") {
4053
+ throw new Error(
4054
+ `Invalid lexicon: ${methodNsid}. Must be a query or procedure.`
4055
+ );
4056
+ }
4057
+ const httpMethod = getMethodSchemaHTTPMethod(def);
4058
+ const httpUri = constructMethodCallUri(methodNsid, def, this.uri, params2);
4059
+ const httpHeaders = constructMethodCallHeaders(def, data, {
4060
+ headers: {
4061
+ ...this.headers,
4062
+ ...opts?.headers
4063
+ },
4064
+ encoding: opts?.encoding
4065
+ });
4066
+ const res = await this.baseClient.fetch(
4067
+ httpUri,
4068
+ httpMethod,
4069
+ httpHeaders,
4070
+ data
4071
+ );
4072
+ const resCode = httpResponseCodeToEnum(res.status);
4073
+ if (resCode === 200 /* Success */) {
4074
+ return new XRPCResponse(res.body, res.headers);
4075
+ } else {
4076
+ if (res.body && isErrorResponseBody(res.body)) {
4077
+ throw new XRPCError(resCode, res.body.error, res.body.message);
4078
+ } else {
4079
+ throw new XRPCError(resCode);
4080
+ }
4081
+ }
4082
+ }
4083
+ };
4084
+ async function defaultFetchHandler(httpUri, httpMethod, httpHeaders, httpReqBody) {
4085
+ try {
4086
+ const res = await fetch(httpUri, {
4087
+ method: httpMethod,
4088
+ headers: httpHeaders,
4089
+ body: encodeMethodCallBody(httpHeaders, httpReqBody)
4090
+ });
4091
+ const resBody = await res.arrayBuffer();
4092
+ return {
4093
+ status: res.status,
4094
+ headers: Object.fromEntries(res.headers.entries()),
4095
+ body: httpResponseBodyParse(res.headers.get("content-type"), resBody)
4096
+ };
4097
+ } catch (e) {
4098
+ throw new XRPCError(1 /* Unknown */, String(e));
4099
+ }
4100
+ }
4101
+ function isErrorResponseBody(v) {
4102
+ return errorResponseBody.safeParse(v).success;
4103
+ }
4104
+
4105
+ // src/index.ts
4106
+ var defaultInst = new Client();
4107
+ var src_default = defaultInst;
4108
+ // Annotate the CommonJS export names for ESM import in node:
4109
+ 0 && (module.exports = {
4110
+ Client,
4111
+ ResponseType,
4112
+ ResponseTypeNames,
4113
+ ResponseTypeStrings,
4114
+ ServiceClient,
4115
+ XRPCError,
4116
+ XRPCResponse,
4117
+ errorResponseBody
4118
+ });
4119
+ //# sourceMappingURL=index.js.map