@powerformer/refly-cli 0.1.0

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