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