@flowriki/agent 0.1.0-beta.11 → 0.1.0-beta.12

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.
@@ -6,7 +6,7 @@ import os from "os";
6
6
  import path from "path";
7
7
  import { createRequire } from "module";
8
8
  import { spawnSync } from "child_process";
9
- var AGENT_VERSION = "0.1.0-beta.11";
9
+ var AGENT_VERSION = "0.1.0-beta.12";
10
10
  async function prepareBrowsers() {
11
11
  if (browsersReady()) {
12
12
  return { ok: true, already: true, message: "chromium is already installed" };
@@ -970,6 +970,60 @@ var SuiteSchema = z22.object({
970
970
  function caseOccurrences(testCase) {
971
971
  return testCase.occurrences.map((item, index) => index === 0 && testCase.useStartPath && !item.navigateFirst ? { ...item, startPath: testCase.startPath, ...testCase.baseUrl ? { baseUrl: testCase.baseUrl } : {} } : item);
972
972
  }
973
+ function caseDebugPlan(testCase, baseUrl) {
974
+ const owners = {};
975
+ const steps = [];
976
+ const occurrences = caseOccurrences(testCase);
977
+ for (const [index, item] of occurrences.entries()) {
978
+ if (index > 0 && item.navigateFirst) {
979
+ const id = `case-nav:${encodeURIComponent(item.occurrenceId)}`;
980
+ owners[id] = { occurrenceId: item.occurrenceId, stepId: null };
981
+ steps.push({ id, type: "navigate", role: "", name: `Go to ${item.name}`, scope: "", value: new URL(item.startPath ?? "/", item.baseUrl ?? testCase.baseUrl ?? baseUrl).href, secret: false, legacySelector: "", proposals: [] });
982
+ }
983
+ for (const step of item.steps) {
984
+ const id = `case-step:${encodeURIComponent(item.occurrenceId)}:${encodeURIComponent(step.id)}`;
985
+ owners[id] = { occurrenceId: item.occurrenceId, stepId: step.id };
986
+ steps.push({ ...step, id });
987
+ }
988
+ }
989
+ const first = occurrences[0];
990
+ const flow = FlowDocumentSchema.parse({
991
+ schemaVersion: 5,
992
+ id: testCase.id,
993
+ featureId: testCase.folderId,
994
+ slug: testCase.slug,
995
+ name: testCase.name,
996
+ revision: testCase.revision,
997
+ recordedAt: testCase.createdAt,
998
+ recordedBy: testCase.createdBy,
999
+ updatedAt: testCase.updatedAt,
1000
+ steps,
1001
+ startPath: new URL(first?.startPath ?? "/", first?.baseUrl ?? testCase.baseUrl ?? baseUrl).href,
1002
+ ...testCase.environment ? { environment: testCase.environment } : {}
1003
+ });
1004
+ return { flow, owners };
1005
+ }
1006
+ function restoreDebugCase(testCase, owners, steps) {
1007
+ const occurrences = testCase.occurrences.map((item) => ({ ...item, steps: [] }));
1008
+ const byId = new Map(occurrences.map((item) => [item.occurrenceId, item]));
1009
+ let current = occurrences[0];
1010
+ const present = new Set(steps.map((step) => step.id));
1011
+ for (const [id, owner] of Object.entries(owners)) {
1012
+ if (owner.stepId === null && !present.has(id)) byId.get(owner.occurrenceId).navigateFirst = false;
1013
+ }
1014
+ for (const step of steps) {
1015
+ const owner = owners[step.id];
1016
+ if (owner) current = byId.get(owner.occurrenceId);
1017
+ if (!current) throw new Error("debug step has no case occurrence");
1018
+ if (owner?.stepId === null) {
1019
+ if (step.type !== "navigate") throw new Error("a case boundary must remain a navigation step");
1020
+ current.startPath = step.value;
1021
+ continue;
1022
+ }
1023
+ current.steps.push({ ...step, id: owner?.stepId ?? step.id });
1024
+ }
1025
+ return { ...testCase, occurrences };
1026
+ }
973
1027
 
974
1028
  // ../recorder/dist/index.js
975
1029
  function openShadowRoots() {
@@ -6515,6 +6569,20 @@ var RecordingCoordinator = class {
6515
6569
  starting = null;
6516
6570
  draft = null;
6517
6571
  stopInFlight = null;
6572
+ /** The last completed stop, kept so a caller that missed the answer can ask
6573
+ * again.
6574
+ *
6575
+ * IN MEMORY AND NEVER ON THE EVENT STREAM. The recording.stopped event is
6576
+ * journalled and replayed to the browser, and this result carries the
6577
+ * passwords the recording captured — so recovery reads it from here rather
6578
+ * than rebuilding it from the event, which would either lose the values or
6579
+ * publish them. */
6580
+ lastResult = null;
6581
+ /** What the last completed stop answered, for a caller that missed it —
6582
+ * a dropped socket, or a Stop pressed inside the recorded page. */
6583
+ lastStop() {
6584
+ return this.lastResult;
6585
+ }
6518
6586
  active() {
6519
6587
  if (!this.session || !this.draft) return null;
6520
6588
  return { sessionId: this.draft.name, steps: this.draft.steps.length };
@@ -6667,7 +6735,13 @@ var RecordingCoordinator = class {
6667
6735
  this.draft = null;
6668
6736
  return { ok: false, error: "the feature this recording belongs to is gone" };
6669
6737
  }
6738
+ const before = this.deps.store.readSecrets();
6670
6739
  this.deps.store.extractSecrets(slugify(draft.name), steps);
6740
+ const after = this.deps.store.readSecrets();
6741
+ const captured = {};
6742
+ for (const [ref, value] of Object.entries(after)) {
6743
+ if (before[ref] !== value) captured[ref] = value;
6744
+ }
6671
6745
  const doc = {
6672
6746
  schemaVersion: CURRENT_SCHEMA_VERSION,
6673
6747
  id: `flw_${crypto3.randomUUID().slice(0, 8)}`,
@@ -6688,7 +6762,7 @@ var RecordingCoordinator = class {
6688
6762
  this.draft = null;
6689
6763
  const saved = { ...this.deps.store.getFlow(doc.id) ?? doc, path: file };
6690
6764
  this.deps.emit({ type: "recording.stopped", flow: saved, file });
6691
- return { ok: true, flow: saved };
6765
+ return this.lastResult = { ok: true, flow: saved, secrets: captured };
6692
6766
  }
6693
6767
  /** Throw the recording away: close the browser, drop the draft, write
6694
6768
  * nothing.
@@ -7625,11 +7699,6 @@ import os5 from "os";
7625
7699
  import path10 from "path";
7626
7700
  import fs25 from "fs";
7627
7701
  import path24 from "path";
7628
- var __defProp = Object.defineProperty;
7629
- var __export = (target, all) => {
7630
- for (var name in all)
7631
- __defProp(target, name, { get: all[name], enumerable: true });
7632
- };
7633
7702
  var NO_CHECKOUT = {
7634
7703
  ok: false,
7635
7704
  reason: "failed",
@@ -8104,7 +8173,10 @@ function recordingHandlers({ recorder, onActivity }) {
8104
8173
  try {
8105
8174
  const saved = await recorder.stop(project.id);
8106
8175
  if (!saved.ok) return { ok: false, reason: "failed", detail: saved.error };
8107
- return { ok: true, result: { flow: saved.flow, projectId: project.id } };
8176
+ return {
8177
+ ok: true,
8178
+ result: { flow: saved.flow, projectId: project.id, secrets: saved.secrets }
8179
+ };
8108
8180
  } finally {
8109
8181
  onActivity?.(null);
8110
8182
  }
@@ -8145,4509 +8217,6 @@ function recordingHandlers({ recorder, onActivity }) {
8145
8217
  }
8146
8218
  };
8147
8219
  }
8148
- var external_exports = {};
8149
- __export(external_exports, {
8150
- BRAND: () => BRAND,
8151
- DIRTY: () => DIRTY,
8152
- EMPTY_PATH: () => EMPTY_PATH,
8153
- INVALID: () => INVALID,
8154
- NEVER: () => NEVER,
8155
- OK: () => OK,
8156
- ParseStatus: () => ParseStatus,
8157
- Schema: () => ZodType,
8158
- ZodAny: () => ZodAny,
8159
- ZodArray: () => ZodArray,
8160
- ZodBigInt: () => ZodBigInt,
8161
- ZodBoolean: () => ZodBoolean,
8162
- ZodBranded: () => ZodBranded,
8163
- ZodCatch: () => ZodCatch,
8164
- ZodDate: () => ZodDate,
8165
- ZodDefault: () => ZodDefault,
8166
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
8167
- ZodEffects: () => ZodEffects,
8168
- ZodEnum: () => ZodEnum,
8169
- ZodError: () => ZodError,
8170
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
8171
- ZodFunction: () => ZodFunction,
8172
- ZodIntersection: () => ZodIntersection,
8173
- ZodIssueCode: () => ZodIssueCode,
8174
- ZodLazy: () => ZodLazy,
8175
- ZodLiteral: () => ZodLiteral,
8176
- ZodMap: () => ZodMap,
8177
- ZodNaN: () => ZodNaN,
8178
- ZodNativeEnum: () => ZodNativeEnum,
8179
- ZodNever: () => ZodNever,
8180
- ZodNull: () => ZodNull,
8181
- ZodNullable: () => ZodNullable,
8182
- ZodNumber: () => ZodNumber,
8183
- ZodObject: () => ZodObject,
8184
- ZodOptional: () => ZodOptional,
8185
- ZodParsedType: () => ZodParsedType,
8186
- ZodPipeline: () => ZodPipeline,
8187
- ZodPromise: () => ZodPromise,
8188
- ZodReadonly: () => ZodReadonly,
8189
- ZodRecord: () => ZodRecord,
8190
- ZodSchema: () => ZodType,
8191
- ZodSet: () => ZodSet,
8192
- ZodString: () => ZodString,
8193
- ZodSymbol: () => ZodSymbol,
8194
- ZodTransformer: () => ZodEffects,
8195
- ZodTuple: () => ZodTuple,
8196
- ZodType: () => ZodType,
8197
- ZodUndefined: () => ZodUndefined,
8198
- ZodUnion: () => ZodUnion,
8199
- ZodUnknown: () => ZodUnknown,
8200
- ZodVoid: () => ZodVoid,
8201
- addIssueToContext: () => addIssueToContext,
8202
- any: () => anyType,
8203
- array: () => arrayType,
8204
- bigint: () => bigIntType,
8205
- boolean: () => booleanType,
8206
- coerce: () => coerce,
8207
- custom: () => custom,
8208
- date: () => dateType,
8209
- datetimeRegex: () => datetimeRegex,
8210
- defaultErrorMap: () => en_default,
8211
- discriminatedUnion: () => discriminatedUnionType,
8212
- effect: () => effectsType,
8213
- enum: () => enumType,
8214
- function: () => functionType,
8215
- getErrorMap: () => getErrorMap,
8216
- getParsedType: () => getParsedType,
8217
- instanceof: () => instanceOfType,
8218
- intersection: () => intersectionType,
8219
- isAborted: () => isAborted,
8220
- isAsync: () => isAsync,
8221
- isDirty: () => isDirty,
8222
- isValid: () => isValid,
8223
- late: () => late,
8224
- lazy: () => lazyType,
8225
- literal: () => literalType,
8226
- makeIssue: () => makeIssue,
8227
- map: () => mapType,
8228
- nan: () => nanType,
8229
- nativeEnum: () => nativeEnumType,
8230
- never: () => neverType,
8231
- null: () => nullType,
8232
- nullable: () => nullableType,
8233
- number: () => numberType,
8234
- object: () => objectType,
8235
- objectUtil: () => objectUtil,
8236
- oboolean: () => oboolean,
8237
- onumber: () => onumber,
8238
- optional: () => optionalType,
8239
- ostring: () => ostring,
8240
- pipeline: () => pipelineType,
8241
- preprocess: () => preprocessType,
8242
- promise: () => promiseType,
8243
- quotelessJson: () => quotelessJson,
8244
- record: () => recordType,
8245
- set: () => setType,
8246
- setErrorMap: () => setErrorMap,
8247
- strictObject: () => strictObjectType,
8248
- string: () => stringType,
8249
- symbol: () => symbolType,
8250
- transformer: () => effectsType,
8251
- tuple: () => tupleType,
8252
- undefined: () => undefinedType,
8253
- union: () => unionType,
8254
- unknown: () => unknownType,
8255
- util: () => util,
8256
- void: () => voidType
8257
- });
8258
- var util;
8259
- (function(util2) {
8260
- util2.assertEqual = (_) => {
8261
- };
8262
- function assertIs(_arg) {
8263
- }
8264
- util2.assertIs = assertIs;
8265
- function assertNever(_x) {
8266
- throw new Error();
8267
- }
8268
- util2.assertNever = assertNever;
8269
- util2.arrayToEnum = (items) => {
8270
- const obj = {};
8271
- for (const item of items) {
8272
- obj[item] = item;
8273
- }
8274
- return obj;
8275
- };
8276
- util2.getValidEnumValues = (obj) => {
8277
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
8278
- const filtered = {};
8279
- for (const k of validKeys) {
8280
- filtered[k] = obj[k];
8281
- }
8282
- return util2.objectValues(filtered);
8283
- };
8284
- util2.objectValues = (obj) => {
8285
- return util2.objectKeys(obj).map(function(e) {
8286
- return obj[e];
8287
- });
8288
- };
8289
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
8290
- const keys = [];
8291
- for (const key in object) {
8292
- if (Object.prototype.hasOwnProperty.call(object, key)) {
8293
- keys.push(key);
8294
- }
8295
- }
8296
- return keys;
8297
- };
8298
- util2.find = (arr, checker) => {
8299
- for (const item of arr) {
8300
- if (checker(item))
8301
- return item;
8302
- }
8303
- return void 0;
8304
- };
8305
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
8306
- function joinValues(array, separator = " | ") {
8307
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
8308
- }
8309
- util2.joinValues = joinValues;
8310
- util2.jsonStringifyReplacer = (_, value) => {
8311
- if (typeof value === "bigint") {
8312
- return value.toString();
8313
- }
8314
- return value;
8315
- };
8316
- })(util || (util = {}));
8317
- var objectUtil;
8318
- (function(objectUtil2) {
8319
- objectUtil2.mergeShapes = (first, second) => {
8320
- return {
8321
- ...first,
8322
- ...second
8323
- // second overwrites first
8324
- };
8325
- };
8326
- })(objectUtil || (objectUtil = {}));
8327
- var ZodParsedType = util.arrayToEnum([
8328
- "string",
8329
- "nan",
8330
- "number",
8331
- "integer",
8332
- "float",
8333
- "boolean",
8334
- "date",
8335
- "bigint",
8336
- "symbol",
8337
- "function",
8338
- "undefined",
8339
- "null",
8340
- "array",
8341
- "object",
8342
- "unknown",
8343
- "promise",
8344
- "void",
8345
- "never",
8346
- "map",
8347
- "set"
8348
- ]);
8349
- var getParsedType = (data) => {
8350
- const t = typeof data;
8351
- switch (t) {
8352
- case "undefined":
8353
- return ZodParsedType.undefined;
8354
- case "string":
8355
- return ZodParsedType.string;
8356
- case "number":
8357
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
8358
- case "boolean":
8359
- return ZodParsedType.boolean;
8360
- case "function":
8361
- return ZodParsedType.function;
8362
- case "bigint":
8363
- return ZodParsedType.bigint;
8364
- case "symbol":
8365
- return ZodParsedType.symbol;
8366
- case "object":
8367
- if (Array.isArray(data)) {
8368
- return ZodParsedType.array;
8369
- }
8370
- if (data === null) {
8371
- return ZodParsedType.null;
8372
- }
8373
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
8374
- return ZodParsedType.promise;
8375
- }
8376
- if (typeof Map !== "undefined" && data instanceof Map) {
8377
- return ZodParsedType.map;
8378
- }
8379
- if (typeof Set !== "undefined" && data instanceof Set) {
8380
- return ZodParsedType.set;
8381
- }
8382
- if (typeof Date !== "undefined" && data instanceof Date) {
8383
- return ZodParsedType.date;
8384
- }
8385
- return ZodParsedType.object;
8386
- default:
8387
- return ZodParsedType.unknown;
8388
- }
8389
- };
8390
- var ZodIssueCode = util.arrayToEnum([
8391
- "invalid_type",
8392
- "invalid_literal",
8393
- "custom",
8394
- "invalid_union",
8395
- "invalid_union_discriminator",
8396
- "invalid_enum_value",
8397
- "unrecognized_keys",
8398
- "invalid_arguments",
8399
- "invalid_return_type",
8400
- "invalid_date",
8401
- "invalid_string",
8402
- "too_small",
8403
- "too_big",
8404
- "invalid_intersection_types",
8405
- "not_multiple_of",
8406
- "not_finite"
8407
- ]);
8408
- var quotelessJson = (obj) => {
8409
- const json = JSON.stringify(obj, null, 2);
8410
- return json.replace(/"([^"]+)":/g, "$1:");
8411
- };
8412
- var ZodError = class _ZodError extends Error {
8413
- get errors() {
8414
- return this.issues;
8415
- }
8416
- constructor(issues) {
8417
- super();
8418
- this.issues = [];
8419
- this.addIssue = (sub) => {
8420
- this.issues = [...this.issues, sub];
8421
- };
8422
- this.addIssues = (subs = []) => {
8423
- this.issues = [...this.issues, ...subs];
8424
- };
8425
- const actualProto = new.target.prototype;
8426
- if (Object.setPrototypeOf) {
8427
- Object.setPrototypeOf(this, actualProto);
8428
- } else {
8429
- this.__proto__ = actualProto;
8430
- }
8431
- this.name = "ZodError";
8432
- this.issues = issues;
8433
- }
8434
- format(_mapper) {
8435
- const mapper = _mapper || function(issue) {
8436
- return issue.message;
8437
- };
8438
- const fieldErrors = { _errors: [] };
8439
- const processError = (error) => {
8440
- for (const issue of error.issues) {
8441
- if (issue.code === "invalid_union") {
8442
- issue.unionErrors.map(processError);
8443
- } else if (issue.code === "invalid_return_type") {
8444
- processError(issue.returnTypeError);
8445
- } else if (issue.code === "invalid_arguments") {
8446
- processError(issue.argumentsError);
8447
- } else if (issue.path.length === 0) {
8448
- fieldErrors._errors.push(mapper(issue));
8449
- } else {
8450
- let curr = fieldErrors;
8451
- let i = 0;
8452
- while (i < issue.path.length) {
8453
- const el = issue.path[i];
8454
- const terminal = i === issue.path.length - 1;
8455
- if (!terminal) {
8456
- curr[el] = curr[el] || { _errors: [] };
8457
- } else {
8458
- curr[el] = curr[el] || { _errors: [] };
8459
- curr[el]._errors.push(mapper(issue));
8460
- }
8461
- curr = curr[el];
8462
- i++;
8463
- }
8464
- }
8465
- }
8466
- };
8467
- processError(this);
8468
- return fieldErrors;
8469
- }
8470
- static assert(value) {
8471
- if (!(value instanceof _ZodError)) {
8472
- throw new Error(`Not a ZodError: ${value}`);
8473
- }
8474
- }
8475
- toString() {
8476
- return this.message;
8477
- }
8478
- get message() {
8479
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
8480
- }
8481
- get isEmpty() {
8482
- return this.issues.length === 0;
8483
- }
8484
- flatten(mapper = (issue) => issue.message) {
8485
- const fieldErrors = {};
8486
- const formErrors = [];
8487
- for (const sub of this.issues) {
8488
- if (sub.path.length > 0) {
8489
- const firstEl = sub.path[0];
8490
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
8491
- fieldErrors[firstEl].push(mapper(sub));
8492
- } else {
8493
- formErrors.push(mapper(sub));
8494
- }
8495
- }
8496
- return { formErrors, fieldErrors };
8497
- }
8498
- get formErrors() {
8499
- return this.flatten();
8500
- }
8501
- };
8502
- ZodError.create = (issues) => {
8503
- const error = new ZodError(issues);
8504
- return error;
8505
- };
8506
- var errorMap = (issue, _ctx) => {
8507
- let message;
8508
- switch (issue.code) {
8509
- case ZodIssueCode.invalid_type:
8510
- if (issue.received === ZodParsedType.undefined) {
8511
- message = "Required";
8512
- } else {
8513
- message = `Expected ${issue.expected}, received ${issue.received}`;
8514
- }
8515
- break;
8516
- case ZodIssueCode.invalid_literal:
8517
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
8518
- break;
8519
- case ZodIssueCode.unrecognized_keys:
8520
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
8521
- break;
8522
- case ZodIssueCode.invalid_union:
8523
- message = `Invalid input`;
8524
- break;
8525
- case ZodIssueCode.invalid_union_discriminator:
8526
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
8527
- break;
8528
- case ZodIssueCode.invalid_enum_value:
8529
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
8530
- break;
8531
- case ZodIssueCode.invalid_arguments:
8532
- message = `Invalid function arguments`;
8533
- break;
8534
- case ZodIssueCode.invalid_return_type:
8535
- message = `Invalid function return type`;
8536
- break;
8537
- case ZodIssueCode.invalid_date:
8538
- message = `Invalid date`;
8539
- break;
8540
- case ZodIssueCode.invalid_string:
8541
- if (typeof issue.validation === "object") {
8542
- if ("includes" in issue.validation) {
8543
- message = `Invalid input: must include "${issue.validation.includes}"`;
8544
- if (typeof issue.validation.position === "number") {
8545
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
8546
- }
8547
- } else if ("startsWith" in issue.validation) {
8548
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
8549
- } else if ("endsWith" in issue.validation) {
8550
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
8551
- } else {
8552
- util.assertNever(issue.validation);
8553
- }
8554
- } else if (issue.validation !== "regex") {
8555
- message = `Invalid ${issue.validation}`;
8556
- } else {
8557
- message = "Invalid";
8558
- }
8559
- break;
8560
- case ZodIssueCode.too_small:
8561
- if (issue.type === "array")
8562
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
8563
- else if (issue.type === "string")
8564
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
8565
- else if (issue.type === "number")
8566
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
8567
- else if (issue.type === "bigint")
8568
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
8569
- else if (issue.type === "date")
8570
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
8571
- else
8572
- message = "Invalid input";
8573
- break;
8574
- case ZodIssueCode.too_big:
8575
- if (issue.type === "array")
8576
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
8577
- else if (issue.type === "string")
8578
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
8579
- else if (issue.type === "number")
8580
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
8581
- else if (issue.type === "bigint")
8582
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
8583
- else if (issue.type === "date")
8584
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
8585
- else
8586
- message = "Invalid input";
8587
- break;
8588
- case ZodIssueCode.custom:
8589
- message = `Invalid input`;
8590
- break;
8591
- case ZodIssueCode.invalid_intersection_types:
8592
- message = `Intersection results could not be merged`;
8593
- break;
8594
- case ZodIssueCode.not_multiple_of:
8595
- message = `Number must be a multiple of ${issue.multipleOf}`;
8596
- break;
8597
- case ZodIssueCode.not_finite:
8598
- message = "Number must be finite";
8599
- break;
8600
- default:
8601
- message = _ctx.defaultError;
8602
- util.assertNever(issue);
8603
- }
8604
- return { message };
8605
- };
8606
- var en_default = errorMap;
8607
- var overrideErrorMap = en_default;
8608
- function setErrorMap(map) {
8609
- overrideErrorMap = map;
8610
- }
8611
- function getErrorMap() {
8612
- return overrideErrorMap;
8613
- }
8614
- var makeIssue = (params) => {
8615
- const { data, path: path33, errorMaps, issueData } = params;
8616
- const fullPath = [...path33, ...issueData.path || []];
8617
- const fullIssue = {
8618
- ...issueData,
8619
- path: fullPath
8620
- };
8621
- if (issueData.message !== void 0) {
8622
- return {
8623
- ...issueData,
8624
- path: fullPath,
8625
- message: issueData.message
8626
- };
8627
- }
8628
- let errorMessage = "";
8629
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
8630
- for (const map of maps) {
8631
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
8632
- }
8633
- return {
8634
- ...issueData,
8635
- path: fullPath,
8636
- message: errorMessage
8637
- };
8638
- };
8639
- var EMPTY_PATH = [];
8640
- function addIssueToContext(ctx, issueData) {
8641
- const overrideMap = getErrorMap();
8642
- const issue = makeIssue({
8643
- issueData,
8644
- data: ctx.data,
8645
- path: ctx.path,
8646
- errorMaps: [
8647
- ctx.common.contextualErrorMap,
8648
- // contextual error map is first priority
8649
- ctx.schemaErrorMap,
8650
- // then schema-bound map if available
8651
- overrideMap,
8652
- // then global override map
8653
- overrideMap === en_default ? void 0 : en_default
8654
- // then global default map
8655
- ].filter((x) => !!x)
8656
- });
8657
- ctx.common.issues.push(issue);
8658
- }
8659
- var ParseStatus = class _ParseStatus {
8660
- constructor() {
8661
- this.value = "valid";
8662
- }
8663
- dirty() {
8664
- if (this.value === "valid")
8665
- this.value = "dirty";
8666
- }
8667
- abort() {
8668
- if (this.value !== "aborted")
8669
- this.value = "aborted";
8670
- }
8671
- static mergeArray(status2, results) {
8672
- const arrayValue = [];
8673
- for (const s2 of results) {
8674
- if (s2.status === "aborted")
8675
- return INVALID;
8676
- if (s2.status === "dirty")
8677
- status2.dirty();
8678
- arrayValue.push(s2.value);
8679
- }
8680
- return { status: status2.value, value: arrayValue };
8681
- }
8682
- static async mergeObjectAsync(status2, pairs) {
8683
- const syncPairs = [];
8684
- for (const pair of pairs) {
8685
- const key = await pair.key;
8686
- const value = await pair.value;
8687
- syncPairs.push({
8688
- key,
8689
- value
8690
- });
8691
- }
8692
- return _ParseStatus.mergeObjectSync(status2, syncPairs);
8693
- }
8694
- static mergeObjectSync(status2, pairs) {
8695
- const finalObject = {};
8696
- for (const pair of pairs) {
8697
- const { key, value } = pair;
8698
- if (key.status === "aborted")
8699
- return INVALID;
8700
- if (value.status === "aborted")
8701
- return INVALID;
8702
- if (key.status === "dirty")
8703
- status2.dirty();
8704
- if (value.status === "dirty")
8705
- status2.dirty();
8706
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
8707
- finalObject[key.value] = value.value;
8708
- }
8709
- }
8710
- return { status: status2.value, value: finalObject };
8711
- }
8712
- };
8713
- var INVALID = Object.freeze({
8714
- status: "aborted"
8715
- });
8716
- var DIRTY = (value) => ({ status: "dirty", value });
8717
- var OK = (value) => ({ status: "valid", value });
8718
- var isAborted = (x) => x.status === "aborted";
8719
- var isDirty = (x) => x.status === "dirty";
8720
- var isValid = (x) => x.status === "valid";
8721
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
8722
- var errorUtil;
8723
- (function(errorUtil2) {
8724
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
8725
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
8726
- })(errorUtil || (errorUtil = {}));
8727
- var ParseInputLazyPath = class {
8728
- constructor(parent, value, path33, key) {
8729
- this._cachedPath = [];
8730
- this.parent = parent;
8731
- this.data = value;
8732
- this._path = path33;
8733
- this._key = key;
8734
- }
8735
- get path() {
8736
- if (!this._cachedPath.length) {
8737
- if (Array.isArray(this._key)) {
8738
- this._cachedPath.push(...this._path, ...this._key);
8739
- } else {
8740
- this._cachedPath.push(...this._path, this._key);
8741
- }
8742
- }
8743
- return this._cachedPath;
8744
- }
8745
- };
8746
- var handleResult = (ctx, result) => {
8747
- if (isValid(result)) {
8748
- return { success: true, data: result.value };
8749
- } else {
8750
- if (!ctx.common.issues.length) {
8751
- throw new Error("Validation failed but no issues detected.");
8752
- }
8753
- return {
8754
- success: false,
8755
- get error() {
8756
- if (this._error)
8757
- return this._error;
8758
- const error = new ZodError(ctx.common.issues);
8759
- this._error = error;
8760
- return this._error;
8761
- }
8762
- };
8763
- }
8764
- };
8765
- function processCreateParams(params) {
8766
- if (!params)
8767
- return {};
8768
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
8769
- if (errorMap2 && (invalid_type_error || required_error)) {
8770
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
8771
- }
8772
- if (errorMap2)
8773
- return { errorMap: errorMap2, description };
8774
- const customMap = (iss, ctx) => {
8775
- const { message } = params;
8776
- if (iss.code === "invalid_enum_value") {
8777
- return { message: message ?? ctx.defaultError };
8778
- }
8779
- if (typeof ctx.data === "undefined") {
8780
- return { message: message ?? required_error ?? ctx.defaultError };
8781
- }
8782
- if (iss.code !== "invalid_type")
8783
- return { message: ctx.defaultError };
8784
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
8785
- };
8786
- return { errorMap: customMap, description };
8787
- }
8788
- var ZodType = class {
8789
- get description() {
8790
- return this._def.description;
8791
- }
8792
- _getType(input) {
8793
- return getParsedType(input.data);
8794
- }
8795
- _getOrReturnCtx(input, ctx) {
8796
- return ctx || {
8797
- common: input.parent.common,
8798
- data: input.data,
8799
- parsedType: getParsedType(input.data),
8800
- schemaErrorMap: this._def.errorMap,
8801
- path: input.path,
8802
- parent: input.parent
8803
- };
8804
- }
8805
- _processInputParams(input) {
8806
- return {
8807
- status: new ParseStatus(),
8808
- ctx: {
8809
- common: input.parent.common,
8810
- data: input.data,
8811
- parsedType: getParsedType(input.data),
8812
- schemaErrorMap: this._def.errorMap,
8813
- path: input.path,
8814
- parent: input.parent
8815
- }
8816
- };
8817
- }
8818
- _parseSync(input) {
8819
- const result = this._parse(input);
8820
- if (isAsync(result)) {
8821
- throw new Error("Synchronous parse encountered promise.");
8822
- }
8823
- return result;
8824
- }
8825
- _parseAsync(input) {
8826
- const result = this._parse(input);
8827
- return Promise.resolve(result);
8828
- }
8829
- parse(data, params) {
8830
- const result = this.safeParse(data, params);
8831
- if (result.success)
8832
- return result.data;
8833
- throw result.error;
8834
- }
8835
- safeParse(data, params) {
8836
- const ctx = {
8837
- common: {
8838
- issues: [],
8839
- async: params?.async ?? false,
8840
- contextualErrorMap: params?.errorMap
8841
- },
8842
- path: params?.path || [],
8843
- schemaErrorMap: this._def.errorMap,
8844
- parent: null,
8845
- data,
8846
- parsedType: getParsedType(data)
8847
- };
8848
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
8849
- return handleResult(ctx, result);
8850
- }
8851
- "~validate"(data) {
8852
- const ctx = {
8853
- common: {
8854
- issues: [],
8855
- async: !!this["~standard"].async
8856
- },
8857
- path: [],
8858
- schemaErrorMap: this._def.errorMap,
8859
- parent: null,
8860
- data,
8861
- parsedType: getParsedType(data)
8862
- };
8863
- if (!this["~standard"].async) {
8864
- try {
8865
- const result = this._parseSync({ data, path: [], parent: ctx });
8866
- return isValid(result) ? {
8867
- value: result.value
8868
- } : {
8869
- issues: ctx.common.issues
8870
- };
8871
- } catch (err) {
8872
- if (err?.message?.toLowerCase()?.includes("encountered")) {
8873
- this["~standard"].async = true;
8874
- }
8875
- ctx.common = {
8876
- issues: [],
8877
- async: true
8878
- };
8879
- }
8880
- }
8881
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
8882
- value: result.value
8883
- } : {
8884
- issues: ctx.common.issues
8885
- });
8886
- }
8887
- async parseAsync(data, params) {
8888
- const result = await this.safeParseAsync(data, params);
8889
- if (result.success)
8890
- return result.data;
8891
- throw result.error;
8892
- }
8893
- async safeParseAsync(data, params) {
8894
- const ctx = {
8895
- common: {
8896
- issues: [],
8897
- contextualErrorMap: params?.errorMap,
8898
- async: true
8899
- },
8900
- path: params?.path || [],
8901
- schemaErrorMap: this._def.errorMap,
8902
- parent: null,
8903
- data,
8904
- parsedType: getParsedType(data)
8905
- };
8906
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
8907
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
8908
- return handleResult(ctx, result);
8909
- }
8910
- refine(check, message) {
8911
- const getIssueProperties = (val) => {
8912
- if (typeof message === "string" || typeof message === "undefined") {
8913
- return { message };
8914
- } else if (typeof message === "function") {
8915
- return message(val);
8916
- } else {
8917
- return message;
8918
- }
8919
- };
8920
- return this._refinement((val, ctx) => {
8921
- const result = check(val);
8922
- const setError = () => ctx.addIssue({
8923
- code: ZodIssueCode.custom,
8924
- ...getIssueProperties(val)
8925
- });
8926
- if (typeof Promise !== "undefined" && result instanceof Promise) {
8927
- return result.then((data) => {
8928
- if (!data) {
8929
- setError();
8930
- return false;
8931
- } else {
8932
- return true;
8933
- }
8934
- });
8935
- }
8936
- if (!result) {
8937
- setError();
8938
- return false;
8939
- } else {
8940
- return true;
8941
- }
8942
- });
8943
- }
8944
- refinement(check, refinementData) {
8945
- return this._refinement((val, ctx) => {
8946
- if (!check(val)) {
8947
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
8948
- return false;
8949
- } else {
8950
- return true;
8951
- }
8952
- });
8953
- }
8954
- _refinement(refinement) {
8955
- return new ZodEffects({
8956
- schema: this,
8957
- typeName: ZodFirstPartyTypeKind.ZodEffects,
8958
- effect: { type: "refinement", refinement }
8959
- });
8960
- }
8961
- superRefine(refinement) {
8962
- return this._refinement(refinement);
8963
- }
8964
- constructor(def) {
8965
- this.spa = this.safeParseAsync;
8966
- this._def = def;
8967
- this.parse = this.parse.bind(this);
8968
- this.safeParse = this.safeParse.bind(this);
8969
- this.parseAsync = this.parseAsync.bind(this);
8970
- this.safeParseAsync = this.safeParseAsync.bind(this);
8971
- this.spa = this.spa.bind(this);
8972
- this.refine = this.refine.bind(this);
8973
- this.refinement = this.refinement.bind(this);
8974
- this.superRefine = this.superRefine.bind(this);
8975
- this.optional = this.optional.bind(this);
8976
- this.nullable = this.nullable.bind(this);
8977
- this.nullish = this.nullish.bind(this);
8978
- this.array = this.array.bind(this);
8979
- this.promise = this.promise.bind(this);
8980
- this.or = this.or.bind(this);
8981
- this.and = this.and.bind(this);
8982
- this.transform = this.transform.bind(this);
8983
- this.brand = this.brand.bind(this);
8984
- this.default = this.default.bind(this);
8985
- this.catch = this.catch.bind(this);
8986
- this.describe = this.describe.bind(this);
8987
- this.pipe = this.pipe.bind(this);
8988
- this.readonly = this.readonly.bind(this);
8989
- this.isNullable = this.isNullable.bind(this);
8990
- this.isOptional = this.isOptional.bind(this);
8991
- this["~standard"] = {
8992
- version: 1,
8993
- vendor: "zod",
8994
- validate: (data) => this["~validate"](data)
8995
- };
8996
- }
8997
- optional() {
8998
- return ZodOptional.create(this, this._def);
8999
- }
9000
- nullable() {
9001
- return ZodNullable.create(this, this._def);
9002
- }
9003
- nullish() {
9004
- return this.nullable().optional();
9005
- }
9006
- array() {
9007
- return ZodArray.create(this);
9008
- }
9009
- promise() {
9010
- return ZodPromise.create(this, this._def);
9011
- }
9012
- or(option) {
9013
- return ZodUnion.create([this, option], this._def);
9014
- }
9015
- and(incoming) {
9016
- return ZodIntersection.create(this, incoming, this._def);
9017
- }
9018
- transform(transform) {
9019
- return new ZodEffects({
9020
- ...processCreateParams(this._def),
9021
- schema: this,
9022
- typeName: ZodFirstPartyTypeKind.ZodEffects,
9023
- effect: { type: "transform", transform }
9024
- });
9025
- }
9026
- default(def) {
9027
- const defaultValueFunc = typeof def === "function" ? def : () => def;
9028
- return new ZodDefault({
9029
- ...processCreateParams(this._def),
9030
- innerType: this,
9031
- defaultValue: defaultValueFunc,
9032
- typeName: ZodFirstPartyTypeKind.ZodDefault
9033
- });
9034
- }
9035
- brand() {
9036
- return new ZodBranded({
9037
- typeName: ZodFirstPartyTypeKind.ZodBranded,
9038
- type: this,
9039
- ...processCreateParams(this._def)
9040
- });
9041
- }
9042
- catch(def) {
9043
- const catchValueFunc = typeof def === "function" ? def : () => def;
9044
- return new ZodCatch({
9045
- ...processCreateParams(this._def),
9046
- innerType: this,
9047
- catchValue: catchValueFunc,
9048
- typeName: ZodFirstPartyTypeKind.ZodCatch
9049
- });
9050
- }
9051
- describe(description) {
9052
- const This = this.constructor;
9053
- return new This({
9054
- ...this._def,
9055
- description
9056
- });
9057
- }
9058
- pipe(target) {
9059
- return ZodPipeline.create(this, target);
9060
- }
9061
- readonly() {
9062
- return ZodReadonly.create(this);
9063
- }
9064
- isOptional() {
9065
- return this.safeParse(void 0).success;
9066
- }
9067
- isNullable() {
9068
- return this.safeParse(null).success;
9069
- }
9070
- };
9071
- var cuidRegex = /^c[^\s-]{8,}$/i;
9072
- var cuid2Regex = /^[0-9a-z]+$/;
9073
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
9074
- 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;
9075
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
9076
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
9077
- 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)?)??$/;
9078
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
9079
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
9080
- var emojiRegex;
9081
- 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])$/;
9082
- 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])$/;
9083
- 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]))$/;
9084
- 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])$/;
9085
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
9086
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
9087
- 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])))`;
9088
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
9089
- function timeRegexSource(args) {
9090
- let secondsRegexSource = `[0-5]\\d`;
9091
- if (args.precision) {
9092
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
9093
- } else if (args.precision == null) {
9094
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
9095
- }
9096
- const secondsQuantifier = args.precision ? "+" : "?";
9097
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
9098
- }
9099
- function timeRegex(args) {
9100
- return new RegExp(`^${timeRegexSource(args)}$`);
9101
- }
9102
- function datetimeRegex(args) {
9103
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
9104
- const opts = [];
9105
- opts.push(args.local ? `Z?` : `Z`);
9106
- if (args.offset)
9107
- opts.push(`([+-]\\d{2}:?\\d{2})`);
9108
- regex = `${regex}(${opts.join("|")})`;
9109
- return new RegExp(`^${regex}$`);
9110
- }
9111
- function isValidIP(ip, version) {
9112
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
9113
- return true;
9114
- }
9115
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
9116
- return true;
9117
- }
9118
- return false;
9119
- }
9120
- function isValidJWT(jwt, alg) {
9121
- if (!jwtRegex.test(jwt))
9122
- return false;
9123
- try {
9124
- const [header] = jwt.split(".");
9125
- if (!header)
9126
- return false;
9127
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
9128
- const decoded = JSON.parse(atob(base64));
9129
- if (typeof decoded !== "object" || decoded === null)
9130
- return false;
9131
- if ("typ" in decoded && decoded?.typ !== "JWT")
9132
- return false;
9133
- if (!decoded.alg)
9134
- return false;
9135
- if (alg && decoded.alg !== alg)
9136
- return false;
9137
- return true;
9138
- } catch {
9139
- return false;
9140
- }
9141
- }
9142
- function isValidCidr(ip, version) {
9143
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
9144
- return true;
9145
- }
9146
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
9147
- return true;
9148
- }
9149
- return false;
9150
- }
9151
- var ZodString = class _ZodString extends ZodType {
9152
- _parse(input) {
9153
- if (this._def.coerce) {
9154
- input.data = String(input.data);
9155
- }
9156
- const parsedType = this._getType(input);
9157
- if (parsedType !== ZodParsedType.string) {
9158
- const ctx2 = this._getOrReturnCtx(input);
9159
- addIssueToContext(ctx2, {
9160
- code: ZodIssueCode.invalid_type,
9161
- expected: ZodParsedType.string,
9162
- received: ctx2.parsedType
9163
- });
9164
- return INVALID;
9165
- }
9166
- const status2 = new ParseStatus();
9167
- let ctx = void 0;
9168
- for (const check of this._def.checks) {
9169
- if (check.kind === "min") {
9170
- if (input.data.length < check.value) {
9171
- ctx = this._getOrReturnCtx(input, ctx);
9172
- addIssueToContext(ctx, {
9173
- code: ZodIssueCode.too_small,
9174
- minimum: check.value,
9175
- type: "string",
9176
- inclusive: true,
9177
- exact: false,
9178
- message: check.message
9179
- });
9180
- status2.dirty();
9181
- }
9182
- } else if (check.kind === "max") {
9183
- if (input.data.length > check.value) {
9184
- ctx = this._getOrReturnCtx(input, ctx);
9185
- addIssueToContext(ctx, {
9186
- code: ZodIssueCode.too_big,
9187
- maximum: check.value,
9188
- type: "string",
9189
- inclusive: true,
9190
- exact: false,
9191
- message: check.message
9192
- });
9193
- status2.dirty();
9194
- }
9195
- } else if (check.kind === "length") {
9196
- const tooBig = input.data.length > check.value;
9197
- const tooSmall = input.data.length < check.value;
9198
- if (tooBig || tooSmall) {
9199
- ctx = this._getOrReturnCtx(input, ctx);
9200
- if (tooBig) {
9201
- addIssueToContext(ctx, {
9202
- code: ZodIssueCode.too_big,
9203
- maximum: check.value,
9204
- type: "string",
9205
- inclusive: true,
9206
- exact: true,
9207
- message: check.message
9208
- });
9209
- } else if (tooSmall) {
9210
- addIssueToContext(ctx, {
9211
- code: ZodIssueCode.too_small,
9212
- minimum: check.value,
9213
- type: "string",
9214
- inclusive: true,
9215
- exact: true,
9216
- message: check.message
9217
- });
9218
- }
9219
- status2.dirty();
9220
- }
9221
- } else if (check.kind === "email") {
9222
- if (!emailRegex.test(input.data)) {
9223
- ctx = this._getOrReturnCtx(input, ctx);
9224
- addIssueToContext(ctx, {
9225
- validation: "email",
9226
- code: ZodIssueCode.invalid_string,
9227
- message: check.message
9228
- });
9229
- status2.dirty();
9230
- }
9231
- } else if (check.kind === "emoji") {
9232
- if (!emojiRegex) {
9233
- emojiRegex = new RegExp(_emojiRegex, "u");
9234
- }
9235
- if (!emojiRegex.test(input.data)) {
9236
- ctx = this._getOrReturnCtx(input, ctx);
9237
- addIssueToContext(ctx, {
9238
- validation: "emoji",
9239
- code: ZodIssueCode.invalid_string,
9240
- message: check.message
9241
- });
9242
- status2.dirty();
9243
- }
9244
- } else if (check.kind === "uuid") {
9245
- if (!uuidRegex.test(input.data)) {
9246
- ctx = this._getOrReturnCtx(input, ctx);
9247
- addIssueToContext(ctx, {
9248
- validation: "uuid",
9249
- code: ZodIssueCode.invalid_string,
9250
- message: check.message
9251
- });
9252
- status2.dirty();
9253
- }
9254
- } else if (check.kind === "nanoid") {
9255
- if (!nanoidRegex.test(input.data)) {
9256
- ctx = this._getOrReturnCtx(input, ctx);
9257
- addIssueToContext(ctx, {
9258
- validation: "nanoid",
9259
- code: ZodIssueCode.invalid_string,
9260
- message: check.message
9261
- });
9262
- status2.dirty();
9263
- }
9264
- } else if (check.kind === "cuid") {
9265
- if (!cuidRegex.test(input.data)) {
9266
- ctx = this._getOrReturnCtx(input, ctx);
9267
- addIssueToContext(ctx, {
9268
- validation: "cuid",
9269
- code: ZodIssueCode.invalid_string,
9270
- message: check.message
9271
- });
9272
- status2.dirty();
9273
- }
9274
- } else if (check.kind === "cuid2") {
9275
- if (!cuid2Regex.test(input.data)) {
9276
- ctx = this._getOrReturnCtx(input, ctx);
9277
- addIssueToContext(ctx, {
9278
- validation: "cuid2",
9279
- code: ZodIssueCode.invalid_string,
9280
- message: check.message
9281
- });
9282
- status2.dirty();
9283
- }
9284
- } else if (check.kind === "ulid") {
9285
- if (!ulidRegex.test(input.data)) {
9286
- ctx = this._getOrReturnCtx(input, ctx);
9287
- addIssueToContext(ctx, {
9288
- validation: "ulid",
9289
- code: ZodIssueCode.invalid_string,
9290
- message: check.message
9291
- });
9292
- status2.dirty();
9293
- }
9294
- } else if (check.kind === "url") {
9295
- try {
9296
- new URL(input.data);
9297
- } catch {
9298
- ctx = this._getOrReturnCtx(input, ctx);
9299
- addIssueToContext(ctx, {
9300
- validation: "url",
9301
- code: ZodIssueCode.invalid_string,
9302
- message: check.message
9303
- });
9304
- status2.dirty();
9305
- }
9306
- } else if (check.kind === "regex") {
9307
- check.regex.lastIndex = 0;
9308
- const testResult = check.regex.test(input.data);
9309
- if (!testResult) {
9310
- ctx = this._getOrReturnCtx(input, ctx);
9311
- addIssueToContext(ctx, {
9312
- validation: "regex",
9313
- code: ZodIssueCode.invalid_string,
9314
- message: check.message
9315
- });
9316
- status2.dirty();
9317
- }
9318
- } else if (check.kind === "trim") {
9319
- input.data = input.data.trim();
9320
- } else if (check.kind === "includes") {
9321
- if (!input.data.includes(check.value, check.position)) {
9322
- ctx = this._getOrReturnCtx(input, ctx);
9323
- addIssueToContext(ctx, {
9324
- code: ZodIssueCode.invalid_string,
9325
- validation: { includes: check.value, position: check.position },
9326
- message: check.message
9327
- });
9328
- status2.dirty();
9329
- }
9330
- } else if (check.kind === "toLowerCase") {
9331
- input.data = input.data.toLowerCase();
9332
- } else if (check.kind === "toUpperCase") {
9333
- input.data = input.data.toUpperCase();
9334
- } else if (check.kind === "startsWith") {
9335
- if (!input.data.startsWith(check.value)) {
9336
- ctx = this._getOrReturnCtx(input, ctx);
9337
- addIssueToContext(ctx, {
9338
- code: ZodIssueCode.invalid_string,
9339
- validation: { startsWith: check.value },
9340
- message: check.message
9341
- });
9342
- status2.dirty();
9343
- }
9344
- } else if (check.kind === "endsWith") {
9345
- if (!input.data.endsWith(check.value)) {
9346
- ctx = this._getOrReturnCtx(input, ctx);
9347
- addIssueToContext(ctx, {
9348
- code: ZodIssueCode.invalid_string,
9349
- validation: { endsWith: check.value },
9350
- message: check.message
9351
- });
9352
- status2.dirty();
9353
- }
9354
- } else if (check.kind === "datetime") {
9355
- const regex = datetimeRegex(check);
9356
- if (!regex.test(input.data)) {
9357
- ctx = this._getOrReturnCtx(input, ctx);
9358
- addIssueToContext(ctx, {
9359
- code: ZodIssueCode.invalid_string,
9360
- validation: "datetime",
9361
- message: check.message
9362
- });
9363
- status2.dirty();
9364
- }
9365
- } else if (check.kind === "date") {
9366
- const regex = dateRegex;
9367
- if (!regex.test(input.data)) {
9368
- ctx = this._getOrReturnCtx(input, ctx);
9369
- addIssueToContext(ctx, {
9370
- code: ZodIssueCode.invalid_string,
9371
- validation: "date",
9372
- message: check.message
9373
- });
9374
- status2.dirty();
9375
- }
9376
- } else if (check.kind === "time") {
9377
- const regex = timeRegex(check);
9378
- if (!regex.test(input.data)) {
9379
- ctx = this._getOrReturnCtx(input, ctx);
9380
- addIssueToContext(ctx, {
9381
- code: ZodIssueCode.invalid_string,
9382
- validation: "time",
9383
- message: check.message
9384
- });
9385
- status2.dirty();
9386
- }
9387
- } else if (check.kind === "duration") {
9388
- if (!durationRegex.test(input.data)) {
9389
- ctx = this._getOrReturnCtx(input, ctx);
9390
- addIssueToContext(ctx, {
9391
- validation: "duration",
9392
- code: ZodIssueCode.invalid_string,
9393
- message: check.message
9394
- });
9395
- status2.dirty();
9396
- }
9397
- } else if (check.kind === "ip") {
9398
- if (!isValidIP(input.data, check.version)) {
9399
- ctx = this._getOrReturnCtx(input, ctx);
9400
- addIssueToContext(ctx, {
9401
- validation: "ip",
9402
- code: ZodIssueCode.invalid_string,
9403
- message: check.message
9404
- });
9405
- status2.dirty();
9406
- }
9407
- } else if (check.kind === "jwt") {
9408
- if (!isValidJWT(input.data, check.alg)) {
9409
- ctx = this._getOrReturnCtx(input, ctx);
9410
- addIssueToContext(ctx, {
9411
- validation: "jwt",
9412
- code: ZodIssueCode.invalid_string,
9413
- message: check.message
9414
- });
9415
- status2.dirty();
9416
- }
9417
- } else if (check.kind === "cidr") {
9418
- if (!isValidCidr(input.data, check.version)) {
9419
- ctx = this._getOrReturnCtx(input, ctx);
9420
- addIssueToContext(ctx, {
9421
- validation: "cidr",
9422
- code: ZodIssueCode.invalid_string,
9423
- message: check.message
9424
- });
9425
- status2.dirty();
9426
- }
9427
- } else if (check.kind === "base64") {
9428
- if (!base64Regex.test(input.data)) {
9429
- ctx = this._getOrReturnCtx(input, ctx);
9430
- addIssueToContext(ctx, {
9431
- validation: "base64",
9432
- code: ZodIssueCode.invalid_string,
9433
- message: check.message
9434
- });
9435
- status2.dirty();
9436
- }
9437
- } else if (check.kind === "base64url") {
9438
- if (!base64urlRegex.test(input.data)) {
9439
- ctx = this._getOrReturnCtx(input, ctx);
9440
- addIssueToContext(ctx, {
9441
- validation: "base64url",
9442
- code: ZodIssueCode.invalid_string,
9443
- message: check.message
9444
- });
9445
- status2.dirty();
9446
- }
9447
- } else {
9448
- util.assertNever(check);
9449
- }
9450
- }
9451
- return { status: status2.value, value: input.data };
9452
- }
9453
- _regex(regex, validation, message) {
9454
- return this.refinement((data) => regex.test(data), {
9455
- validation,
9456
- code: ZodIssueCode.invalid_string,
9457
- ...errorUtil.errToObj(message)
9458
- });
9459
- }
9460
- _addCheck(check) {
9461
- return new _ZodString({
9462
- ...this._def,
9463
- checks: [...this._def.checks, check]
9464
- });
9465
- }
9466
- email(message) {
9467
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
9468
- }
9469
- url(message) {
9470
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
9471
- }
9472
- emoji(message) {
9473
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
9474
- }
9475
- uuid(message) {
9476
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
9477
- }
9478
- nanoid(message) {
9479
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
9480
- }
9481
- cuid(message) {
9482
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
9483
- }
9484
- cuid2(message) {
9485
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
9486
- }
9487
- ulid(message) {
9488
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
9489
- }
9490
- base64(message) {
9491
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
9492
- }
9493
- base64url(message) {
9494
- return this._addCheck({
9495
- kind: "base64url",
9496
- ...errorUtil.errToObj(message)
9497
- });
9498
- }
9499
- jwt(options) {
9500
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
9501
- }
9502
- ip(options) {
9503
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
9504
- }
9505
- cidr(options) {
9506
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
9507
- }
9508
- datetime(options) {
9509
- if (typeof options === "string") {
9510
- return this._addCheck({
9511
- kind: "datetime",
9512
- precision: null,
9513
- offset: false,
9514
- local: false,
9515
- message: options
9516
- });
9517
- }
9518
- return this._addCheck({
9519
- kind: "datetime",
9520
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
9521
- offset: options?.offset ?? false,
9522
- local: options?.local ?? false,
9523
- ...errorUtil.errToObj(options?.message)
9524
- });
9525
- }
9526
- date(message) {
9527
- return this._addCheck({ kind: "date", message });
9528
- }
9529
- time(options) {
9530
- if (typeof options === "string") {
9531
- return this._addCheck({
9532
- kind: "time",
9533
- precision: null,
9534
- message: options
9535
- });
9536
- }
9537
- return this._addCheck({
9538
- kind: "time",
9539
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
9540
- ...errorUtil.errToObj(options?.message)
9541
- });
9542
- }
9543
- duration(message) {
9544
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
9545
- }
9546
- regex(regex, message) {
9547
- return this._addCheck({
9548
- kind: "regex",
9549
- regex,
9550
- ...errorUtil.errToObj(message)
9551
- });
9552
- }
9553
- includes(value, options) {
9554
- return this._addCheck({
9555
- kind: "includes",
9556
- value,
9557
- position: options?.position,
9558
- ...errorUtil.errToObj(options?.message)
9559
- });
9560
- }
9561
- startsWith(value, message) {
9562
- return this._addCheck({
9563
- kind: "startsWith",
9564
- value,
9565
- ...errorUtil.errToObj(message)
9566
- });
9567
- }
9568
- endsWith(value, message) {
9569
- return this._addCheck({
9570
- kind: "endsWith",
9571
- value,
9572
- ...errorUtil.errToObj(message)
9573
- });
9574
- }
9575
- min(minLength, message) {
9576
- return this._addCheck({
9577
- kind: "min",
9578
- value: minLength,
9579
- ...errorUtil.errToObj(message)
9580
- });
9581
- }
9582
- max(maxLength, message) {
9583
- return this._addCheck({
9584
- kind: "max",
9585
- value: maxLength,
9586
- ...errorUtil.errToObj(message)
9587
- });
9588
- }
9589
- length(len, message) {
9590
- return this._addCheck({
9591
- kind: "length",
9592
- value: len,
9593
- ...errorUtil.errToObj(message)
9594
- });
9595
- }
9596
- /**
9597
- * Equivalent to `.min(1)`
9598
- */
9599
- nonempty(message) {
9600
- return this.min(1, errorUtil.errToObj(message));
9601
- }
9602
- trim() {
9603
- return new _ZodString({
9604
- ...this._def,
9605
- checks: [...this._def.checks, { kind: "trim" }]
9606
- });
9607
- }
9608
- toLowerCase() {
9609
- return new _ZodString({
9610
- ...this._def,
9611
- checks: [...this._def.checks, { kind: "toLowerCase" }]
9612
- });
9613
- }
9614
- toUpperCase() {
9615
- return new _ZodString({
9616
- ...this._def,
9617
- checks: [...this._def.checks, { kind: "toUpperCase" }]
9618
- });
9619
- }
9620
- get isDatetime() {
9621
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
9622
- }
9623
- get isDate() {
9624
- return !!this._def.checks.find((ch) => ch.kind === "date");
9625
- }
9626
- get isTime() {
9627
- return !!this._def.checks.find((ch) => ch.kind === "time");
9628
- }
9629
- get isDuration() {
9630
- return !!this._def.checks.find((ch) => ch.kind === "duration");
9631
- }
9632
- get isEmail() {
9633
- return !!this._def.checks.find((ch) => ch.kind === "email");
9634
- }
9635
- get isURL() {
9636
- return !!this._def.checks.find((ch) => ch.kind === "url");
9637
- }
9638
- get isEmoji() {
9639
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
9640
- }
9641
- get isUUID() {
9642
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
9643
- }
9644
- get isNANOID() {
9645
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
9646
- }
9647
- get isCUID() {
9648
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
9649
- }
9650
- get isCUID2() {
9651
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
9652
- }
9653
- get isULID() {
9654
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
9655
- }
9656
- get isIP() {
9657
- return !!this._def.checks.find((ch) => ch.kind === "ip");
9658
- }
9659
- get isCIDR() {
9660
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
9661
- }
9662
- get isBase64() {
9663
- return !!this._def.checks.find((ch) => ch.kind === "base64");
9664
- }
9665
- get isBase64url() {
9666
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
9667
- }
9668
- get minLength() {
9669
- let min = null;
9670
- for (const ch of this._def.checks) {
9671
- if (ch.kind === "min") {
9672
- if (min === null || ch.value > min)
9673
- min = ch.value;
9674
- }
9675
- }
9676
- return min;
9677
- }
9678
- get maxLength() {
9679
- let max = null;
9680
- for (const ch of this._def.checks) {
9681
- if (ch.kind === "max") {
9682
- if (max === null || ch.value < max)
9683
- max = ch.value;
9684
- }
9685
- }
9686
- return max;
9687
- }
9688
- };
9689
- ZodString.create = (params) => {
9690
- return new ZodString({
9691
- checks: [],
9692
- typeName: ZodFirstPartyTypeKind.ZodString,
9693
- coerce: params?.coerce ?? false,
9694
- ...processCreateParams(params)
9695
- });
9696
- };
9697
- function floatSafeRemainder(val, step) {
9698
- const valDecCount = (val.toString().split(".")[1] || "").length;
9699
- const stepDecCount = (step.toString().split(".")[1] || "").length;
9700
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
9701
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
9702
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
9703
- return valInt % stepInt / 10 ** decCount;
9704
- }
9705
- var ZodNumber = class _ZodNumber extends ZodType {
9706
- constructor() {
9707
- super(...arguments);
9708
- this.min = this.gte;
9709
- this.max = this.lte;
9710
- this.step = this.multipleOf;
9711
- }
9712
- _parse(input) {
9713
- if (this._def.coerce) {
9714
- input.data = Number(input.data);
9715
- }
9716
- const parsedType = this._getType(input);
9717
- if (parsedType !== ZodParsedType.number) {
9718
- const ctx2 = this._getOrReturnCtx(input);
9719
- addIssueToContext(ctx2, {
9720
- code: ZodIssueCode.invalid_type,
9721
- expected: ZodParsedType.number,
9722
- received: ctx2.parsedType
9723
- });
9724
- return INVALID;
9725
- }
9726
- let ctx = void 0;
9727
- const status2 = new ParseStatus();
9728
- for (const check of this._def.checks) {
9729
- if (check.kind === "int") {
9730
- if (!util.isInteger(input.data)) {
9731
- ctx = this._getOrReturnCtx(input, ctx);
9732
- addIssueToContext(ctx, {
9733
- code: ZodIssueCode.invalid_type,
9734
- expected: "integer",
9735
- received: "float",
9736
- message: check.message
9737
- });
9738
- status2.dirty();
9739
- }
9740
- } else if (check.kind === "min") {
9741
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
9742
- if (tooSmall) {
9743
- ctx = this._getOrReturnCtx(input, ctx);
9744
- addIssueToContext(ctx, {
9745
- code: ZodIssueCode.too_small,
9746
- minimum: check.value,
9747
- type: "number",
9748
- inclusive: check.inclusive,
9749
- exact: false,
9750
- message: check.message
9751
- });
9752
- status2.dirty();
9753
- }
9754
- } else if (check.kind === "max") {
9755
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
9756
- if (tooBig) {
9757
- ctx = this._getOrReturnCtx(input, ctx);
9758
- addIssueToContext(ctx, {
9759
- code: ZodIssueCode.too_big,
9760
- maximum: check.value,
9761
- type: "number",
9762
- inclusive: check.inclusive,
9763
- exact: false,
9764
- message: check.message
9765
- });
9766
- status2.dirty();
9767
- }
9768
- } else if (check.kind === "multipleOf") {
9769
- if (floatSafeRemainder(input.data, check.value) !== 0) {
9770
- ctx = this._getOrReturnCtx(input, ctx);
9771
- addIssueToContext(ctx, {
9772
- code: ZodIssueCode.not_multiple_of,
9773
- multipleOf: check.value,
9774
- message: check.message
9775
- });
9776
- status2.dirty();
9777
- }
9778
- } else if (check.kind === "finite") {
9779
- if (!Number.isFinite(input.data)) {
9780
- ctx = this._getOrReturnCtx(input, ctx);
9781
- addIssueToContext(ctx, {
9782
- code: ZodIssueCode.not_finite,
9783
- message: check.message
9784
- });
9785
- status2.dirty();
9786
- }
9787
- } else {
9788
- util.assertNever(check);
9789
- }
9790
- }
9791
- return { status: status2.value, value: input.data };
9792
- }
9793
- gte(value, message) {
9794
- return this.setLimit("min", value, true, errorUtil.toString(message));
9795
- }
9796
- gt(value, message) {
9797
- return this.setLimit("min", value, false, errorUtil.toString(message));
9798
- }
9799
- lte(value, message) {
9800
- return this.setLimit("max", value, true, errorUtil.toString(message));
9801
- }
9802
- lt(value, message) {
9803
- return this.setLimit("max", value, false, errorUtil.toString(message));
9804
- }
9805
- setLimit(kind, value, inclusive, message) {
9806
- return new _ZodNumber({
9807
- ...this._def,
9808
- checks: [
9809
- ...this._def.checks,
9810
- {
9811
- kind,
9812
- value,
9813
- inclusive,
9814
- message: errorUtil.toString(message)
9815
- }
9816
- ]
9817
- });
9818
- }
9819
- _addCheck(check) {
9820
- return new _ZodNumber({
9821
- ...this._def,
9822
- checks: [...this._def.checks, check]
9823
- });
9824
- }
9825
- int(message) {
9826
- return this._addCheck({
9827
- kind: "int",
9828
- message: errorUtil.toString(message)
9829
- });
9830
- }
9831
- positive(message) {
9832
- return this._addCheck({
9833
- kind: "min",
9834
- value: 0,
9835
- inclusive: false,
9836
- message: errorUtil.toString(message)
9837
- });
9838
- }
9839
- negative(message) {
9840
- return this._addCheck({
9841
- kind: "max",
9842
- value: 0,
9843
- inclusive: false,
9844
- message: errorUtil.toString(message)
9845
- });
9846
- }
9847
- nonpositive(message) {
9848
- return this._addCheck({
9849
- kind: "max",
9850
- value: 0,
9851
- inclusive: true,
9852
- message: errorUtil.toString(message)
9853
- });
9854
- }
9855
- nonnegative(message) {
9856
- return this._addCheck({
9857
- kind: "min",
9858
- value: 0,
9859
- inclusive: true,
9860
- message: errorUtil.toString(message)
9861
- });
9862
- }
9863
- multipleOf(value, message) {
9864
- return this._addCheck({
9865
- kind: "multipleOf",
9866
- value,
9867
- message: errorUtil.toString(message)
9868
- });
9869
- }
9870
- finite(message) {
9871
- return this._addCheck({
9872
- kind: "finite",
9873
- message: errorUtil.toString(message)
9874
- });
9875
- }
9876
- safe(message) {
9877
- return this._addCheck({
9878
- kind: "min",
9879
- inclusive: true,
9880
- value: Number.MIN_SAFE_INTEGER,
9881
- message: errorUtil.toString(message)
9882
- })._addCheck({
9883
- kind: "max",
9884
- inclusive: true,
9885
- value: Number.MAX_SAFE_INTEGER,
9886
- message: errorUtil.toString(message)
9887
- });
9888
- }
9889
- get minValue() {
9890
- let min = null;
9891
- for (const ch of this._def.checks) {
9892
- if (ch.kind === "min") {
9893
- if (min === null || ch.value > min)
9894
- min = ch.value;
9895
- }
9896
- }
9897
- return min;
9898
- }
9899
- get maxValue() {
9900
- let max = null;
9901
- for (const ch of this._def.checks) {
9902
- if (ch.kind === "max") {
9903
- if (max === null || ch.value < max)
9904
- max = ch.value;
9905
- }
9906
- }
9907
- return max;
9908
- }
9909
- get isInt() {
9910
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
9911
- }
9912
- get isFinite() {
9913
- let max = null;
9914
- let min = null;
9915
- for (const ch of this._def.checks) {
9916
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
9917
- return true;
9918
- } else if (ch.kind === "min") {
9919
- if (min === null || ch.value > min)
9920
- min = ch.value;
9921
- } else if (ch.kind === "max") {
9922
- if (max === null || ch.value < max)
9923
- max = ch.value;
9924
- }
9925
- }
9926
- return Number.isFinite(min) && Number.isFinite(max);
9927
- }
9928
- };
9929
- ZodNumber.create = (params) => {
9930
- return new ZodNumber({
9931
- checks: [],
9932
- typeName: ZodFirstPartyTypeKind.ZodNumber,
9933
- coerce: params?.coerce || false,
9934
- ...processCreateParams(params)
9935
- });
9936
- };
9937
- var ZodBigInt = class _ZodBigInt extends ZodType {
9938
- constructor() {
9939
- super(...arguments);
9940
- this.min = this.gte;
9941
- this.max = this.lte;
9942
- }
9943
- _parse(input) {
9944
- if (this._def.coerce) {
9945
- try {
9946
- input.data = BigInt(input.data);
9947
- } catch {
9948
- return this._getInvalidInput(input);
9949
- }
9950
- }
9951
- const parsedType = this._getType(input);
9952
- if (parsedType !== ZodParsedType.bigint) {
9953
- return this._getInvalidInput(input);
9954
- }
9955
- let ctx = void 0;
9956
- const status2 = new ParseStatus();
9957
- for (const check of this._def.checks) {
9958
- if (check.kind === "min") {
9959
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
9960
- if (tooSmall) {
9961
- ctx = this._getOrReturnCtx(input, ctx);
9962
- addIssueToContext(ctx, {
9963
- code: ZodIssueCode.too_small,
9964
- type: "bigint",
9965
- minimum: check.value,
9966
- inclusive: check.inclusive,
9967
- message: check.message
9968
- });
9969
- status2.dirty();
9970
- }
9971
- } else if (check.kind === "max") {
9972
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
9973
- if (tooBig) {
9974
- ctx = this._getOrReturnCtx(input, ctx);
9975
- addIssueToContext(ctx, {
9976
- code: ZodIssueCode.too_big,
9977
- type: "bigint",
9978
- maximum: check.value,
9979
- inclusive: check.inclusive,
9980
- message: check.message
9981
- });
9982
- status2.dirty();
9983
- }
9984
- } else if (check.kind === "multipleOf") {
9985
- if (input.data % check.value !== BigInt(0)) {
9986
- ctx = this._getOrReturnCtx(input, ctx);
9987
- addIssueToContext(ctx, {
9988
- code: ZodIssueCode.not_multiple_of,
9989
- multipleOf: check.value,
9990
- message: check.message
9991
- });
9992
- status2.dirty();
9993
- }
9994
- } else {
9995
- util.assertNever(check);
9996
- }
9997
- }
9998
- return { status: status2.value, value: input.data };
9999
- }
10000
- _getInvalidInput(input) {
10001
- const ctx = this._getOrReturnCtx(input);
10002
- addIssueToContext(ctx, {
10003
- code: ZodIssueCode.invalid_type,
10004
- expected: ZodParsedType.bigint,
10005
- received: ctx.parsedType
10006
- });
10007
- return INVALID;
10008
- }
10009
- gte(value, message) {
10010
- return this.setLimit("min", value, true, errorUtil.toString(message));
10011
- }
10012
- gt(value, message) {
10013
- return this.setLimit("min", value, false, errorUtil.toString(message));
10014
- }
10015
- lte(value, message) {
10016
- return this.setLimit("max", value, true, errorUtil.toString(message));
10017
- }
10018
- lt(value, message) {
10019
- return this.setLimit("max", value, false, errorUtil.toString(message));
10020
- }
10021
- setLimit(kind, value, inclusive, message) {
10022
- return new _ZodBigInt({
10023
- ...this._def,
10024
- checks: [
10025
- ...this._def.checks,
10026
- {
10027
- kind,
10028
- value,
10029
- inclusive,
10030
- message: errorUtil.toString(message)
10031
- }
10032
- ]
10033
- });
10034
- }
10035
- _addCheck(check) {
10036
- return new _ZodBigInt({
10037
- ...this._def,
10038
- checks: [...this._def.checks, check]
10039
- });
10040
- }
10041
- positive(message) {
10042
- return this._addCheck({
10043
- kind: "min",
10044
- value: BigInt(0),
10045
- inclusive: false,
10046
- message: errorUtil.toString(message)
10047
- });
10048
- }
10049
- negative(message) {
10050
- return this._addCheck({
10051
- kind: "max",
10052
- value: BigInt(0),
10053
- inclusive: false,
10054
- message: errorUtil.toString(message)
10055
- });
10056
- }
10057
- nonpositive(message) {
10058
- return this._addCheck({
10059
- kind: "max",
10060
- value: BigInt(0),
10061
- inclusive: true,
10062
- message: errorUtil.toString(message)
10063
- });
10064
- }
10065
- nonnegative(message) {
10066
- return this._addCheck({
10067
- kind: "min",
10068
- value: BigInt(0),
10069
- inclusive: true,
10070
- message: errorUtil.toString(message)
10071
- });
10072
- }
10073
- multipleOf(value, message) {
10074
- return this._addCheck({
10075
- kind: "multipleOf",
10076
- value,
10077
- message: errorUtil.toString(message)
10078
- });
10079
- }
10080
- get minValue() {
10081
- let min = null;
10082
- for (const ch of this._def.checks) {
10083
- if (ch.kind === "min") {
10084
- if (min === null || ch.value > min)
10085
- min = ch.value;
10086
- }
10087
- }
10088
- return min;
10089
- }
10090
- get maxValue() {
10091
- let max = null;
10092
- for (const ch of this._def.checks) {
10093
- if (ch.kind === "max") {
10094
- if (max === null || ch.value < max)
10095
- max = ch.value;
10096
- }
10097
- }
10098
- return max;
10099
- }
10100
- };
10101
- ZodBigInt.create = (params) => {
10102
- return new ZodBigInt({
10103
- checks: [],
10104
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
10105
- coerce: params?.coerce ?? false,
10106
- ...processCreateParams(params)
10107
- });
10108
- };
10109
- var ZodBoolean = class extends ZodType {
10110
- _parse(input) {
10111
- if (this._def.coerce) {
10112
- input.data = Boolean(input.data);
10113
- }
10114
- const parsedType = this._getType(input);
10115
- if (parsedType !== ZodParsedType.boolean) {
10116
- const ctx = this._getOrReturnCtx(input);
10117
- addIssueToContext(ctx, {
10118
- code: ZodIssueCode.invalid_type,
10119
- expected: ZodParsedType.boolean,
10120
- received: ctx.parsedType
10121
- });
10122
- return INVALID;
10123
- }
10124
- return OK(input.data);
10125
- }
10126
- };
10127
- ZodBoolean.create = (params) => {
10128
- return new ZodBoolean({
10129
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
10130
- coerce: params?.coerce || false,
10131
- ...processCreateParams(params)
10132
- });
10133
- };
10134
- var ZodDate = class _ZodDate extends ZodType {
10135
- _parse(input) {
10136
- if (this._def.coerce) {
10137
- input.data = new Date(input.data);
10138
- }
10139
- const parsedType = this._getType(input);
10140
- if (parsedType !== ZodParsedType.date) {
10141
- const ctx2 = this._getOrReturnCtx(input);
10142
- addIssueToContext(ctx2, {
10143
- code: ZodIssueCode.invalid_type,
10144
- expected: ZodParsedType.date,
10145
- received: ctx2.parsedType
10146
- });
10147
- return INVALID;
10148
- }
10149
- if (Number.isNaN(input.data.getTime())) {
10150
- const ctx2 = this._getOrReturnCtx(input);
10151
- addIssueToContext(ctx2, {
10152
- code: ZodIssueCode.invalid_date
10153
- });
10154
- return INVALID;
10155
- }
10156
- const status2 = new ParseStatus();
10157
- let ctx = void 0;
10158
- for (const check of this._def.checks) {
10159
- if (check.kind === "min") {
10160
- if (input.data.getTime() < check.value) {
10161
- ctx = this._getOrReturnCtx(input, ctx);
10162
- addIssueToContext(ctx, {
10163
- code: ZodIssueCode.too_small,
10164
- message: check.message,
10165
- inclusive: true,
10166
- exact: false,
10167
- minimum: check.value,
10168
- type: "date"
10169
- });
10170
- status2.dirty();
10171
- }
10172
- } else if (check.kind === "max") {
10173
- if (input.data.getTime() > check.value) {
10174
- ctx = this._getOrReturnCtx(input, ctx);
10175
- addIssueToContext(ctx, {
10176
- code: ZodIssueCode.too_big,
10177
- message: check.message,
10178
- inclusive: true,
10179
- exact: false,
10180
- maximum: check.value,
10181
- type: "date"
10182
- });
10183
- status2.dirty();
10184
- }
10185
- } else {
10186
- util.assertNever(check);
10187
- }
10188
- }
10189
- return {
10190
- status: status2.value,
10191
- value: new Date(input.data.getTime())
10192
- };
10193
- }
10194
- _addCheck(check) {
10195
- return new _ZodDate({
10196
- ...this._def,
10197
- checks: [...this._def.checks, check]
10198
- });
10199
- }
10200
- min(minDate, message) {
10201
- return this._addCheck({
10202
- kind: "min",
10203
- value: minDate.getTime(),
10204
- message: errorUtil.toString(message)
10205
- });
10206
- }
10207
- max(maxDate, message) {
10208
- return this._addCheck({
10209
- kind: "max",
10210
- value: maxDate.getTime(),
10211
- message: errorUtil.toString(message)
10212
- });
10213
- }
10214
- get minDate() {
10215
- let min = null;
10216
- for (const ch of this._def.checks) {
10217
- if (ch.kind === "min") {
10218
- if (min === null || ch.value > min)
10219
- min = ch.value;
10220
- }
10221
- }
10222
- return min != null ? new Date(min) : null;
10223
- }
10224
- get maxDate() {
10225
- let max = null;
10226
- for (const ch of this._def.checks) {
10227
- if (ch.kind === "max") {
10228
- if (max === null || ch.value < max)
10229
- max = ch.value;
10230
- }
10231
- }
10232
- return max != null ? new Date(max) : null;
10233
- }
10234
- };
10235
- ZodDate.create = (params) => {
10236
- return new ZodDate({
10237
- checks: [],
10238
- coerce: params?.coerce || false,
10239
- typeName: ZodFirstPartyTypeKind.ZodDate,
10240
- ...processCreateParams(params)
10241
- });
10242
- };
10243
- var ZodSymbol = class extends ZodType {
10244
- _parse(input) {
10245
- const parsedType = this._getType(input);
10246
- if (parsedType !== ZodParsedType.symbol) {
10247
- const ctx = this._getOrReturnCtx(input);
10248
- addIssueToContext(ctx, {
10249
- code: ZodIssueCode.invalid_type,
10250
- expected: ZodParsedType.symbol,
10251
- received: ctx.parsedType
10252
- });
10253
- return INVALID;
10254
- }
10255
- return OK(input.data);
10256
- }
10257
- };
10258
- ZodSymbol.create = (params) => {
10259
- return new ZodSymbol({
10260
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
10261
- ...processCreateParams(params)
10262
- });
10263
- };
10264
- var ZodUndefined = class extends ZodType {
10265
- _parse(input) {
10266
- const parsedType = this._getType(input);
10267
- if (parsedType !== ZodParsedType.undefined) {
10268
- const ctx = this._getOrReturnCtx(input);
10269
- addIssueToContext(ctx, {
10270
- code: ZodIssueCode.invalid_type,
10271
- expected: ZodParsedType.undefined,
10272
- received: ctx.parsedType
10273
- });
10274
- return INVALID;
10275
- }
10276
- return OK(input.data);
10277
- }
10278
- };
10279
- ZodUndefined.create = (params) => {
10280
- return new ZodUndefined({
10281
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
10282
- ...processCreateParams(params)
10283
- });
10284
- };
10285
- var ZodNull = class extends ZodType {
10286
- _parse(input) {
10287
- const parsedType = this._getType(input);
10288
- if (parsedType !== ZodParsedType.null) {
10289
- const ctx = this._getOrReturnCtx(input);
10290
- addIssueToContext(ctx, {
10291
- code: ZodIssueCode.invalid_type,
10292
- expected: ZodParsedType.null,
10293
- received: ctx.parsedType
10294
- });
10295
- return INVALID;
10296
- }
10297
- return OK(input.data);
10298
- }
10299
- };
10300
- ZodNull.create = (params) => {
10301
- return new ZodNull({
10302
- typeName: ZodFirstPartyTypeKind.ZodNull,
10303
- ...processCreateParams(params)
10304
- });
10305
- };
10306
- var ZodAny = class extends ZodType {
10307
- constructor() {
10308
- super(...arguments);
10309
- this._any = true;
10310
- }
10311
- _parse(input) {
10312
- return OK(input.data);
10313
- }
10314
- };
10315
- ZodAny.create = (params) => {
10316
- return new ZodAny({
10317
- typeName: ZodFirstPartyTypeKind.ZodAny,
10318
- ...processCreateParams(params)
10319
- });
10320
- };
10321
- var ZodUnknown = class extends ZodType {
10322
- constructor() {
10323
- super(...arguments);
10324
- this._unknown = true;
10325
- }
10326
- _parse(input) {
10327
- return OK(input.data);
10328
- }
10329
- };
10330
- ZodUnknown.create = (params) => {
10331
- return new ZodUnknown({
10332
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
10333
- ...processCreateParams(params)
10334
- });
10335
- };
10336
- var ZodNever = class extends ZodType {
10337
- _parse(input) {
10338
- const ctx = this._getOrReturnCtx(input);
10339
- addIssueToContext(ctx, {
10340
- code: ZodIssueCode.invalid_type,
10341
- expected: ZodParsedType.never,
10342
- received: ctx.parsedType
10343
- });
10344
- return INVALID;
10345
- }
10346
- };
10347
- ZodNever.create = (params) => {
10348
- return new ZodNever({
10349
- typeName: ZodFirstPartyTypeKind.ZodNever,
10350
- ...processCreateParams(params)
10351
- });
10352
- };
10353
- var ZodVoid = class extends ZodType {
10354
- _parse(input) {
10355
- const parsedType = this._getType(input);
10356
- if (parsedType !== ZodParsedType.undefined) {
10357
- const ctx = this._getOrReturnCtx(input);
10358
- addIssueToContext(ctx, {
10359
- code: ZodIssueCode.invalid_type,
10360
- expected: ZodParsedType.void,
10361
- received: ctx.parsedType
10362
- });
10363
- return INVALID;
10364
- }
10365
- return OK(input.data);
10366
- }
10367
- };
10368
- ZodVoid.create = (params) => {
10369
- return new ZodVoid({
10370
- typeName: ZodFirstPartyTypeKind.ZodVoid,
10371
- ...processCreateParams(params)
10372
- });
10373
- };
10374
- var ZodArray = class _ZodArray extends ZodType {
10375
- _parse(input) {
10376
- const { ctx, status: status2 } = this._processInputParams(input);
10377
- const def = this._def;
10378
- if (ctx.parsedType !== ZodParsedType.array) {
10379
- addIssueToContext(ctx, {
10380
- code: ZodIssueCode.invalid_type,
10381
- expected: ZodParsedType.array,
10382
- received: ctx.parsedType
10383
- });
10384
- return INVALID;
10385
- }
10386
- if (def.exactLength !== null) {
10387
- const tooBig = ctx.data.length > def.exactLength.value;
10388
- const tooSmall = ctx.data.length < def.exactLength.value;
10389
- if (tooBig || tooSmall) {
10390
- addIssueToContext(ctx, {
10391
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
10392
- minimum: tooSmall ? def.exactLength.value : void 0,
10393
- maximum: tooBig ? def.exactLength.value : void 0,
10394
- type: "array",
10395
- inclusive: true,
10396
- exact: true,
10397
- message: def.exactLength.message
10398
- });
10399
- status2.dirty();
10400
- }
10401
- }
10402
- if (def.minLength !== null) {
10403
- if (ctx.data.length < def.minLength.value) {
10404
- addIssueToContext(ctx, {
10405
- code: ZodIssueCode.too_small,
10406
- minimum: def.minLength.value,
10407
- type: "array",
10408
- inclusive: true,
10409
- exact: false,
10410
- message: def.minLength.message
10411
- });
10412
- status2.dirty();
10413
- }
10414
- }
10415
- if (def.maxLength !== null) {
10416
- if (ctx.data.length > def.maxLength.value) {
10417
- addIssueToContext(ctx, {
10418
- code: ZodIssueCode.too_big,
10419
- maximum: def.maxLength.value,
10420
- type: "array",
10421
- inclusive: true,
10422
- exact: false,
10423
- message: def.maxLength.message
10424
- });
10425
- status2.dirty();
10426
- }
10427
- }
10428
- if (ctx.common.async) {
10429
- return Promise.all([...ctx.data].map((item, i) => {
10430
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
10431
- })).then((result2) => {
10432
- return ParseStatus.mergeArray(status2, result2);
10433
- });
10434
- }
10435
- const result = [...ctx.data].map((item, i) => {
10436
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
10437
- });
10438
- return ParseStatus.mergeArray(status2, result);
10439
- }
10440
- get element() {
10441
- return this._def.type;
10442
- }
10443
- min(minLength, message) {
10444
- return new _ZodArray({
10445
- ...this._def,
10446
- minLength: { value: minLength, message: errorUtil.toString(message) }
10447
- });
10448
- }
10449
- max(maxLength, message) {
10450
- return new _ZodArray({
10451
- ...this._def,
10452
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
10453
- });
10454
- }
10455
- length(len, message) {
10456
- return new _ZodArray({
10457
- ...this._def,
10458
- exactLength: { value: len, message: errorUtil.toString(message) }
10459
- });
10460
- }
10461
- nonempty(message) {
10462
- return this.min(1, message);
10463
- }
10464
- };
10465
- ZodArray.create = (schema, params) => {
10466
- return new ZodArray({
10467
- type: schema,
10468
- minLength: null,
10469
- maxLength: null,
10470
- exactLength: null,
10471
- typeName: ZodFirstPartyTypeKind.ZodArray,
10472
- ...processCreateParams(params)
10473
- });
10474
- };
10475
- function deepPartialify(schema) {
10476
- if (schema instanceof ZodObject) {
10477
- const newShape = {};
10478
- for (const key in schema.shape) {
10479
- const fieldSchema = schema.shape[key];
10480
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
10481
- }
10482
- return new ZodObject({
10483
- ...schema._def,
10484
- shape: () => newShape
10485
- });
10486
- } else if (schema instanceof ZodArray) {
10487
- return new ZodArray({
10488
- ...schema._def,
10489
- type: deepPartialify(schema.element)
10490
- });
10491
- } else if (schema instanceof ZodOptional) {
10492
- return ZodOptional.create(deepPartialify(schema.unwrap()));
10493
- } else if (schema instanceof ZodNullable) {
10494
- return ZodNullable.create(deepPartialify(schema.unwrap()));
10495
- } else if (schema instanceof ZodTuple) {
10496
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
10497
- } else {
10498
- return schema;
10499
- }
10500
- }
10501
- var ZodObject = class _ZodObject extends ZodType {
10502
- constructor() {
10503
- super(...arguments);
10504
- this._cached = null;
10505
- this.nonstrict = this.passthrough;
10506
- this.augment = this.extend;
10507
- }
10508
- _getCached() {
10509
- if (this._cached !== null)
10510
- return this._cached;
10511
- const shape = this._def.shape();
10512
- const keys = util.objectKeys(shape);
10513
- this._cached = { shape, keys };
10514
- return this._cached;
10515
- }
10516
- _parse(input) {
10517
- const parsedType = this._getType(input);
10518
- if (parsedType !== ZodParsedType.object) {
10519
- const ctx2 = this._getOrReturnCtx(input);
10520
- addIssueToContext(ctx2, {
10521
- code: ZodIssueCode.invalid_type,
10522
- expected: ZodParsedType.object,
10523
- received: ctx2.parsedType
10524
- });
10525
- return INVALID;
10526
- }
10527
- const { status: status2, ctx } = this._processInputParams(input);
10528
- const { shape, keys: shapeKeys } = this._getCached();
10529
- const extraKeys = [];
10530
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
10531
- for (const key in ctx.data) {
10532
- if (!shapeKeys.includes(key)) {
10533
- extraKeys.push(key);
10534
- }
10535
- }
10536
- }
10537
- const pairs = [];
10538
- for (const key of shapeKeys) {
10539
- const keyValidator = shape[key];
10540
- const value = ctx.data[key];
10541
- pairs.push({
10542
- key: { status: "valid", value: key },
10543
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
10544
- alwaysSet: key in ctx.data
10545
- });
10546
- }
10547
- if (this._def.catchall instanceof ZodNever) {
10548
- const unknownKeys = this._def.unknownKeys;
10549
- if (unknownKeys === "passthrough") {
10550
- for (const key of extraKeys) {
10551
- pairs.push({
10552
- key: { status: "valid", value: key },
10553
- value: { status: "valid", value: ctx.data[key] }
10554
- });
10555
- }
10556
- } else if (unknownKeys === "strict") {
10557
- if (extraKeys.length > 0) {
10558
- addIssueToContext(ctx, {
10559
- code: ZodIssueCode.unrecognized_keys,
10560
- keys: extraKeys
10561
- });
10562
- status2.dirty();
10563
- }
10564
- } else if (unknownKeys === "strip") {
10565
- } else {
10566
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
10567
- }
10568
- } else {
10569
- const catchall = this._def.catchall;
10570
- for (const key of extraKeys) {
10571
- const value = ctx.data[key];
10572
- pairs.push({
10573
- key: { status: "valid", value: key },
10574
- value: catchall._parse(
10575
- new ParseInputLazyPath(ctx, value, ctx.path, key)
10576
- //, ctx.child(key), value, getParsedType(value)
10577
- ),
10578
- alwaysSet: key in ctx.data
10579
- });
10580
- }
10581
- }
10582
- if (ctx.common.async) {
10583
- return Promise.resolve().then(async () => {
10584
- const syncPairs = [];
10585
- for (const pair of pairs) {
10586
- const key = await pair.key;
10587
- const value = await pair.value;
10588
- syncPairs.push({
10589
- key,
10590
- value,
10591
- alwaysSet: pair.alwaysSet
10592
- });
10593
- }
10594
- return syncPairs;
10595
- }).then((syncPairs) => {
10596
- return ParseStatus.mergeObjectSync(status2, syncPairs);
10597
- });
10598
- } else {
10599
- return ParseStatus.mergeObjectSync(status2, pairs);
10600
- }
10601
- }
10602
- get shape() {
10603
- return this._def.shape();
10604
- }
10605
- strict(message) {
10606
- errorUtil.errToObj;
10607
- return new _ZodObject({
10608
- ...this._def,
10609
- unknownKeys: "strict",
10610
- ...message !== void 0 ? {
10611
- errorMap: (issue, ctx) => {
10612
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
10613
- if (issue.code === "unrecognized_keys")
10614
- return {
10615
- message: errorUtil.errToObj(message).message ?? defaultError
10616
- };
10617
- return {
10618
- message: defaultError
10619
- };
10620
- }
10621
- } : {}
10622
- });
10623
- }
10624
- strip() {
10625
- return new _ZodObject({
10626
- ...this._def,
10627
- unknownKeys: "strip"
10628
- });
10629
- }
10630
- passthrough() {
10631
- return new _ZodObject({
10632
- ...this._def,
10633
- unknownKeys: "passthrough"
10634
- });
10635
- }
10636
- // const AugmentFactory =
10637
- // <Def extends ZodObjectDef>(def: Def) =>
10638
- // <Augmentation extends ZodRawShape>(
10639
- // augmentation: Augmentation
10640
- // ): ZodObject<
10641
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
10642
- // Def["unknownKeys"],
10643
- // Def["catchall"]
10644
- // > => {
10645
- // return new ZodObject({
10646
- // ...def,
10647
- // shape: () => ({
10648
- // ...def.shape(),
10649
- // ...augmentation,
10650
- // }),
10651
- // }) as any;
10652
- // };
10653
- extend(augmentation) {
10654
- return new _ZodObject({
10655
- ...this._def,
10656
- shape: () => ({
10657
- ...this._def.shape(),
10658
- ...augmentation
10659
- })
10660
- });
10661
- }
10662
- /**
10663
- * Prior to zod@1.0.12 there was a bug in the
10664
- * inferred type of merged objects. Please
10665
- * upgrade if you are experiencing issues.
10666
- */
10667
- merge(merging) {
10668
- const merged = new _ZodObject({
10669
- unknownKeys: merging._def.unknownKeys,
10670
- catchall: merging._def.catchall,
10671
- shape: () => ({
10672
- ...this._def.shape(),
10673
- ...merging._def.shape()
10674
- }),
10675
- typeName: ZodFirstPartyTypeKind.ZodObject
10676
- });
10677
- return merged;
10678
- }
10679
- // merge<
10680
- // Incoming extends AnyZodObject,
10681
- // Augmentation extends Incoming["shape"],
10682
- // NewOutput extends {
10683
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
10684
- // ? Augmentation[k]["_output"]
10685
- // : k extends keyof Output
10686
- // ? Output[k]
10687
- // : never;
10688
- // },
10689
- // NewInput extends {
10690
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
10691
- // ? Augmentation[k]["_input"]
10692
- // : k extends keyof Input
10693
- // ? Input[k]
10694
- // : never;
10695
- // }
10696
- // >(
10697
- // merging: Incoming
10698
- // ): ZodObject<
10699
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
10700
- // Incoming["_def"]["unknownKeys"],
10701
- // Incoming["_def"]["catchall"],
10702
- // NewOutput,
10703
- // NewInput
10704
- // > {
10705
- // const merged: any = new ZodObject({
10706
- // unknownKeys: merging._def.unknownKeys,
10707
- // catchall: merging._def.catchall,
10708
- // shape: () =>
10709
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
10710
- // typeName: ZodFirstPartyTypeKind.ZodObject,
10711
- // }) as any;
10712
- // return merged;
10713
- // }
10714
- setKey(key, schema) {
10715
- return this.augment({ [key]: schema });
10716
- }
10717
- // merge<Incoming extends AnyZodObject>(
10718
- // merging: Incoming
10719
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
10720
- // ZodObject<
10721
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
10722
- // Incoming["_def"]["unknownKeys"],
10723
- // Incoming["_def"]["catchall"]
10724
- // > {
10725
- // // const mergedShape = objectUtil.mergeShapes(
10726
- // // this._def.shape(),
10727
- // // merging._def.shape()
10728
- // // );
10729
- // const merged: any = new ZodObject({
10730
- // unknownKeys: merging._def.unknownKeys,
10731
- // catchall: merging._def.catchall,
10732
- // shape: () =>
10733
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
10734
- // typeName: ZodFirstPartyTypeKind.ZodObject,
10735
- // }) as any;
10736
- // return merged;
10737
- // }
10738
- catchall(index) {
10739
- return new _ZodObject({
10740
- ...this._def,
10741
- catchall: index
10742
- });
10743
- }
10744
- pick(mask) {
10745
- const shape = {};
10746
- for (const key of util.objectKeys(mask)) {
10747
- if (mask[key] && this.shape[key]) {
10748
- shape[key] = this.shape[key];
10749
- }
10750
- }
10751
- return new _ZodObject({
10752
- ...this._def,
10753
- shape: () => shape
10754
- });
10755
- }
10756
- omit(mask) {
10757
- const shape = {};
10758
- for (const key of util.objectKeys(this.shape)) {
10759
- if (!mask[key]) {
10760
- shape[key] = this.shape[key];
10761
- }
10762
- }
10763
- return new _ZodObject({
10764
- ...this._def,
10765
- shape: () => shape
10766
- });
10767
- }
10768
- /**
10769
- * @deprecated
10770
- */
10771
- deepPartial() {
10772
- return deepPartialify(this);
10773
- }
10774
- partial(mask) {
10775
- const newShape = {};
10776
- for (const key of util.objectKeys(this.shape)) {
10777
- const fieldSchema = this.shape[key];
10778
- if (mask && !mask[key]) {
10779
- newShape[key] = fieldSchema;
10780
- } else {
10781
- newShape[key] = fieldSchema.optional();
10782
- }
10783
- }
10784
- return new _ZodObject({
10785
- ...this._def,
10786
- shape: () => newShape
10787
- });
10788
- }
10789
- required(mask) {
10790
- const newShape = {};
10791
- for (const key of util.objectKeys(this.shape)) {
10792
- if (mask && !mask[key]) {
10793
- newShape[key] = this.shape[key];
10794
- } else {
10795
- const fieldSchema = this.shape[key];
10796
- let newField = fieldSchema;
10797
- while (newField instanceof ZodOptional) {
10798
- newField = newField._def.innerType;
10799
- }
10800
- newShape[key] = newField;
10801
- }
10802
- }
10803
- return new _ZodObject({
10804
- ...this._def,
10805
- shape: () => newShape
10806
- });
10807
- }
10808
- keyof() {
10809
- return createZodEnum(util.objectKeys(this.shape));
10810
- }
10811
- };
10812
- ZodObject.create = (shape, params) => {
10813
- return new ZodObject({
10814
- shape: () => shape,
10815
- unknownKeys: "strip",
10816
- catchall: ZodNever.create(),
10817
- typeName: ZodFirstPartyTypeKind.ZodObject,
10818
- ...processCreateParams(params)
10819
- });
10820
- };
10821
- ZodObject.strictCreate = (shape, params) => {
10822
- return new ZodObject({
10823
- shape: () => shape,
10824
- unknownKeys: "strict",
10825
- catchall: ZodNever.create(),
10826
- typeName: ZodFirstPartyTypeKind.ZodObject,
10827
- ...processCreateParams(params)
10828
- });
10829
- };
10830
- ZodObject.lazycreate = (shape, params) => {
10831
- return new ZodObject({
10832
- shape,
10833
- unknownKeys: "strip",
10834
- catchall: ZodNever.create(),
10835
- typeName: ZodFirstPartyTypeKind.ZodObject,
10836
- ...processCreateParams(params)
10837
- });
10838
- };
10839
- var ZodUnion = class extends ZodType {
10840
- _parse(input) {
10841
- const { ctx } = this._processInputParams(input);
10842
- const options = this._def.options;
10843
- function handleResults(results) {
10844
- for (const result of results) {
10845
- if (result.result.status === "valid") {
10846
- return result.result;
10847
- }
10848
- }
10849
- for (const result of results) {
10850
- if (result.result.status === "dirty") {
10851
- ctx.common.issues.push(...result.ctx.common.issues);
10852
- return result.result;
10853
- }
10854
- }
10855
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
10856
- addIssueToContext(ctx, {
10857
- code: ZodIssueCode.invalid_union,
10858
- unionErrors
10859
- });
10860
- return INVALID;
10861
- }
10862
- if (ctx.common.async) {
10863
- return Promise.all(options.map(async (option) => {
10864
- const childCtx = {
10865
- ...ctx,
10866
- common: {
10867
- ...ctx.common,
10868
- issues: []
10869
- },
10870
- parent: null
10871
- };
10872
- return {
10873
- result: await option._parseAsync({
10874
- data: ctx.data,
10875
- path: ctx.path,
10876
- parent: childCtx
10877
- }),
10878
- ctx: childCtx
10879
- };
10880
- })).then(handleResults);
10881
- } else {
10882
- let dirty = void 0;
10883
- const issues = [];
10884
- for (const option of options) {
10885
- const childCtx = {
10886
- ...ctx,
10887
- common: {
10888
- ...ctx.common,
10889
- issues: []
10890
- },
10891
- parent: null
10892
- };
10893
- const result = option._parseSync({
10894
- data: ctx.data,
10895
- path: ctx.path,
10896
- parent: childCtx
10897
- });
10898
- if (result.status === "valid") {
10899
- return result;
10900
- } else if (result.status === "dirty" && !dirty) {
10901
- dirty = { result, ctx: childCtx };
10902
- }
10903
- if (childCtx.common.issues.length) {
10904
- issues.push(childCtx.common.issues);
10905
- }
10906
- }
10907
- if (dirty) {
10908
- ctx.common.issues.push(...dirty.ctx.common.issues);
10909
- return dirty.result;
10910
- }
10911
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
10912
- addIssueToContext(ctx, {
10913
- code: ZodIssueCode.invalid_union,
10914
- unionErrors
10915
- });
10916
- return INVALID;
10917
- }
10918
- }
10919
- get options() {
10920
- return this._def.options;
10921
- }
10922
- };
10923
- ZodUnion.create = (types, params) => {
10924
- return new ZodUnion({
10925
- options: types,
10926
- typeName: ZodFirstPartyTypeKind.ZodUnion,
10927
- ...processCreateParams(params)
10928
- });
10929
- };
10930
- var getDiscriminator = (type) => {
10931
- if (type instanceof ZodLazy) {
10932
- return getDiscriminator(type.schema);
10933
- } else if (type instanceof ZodEffects) {
10934
- return getDiscriminator(type.innerType());
10935
- } else if (type instanceof ZodLiteral) {
10936
- return [type.value];
10937
- } else if (type instanceof ZodEnum) {
10938
- return type.options;
10939
- } else if (type instanceof ZodNativeEnum) {
10940
- return util.objectValues(type.enum);
10941
- } else if (type instanceof ZodDefault) {
10942
- return getDiscriminator(type._def.innerType);
10943
- } else if (type instanceof ZodUndefined) {
10944
- return [void 0];
10945
- } else if (type instanceof ZodNull) {
10946
- return [null];
10947
- } else if (type instanceof ZodOptional) {
10948
- return [void 0, ...getDiscriminator(type.unwrap())];
10949
- } else if (type instanceof ZodNullable) {
10950
- return [null, ...getDiscriminator(type.unwrap())];
10951
- } else if (type instanceof ZodBranded) {
10952
- return getDiscriminator(type.unwrap());
10953
- } else if (type instanceof ZodReadonly) {
10954
- return getDiscriminator(type.unwrap());
10955
- } else if (type instanceof ZodCatch) {
10956
- return getDiscriminator(type._def.innerType);
10957
- } else {
10958
- return [];
10959
- }
10960
- };
10961
- var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
10962
- _parse(input) {
10963
- const { ctx } = this._processInputParams(input);
10964
- if (ctx.parsedType !== ZodParsedType.object) {
10965
- addIssueToContext(ctx, {
10966
- code: ZodIssueCode.invalid_type,
10967
- expected: ZodParsedType.object,
10968
- received: ctx.parsedType
10969
- });
10970
- return INVALID;
10971
- }
10972
- const discriminator = this.discriminator;
10973
- const discriminatorValue = ctx.data[discriminator];
10974
- const option = this.optionsMap.get(discriminatorValue);
10975
- if (!option) {
10976
- addIssueToContext(ctx, {
10977
- code: ZodIssueCode.invalid_union_discriminator,
10978
- options: Array.from(this.optionsMap.keys()),
10979
- path: [discriminator]
10980
- });
10981
- return INVALID;
10982
- }
10983
- if (ctx.common.async) {
10984
- return option._parseAsync({
10985
- data: ctx.data,
10986
- path: ctx.path,
10987
- parent: ctx
10988
- });
10989
- } else {
10990
- return option._parseSync({
10991
- data: ctx.data,
10992
- path: ctx.path,
10993
- parent: ctx
10994
- });
10995
- }
10996
- }
10997
- get discriminator() {
10998
- return this._def.discriminator;
10999
- }
11000
- get options() {
11001
- return this._def.options;
11002
- }
11003
- get optionsMap() {
11004
- return this._def.optionsMap;
11005
- }
11006
- /**
11007
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
11008
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
11009
- * have a different value for each object in the union.
11010
- * @param discriminator the name of the discriminator property
11011
- * @param types an array of object schemas
11012
- * @param params
11013
- */
11014
- static create(discriminator, options, params) {
11015
- const optionsMap = /* @__PURE__ */ new Map();
11016
- for (const type of options) {
11017
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
11018
- if (!discriminatorValues.length) {
11019
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
11020
- }
11021
- for (const value of discriminatorValues) {
11022
- if (optionsMap.has(value)) {
11023
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
11024
- }
11025
- optionsMap.set(value, type);
11026
- }
11027
- }
11028
- return new _ZodDiscriminatedUnion({
11029
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
11030
- discriminator,
11031
- options,
11032
- optionsMap,
11033
- ...processCreateParams(params)
11034
- });
11035
- }
11036
- };
11037
- function mergeValues(a, b2) {
11038
- const aType = getParsedType(a);
11039
- const bType = getParsedType(b2);
11040
- if (a === b2) {
11041
- return { valid: true, data: a };
11042
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
11043
- const bKeys = util.objectKeys(b2);
11044
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
11045
- const newObj = { ...a, ...b2 };
11046
- for (const key of sharedKeys) {
11047
- const sharedValue = mergeValues(a[key], b2[key]);
11048
- if (!sharedValue.valid) {
11049
- return { valid: false };
11050
- }
11051
- newObj[key] = sharedValue.data;
11052
- }
11053
- return { valid: true, data: newObj };
11054
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
11055
- if (a.length !== b2.length) {
11056
- return { valid: false };
11057
- }
11058
- const newArray = [];
11059
- for (let index = 0; index < a.length; index++) {
11060
- const itemA = a[index];
11061
- const itemB = b2[index];
11062
- const sharedValue = mergeValues(itemA, itemB);
11063
- if (!sharedValue.valid) {
11064
- return { valid: false };
11065
- }
11066
- newArray.push(sharedValue.data);
11067
- }
11068
- return { valid: true, data: newArray };
11069
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b2) {
11070
- return { valid: true, data: a };
11071
- } else {
11072
- return { valid: false };
11073
- }
11074
- }
11075
- var ZodIntersection = class extends ZodType {
11076
- _parse(input) {
11077
- const { status: status2, ctx } = this._processInputParams(input);
11078
- const handleParsed = (parsedLeft, parsedRight) => {
11079
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
11080
- return INVALID;
11081
- }
11082
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
11083
- if (!merged.valid) {
11084
- addIssueToContext(ctx, {
11085
- code: ZodIssueCode.invalid_intersection_types
11086
- });
11087
- return INVALID;
11088
- }
11089
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
11090
- status2.dirty();
11091
- }
11092
- return { status: status2.value, value: merged.data };
11093
- };
11094
- if (ctx.common.async) {
11095
- return Promise.all([
11096
- this._def.left._parseAsync({
11097
- data: ctx.data,
11098
- path: ctx.path,
11099
- parent: ctx
11100
- }),
11101
- this._def.right._parseAsync({
11102
- data: ctx.data,
11103
- path: ctx.path,
11104
- parent: ctx
11105
- })
11106
- ]).then(([left, right]) => handleParsed(left, right));
11107
- } else {
11108
- return handleParsed(this._def.left._parseSync({
11109
- data: ctx.data,
11110
- path: ctx.path,
11111
- parent: ctx
11112
- }), this._def.right._parseSync({
11113
- data: ctx.data,
11114
- path: ctx.path,
11115
- parent: ctx
11116
- }));
11117
- }
11118
- }
11119
- };
11120
- ZodIntersection.create = (left, right, params) => {
11121
- return new ZodIntersection({
11122
- left,
11123
- right,
11124
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
11125
- ...processCreateParams(params)
11126
- });
11127
- };
11128
- var ZodTuple = class _ZodTuple extends ZodType {
11129
- _parse(input) {
11130
- const { status: status2, ctx } = this._processInputParams(input);
11131
- if (ctx.parsedType !== ZodParsedType.array) {
11132
- addIssueToContext(ctx, {
11133
- code: ZodIssueCode.invalid_type,
11134
- expected: ZodParsedType.array,
11135
- received: ctx.parsedType
11136
- });
11137
- return INVALID;
11138
- }
11139
- if (ctx.data.length < this._def.items.length) {
11140
- addIssueToContext(ctx, {
11141
- code: ZodIssueCode.too_small,
11142
- minimum: this._def.items.length,
11143
- inclusive: true,
11144
- exact: false,
11145
- type: "array"
11146
- });
11147
- return INVALID;
11148
- }
11149
- const rest = this._def.rest;
11150
- if (!rest && ctx.data.length > this._def.items.length) {
11151
- addIssueToContext(ctx, {
11152
- code: ZodIssueCode.too_big,
11153
- maximum: this._def.items.length,
11154
- inclusive: true,
11155
- exact: false,
11156
- type: "array"
11157
- });
11158
- status2.dirty();
11159
- }
11160
- const items = [...ctx.data].map((item, itemIndex) => {
11161
- const schema = this._def.items[itemIndex] || this._def.rest;
11162
- if (!schema)
11163
- return null;
11164
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
11165
- }).filter((x) => !!x);
11166
- if (ctx.common.async) {
11167
- return Promise.all(items).then((results) => {
11168
- return ParseStatus.mergeArray(status2, results);
11169
- });
11170
- } else {
11171
- return ParseStatus.mergeArray(status2, items);
11172
- }
11173
- }
11174
- get items() {
11175
- return this._def.items;
11176
- }
11177
- rest(rest) {
11178
- return new _ZodTuple({
11179
- ...this._def,
11180
- rest
11181
- });
11182
- }
11183
- };
11184
- ZodTuple.create = (schemas, params) => {
11185
- if (!Array.isArray(schemas)) {
11186
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
11187
- }
11188
- return new ZodTuple({
11189
- items: schemas,
11190
- typeName: ZodFirstPartyTypeKind.ZodTuple,
11191
- rest: null,
11192
- ...processCreateParams(params)
11193
- });
11194
- };
11195
- var ZodRecord = class _ZodRecord extends ZodType {
11196
- get keySchema() {
11197
- return this._def.keyType;
11198
- }
11199
- get valueSchema() {
11200
- return this._def.valueType;
11201
- }
11202
- _parse(input) {
11203
- const { status: status2, ctx } = this._processInputParams(input);
11204
- if (ctx.parsedType !== ZodParsedType.object) {
11205
- addIssueToContext(ctx, {
11206
- code: ZodIssueCode.invalid_type,
11207
- expected: ZodParsedType.object,
11208
- received: ctx.parsedType
11209
- });
11210
- return INVALID;
11211
- }
11212
- const pairs = [];
11213
- const keyType = this._def.keyType;
11214
- const valueType = this._def.valueType;
11215
- for (const key in ctx.data) {
11216
- pairs.push({
11217
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
11218
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
11219
- alwaysSet: key in ctx.data
11220
- });
11221
- }
11222
- if (ctx.common.async) {
11223
- return ParseStatus.mergeObjectAsync(status2, pairs);
11224
- } else {
11225
- return ParseStatus.mergeObjectSync(status2, pairs);
11226
- }
11227
- }
11228
- get element() {
11229
- return this._def.valueType;
11230
- }
11231
- static create(first, second, third) {
11232
- if (second instanceof ZodType) {
11233
- return new _ZodRecord({
11234
- keyType: first,
11235
- valueType: second,
11236
- typeName: ZodFirstPartyTypeKind.ZodRecord,
11237
- ...processCreateParams(third)
11238
- });
11239
- }
11240
- return new _ZodRecord({
11241
- keyType: ZodString.create(),
11242
- valueType: first,
11243
- typeName: ZodFirstPartyTypeKind.ZodRecord,
11244
- ...processCreateParams(second)
11245
- });
11246
- }
11247
- };
11248
- var ZodMap = class extends ZodType {
11249
- get keySchema() {
11250
- return this._def.keyType;
11251
- }
11252
- get valueSchema() {
11253
- return this._def.valueType;
11254
- }
11255
- _parse(input) {
11256
- const { status: status2, ctx } = this._processInputParams(input);
11257
- if (ctx.parsedType !== ZodParsedType.map) {
11258
- addIssueToContext(ctx, {
11259
- code: ZodIssueCode.invalid_type,
11260
- expected: ZodParsedType.map,
11261
- received: ctx.parsedType
11262
- });
11263
- return INVALID;
11264
- }
11265
- const keyType = this._def.keyType;
11266
- const valueType = this._def.valueType;
11267
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
11268
- return {
11269
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
11270
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
11271
- };
11272
- });
11273
- if (ctx.common.async) {
11274
- const finalMap = /* @__PURE__ */ new Map();
11275
- return Promise.resolve().then(async () => {
11276
- for (const pair of pairs) {
11277
- const key = await pair.key;
11278
- const value = await pair.value;
11279
- if (key.status === "aborted" || value.status === "aborted") {
11280
- return INVALID;
11281
- }
11282
- if (key.status === "dirty" || value.status === "dirty") {
11283
- status2.dirty();
11284
- }
11285
- finalMap.set(key.value, value.value);
11286
- }
11287
- return { status: status2.value, value: finalMap };
11288
- });
11289
- } else {
11290
- const finalMap = /* @__PURE__ */ new Map();
11291
- for (const pair of pairs) {
11292
- const key = pair.key;
11293
- const value = pair.value;
11294
- if (key.status === "aborted" || value.status === "aborted") {
11295
- return INVALID;
11296
- }
11297
- if (key.status === "dirty" || value.status === "dirty") {
11298
- status2.dirty();
11299
- }
11300
- finalMap.set(key.value, value.value);
11301
- }
11302
- return { status: status2.value, value: finalMap };
11303
- }
11304
- }
11305
- };
11306
- ZodMap.create = (keyType, valueType, params) => {
11307
- return new ZodMap({
11308
- valueType,
11309
- keyType,
11310
- typeName: ZodFirstPartyTypeKind.ZodMap,
11311
- ...processCreateParams(params)
11312
- });
11313
- };
11314
- var ZodSet = class _ZodSet extends ZodType {
11315
- _parse(input) {
11316
- const { status: status2, ctx } = this._processInputParams(input);
11317
- if (ctx.parsedType !== ZodParsedType.set) {
11318
- addIssueToContext(ctx, {
11319
- code: ZodIssueCode.invalid_type,
11320
- expected: ZodParsedType.set,
11321
- received: ctx.parsedType
11322
- });
11323
- return INVALID;
11324
- }
11325
- const def = this._def;
11326
- if (def.minSize !== null) {
11327
- if (ctx.data.size < def.minSize.value) {
11328
- addIssueToContext(ctx, {
11329
- code: ZodIssueCode.too_small,
11330
- minimum: def.minSize.value,
11331
- type: "set",
11332
- inclusive: true,
11333
- exact: false,
11334
- message: def.minSize.message
11335
- });
11336
- status2.dirty();
11337
- }
11338
- }
11339
- if (def.maxSize !== null) {
11340
- if (ctx.data.size > def.maxSize.value) {
11341
- addIssueToContext(ctx, {
11342
- code: ZodIssueCode.too_big,
11343
- maximum: def.maxSize.value,
11344
- type: "set",
11345
- inclusive: true,
11346
- exact: false,
11347
- message: def.maxSize.message
11348
- });
11349
- status2.dirty();
11350
- }
11351
- }
11352
- const valueType = this._def.valueType;
11353
- function finalizeSet(elements2) {
11354
- const parsedSet = /* @__PURE__ */ new Set();
11355
- for (const element of elements2) {
11356
- if (element.status === "aborted")
11357
- return INVALID;
11358
- if (element.status === "dirty")
11359
- status2.dirty();
11360
- parsedSet.add(element.value);
11361
- }
11362
- return { status: status2.value, value: parsedSet };
11363
- }
11364
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
11365
- if (ctx.common.async) {
11366
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
11367
- } else {
11368
- return finalizeSet(elements);
11369
- }
11370
- }
11371
- min(minSize, message) {
11372
- return new _ZodSet({
11373
- ...this._def,
11374
- minSize: { value: minSize, message: errorUtil.toString(message) }
11375
- });
11376
- }
11377
- max(maxSize, message) {
11378
- return new _ZodSet({
11379
- ...this._def,
11380
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
11381
- });
11382
- }
11383
- size(size, message) {
11384
- return this.min(size, message).max(size, message);
11385
- }
11386
- nonempty(message) {
11387
- return this.min(1, message);
11388
- }
11389
- };
11390
- ZodSet.create = (valueType, params) => {
11391
- return new ZodSet({
11392
- valueType,
11393
- minSize: null,
11394
- maxSize: null,
11395
- typeName: ZodFirstPartyTypeKind.ZodSet,
11396
- ...processCreateParams(params)
11397
- });
11398
- };
11399
- var ZodFunction = class _ZodFunction extends ZodType {
11400
- constructor() {
11401
- super(...arguments);
11402
- this.validate = this.implement;
11403
- }
11404
- _parse(input) {
11405
- const { ctx } = this._processInputParams(input);
11406
- if (ctx.parsedType !== ZodParsedType.function) {
11407
- addIssueToContext(ctx, {
11408
- code: ZodIssueCode.invalid_type,
11409
- expected: ZodParsedType.function,
11410
- received: ctx.parsedType
11411
- });
11412
- return INVALID;
11413
- }
11414
- function makeArgsIssue(args, error) {
11415
- return makeIssue({
11416
- data: args,
11417
- path: ctx.path,
11418
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
11419
- issueData: {
11420
- code: ZodIssueCode.invalid_arguments,
11421
- argumentsError: error
11422
- }
11423
- });
11424
- }
11425
- function makeReturnsIssue(returns, error) {
11426
- return makeIssue({
11427
- data: returns,
11428
- path: ctx.path,
11429
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
11430
- issueData: {
11431
- code: ZodIssueCode.invalid_return_type,
11432
- returnTypeError: error
11433
- }
11434
- });
11435
- }
11436
- const params = { errorMap: ctx.common.contextualErrorMap };
11437
- const fn = ctx.data;
11438
- if (this._def.returns instanceof ZodPromise) {
11439
- const me = this;
11440
- return OK(async function(...args) {
11441
- const error = new ZodError([]);
11442
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
11443
- error.addIssue(makeArgsIssue(args, e));
11444
- throw error;
11445
- });
11446
- const result = await Reflect.apply(fn, this, parsedArgs);
11447
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
11448
- error.addIssue(makeReturnsIssue(result, e));
11449
- throw error;
11450
- });
11451
- return parsedReturns;
11452
- });
11453
- } else {
11454
- const me = this;
11455
- return OK(function(...args) {
11456
- const parsedArgs = me._def.args.safeParse(args, params);
11457
- if (!parsedArgs.success) {
11458
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
11459
- }
11460
- const result = Reflect.apply(fn, this, parsedArgs.data);
11461
- const parsedReturns = me._def.returns.safeParse(result, params);
11462
- if (!parsedReturns.success) {
11463
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
11464
- }
11465
- return parsedReturns.data;
11466
- });
11467
- }
11468
- }
11469
- parameters() {
11470
- return this._def.args;
11471
- }
11472
- returnType() {
11473
- return this._def.returns;
11474
- }
11475
- args(...items) {
11476
- return new _ZodFunction({
11477
- ...this._def,
11478
- args: ZodTuple.create(items).rest(ZodUnknown.create())
11479
- });
11480
- }
11481
- returns(returnType) {
11482
- return new _ZodFunction({
11483
- ...this._def,
11484
- returns: returnType
11485
- });
11486
- }
11487
- implement(func) {
11488
- const validatedFunc = this.parse(func);
11489
- return validatedFunc;
11490
- }
11491
- strictImplement(func) {
11492
- const validatedFunc = this.parse(func);
11493
- return validatedFunc;
11494
- }
11495
- static create(args, returns, params) {
11496
- return new _ZodFunction({
11497
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
11498
- returns: returns || ZodUnknown.create(),
11499
- typeName: ZodFirstPartyTypeKind.ZodFunction,
11500
- ...processCreateParams(params)
11501
- });
11502
- }
11503
- };
11504
- var ZodLazy = class extends ZodType {
11505
- get schema() {
11506
- return this._def.getter();
11507
- }
11508
- _parse(input) {
11509
- const { ctx } = this._processInputParams(input);
11510
- const lazySchema = this._def.getter();
11511
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
11512
- }
11513
- };
11514
- ZodLazy.create = (getter, params) => {
11515
- return new ZodLazy({
11516
- getter,
11517
- typeName: ZodFirstPartyTypeKind.ZodLazy,
11518
- ...processCreateParams(params)
11519
- });
11520
- };
11521
- var ZodLiteral = class extends ZodType {
11522
- _parse(input) {
11523
- if (input.data !== this._def.value) {
11524
- const ctx = this._getOrReturnCtx(input);
11525
- addIssueToContext(ctx, {
11526
- received: ctx.data,
11527
- code: ZodIssueCode.invalid_literal,
11528
- expected: this._def.value
11529
- });
11530
- return INVALID;
11531
- }
11532
- return { status: "valid", value: input.data };
11533
- }
11534
- get value() {
11535
- return this._def.value;
11536
- }
11537
- };
11538
- ZodLiteral.create = (value, params) => {
11539
- return new ZodLiteral({
11540
- value,
11541
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
11542
- ...processCreateParams(params)
11543
- });
11544
- };
11545
- function createZodEnum(values, params) {
11546
- return new ZodEnum({
11547
- values,
11548
- typeName: ZodFirstPartyTypeKind.ZodEnum,
11549
- ...processCreateParams(params)
11550
- });
11551
- }
11552
- var ZodEnum = class _ZodEnum extends ZodType {
11553
- _parse(input) {
11554
- if (typeof input.data !== "string") {
11555
- const ctx = this._getOrReturnCtx(input);
11556
- const expectedValues = this._def.values;
11557
- addIssueToContext(ctx, {
11558
- expected: util.joinValues(expectedValues),
11559
- received: ctx.parsedType,
11560
- code: ZodIssueCode.invalid_type
11561
- });
11562
- return INVALID;
11563
- }
11564
- if (!this._cache) {
11565
- this._cache = new Set(this._def.values);
11566
- }
11567
- if (!this._cache.has(input.data)) {
11568
- const ctx = this._getOrReturnCtx(input);
11569
- const expectedValues = this._def.values;
11570
- addIssueToContext(ctx, {
11571
- received: ctx.data,
11572
- code: ZodIssueCode.invalid_enum_value,
11573
- options: expectedValues
11574
- });
11575
- return INVALID;
11576
- }
11577
- return OK(input.data);
11578
- }
11579
- get options() {
11580
- return this._def.values;
11581
- }
11582
- get enum() {
11583
- const enumValues = {};
11584
- for (const val of this._def.values) {
11585
- enumValues[val] = val;
11586
- }
11587
- return enumValues;
11588
- }
11589
- get Values() {
11590
- const enumValues = {};
11591
- for (const val of this._def.values) {
11592
- enumValues[val] = val;
11593
- }
11594
- return enumValues;
11595
- }
11596
- get Enum() {
11597
- const enumValues = {};
11598
- for (const val of this._def.values) {
11599
- enumValues[val] = val;
11600
- }
11601
- return enumValues;
11602
- }
11603
- extract(values, newDef = this._def) {
11604
- return _ZodEnum.create(values, {
11605
- ...this._def,
11606
- ...newDef
11607
- });
11608
- }
11609
- exclude(values, newDef = this._def) {
11610
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
11611
- ...this._def,
11612
- ...newDef
11613
- });
11614
- }
11615
- };
11616
- ZodEnum.create = createZodEnum;
11617
- var ZodNativeEnum = class extends ZodType {
11618
- _parse(input) {
11619
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
11620
- const ctx = this._getOrReturnCtx(input);
11621
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
11622
- const expectedValues = util.objectValues(nativeEnumValues);
11623
- addIssueToContext(ctx, {
11624
- expected: util.joinValues(expectedValues),
11625
- received: ctx.parsedType,
11626
- code: ZodIssueCode.invalid_type
11627
- });
11628
- return INVALID;
11629
- }
11630
- if (!this._cache) {
11631
- this._cache = new Set(util.getValidEnumValues(this._def.values));
11632
- }
11633
- if (!this._cache.has(input.data)) {
11634
- const expectedValues = util.objectValues(nativeEnumValues);
11635
- addIssueToContext(ctx, {
11636
- received: ctx.data,
11637
- code: ZodIssueCode.invalid_enum_value,
11638
- options: expectedValues
11639
- });
11640
- return INVALID;
11641
- }
11642
- return OK(input.data);
11643
- }
11644
- get enum() {
11645
- return this._def.values;
11646
- }
11647
- };
11648
- ZodNativeEnum.create = (values, params) => {
11649
- return new ZodNativeEnum({
11650
- values,
11651
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
11652
- ...processCreateParams(params)
11653
- });
11654
- };
11655
- var ZodPromise = class extends ZodType {
11656
- unwrap() {
11657
- return this._def.type;
11658
- }
11659
- _parse(input) {
11660
- const { ctx } = this._processInputParams(input);
11661
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
11662
- addIssueToContext(ctx, {
11663
- code: ZodIssueCode.invalid_type,
11664
- expected: ZodParsedType.promise,
11665
- received: ctx.parsedType
11666
- });
11667
- return INVALID;
11668
- }
11669
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
11670
- return OK(promisified.then((data) => {
11671
- return this._def.type.parseAsync(data, {
11672
- path: ctx.path,
11673
- errorMap: ctx.common.contextualErrorMap
11674
- });
11675
- }));
11676
- }
11677
- };
11678
- ZodPromise.create = (schema, params) => {
11679
- return new ZodPromise({
11680
- type: schema,
11681
- typeName: ZodFirstPartyTypeKind.ZodPromise,
11682
- ...processCreateParams(params)
11683
- });
11684
- };
11685
- var ZodEffects = class extends ZodType {
11686
- innerType() {
11687
- return this._def.schema;
11688
- }
11689
- sourceType() {
11690
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
11691
- }
11692
- _parse(input) {
11693
- const { status: status2, ctx } = this._processInputParams(input);
11694
- const effect = this._def.effect || null;
11695
- const checkCtx = {
11696
- addIssue: (arg) => {
11697
- addIssueToContext(ctx, arg);
11698
- if (arg.fatal) {
11699
- status2.abort();
11700
- } else {
11701
- status2.dirty();
11702
- }
11703
- },
11704
- get path() {
11705
- return ctx.path;
11706
- }
11707
- };
11708
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
11709
- if (effect.type === "preprocess") {
11710
- const processed = effect.transform(ctx.data, checkCtx);
11711
- if (ctx.common.async) {
11712
- return Promise.resolve(processed).then(async (processed2) => {
11713
- if (status2.value === "aborted")
11714
- return INVALID;
11715
- const result = await this._def.schema._parseAsync({
11716
- data: processed2,
11717
- path: ctx.path,
11718
- parent: ctx
11719
- });
11720
- if (result.status === "aborted")
11721
- return INVALID;
11722
- if (result.status === "dirty")
11723
- return DIRTY(result.value);
11724
- if (status2.value === "dirty")
11725
- return DIRTY(result.value);
11726
- return result;
11727
- });
11728
- } else {
11729
- if (status2.value === "aborted")
11730
- return INVALID;
11731
- const result = this._def.schema._parseSync({
11732
- data: processed,
11733
- path: ctx.path,
11734
- parent: ctx
11735
- });
11736
- if (result.status === "aborted")
11737
- return INVALID;
11738
- if (result.status === "dirty")
11739
- return DIRTY(result.value);
11740
- if (status2.value === "dirty")
11741
- return DIRTY(result.value);
11742
- return result;
11743
- }
11744
- }
11745
- if (effect.type === "refinement") {
11746
- const executeRefinement = (acc) => {
11747
- const result = effect.refinement(acc, checkCtx);
11748
- if (ctx.common.async) {
11749
- return Promise.resolve(result);
11750
- }
11751
- if (result instanceof Promise) {
11752
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
11753
- }
11754
- return acc;
11755
- };
11756
- if (ctx.common.async === false) {
11757
- const inner = this._def.schema._parseSync({
11758
- data: ctx.data,
11759
- path: ctx.path,
11760
- parent: ctx
11761
- });
11762
- if (inner.status === "aborted")
11763
- return INVALID;
11764
- if (inner.status === "dirty")
11765
- status2.dirty();
11766
- executeRefinement(inner.value);
11767
- return { status: status2.value, value: inner.value };
11768
- } else {
11769
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
11770
- if (inner.status === "aborted")
11771
- return INVALID;
11772
- if (inner.status === "dirty")
11773
- status2.dirty();
11774
- return executeRefinement(inner.value).then(() => {
11775
- return { status: status2.value, value: inner.value };
11776
- });
11777
- });
11778
- }
11779
- }
11780
- if (effect.type === "transform") {
11781
- if (ctx.common.async === false) {
11782
- const base = this._def.schema._parseSync({
11783
- data: ctx.data,
11784
- path: ctx.path,
11785
- parent: ctx
11786
- });
11787
- if (!isValid(base))
11788
- return INVALID;
11789
- const result = effect.transform(base.value, checkCtx);
11790
- if (result instanceof Promise) {
11791
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
11792
- }
11793
- return { status: status2.value, value: result };
11794
- } else {
11795
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
11796
- if (!isValid(base))
11797
- return INVALID;
11798
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
11799
- status: status2.value,
11800
- value: result
11801
- }));
11802
- });
11803
- }
11804
- }
11805
- util.assertNever(effect);
11806
- }
11807
- };
11808
- ZodEffects.create = (schema, effect, params) => {
11809
- return new ZodEffects({
11810
- schema,
11811
- typeName: ZodFirstPartyTypeKind.ZodEffects,
11812
- effect,
11813
- ...processCreateParams(params)
11814
- });
11815
- };
11816
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
11817
- return new ZodEffects({
11818
- schema,
11819
- effect: { type: "preprocess", transform: preprocess },
11820
- typeName: ZodFirstPartyTypeKind.ZodEffects,
11821
- ...processCreateParams(params)
11822
- });
11823
- };
11824
- var ZodOptional = class extends ZodType {
11825
- _parse(input) {
11826
- const parsedType = this._getType(input);
11827
- if (parsedType === ZodParsedType.undefined) {
11828
- return OK(void 0);
11829
- }
11830
- return this._def.innerType._parse(input);
11831
- }
11832
- unwrap() {
11833
- return this._def.innerType;
11834
- }
11835
- };
11836
- ZodOptional.create = (type, params) => {
11837
- return new ZodOptional({
11838
- innerType: type,
11839
- typeName: ZodFirstPartyTypeKind.ZodOptional,
11840
- ...processCreateParams(params)
11841
- });
11842
- };
11843
- var ZodNullable = class extends ZodType {
11844
- _parse(input) {
11845
- const parsedType = this._getType(input);
11846
- if (parsedType === ZodParsedType.null) {
11847
- return OK(null);
11848
- }
11849
- return this._def.innerType._parse(input);
11850
- }
11851
- unwrap() {
11852
- return this._def.innerType;
11853
- }
11854
- };
11855
- ZodNullable.create = (type, params) => {
11856
- return new ZodNullable({
11857
- innerType: type,
11858
- typeName: ZodFirstPartyTypeKind.ZodNullable,
11859
- ...processCreateParams(params)
11860
- });
11861
- };
11862
- var ZodDefault = class extends ZodType {
11863
- _parse(input) {
11864
- const { ctx } = this._processInputParams(input);
11865
- let data = ctx.data;
11866
- if (ctx.parsedType === ZodParsedType.undefined) {
11867
- data = this._def.defaultValue();
11868
- }
11869
- return this._def.innerType._parse({
11870
- data,
11871
- path: ctx.path,
11872
- parent: ctx
11873
- });
11874
- }
11875
- removeDefault() {
11876
- return this._def.innerType;
11877
- }
11878
- };
11879
- ZodDefault.create = (type, params) => {
11880
- return new ZodDefault({
11881
- innerType: type,
11882
- typeName: ZodFirstPartyTypeKind.ZodDefault,
11883
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
11884
- ...processCreateParams(params)
11885
- });
11886
- };
11887
- var ZodCatch = class extends ZodType {
11888
- _parse(input) {
11889
- const { ctx } = this._processInputParams(input);
11890
- const newCtx = {
11891
- ...ctx,
11892
- common: {
11893
- ...ctx.common,
11894
- issues: []
11895
- }
11896
- };
11897
- const result = this._def.innerType._parse({
11898
- data: newCtx.data,
11899
- path: newCtx.path,
11900
- parent: {
11901
- ...newCtx
11902
- }
11903
- });
11904
- if (isAsync(result)) {
11905
- return result.then((result2) => {
11906
- return {
11907
- status: "valid",
11908
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
11909
- get error() {
11910
- return new ZodError(newCtx.common.issues);
11911
- },
11912
- input: newCtx.data
11913
- })
11914
- };
11915
- });
11916
- } else {
11917
- return {
11918
- status: "valid",
11919
- value: result.status === "valid" ? result.value : this._def.catchValue({
11920
- get error() {
11921
- return new ZodError(newCtx.common.issues);
11922
- },
11923
- input: newCtx.data
11924
- })
11925
- };
11926
- }
11927
- }
11928
- removeCatch() {
11929
- return this._def.innerType;
11930
- }
11931
- };
11932
- ZodCatch.create = (type, params) => {
11933
- return new ZodCatch({
11934
- innerType: type,
11935
- typeName: ZodFirstPartyTypeKind.ZodCatch,
11936
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
11937
- ...processCreateParams(params)
11938
- });
11939
- };
11940
- var ZodNaN = class extends ZodType {
11941
- _parse(input) {
11942
- const parsedType = this._getType(input);
11943
- if (parsedType !== ZodParsedType.nan) {
11944
- const ctx = this._getOrReturnCtx(input);
11945
- addIssueToContext(ctx, {
11946
- code: ZodIssueCode.invalid_type,
11947
- expected: ZodParsedType.nan,
11948
- received: ctx.parsedType
11949
- });
11950
- return INVALID;
11951
- }
11952
- return { status: "valid", value: input.data };
11953
- }
11954
- };
11955
- ZodNaN.create = (params) => {
11956
- return new ZodNaN({
11957
- typeName: ZodFirstPartyTypeKind.ZodNaN,
11958
- ...processCreateParams(params)
11959
- });
11960
- };
11961
- var BRAND = /* @__PURE__ */ Symbol("zod_brand");
11962
- var ZodBranded = class extends ZodType {
11963
- _parse(input) {
11964
- const { ctx } = this._processInputParams(input);
11965
- const data = ctx.data;
11966
- return this._def.type._parse({
11967
- data,
11968
- path: ctx.path,
11969
- parent: ctx
11970
- });
11971
- }
11972
- unwrap() {
11973
- return this._def.type;
11974
- }
11975
- };
11976
- var ZodPipeline = class _ZodPipeline extends ZodType {
11977
- _parse(input) {
11978
- const { status: status2, ctx } = this._processInputParams(input);
11979
- if (ctx.common.async) {
11980
- const handleAsync = async () => {
11981
- const inResult = await this._def.in._parseAsync({
11982
- data: ctx.data,
11983
- path: ctx.path,
11984
- parent: ctx
11985
- });
11986
- if (inResult.status === "aborted")
11987
- return INVALID;
11988
- if (inResult.status === "dirty") {
11989
- status2.dirty();
11990
- return DIRTY(inResult.value);
11991
- } else {
11992
- return this._def.out._parseAsync({
11993
- data: inResult.value,
11994
- path: ctx.path,
11995
- parent: ctx
11996
- });
11997
- }
11998
- };
11999
- return handleAsync();
12000
- } else {
12001
- const inResult = this._def.in._parseSync({
12002
- data: ctx.data,
12003
- path: ctx.path,
12004
- parent: ctx
12005
- });
12006
- if (inResult.status === "aborted")
12007
- return INVALID;
12008
- if (inResult.status === "dirty") {
12009
- status2.dirty();
12010
- return {
12011
- status: "dirty",
12012
- value: inResult.value
12013
- };
12014
- } else {
12015
- return this._def.out._parseSync({
12016
- data: inResult.value,
12017
- path: ctx.path,
12018
- parent: ctx
12019
- });
12020
- }
12021
- }
12022
- }
12023
- static create(a, b2) {
12024
- return new _ZodPipeline({
12025
- in: a,
12026
- out: b2,
12027
- typeName: ZodFirstPartyTypeKind.ZodPipeline
12028
- });
12029
- }
12030
- };
12031
- var ZodReadonly = class extends ZodType {
12032
- _parse(input) {
12033
- const result = this._def.innerType._parse(input);
12034
- const freeze = (data) => {
12035
- if (isValid(data)) {
12036
- data.value = Object.freeze(data.value);
12037
- }
12038
- return data;
12039
- };
12040
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
12041
- }
12042
- unwrap() {
12043
- return this._def.innerType;
12044
- }
12045
- };
12046
- ZodReadonly.create = (type, params) => {
12047
- return new ZodReadonly({
12048
- innerType: type,
12049
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
12050
- ...processCreateParams(params)
12051
- });
12052
- };
12053
- function cleanParams(params, data) {
12054
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
12055
- const p2 = typeof p === "string" ? { message: p } : p;
12056
- return p2;
12057
- }
12058
- function custom(check, _params = {}, fatal) {
12059
- if (check)
12060
- return ZodAny.create().superRefine((data, ctx) => {
12061
- const r = check(data);
12062
- if (r instanceof Promise) {
12063
- return r.then((r2) => {
12064
- if (!r2) {
12065
- const params = cleanParams(_params, data);
12066
- const _fatal = params.fatal ?? fatal ?? true;
12067
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
12068
- }
12069
- });
12070
- }
12071
- if (!r) {
12072
- const params = cleanParams(_params, data);
12073
- const _fatal = params.fatal ?? fatal ?? true;
12074
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
12075
- }
12076
- return;
12077
- });
12078
- return ZodAny.create();
12079
- }
12080
- var late = {
12081
- object: ZodObject.lazycreate
12082
- };
12083
- var ZodFirstPartyTypeKind;
12084
- (function(ZodFirstPartyTypeKind2) {
12085
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
12086
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
12087
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
12088
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
12089
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
12090
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
12091
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
12092
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
12093
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
12094
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
12095
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
12096
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
12097
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
12098
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
12099
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
12100
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
12101
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
12102
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
12103
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
12104
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
12105
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
12106
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
12107
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
12108
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
12109
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
12110
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
12111
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
12112
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
12113
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
12114
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
12115
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
12116
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
12117
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
12118
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
12119
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
12120
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
12121
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
12122
- var instanceOfType = (cls, params = {
12123
- message: `Input not instance of ${cls.name}`
12124
- }) => custom((data) => data instanceof cls, params);
12125
- var stringType = ZodString.create;
12126
- var numberType = ZodNumber.create;
12127
- var nanType = ZodNaN.create;
12128
- var bigIntType = ZodBigInt.create;
12129
- var booleanType = ZodBoolean.create;
12130
- var dateType = ZodDate.create;
12131
- var symbolType = ZodSymbol.create;
12132
- var undefinedType = ZodUndefined.create;
12133
- var nullType = ZodNull.create;
12134
- var anyType = ZodAny.create;
12135
- var unknownType = ZodUnknown.create;
12136
- var neverType = ZodNever.create;
12137
- var voidType = ZodVoid.create;
12138
- var arrayType = ZodArray.create;
12139
- var objectType = ZodObject.create;
12140
- var strictObjectType = ZodObject.strictCreate;
12141
- var unionType = ZodUnion.create;
12142
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
12143
- var intersectionType = ZodIntersection.create;
12144
- var tupleType = ZodTuple.create;
12145
- var recordType = ZodRecord.create;
12146
- var mapType = ZodMap.create;
12147
- var setType = ZodSet.create;
12148
- var functionType = ZodFunction.create;
12149
- var lazyType = ZodLazy.create;
12150
- var literalType = ZodLiteral.create;
12151
- var enumType = ZodEnum.create;
12152
- var nativeEnumType = ZodNativeEnum.create;
12153
- var promiseType = ZodPromise.create;
12154
- var effectsType = ZodEffects.create;
12155
- var optionalType = ZodOptional.create;
12156
- var nullableType = ZodNullable.create;
12157
- var preprocessType = ZodEffects.createWithPreprocess;
12158
- var pipelineType = ZodPipeline.create;
12159
- var ostring = () => stringType().optional();
12160
- var onumber = () => numberType().optional();
12161
- var oboolean = () => booleanType().optional();
12162
- var coerce = {
12163
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
12164
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
12165
- boolean: ((arg) => ZodBoolean.create({
12166
- ...arg,
12167
- coerce: true
12168
- })),
12169
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
12170
- date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
12171
- };
12172
- var NEVER = INVALID;
12173
- var LocatorOverrideSchema2 = external_exports.object({
12174
- strategy: external_exports.enum(["css", "xpath", "id", "testId", "text", "label", "placeholder", "altText", "title"]),
12175
- value: external_exports.string()
12176
- }).strict();
12177
- var CaptureModeSchema2 = external_exports.enum(["off", "on-failure", "always"]);
12178
- var ArtifactPolicySchema2 = external_exports.object({
12179
- /** Masked before the shutter opens — password fields are covered. */
12180
- screenshot: CaptureModeSchema2.optional(),
12181
- /** NOT maskable. A video shows every character typed, so a flow holding a
12182
- * secret is skipped unless allowUnmaskedArtifacts says otherwise. */
12183
- video: CaptureModeSchema2.optional(),
12184
- /** Also not maskable: a Playwright trace embeds DOM snapshots containing
12185
- * whatever was typed into the page. */
12186
- trace: CaptureModeSchema2.optional(),
12187
- /** Cheap, small, and the first thing anyone asks for when a step fails for
12188
- * no visible reason. */
12189
- console: external_exports.boolean().optional(),
12190
- /** How many runs keep their artifacts. Video is megabytes per run, so an
12191
- * unbounded history fills a disk quietly. */
12192
- retainRuns: external_exports.number().int().positive().max(1e4).optional(),
12193
- /** Deliberate opt-out of the secret guard, for a project with nothing to
12194
- * protect. Off by default: leaking a password into a video that nobody
12195
- * thinks of as sensitive is not a mistake worth making by accident. */
12196
- allowUnmaskedArtifacts: external_exports.boolean().optional()
12197
- }).strict();
12198
- var ExecutionEnvironmentSchema2 = external_exports.object({
12199
- browser: external_exports.enum(["chromium", "firefox", "webkit"]).optional(),
12200
- viewport: external_exports.object({ width: external_exports.number().int().positive(), height: external_exports.number().int().positive() }).optional(),
12201
- locale: external_exports.string().optional(),
12202
- timezoneId: external_exports.string().optional(),
12203
- colorScheme: external_exports.enum(["light", "dark", "no-preference"]).optional(),
12204
- /** How long a single step may take to find its target and act. */
12205
- timeoutMs: external_exports.number().int().positive().max(3e5).optional(),
12206
- /** How long a page load or history traversal may take. Separate from the
12207
- * step timeout on purpose: "this page is slow to load" and "this element
12208
- * does not exist" are different problems, and one number for both made
12209
- * every real site fail during load rather than during the assertion. */
12210
- navigationTimeoutMs: external_exports.number().int().positive().max(3e5).optional(),
12211
- /** How long an assertion may wait for the state it expects. Usually shorter
12212
- * than a step — an outcome that has not appeared quickly usually is not
12213
- * coming — but slow back ends need it raised. */
12214
- assertionTimeoutMs: external_exports.number().int().positive().max(3e5).optional(),
12215
- openClosedShadowRoots: external_exports.boolean().optional(),
12216
- /** Let the browser window take the whole screen, and the page take the whole
12217
- * window.
12218
- *
12219
- * Off by default, deliberately: a FIXED viewport is what makes a run
12220
- * reproducible, and a maximised window is whatever size the machine that ran
12221
- * it happened to have. But a recording done at 1280x720 inside a large
12222
- * display is a small box in the middle of an empty screen, which is a
12223
- * miserable way to drive an app — so this is offered, with the trade stated.
12224
- *
12225
- * Recorded ON the flow, like the rest of the environment, so a run always
12226
- * says which of the two it was. */
12227
- fullWindow: external_exports.boolean().optional()
12228
- }).strict();
12229
- var RecordedTargetSchema2 = external_exports.object({
12230
- role: external_exports.string(),
12231
- name: external_exports.string(),
12232
- scope: external_exports.string().optional(),
12233
- scopeRole: external_exports.string().optional(),
12234
- frame: external_exports.array(external_exports.string()).optional(),
12235
- pageId: external_exports.string().optional(),
12236
- nameFrom: external_exports.enum(["adjacent-label", "text"]).optional(),
12237
- locator: LocatorOverrideSchema2.optional(),
12238
- nth: external_exports.number().int().nonnegative().optional()
12239
- });
12240
- var RecordedAssertionKindSchema2 = external_exports.enum([
12241
- // Proposed automatically from a page-signature diff. Heuristic shapes, not
12242
- // things a person picks by name.
12243
- "screen",
12244
- "message",
12245
- "fields_visible",
12246
- // Element state.
12247
- "visible",
12248
- "hidden",
12249
- "attached",
12250
- "enabled",
12251
- "editable",
12252
- "focused",
12253
- "checked",
12254
- // Element content.
12255
- "text",
12256
- "value",
12257
- "attribute",
12258
- "class",
12259
- // Collections.
12260
- "count",
12261
- // The page itself.
12262
- "url",
12263
- "title",
12264
- "heading"
12265
- ]);
12266
- var AssertionOpSchema2 = external_exports.enum(["equals", "contains", "matches", "gt", "gte", "lt", "lte"]);
12267
- var RecordedAssertionSchema2 = external_exports.object({
12268
- kind: RecordedAssertionKindSchema2,
12269
- value: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]),
12270
- /** Defaults to "equals" when absent, so older flows keep their meaning. */
12271
- op: AssertionOpSchema2.optional(),
12272
- /** Negates the whole assertion, which is what gives every reading a mirror
12273
- * without doubling the catalogue. `visible` + `not` IS `hidden`. */
12274
- not: external_exports.boolean().optional(),
12275
- /** Which attribute, for kind "attribute". Ignored otherwise. */
12276
- attr: external_exports.string().optional(),
12277
- /** A failure records the check and lets the run carry on, instead of
12278
- * stopping the flow. Chosen by whoever authored the assertion: some checks
12279
- * are the point of the test and some are worth knowing about. */
12280
- soft: external_exports.boolean().optional(),
12281
- why: external_exports.string().optional(),
12282
- enabled: external_exports.boolean().optional(),
12283
- confidence: external_exports.enum(["low", "high"]).optional(),
12284
- target: RecordedTargetSchema2.optional()
12285
- }).strict();
12286
- var PageSignatureSchema2 = external_exports.object({
12287
- url: external_exports.string(),
12288
- title: external_exports.string(),
12289
- heading: external_exports.string(),
12290
- alerts: external_exports.array(external_exports.string()),
12291
- fields: external_exports.array(external_exports.string()),
12292
- /** Every short piece of visible text on the page, each tagged with enough
12293
- * identity to tell two elements apart.
12294
- *
12295
- * The generic net beneath `alerts`, which only sees a message when the page
12296
- * announced itself with role=alert or a class we happened to guess — so a
12297
- * bare <div id="error">Your username is invalid!</div> was invisible to it.
12298
- *
12299
- * `key` exists because comparing bare strings is not enough: a page that
12300
- * quotes its own error message in body copy (a docs page, help text, an
12301
- * empty state) already contains that string before anything happens, so the
12302
- * real message appearing looked like nothing had changed. The key is used
12303
- * ONLY to diff two snapshots of the same page a moment apart — never to
12304
- * find an element, which stays role + accessible name. */
12305
- texts: external_exports.array(external_exports.object({ key: external_exports.string(), text: external_exports.string() })).default([])
12306
- });
12307
- var AssertionKindSchema2 = external_exports.enum(["screen", "message", "heading", "fields_visible"]);
12308
- var AssertionSchema2 = external_exports.object({
12309
- id: external_exports.string(),
12310
- kind: AssertionKindSchema2,
12311
- value: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]),
12312
- /** Human-readable reason it was proposed — shown next to the tick box. */
12313
- why: external_exports.string().optional(),
12314
- /** Present only on INFERRED proposals — ones derived from a text diff rather
12315
- * than from something the page stated about itself. They arrive unticked,
12316
- * because a guess that silently becomes a passing assertion is worse than no
12317
- * assertion: it makes the suite look green for a reason nobody chose. */
12318
- confidence: external_exports.literal("low").optional(),
12319
- /** Unticked assertions stay in the file as a record of what was offered. */
12320
- enabled: external_exports.boolean().default(true),
12321
- source: external_exports.enum(["proposed", "manual"]).default("proposed")
12322
- });
12323
- var AssertionProposalSchema2 = AssertionSchema2.omit({ id: true, enabled: true, source: true });
12324
- var FeatureSchema2 = external_exports.object({
12325
- schemaVersion: external_exports.literal(1),
12326
- id: external_exports.string(),
12327
- /** Directory name. Stable even when the display name is edited. */
12328
- slug: external_exports.string(),
12329
- name: external_exports.string(),
12330
- description: external_exports.string().default(""),
12331
- /** Manual ordering in the UI; ties break by name. */
12332
- order: external_exports.number().int().default(0),
12333
- createdAt: external_exports.string(),
12334
- createdBy: external_exports.string().default("")
12335
- });
12336
- var SECRET_REF_PATTERN2 = /^[a-z0-9][a-z0-9_-]*$/;
12337
- var ScrollPrerequisiteSchema2 = external_exports.object({
12338
- x: external_exports.number(),
12339
- y: external_exports.number(),
12340
- container: RecordedTargetSchema2.optional(),
12341
- legacySelector: external_exports.string().optional()
12342
- }).strict();
12343
- var DialogAnswerSchema2 = external_exports.object({
12344
- type: external_exports.enum(["alert", "confirm", "prompt", "beforeunload"]),
12345
- message: external_exports.string(),
12346
- accept: external_exports.boolean(),
12347
- promptText: external_exports.string().optional()
12348
- }).strict();
12349
- var RecordedStepSchema2 = RecordedTargetSchema2.extend({
12350
- id: external_exports.string().min(1),
12351
- type: external_exports.enum(["fill", "select", "click", "dblclick", "rightclick", "drag", "check", "press", "hover", "upload", "scroll", "back", "forward", "navigate", "closePage", "unsupported", "setRange", "assert"]),
12352
- scope: external_exports.string(),
12353
- value: external_exports.string(),
12354
- secret: external_exports.boolean(),
12355
- legacySelector: external_exports.string(),
12356
- proposals: external_exports.array(RecordedAssertionSchema2),
12357
- values: external_exports.array(external_exports.string()).optional(),
12358
- to: RecordedTargetSchema2.optional(),
12359
- manual: external_exports.boolean().optional(),
12360
- verified: external_exports.boolean().optional(),
12361
- /** Skip this step without deleting it.
12362
- *
12363
- * There is a real gap between "this step is wrong" and "this field is broken
12364
- * today". Deleting is the only way to express the second without this, which
12365
- * loses the step's identity, its assertions and its place in the order — and
12366
- * the person then has to re-record it once the field is fixed.
12367
- *
12368
- * Absent means enabled, so every flow recorded before this stays enabled
12369
- * without a migration. */
12370
- disabled: external_exports.boolean().optional(),
12371
- /** How long a single step may take to find its target and act. */
12372
- timeoutMs: external_exports.number().int().positive().max(3e5).optional(),
12373
- /** How long a page load or history traversal may take. Separate from the
12374
- * step timeout on purpose: "this page is slow to load" and "this element
12375
- * does not exist" are different problems, and one number for both made
12376
- * every real site fail during load rather than during the assertion. */
12377
- navigationTimeoutMs: external_exports.number().int().positive().max(3e5).optional(),
12378
- /** How long an assertion may wait for the state it expects. Usually shorter
12379
- * than a step — an outcome that has not appeared quickly usually is not
12380
- * coming — but slow back ends need it raised. */
12381
- assertionTimeoutMs: external_exports.number().int().positive().max(3e5).optional(),
12382
- // Popups are bound to the action that created them; subsequent steps use pageId.
12383
- opensPage: external_exports.string().optional(),
12384
- dialogs: external_exports.array(DialogAnswerSchema2).optional(),
12385
- downloads: external_exports.array(external_exports.string()).optional(),
12386
- warning: external_exports.string().optional(),
12387
- scroll: ScrollPrerequisiteSchema2.optional(),
12388
- /** The NAME of a secret held outside this document.
12389
- *
12390
- * Explicit, because `secret: true` with the reference living in `value` made
12391
- * a reference and a password the same shape. Nothing could then tell an
12392
- * unresolvable reference from a leaked literal, and the code that tried
12393
- * guessed from whether the local secret store happened to contain the key —
12394
- * so on a machine that had never held the secret, a perfectly good reference
12395
- * was "healed" into a password whose value was its own name.
12396
- *
12397
- * When this is set, `value` is empty and carries nothing: the secret is
12398
- * looked up by this name at run time, and a name that is not on this machine
12399
- * stays unresolved and is reported, never invented. */
12400
- secretRef: external_exports.string().regex(SECRET_REF_PATTERN2).optional()
12401
- }).strict();
12402
- var CURRENT_SCHEMA_VERSION2 = 5;
12403
- var FlowDocumentSchema2 = external_exports.object({
12404
- schemaVersion: external_exports.literal(CURRENT_SCHEMA_VERSION2),
12405
- id: external_exports.string().min(1),
12406
- featureId: external_exports.string().min(1),
12407
- name: external_exports.string().min(1),
12408
- slug: external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/),
12409
- /** Where this flow starts, when it is pinned to somewhere of its own.
12410
- *
12411
- * OPTIONAL, and normally absent. The origin belongs to the project, not to
12412
- * each flow: a flow that carries its own hard-codes an environment into a
12413
- * git-tracked file, and the POC proved how that ends — an ephemeral port,
12414
- * `http://127.0.0.1:65226/`, committed and unrunnable on any other machine.
12415
- * Absent means "the project's base URL", which is what a flow recorded today
12416
- * stores. Present is honoured, so every flow recorded before this keeps
12417
- * working exactly as it did. */
12418
- baseUrl: external_exports.string().url().optional(),
12419
- /** The route, resolved against whichever base URL applies. */
12420
- startPath: external_exports.string(),
12421
- recordedAt: external_exports.string(),
12422
- recordedBy: external_exports.string(),
12423
- updatedAt: external_exports.string(),
12424
- steps: external_exports.array(RecordedStepSchema2),
12425
- environment: ExecutionEnvironmentSchema2.optional(),
12426
- path: external_exports.string().optional(),
12427
- /** Bumped on every save. An edit carries the revision it was made against,
12428
- * so a save built on a stale copy is refused instead of overwriting work
12429
- * somebody else — or a debug session on the same machine — has since done.
12430
- * Documents written before this default to 0. */
12431
- revision: external_exports.number().int().nonnegative().default(0)
12432
- }).strict().superRefine((flow, ctx) => {
12433
- const ids = /* @__PURE__ */ new Set();
12434
- flow.steps.forEach((s2, i) => {
12435
- if (ids.has(s2.id)) ctx.addIssue({ code: "custom", path: ["steps", i, "id"], message: "Step IDs must be unique" });
12436
- ids.add(s2.id);
12437
- });
12438
- });
12439
- var EngineSchema2 = external_exports.enum(["chromium", "firefox", "webkit"]);
12440
- var CapabilitySchema2 = external_exports.object({
12441
- id: external_exports.string(),
12442
- provider: external_exports.string().default("local"),
12443
- engine: EngineSchema2,
12444
- /** Branded local builds: "chrome", "msedge". */
12445
- channel: external_exports.string().optional(),
12446
- browserVersion: external_exports.string().optional(),
12447
- os: external_exports.string().optional(),
12448
- osVersion: external_exports.string().optional(),
12449
- device: external_exports.string().optional(),
12450
- viewport: external_exports.object({ width: external_exports.number().int(), height: external_exports.number().int() }).optional()
12451
- });
12452
- var ExecutionConfigSchema2 = external_exports.object({
12453
- concurrency: external_exports.number().int().positive().default(4),
12454
- defaultBrowser: external_exports.string().default("chromium"),
12455
- retries: external_exports.number().int().nonnegative().default(0),
12456
- browsers: external_exports.record(external_exports.string(), CapabilitySchema2.omit({ id: true }).partial({ provider: true })),
12457
- suites: external_exports.record(
12458
- external_exports.string(),
12459
- external_exports.object({
12460
- flows: external_exports.array(external_exports.string()).default([]),
12461
- browser: external_exports.string().optional(),
12462
- /** Opt-in cross-browser fan-out for this suite only. */
12463
- matrix: external_exports.array(external_exports.string()).optional()
12464
- })
12465
- ).default({})
12466
- });
12467
- var FlowOccurrenceSchema2 = external_exports.object({
12468
- /** This copy's own identity. Not the source flow's — a flow added twice is
12469
- * two occurrences, and editing, breakpoints, results and deletion must be
12470
- * able to tell them apart. */
12471
- occurrenceId: external_exports.string().min(1),
12472
- /** Editable, and initially the source flow's name. */
12473
- name: external_exports.string().min(1),
12474
- /** Where this copy starts, when it is told to navigate before running.
12475
- * Absent means continue from wherever the previous row left the browser. */
12476
- startPath: external_exports.string().optional(),
12477
- baseUrl: external_exports.string().url().optional(),
12478
- /** GO SOMEWHERE FIRST, or carry on where the last row ended.
12479
- *
12480
- * Off by default, because a case is a sequence in one browser: re-entering
12481
- * each flow's original starting URL would sign the tester out between rows
12482
- * and is exactly the behaviour composing flows is meant to avoid. */
12483
- navigateFirst: external_exports.boolean().default(false),
12484
- steps: external_exports.array(RecordedStepSchema2),
12485
- environment: ExecutionEnvironmentSchema2.optional(),
12486
- /** Where this copy came from, so the editor can say whether the source has
12487
- * moved on — informational only, never a trigger to rewrite anything. */
12488
- origin: external_exports.object({
12489
- flowId: external_exports.string(),
12490
- /** The schema the source was written in, which may be older than today's. */
12491
- schemaVersion: external_exports.number().int().nonnegative(),
12492
- /** The source's own revision counter at the moment it was copied. */
12493
- revision: external_exports.number().int().nonnegative(),
12494
- /** The commit the copy was taken from, when one was known. */
12495
- commit: external_exports.string().optional(),
12496
- featureId: external_exports.string(),
12497
- /** Names as they were, so an old case still reads correctly after the
12498
- * source is renamed, moved or deleted. */
12499
- featureName: external_exports.string(),
12500
- flowName: external_exports.string(),
12501
- /** Source step id → the id it was given here. Kept so a later comparison
12502
- * against the source can line the two up; nothing depends on it to run. */
12503
- stepIds: external_exports.record(external_exports.string(), external_exports.string()).default({}),
12504
- copiedAt: external_exports.string()
12505
- })
12506
- }).strict();
12507
- var CASE_SCHEMA_VERSION2 = 1;
12508
- var TestCaseSchema2 = external_exports.object({
12509
- schemaVersion: external_exports.literal(CASE_SCHEMA_VERSION2),
12510
- id: external_exports.string().min(1),
12511
- folderId: external_exports.string().min(1),
12512
- slug: external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/),
12513
- name: external_exports.string().min(1),
12514
- description: external_exports.string().default(""),
12515
- /** Where the case itself begins. The first row continues from here unless it
12516
- * carries its own navigation. */
12517
- startPath: external_exports.string().default("/"),
12518
- useStartPath: external_exports.boolean().default(false),
12519
- baseUrl: external_exports.string().url().optional(),
12520
- environment: ExecutionEnvironmentSchema2.optional(),
12521
- occurrences: external_exports.array(FlowOccurrenceSchema2).default([]),
12522
- createdAt: external_exports.string(),
12523
- createdBy: external_exports.string().default(""),
12524
- updatedAt: external_exports.string(),
12525
- /** The same optimistic-concurrency counter a flow carries, so an edit made
12526
- * against a stale copy is refused rather than overwriting. */
12527
- revision: external_exports.number().int().nonnegative().default(0)
12528
- }).strict().superRefine((testCase, ctx) => {
12529
- const seen = /* @__PURE__ */ new Set();
12530
- testCase.occurrences.forEach((occurrence, i) => {
12531
- if (seen.has(occurrence.occurrenceId)) {
12532
- ctx.addIssue({ code: "custom", path: ["occurrences", i, "occurrenceId"], message: "Occurrence IDs must be unique" });
12533
- }
12534
- seen.add(occurrence.occurrenceId);
12535
- const steps = /* @__PURE__ */ new Set();
12536
- occurrence.steps.forEach((step, s2) => {
12537
- if (steps.has(step.id)) {
12538
- ctx.addIssue({ code: "custom", path: ["occurrences", i, "steps", s2, "id"], message: "Step IDs must be unique within an occurrence" });
12539
- }
12540
- steps.add(step.id);
12541
- });
12542
- });
12543
- });
12544
- var CaseFolderSchema2 = external_exports.object({
12545
- schemaVersion: external_exports.literal(1),
12546
- id: external_exports.string().min(1),
12547
- slug: external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/),
12548
- name: external_exports.string().min(1),
12549
- description: external_exports.string().default(""),
12550
- order: external_exports.number().int().default(0),
12551
- createdAt: external_exports.string(),
12552
- createdBy: external_exports.string().default("")
12553
- }).strict();
12554
- var SUITE_SCHEMA_VERSION2 = 1;
12555
- var SuiteEntrySchema2 = external_exports.object({
12556
- entryId: external_exports.string().min(1),
12557
- kind: external_exports.enum(["flow", "testCase"]),
12558
- /** The document's ID — never its name or path, so renaming or moving what it
12559
- * points at cannot break the reference. */
12560
- ref: external_exports.string().min(1),
12561
- enabled: external_exports.boolean().default(true),
12562
- order: external_exports.number().int().nonnegative(),
12563
- /** What it was called when it was added, so a result stays readable after the
12564
- * source is renamed or deleted. */
12565
- nameSnapshot: external_exports.string().default("")
12566
- }).strict();
12567
- var SuiteSchema2 = external_exports.object({
12568
- schemaVersion: external_exports.literal(SUITE_SCHEMA_VERSION2),
12569
- id: external_exports.string().min(1),
12570
- slug: external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/),
12571
- name: external_exports.string().min(1),
12572
- description: external_exports.string().default(""),
12573
- entries: external_exports.array(SuiteEntrySchema2).default([]),
12574
- defaults: external_exports.object({
12575
- headless: external_exports.boolean().optional(),
12576
- /** Carry on through the remaining entries, or stop at the first failure.
12577
- * Continuing is the default: a suite is a list of independent things and
12578
- * one failure rarely invalidates the rest. */
12579
- failurePolicy: external_exports.enum(["continue", "stop"]).default("continue")
12580
- }).default({ failurePolicy: "continue" }),
12581
- createdAt: external_exports.string(),
12582
- createdBy: external_exports.string().default(""),
12583
- updatedAt: external_exports.string(),
12584
- revision: external_exports.number().int().nonnegative().default(0)
12585
- }).strict().superRefine((suite, ctx) => {
12586
- const seen = /* @__PURE__ */ new Set();
12587
- suite.entries.forEach((entry, i) => {
12588
- if (seen.has(entry.entryId)) {
12589
- ctx.addIssue({ code: "custom", path: ["entries", i, "entryId"], message: "Entry IDs must be unique" });
12590
- }
12591
- seen.add(entry.entryId);
12592
- });
12593
- });
12594
- function caseOccurrences2(testCase) {
12595
- return testCase.occurrences.map((item, index) => index === 0 && testCase.useStartPath && !item.navigateFirst ? { ...item, startPath: testCase.startPath, ...testCase.baseUrl ? { baseUrl: testCase.baseUrl } : {} } : item);
12596
- }
12597
- function caseDebugPlan(testCase, baseUrl) {
12598
- const owners = {};
12599
- const steps = [];
12600
- const occurrences = caseOccurrences2(testCase);
12601
- for (const [index, item] of occurrences.entries()) {
12602
- if (index > 0 && item.navigateFirst) {
12603
- const id = `case-nav:${encodeURIComponent(item.occurrenceId)}`;
12604
- owners[id] = { occurrenceId: item.occurrenceId, stepId: null };
12605
- steps.push({ id, type: "navigate", role: "", name: `Go to ${item.name}`, scope: "", value: new URL(item.startPath ?? "/", item.baseUrl ?? testCase.baseUrl ?? baseUrl).href, secret: false, legacySelector: "", proposals: [] });
12606
- }
12607
- for (const step of item.steps) {
12608
- const id = `case-step:${encodeURIComponent(item.occurrenceId)}:${encodeURIComponent(step.id)}`;
12609
- owners[id] = { occurrenceId: item.occurrenceId, stepId: step.id };
12610
- steps.push({ ...step, id });
12611
- }
12612
- }
12613
- const first = occurrences[0];
12614
- const flow = FlowDocumentSchema2.parse({
12615
- schemaVersion: 5,
12616
- id: testCase.id,
12617
- featureId: testCase.folderId,
12618
- slug: testCase.slug,
12619
- name: testCase.name,
12620
- revision: testCase.revision,
12621
- recordedAt: testCase.createdAt,
12622
- recordedBy: testCase.createdBy,
12623
- updatedAt: testCase.updatedAt,
12624
- steps,
12625
- startPath: new URL(first?.startPath ?? "/", first?.baseUrl ?? testCase.baseUrl ?? baseUrl).href,
12626
- ...testCase.environment ? { environment: testCase.environment } : {}
12627
- });
12628
- return { flow, owners };
12629
- }
12630
- function restoreDebugCase(testCase, owners, steps) {
12631
- const occurrences = testCase.occurrences.map((item) => ({ ...item, steps: [] }));
12632
- const byId = new Map(occurrences.map((item) => [item.occurrenceId, item]));
12633
- let current = occurrences[0];
12634
- const present = new Set(steps.map((step) => step.id));
12635
- for (const [id, owner] of Object.entries(owners)) {
12636
- if (owner.stepId === null && !present.has(id)) byId.get(owner.occurrenceId).navigateFirst = false;
12637
- }
12638
- for (const step of steps) {
12639
- const owner = owners[step.id];
12640
- if (owner) current = byId.get(owner.occurrenceId);
12641
- if (!current) throw new Error("debug step has no case occurrence");
12642
- if (owner?.stepId === null) {
12643
- if (step.type !== "navigate") throw new Error("a case boundary must remain a navigation step");
12644
- current.startPath = step.value;
12645
- continue;
12646
- }
12647
- current.steps.push({ ...step, id: owner?.stepId ?? step.id });
12648
- }
12649
- return { ...testCase, occurrences };
12650
- }
12651
8220
  function debuggingHandlers(ctx) {
12652
8221
  const { debugging, onActivity, deps } = ctx;
12653
8222
  let sessionProject = null;
@@ -12689,7 +8258,7 @@ function debuggingHandlers(ctx) {
12689
8258
  // The browser opens on this machine and the panel lives inside that window,
12690
8259
  // so whoever is at the keyboard sees the same state the dashboard does.
12691
8260
  "debug.start": async (command, project) => {
12692
- const document2 = command.args["case"] ? TestCaseSchema2.parse(command.args["case"]) : null;
8261
+ const document2 = command.args["case"] ? TestCaseSchema.parse(command.args["case"]) : null;
12693
8262
  const plan = document2 ? caseDebugPlan(document2, String(command.args["baseUrl"] ?? "")) : null;
12694
8263
  const carried = plan?.flow ?? command.args["flow"];
12695
8264
  if (!carried && !project.root) return NO_CHECKOUT;
@@ -12751,7 +8320,7 @@ function debuggingHandlers(ctx) {
12751
8320
  const res = await debugging.end(command.args["commit"] !== false);
12752
8321
  if (!res.ok) return { ok: false, reason: "failed", detail: res.error ?? "no debug session is running" };
12753
8322
  if (caseSession && res.flow) {
12754
- const testCase = restoreDebugCase(caseSession.document, caseSession.owners, FlowDocumentSchema2.parse(res.flow).steps);
8323
+ const testCase = restoreDebugCase(caseSession.document, caseSession.owners, FlowDocumentSchema.parse(res.flow).steps);
12755
8324
  return { ok: true, result: { ...res, flow: void 0, testCase, caseChangeId: caseSession.changeId } };
12756
8325
  }
12757
8326
  return { ok: true, result: res };
@@ -12800,7 +8369,7 @@ function createAgentRuntime(options) {
12800
8369
  lease,
12801
8370
  store: new Store(projectRoot),
12802
8371
  emit: (event) => {
12803
- if (event.type === "recording.stopped") lastRecording = { ok: true, flow: event.flow };
8372
+ if (event.type === "recording.stopped") lastRecording = { ok: true, flow: event.flow, secrets: {} };
12804
8373
  journal?.append({ name: `recording.${event.type.replace(/^recording\./, "")}`, data: event });
12805
8374
  }
12806
8375
  });
@@ -12887,8 +8456,9 @@ function createAgentRuntime(options) {
12887
8456
  },
12888
8457
  stop: async (projectId) => {
12889
8458
  if (projectId && recordingProject && projectId !== recordingProject) return { ok: false, error: "This recording belongs to another project" };
12890
- if (lastRecording?.ok) return lastRecording;
12891
- if (!recordingIn) return lastRecording ?? { ok: false, error: "no recording is in progress on this machine" };
8459
+ const remembered = recordingIn?.lastStop() ?? lastRecording;
8460
+ if (remembered?.ok) return remembered;
8461
+ if (!recordingIn) return remembered ?? { ok: false, error: "no recording is in progress on this machine" };
12892
8462
  const result = await recordingIn.stop();
12893
8463
  lastRecording = result;
12894
8464
  return result;