@commandgarden/cli 1.0.2 → 1.1.1

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