fetchtype 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4098 +1,57 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/index.ts
8
- import { access, appendFile, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
9
- import { dirname as dirname2, resolve as resolve4 } from "path";
10
- import process2 from "process";
11
- import chalk from "chalk";
12
- import { Command, CommanderError, Option } from "commander";
13
- import { lilconfig } from "lilconfig";
14
-
15
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
16
- var external_exports = {};
17
- __export(external_exports, {
18
- BRAND: () => BRAND,
19
- DIRTY: () => DIRTY,
20
- EMPTY_PATH: () => EMPTY_PATH,
21
- INVALID: () => INVALID,
22
- NEVER: () => NEVER,
23
- OK: () => OK,
24
- ParseStatus: () => ParseStatus,
25
- Schema: () => ZodType,
26
- ZodAny: () => ZodAny,
27
- ZodArray: () => ZodArray,
28
- ZodBigInt: () => ZodBigInt,
29
- ZodBoolean: () => ZodBoolean,
30
- ZodBranded: () => ZodBranded,
31
- ZodCatch: () => ZodCatch,
32
- ZodDate: () => ZodDate,
33
- ZodDefault: () => ZodDefault,
34
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
35
- ZodEffects: () => ZodEffects,
36
- ZodEnum: () => ZodEnum,
37
- ZodError: () => ZodError,
38
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
39
- ZodFunction: () => ZodFunction,
40
- ZodIntersection: () => ZodIntersection,
41
- ZodIssueCode: () => ZodIssueCode,
42
- ZodLazy: () => ZodLazy,
43
- ZodLiteral: () => ZodLiteral,
44
- ZodMap: () => ZodMap,
45
- ZodNaN: () => ZodNaN,
46
- ZodNativeEnum: () => ZodNativeEnum,
47
- ZodNever: () => ZodNever,
48
- ZodNull: () => ZodNull,
49
- ZodNullable: () => ZodNullable,
50
- ZodNumber: () => ZodNumber,
51
- ZodObject: () => ZodObject,
52
- ZodOptional: () => ZodOptional,
53
- ZodParsedType: () => ZodParsedType,
54
- ZodPipeline: () => ZodPipeline,
55
- ZodPromise: () => ZodPromise,
56
- ZodReadonly: () => ZodReadonly,
57
- ZodRecord: () => ZodRecord,
58
- ZodSchema: () => ZodType,
59
- ZodSet: () => ZodSet,
60
- ZodString: () => ZodString,
61
- ZodSymbol: () => ZodSymbol,
62
- ZodTransformer: () => ZodEffects,
63
- ZodTuple: () => ZodTuple,
64
- ZodType: () => ZodType,
65
- ZodUndefined: () => ZodUndefined,
66
- ZodUnion: () => ZodUnion,
67
- ZodUnknown: () => ZodUnknown,
68
- ZodVoid: () => ZodVoid,
69
- addIssueToContext: () => addIssueToContext,
70
- any: () => anyType,
71
- array: () => arrayType,
72
- bigint: () => bigIntType,
73
- boolean: () => booleanType,
74
- coerce: () => coerce,
75
- custom: () => custom,
76
- date: () => dateType,
77
- datetimeRegex: () => datetimeRegex,
78
- defaultErrorMap: () => en_default,
79
- discriminatedUnion: () => discriminatedUnionType,
80
- effect: () => effectsType,
81
- enum: () => enumType,
82
- function: () => functionType,
83
- getErrorMap: () => getErrorMap,
84
- getParsedType: () => getParsedType,
85
- instanceof: () => instanceOfType,
86
- intersection: () => intersectionType,
87
- isAborted: () => isAborted,
88
- isAsync: () => isAsync,
89
- isDirty: () => isDirty,
90
- isValid: () => isValid,
91
- late: () => late,
92
- lazy: () => lazyType,
93
- literal: () => literalType,
94
- makeIssue: () => makeIssue,
95
- map: () => mapType,
96
- nan: () => nanType,
97
- nativeEnum: () => nativeEnumType,
98
- never: () => neverType,
99
- null: () => nullType,
100
- nullable: () => nullableType,
101
- number: () => numberType,
102
- object: () => objectType,
103
- objectUtil: () => objectUtil,
104
- oboolean: () => oboolean,
105
- onumber: () => onumber,
106
- optional: () => optionalType,
107
- ostring: () => ostring,
108
- pipeline: () => pipelineType,
109
- preprocess: () => preprocessType,
110
- promise: () => promiseType,
111
- quotelessJson: () => quotelessJson,
112
- record: () => recordType,
113
- set: () => setType,
114
- setErrorMap: () => setErrorMap,
115
- strictObject: () => strictObjectType,
116
- string: () => stringType,
117
- symbol: () => symbolType,
118
- transformer: () => effectsType,
119
- tuple: () => tupleType,
120
- undefined: () => undefinedType,
121
- union: () => unionType,
122
- unknown: () => unknownType,
123
- util: () => util,
124
- void: () => voidType
125
- });
126
-
127
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
128
- var util;
129
- (function(util2) {
130
- util2.assertEqual = (_) => {
131
- };
132
- function assertIs(_arg) {
133
- }
134
- util2.assertIs = assertIs;
135
- function assertNever(_x) {
136
- throw new Error();
137
- }
138
- util2.assertNever = assertNever;
139
- util2.arrayToEnum = (items) => {
140
- const obj = {};
141
- for (const item of items) {
142
- obj[item] = item;
143
- }
144
- return obj;
145
- };
146
- util2.getValidEnumValues = (obj) => {
147
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
148
- const filtered = {};
149
- for (const k of validKeys) {
150
- filtered[k] = obj[k];
151
- }
152
- return util2.objectValues(filtered);
153
- };
154
- util2.objectValues = (obj) => {
155
- return util2.objectKeys(obj).map(function(e) {
156
- return obj[e];
157
- });
158
- };
159
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
160
- const keys = [];
161
- for (const key in object) {
162
- if (Object.prototype.hasOwnProperty.call(object, key)) {
163
- keys.push(key);
164
- }
165
- }
166
- return keys;
167
- };
168
- util2.find = (arr, checker) => {
169
- for (const item of arr) {
170
- if (checker(item))
171
- return item;
172
- }
173
- return void 0;
174
- };
175
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
176
- function joinValues(array, separator = " | ") {
177
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
178
- }
179
- util2.joinValues = joinValues;
180
- util2.jsonStringifyReplacer = (_, value) => {
181
- if (typeof value === "bigint") {
182
- return value.toString();
183
- }
184
- return value;
185
- };
186
- })(util || (util = {}));
187
- var objectUtil;
188
- (function(objectUtil2) {
189
- objectUtil2.mergeShapes = (first, second) => {
190
- return {
191
- ...first,
192
- ...second
193
- // second overwrites first
194
- };
195
- };
196
- })(objectUtil || (objectUtil = {}));
197
- var ZodParsedType = util.arrayToEnum([
198
- "string",
199
- "nan",
200
- "number",
201
- "integer",
202
- "float",
203
- "boolean",
204
- "date",
205
- "bigint",
206
- "symbol",
207
- "function",
208
- "undefined",
209
- "null",
210
- "array",
211
- "object",
212
- "unknown",
213
- "promise",
214
- "void",
215
- "never",
216
- "map",
217
- "set"
218
- ]);
219
- var getParsedType = (data) => {
220
- const t = typeof data;
221
- switch (t) {
222
- case "undefined":
223
- return ZodParsedType.undefined;
224
- case "string":
225
- return ZodParsedType.string;
226
- case "number":
227
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
228
- case "boolean":
229
- return ZodParsedType.boolean;
230
- case "function":
231
- return ZodParsedType.function;
232
- case "bigint":
233
- return ZodParsedType.bigint;
234
- case "symbol":
235
- return ZodParsedType.symbol;
236
- case "object":
237
- if (Array.isArray(data)) {
238
- return ZodParsedType.array;
239
- }
240
- if (data === null) {
241
- return ZodParsedType.null;
242
- }
243
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
244
- return ZodParsedType.promise;
245
- }
246
- if (typeof Map !== "undefined" && data instanceof Map) {
247
- return ZodParsedType.map;
248
- }
249
- if (typeof Set !== "undefined" && data instanceof Set) {
250
- return ZodParsedType.set;
251
- }
252
- if (typeof Date !== "undefined" && data instanceof Date) {
253
- return ZodParsedType.date;
254
- }
255
- return ZodParsedType.object;
256
- default:
257
- return ZodParsedType.unknown;
258
- }
259
- };
260
-
261
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
262
- var ZodIssueCode = util.arrayToEnum([
263
- "invalid_type",
264
- "invalid_literal",
265
- "custom",
266
- "invalid_union",
267
- "invalid_union_discriminator",
268
- "invalid_enum_value",
269
- "unrecognized_keys",
270
- "invalid_arguments",
271
- "invalid_return_type",
272
- "invalid_date",
273
- "invalid_string",
274
- "too_small",
275
- "too_big",
276
- "invalid_intersection_types",
277
- "not_multiple_of",
278
- "not_finite"
279
- ]);
280
- var quotelessJson = (obj) => {
281
- const json = JSON.stringify(obj, null, 2);
282
- return json.replace(/"([^"]+)":/g, "$1:");
283
- };
284
- var ZodError = class _ZodError extends Error {
285
- get errors() {
286
- return this.issues;
287
- }
288
- constructor(issues) {
289
- super();
290
- this.issues = [];
291
- this.addIssue = (sub) => {
292
- this.issues = [...this.issues, sub];
293
- };
294
- this.addIssues = (subs = []) => {
295
- this.issues = [...this.issues, ...subs];
296
- };
297
- const actualProto = new.target.prototype;
298
- if (Object.setPrototypeOf) {
299
- Object.setPrototypeOf(this, actualProto);
300
- } else {
301
- this.__proto__ = actualProto;
302
- }
303
- this.name = "ZodError";
304
- this.issues = issues;
305
- }
306
- format(_mapper) {
307
- const mapper = _mapper || function(issue) {
308
- return issue.message;
309
- };
310
- const fieldErrors = { _errors: [] };
311
- const processError = (error) => {
312
- for (const issue of error.issues) {
313
- if (issue.code === "invalid_union") {
314
- issue.unionErrors.map(processError);
315
- } else if (issue.code === "invalid_return_type") {
316
- processError(issue.returnTypeError);
317
- } else if (issue.code === "invalid_arguments") {
318
- processError(issue.argumentsError);
319
- } else if (issue.path.length === 0) {
320
- fieldErrors._errors.push(mapper(issue));
321
- } else {
322
- let curr = fieldErrors;
323
- let i = 0;
324
- while (i < issue.path.length) {
325
- const el = issue.path[i];
326
- const terminal = i === issue.path.length - 1;
327
- if (!terminal) {
328
- curr[el] = curr[el] || { _errors: [] };
329
- } else {
330
- curr[el] = curr[el] || { _errors: [] };
331
- curr[el]._errors.push(mapper(issue));
332
- }
333
- curr = curr[el];
334
- i++;
335
- }
336
- }
337
- }
338
- };
339
- processError(this);
340
- return fieldErrors;
341
- }
342
- static assert(value) {
343
- if (!(value instanceof _ZodError)) {
344
- throw new Error(`Not a ZodError: ${value}`);
345
- }
346
- }
347
- toString() {
348
- return this.message;
349
- }
350
- get message() {
351
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
352
- }
353
- get isEmpty() {
354
- return this.issues.length === 0;
355
- }
356
- flatten(mapper = (issue) => issue.message) {
357
- const fieldErrors = {};
358
- const formErrors = [];
359
- for (const sub of this.issues) {
360
- if (sub.path.length > 0) {
361
- const firstEl = sub.path[0];
362
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
363
- fieldErrors[firstEl].push(mapper(sub));
364
- } else {
365
- formErrors.push(mapper(sub));
366
- }
367
- }
368
- return { formErrors, fieldErrors };
369
- }
370
- get formErrors() {
371
- return this.flatten();
372
- }
373
- };
374
- ZodError.create = (issues) => {
375
- const error = new ZodError(issues);
376
- return error;
377
- };
378
-
379
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
380
- var errorMap = (issue, _ctx) => {
381
- let message;
382
- switch (issue.code) {
383
- case ZodIssueCode.invalid_type:
384
- if (issue.received === ZodParsedType.undefined) {
385
- message = "Required";
386
- } else {
387
- message = `Expected ${issue.expected}, received ${issue.received}`;
388
- }
389
- break;
390
- case ZodIssueCode.invalid_literal:
391
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
392
- break;
393
- case ZodIssueCode.unrecognized_keys:
394
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
395
- break;
396
- case ZodIssueCode.invalid_union:
397
- message = `Invalid input`;
398
- break;
399
- case ZodIssueCode.invalid_union_discriminator:
400
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
401
- break;
402
- case ZodIssueCode.invalid_enum_value:
403
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
404
- break;
405
- case ZodIssueCode.invalid_arguments:
406
- message = `Invalid function arguments`;
407
- break;
408
- case ZodIssueCode.invalid_return_type:
409
- message = `Invalid function return type`;
410
- break;
411
- case ZodIssueCode.invalid_date:
412
- message = `Invalid date`;
413
- break;
414
- case ZodIssueCode.invalid_string:
415
- if (typeof issue.validation === "object") {
416
- if ("includes" in issue.validation) {
417
- message = `Invalid input: must include "${issue.validation.includes}"`;
418
- if (typeof issue.validation.position === "number") {
419
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
420
- }
421
- } else if ("startsWith" in issue.validation) {
422
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
423
- } else if ("endsWith" in issue.validation) {
424
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
425
- } else {
426
- util.assertNever(issue.validation);
427
- }
428
- } else if (issue.validation !== "regex") {
429
- message = `Invalid ${issue.validation}`;
430
- } else {
431
- message = "Invalid";
432
- }
433
- break;
434
- case ZodIssueCode.too_small:
435
- if (issue.type === "array")
436
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
437
- else if (issue.type === "string")
438
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
439
- else if (issue.type === "number")
440
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
441
- else if (issue.type === "bigint")
442
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
443
- else if (issue.type === "date")
444
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
445
- else
446
- message = "Invalid input";
447
- break;
448
- case ZodIssueCode.too_big:
449
- if (issue.type === "array")
450
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
451
- else if (issue.type === "string")
452
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
453
- else if (issue.type === "number")
454
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
455
- else if (issue.type === "bigint")
456
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
457
- else if (issue.type === "date")
458
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
459
- else
460
- message = "Invalid input";
461
- break;
462
- case ZodIssueCode.custom:
463
- message = `Invalid input`;
464
- break;
465
- case ZodIssueCode.invalid_intersection_types:
466
- message = `Intersection results could not be merged`;
467
- break;
468
- case ZodIssueCode.not_multiple_of:
469
- message = `Number must be a multiple of ${issue.multipleOf}`;
470
- break;
471
- case ZodIssueCode.not_finite:
472
- message = "Number must be finite";
473
- break;
474
- default:
475
- message = _ctx.defaultError;
476
- util.assertNever(issue);
477
- }
478
- return { message };
479
- };
480
- var en_default = errorMap;
481
-
482
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
483
- var overrideErrorMap = en_default;
484
- function setErrorMap(map) {
485
- overrideErrorMap = map;
486
- }
487
- function getErrorMap() {
488
- return overrideErrorMap;
489
- }
490
-
491
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
492
- var makeIssue = (params) => {
493
- const { data, path, errorMaps, issueData } = params;
494
- const fullPath = [...path, ...issueData.path || []];
495
- const fullIssue = {
496
- ...issueData,
497
- path: fullPath
498
- };
499
- if (issueData.message !== void 0) {
500
- return {
501
- ...issueData,
502
- path: fullPath,
503
- message: issueData.message
504
- };
505
- }
506
- let errorMessage = "";
507
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
508
- for (const map of maps) {
509
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
510
- }
511
- return {
512
- ...issueData,
513
- path: fullPath,
514
- message: errorMessage
515
- };
516
- };
517
- var EMPTY_PATH = [];
518
- function addIssueToContext(ctx, issueData) {
519
- const overrideMap = getErrorMap();
520
- const issue = makeIssue({
521
- issueData,
522
- data: ctx.data,
523
- path: ctx.path,
524
- errorMaps: [
525
- ctx.common.contextualErrorMap,
526
- // contextual error map is first priority
527
- ctx.schemaErrorMap,
528
- // then schema-bound map if available
529
- overrideMap,
530
- // then global override map
531
- overrideMap === en_default ? void 0 : en_default
532
- // then global default map
533
- ].filter((x) => !!x)
534
- });
535
- ctx.common.issues.push(issue);
536
- }
537
- var ParseStatus = class _ParseStatus {
538
- constructor() {
539
- this.value = "valid";
540
- }
541
- dirty() {
542
- if (this.value === "valid")
543
- this.value = "dirty";
544
- }
545
- abort() {
546
- if (this.value !== "aborted")
547
- this.value = "aborted";
548
- }
549
- static mergeArray(status, results) {
550
- const arrayValue = [];
551
- for (const s of results) {
552
- if (s.status === "aborted")
553
- return INVALID;
554
- if (s.status === "dirty")
555
- status.dirty();
556
- arrayValue.push(s.value);
557
- }
558
- return { status: status.value, value: arrayValue };
559
- }
560
- static async mergeObjectAsync(status, pairs) {
561
- const syncPairs = [];
562
- for (const pair of pairs) {
563
- const key = await pair.key;
564
- const value = await pair.value;
565
- syncPairs.push({
566
- key,
567
- value
568
- });
569
- }
570
- return _ParseStatus.mergeObjectSync(status, syncPairs);
571
- }
572
- static mergeObjectSync(status, pairs) {
573
- const finalObject = {};
574
- for (const pair of pairs) {
575
- const { key, value } = pair;
576
- if (key.status === "aborted")
577
- return INVALID;
578
- if (value.status === "aborted")
579
- return INVALID;
580
- if (key.status === "dirty")
581
- status.dirty();
582
- if (value.status === "dirty")
583
- status.dirty();
584
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
585
- finalObject[key.value] = value.value;
586
- }
587
- }
588
- return { status: status.value, value: finalObject };
589
- }
590
- };
591
- var INVALID = Object.freeze({
592
- status: "aborted"
593
- });
594
- var DIRTY = (value) => ({ status: "dirty", value });
595
- var OK = (value) => ({ status: "valid", value });
596
- var isAborted = (x) => x.status === "aborted";
597
- var isDirty = (x) => x.status === "dirty";
598
- var isValid = (x) => x.status === "valid";
599
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
600
-
601
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
602
- var errorUtil;
603
- (function(errorUtil2) {
604
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
605
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
606
- })(errorUtil || (errorUtil = {}));
607
-
608
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
609
- var ParseInputLazyPath = class {
610
- constructor(parent, value, path, key) {
611
- this._cachedPath = [];
612
- this.parent = parent;
613
- this.data = value;
614
- this._path = path;
615
- this._key = key;
616
- }
617
- get path() {
618
- if (!this._cachedPath.length) {
619
- if (Array.isArray(this._key)) {
620
- this._cachedPath.push(...this._path, ...this._key);
621
- } else {
622
- this._cachedPath.push(...this._path, this._key);
623
- }
624
- }
625
- return this._cachedPath;
626
- }
627
- };
628
- var handleResult = (ctx, result) => {
629
- if (isValid(result)) {
630
- return { success: true, data: result.value };
631
- } else {
632
- if (!ctx.common.issues.length) {
633
- throw new Error("Validation failed but no issues detected.");
634
- }
635
- return {
636
- success: false,
637
- get error() {
638
- if (this._error)
639
- return this._error;
640
- const error = new ZodError(ctx.common.issues);
641
- this._error = error;
642
- return this._error;
643
- }
644
- };
645
- }
646
- };
647
- function processCreateParams(params) {
648
- if (!params)
649
- return {};
650
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
651
- if (errorMap2 && (invalid_type_error || required_error)) {
652
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
653
- }
654
- if (errorMap2)
655
- return { errorMap: errorMap2, description };
656
- const customMap = (iss, ctx) => {
657
- const { message } = params;
658
- if (iss.code === "invalid_enum_value") {
659
- return { message: message ?? ctx.defaultError };
660
- }
661
- if (typeof ctx.data === "undefined") {
662
- return { message: message ?? required_error ?? ctx.defaultError };
663
- }
664
- if (iss.code !== "invalid_type")
665
- return { message: ctx.defaultError };
666
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
667
- };
668
- return { errorMap: customMap, description };
669
- }
670
- var ZodType = class {
671
- get description() {
672
- return this._def.description;
673
- }
674
- _getType(input) {
675
- return getParsedType(input.data);
676
- }
677
- _getOrReturnCtx(input, ctx) {
678
- return ctx || {
679
- common: input.parent.common,
680
- data: input.data,
681
- parsedType: getParsedType(input.data),
682
- schemaErrorMap: this._def.errorMap,
683
- path: input.path,
684
- parent: input.parent
685
- };
686
- }
687
- _processInputParams(input) {
688
- return {
689
- status: new ParseStatus(),
690
- ctx: {
691
- common: input.parent.common,
692
- data: input.data,
693
- parsedType: getParsedType(input.data),
694
- schemaErrorMap: this._def.errorMap,
695
- path: input.path,
696
- parent: input.parent
697
- }
698
- };
699
- }
700
- _parseSync(input) {
701
- const result = this._parse(input);
702
- if (isAsync(result)) {
703
- throw new Error("Synchronous parse encountered promise.");
704
- }
705
- return result;
706
- }
707
- _parseAsync(input) {
708
- const result = this._parse(input);
709
- return Promise.resolve(result);
710
- }
711
- parse(data, params) {
712
- const result = this.safeParse(data, params);
713
- if (result.success)
714
- return result.data;
715
- throw result.error;
716
- }
717
- safeParse(data, params) {
718
- const ctx = {
719
- common: {
720
- issues: [],
721
- async: params?.async ?? false,
722
- contextualErrorMap: params?.errorMap
723
- },
724
- path: params?.path || [],
725
- schemaErrorMap: this._def.errorMap,
726
- parent: null,
727
- data,
728
- parsedType: getParsedType(data)
729
- };
730
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
731
- return handleResult(ctx, result);
732
- }
733
- "~validate"(data) {
734
- const ctx = {
735
- common: {
736
- issues: [],
737
- async: !!this["~standard"].async
738
- },
739
- path: [],
740
- schemaErrorMap: this._def.errorMap,
741
- parent: null,
742
- data,
743
- parsedType: getParsedType(data)
744
- };
745
- if (!this["~standard"].async) {
746
- try {
747
- const result = this._parseSync({ data, path: [], parent: ctx });
748
- return isValid(result) ? {
749
- value: result.value
750
- } : {
751
- issues: ctx.common.issues
752
- };
753
- } catch (err) {
754
- if (err?.message?.toLowerCase()?.includes("encountered")) {
755
- this["~standard"].async = true;
756
- }
757
- ctx.common = {
758
- issues: [],
759
- async: true
760
- };
761
- }
762
- }
763
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
764
- value: result.value
765
- } : {
766
- issues: ctx.common.issues
767
- });
768
- }
769
- async parseAsync(data, params) {
770
- const result = await this.safeParseAsync(data, params);
771
- if (result.success)
772
- return result.data;
773
- throw result.error;
774
- }
775
- async safeParseAsync(data, params) {
776
- const ctx = {
777
- common: {
778
- issues: [],
779
- contextualErrorMap: params?.errorMap,
780
- async: true
781
- },
782
- path: params?.path || [],
783
- schemaErrorMap: this._def.errorMap,
784
- parent: null,
785
- data,
786
- parsedType: getParsedType(data)
787
- };
788
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
789
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
790
- return handleResult(ctx, result);
791
- }
792
- refine(check, message) {
793
- const getIssueProperties = (val) => {
794
- if (typeof message === "string" || typeof message === "undefined") {
795
- return { message };
796
- } else if (typeof message === "function") {
797
- return message(val);
798
- } else {
799
- return message;
800
- }
801
- };
802
- return this._refinement((val, ctx) => {
803
- const result = check(val);
804
- const setError = () => ctx.addIssue({
805
- code: ZodIssueCode.custom,
806
- ...getIssueProperties(val)
807
- });
808
- if (typeof Promise !== "undefined" && result instanceof Promise) {
809
- return result.then((data) => {
810
- if (!data) {
811
- setError();
812
- return false;
813
- } else {
814
- return true;
815
- }
816
- });
817
- }
818
- if (!result) {
819
- setError();
820
- return false;
821
- } else {
822
- return true;
823
- }
824
- });
825
- }
826
- refinement(check, refinementData) {
827
- return this._refinement((val, ctx) => {
828
- if (!check(val)) {
829
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
830
- return false;
831
- } else {
832
- return true;
833
- }
834
- });
835
- }
836
- _refinement(refinement) {
837
- return new ZodEffects({
838
- schema: this,
839
- typeName: ZodFirstPartyTypeKind.ZodEffects,
840
- effect: { type: "refinement", refinement }
841
- });
842
- }
843
- superRefine(refinement) {
844
- return this._refinement(refinement);
845
- }
846
- constructor(def) {
847
- this.spa = this.safeParseAsync;
848
- this._def = def;
849
- this.parse = this.parse.bind(this);
850
- this.safeParse = this.safeParse.bind(this);
851
- this.parseAsync = this.parseAsync.bind(this);
852
- this.safeParseAsync = this.safeParseAsync.bind(this);
853
- this.spa = this.spa.bind(this);
854
- this.refine = this.refine.bind(this);
855
- this.refinement = this.refinement.bind(this);
856
- this.superRefine = this.superRefine.bind(this);
857
- this.optional = this.optional.bind(this);
858
- this.nullable = this.nullable.bind(this);
859
- this.nullish = this.nullish.bind(this);
860
- this.array = this.array.bind(this);
861
- this.promise = this.promise.bind(this);
862
- this.or = this.or.bind(this);
863
- this.and = this.and.bind(this);
864
- this.transform = this.transform.bind(this);
865
- this.brand = this.brand.bind(this);
866
- this.default = this.default.bind(this);
867
- this.catch = this.catch.bind(this);
868
- this.describe = this.describe.bind(this);
869
- this.pipe = this.pipe.bind(this);
870
- this.readonly = this.readonly.bind(this);
871
- this.isNullable = this.isNullable.bind(this);
872
- this.isOptional = this.isOptional.bind(this);
873
- this["~standard"] = {
874
- version: 1,
875
- vendor: "zod",
876
- validate: (data) => this["~validate"](data)
877
- };
878
- }
879
- optional() {
880
- return ZodOptional.create(this, this._def);
881
- }
882
- nullable() {
883
- return ZodNullable.create(this, this._def);
884
- }
885
- nullish() {
886
- return this.nullable().optional();
887
- }
888
- array() {
889
- return ZodArray.create(this);
890
- }
891
- promise() {
892
- return ZodPromise.create(this, this._def);
893
- }
894
- or(option) {
895
- return ZodUnion.create([this, option], this._def);
896
- }
897
- and(incoming) {
898
- return ZodIntersection.create(this, incoming, this._def);
899
- }
900
- transform(transform) {
901
- return new ZodEffects({
902
- ...processCreateParams(this._def),
903
- schema: this,
904
- typeName: ZodFirstPartyTypeKind.ZodEffects,
905
- effect: { type: "transform", transform }
906
- });
907
- }
908
- default(def) {
909
- const defaultValueFunc = typeof def === "function" ? def : () => def;
910
- return new ZodDefault({
911
- ...processCreateParams(this._def),
912
- innerType: this,
913
- defaultValue: defaultValueFunc,
914
- typeName: ZodFirstPartyTypeKind.ZodDefault
915
- });
916
- }
917
- brand() {
918
- return new ZodBranded({
919
- typeName: ZodFirstPartyTypeKind.ZodBranded,
920
- type: this,
921
- ...processCreateParams(this._def)
922
- });
923
- }
924
- catch(def) {
925
- const catchValueFunc = typeof def === "function" ? def : () => def;
926
- return new ZodCatch({
927
- ...processCreateParams(this._def),
928
- innerType: this,
929
- catchValue: catchValueFunc,
930
- typeName: ZodFirstPartyTypeKind.ZodCatch
931
- });
932
- }
933
- describe(description) {
934
- const This = this.constructor;
935
- return new This({
936
- ...this._def,
937
- description
938
- });
939
- }
940
- pipe(target) {
941
- return ZodPipeline.create(this, target);
942
- }
943
- readonly() {
944
- return ZodReadonly.create(this);
945
- }
946
- isOptional() {
947
- return this.safeParse(void 0).success;
948
- }
949
- isNullable() {
950
- return this.safeParse(null).success;
951
- }
952
- };
953
- var cuidRegex = /^c[^\s-]{8,}$/i;
954
- var cuid2Regex = /^[0-9a-z]+$/;
955
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
956
- var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
957
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
958
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
959
- var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
960
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
961
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
962
- var emojiRegex;
963
- var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
964
- var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
965
- var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
966
- var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
967
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
968
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
969
- var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
970
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
971
- function timeRegexSource(args) {
972
- let secondsRegexSource = `[0-5]\\d`;
973
- if (args.precision) {
974
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
975
- } else if (args.precision == null) {
976
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
977
- }
978
- const secondsQuantifier = args.precision ? "+" : "?";
979
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
980
- }
981
- function timeRegex(args) {
982
- return new RegExp(`^${timeRegexSource(args)}$`);
983
- }
984
- function datetimeRegex(args) {
985
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
986
- const opts = [];
987
- opts.push(args.local ? `Z?` : `Z`);
988
- if (args.offset)
989
- opts.push(`([+-]\\d{2}:?\\d{2})`);
990
- regex = `${regex}(${opts.join("|")})`;
991
- return new RegExp(`^${regex}$`);
992
- }
993
- function isValidIP(ip, version) {
994
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
995
- return true;
996
- }
997
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
998
- return true;
999
- }
1000
- return false;
1001
- }
1002
- function isValidJWT(jwt, alg) {
1003
- if (!jwtRegex.test(jwt))
1004
- return false;
1005
- try {
1006
- const [header] = jwt.split(".");
1007
- if (!header)
1008
- return false;
1009
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1010
- const decoded = JSON.parse(atob(base64));
1011
- if (typeof decoded !== "object" || decoded === null)
1012
- return false;
1013
- if ("typ" in decoded && decoded?.typ !== "JWT")
1014
- return false;
1015
- if (!decoded.alg)
1016
- return false;
1017
- if (alg && decoded.alg !== alg)
1018
- return false;
1019
- return true;
1020
- } catch {
1021
- return false;
1022
- }
1023
- }
1024
- function isValidCidr(ip, version) {
1025
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1026
- return true;
1027
- }
1028
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1029
- return true;
1030
- }
1031
- return false;
1032
- }
1033
- var ZodString = class _ZodString extends ZodType {
1034
- _parse(input) {
1035
- if (this._def.coerce) {
1036
- input.data = String(input.data);
1037
- }
1038
- const parsedType = this._getType(input);
1039
- if (parsedType !== ZodParsedType.string) {
1040
- const ctx2 = this._getOrReturnCtx(input);
1041
- addIssueToContext(ctx2, {
1042
- code: ZodIssueCode.invalid_type,
1043
- expected: ZodParsedType.string,
1044
- received: ctx2.parsedType
1045
- });
1046
- return INVALID;
1047
- }
1048
- const status = new ParseStatus();
1049
- let ctx = void 0;
1050
- for (const check of this._def.checks) {
1051
- if (check.kind === "min") {
1052
- if (input.data.length < check.value) {
1053
- ctx = this._getOrReturnCtx(input, ctx);
1054
- addIssueToContext(ctx, {
1055
- code: ZodIssueCode.too_small,
1056
- minimum: check.value,
1057
- type: "string",
1058
- inclusive: true,
1059
- exact: false,
1060
- message: check.message
1061
- });
1062
- status.dirty();
1063
- }
1064
- } else if (check.kind === "max") {
1065
- if (input.data.length > check.value) {
1066
- ctx = this._getOrReturnCtx(input, ctx);
1067
- addIssueToContext(ctx, {
1068
- code: ZodIssueCode.too_big,
1069
- maximum: check.value,
1070
- type: "string",
1071
- inclusive: true,
1072
- exact: false,
1073
- message: check.message
1074
- });
1075
- status.dirty();
1076
- }
1077
- } else if (check.kind === "length") {
1078
- const tooBig = input.data.length > check.value;
1079
- const tooSmall = input.data.length < check.value;
1080
- if (tooBig || tooSmall) {
1081
- ctx = this._getOrReturnCtx(input, ctx);
1082
- if (tooBig) {
1083
- addIssueToContext(ctx, {
1084
- code: ZodIssueCode.too_big,
1085
- maximum: check.value,
1086
- type: "string",
1087
- inclusive: true,
1088
- exact: true,
1089
- message: check.message
1090
- });
1091
- } else if (tooSmall) {
1092
- addIssueToContext(ctx, {
1093
- code: ZodIssueCode.too_small,
1094
- minimum: check.value,
1095
- type: "string",
1096
- inclusive: true,
1097
- exact: true,
1098
- message: check.message
1099
- });
1100
- }
1101
- status.dirty();
1102
- }
1103
- } else if (check.kind === "email") {
1104
- if (!emailRegex.test(input.data)) {
1105
- ctx = this._getOrReturnCtx(input, ctx);
1106
- addIssueToContext(ctx, {
1107
- validation: "email",
1108
- code: ZodIssueCode.invalid_string,
1109
- message: check.message
1110
- });
1111
- status.dirty();
1112
- }
1113
- } else if (check.kind === "emoji") {
1114
- if (!emojiRegex) {
1115
- emojiRegex = new RegExp(_emojiRegex, "u");
1116
- }
1117
- if (!emojiRegex.test(input.data)) {
1118
- ctx = this._getOrReturnCtx(input, ctx);
1119
- addIssueToContext(ctx, {
1120
- validation: "emoji",
1121
- code: ZodIssueCode.invalid_string,
1122
- message: check.message
1123
- });
1124
- status.dirty();
1125
- }
1126
- } else if (check.kind === "uuid") {
1127
- if (!uuidRegex.test(input.data)) {
1128
- ctx = this._getOrReturnCtx(input, ctx);
1129
- addIssueToContext(ctx, {
1130
- validation: "uuid",
1131
- code: ZodIssueCode.invalid_string,
1132
- message: check.message
1133
- });
1134
- status.dirty();
1135
- }
1136
- } else if (check.kind === "nanoid") {
1137
- if (!nanoidRegex.test(input.data)) {
1138
- ctx = this._getOrReturnCtx(input, ctx);
1139
- addIssueToContext(ctx, {
1140
- validation: "nanoid",
1141
- code: ZodIssueCode.invalid_string,
1142
- message: check.message
1143
- });
1144
- status.dirty();
1145
- }
1146
- } else if (check.kind === "cuid") {
1147
- if (!cuidRegex.test(input.data)) {
1148
- ctx = this._getOrReturnCtx(input, ctx);
1149
- addIssueToContext(ctx, {
1150
- validation: "cuid",
1151
- code: ZodIssueCode.invalid_string,
1152
- message: check.message
1153
- });
1154
- status.dirty();
1155
- }
1156
- } else if (check.kind === "cuid2") {
1157
- if (!cuid2Regex.test(input.data)) {
1158
- ctx = this._getOrReturnCtx(input, ctx);
1159
- addIssueToContext(ctx, {
1160
- validation: "cuid2",
1161
- code: ZodIssueCode.invalid_string,
1162
- message: check.message
1163
- });
1164
- status.dirty();
1165
- }
1166
- } else if (check.kind === "ulid") {
1167
- if (!ulidRegex.test(input.data)) {
1168
- ctx = this._getOrReturnCtx(input, ctx);
1169
- addIssueToContext(ctx, {
1170
- validation: "ulid",
1171
- code: ZodIssueCode.invalid_string,
1172
- message: check.message
1173
- });
1174
- status.dirty();
1175
- }
1176
- } else if (check.kind === "url") {
1177
- try {
1178
- new URL(input.data);
1179
- } catch {
1180
- ctx = this._getOrReturnCtx(input, ctx);
1181
- addIssueToContext(ctx, {
1182
- validation: "url",
1183
- code: ZodIssueCode.invalid_string,
1184
- message: check.message
1185
- });
1186
- status.dirty();
1187
- }
1188
- } else if (check.kind === "regex") {
1189
- check.regex.lastIndex = 0;
1190
- const testResult = check.regex.test(input.data);
1191
- if (!testResult) {
1192
- ctx = this._getOrReturnCtx(input, ctx);
1193
- addIssueToContext(ctx, {
1194
- validation: "regex",
1195
- code: ZodIssueCode.invalid_string,
1196
- message: check.message
1197
- });
1198
- status.dirty();
1199
- }
1200
- } else if (check.kind === "trim") {
1201
- input.data = input.data.trim();
1202
- } else if (check.kind === "includes") {
1203
- if (!input.data.includes(check.value, check.position)) {
1204
- ctx = this._getOrReturnCtx(input, ctx);
1205
- addIssueToContext(ctx, {
1206
- code: ZodIssueCode.invalid_string,
1207
- validation: { includes: check.value, position: check.position },
1208
- message: check.message
1209
- });
1210
- status.dirty();
1211
- }
1212
- } else if (check.kind === "toLowerCase") {
1213
- input.data = input.data.toLowerCase();
1214
- } else if (check.kind === "toUpperCase") {
1215
- input.data = input.data.toUpperCase();
1216
- } else if (check.kind === "startsWith") {
1217
- if (!input.data.startsWith(check.value)) {
1218
- ctx = this._getOrReturnCtx(input, ctx);
1219
- addIssueToContext(ctx, {
1220
- code: ZodIssueCode.invalid_string,
1221
- validation: { startsWith: check.value },
1222
- message: check.message
1223
- });
1224
- status.dirty();
1225
- }
1226
- } else if (check.kind === "endsWith") {
1227
- if (!input.data.endsWith(check.value)) {
1228
- ctx = this._getOrReturnCtx(input, ctx);
1229
- addIssueToContext(ctx, {
1230
- code: ZodIssueCode.invalid_string,
1231
- validation: { endsWith: check.value },
1232
- message: check.message
1233
- });
1234
- status.dirty();
1235
- }
1236
- } else if (check.kind === "datetime") {
1237
- const regex = datetimeRegex(check);
1238
- if (!regex.test(input.data)) {
1239
- ctx = this._getOrReturnCtx(input, ctx);
1240
- addIssueToContext(ctx, {
1241
- code: ZodIssueCode.invalid_string,
1242
- validation: "datetime",
1243
- message: check.message
1244
- });
1245
- status.dirty();
1246
- }
1247
- } else if (check.kind === "date") {
1248
- const regex = dateRegex;
1249
- if (!regex.test(input.data)) {
1250
- ctx = this._getOrReturnCtx(input, ctx);
1251
- addIssueToContext(ctx, {
1252
- code: ZodIssueCode.invalid_string,
1253
- validation: "date",
1254
- message: check.message
1255
- });
1256
- status.dirty();
1257
- }
1258
- } else if (check.kind === "time") {
1259
- const regex = timeRegex(check);
1260
- if (!regex.test(input.data)) {
1261
- ctx = this._getOrReturnCtx(input, ctx);
1262
- addIssueToContext(ctx, {
1263
- code: ZodIssueCode.invalid_string,
1264
- validation: "time",
1265
- message: check.message
1266
- });
1267
- status.dirty();
1268
- }
1269
- } else if (check.kind === "duration") {
1270
- if (!durationRegex.test(input.data)) {
1271
- ctx = this._getOrReturnCtx(input, ctx);
1272
- addIssueToContext(ctx, {
1273
- validation: "duration",
1274
- code: ZodIssueCode.invalid_string,
1275
- message: check.message
1276
- });
1277
- status.dirty();
1278
- }
1279
- } else if (check.kind === "ip") {
1280
- if (!isValidIP(input.data, check.version)) {
1281
- ctx = this._getOrReturnCtx(input, ctx);
1282
- addIssueToContext(ctx, {
1283
- validation: "ip",
1284
- code: ZodIssueCode.invalid_string,
1285
- message: check.message
1286
- });
1287
- status.dirty();
1288
- }
1289
- } else if (check.kind === "jwt") {
1290
- if (!isValidJWT(input.data, check.alg)) {
1291
- ctx = this._getOrReturnCtx(input, ctx);
1292
- addIssueToContext(ctx, {
1293
- validation: "jwt",
1294
- code: ZodIssueCode.invalid_string,
1295
- message: check.message
1296
- });
1297
- status.dirty();
1298
- }
1299
- } else if (check.kind === "cidr") {
1300
- if (!isValidCidr(input.data, check.version)) {
1301
- ctx = this._getOrReturnCtx(input, ctx);
1302
- addIssueToContext(ctx, {
1303
- validation: "cidr",
1304
- code: ZodIssueCode.invalid_string,
1305
- message: check.message
1306
- });
1307
- status.dirty();
1308
- }
1309
- } else if (check.kind === "base64") {
1310
- if (!base64Regex.test(input.data)) {
1311
- ctx = this._getOrReturnCtx(input, ctx);
1312
- addIssueToContext(ctx, {
1313
- validation: "base64",
1314
- code: ZodIssueCode.invalid_string,
1315
- message: check.message
1316
- });
1317
- status.dirty();
1318
- }
1319
- } else if (check.kind === "base64url") {
1320
- if (!base64urlRegex.test(input.data)) {
1321
- ctx = this._getOrReturnCtx(input, ctx);
1322
- addIssueToContext(ctx, {
1323
- validation: "base64url",
1324
- code: ZodIssueCode.invalid_string,
1325
- message: check.message
1326
- });
1327
- status.dirty();
1328
- }
1329
- } else {
1330
- util.assertNever(check);
1331
- }
1332
- }
1333
- return { status: status.value, value: input.data };
1334
- }
1335
- _regex(regex, validation, message) {
1336
- return this.refinement((data) => regex.test(data), {
1337
- validation,
1338
- code: ZodIssueCode.invalid_string,
1339
- ...errorUtil.errToObj(message)
1340
- });
1341
- }
1342
- _addCheck(check) {
1343
- return new _ZodString({
1344
- ...this._def,
1345
- checks: [...this._def.checks, check]
1346
- });
1347
- }
1348
- email(message) {
1349
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1350
- }
1351
- url(message) {
1352
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1353
- }
1354
- emoji(message) {
1355
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1356
- }
1357
- uuid(message) {
1358
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1359
- }
1360
- nanoid(message) {
1361
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1362
- }
1363
- cuid(message) {
1364
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1365
- }
1366
- cuid2(message) {
1367
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1368
- }
1369
- ulid(message) {
1370
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1371
- }
1372
- base64(message) {
1373
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1374
- }
1375
- base64url(message) {
1376
- return this._addCheck({
1377
- kind: "base64url",
1378
- ...errorUtil.errToObj(message)
1379
- });
1380
- }
1381
- jwt(options) {
1382
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1383
- }
1384
- ip(options) {
1385
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1386
- }
1387
- cidr(options) {
1388
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1389
- }
1390
- datetime(options) {
1391
- if (typeof options === "string") {
1392
- return this._addCheck({
1393
- kind: "datetime",
1394
- precision: null,
1395
- offset: false,
1396
- local: false,
1397
- message: options
1398
- });
1399
- }
1400
- return this._addCheck({
1401
- kind: "datetime",
1402
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1403
- offset: options?.offset ?? false,
1404
- local: options?.local ?? false,
1405
- ...errorUtil.errToObj(options?.message)
1406
- });
1407
- }
1408
- date(message) {
1409
- return this._addCheck({ kind: "date", message });
1410
- }
1411
- time(options) {
1412
- if (typeof options === "string") {
1413
- return this._addCheck({
1414
- kind: "time",
1415
- precision: null,
1416
- message: options
1417
- });
1418
- }
1419
- return this._addCheck({
1420
- kind: "time",
1421
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1422
- ...errorUtil.errToObj(options?.message)
1423
- });
1424
- }
1425
- duration(message) {
1426
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1427
- }
1428
- regex(regex, message) {
1429
- return this._addCheck({
1430
- kind: "regex",
1431
- regex,
1432
- ...errorUtil.errToObj(message)
1433
- });
1434
- }
1435
- includes(value, options) {
1436
- return this._addCheck({
1437
- kind: "includes",
1438
- value,
1439
- position: options?.position,
1440
- ...errorUtil.errToObj(options?.message)
1441
- });
1442
- }
1443
- startsWith(value, message) {
1444
- return this._addCheck({
1445
- kind: "startsWith",
1446
- value,
1447
- ...errorUtil.errToObj(message)
1448
- });
1449
- }
1450
- endsWith(value, message) {
1451
- return this._addCheck({
1452
- kind: "endsWith",
1453
- value,
1454
- ...errorUtil.errToObj(message)
1455
- });
1456
- }
1457
- min(minLength, message) {
1458
- return this._addCheck({
1459
- kind: "min",
1460
- value: minLength,
1461
- ...errorUtil.errToObj(message)
1462
- });
1463
- }
1464
- max(maxLength, message) {
1465
- return this._addCheck({
1466
- kind: "max",
1467
- value: maxLength,
1468
- ...errorUtil.errToObj(message)
1469
- });
1470
- }
1471
- length(len, message) {
1472
- return this._addCheck({
1473
- kind: "length",
1474
- value: len,
1475
- ...errorUtil.errToObj(message)
1476
- });
1477
- }
1478
- /**
1479
- * Equivalent to `.min(1)`
1480
- */
1481
- nonempty(message) {
1482
- return this.min(1, errorUtil.errToObj(message));
1483
- }
1484
- trim() {
1485
- return new _ZodString({
1486
- ...this._def,
1487
- checks: [...this._def.checks, { kind: "trim" }]
1488
- });
1489
- }
1490
- toLowerCase() {
1491
- return new _ZodString({
1492
- ...this._def,
1493
- checks: [...this._def.checks, { kind: "toLowerCase" }]
1494
- });
1495
- }
1496
- toUpperCase() {
1497
- return new _ZodString({
1498
- ...this._def,
1499
- checks: [...this._def.checks, { kind: "toUpperCase" }]
1500
- });
1501
- }
1502
- get isDatetime() {
1503
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
1504
- }
1505
- get isDate() {
1506
- return !!this._def.checks.find((ch) => ch.kind === "date");
1507
- }
1508
- get isTime() {
1509
- return !!this._def.checks.find((ch) => ch.kind === "time");
1510
- }
1511
- get isDuration() {
1512
- return !!this._def.checks.find((ch) => ch.kind === "duration");
1513
- }
1514
- get isEmail() {
1515
- return !!this._def.checks.find((ch) => ch.kind === "email");
1516
- }
1517
- get isURL() {
1518
- return !!this._def.checks.find((ch) => ch.kind === "url");
1519
- }
1520
- get isEmoji() {
1521
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1522
- }
1523
- get isUUID() {
1524
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1525
- }
1526
- get isNANOID() {
1527
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1528
- }
1529
- get isCUID() {
1530
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1531
- }
1532
- get isCUID2() {
1533
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1534
- }
1535
- get isULID() {
1536
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1537
- }
1538
- get isIP() {
1539
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1540
- }
1541
- get isCIDR() {
1542
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1543
- }
1544
- get isBase64() {
1545
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1546
- }
1547
- get isBase64url() {
1548
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1549
- }
1550
- get minLength() {
1551
- let min = null;
1552
- for (const ch of this._def.checks) {
1553
- if (ch.kind === "min") {
1554
- if (min === null || ch.value > min)
1555
- min = ch.value;
1556
- }
1557
- }
1558
- return min;
1559
- }
1560
- get maxLength() {
1561
- let max = null;
1562
- for (const ch of this._def.checks) {
1563
- if (ch.kind === "max") {
1564
- if (max === null || ch.value < max)
1565
- max = ch.value;
1566
- }
1567
- }
1568
- return max;
1569
- }
1570
- };
1571
- ZodString.create = (params) => {
1572
- return new ZodString({
1573
- checks: [],
1574
- typeName: ZodFirstPartyTypeKind.ZodString,
1575
- coerce: params?.coerce ?? false,
1576
- ...processCreateParams(params)
1577
- });
1578
- };
1579
- function floatSafeRemainder(val, step) {
1580
- const valDecCount = (val.toString().split(".")[1] || "").length;
1581
- const stepDecCount = (step.toString().split(".")[1] || "").length;
1582
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1583
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1584
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1585
- return valInt % stepInt / 10 ** decCount;
1586
- }
1587
- var ZodNumber = class _ZodNumber extends ZodType {
1588
- constructor() {
1589
- super(...arguments);
1590
- this.min = this.gte;
1591
- this.max = this.lte;
1592
- this.step = this.multipleOf;
1593
- }
1594
- _parse(input) {
1595
- if (this._def.coerce) {
1596
- input.data = Number(input.data);
1597
- }
1598
- const parsedType = this._getType(input);
1599
- if (parsedType !== ZodParsedType.number) {
1600
- const ctx2 = this._getOrReturnCtx(input);
1601
- addIssueToContext(ctx2, {
1602
- code: ZodIssueCode.invalid_type,
1603
- expected: ZodParsedType.number,
1604
- received: ctx2.parsedType
1605
- });
1606
- return INVALID;
1607
- }
1608
- let ctx = void 0;
1609
- const status = new ParseStatus();
1610
- for (const check of this._def.checks) {
1611
- if (check.kind === "int") {
1612
- if (!util.isInteger(input.data)) {
1613
- ctx = this._getOrReturnCtx(input, ctx);
1614
- addIssueToContext(ctx, {
1615
- code: ZodIssueCode.invalid_type,
1616
- expected: "integer",
1617
- received: "float",
1618
- message: check.message
1619
- });
1620
- status.dirty();
1621
- }
1622
- } else if (check.kind === "min") {
1623
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1624
- if (tooSmall) {
1625
- ctx = this._getOrReturnCtx(input, ctx);
1626
- addIssueToContext(ctx, {
1627
- code: ZodIssueCode.too_small,
1628
- minimum: check.value,
1629
- type: "number",
1630
- inclusive: check.inclusive,
1631
- exact: false,
1632
- message: check.message
1633
- });
1634
- status.dirty();
1635
- }
1636
- } else if (check.kind === "max") {
1637
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1638
- if (tooBig) {
1639
- ctx = this._getOrReturnCtx(input, ctx);
1640
- addIssueToContext(ctx, {
1641
- code: ZodIssueCode.too_big,
1642
- maximum: check.value,
1643
- type: "number",
1644
- inclusive: check.inclusive,
1645
- exact: false,
1646
- message: check.message
1647
- });
1648
- status.dirty();
1649
- }
1650
- } else if (check.kind === "multipleOf") {
1651
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1652
- ctx = this._getOrReturnCtx(input, ctx);
1653
- addIssueToContext(ctx, {
1654
- code: ZodIssueCode.not_multiple_of,
1655
- multipleOf: check.value,
1656
- message: check.message
1657
- });
1658
- status.dirty();
1659
- }
1660
- } else if (check.kind === "finite") {
1661
- if (!Number.isFinite(input.data)) {
1662
- ctx = this._getOrReturnCtx(input, ctx);
1663
- addIssueToContext(ctx, {
1664
- code: ZodIssueCode.not_finite,
1665
- message: check.message
1666
- });
1667
- status.dirty();
1668
- }
1669
- } else {
1670
- util.assertNever(check);
1671
- }
1672
- }
1673
- return { status: status.value, value: input.data };
1674
- }
1675
- gte(value, message) {
1676
- return this.setLimit("min", value, true, errorUtil.toString(message));
1677
- }
1678
- gt(value, message) {
1679
- return this.setLimit("min", value, false, errorUtil.toString(message));
1680
- }
1681
- lte(value, message) {
1682
- return this.setLimit("max", value, true, errorUtil.toString(message));
1683
- }
1684
- lt(value, message) {
1685
- return this.setLimit("max", value, false, errorUtil.toString(message));
1686
- }
1687
- setLimit(kind, value, inclusive, message) {
1688
- return new _ZodNumber({
1689
- ...this._def,
1690
- checks: [
1691
- ...this._def.checks,
1692
- {
1693
- kind,
1694
- value,
1695
- inclusive,
1696
- message: errorUtil.toString(message)
1697
- }
1698
- ]
1699
- });
1700
- }
1701
- _addCheck(check) {
1702
- return new _ZodNumber({
1703
- ...this._def,
1704
- checks: [...this._def.checks, check]
1705
- });
1706
- }
1707
- int(message) {
1708
- return this._addCheck({
1709
- kind: "int",
1710
- message: errorUtil.toString(message)
1711
- });
1712
- }
1713
- positive(message) {
1714
- return this._addCheck({
1715
- kind: "min",
1716
- value: 0,
1717
- inclusive: false,
1718
- message: errorUtil.toString(message)
1719
- });
1720
- }
1721
- negative(message) {
1722
- return this._addCheck({
1723
- kind: "max",
1724
- value: 0,
1725
- inclusive: false,
1726
- message: errorUtil.toString(message)
1727
- });
1728
- }
1729
- nonpositive(message) {
1730
- return this._addCheck({
1731
- kind: "max",
1732
- value: 0,
1733
- inclusive: true,
1734
- message: errorUtil.toString(message)
1735
- });
1736
- }
1737
- nonnegative(message) {
1738
- return this._addCheck({
1739
- kind: "min",
1740
- value: 0,
1741
- inclusive: true,
1742
- message: errorUtil.toString(message)
1743
- });
1744
- }
1745
- multipleOf(value, message) {
1746
- return this._addCheck({
1747
- kind: "multipleOf",
1748
- value,
1749
- message: errorUtil.toString(message)
1750
- });
1751
- }
1752
- finite(message) {
1753
- return this._addCheck({
1754
- kind: "finite",
1755
- message: errorUtil.toString(message)
1756
- });
1757
- }
1758
- safe(message) {
1759
- return this._addCheck({
1760
- kind: "min",
1761
- inclusive: true,
1762
- value: Number.MIN_SAFE_INTEGER,
1763
- message: errorUtil.toString(message)
1764
- })._addCheck({
1765
- kind: "max",
1766
- inclusive: true,
1767
- value: Number.MAX_SAFE_INTEGER,
1768
- message: errorUtil.toString(message)
1769
- });
1770
- }
1771
- get minValue() {
1772
- let min = null;
1773
- for (const ch of this._def.checks) {
1774
- if (ch.kind === "min") {
1775
- if (min === null || ch.value > min)
1776
- min = ch.value;
1777
- }
1778
- }
1779
- return min;
1780
- }
1781
- get maxValue() {
1782
- let max = null;
1783
- for (const ch of this._def.checks) {
1784
- if (ch.kind === "max") {
1785
- if (max === null || ch.value < max)
1786
- max = ch.value;
1787
- }
1788
- }
1789
- return max;
1790
- }
1791
- get isInt() {
1792
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1793
- }
1794
- get isFinite() {
1795
- let max = null;
1796
- let min = null;
1797
- for (const ch of this._def.checks) {
1798
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1799
- return true;
1800
- } else if (ch.kind === "min") {
1801
- if (min === null || ch.value > min)
1802
- min = ch.value;
1803
- } else if (ch.kind === "max") {
1804
- if (max === null || ch.value < max)
1805
- max = ch.value;
1806
- }
1807
- }
1808
- return Number.isFinite(min) && Number.isFinite(max);
1809
- }
1810
- };
1811
- ZodNumber.create = (params) => {
1812
- return new ZodNumber({
1813
- checks: [],
1814
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1815
- coerce: params?.coerce || false,
1816
- ...processCreateParams(params)
1817
- });
1818
- };
1819
- var ZodBigInt = class _ZodBigInt extends ZodType {
1820
- constructor() {
1821
- super(...arguments);
1822
- this.min = this.gte;
1823
- this.max = this.lte;
1824
- }
1825
- _parse(input) {
1826
- if (this._def.coerce) {
1827
- try {
1828
- input.data = BigInt(input.data);
1829
- } catch {
1830
- return this._getInvalidInput(input);
1831
- }
1832
- }
1833
- const parsedType = this._getType(input);
1834
- if (parsedType !== ZodParsedType.bigint) {
1835
- return this._getInvalidInput(input);
1836
- }
1837
- let ctx = void 0;
1838
- const status = new ParseStatus();
1839
- for (const check of this._def.checks) {
1840
- if (check.kind === "min") {
1841
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1842
- if (tooSmall) {
1843
- ctx = this._getOrReturnCtx(input, ctx);
1844
- addIssueToContext(ctx, {
1845
- code: ZodIssueCode.too_small,
1846
- type: "bigint",
1847
- minimum: check.value,
1848
- inclusive: check.inclusive,
1849
- message: check.message
1850
- });
1851
- status.dirty();
1852
- }
1853
- } else if (check.kind === "max") {
1854
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1855
- if (tooBig) {
1856
- ctx = this._getOrReturnCtx(input, ctx);
1857
- addIssueToContext(ctx, {
1858
- code: ZodIssueCode.too_big,
1859
- type: "bigint",
1860
- maximum: check.value,
1861
- inclusive: check.inclusive,
1862
- message: check.message
1863
- });
1864
- status.dirty();
1865
- }
1866
- } else if (check.kind === "multipleOf") {
1867
- if (input.data % check.value !== BigInt(0)) {
1868
- ctx = this._getOrReturnCtx(input, ctx);
1869
- addIssueToContext(ctx, {
1870
- code: ZodIssueCode.not_multiple_of,
1871
- multipleOf: check.value,
1872
- message: check.message
1873
- });
1874
- status.dirty();
1875
- }
1876
- } else {
1877
- util.assertNever(check);
1878
- }
1879
- }
1880
- return { status: status.value, value: input.data };
1881
- }
1882
- _getInvalidInput(input) {
1883
- const ctx = this._getOrReturnCtx(input);
1884
- addIssueToContext(ctx, {
1885
- code: ZodIssueCode.invalid_type,
1886
- expected: ZodParsedType.bigint,
1887
- received: ctx.parsedType
1888
- });
1889
- return INVALID;
1890
- }
1891
- gte(value, message) {
1892
- return this.setLimit("min", value, true, errorUtil.toString(message));
1893
- }
1894
- gt(value, message) {
1895
- return this.setLimit("min", value, false, errorUtil.toString(message));
1896
- }
1897
- lte(value, message) {
1898
- return this.setLimit("max", value, true, errorUtil.toString(message));
1899
- }
1900
- lt(value, message) {
1901
- return this.setLimit("max", value, false, errorUtil.toString(message));
1902
- }
1903
- setLimit(kind, value, inclusive, message) {
1904
- return new _ZodBigInt({
1905
- ...this._def,
1906
- checks: [
1907
- ...this._def.checks,
1908
- {
1909
- kind,
1910
- value,
1911
- inclusive,
1912
- message: errorUtil.toString(message)
1913
- }
1914
- ]
1915
- });
1916
- }
1917
- _addCheck(check) {
1918
- return new _ZodBigInt({
1919
- ...this._def,
1920
- checks: [...this._def.checks, check]
1921
- });
1922
- }
1923
- positive(message) {
1924
- return this._addCheck({
1925
- kind: "min",
1926
- value: BigInt(0),
1927
- inclusive: false,
1928
- message: errorUtil.toString(message)
1929
- });
1930
- }
1931
- negative(message) {
1932
- return this._addCheck({
1933
- kind: "max",
1934
- value: BigInt(0),
1935
- inclusive: false,
1936
- message: errorUtil.toString(message)
1937
- });
1938
- }
1939
- nonpositive(message) {
1940
- return this._addCheck({
1941
- kind: "max",
1942
- value: BigInt(0),
1943
- inclusive: true,
1944
- message: errorUtil.toString(message)
1945
- });
1946
- }
1947
- nonnegative(message) {
1948
- return this._addCheck({
1949
- kind: "min",
1950
- value: BigInt(0),
1951
- inclusive: true,
1952
- message: errorUtil.toString(message)
1953
- });
1954
- }
1955
- multipleOf(value, message) {
1956
- return this._addCheck({
1957
- kind: "multipleOf",
1958
- value,
1959
- message: errorUtil.toString(message)
1960
- });
1961
- }
1962
- get minValue() {
1963
- let min = null;
1964
- for (const ch of this._def.checks) {
1965
- if (ch.kind === "min") {
1966
- if (min === null || ch.value > min)
1967
- min = ch.value;
1968
- }
1969
- }
1970
- return min;
1971
- }
1972
- get maxValue() {
1973
- let max = null;
1974
- for (const ch of this._def.checks) {
1975
- if (ch.kind === "max") {
1976
- if (max === null || ch.value < max)
1977
- max = ch.value;
1978
- }
1979
- }
1980
- return max;
1981
- }
1982
- };
1983
- ZodBigInt.create = (params) => {
1984
- return new ZodBigInt({
1985
- checks: [],
1986
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
1987
- coerce: params?.coerce ?? false,
1988
- ...processCreateParams(params)
1989
- });
1990
- };
1991
- var ZodBoolean = class extends ZodType {
1992
- _parse(input) {
1993
- if (this._def.coerce) {
1994
- input.data = Boolean(input.data);
1995
- }
1996
- const parsedType = this._getType(input);
1997
- if (parsedType !== ZodParsedType.boolean) {
1998
- const ctx = this._getOrReturnCtx(input);
1999
- addIssueToContext(ctx, {
2000
- code: ZodIssueCode.invalid_type,
2001
- expected: ZodParsedType.boolean,
2002
- received: ctx.parsedType
2003
- });
2004
- return INVALID;
2005
- }
2006
- return OK(input.data);
2007
- }
2008
- };
2009
- ZodBoolean.create = (params) => {
2010
- return new ZodBoolean({
2011
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2012
- coerce: params?.coerce || false,
2013
- ...processCreateParams(params)
2014
- });
2015
- };
2016
- var ZodDate = class _ZodDate extends ZodType {
2017
- _parse(input) {
2018
- if (this._def.coerce) {
2019
- input.data = new Date(input.data);
2020
- }
2021
- const parsedType = this._getType(input);
2022
- if (parsedType !== ZodParsedType.date) {
2023
- const ctx2 = this._getOrReturnCtx(input);
2024
- addIssueToContext(ctx2, {
2025
- code: ZodIssueCode.invalid_type,
2026
- expected: ZodParsedType.date,
2027
- received: ctx2.parsedType
2028
- });
2029
- return INVALID;
2030
- }
2031
- if (Number.isNaN(input.data.getTime())) {
2032
- const ctx2 = this._getOrReturnCtx(input);
2033
- addIssueToContext(ctx2, {
2034
- code: ZodIssueCode.invalid_date
2035
- });
2036
- return INVALID;
2037
- }
2038
- const status = new ParseStatus();
2039
- let ctx = void 0;
2040
- for (const check of this._def.checks) {
2041
- if (check.kind === "min") {
2042
- if (input.data.getTime() < check.value) {
2043
- ctx = this._getOrReturnCtx(input, ctx);
2044
- addIssueToContext(ctx, {
2045
- code: ZodIssueCode.too_small,
2046
- message: check.message,
2047
- inclusive: true,
2048
- exact: false,
2049
- minimum: check.value,
2050
- type: "date"
2051
- });
2052
- status.dirty();
2053
- }
2054
- } else if (check.kind === "max") {
2055
- if (input.data.getTime() > check.value) {
2056
- ctx = this._getOrReturnCtx(input, ctx);
2057
- addIssueToContext(ctx, {
2058
- code: ZodIssueCode.too_big,
2059
- message: check.message,
2060
- inclusive: true,
2061
- exact: false,
2062
- maximum: check.value,
2063
- type: "date"
2064
- });
2065
- status.dirty();
2066
- }
2067
- } else {
2068
- util.assertNever(check);
2069
- }
2070
- }
2071
- return {
2072
- status: status.value,
2073
- value: new Date(input.data.getTime())
2074
- };
2075
- }
2076
- _addCheck(check) {
2077
- return new _ZodDate({
2078
- ...this._def,
2079
- checks: [...this._def.checks, check]
2080
- });
2081
- }
2082
- min(minDate, message) {
2083
- return this._addCheck({
2084
- kind: "min",
2085
- value: minDate.getTime(),
2086
- message: errorUtil.toString(message)
2087
- });
2088
- }
2089
- max(maxDate, message) {
2090
- return this._addCheck({
2091
- kind: "max",
2092
- value: maxDate.getTime(),
2093
- message: errorUtil.toString(message)
2094
- });
2095
- }
2096
- get minDate() {
2097
- let min = null;
2098
- for (const ch of this._def.checks) {
2099
- if (ch.kind === "min") {
2100
- if (min === null || ch.value > min)
2101
- min = ch.value;
2102
- }
2103
- }
2104
- return min != null ? new Date(min) : null;
2105
- }
2106
- get maxDate() {
2107
- let max = null;
2108
- for (const ch of this._def.checks) {
2109
- if (ch.kind === "max") {
2110
- if (max === null || ch.value < max)
2111
- max = ch.value;
2112
- }
2113
- }
2114
- return max != null ? new Date(max) : null;
2115
- }
2116
- };
2117
- ZodDate.create = (params) => {
2118
- return new ZodDate({
2119
- checks: [],
2120
- coerce: params?.coerce || false,
2121
- typeName: ZodFirstPartyTypeKind.ZodDate,
2122
- ...processCreateParams(params)
2123
- });
2124
- };
2125
- var ZodSymbol = class extends ZodType {
2126
- _parse(input) {
2127
- const parsedType = this._getType(input);
2128
- if (parsedType !== ZodParsedType.symbol) {
2129
- const ctx = this._getOrReturnCtx(input);
2130
- addIssueToContext(ctx, {
2131
- code: ZodIssueCode.invalid_type,
2132
- expected: ZodParsedType.symbol,
2133
- received: ctx.parsedType
2134
- });
2135
- return INVALID;
2136
- }
2137
- return OK(input.data);
2138
- }
2139
- };
2140
- ZodSymbol.create = (params) => {
2141
- return new ZodSymbol({
2142
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2143
- ...processCreateParams(params)
2144
- });
2145
- };
2146
- var ZodUndefined = class extends ZodType {
2147
- _parse(input) {
2148
- const parsedType = this._getType(input);
2149
- if (parsedType !== ZodParsedType.undefined) {
2150
- const ctx = this._getOrReturnCtx(input);
2151
- addIssueToContext(ctx, {
2152
- code: ZodIssueCode.invalid_type,
2153
- expected: ZodParsedType.undefined,
2154
- received: ctx.parsedType
2155
- });
2156
- return INVALID;
2157
- }
2158
- return OK(input.data);
2159
- }
2160
- };
2161
- ZodUndefined.create = (params) => {
2162
- return new ZodUndefined({
2163
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2164
- ...processCreateParams(params)
2165
- });
2166
- };
2167
- var ZodNull = class extends ZodType {
2168
- _parse(input) {
2169
- const parsedType = this._getType(input);
2170
- if (parsedType !== ZodParsedType.null) {
2171
- const ctx = this._getOrReturnCtx(input);
2172
- addIssueToContext(ctx, {
2173
- code: ZodIssueCode.invalid_type,
2174
- expected: ZodParsedType.null,
2175
- received: ctx.parsedType
2176
- });
2177
- return INVALID;
2178
- }
2179
- return OK(input.data);
2180
- }
2181
- };
2182
- ZodNull.create = (params) => {
2183
- return new ZodNull({
2184
- typeName: ZodFirstPartyTypeKind.ZodNull,
2185
- ...processCreateParams(params)
2186
- });
2187
- };
2188
- var ZodAny = class extends ZodType {
2189
- constructor() {
2190
- super(...arguments);
2191
- this._any = true;
2192
- }
2193
- _parse(input) {
2194
- return OK(input.data);
2195
- }
2196
- };
2197
- ZodAny.create = (params) => {
2198
- return new ZodAny({
2199
- typeName: ZodFirstPartyTypeKind.ZodAny,
2200
- ...processCreateParams(params)
2201
- });
2202
- };
2203
- var ZodUnknown = class extends ZodType {
2204
- constructor() {
2205
- super(...arguments);
2206
- this._unknown = true;
2207
- }
2208
- _parse(input) {
2209
- return OK(input.data);
2210
- }
2211
- };
2212
- ZodUnknown.create = (params) => {
2213
- return new ZodUnknown({
2214
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2215
- ...processCreateParams(params)
2216
- });
2217
- };
2218
- var ZodNever = class extends ZodType {
2219
- _parse(input) {
2220
- const ctx = this._getOrReturnCtx(input);
2221
- addIssueToContext(ctx, {
2222
- code: ZodIssueCode.invalid_type,
2223
- expected: ZodParsedType.never,
2224
- received: ctx.parsedType
2225
- });
2226
- return INVALID;
2227
- }
2228
- };
2229
- ZodNever.create = (params) => {
2230
- return new ZodNever({
2231
- typeName: ZodFirstPartyTypeKind.ZodNever,
2232
- ...processCreateParams(params)
2233
- });
2234
- };
2235
- var ZodVoid = class extends ZodType {
2236
- _parse(input) {
2237
- const parsedType = this._getType(input);
2238
- if (parsedType !== ZodParsedType.undefined) {
2239
- const ctx = this._getOrReturnCtx(input);
2240
- addIssueToContext(ctx, {
2241
- code: ZodIssueCode.invalid_type,
2242
- expected: ZodParsedType.void,
2243
- received: ctx.parsedType
2244
- });
2245
- return INVALID;
2246
- }
2247
- return OK(input.data);
2248
- }
2249
- };
2250
- ZodVoid.create = (params) => {
2251
- return new ZodVoid({
2252
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2253
- ...processCreateParams(params)
2254
- });
2255
- };
2256
- var ZodArray = class _ZodArray extends ZodType {
2257
- _parse(input) {
2258
- const { ctx, status } = this._processInputParams(input);
2259
- const def = this._def;
2260
- if (ctx.parsedType !== ZodParsedType.array) {
2261
- addIssueToContext(ctx, {
2262
- code: ZodIssueCode.invalid_type,
2263
- expected: ZodParsedType.array,
2264
- received: ctx.parsedType
2265
- });
2266
- return INVALID;
2267
- }
2268
- if (def.exactLength !== null) {
2269
- const tooBig = ctx.data.length > def.exactLength.value;
2270
- const tooSmall = ctx.data.length < def.exactLength.value;
2271
- if (tooBig || tooSmall) {
2272
- addIssueToContext(ctx, {
2273
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2274
- minimum: tooSmall ? def.exactLength.value : void 0,
2275
- maximum: tooBig ? def.exactLength.value : void 0,
2276
- type: "array",
2277
- inclusive: true,
2278
- exact: true,
2279
- message: def.exactLength.message
2280
- });
2281
- status.dirty();
2282
- }
2283
- }
2284
- if (def.minLength !== null) {
2285
- if (ctx.data.length < def.minLength.value) {
2286
- addIssueToContext(ctx, {
2287
- code: ZodIssueCode.too_small,
2288
- minimum: def.minLength.value,
2289
- type: "array",
2290
- inclusive: true,
2291
- exact: false,
2292
- message: def.minLength.message
2293
- });
2294
- status.dirty();
2295
- }
2296
- }
2297
- if (def.maxLength !== null) {
2298
- if (ctx.data.length > def.maxLength.value) {
2299
- addIssueToContext(ctx, {
2300
- code: ZodIssueCode.too_big,
2301
- maximum: def.maxLength.value,
2302
- type: "array",
2303
- inclusive: true,
2304
- exact: false,
2305
- message: def.maxLength.message
2306
- });
2307
- status.dirty();
2308
- }
2309
- }
2310
- if (ctx.common.async) {
2311
- return Promise.all([...ctx.data].map((item, i) => {
2312
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2313
- })).then((result2) => {
2314
- return ParseStatus.mergeArray(status, result2);
2315
- });
2316
- }
2317
- const result = [...ctx.data].map((item, i) => {
2318
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2319
- });
2320
- return ParseStatus.mergeArray(status, result);
2321
- }
2322
- get element() {
2323
- return this._def.type;
2324
- }
2325
- min(minLength, message) {
2326
- return new _ZodArray({
2327
- ...this._def,
2328
- minLength: { value: minLength, message: errorUtil.toString(message) }
2329
- });
2330
- }
2331
- max(maxLength, message) {
2332
- return new _ZodArray({
2333
- ...this._def,
2334
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
2335
- });
2336
- }
2337
- length(len, message) {
2338
- return new _ZodArray({
2339
- ...this._def,
2340
- exactLength: { value: len, message: errorUtil.toString(message) }
2341
- });
2342
- }
2343
- nonempty(message) {
2344
- return this.min(1, message);
2345
- }
2346
- };
2347
- ZodArray.create = (schema, params) => {
2348
- return new ZodArray({
2349
- type: schema,
2350
- minLength: null,
2351
- maxLength: null,
2352
- exactLength: null,
2353
- typeName: ZodFirstPartyTypeKind.ZodArray,
2354
- ...processCreateParams(params)
2355
- });
2356
- };
2357
- function deepPartialify(schema) {
2358
- if (schema instanceof ZodObject) {
2359
- const newShape = {};
2360
- for (const key in schema.shape) {
2361
- const fieldSchema = schema.shape[key];
2362
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2363
- }
2364
- return new ZodObject({
2365
- ...schema._def,
2366
- shape: () => newShape
2367
- });
2368
- } else if (schema instanceof ZodArray) {
2369
- return new ZodArray({
2370
- ...schema._def,
2371
- type: deepPartialify(schema.element)
2372
- });
2373
- } else if (schema instanceof ZodOptional) {
2374
- return ZodOptional.create(deepPartialify(schema.unwrap()));
2375
- } else if (schema instanceof ZodNullable) {
2376
- return ZodNullable.create(deepPartialify(schema.unwrap()));
2377
- } else if (schema instanceof ZodTuple) {
2378
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2379
- } else {
2380
- return schema;
2381
- }
2382
- }
2383
- var ZodObject = class _ZodObject extends ZodType {
2384
- constructor() {
2385
- super(...arguments);
2386
- this._cached = null;
2387
- this.nonstrict = this.passthrough;
2388
- this.augment = this.extend;
2389
- }
2390
- _getCached() {
2391
- if (this._cached !== null)
2392
- return this._cached;
2393
- const shape = this._def.shape();
2394
- const keys = util.objectKeys(shape);
2395
- this._cached = { shape, keys };
2396
- return this._cached;
2397
- }
2398
- _parse(input) {
2399
- const parsedType = this._getType(input);
2400
- if (parsedType !== ZodParsedType.object) {
2401
- const ctx2 = this._getOrReturnCtx(input);
2402
- addIssueToContext(ctx2, {
2403
- code: ZodIssueCode.invalid_type,
2404
- expected: ZodParsedType.object,
2405
- received: ctx2.parsedType
2406
- });
2407
- return INVALID;
2408
- }
2409
- const { status, ctx } = this._processInputParams(input);
2410
- const { shape, keys: shapeKeys } = this._getCached();
2411
- const extraKeys = [];
2412
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2413
- for (const key in ctx.data) {
2414
- if (!shapeKeys.includes(key)) {
2415
- extraKeys.push(key);
2416
- }
2417
- }
2418
- }
2419
- const pairs = [];
2420
- for (const key of shapeKeys) {
2421
- const keyValidator = shape[key];
2422
- const value = ctx.data[key];
2423
- pairs.push({
2424
- key: { status: "valid", value: key },
2425
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2426
- alwaysSet: key in ctx.data
2427
- });
2428
- }
2429
- if (this._def.catchall instanceof ZodNever) {
2430
- const unknownKeys = this._def.unknownKeys;
2431
- if (unknownKeys === "passthrough") {
2432
- for (const key of extraKeys) {
2433
- pairs.push({
2434
- key: { status: "valid", value: key },
2435
- value: { status: "valid", value: ctx.data[key] }
2436
- });
2437
- }
2438
- } else if (unknownKeys === "strict") {
2439
- if (extraKeys.length > 0) {
2440
- addIssueToContext(ctx, {
2441
- code: ZodIssueCode.unrecognized_keys,
2442
- keys: extraKeys
2443
- });
2444
- status.dirty();
2445
- }
2446
- } else if (unknownKeys === "strip") {
2447
- } else {
2448
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2449
- }
2450
- } else {
2451
- const catchall = this._def.catchall;
2452
- for (const key of extraKeys) {
2453
- const value = ctx.data[key];
2454
- pairs.push({
2455
- key: { status: "valid", value: key },
2456
- value: catchall._parse(
2457
- new ParseInputLazyPath(ctx, value, ctx.path, key)
2458
- //, ctx.child(key), value, getParsedType(value)
2459
- ),
2460
- alwaysSet: key in ctx.data
2461
- });
2462
- }
2463
- }
2464
- if (ctx.common.async) {
2465
- return Promise.resolve().then(async () => {
2466
- const syncPairs = [];
2467
- for (const pair of pairs) {
2468
- const key = await pair.key;
2469
- const value = await pair.value;
2470
- syncPairs.push({
2471
- key,
2472
- value,
2473
- alwaysSet: pair.alwaysSet
2474
- });
2475
- }
2476
- return syncPairs;
2477
- }).then((syncPairs) => {
2478
- return ParseStatus.mergeObjectSync(status, syncPairs);
2479
- });
2480
- } else {
2481
- return ParseStatus.mergeObjectSync(status, pairs);
2482
- }
2483
- }
2484
- get shape() {
2485
- return this._def.shape();
2486
- }
2487
- strict(message) {
2488
- errorUtil.errToObj;
2489
- return new _ZodObject({
2490
- ...this._def,
2491
- unknownKeys: "strict",
2492
- ...message !== void 0 ? {
2493
- errorMap: (issue, ctx) => {
2494
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2495
- if (issue.code === "unrecognized_keys")
2496
- return {
2497
- message: errorUtil.errToObj(message).message ?? defaultError
2498
- };
2499
- return {
2500
- message: defaultError
2501
- };
2502
- }
2503
- } : {}
2504
- });
2505
- }
2506
- strip() {
2507
- return new _ZodObject({
2508
- ...this._def,
2509
- unknownKeys: "strip"
2510
- });
2511
- }
2512
- passthrough() {
2513
- return new _ZodObject({
2514
- ...this._def,
2515
- unknownKeys: "passthrough"
2516
- });
2517
- }
2518
- // const AugmentFactory =
2519
- // <Def extends ZodObjectDef>(def: Def) =>
2520
- // <Augmentation extends ZodRawShape>(
2521
- // augmentation: Augmentation
2522
- // ): ZodObject<
2523
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2524
- // Def["unknownKeys"],
2525
- // Def["catchall"]
2526
- // > => {
2527
- // return new ZodObject({
2528
- // ...def,
2529
- // shape: () => ({
2530
- // ...def.shape(),
2531
- // ...augmentation,
2532
- // }),
2533
- // }) as any;
2534
- // };
2535
- extend(augmentation) {
2536
- return new _ZodObject({
2537
- ...this._def,
2538
- shape: () => ({
2539
- ...this._def.shape(),
2540
- ...augmentation
2541
- })
2542
- });
2543
- }
2544
- /**
2545
- * Prior to zod@1.0.12 there was a bug in the
2546
- * inferred type of merged objects. Please
2547
- * upgrade if you are experiencing issues.
2548
- */
2549
- merge(merging) {
2550
- const merged = new _ZodObject({
2551
- unknownKeys: merging._def.unknownKeys,
2552
- catchall: merging._def.catchall,
2553
- shape: () => ({
2554
- ...this._def.shape(),
2555
- ...merging._def.shape()
2556
- }),
2557
- typeName: ZodFirstPartyTypeKind.ZodObject
2558
- });
2559
- return merged;
2560
- }
2561
- // merge<
2562
- // Incoming extends AnyZodObject,
2563
- // Augmentation extends Incoming["shape"],
2564
- // NewOutput extends {
2565
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2566
- // ? Augmentation[k]["_output"]
2567
- // : k extends keyof Output
2568
- // ? Output[k]
2569
- // : never;
2570
- // },
2571
- // NewInput extends {
2572
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2573
- // ? Augmentation[k]["_input"]
2574
- // : k extends keyof Input
2575
- // ? Input[k]
2576
- // : never;
2577
- // }
2578
- // >(
2579
- // merging: Incoming
2580
- // ): ZodObject<
2581
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2582
- // Incoming["_def"]["unknownKeys"],
2583
- // Incoming["_def"]["catchall"],
2584
- // NewOutput,
2585
- // NewInput
2586
- // > {
2587
- // const merged: any = new ZodObject({
2588
- // unknownKeys: merging._def.unknownKeys,
2589
- // catchall: merging._def.catchall,
2590
- // shape: () =>
2591
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2592
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2593
- // }) as any;
2594
- // return merged;
2595
- // }
2596
- setKey(key, schema) {
2597
- return this.augment({ [key]: schema });
2598
- }
2599
- // merge<Incoming extends AnyZodObject>(
2600
- // merging: Incoming
2601
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2602
- // ZodObject<
2603
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2604
- // Incoming["_def"]["unknownKeys"],
2605
- // Incoming["_def"]["catchall"]
2606
- // > {
2607
- // // const mergedShape = objectUtil.mergeShapes(
2608
- // // this._def.shape(),
2609
- // // merging._def.shape()
2610
- // // );
2611
- // const merged: any = new ZodObject({
2612
- // unknownKeys: merging._def.unknownKeys,
2613
- // catchall: merging._def.catchall,
2614
- // shape: () =>
2615
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2616
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2617
- // }) as any;
2618
- // return merged;
2619
- // }
2620
- catchall(index) {
2621
- return new _ZodObject({
2622
- ...this._def,
2623
- catchall: index
2624
- });
2625
- }
2626
- pick(mask) {
2627
- const shape = {};
2628
- for (const key of util.objectKeys(mask)) {
2629
- if (mask[key] && this.shape[key]) {
2630
- shape[key] = this.shape[key];
2631
- }
2632
- }
2633
- return new _ZodObject({
2634
- ...this._def,
2635
- shape: () => shape
2636
- });
2637
- }
2638
- omit(mask) {
2639
- const shape = {};
2640
- for (const key of util.objectKeys(this.shape)) {
2641
- if (!mask[key]) {
2642
- shape[key] = this.shape[key];
2643
- }
2644
- }
2645
- return new _ZodObject({
2646
- ...this._def,
2647
- shape: () => shape
2648
- });
2649
- }
2650
- /**
2651
- * @deprecated
2652
- */
2653
- deepPartial() {
2654
- return deepPartialify(this);
2655
- }
2656
- partial(mask) {
2657
- const newShape = {};
2658
- for (const key of util.objectKeys(this.shape)) {
2659
- const fieldSchema = this.shape[key];
2660
- if (mask && !mask[key]) {
2661
- newShape[key] = fieldSchema;
2662
- } else {
2663
- newShape[key] = fieldSchema.optional();
2664
- }
2665
- }
2666
- return new _ZodObject({
2667
- ...this._def,
2668
- shape: () => newShape
2669
- });
2670
- }
2671
- required(mask) {
2672
- const newShape = {};
2673
- for (const key of util.objectKeys(this.shape)) {
2674
- if (mask && !mask[key]) {
2675
- newShape[key] = this.shape[key];
2676
- } else {
2677
- const fieldSchema = this.shape[key];
2678
- let newField = fieldSchema;
2679
- while (newField instanceof ZodOptional) {
2680
- newField = newField._def.innerType;
2681
- }
2682
- newShape[key] = newField;
2683
- }
2684
- }
2685
- return new _ZodObject({
2686
- ...this._def,
2687
- shape: () => newShape
2688
- });
2689
- }
2690
- keyof() {
2691
- return createZodEnum(util.objectKeys(this.shape));
2692
- }
2693
- };
2694
- ZodObject.create = (shape, params) => {
2695
- return new ZodObject({
2696
- shape: () => shape,
2697
- unknownKeys: "strip",
2698
- catchall: ZodNever.create(),
2699
- typeName: ZodFirstPartyTypeKind.ZodObject,
2700
- ...processCreateParams(params)
2701
- });
2702
- };
2703
- ZodObject.strictCreate = (shape, params) => {
2704
- return new ZodObject({
2705
- shape: () => shape,
2706
- unknownKeys: "strict",
2707
- catchall: ZodNever.create(),
2708
- typeName: ZodFirstPartyTypeKind.ZodObject,
2709
- ...processCreateParams(params)
2710
- });
2711
- };
2712
- ZodObject.lazycreate = (shape, params) => {
2713
- return new ZodObject({
2714
- shape,
2715
- unknownKeys: "strip",
2716
- catchall: ZodNever.create(),
2717
- typeName: ZodFirstPartyTypeKind.ZodObject,
2718
- ...processCreateParams(params)
2719
- });
2720
- };
2721
- var ZodUnion = class extends ZodType {
2722
- _parse(input) {
2723
- const { ctx } = this._processInputParams(input);
2724
- const options = this._def.options;
2725
- function handleResults(results) {
2726
- for (const result of results) {
2727
- if (result.result.status === "valid") {
2728
- return result.result;
2729
- }
2730
- }
2731
- for (const result of results) {
2732
- if (result.result.status === "dirty") {
2733
- ctx.common.issues.push(...result.ctx.common.issues);
2734
- return result.result;
2735
- }
2736
- }
2737
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2738
- addIssueToContext(ctx, {
2739
- code: ZodIssueCode.invalid_union,
2740
- unionErrors
2741
- });
2742
- return INVALID;
2743
- }
2744
- if (ctx.common.async) {
2745
- return Promise.all(options.map(async (option) => {
2746
- const childCtx = {
2747
- ...ctx,
2748
- common: {
2749
- ...ctx.common,
2750
- issues: []
2751
- },
2752
- parent: null
2753
- };
2754
- return {
2755
- result: await option._parseAsync({
2756
- data: ctx.data,
2757
- path: ctx.path,
2758
- parent: childCtx
2759
- }),
2760
- ctx: childCtx
2761
- };
2762
- })).then(handleResults);
2763
- } else {
2764
- let dirty = void 0;
2765
- const issues = [];
2766
- for (const option of options) {
2767
- const childCtx = {
2768
- ...ctx,
2769
- common: {
2770
- ...ctx.common,
2771
- issues: []
2772
- },
2773
- parent: null
2774
- };
2775
- const result = option._parseSync({
2776
- data: ctx.data,
2777
- path: ctx.path,
2778
- parent: childCtx
2779
- });
2780
- if (result.status === "valid") {
2781
- return result;
2782
- } else if (result.status === "dirty" && !dirty) {
2783
- dirty = { result, ctx: childCtx };
2784
- }
2785
- if (childCtx.common.issues.length) {
2786
- issues.push(childCtx.common.issues);
2787
- }
2788
- }
2789
- if (dirty) {
2790
- ctx.common.issues.push(...dirty.ctx.common.issues);
2791
- return dirty.result;
2792
- }
2793
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
2794
- addIssueToContext(ctx, {
2795
- code: ZodIssueCode.invalid_union,
2796
- unionErrors
2797
- });
2798
- return INVALID;
2799
- }
2800
- }
2801
- get options() {
2802
- return this._def.options;
2803
- }
2804
- };
2805
- ZodUnion.create = (types, params) => {
2806
- return new ZodUnion({
2807
- options: types,
2808
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2809
- ...processCreateParams(params)
2810
- });
2811
- };
2812
- var getDiscriminator = (type) => {
2813
- if (type instanceof ZodLazy) {
2814
- return getDiscriminator(type.schema);
2815
- } else if (type instanceof ZodEffects) {
2816
- return getDiscriminator(type.innerType());
2817
- } else if (type instanceof ZodLiteral) {
2818
- return [type.value];
2819
- } else if (type instanceof ZodEnum) {
2820
- return type.options;
2821
- } else if (type instanceof ZodNativeEnum) {
2822
- return util.objectValues(type.enum);
2823
- } else if (type instanceof ZodDefault) {
2824
- return getDiscriminator(type._def.innerType);
2825
- } else if (type instanceof ZodUndefined) {
2826
- return [void 0];
2827
- } else if (type instanceof ZodNull) {
2828
- return [null];
2829
- } else if (type instanceof ZodOptional) {
2830
- return [void 0, ...getDiscriminator(type.unwrap())];
2831
- } else if (type instanceof ZodNullable) {
2832
- return [null, ...getDiscriminator(type.unwrap())];
2833
- } else if (type instanceof ZodBranded) {
2834
- return getDiscriminator(type.unwrap());
2835
- } else if (type instanceof ZodReadonly) {
2836
- return getDiscriminator(type.unwrap());
2837
- } else if (type instanceof ZodCatch) {
2838
- return getDiscriminator(type._def.innerType);
2839
- } else {
2840
- return [];
2841
- }
2842
- };
2843
- var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2844
- _parse(input) {
2845
- const { ctx } = this._processInputParams(input);
2846
- if (ctx.parsedType !== ZodParsedType.object) {
2847
- addIssueToContext(ctx, {
2848
- code: ZodIssueCode.invalid_type,
2849
- expected: ZodParsedType.object,
2850
- received: ctx.parsedType
2851
- });
2852
- return INVALID;
2853
- }
2854
- const discriminator = this.discriminator;
2855
- const discriminatorValue = ctx.data[discriminator];
2856
- const option = this.optionsMap.get(discriminatorValue);
2857
- if (!option) {
2858
- addIssueToContext(ctx, {
2859
- code: ZodIssueCode.invalid_union_discriminator,
2860
- options: Array.from(this.optionsMap.keys()),
2861
- path: [discriminator]
2862
- });
2863
- return INVALID;
2864
- }
2865
- if (ctx.common.async) {
2866
- return option._parseAsync({
2867
- data: ctx.data,
2868
- path: ctx.path,
2869
- parent: ctx
2870
- });
2871
- } else {
2872
- return option._parseSync({
2873
- data: ctx.data,
2874
- path: ctx.path,
2875
- parent: ctx
2876
- });
2877
- }
2878
- }
2879
- get discriminator() {
2880
- return this._def.discriminator;
2881
- }
2882
- get options() {
2883
- return this._def.options;
2884
- }
2885
- get optionsMap() {
2886
- return this._def.optionsMap;
2887
- }
2888
- /**
2889
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2890
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2891
- * have a different value for each object in the union.
2892
- * @param discriminator the name of the discriminator property
2893
- * @param types an array of object schemas
2894
- * @param params
2895
- */
2896
- static create(discriminator, options, params) {
2897
- const optionsMap = /* @__PURE__ */ new Map();
2898
- for (const type of options) {
2899
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2900
- if (!discriminatorValues.length) {
2901
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2902
- }
2903
- for (const value of discriminatorValues) {
2904
- if (optionsMap.has(value)) {
2905
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2906
- }
2907
- optionsMap.set(value, type);
2908
- }
2909
- }
2910
- return new _ZodDiscriminatedUnion({
2911
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2912
- discriminator,
2913
- options,
2914
- optionsMap,
2915
- ...processCreateParams(params)
2916
- });
2917
- }
2918
- };
2919
- function mergeValues(a, b) {
2920
- const aType = getParsedType(a);
2921
- const bType = getParsedType(b);
2922
- if (a === b) {
2923
- return { valid: true, data: a };
2924
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2925
- const bKeys = util.objectKeys(b);
2926
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2927
- const newObj = { ...a, ...b };
2928
- for (const key of sharedKeys) {
2929
- const sharedValue = mergeValues(a[key], b[key]);
2930
- if (!sharedValue.valid) {
2931
- return { valid: false };
2932
- }
2933
- newObj[key] = sharedValue.data;
2934
- }
2935
- return { valid: true, data: newObj };
2936
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2937
- if (a.length !== b.length) {
2938
- return { valid: false };
2939
- }
2940
- const newArray = [];
2941
- for (let index = 0; index < a.length; index++) {
2942
- const itemA = a[index];
2943
- const itemB = b[index];
2944
- const sharedValue = mergeValues(itemA, itemB);
2945
- if (!sharedValue.valid) {
2946
- return { valid: false };
2947
- }
2948
- newArray.push(sharedValue.data);
2949
- }
2950
- return { valid: true, data: newArray };
2951
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2952
- return { valid: true, data: a };
2953
- } else {
2954
- return { valid: false };
2955
- }
2956
- }
2957
- var ZodIntersection = class extends ZodType {
2958
- _parse(input) {
2959
- const { status, ctx } = this._processInputParams(input);
2960
- const handleParsed = (parsedLeft, parsedRight) => {
2961
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2962
- return INVALID;
2963
- }
2964
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2965
- if (!merged.valid) {
2966
- addIssueToContext(ctx, {
2967
- code: ZodIssueCode.invalid_intersection_types
2968
- });
2969
- return INVALID;
2970
- }
2971
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2972
- status.dirty();
2973
- }
2974
- return { status: status.value, value: merged.data };
2975
- };
2976
- if (ctx.common.async) {
2977
- return Promise.all([
2978
- this._def.left._parseAsync({
2979
- data: ctx.data,
2980
- path: ctx.path,
2981
- parent: ctx
2982
- }),
2983
- this._def.right._parseAsync({
2984
- data: ctx.data,
2985
- path: ctx.path,
2986
- parent: ctx
2987
- })
2988
- ]).then(([left, right]) => handleParsed(left, right));
2989
- } else {
2990
- return handleParsed(this._def.left._parseSync({
2991
- data: ctx.data,
2992
- path: ctx.path,
2993
- parent: ctx
2994
- }), this._def.right._parseSync({
2995
- data: ctx.data,
2996
- path: ctx.path,
2997
- parent: ctx
2998
- }));
2999
- }
3000
- }
3001
- };
3002
- ZodIntersection.create = (left, right, params) => {
3003
- return new ZodIntersection({
3004
- left,
3005
- right,
3006
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
3007
- ...processCreateParams(params)
3008
- });
3009
- };
3010
- var ZodTuple = class _ZodTuple extends ZodType {
3011
- _parse(input) {
3012
- const { status, ctx } = this._processInputParams(input);
3013
- if (ctx.parsedType !== ZodParsedType.array) {
3014
- addIssueToContext(ctx, {
3015
- code: ZodIssueCode.invalid_type,
3016
- expected: ZodParsedType.array,
3017
- received: ctx.parsedType
3018
- });
3019
- return INVALID;
3020
- }
3021
- if (ctx.data.length < this._def.items.length) {
3022
- addIssueToContext(ctx, {
3023
- code: ZodIssueCode.too_small,
3024
- minimum: this._def.items.length,
3025
- inclusive: true,
3026
- exact: false,
3027
- type: "array"
3028
- });
3029
- return INVALID;
3030
- }
3031
- const rest = this._def.rest;
3032
- if (!rest && ctx.data.length > this._def.items.length) {
3033
- addIssueToContext(ctx, {
3034
- code: ZodIssueCode.too_big,
3035
- maximum: this._def.items.length,
3036
- inclusive: true,
3037
- exact: false,
3038
- type: "array"
3039
- });
3040
- status.dirty();
3041
- }
3042
- const items = [...ctx.data].map((item, itemIndex) => {
3043
- const schema = this._def.items[itemIndex] || this._def.rest;
3044
- if (!schema)
3045
- return null;
3046
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3047
- }).filter((x) => !!x);
3048
- if (ctx.common.async) {
3049
- return Promise.all(items).then((results) => {
3050
- return ParseStatus.mergeArray(status, results);
3051
- });
3052
- } else {
3053
- return ParseStatus.mergeArray(status, items);
3054
- }
3055
- }
3056
- get items() {
3057
- return this._def.items;
3058
- }
3059
- rest(rest) {
3060
- return new _ZodTuple({
3061
- ...this._def,
3062
- rest
3063
- });
3064
- }
3065
- };
3066
- ZodTuple.create = (schemas, params) => {
3067
- if (!Array.isArray(schemas)) {
3068
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3069
- }
3070
- return new ZodTuple({
3071
- items: schemas,
3072
- typeName: ZodFirstPartyTypeKind.ZodTuple,
3073
- rest: null,
3074
- ...processCreateParams(params)
3075
- });
3076
- };
3077
- var ZodRecord = class _ZodRecord extends ZodType {
3078
- get keySchema() {
3079
- return this._def.keyType;
3080
- }
3081
- get valueSchema() {
3082
- return this._def.valueType;
3083
- }
3084
- _parse(input) {
3085
- const { status, ctx } = this._processInputParams(input);
3086
- if (ctx.parsedType !== ZodParsedType.object) {
3087
- addIssueToContext(ctx, {
3088
- code: ZodIssueCode.invalid_type,
3089
- expected: ZodParsedType.object,
3090
- received: ctx.parsedType
3091
- });
3092
- return INVALID;
3093
- }
3094
- const pairs = [];
3095
- const keyType = this._def.keyType;
3096
- const valueType = this._def.valueType;
3097
- for (const key in ctx.data) {
3098
- pairs.push({
3099
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3100
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3101
- alwaysSet: key in ctx.data
3102
- });
3103
- }
3104
- if (ctx.common.async) {
3105
- return ParseStatus.mergeObjectAsync(status, pairs);
3106
- } else {
3107
- return ParseStatus.mergeObjectSync(status, pairs);
3108
- }
3109
- }
3110
- get element() {
3111
- return this._def.valueType;
3112
- }
3113
- static create(first, second, third) {
3114
- if (second instanceof ZodType) {
3115
- return new _ZodRecord({
3116
- keyType: first,
3117
- valueType: second,
3118
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3119
- ...processCreateParams(third)
3120
- });
3121
- }
3122
- return new _ZodRecord({
3123
- keyType: ZodString.create(),
3124
- valueType: first,
3125
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3126
- ...processCreateParams(second)
3127
- });
3128
- }
3129
- };
3130
- var ZodMap = class extends ZodType {
3131
- get keySchema() {
3132
- return this._def.keyType;
3133
- }
3134
- get valueSchema() {
3135
- return this._def.valueType;
3136
- }
3137
- _parse(input) {
3138
- const { status, ctx } = this._processInputParams(input);
3139
- if (ctx.parsedType !== ZodParsedType.map) {
3140
- addIssueToContext(ctx, {
3141
- code: ZodIssueCode.invalid_type,
3142
- expected: ZodParsedType.map,
3143
- received: ctx.parsedType
3144
- });
3145
- return INVALID;
3146
- }
3147
- const keyType = this._def.keyType;
3148
- const valueType = this._def.valueType;
3149
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3150
- return {
3151
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3152
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3153
- };
3154
- });
3155
- if (ctx.common.async) {
3156
- const finalMap = /* @__PURE__ */ new Map();
3157
- return Promise.resolve().then(async () => {
3158
- for (const pair of pairs) {
3159
- const key = await pair.key;
3160
- const value = await pair.value;
3161
- if (key.status === "aborted" || value.status === "aborted") {
3162
- return INVALID;
3163
- }
3164
- if (key.status === "dirty" || value.status === "dirty") {
3165
- status.dirty();
3166
- }
3167
- finalMap.set(key.value, value.value);
3168
- }
3169
- return { status: status.value, value: finalMap };
3170
- });
3171
- } else {
3172
- const finalMap = /* @__PURE__ */ new Map();
3173
- for (const pair of pairs) {
3174
- const key = pair.key;
3175
- const value = pair.value;
3176
- if (key.status === "aborted" || value.status === "aborted") {
3177
- return INVALID;
3178
- }
3179
- if (key.status === "dirty" || value.status === "dirty") {
3180
- status.dirty();
3181
- }
3182
- finalMap.set(key.value, value.value);
3183
- }
3184
- return { status: status.value, value: finalMap };
3185
- }
3186
- }
3187
- };
3188
- ZodMap.create = (keyType, valueType, params) => {
3189
- return new ZodMap({
3190
- valueType,
3191
- keyType,
3192
- typeName: ZodFirstPartyTypeKind.ZodMap,
3193
- ...processCreateParams(params)
3194
- });
3195
- };
3196
- var ZodSet = class _ZodSet extends ZodType {
3197
- _parse(input) {
3198
- const { status, ctx } = this._processInputParams(input);
3199
- if (ctx.parsedType !== ZodParsedType.set) {
3200
- addIssueToContext(ctx, {
3201
- code: ZodIssueCode.invalid_type,
3202
- expected: ZodParsedType.set,
3203
- received: ctx.parsedType
3204
- });
3205
- return INVALID;
3206
- }
3207
- const def = this._def;
3208
- if (def.minSize !== null) {
3209
- if (ctx.data.size < def.minSize.value) {
3210
- addIssueToContext(ctx, {
3211
- code: ZodIssueCode.too_small,
3212
- minimum: def.minSize.value,
3213
- type: "set",
3214
- inclusive: true,
3215
- exact: false,
3216
- message: def.minSize.message
3217
- });
3218
- status.dirty();
3219
- }
3220
- }
3221
- if (def.maxSize !== null) {
3222
- if (ctx.data.size > def.maxSize.value) {
3223
- addIssueToContext(ctx, {
3224
- code: ZodIssueCode.too_big,
3225
- maximum: def.maxSize.value,
3226
- type: "set",
3227
- inclusive: true,
3228
- exact: false,
3229
- message: def.maxSize.message
3230
- });
3231
- status.dirty();
3232
- }
3233
- }
3234
- const valueType = this._def.valueType;
3235
- function finalizeSet(elements2) {
3236
- const parsedSet = /* @__PURE__ */ new Set();
3237
- for (const element of elements2) {
3238
- if (element.status === "aborted")
3239
- return INVALID;
3240
- if (element.status === "dirty")
3241
- status.dirty();
3242
- parsedSet.add(element.value);
3243
- }
3244
- return { status: status.value, value: parsedSet };
3245
- }
3246
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3247
- if (ctx.common.async) {
3248
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3249
- } else {
3250
- return finalizeSet(elements);
3251
- }
3252
- }
3253
- min(minSize, message) {
3254
- return new _ZodSet({
3255
- ...this._def,
3256
- minSize: { value: minSize, message: errorUtil.toString(message) }
3257
- });
3258
- }
3259
- max(maxSize, message) {
3260
- return new _ZodSet({
3261
- ...this._def,
3262
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
3263
- });
3264
- }
3265
- size(size, message) {
3266
- return this.min(size, message).max(size, message);
3267
- }
3268
- nonempty(message) {
3269
- return this.min(1, message);
3270
- }
3271
- };
3272
- ZodSet.create = (valueType, params) => {
3273
- return new ZodSet({
3274
- valueType,
3275
- minSize: null,
3276
- maxSize: null,
3277
- typeName: ZodFirstPartyTypeKind.ZodSet,
3278
- ...processCreateParams(params)
3279
- });
3280
- };
3281
- var ZodFunction = class _ZodFunction extends ZodType {
3282
- constructor() {
3283
- super(...arguments);
3284
- this.validate = this.implement;
3285
- }
3286
- _parse(input) {
3287
- const { ctx } = this._processInputParams(input);
3288
- if (ctx.parsedType !== ZodParsedType.function) {
3289
- addIssueToContext(ctx, {
3290
- code: ZodIssueCode.invalid_type,
3291
- expected: ZodParsedType.function,
3292
- received: ctx.parsedType
3293
- });
3294
- return INVALID;
3295
- }
3296
- function makeArgsIssue(args, error) {
3297
- return makeIssue({
3298
- data: args,
3299
- path: ctx.path,
3300
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3301
- issueData: {
3302
- code: ZodIssueCode.invalid_arguments,
3303
- argumentsError: error
3304
- }
3305
- });
3306
- }
3307
- function makeReturnsIssue(returns, error) {
3308
- return makeIssue({
3309
- data: returns,
3310
- path: ctx.path,
3311
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3312
- issueData: {
3313
- code: ZodIssueCode.invalid_return_type,
3314
- returnTypeError: error
3315
- }
3316
- });
3317
- }
3318
- const params = { errorMap: ctx.common.contextualErrorMap };
3319
- const fn = ctx.data;
3320
- if (this._def.returns instanceof ZodPromise) {
3321
- const me = this;
3322
- return OK(async function(...args) {
3323
- const error = new ZodError([]);
3324
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3325
- error.addIssue(makeArgsIssue(args, e));
3326
- throw error;
3327
- });
3328
- const result = await Reflect.apply(fn, this, parsedArgs);
3329
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3330
- error.addIssue(makeReturnsIssue(result, e));
3331
- throw error;
3332
- });
3333
- return parsedReturns;
3334
- });
3335
- } else {
3336
- const me = this;
3337
- return OK(function(...args) {
3338
- const parsedArgs = me._def.args.safeParse(args, params);
3339
- if (!parsedArgs.success) {
3340
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3341
- }
3342
- const result = Reflect.apply(fn, this, parsedArgs.data);
3343
- const parsedReturns = me._def.returns.safeParse(result, params);
3344
- if (!parsedReturns.success) {
3345
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3346
- }
3347
- return parsedReturns.data;
3348
- });
3349
- }
3350
- }
3351
- parameters() {
3352
- return this._def.args;
3353
- }
3354
- returnType() {
3355
- return this._def.returns;
3356
- }
3357
- args(...items) {
3358
- return new _ZodFunction({
3359
- ...this._def,
3360
- args: ZodTuple.create(items).rest(ZodUnknown.create())
3361
- });
3362
- }
3363
- returns(returnType) {
3364
- return new _ZodFunction({
3365
- ...this._def,
3366
- returns: returnType
3367
- });
3368
- }
3369
- implement(func) {
3370
- const validatedFunc = this.parse(func);
3371
- return validatedFunc;
3372
- }
3373
- strictImplement(func) {
3374
- const validatedFunc = this.parse(func);
3375
- return validatedFunc;
3376
- }
3377
- static create(args, returns, params) {
3378
- return new _ZodFunction({
3379
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3380
- returns: returns || ZodUnknown.create(),
3381
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3382
- ...processCreateParams(params)
3383
- });
3384
- }
3385
- };
3386
- var ZodLazy = class extends ZodType {
3387
- get schema() {
3388
- return this._def.getter();
3389
- }
3390
- _parse(input) {
3391
- const { ctx } = this._processInputParams(input);
3392
- const lazySchema = this._def.getter();
3393
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3394
- }
3395
- };
3396
- ZodLazy.create = (getter, params) => {
3397
- return new ZodLazy({
3398
- getter,
3399
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3400
- ...processCreateParams(params)
3401
- });
3402
- };
3403
- var ZodLiteral = class extends ZodType {
3404
- _parse(input) {
3405
- if (input.data !== this._def.value) {
3406
- const ctx = this._getOrReturnCtx(input);
3407
- addIssueToContext(ctx, {
3408
- received: ctx.data,
3409
- code: ZodIssueCode.invalid_literal,
3410
- expected: this._def.value
3411
- });
3412
- return INVALID;
3413
- }
3414
- return { status: "valid", value: input.data };
3415
- }
3416
- get value() {
3417
- return this._def.value;
3418
- }
3419
- };
3420
- ZodLiteral.create = (value, params) => {
3421
- return new ZodLiteral({
3422
- value,
3423
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3424
- ...processCreateParams(params)
3425
- });
3426
- };
3427
- function createZodEnum(values, params) {
3428
- return new ZodEnum({
3429
- values,
3430
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3431
- ...processCreateParams(params)
3432
- });
3433
- }
3434
- var ZodEnum = class _ZodEnum extends ZodType {
3435
- _parse(input) {
3436
- if (typeof input.data !== "string") {
3437
- const ctx = this._getOrReturnCtx(input);
3438
- const expectedValues = this._def.values;
3439
- addIssueToContext(ctx, {
3440
- expected: util.joinValues(expectedValues),
3441
- received: ctx.parsedType,
3442
- code: ZodIssueCode.invalid_type
3443
- });
3444
- return INVALID;
3445
- }
3446
- if (!this._cache) {
3447
- this._cache = new Set(this._def.values);
3448
- }
3449
- if (!this._cache.has(input.data)) {
3450
- const ctx = this._getOrReturnCtx(input);
3451
- const expectedValues = this._def.values;
3452
- addIssueToContext(ctx, {
3453
- received: ctx.data,
3454
- code: ZodIssueCode.invalid_enum_value,
3455
- options: expectedValues
3456
- });
3457
- return INVALID;
3458
- }
3459
- return OK(input.data);
3460
- }
3461
- get options() {
3462
- return this._def.values;
3463
- }
3464
- get enum() {
3465
- const enumValues = {};
3466
- for (const val of this._def.values) {
3467
- enumValues[val] = val;
3468
- }
3469
- return enumValues;
3470
- }
3471
- get Values() {
3472
- const enumValues = {};
3473
- for (const val of this._def.values) {
3474
- enumValues[val] = val;
3475
- }
3476
- return enumValues;
3477
- }
3478
- get Enum() {
3479
- const enumValues = {};
3480
- for (const val of this._def.values) {
3481
- enumValues[val] = val;
3482
- }
3483
- return enumValues;
3484
- }
3485
- extract(values, newDef = this._def) {
3486
- return _ZodEnum.create(values, {
3487
- ...this._def,
3488
- ...newDef
3489
- });
3490
- }
3491
- exclude(values, newDef = this._def) {
3492
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3493
- ...this._def,
3494
- ...newDef
3495
- });
3496
- }
3497
- };
3498
- ZodEnum.create = createZodEnum;
3499
- var ZodNativeEnum = class extends ZodType {
3500
- _parse(input) {
3501
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3502
- const ctx = this._getOrReturnCtx(input);
3503
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3504
- const expectedValues = util.objectValues(nativeEnumValues);
3505
- addIssueToContext(ctx, {
3506
- expected: util.joinValues(expectedValues),
3507
- received: ctx.parsedType,
3508
- code: ZodIssueCode.invalid_type
3509
- });
3510
- return INVALID;
3511
- }
3512
- if (!this._cache) {
3513
- this._cache = new Set(util.getValidEnumValues(this._def.values));
3514
- }
3515
- if (!this._cache.has(input.data)) {
3516
- const expectedValues = util.objectValues(nativeEnumValues);
3517
- addIssueToContext(ctx, {
3518
- received: ctx.data,
3519
- code: ZodIssueCode.invalid_enum_value,
3520
- options: expectedValues
3521
- });
3522
- return INVALID;
3523
- }
3524
- return OK(input.data);
3525
- }
3526
- get enum() {
3527
- return this._def.values;
3528
- }
3529
- };
3530
- ZodNativeEnum.create = (values, params) => {
3531
- return new ZodNativeEnum({
3532
- values,
3533
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3534
- ...processCreateParams(params)
3535
- });
3536
- };
3537
- var ZodPromise = class extends ZodType {
3538
- unwrap() {
3539
- return this._def.type;
3540
- }
3541
- _parse(input) {
3542
- const { ctx } = this._processInputParams(input);
3543
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3544
- addIssueToContext(ctx, {
3545
- code: ZodIssueCode.invalid_type,
3546
- expected: ZodParsedType.promise,
3547
- received: ctx.parsedType
3548
- });
3549
- return INVALID;
3550
- }
3551
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3552
- return OK(promisified.then((data) => {
3553
- return this._def.type.parseAsync(data, {
3554
- path: ctx.path,
3555
- errorMap: ctx.common.contextualErrorMap
3556
- });
3557
- }));
3558
- }
3559
- };
3560
- ZodPromise.create = (schema, params) => {
3561
- return new ZodPromise({
3562
- type: schema,
3563
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3564
- ...processCreateParams(params)
3565
- });
3566
- };
3567
- var ZodEffects = class extends ZodType {
3568
- innerType() {
3569
- return this._def.schema;
3570
- }
3571
- sourceType() {
3572
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3573
- }
3574
- _parse(input) {
3575
- const { status, ctx } = this._processInputParams(input);
3576
- const effect = this._def.effect || null;
3577
- const checkCtx = {
3578
- addIssue: (arg) => {
3579
- addIssueToContext(ctx, arg);
3580
- if (arg.fatal) {
3581
- status.abort();
3582
- } else {
3583
- status.dirty();
3584
- }
3585
- },
3586
- get path() {
3587
- return ctx.path;
3588
- }
3589
- };
3590
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3591
- if (effect.type === "preprocess") {
3592
- const processed = effect.transform(ctx.data, checkCtx);
3593
- if (ctx.common.async) {
3594
- return Promise.resolve(processed).then(async (processed2) => {
3595
- if (status.value === "aborted")
3596
- return INVALID;
3597
- const result = await this._def.schema._parseAsync({
3598
- data: processed2,
3599
- path: ctx.path,
3600
- parent: ctx
3601
- });
3602
- if (result.status === "aborted")
3603
- return INVALID;
3604
- if (result.status === "dirty")
3605
- return DIRTY(result.value);
3606
- if (status.value === "dirty")
3607
- return DIRTY(result.value);
3608
- return result;
3609
- });
3610
- } else {
3611
- if (status.value === "aborted")
3612
- return INVALID;
3613
- const result = this._def.schema._parseSync({
3614
- data: processed,
3615
- path: ctx.path,
3616
- parent: ctx
3617
- });
3618
- if (result.status === "aborted")
3619
- return INVALID;
3620
- if (result.status === "dirty")
3621
- return DIRTY(result.value);
3622
- if (status.value === "dirty")
3623
- return DIRTY(result.value);
3624
- return result;
3625
- }
3626
- }
3627
- if (effect.type === "refinement") {
3628
- const executeRefinement = (acc) => {
3629
- const result = effect.refinement(acc, checkCtx);
3630
- if (ctx.common.async) {
3631
- return Promise.resolve(result);
3632
- }
3633
- if (result instanceof Promise) {
3634
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3635
- }
3636
- return acc;
3637
- };
3638
- if (ctx.common.async === false) {
3639
- const inner = this._def.schema._parseSync({
3640
- data: ctx.data,
3641
- path: ctx.path,
3642
- parent: ctx
3643
- });
3644
- if (inner.status === "aborted")
3645
- return INVALID;
3646
- if (inner.status === "dirty")
3647
- status.dirty();
3648
- executeRefinement(inner.value);
3649
- return { status: status.value, value: inner.value };
3650
- } else {
3651
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3652
- if (inner.status === "aborted")
3653
- return INVALID;
3654
- if (inner.status === "dirty")
3655
- status.dirty();
3656
- return executeRefinement(inner.value).then(() => {
3657
- return { status: status.value, value: inner.value };
3658
- });
3659
- });
3660
- }
3661
- }
3662
- if (effect.type === "transform") {
3663
- if (ctx.common.async === false) {
3664
- const base = this._def.schema._parseSync({
3665
- data: ctx.data,
3666
- path: ctx.path,
3667
- parent: ctx
3668
- });
3669
- if (!isValid(base))
3670
- return INVALID;
3671
- const result = effect.transform(base.value, checkCtx);
3672
- if (result instanceof Promise) {
3673
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3674
- }
3675
- return { status: status.value, value: result };
3676
- } else {
3677
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3678
- if (!isValid(base))
3679
- return INVALID;
3680
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3681
- status: status.value,
3682
- value: result
3683
- }));
3684
- });
3685
- }
3686
- }
3687
- util.assertNever(effect);
3688
- }
3689
- };
3690
- ZodEffects.create = (schema, effect, params) => {
3691
- return new ZodEffects({
3692
- schema,
3693
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3694
- effect,
3695
- ...processCreateParams(params)
3696
- });
3697
- };
3698
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3699
- return new ZodEffects({
3700
- schema,
3701
- effect: { type: "preprocess", transform: preprocess },
3702
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3703
- ...processCreateParams(params)
3704
- });
3705
- };
3706
- var ZodOptional = class extends ZodType {
3707
- _parse(input) {
3708
- const parsedType = this._getType(input);
3709
- if (parsedType === ZodParsedType.undefined) {
3710
- return OK(void 0);
3711
- }
3712
- return this._def.innerType._parse(input);
3713
- }
3714
- unwrap() {
3715
- return this._def.innerType;
3716
- }
3717
- };
3718
- ZodOptional.create = (type, params) => {
3719
- return new ZodOptional({
3720
- innerType: type,
3721
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3722
- ...processCreateParams(params)
3723
- });
3724
- };
3725
- var ZodNullable = class extends ZodType {
3726
- _parse(input) {
3727
- const parsedType = this._getType(input);
3728
- if (parsedType === ZodParsedType.null) {
3729
- return OK(null);
3730
- }
3731
- return this._def.innerType._parse(input);
3732
- }
3733
- unwrap() {
3734
- return this._def.innerType;
3735
- }
3736
- };
3737
- ZodNullable.create = (type, params) => {
3738
- return new ZodNullable({
3739
- innerType: type,
3740
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3741
- ...processCreateParams(params)
3742
- });
3743
- };
3744
- var ZodDefault = class extends ZodType {
3745
- _parse(input) {
3746
- const { ctx } = this._processInputParams(input);
3747
- let data = ctx.data;
3748
- if (ctx.parsedType === ZodParsedType.undefined) {
3749
- data = this._def.defaultValue();
3750
- }
3751
- return this._def.innerType._parse({
3752
- data,
3753
- path: ctx.path,
3754
- parent: ctx
3755
- });
3756
- }
3757
- removeDefault() {
3758
- return this._def.innerType;
3759
- }
3760
- };
3761
- ZodDefault.create = (type, params) => {
3762
- return new ZodDefault({
3763
- innerType: type,
3764
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3765
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3766
- ...processCreateParams(params)
3767
- });
3768
- };
3769
- var ZodCatch = class extends ZodType {
3770
- _parse(input) {
3771
- const { ctx } = this._processInputParams(input);
3772
- const newCtx = {
3773
- ...ctx,
3774
- common: {
3775
- ...ctx.common,
3776
- issues: []
3777
- }
3778
- };
3779
- const result = this._def.innerType._parse({
3780
- data: newCtx.data,
3781
- path: newCtx.path,
3782
- parent: {
3783
- ...newCtx
3784
- }
3785
- });
3786
- if (isAsync(result)) {
3787
- return result.then((result2) => {
3788
- return {
3789
- status: "valid",
3790
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
3791
- get error() {
3792
- return new ZodError(newCtx.common.issues);
3793
- },
3794
- input: newCtx.data
3795
- })
3796
- };
3797
- });
3798
- } else {
3799
- return {
3800
- status: "valid",
3801
- value: result.status === "valid" ? result.value : this._def.catchValue({
3802
- get error() {
3803
- return new ZodError(newCtx.common.issues);
3804
- },
3805
- input: newCtx.data
3806
- })
3807
- };
3808
- }
3809
- }
3810
- removeCatch() {
3811
- return this._def.innerType;
3812
- }
3813
- };
3814
- ZodCatch.create = (type, params) => {
3815
- return new ZodCatch({
3816
- innerType: type,
3817
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3818
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3819
- ...processCreateParams(params)
3820
- });
3821
- };
3822
- var ZodNaN = class extends ZodType {
3823
- _parse(input) {
3824
- const parsedType = this._getType(input);
3825
- if (parsedType !== ZodParsedType.nan) {
3826
- const ctx = this._getOrReturnCtx(input);
3827
- addIssueToContext(ctx, {
3828
- code: ZodIssueCode.invalid_type,
3829
- expected: ZodParsedType.nan,
3830
- received: ctx.parsedType
3831
- });
3832
- return INVALID;
3833
- }
3834
- return { status: "valid", value: input.data };
3835
- }
3836
- };
3837
- ZodNaN.create = (params) => {
3838
- return new ZodNaN({
3839
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3840
- ...processCreateParams(params)
3841
- });
3842
- };
3843
- var BRAND = /* @__PURE__ */ Symbol("zod_brand");
3844
- var ZodBranded = class extends ZodType {
3845
- _parse(input) {
3846
- const { ctx } = this._processInputParams(input);
3847
- const data = ctx.data;
3848
- return this._def.type._parse({
3849
- data,
3850
- path: ctx.path,
3851
- parent: ctx
3852
- });
3853
- }
3854
- unwrap() {
3855
- return this._def.type;
3856
- }
3857
- };
3858
- var ZodPipeline = class _ZodPipeline extends ZodType {
3859
- _parse(input) {
3860
- const { status, ctx } = this._processInputParams(input);
3861
- if (ctx.common.async) {
3862
- const handleAsync = async () => {
3863
- const inResult = await this._def.in._parseAsync({
3864
- data: ctx.data,
3865
- path: ctx.path,
3866
- parent: ctx
3867
- });
3868
- if (inResult.status === "aborted")
3869
- return INVALID;
3870
- if (inResult.status === "dirty") {
3871
- status.dirty();
3872
- return DIRTY(inResult.value);
3873
- } else {
3874
- return this._def.out._parseAsync({
3875
- data: inResult.value,
3876
- path: ctx.path,
3877
- parent: ctx
3878
- });
3879
- }
3880
- };
3881
- return handleAsync();
3882
- } else {
3883
- const inResult = this._def.in._parseSync({
3884
- data: ctx.data,
3885
- path: ctx.path,
3886
- parent: ctx
3887
- });
3888
- if (inResult.status === "aborted")
3889
- return INVALID;
3890
- if (inResult.status === "dirty") {
3891
- status.dirty();
3892
- return {
3893
- status: "dirty",
3894
- value: inResult.value
3895
- };
3896
- } else {
3897
- return this._def.out._parseSync({
3898
- data: inResult.value,
3899
- path: ctx.path,
3900
- parent: ctx
3901
- });
3902
- }
3903
- }
3904
- }
3905
- static create(a, b) {
3906
- return new _ZodPipeline({
3907
- in: a,
3908
- out: b,
3909
- typeName: ZodFirstPartyTypeKind.ZodPipeline
3910
- });
3911
- }
3912
- };
3913
- var ZodReadonly = class extends ZodType {
3914
- _parse(input) {
3915
- const result = this._def.innerType._parse(input);
3916
- const freeze = (data) => {
3917
- if (isValid(data)) {
3918
- data.value = Object.freeze(data.value);
3919
- }
3920
- return data;
3921
- };
3922
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3923
- }
3924
- unwrap() {
3925
- return this._def.innerType;
3926
- }
3927
- };
3928
- ZodReadonly.create = (type, params) => {
3929
- return new ZodReadonly({
3930
- innerType: type,
3931
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3932
- ...processCreateParams(params)
3933
- });
3934
- };
3935
- function cleanParams(params, data) {
3936
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3937
- const p2 = typeof p === "string" ? { message: p } : p;
3938
- return p2;
3939
- }
3940
- function custom(check, _params = {}, fatal) {
3941
- if (check)
3942
- return ZodAny.create().superRefine((data, ctx) => {
3943
- const r = check(data);
3944
- if (r instanceof Promise) {
3945
- return r.then((r2) => {
3946
- if (!r2) {
3947
- const params = cleanParams(_params, data);
3948
- const _fatal = params.fatal ?? fatal ?? true;
3949
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3950
- }
3951
- });
3952
- }
3953
- if (!r) {
3954
- const params = cleanParams(_params, data);
3955
- const _fatal = params.fatal ?? fatal ?? true;
3956
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3957
- }
3958
- return;
3959
- });
3960
- return ZodAny.create();
3961
- }
3962
- var late = {
3963
- object: ZodObject.lazycreate
3964
- };
3965
- var ZodFirstPartyTypeKind;
3966
- (function(ZodFirstPartyTypeKind2) {
3967
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3968
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3969
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3970
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3971
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3972
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3973
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3974
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3975
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3976
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3977
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3978
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3979
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3980
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3981
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3982
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3983
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3984
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3985
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3986
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3987
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3988
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3989
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3990
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3991
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3992
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3993
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3994
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3995
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3996
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3997
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3998
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3999
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4000
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4001
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4002
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4003
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4004
- var instanceOfType = (cls, params = {
4005
- message: `Input not instance of ${cls.name}`
4006
- }) => custom((data) => data instanceof cls, params);
4007
- var stringType = ZodString.create;
4008
- var numberType = ZodNumber.create;
4009
- var nanType = ZodNaN.create;
4010
- var bigIntType = ZodBigInt.create;
4011
- var booleanType = ZodBoolean.create;
4012
- var dateType = ZodDate.create;
4013
- var symbolType = ZodSymbol.create;
4014
- var undefinedType = ZodUndefined.create;
4015
- var nullType = ZodNull.create;
4016
- var anyType = ZodAny.create;
4017
- var unknownType = ZodUnknown.create;
4018
- var neverType = ZodNever.create;
4019
- var voidType = ZodVoid.create;
4020
- var arrayType = ZodArray.create;
4021
- var objectType = ZodObject.create;
4022
- var strictObjectType = ZodObject.strictCreate;
4023
- var unionType = ZodUnion.create;
4024
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
4025
- var intersectionType = ZodIntersection.create;
4026
- var tupleType = ZodTuple.create;
4027
- var recordType = ZodRecord.create;
4028
- var mapType = ZodMap.create;
4029
- var setType = ZodSet.create;
4030
- var functionType = ZodFunction.create;
4031
- var lazyType = ZodLazy.create;
4032
- var literalType = ZodLiteral.create;
4033
- var enumType = ZodEnum.create;
4034
- var nativeEnumType = ZodNativeEnum.create;
4035
- var promiseType = ZodPromise.create;
4036
- var effectsType = ZodEffects.create;
4037
- var optionalType = ZodOptional.create;
4038
- var nullableType = ZodNullable.create;
4039
- var preprocessType = ZodEffects.createWithPreprocess;
4040
- var pipelineType = ZodPipeline.create;
4041
- var ostring = () => stringType().optional();
4042
- var onumber = () => numberType().optional();
4043
- var oboolean = () => booleanType().optional();
4044
- var coerce = {
4045
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4046
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4047
- boolean: ((arg) => ZodBoolean.create({
4048
- ...arg,
4049
- coerce: true
4050
- })),
4051
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4052
- date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4053
- };
4054
- var NEVER = INVALID;
1
+ // src/index.ts
2
+ import { access, appendFile, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
3
+ import { dirname as dirname2, resolve as resolve4 } from "path";
4
+ import process2 from "process";
5
+ import chalk from "chalk";
6
+ import { Command, CommanderError, Option } from "commander";
7
+ import { lilconfig } from "lilconfig";
4055
8
 
4056
9
  // ../types/dist/index.js
4057
- var FontSourceSchema = external_exports.enum(["google", "self-hosted", "custom", "generated"]);
4058
- var FontLicenseSchema = external_exports.object({
4059
- type: external_exports.enum(["ofl", "apache2", "proprietary", "custom", "derivative"]),
4060
- name: external_exports.string(),
4061
- url: external_exports.string().url().optional(),
4062
- restrictions: external_exports.object({
4063
- domains: external_exports.array(external_exports.string()).optional(),
4064
- regions: external_exports.array(external_exports.string()).optional(),
4065
- redistribution: external_exports.boolean().optional(),
4066
- modification: external_exports.boolean().optional()
10
+ import { z } from "zod";
11
+ import { z as z2 } from "zod";
12
+ import { z as z3 } from "zod";
13
+ import { z as z4 } from "zod";
14
+ import { z as z5 } from "zod";
15
+ import { z as z6 } from "zod";
16
+ var FontSourceSchema = z.enum(["google", "self-hosted", "custom", "generated"]);
17
+ var FontLicenseSchema = z.object({
18
+ type: z.enum(["ofl", "apache2", "proprietary", "custom", "derivative"]),
19
+ name: z.string(),
20
+ url: z.string().url().optional(),
21
+ restrictions: z.object({
22
+ domains: z.array(z.string()).optional(),
23
+ regions: z.array(z.string()).optional(),
24
+ redistribution: z.boolean().optional(),
25
+ modification: z.boolean().optional()
4067
26
  }).optional()
4068
27
  });
4069
- var FontAxisSchema = external_exports.object({
4070
- min: external_exports.number(),
4071
- max: external_exports.number(),
4072
- default: external_exports.number()
28
+ var FontAxisSchema = z.object({
29
+ min: z.number(),
30
+ max: z.number(),
31
+ default: z.number()
4073
32
  });
4074
- var FontReferenceSchema = external_exports.object({
4075
- family: external_exports.string(),
33
+ var FontReferenceSchema = z.object({
34
+ family: z.string(),
4076
35
  source: FontSourceSchema,
4077
- variable: external_exports.boolean().default(false),
4078
- axes: external_exports.record(external_exports.string(), FontAxisSchema).optional(),
36
+ variable: z.boolean().default(false),
37
+ axes: z.record(z.string(), FontAxisSchema).optional(),
4079
38
  license: FontLicenseSchema.optional(),
4080
- category: external_exports.enum(["sans-serif", "serif", "monospace", "display", "handwriting"]).optional(),
4081
- fallbacks: external_exports.array(external_exports.string()).optional()
39
+ category: z.enum(["sans-serif", "serif", "monospace", "display", "handwriting"]).optional(),
40
+ fallbacks: z.array(z.string()).optional()
4082
41
  });
4083
- var FontIntentSchema = external_exports.enum(["heading", "body", "ui", "data", "display", "code"]);
4084
- var FontSpecSchema = external_exports.object({
42
+ var FontIntentSchema = z.enum(["heading", "body", "ui", "data", "display", "code"]);
43
+ var FontSpecSchema = z.object({
4085
44
  primary: FontReferenceSchema,
4086
45
  secondary: FontReferenceSchema.optional(),
4087
46
  mono: FontReferenceSchema.optional(),
4088
- weights: external_exports.array(external_exports.number().min(1).max(1e3)),
4089
- opticalSizes: external_exports.object({
4090
- min: external_exports.number(),
4091
- max: external_exports.number()
47
+ weights: z.array(z.number().min(1).max(1e3)),
48
+ opticalSizes: z.object({
49
+ min: z.number(),
50
+ max: z.number()
4092
51
  }).optional(),
4093
52
  intent: FontIntentSchema
4094
53
  });
4095
- var FontMoodSchema = external_exports.enum([
54
+ var FontMoodSchema = z.enum([
4096
55
  "modern",
4097
56
  "classic",
4098
57
  "playful",
@@ -4108,32 +67,32 @@ var FontMoodSchema = external_exports.enum([
4108
67
  "casual",
4109
68
  "formal"
4110
69
  ]);
4111
- var FontMetadataSchema = external_exports.object({
4112
- family: external_exports.string(),
70
+ var FontMetadataSchema = z.object({
71
+ family: z.string(),
4113
72
  source: FontSourceSchema,
4114
- category: external_exports.enum(["sans-serif", "serif", "monospace", "display", "handwriting"]),
4115
- variable: external_exports.boolean(),
4116
- axes: external_exports.record(external_exports.string(), FontAxisSchema).optional(),
4117
- weights: external_exports.array(external_exports.number()),
4118
- subsets: external_exports.array(external_exports.string()),
4119
- moods: external_exports.array(FontMoodSchema),
4120
- readabilityScore: external_exports.number().min(0).max(1),
73
+ category: z.enum(["sans-serif", "serif", "monospace", "display", "handwriting"]),
74
+ variable: z.boolean(),
75
+ axes: z.record(z.string(), FontAxisSchema).optional(),
76
+ weights: z.array(z.number()),
77
+ subsets: z.array(z.string()),
78
+ moods: z.array(FontMoodSchema),
79
+ readabilityScore: z.number().min(0).max(1),
4121
80
  license: FontLicenseSchema,
4122
- popularityRank: external_exports.number().optional(),
4123
- pairingHints: external_exports.array(external_exports.string()).optional()
81
+ popularityRank: z.number().optional(),
82
+ pairingHints: z.array(z.string()).optional()
4124
83
  });
4125
- var FontFormatSchema = external_exports.enum(["woff2", "woff", "ttf", "otf", "variable"]);
4126
- var FontAssetSchema = external_exports.object({
4127
- family: external_exports.string(),
4128
- weight: external_exports.number().optional(),
4129
- style: external_exports.enum(["normal", "italic"]).default("normal"),
84
+ var FontFormatSchema = z.enum(["woff2", "woff", "ttf", "otf", "variable"]);
85
+ var FontAssetSchema = z.object({
86
+ family: z.string(),
87
+ weight: z.number().optional(),
88
+ style: z.enum(["normal", "italic"]).default("normal"),
4130
89
  format: FontFormatSchema,
4131
- url: external_exports.string(),
4132
- subset: external_exports.string().optional(),
4133
- unicodeRange: external_exports.string().optional(),
4134
- sizeBytes: external_exports.number().optional()
90
+ url: z.string(),
91
+ subset: z.string().optional(),
92
+ unicodeRange: z.string().optional(),
93
+ sizeBytes: z.number().optional()
4135
94
  });
4136
- var TypographyContextSchema = external_exports.enum([
95
+ var TypographyContextSchema = z2.enum([
4137
96
  "heading",
4138
97
  "subheading",
4139
98
  "body",
@@ -4147,40 +106,40 @@ var TypographyContextSchema = external_exports.enum([
4147
106
  "code",
4148
107
  "blockquote"
4149
108
  ]);
4150
- var TokenReferenceSchema = external_exports.string().regex(/^\{[A-Za-z0-9_.-]+\}$/);
4151
- var TypographyTokenSchema = external_exports.object({
4152
- fontFamily: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]),
4153
- fontSize: external_exports.string(),
4154
- fontWeight: external_exports.union([external_exports.number(), external_exports.string()]),
4155
- lineHeight: external_exports.union([external_exports.string(), external_exports.number()]),
4156
- letterSpacing: external_exports.string().optional(),
4157
- textTransform: external_exports.enum(["none", "uppercase", "lowercase", "capitalize"]).optional(),
4158
- textDecoration: external_exports.enum(["none", "underline", "line-through"]).optional()
109
+ var TokenReferenceSchema = z2.string().regex(/^\{[A-Za-z0-9_.-]+\}$/);
110
+ var TypographyTokenSchema = z2.object({
111
+ fontFamily: z2.union([z2.string(), z2.array(z2.string())]),
112
+ fontSize: z2.string(),
113
+ fontWeight: z2.union([z2.number(), z2.string()]),
114
+ lineHeight: z2.union([z2.string(), z2.number()]),
115
+ letterSpacing: z2.string().optional(),
116
+ textTransform: z2.enum(["none", "uppercase", "lowercase", "capitalize"]).optional(),
117
+ textDecoration: z2.enum(["none", "underline", "line-through"]).optional()
4159
118
  });
4160
- var ColorTokenSchema = external_exports.object({
4161
- value: external_exports.string(),
4162
- description: external_exports.string().optional()
119
+ var ColorTokenSchema = z2.object({
120
+ value: z2.string(),
121
+ description: z2.string().optional()
4163
122
  });
4164
- var ColorTokensSchema = external_exports.object({
4165
- text: external_exports.object({
123
+ var ColorTokensSchema = z2.object({
124
+ text: z2.object({
4166
125
  primary: ColorTokenSchema,
4167
126
  secondary: ColorTokenSchema,
4168
127
  muted: ColorTokenSchema,
4169
128
  accent: ColorTokenSchema,
4170
129
  inverse: ColorTokenSchema
4171
130
  }),
4172
- background: external_exports.object({
131
+ background: z2.object({
4173
132
  primary: ColorTokenSchema,
4174
133
  secondary: ColorTokenSchema,
4175
134
  accent: ColorTokenSchema,
4176
135
  muted: ColorTokenSchema
4177
136
  }),
4178
- border: external_exports.object({
137
+ border: z2.object({
4179
138
  default: ColorTokenSchema,
4180
139
  muted: ColorTokenSchema,
4181
140
  accent: ColorTokenSchema
4182
141
  }),
4183
- interactive: external_exports.object({
142
+ interactive: z2.object({
4184
143
  default: ColorTokenSchema,
4185
144
  hover: ColorTokenSchema,
4186
145
  active: ColorTokenSchema,
@@ -4188,34 +147,34 @@ var ColorTokensSchema = external_exports.object({
4188
147
  disabled: ColorTokenSchema
4189
148
  })
4190
149
  });
4191
- var SpacingTokensSchema = external_exports.object({
4192
- unit: external_exports.string(),
4193
- scale: external_exports.record(external_exports.string(), external_exports.string())
150
+ var SpacingTokensSchema = z2.object({
151
+ unit: z2.string(),
152
+ scale: z2.record(z2.string(), z2.string())
4194
153
  });
4195
- var LayoutTokensSchema = external_exports.object({
4196
- maxWidth: external_exports.object({
4197
- prose: external_exports.string(),
4198
- content: external_exports.string(),
4199
- wide: external_exports.string(),
4200
- full: external_exports.string()
154
+ var LayoutTokensSchema = z2.object({
155
+ maxWidth: z2.object({
156
+ prose: z2.string(),
157
+ content: z2.string(),
158
+ wide: z2.string(),
159
+ full: z2.string()
4201
160
  }),
4202
- breakpoints: external_exports.record(external_exports.string(), external_exports.string()),
4203
- grid: external_exports.object({
4204
- columns: external_exports.number(),
4205
- gap: external_exports.string()
161
+ breakpoints: z2.record(z2.string(), z2.string()),
162
+ grid: z2.object({
163
+ columns: z2.number(),
164
+ gap: z2.string()
4206
165
  }).optional()
4207
166
  });
4208
- var HeadingLevelSchema = external_exports.object({
4209
- fontSize: external_exports.string(),
4210
- fontWeight: external_exports.union([external_exports.number(), external_exports.string()]),
4211
- lineHeight: external_exports.union([external_exports.string(), external_exports.number()]),
4212
- letterSpacing: external_exports.string().optional(),
4213
- fontFamily: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional()
167
+ var HeadingLevelSchema = z2.object({
168
+ fontSize: z2.string(),
169
+ fontWeight: z2.union([z2.number(), z2.string()]),
170
+ lineHeight: z2.union([z2.string(), z2.number()]),
171
+ letterSpacing: z2.string().optional(),
172
+ fontFamily: z2.union([z2.string(), z2.array(z2.string())]).optional()
4214
173
  });
4215
- var HierarchyRulesSchema = external_exports.object({
4216
- scale: external_exports.enum(["minor-second", "major-second", "minor-third", "major-third", "perfect-fourth"]),
4217
- baseSize: external_exports.string(),
4218
- headings: external_exports.object({
174
+ var HierarchyRulesSchema = z2.object({
175
+ scale: z2.enum(["minor-second", "major-second", "minor-third", "major-third", "perfect-fourth"]),
176
+ baseSize: z2.string(),
177
+ headings: z2.object({
4219
178
  h1: HeadingLevelSchema,
4220
179
  h2: HeadingLevelSchema,
4221
180
  h3: HeadingLevelSchema,
@@ -4223,144 +182,144 @@ var HierarchyRulesSchema = external_exports.object({
4223
182
  h5: HeadingLevelSchema,
4224
183
  h6: HeadingLevelSchema
4225
184
  }),
4226
- emphasis: external_exports.object({
4227
- strong: external_exports.object({ fontWeight: external_exports.union([external_exports.number(), external_exports.string()]) }),
4228
- subtle: external_exports.object({ opacity: external_exports.number(), fontSize: external_exports.string().optional() })
185
+ emphasis: z2.object({
186
+ strong: z2.object({ fontWeight: z2.union([z2.number(), z2.string()]) }),
187
+ subtle: z2.object({ opacity: z2.number(), fontSize: z2.string().optional() })
4229
188
  })
4230
189
  });
4231
- var DesignTokenSetSchema = external_exports.object({
4232
- typography: external_exports.record(TypographyContextSchema, TypographyTokenSchema),
4233
- color: external_exports.object({
190
+ var DesignTokenSetSchema = z2.object({
191
+ typography: z2.record(TypographyContextSchema, TypographyTokenSchema),
192
+ color: z2.object({
4234
193
  light: ColorTokensSchema,
4235
194
  dark: ColorTokensSchema
4236
195
  }),
4237
196
  spacing: SpacingTokensSchema,
4238
197
  layout: LayoutTokensSchema,
4239
198
  hierarchy: HierarchyRulesSchema,
4240
- themes: external_exports.array(external_exports.lazy(() => ThemeModeSchema)).default([]),
4241
- modes: external_exports.record(external_exports.string(), external_exports.lazy(() => ModeOverrideSchema)).default({}),
199
+ themes: z2.array(z2.lazy(() => ThemeModeSchema)).default([]),
200
+ modes: z2.record(z2.string(), z2.lazy(() => ModeOverrideSchema)).default({}),
4242
201
  /** Optional: required font subsets for locale/script coverage validation. */
4243
- requiredSubsets: external_exports.array(external_exports.string()).optional(),
202
+ requiredSubsets: z2.array(z2.string()).optional(),
4244
203
  /** Optional: font-display strategy for font loading validation. */
4245
- fontDisplay: external_exports.enum(["auto", "block", "swap", "fallback", "optional"]).optional()
204
+ fontDisplay: z2.enum(["auto", "block", "swap", "fallback", "optional"]).optional()
4246
205
  });
4247
- var ModeOverrideSchema = external_exports.object({
4248
- name: external_exports.string(),
4249
- description: external_exports.string().optional(),
4250
- tokens: external_exports.record(external_exports.string(), external_exports.unknown()).default({})
206
+ var ModeOverrideSchema = z2.object({
207
+ name: z2.string(),
208
+ description: z2.string().optional(),
209
+ tokens: z2.record(z2.string(), z2.unknown()).default({})
4251
210
  });
4252
- var ThemeColorSchemeSchema = external_exports.enum(["light", "dark", "auto", "brand", "high-contrast"]);
4253
- var ThemeModeSchema = external_exports.object({
4254
- name: external_exports.string(),
211
+ var ThemeColorSchemeSchema = z2.enum(["light", "dark", "auto", "brand", "high-contrast"]);
212
+ var ThemeModeSchema = z2.object({
213
+ name: z2.string(),
4255
214
  colorScheme: ThemeColorSchemeSchema,
4256
- selector: external_exports.string().optional(),
4257
- tokens: external_exports.record(external_exports.string(), external_exports.unknown()).default({})
215
+ selector: z2.string().optional(),
216
+ tokens: z2.record(z2.string(), z2.unknown()).default({})
4258
217
  });
4259
- var SeveritySchema = external_exports.enum(["error", "warning", "info"]);
4260
- var DiagnosticSchema = external_exports.object({
4261
- rule: external_exports.string(),
218
+ var SeveritySchema = z3.enum(["error", "warning", "info"]);
219
+ var DiagnosticSchema = z3.object({
220
+ rule: z3.string(),
4262
221
  severity: SeveritySchema,
4263
- path: external_exports.string(),
4264
- message: external_exports.string(),
4265
- expected: external_exports.string().optional(),
4266
- actual: external_exports.string().optional()
222
+ path: z3.string(),
223
+ message: z3.string(),
224
+ expected: z3.string().optional(),
225
+ actual: z3.string().optional()
4267
226
  });
4268
- var ReferenceEvaluationSchema = external_exports.object({
4269
- referenceId: external_exports.string(),
4270
- referenceName: external_exports.string(),
4271
- score: external_exports.number(),
4272
- matched: external_exports.array(external_exports.string()),
4273
- mismatched: external_exports.array(external_exports.string()),
4274
- summary: external_exports.string().optional()
227
+ var ReferenceEvaluationSchema = z3.object({
228
+ referenceId: z3.string(),
229
+ referenceName: z3.string(),
230
+ score: z3.number(),
231
+ matched: z3.array(z3.string()),
232
+ mismatched: z3.array(z3.string()),
233
+ summary: z3.string().optional()
4275
234
  });
4276
- var ValidationReportSchema = external_exports.object({
4277
- diagnostics: external_exports.array(DiagnosticSchema),
4278
- references: external_exports.array(ReferenceEvaluationSchema).optional(),
4279
- counts: external_exports.object({
4280
- error: external_exports.number(),
4281
- warning: external_exports.number(),
4282
- info: external_exports.number()
235
+ var ValidationReportSchema = z3.object({
236
+ diagnostics: z3.array(DiagnosticSchema),
237
+ references: z3.array(ReferenceEvaluationSchema).optional(),
238
+ counts: z3.object({
239
+ error: z3.number(),
240
+ warning: z3.number(),
241
+ info: z3.number()
4283
242
  }),
4284
- pass: external_exports.boolean()
243
+ pass: z3.boolean()
4285
244
  });
4286
- var ExportFormatSchema = external_exports.enum(["css", "json", "tailwind", "shadcn", "w3c"]);
4287
- var RuleConfigSchema = external_exports.union([
245
+ var ExportFormatSchema = z4.enum(["css", "json", "tailwind", "shadcn", "w3c"]);
246
+ var RuleConfigSchema = z4.union([
4288
247
  SeveritySchema,
4289
248
  // Just set severity: "error" | "warning" | "info"
4290
- external_exports.literal(false),
249
+ z4.literal(false),
4291
250
  // Disable the rule
4292
- external_exports.object({
251
+ z4.object({
4293
252
  severity: SeveritySchema,
4294
- options: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
253
+ options: z4.record(z4.string(), z4.unknown()).optional()
4295
254
  })
4296
255
  ]);
4297
- var FetchTypeConfigSchema = external_exports.object({
256
+ var FetchTypeConfigSchema = z4.object({
4298
257
  // Extend a built-in profile or npm package config
4299
- extends: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional(),
258
+ extends: z4.union([z4.string(), z4.array(z4.string())]).optional(),
4300
259
  // Base preset to use (editorial, dashboard, etc.)
4301
- preset: external_exports.string().optional(),
260
+ preset: z4.string().optional(),
4302
261
  // Token file glob pattern(s)
4303
- tokens: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).default("tokens/**/*.json"),
262
+ tokens: z4.union([z4.string(), z4.array(z4.string())]).default("tokens/**/*.json"),
4304
263
  // Output directory
4305
- outDir: external_exports.string().default("dist/tokens"),
264
+ outDir: z4.string().default("dist/tokens"),
4306
265
  // Export formats to produce
4307
- exporters: external_exports.array(ExportFormatSchema).default(["css", "json"]),
266
+ exporters: z4.array(ExportFormatSchema).default(["css", "json"]),
4308
267
  // Theme settings
4309
- themes: external_exports.object({
4310
- default: external_exports.string().default("light")
268
+ themes: z4.object({
269
+ default: z4.string().default("light")
4311
270
  }).default({}),
4312
271
  // Validation rule configuration
4313
- rules: external_exports.record(external_exports.string(), RuleConfigSchema).default({}),
272
+ rules: z4.record(z4.string(), RuleConfigSchema).default({}),
4314
273
  // Font policy
4315
- fonts: external_exports.object({
4316
- allow: external_exports.array(external_exports.string()).optional(),
274
+ fonts: z4.object({
275
+ allow: z4.array(z4.string()).optional(),
4317
276
  // Only these fonts allowed
4318
- block: external_exports.array(
4319
- external_exports.union([
4320
- external_exports.string(),
4321
- external_exports.object({ family: external_exports.string(), reason: external_exports.string() })
277
+ block: z4.array(
278
+ z4.union([
279
+ z4.string(),
280
+ z4.object({ family: z4.string(), reason: z4.string() })
4322
281
  ])
4323
282
  ).optional(),
4324
283
  // These fonts blocked with reasons
4325
- googleFontsApiKey: external_exports.string().optional(),
4326
- cacheDir: external_exports.string().default(".fetchtype/fonts")
284
+ googleFontsApiKey: z4.string().optional(),
285
+ cacheDir: z4.string().default(".fetchtype/fonts")
4327
286
  }).default({}),
4328
287
  // Performance budgets
4329
- performance: external_exports.object({
4330
- maxFontPayloadKb: external_exports.number().optional(),
4331
- maxFontCount: external_exports.number().optional(),
4332
- maxPreloadCount: external_exports.number().optional()
288
+ performance: z4.object({
289
+ maxFontPayloadKb: z4.number().optional(),
290
+ maxFontCount: z4.number().optional(),
291
+ maxPreloadCount: z4.number().optional()
4333
292
  }).default({}),
4334
293
  // Required subsets for locale coverage
4335
- requiredSubsets: external_exports.array(external_exports.string()).optional(),
294
+ requiredSubsets: z4.array(z4.string()).optional(),
4336
295
  // Plugin packages (future)
4337
- plugins: external_exports.array(external_exports.string()).default([])
296
+ plugins: z4.array(z4.string()).default([])
4338
297
  });
4339
- var AgentNextActionSchema = external_exports.object({
4340
- tool: external_exports.string(),
4341
- description: external_exports.string(),
4342
- suggestedArgs: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
298
+ var AgentNextActionSchema = z5.object({
299
+ tool: z5.string(),
300
+ description: z5.string(),
301
+ suggestedArgs: z5.record(z5.string(), z5.unknown()).optional()
4343
302
  });
4344
- var AgentDecisionSchema = external_exports.object({
4345
- decision: external_exports.string(),
4346
- confidence: external_exports.number().min(0).max(1),
4347
- alternatives: external_exports.array(
4348
- external_exports.object({
4349
- option: external_exports.string(),
4350
- tradeoff: external_exports.string()
303
+ var AgentDecisionSchema = z5.object({
304
+ decision: z5.string(),
305
+ confidence: z5.number().min(0).max(1),
306
+ alternatives: z5.array(
307
+ z5.object({
308
+ option: z5.string(),
309
+ tradeoff: z5.string()
4351
310
  })
4352
311
  ).default([]),
4353
- constraints: external_exports.array(external_exports.string()).default([]),
4354
- nextActions: external_exports.array(AgentNextActionSchema).default([])
312
+ constraints: z5.array(z5.string()).default([]),
313
+ nextActions: z5.array(AgentNextActionSchema).default([])
4355
314
  });
4356
- var RenderingTargetSchema = external_exports.enum([
315
+ var RenderingTargetSchema = z6.enum([
4357
316
  "apple",
4358
317
  "windows",
4359
318
  "android",
4360
319
  "linux",
4361
320
  "universal"
4362
321
  ]);
4363
- var TypographicContextSchema = external_exports.enum([
322
+ var TypographicContextSchema = z6.enum([
4364
323
  "display",
4365
324
  "interface",
4366
325
  "reading",
@@ -4368,101 +327,101 @@ var TypographicContextSchema = external_exports.enum([
4368
327
  "editorial",
4369
328
  "data"
4370
329
  ]);
4371
- var RegistryVariableAxisSchema = external_exports.object({
4372
- tag: external_exports.string(),
4373
- name: external_exports.string(),
4374
- min: external_exports.number(),
4375
- max: external_exports.number(),
4376
- default: external_exports.number(),
4377
- step: external_exports.number(),
4378
- cssProperty: external_exports.string().nullable()
330
+ var RegistryVariableAxisSchema = z6.object({
331
+ tag: z6.string(),
332
+ name: z6.string(),
333
+ min: z6.number(),
334
+ max: z6.number(),
335
+ default: z6.number(),
336
+ step: z6.number(),
337
+ cssProperty: z6.string().nullable()
4379
338
  });
4380
- var FallbackOverridesSchema = external_exports.object({
4381
- ascentOverride: external_exports.string(),
4382
- descentOverride: external_exports.string(),
4383
- lineGapOverride: external_exports.string(),
4384
- sizeAdjust: external_exports.string()
339
+ var FallbackOverridesSchema = z6.object({
340
+ ascentOverride: z6.string(),
341
+ descentOverride: z6.string(),
342
+ lineGapOverride: z6.string(),
343
+ sizeAdjust: z6.string()
4385
344
  });
4386
- var FallbackTargetSchema = external_exports.object({
345
+ var FallbackTargetSchema = z6.object({
4387
346
  target: RenderingTargetSchema,
4388
- fallbackFont: external_exports.string(),
4389
- localNames: external_exports.array(external_exports.string()),
347
+ fallbackFont: z6.string(),
348
+ localNames: z6.array(z6.string()),
4390
349
  overrides: FallbackOverridesSchema
4391
350
  });
4392
- var PairingRoleSchema = external_exports.enum(["heading", "body", "accent", "mono"]);
4393
- var PairingRecommendationSchema = external_exports.object({
4394
- fontId: external_exports.string(),
351
+ var PairingRoleSchema = z6.enum(["heading", "body", "accent", "mono"]);
352
+ var PairingRecommendationSchema = z6.object({
353
+ fontId: z6.string(),
4395
354
  role: PairingRoleSchema,
4396
- confidence: external_exports.number().min(0).max(1),
4397
- rationale: external_exports.string(),
4398
- source: external_exports.enum(["curated", "algorithmic"]).optional()
355
+ confidence: z6.number().min(0).max(1),
356
+ rationale: z6.string(),
357
+ source: z6.enum(["curated", "algorithmic"]).optional()
4399
358
  });
4400
- var SystemFontInfoSchema = external_exports.object({
4401
- platforms: external_exports.array(RenderingTargetSchema),
4402
- localNames: external_exports.array(external_exports.string()),
4403
- cssKeywords: external_exports.array(external_exports.string()),
4404
- note: external_exports.string().nullable()
359
+ var SystemFontInfoSchema = z6.object({
360
+ platforms: z6.array(RenderingTargetSchema),
361
+ localNames: z6.array(z6.string()),
362
+ cssKeywords: z6.array(z6.string()),
363
+ note: z6.string().nullable()
4405
364
  });
4406
- var FontPerformanceSchema = external_exports.object({
4407
- woff2Size: external_exports.record(external_exports.string(), external_exports.number()),
4408
- variableFileSize: external_exports.number().nullable(),
4409
- estimatedPayload: external_exports.number(),
4410
- loadingImpact: external_exports.enum(["minimal", "moderate", "heavy"])
365
+ var FontPerformanceSchema = z6.object({
366
+ woff2Size: z6.record(z6.string(), z6.number()),
367
+ variableFileSize: z6.number().nullable(),
368
+ estimatedPayload: z6.number(),
369
+ loadingImpact: z6.enum(["minimal", "moderate", "heavy"])
4411
370
  });
4412
- var FontMetricsSchema = external_exports.object({
4413
- unitsPerEm: external_exports.number(),
4414
- ascent: external_exports.number(),
4415
- descent: external_exports.number(),
4416
- lineGap: external_exports.number(),
4417
- xHeight: external_exports.number().nullable(),
4418
- capHeight: external_exports.number().nullable(),
4419
- useTypoMetrics: external_exports.boolean(),
4420
- hheaAscent: external_exports.number().nullable(),
4421
- hheaDescent: external_exports.number().nullable(),
4422
- winAscent: external_exports.number().nullable(),
4423
- winDescent: external_exports.number().nullable()
371
+ var FontMetricsSchema = z6.object({
372
+ unitsPerEm: z6.number(),
373
+ ascent: z6.number(),
374
+ descent: z6.number(),
375
+ lineGap: z6.number(),
376
+ xHeight: z6.number().nullable(),
377
+ capHeight: z6.number().nullable(),
378
+ useTypoMetrics: z6.boolean(),
379
+ hheaAscent: z6.number().nullable(),
380
+ hheaDescent: z6.number().nullable(),
381
+ winAscent: z6.number().nullable(),
382
+ winDescent: z6.number().nullable()
4424
383
  });
4425
- var FontFallbackSchema = external_exports.object({
4426
- targets: external_exports.array(FallbackTargetSchema),
4427
- requiresPlatformSplit: external_exports.boolean(),
4428
- generatedCSS: external_exports.string()
384
+ var FontFallbackSchema = z6.object({
385
+ targets: z6.array(FallbackTargetSchema),
386
+ requiresPlatformSplit: z6.boolean(),
387
+ generatedCSS: z6.string()
4429
388
  });
4430
- var FontPairingIntelligenceSchema = external_exports.object({
4431
- recommended: external_exports.array(PairingRecommendationSchema)
389
+ var FontPairingIntelligenceSchema = z6.object({
390
+ recommended: z6.array(PairingRecommendationSchema)
4432
391
  });
4433
- var RegistryLicenseSchema = external_exports.object({
4434
- type: external_exports.string(),
4435
- url: external_exports.string(),
4436
- commercial: external_exports.boolean(),
4437
- selfHostable: external_exports.boolean(),
4438
- attribution: external_exports.string().nullable()
392
+ var RegistryLicenseSchema = z6.object({
393
+ type: z6.string(),
394
+ url: z6.string(),
395
+ commercial: z6.boolean(),
396
+ selfHostable: z6.boolean(),
397
+ attribution: z6.string().nullable()
4439
398
  });
4440
- var FontInstallSchema = external_exports.object({
4441
- fontsource: external_exports.string().nullable(),
4442
- googleCdn: external_exports.string().nullable(),
4443
- npmPackage: external_exports.string().nullable(),
399
+ var FontInstallSchema = z6.object({
400
+ fontsource: z6.string().nullable(),
401
+ googleCdn: z6.string().nullable(),
402
+ npmPackage: z6.string().nullable(),
4444
403
  system: SystemFontInfoSchema.nullable()
4445
404
  });
4446
- var FontEntrySchema = external_exports.object({
405
+ var FontEntrySchema = z6.object({
4447
406
  // Identity
4448
- id: external_exports.string(),
4449
- family: external_exports.string(),
4450
- version: external_exports.string(),
4451
- source: external_exports.enum(["google", "fontsource", "system", "community"]),
4452
- lastUpdated: external_exports.string(),
407
+ id: z6.string(),
408
+ family: z6.string(),
409
+ version: z6.string(),
410
+ source: z6.enum(["google", "fontsource", "system", "community"]),
411
+ lastUpdated: z6.string(),
4453
412
  // Classification
4454
- category: external_exports.enum(["sans-serif", "serif", "monospace", "display", "handwriting"]),
4455
- tags: external_exports.array(external_exports.string()),
4456
- contexts: external_exports.array(TypographicContextSchema),
413
+ category: z6.enum(["sans-serif", "serif", "monospace", "display", "handwriting"]),
414
+ tags: z6.array(z6.string()),
415
+ contexts: z6.array(TypographicContextSchema),
4457
416
  // Technical
4458
- variable: external_exports.boolean(),
4459
- axes: external_exports.array(RegistryVariableAxisSchema),
4460
- weights: external_exports.array(external_exports.number()),
4461
- styles: external_exports.array(external_exports.enum(["normal", "italic"])),
4462
- subsets: external_exports.array(external_exports.string()),
4463
- formats: external_exports.array(external_exports.enum(["woff2", "woff", "ttf", "otf"])),
4464
- hasItalic: external_exports.boolean(),
4465
- hasOpticalSizing: external_exports.boolean(),
417
+ variable: z6.boolean(),
418
+ axes: z6.array(RegistryVariableAxisSchema),
419
+ weights: z6.array(z6.number()),
420
+ styles: z6.array(z6.enum(["normal", "italic"])),
421
+ subsets: z6.array(z6.string()),
422
+ formats: z6.array(z6.enum(["woff2", "woff", "ttf", "otf"])),
423
+ hasItalic: z6.boolean(),
424
+ hasOpticalSizing: z6.boolean(),
4466
425
  // Performance (enriched)
4467
426
  performance: FontPerformanceSchema,
4468
427
  // Rendering (enriched)
@@ -4476,23 +435,23 @@ var FontEntrySchema = external_exports.object({
4476
435
  // Deployment
4477
436
  install: FontInstallSchema,
4478
437
  // Context Intelligence (enriched)
4479
- contextScores: external_exports.record(external_exports.string(), external_exports.number()).optional(),
438
+ contextScores: z6.record(z6.string(), z6.number()).optional(),
4480
439
  // Size Guidance (enriched)
4481
- sizeGuidance: external_exports.object({
4482
- body: external_exports.object({ min: external_exports.number(), optimal: external_exports.number(), max: external_exports.number() }),
4483
- display: external_exports.object({ min: external_exports.number() }),
4484
- caption: external_exports.object({ min: external_exports.number() }),
4485
- opticalSizeMapping: external_exports.array(external_exports.object({
4486
- cssSize: external_exports.number(),
4487
- opszValue: external_exports.number()
440
+ sizeGuidance: z6.object({
441
+ body: z6.object({ min: z6.number(), optimal: z6.number(), max: z6.number() }),
442
+ display: z6.object({ min: z6.number() }),
443
+ caption: z6.object({ min: z6.number() }),
444
+ opticalSizeMapping: z6.array(z6.object({
445
+ cssSize: z6.number(),
446
+ opszValue: z6.number()
4488
447
  })).nullable()
4489
448
  }).optional()
4490
449
  });
4491
- var FontRegistrySchema = external_exports.object({
4492
- version: external_exports.string(),
4493
- generatedAt: external_exports.string(),
4494
- count: external_exports.number(),
4495
- fonts: external_exports.array(FontEntrySchema)
450
+ var FontRegistrySchema = z6.object({
451
+ version: z6.string(),
452
+ generatedAt: z6.string(),
453
+ count: z6.number(),
454
+ fonts: z6.array(FontEntrySchema)
4496
455
  });
4497
456
 
4498
457
  // ../fonts/dist/index.js
@@ -12705,6 +8664,44 @@ function validateFonts(tokenSet, config) {
12705
8664
  )
12706
8665
  );
12707
8666
  }
8667
+ for (const { path, fontFamily } of fontFamilySources) {
8668
+ const families = Array.isArray(fontFamily) ? fontFamily : [fontFamily];
8669
+ const primary = families[0];
8670
+ if (!primary || TOKEN_REFERENCE_PATTERN.test(primary)) continue;
8671
+ const resolved = resolveFont(primary);
8672
+ if (!resolved) continue;
8673
+ const targets = resolved.fallback?.targets;
8674
+ if (!targets || targets.length === 0) continue;
8675
+ for (const t of targets) {
8676
+ const sizeAdj = parseFloat(t.overrides.sizeAdjust);
8677
+ if (isNaN(sizeAdj)) continue;
8678
+ const drift = Math.abs(sizeAdj - 100);
8679
+ if (drift >= 8) {
8680
+ pushDiagnosticWithConfig(
8681
+ diagnostics,
8682
+ config,
8683
+ "font.platform-rendering",
8684
+ "warning",
8685
+ path,
8686
+ `"${primary}" has ${drift.toFixed(1)}% metric drift on ${t.target} (fallback: ${t.fallbackFont}). Users on this platform will see a noticeable layout shift when the web font loads. Consider testing or providing a tighter fallback.`,
8687
+ "<= 5% size-adjust drift",
8688
+ `${drift.toFixed(1)}% on ${t.target}`
8689
+ );
8690
+ }
8691
+ }
8692
+ if (resolved.fallback?.requiresPlatformSplit) {
8693
+ pushDiagnosticWithConfig(
8694
+ diagnostics,
8695
+ config,
8696
+ "font.platform-rendering",
8697
+ "info",
8698
+ path,
8699
+ `"${primary}" requires platform-specific fallback CSS for optimal rendering. Use \`fetchtype resolve ${primary.toLowerCase().replace(/ /g, "-")} --css\` to generate per-platform @font-face rules.`,
8700
+ "Single fallback",
8701
+ "Platform split required"
8702
+ );
8703
+ }
8704
+ }
12708
8705
  if (config?.fonts?.allow && config.fonts.allow.length > 0) {
12709
8706
  const allowSet = new Set(config.fonts.allow.map((f) => f.toLowerCase()));
12710
8707
  const allowlistSeverity = getRuleSeverity("policy.font-allowlist", config);
@@ -12774,6 +8771,7 @@ function validateFonts(tokenSet, config) {
12774
8771
  // src/mcp.ts
12775
8772
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12776
8773
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8774
+ import { z as z7 } from "zod";
12777
8775
 
12778
8776
  // src/prompt-init.ts
12779
8777
  var PRESET_PATTERNS = [
@@ -13198,8 +9196,8 @@ function createMcpServer() {
13198
9196
  "fetchtype_validate",
13199
9197
  "Validate a design token set against fetchtype rules",
13200
9198
  {
13201
- tokens: external_exports.unknown(),
13202
- referenceSystems: external_exports.array(external_exports.string()).optional()
9199
+ tokens: z7.unknown(),
9200
+ referenceSystems: z7.array(z7.string()).optional()
13203
9201
  },
13204
9202
  async (args) => {
13205
9203
  const tokens = args.tokens;
@@ -13228,8 +9226,8 @@ function createMcpServer() {
13228
9226
  "fetchtype_build",
13229
9227
  "Build artifacts (CSS, JSON, Tailwind, shadcn) from a design token set",
13230
9228
  {
13231
- tokens: external_exports.unknown(),
13232
- format: external_exports.enum(["css", "json", "tailwind", "shadcn"]).optional()
9229
+ tokens: z7.unknown(),
9230
+ format: z7.enum(["css", "json", "tailwind", "shadcn"]).optional()
13233
9231
  },
13234
9232
  async (args) => {
13235
9233
  const tokens = args.tokens;
@@ -13277,10 +9275,10 @@ function createMcpServer() {
13277
9275
  "fetchtype_suggest",
13278
9276
  "Suggest fonts for a given usage context",
13279
9277
  {
13280
- context: external_exports.enum(["display", "interface", "reading", "mono"]),
13281
- limit: external_exports.number().optional(),
13282
- referenceSystem: external_exports.string().optional(),
13283
- variableOnly: external_exports.boolean().optional()
9278
+ context: z7.enum(["display", "interface", "reading", "mono"]),
9279
+ limit: z7.number().optional(),
9280
+ referenceSystem: z7.string().optional(),
9281
+ variableOnly: z7.boolean().optional()
13284
9282
  },
13285
9283
  async (args) => {
13286
9284
  const context = args.context;
@@ -13323,7 +9321,7 @@ function createMcpServer() {
13323
9321
  server,
13324
9322
  "fetchtype_init",
13325
9323
  "Get a starter token set, optionally from a named preset",
13326
- { preset: external_exports.string().optional(), prompt: external_exports.string().optional() },
9324
+ { preset: z7.string().optional(), prompt: z7.string().optional() },
13327
9325
  async (args) => {
13328
9326
  const preset = typeof args.preset === "string" ? args.preset : void 0;
13329
9327
  const prompt = typeof args.prompt === "string" ? args.prompt : void 0;
@@ -13400,11 +9398,11 @@ function createMcpServer() {
13400
9398
  "fetchtype_systems",
13401
9399
  "Query curated typography systems, associated keywords, and extracted cross-system patterns",
13402
9400
  {
13403
- query: external_exports.string().optional(),
13404
- useCase: external_exports.string().optional(),
13405
- style: external_exports.string().optional(),
13406
- kind: external_exports.enum(["all", "official-design-system", "foundational-archetype"]).optional(),
13407
- includePatterns: external_exports.boolean().optional()
9401
+ query: z7.string().optional(),
9402
+ useCase: z7.string().optional(),
9403
+ style: z7.string().optional(),
9404
+ kind: z7.enum(["all", "official-design-system", "foundational-archetype"]).optional(),
9405
+ includePatterns: z7.boolean().optional()
13408
9406
  },
13409
9407
  async (args) => {
13410
9408
  const query = typeof args.query === "string" ? args.query : void 0;
@@ -13438,7 +9436,7 @@ function createMcpServer() {
13438
9436
  "fetchtype_resolve",
13439
9437
  "Resolve a font from the registry. Returns full metadata including install paths, metrics, and classification.",
13440
9438
  {
13441
- font: external_exports.string().describe('Font family name or ID (e.g. "inter", "Roboto")')
9439
+ font: z7.string().describe('Font family name or ID (e.g. "inter", "Roboto")')
13442
9440
  },
13443
9441
  async (args) => {
13444
9442
  const font = typeof args.font === "string" ? args.font : "";
@@ -13454,9 +9452,9 @@ function createMcpServer() {
13454
9452
  "fetchtype_pair",
13455
9453
  "Get font pairing recommendations. Returns curated and algorithmic pairings with confidence scores.",
13456
9454
  {
13457
- font: external_exports.string().describe("Font family name or ID to get pairings for"),
13458
- role: external_exports.enum(["heading", "body", "accent", "mono"]).optional().describe("Filter by pairing role"),
13459
- limit: external_exports.number().optional().describe("Max number of recommendations (default: 5)")
9455
+ font: z7.string().describe("Font family name or ID to get pairings for"),
9456
+ role: z7.enum(["heading", "body", "accent", "mono"]).optional().describe("Filter by pairing role"),
9457
+ limit: z7.number().optional().describe("Max number of recommendations (default: 5)")
13460
9458
  },
13461
9459
  async (args) => {
13462
9460
  const font = typeof args.font === "string" ? args.font : "";
@@ -13497,9 +9495,9 @@ function createMcpServer() {
13497
9495
  "fetchtype_fallback",
13498
9496
  "Generate platform-aware fallback CSS with metric overrides for CLS-free font loading across Windows, Apple, Android, Linux.",
13499
9497
  {
13500
- font: external_exports.string().describe("Font family name or ID"),
13501
- compact: external_exports.boolean().optional().describe("Use single @font-face instead of per-platform (less precise, smaller CSS)"),
13502
- safariWrap: external_exports.boolean().optional().describe("Wrap in @supports to exclude Safari (default: true)")
9498
+ font: z7.string().describe("Font family name or ID"),
9499
+ compact: z7.boolean().optional().describe("Use single @font-face instead of per-platform (less precise, smaller CSS)"),
9500
+ safariWrap: z7.boolean().optional().describe("Wrap in @supports to exclude Safari (default: true)")
13503
9501
  },
13504
9502
  async (args) => {
13505
9503
  const font = typeof args.font === "string" ? args.font : "";
@@ -13518,14 +9516,14 @@ function createMcpServer() {
13518
9516
  "fetchtype_prepare",
13519
9517
  "Download and optimize a font for production use. Generates WOFF2 files, @font-face CSS, fallback CSS, preload tags, and manifest.",
13520
9518
  {
13521
- fontId: external_exports.string().describe('Font ID from registry (e.g. "inter", "roboto")'),
13522
- weights: external_exports.array(external_exports.number()).optional().describe("Weights to include (default: [400, 500, 700])"),
13523
- subsets: external_exports.array(external_exports.string()).optional().describe('Subsets (default: ["latin"])'),
13524
- outputDir: external_exports.string().optional().describe('Output directory (default: "./dist/fonts")'),
13525
- fontDisplay: external_exports.enum(["swap", "block", "fallback", "optional", "auto"]).optional().describe("font-display strategy (default: swap)"),
13526
- generateFallbacks: external_exports.boolean().optional().describe("Generate fallback CSS (default: true)"),
13527
- performanceBudget: external_exports.number().optional().describe("Budget in bytes (default: 150000)"),
13528
- tokenFile: external_exports.string().optional().describe("Token file to update with font reference")
9519
+ fontId: z7.string().describe('Font ID from registry (e.g. "inter", "roboto")'),
9520
+ weights: z7.array(z7.number()).optional().describe("Weights to include (default: [400, 500, 700])"),
9521
+ subsets: z7.array(z7.string()).optional().describe('Subsets (default: ["latin"])'),
9522
+ outputDir: z7.string().optional().describe('Output directory (default: "./dist/fonts")'),
9523
+ fontDisplay: z7.enum(["swap", "block", "fallback", "optional", "auto"]).optional().describe("font-display strategy (default: swap)"),
9524
+ generateFallbacks: z7.boolean().optional().describe("Generate fallback CSS (default: true)"),
9525
+ performanceBudget: z7.number().optional().describe("Budget in bytes (default: 150000)"),
9526
+ tokenFile: z7.string().optional().describe("Token file to update with font reference")
13529
9527
  },
13530
9528
  async (args) => {
13531
9529
  const fontId = typeof args.fontId === "string" ? args.fontId : "";
@@ -13592,13 +9590,13 @@ function createMcpServer() {
13592
9590
  "fetchtype_search",
13593
9591
  "Search the font registry with free-text and filters. Returns matching fonts with metadata.",
13594
9592
  {
13595
- query: external_exports.string().optional().describe("Free-text search (matches family name, tags, category)"),
13596
- context: external_exports.enum(["display", "interface", "reading", "mono", "editorial", "data"]).optional(),
13597
- category: external_exports.enum(["sans-serif", "serif", "monospace", "display", "handwriting"]).optional(),
13598
- variable: external_exports.boolean().optional().describe("Only variable fonts"),
13599
- subset: external_exports.string().optional().describe('Filter by subset support (e.g. "cyrillic")'),
13600
- maxPayload: external_exports.number().optional().describe("Maximum estimated payload in bytes"),
13601
- limit: external_exports.number().optional().describe("Max results (default: 20)")
9593
+ query: z7.string().optional().describe("Free-text search (matches family name, tags, category)"),
9594
+ context: z7.enum(["display", "interface", "reading", "mono", "editorial", "data"]).optional(),
9595
+ category: z7.enum(["sans-serif", "serif", "monospace", "display", "handwriting"]).optional(),
9596
+ variable: z7.boolean().optional().describe("Only variable fonts"),
9597
+ subset: z7.string().optional().describe('Filter by subset support (e.g. "cyrillic")'),
9598
+ maxPayload: z7.number().optional().describe("Maximum estimated payload in bytes"),
9599
+ limit: z7.number().optional().describe("Max results (default: 20)")
13602
9600
  },
13603
9601
  async (args) => {
13604
9602
  const results = searchRegistry({
@@ -13634,9 +9632,9 @@ function createMcpServer() {
13634
9632
  "fetchtype_audit",
13635
9633
  "Audit a directory or file content for typography issues. Use to self-audit generated code.",
13636
9634
  {
13637
- dir: external_exports.string().optional().describe("Directory path to audit"),
13638
- content: external_exports.string().optional().describe("CSS/HTML content to audit inline (for self-audit)"),
13639
- format: external_exports.enum(["json", "summary"]).optional().describe("Output format (default: summary)")
9635
+ dir: z7.string().optional().describe("Directory path to audit"),
9636
+ content: z7.string().optional().describe("CSS/HTML content to audit inline (for self-audit)"),
9637
+ format: z7.enum(["json", "summary"]).optional().describe("Output format (default: summary)")
13640
9638
  },
13641
9639
  async (args) => {
13642
9640
  const dir = typeof args.dir === "string" ? args.dir : void 0;
@@ -13689,7 +9687,7 @@ Self-audit complete: ${errorCount} error${errorCount !== 1 ? "s" : ""}, ${warnCo
13689
9687
  "fetchtype_workflow",
13690
9688
  "Plan a complete typography workflow. Returns ordered sequence of fetchtype tools to call.",
13691
9689
  {
13692
- goal: external_exports.string().describe(
9690
+ goal: z7.string().describe(
13693
9691
  'What you want to achieve, e.g., "set up typography for a SaaS dashboard"'
13694
9692
  )
13695
9693
  },
@@ -13762,9 +9760,9 @@ Self-audit complete: ${errorCount} error${errorCount !== 1 ? "s" : ""}, ${warnCo
13762
9760
  "fetchtype_generate",
13763
9761
  "Generate a complete, validated token set from context and constraints. One call, one output.",
13764
9762
  {
13765
- context: external_exports.string().describe("Target context: saas-dashboard, editorial, ecommerce, docs, marketing"),
13766
- brandColor: external_exports.string().optional().describe("Primary brand color hex, e.g., #2563eb"),
13767
- preset: external_exports.string().optional().describe("Explicit preset name to use as base")
9763
+ context: z7.string().describe("Target context: saas-dashboard, editorial, ecommerce, docs, marketing"),
9764
+ brandColor: z7.string().optional().describe("Primary brand color hex, e.g., #2563eb"),
9765
+ preset: z7.string().optional().describe("Explicit preset name to use as base")
13768
9766
  },
13769
9767
  ({ context, brandColor, preset }) => {
13770
9768
  const result = generateTokenSet({
@@ -13778,7 +9776,10 @@ Self-audit complete: ${errorCount} error${errorCount !== 1 ? "s" : ""}, ${warnCo
13778
9776
  confidence: result.warnings.length === 0 ? 0.95 : 0.7,
13779
9777
  alternatives: [],
13780
9778
  constraints: result.warnings,
13781
- nextActions: [{ tool: "fetchtype_validate", description: "Validate the generated token set" }]
9779
+ nextActions: [
9780
+ { tool: "fetchtype_validate", description: "Validate the generated token set" },
9781
+ { tool: "save_as_preset", description: 'Save as fetchtype.tokens.json in the project root. To make it a reusable team preset, publish as an npm package and reference via "extends" in .fetchtype.json.' }
9782
+ ]
13782
9783
  })
13783
9784
  );
13784
9785
  }
@@ -14905,4 +10906,4 @@ export {
14905
10906
  createProgram,
14906
10907
  runCli
14907
10908
  };
14908
- //# sourceMappingURL=chunk-EFWDDTTC.js.map
10909
+ //# sourceMappingURL=chunk-RDDRPHH6.js.map