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