switchroom 0.15.44 → 0.16.4

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 (150) hide show
  1. package/dist/agent-scheduler/index.js +122 -88
  2. package/dist/auth-broker/index.js +463 -177
  3. package/dist/cli/autoaccept-poll.js +4842 -35
  4. package/dist/cli/drive-write-pretool.mjs +17 -14
  5. package/dist/cli/notion-write-pretool.mjs +117 -86
  6. package/dist/cli/self-improve-apply-guard-pretool.mjs +626 -0
  7. package/dist/cli/self-improve-stop.mjs +428 -0
  8. package/dist/cli/skill-validate-pretool.mjs +72 -72
  9. package/dist/cli/switchroom.js +3249 -1241
  10. package/dist/cli/ui/index.html +1 -1
  11. package/dist/host-control/main.js +2833 -355
  12. package/dist/vault/approvals/kernel-server.js +7482 -7439
  13. package/dist/vault/broker/server.js +11315 -11272
  14. package/examples/minimal.yaml +1 -0
  15. package/examples/switchroom.yaml +1 -0
  16. package/package.json +3 -3
  17. package/profiles/_base/start.sh.hbs +88 -1
  18. package/profiles/_shared/execution-discipline.md.hbs +18 -0
  19. package/profiles/default/CLAUDE.md.hbs +3 -22
  20. package/telegram-plugin/.claude-plugin/plugin.json +2 -2
  21. package/telegram-plugin/answer-stream-flag.ts +12 -49
  22. package/telegram-plugin/answer-stream.ts +5 -150
  23. package/telegram-plugin/auth-snapshot-format.ts +280 -48
  24. package/telegram-plugin/auto-fallback-fleet.ts +44 -1
  25. package/telegram-plugin/context-exhaustion.ts +12 -0
  26. package/telegram-plugin/demo-mask.ts +154 -0
  27. package/telegram-plugin/dist/bridge/bridge.js +167 -124
  28. package/telegram-plugin/dist/gateway/gateway.js +3039 -1159
  29. package/telegram-plugin/dist/server.js +215 -172
  30. package/telegram-plugin/docs/waiting-ux-spec.md +2 -2
  31. package/telegram-plugin/draft-stream.ts +47 -410
  32. package/telegram-plugin/final-answer-detect.ts +17 -12
  33. package/telegram-plugin/fleet-fallback-resume.ts +131 -0
  34. package/telegram-plugin/format.ts +56 -19
  35. package/telegram-plugin/gateway/auth-add-flow.ts +332 -127
  36. package/telegram-plugin/gateway/auth-broker-client.ts +2 -2
  37. package/telegram-plugin/gateway/auth-command.ts +70 -14
  38. package/telegram-plugin/gateway/clean-shutdown-marker.ts +44 -0
  39. package/telegram-plugin/gateway/config-approval-handler.test.ts +91 -4
  40. package/telegram-plugin/gateway/config-approval-handler.ts +94 -13
  41. package/telegram-plugin/gateway/current-turn-map.ts +188 -0
  42. package/telegram-plugin/gateway/disconnect-flush.ts +3 -1
  43. package/telegram-plugin/gateway/effort-command.ts +8 -3
  44. package/telegram-plugin/gateway/emission-authority.ts +369 -0
  45. package/telegram-plugin/gateway/feed-open-gate.ts +292 -0
  46. package/telegram-plugin/gateway/gateway.ts +1837 -291
  47. package/telegram-plugin/gateway/inject-handler.test.ts +2 -1
  48. package/telegram-plugin/gateway/ms365-write-approval.test.ts +4 -4
  49. package/telegram-plugin/gateway/represent-guard.ts +72 -0
  50. package/telegram-plugin/gateway/status-surface-log.test.ts +5 -4
  51. package/telegram-plugin/gateway/status-surface-log.ts +14 -3
  52. package/telegram-plugin/history.ts +33 -11
  53. package/telegram-plugin/hooks/repo-context-pretool.mjs +26 -0
  54. package/telegram-plugin/hooks/subagent-tracker-posttool.mjs +5 -0
  55. package/telegram-plugin/hooks/subagent-tracker-pretool.mjs +8 -0
  56. package/telegram-plugin/hooks/tool-label-pretool.mjs +39 -15
  57. package/telegram-plugin/issues-card.ts +4 -0
  58. package/telegram-plugin/model-unavailable.ts +124 -0
  59. package/telegram-plugin/narrative-dedup.ts +69 -0
  60. package/telegram-plugin/over-ping-safety-net.ts +70 -4
  61. package/telegram-plugin/package.json +3 -3
  62. package/telegram-plugin/pending-work-progress.ts +12 -0
  63. package/telegram-plugin/permission-rule.ts +32 -5
  64. package/telegram-plugin/permission-title.ts +152 -9
  65. package/telegram-plugin/quota-check.ts +13 -0
  66. package/telegram-plugin/quota-watch.ts +135 -7
  67. package/telegram-plugin/registry/turns-schema.test.ts +24 -0
  68. package/telegram-plugin/registry/turns-schema.ts +9 -0
  69. package/telegram-plugin/runtime-metrics.ts +13 -0
  70. package/telegram-plugin/session-tail.ts +96 -11
  71. package/telegram-plugin/silence-poke.ts +170 -24
  72. package/telegram-plugin/slot-banner-driver.ts +3 -0
  73. package/telegram-plugin/status-no-truncate.ts +44 -0
  74. package/telegram-plugin/status-reactions.ts +20 -3
  75. package/telegram-plugin/stream-controller.ts +4 -23
  76. package/telegram-plugin/stream-reply-handler.ts +6 -24
  77. package/telegram-plugin/streaming-metrics.ts +91 -0
  78. package/telegram-plugin/subagent-watcher.ts +212 -66
  79. package/telegram-plugin/tests/activity-ever-opened-sticky.test.ts +47 -0
  80. package/telegram-plugin/tests/answer-stream-dedup.test.ts +9 -26
  81. package/telegram-plugin/tests/answer-stream-flag.test.ts +25 -58
  82. package/telegram-plugin/tests/answer-stream-silent-markers.test.ts +41 -51
  83. package/telegram-plugin/tests/answer-stream.test.ts +2 -411
  84. package/telegram-plugin/tests/auth-add-flow.test.ts +488 -253
  85. package/telegram-plugin/tests/auth-command-format2.test.ts +71 -1
  86. package/telegram-plugin/tests/auth-snapshot-format.test.ts +376 -6
  87. package/telegram-plugin/tests/auto-fallback-fleet.test.ts +120 -0
  88. package/telegram-plugin/tests/cross-turn-card-gate.test.ts +424 -0
  89. package/telegram-plugin/tests/demo-mask.test.ts +127 -0
  90. package/telegram-plugin/tests/draft-stream.test.ts +0 -827
  91. package/telegram-plugin/tests/emission-authority-card-drain-gate.test.ts +236 -0
  92. package/telegram-plugin/tests/emission-authority-facade.test.ts +488 -0
  93. package/telegram-plugin/tests/emission-authority-open-gate.test.ts +179 -0
  94. package/telegram-plugin/tests/emission-authority-ping-gate.test.ts +395 -0
  95. package/telegram-plugin/tests/emission-determinism-wiring.test.ts +177 -0
  96. package/telegram-plugin/tests/feed-heartbeat-liveness-open.test.ts +146 -0
  97. package/telegram-plugin/tests/feed-open-gate.test.ts +259 -0
  98. package/telegram-plugin/tests/feed-survival.test.ts +526 -0
  99. package/telegram-plugin/tests/fleet-fallback-resume.test.ts +197 -0
  100. package/telegram-plugin/tests/gateway-clean-shutdown-marker.test.ts +117 -0
  101. package/telegram-plugin/tests/gateway-no-reply-single-emit.test.ts +4 -11
  102. package/telegram-plugin/tests/history.test.ts +60 -0
  103. package/telegram-plugin/tests/model-unavailable.test.ts +118 -0
  104. package/telegram-plugin/tests/narrative-dedup.test.ts +118 -0
  105. package/telegram-plugin/tests/orphaned-reply-rearm.test.ts +285 -0
  106. package/telegram-plugin/tests/over-ping-final-answer-decoupling.test.ts +194 -0
  107. package/telegram-plugin/tests/over-ping-safety-net.test.ts +2 -2
  108. package/telegram-plugin/tests/per-topic-current-turn.test.ts +373 -0
  109. package/telegram-plugin/tests/permission-card-origin-kill-switch.test.ts +42 -0
  110. package/telegram-plugin/tests/permission-rule.test.ts +17 -0
  111. package/telegram-plugin/tests/permission-title.test.ts +206 -17
  112. package/telegram-plugin/tests/quota-watch.test.ts +252 -9
  113. package/telegram-plugin/tests/reply-terminal-reaction.test.ts +6 -1
  114. package/telegram-plugin/tests/repo-context-pretool.test.ts +62 -0
  115. package/telegram-plugin/tests/represent-guard.test.ts +162 -0
  116. package/telegram-plugin/tests/session-tail.test.ts +147 -3
  117. package/telegram-plugin/tests/silence-liveness-wiring.test.ts +18 -0
  118. package/telegram-plugin/tests/status-card-budget-parity.test.ts +72 -0
  119. package/telegram-plugin/tests/status-surface-log.test.ts +146 -0
  120. package/telegram-plugin/tests/subagent-watcher-clip-narrative.test.ts +58 -0
  121. package/telegram-plugin/tests/subagent-watcher-parent-turn-key.test.ts +102 -0
  122. package/telegram-plugin/tests/subagent-watcher-workflow-visibility.test.ts +225 -0
  123. package/telegram-plugin/tests/subagent-watcher.test.ts +147 -0
  124. package/telegram-plugin/tests/telegram-activity-visibility-integration.test.ts +597 -0
  125. package/telegram-plugin/tests/telegram-format.test.ts +101 -6
  126. package/telegram-plugin/tests/tool-activity-summary.test.ts +550 -15
  127. package/telegram-plugin/tests/tool-label-pretool.test.ts +73 -0
  128. package/telegram-plugin/tests/tool-label-sidecar.test.ts +44 -0
  129. package/telegram-plugin/tests/tool-labels.test.ts +67 -0
  130. package/telegram-plugin/tests/turn-liveness-floor.test.ts +196 -0
  131. package/telegram-plugin/tests/turn-liveness-invariant.test.ts +340 -0
  132. package/telegram-plugin/tests/welcome-text.test.ts +32 -3
  133. package/telegram-plugin/tests/worker-activity-feed.test.ts +470 -22
  134. package/telegram-plugin/tool-activity-summary.ts +375 -58
  135. package/telegram-plugin/turn-liveness-floor.ts +240 -0
  136. package/telegram-plugin/uat/assertions.ts +115 -0
  137. package/telegram-plugin/uat/driver.ts +68 -0
  138. package/telegram-plugin/uat/scenarios/bg-sub-agent-dispatch-dm.test.ts +119 -133
  139. package/telegram-plugin/uat/scenarios/jtbd-answer-pings.test.ts +94 -0
  140. package/telegram-plugin/uat/scenarios/jtbd-cross-turn-card-dm.test.ts +109 -0
  141. package/telegram-plugin/uat/scenarios/jtbd-foreground-feed-thinkgap-dm.test.ts +478 -0
  142. package/telegram-plugin/uat/scenarios/jtbd-foreground-feed-visibility-dm.test.ts +396 -0
  143. package/telegram-plugin/uat/scenarios/jtbd-liveness-feed-open-dm.test.ts +202 -0
  144. package/telegram-plugin/uat/scenarios/jtbd-reply-is-last-dm.test.ts +202 -0
  145. package/telegram-plugin/uat/scenarios/reactions-dm.test.ts +93 -87
  146. package/telegram-plugin/welcome-text.ts +13 -1
  147. package/telegram-plugin/worker-activity-feed.ts +157 -82
  148. package/telegram-plugin/draft-transport.ts +0 -122
  149. package/telegram-plugin/tests/draft-retirement-wiring.test.ts +0 -82
  150. package/telegram-plugin/tests/draft-transport.test.ts +0 -211
@@ -1,5 +1,22 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
+ var __defProp = Object.defineProperty;
4
+ var __returnValue = (v) => v;
5
+ function __exportSetter(name, newValue) {
6
+ this[name] = __returnValue.bind(null, newValue);
7
+ }
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, {
11
+ get: all[name],
12
+ enumerable: true,
13
+ configurable: true,
14
+ set: __exportSetter.bind(all, name)
15
+ });
16
+ };
17
+
18
+ // src/cli/autoaccept-poll.ts
19
+ import { execFileSync as execFileSync3 } from "child_process";
3
20
 
4
21
  // src/agents/autoaccept.ts
5
22
  import { execFileSync } from "node:child_process";
@@ -34,6 +51,12 @@ var PROMPTS = [
34
51
  match: /Anthropic.{1,80}Bedrock/,
35
52
  keys: ["Enter"]
36
53
  },
54
+ {
55
+ name: "effort-modal-dismiss",
56
+ match: /Change.{1,30}effort.{1,30}level/i,
57
+ keys: ["Escape"],
58
+ maxFires: 5
59
+ },
37
60
  {
38
61
  name: "enter-to-confirm",
39
62
  match: /Enter.{1,30}confirm/,
@@ -149,6 +172,12 @@ var PROMPTS2 = [
149
172
  match: /Anthropic.{1,80}Bedrock/,
150
173
  keys: ["Enter"]
151
174
  },
175
+ {
176
+ name: "effort-modal-dismiss",
177
+ match: /Change.{1,30}effort.{1,30}level/i,
178
+ keys: ["Escape"],
179
+ maxFires: 5
180
+ },
152
181
  {
153
182
  name: "enter-to-confirm",
154
183
  match: /Enter.{1,30}confirm/,
@@ -183,6 +212,32 @@ function sendKeys2(agentName, keys) {
183
212
  // src/agents/wedge-watchdog.ts
184
213
  var WEDGE_FOOTER_SIGNATURE = /(?=[\s\S]*[Ee]sc(?:ape)?[^\n]*cancel)(?=[\s\S]*(?:to select|to navigate|\u2191\/\u2193))/;
185
214
  var RATE_LIMIT_MENU_SIGNATURE = /(?=[\s\S]*Stop and wait for)(?=[\s\S]*(?:usage credits|Upgrade your plan|\/rate-limit-options))/;
215
+ function usageCreditsMenuNav(text) {
216
+ const options = [];
217
+ for (const line of text.split(`
218
+ `)) {
219
+ const m = line.match(/^\s*(\u276f)?\s*(\d+)\.\s+(.*\S)\s*$/);
220
+ if (!m)
221
+ continue;
222
+ options.push({ selected: !!m[1], label: m[3] });
223
+ }
224
+ if (options.length === 0)
225
+ return null;
226
+ const creditIdx = options.findIndex((o) => /usage credits/i.test(o.label));
227
+ if (creditIdx === -1)
228
+ return null;
229
+ let selIdx = options.findIndex((o) => o.selected);
230
+ if (selIdx === -1)
231
+ selIdx = 0;
232
+ const down = creditIdx - selIdx;
233
+ if (down <= 0)
234
+ return null;
235
+ return [...Array(down).fill("Down"), "Enter"];
236
+ }
237
+ var CONFIRM_MODAL_SIGNATURE = /Change\s+effort\s+level|(?=[\s\S]*\b1\.\s*Yes\b)(?=[\s\S]*\b2\.\s*No\b)/i;
238
+ var PERMISSION_PROMPT_SIGNATURE = /(?=[\s\S]*Do you want to proceed\?)(?=[\s\S]*don['\u2019]t ask again)/i;
239
+ var STOP_HOOK_ERROR_SIGNATURE = /Stop hook error|running stop hooks\s+0\/\d+/i;
240
+ var MANIFESTING_SIGNATURE = /Manifesting|esc to interrupt/i;
186
241
  var MONTHS = {
187
242
  jan: 0,
188
243
  feb: 1,
@@ -199,31 +254,75 @@ var MONTHS = {
199
254
  };
200
255
  function parseWeeklyReset(text, nowMs = Date.now()) {
201
256
  const m = text.match(/resets\s+([A-Za-z]{3,9})\s+(\d{1,2}),?\s+(\d{1,2})(?::(\d{2}))?\s*([ap]m)?\s*(?:\(([^)]+)\))?/i);
202
- if (!m)
203
- return null;
204
- const mon = MONTHS[m[1].slice(0, 3).toLowerCase()];
205
- if (mon === undefined)
206
- return null;
207
- const day = Number(m[2]);
208
- let hour = Number(m[3]);
209
- const minute = m[4] ? Number(m[4]) : 0;
210
- const ampm = m[5]?.toLowerCase();
211
- if (ampm === "pm" && hour < 12)
212
- hour += 12;
213
- if (ampm === "am" && hour === 12)
214
- hour = 0;
215
- if (!Number.isFinite(day) || !Number.isFinite(hour) || day < 1 || day > 31 || hour > 23) {
216
- return null;
257
+ if (m) {
258
+ const mon = MONTHS[m[1].slice(0, 3).toLowerCase()];
259
+ if (mon !== undefined) {
260
+ const day = Number(m[2]);
261
+ let hour = Number(m[3]);
262
+ const minute = m[4] ? Number(m[4]) : 0;
263
+ const ampm = m[5]?.toLowerCase();
264
+ if (ampm === "pm" && hour < 12)
265
+ hour += 12;
266
+ if (ampm === "am" && hour === 12)
267
+ hour = 0;
268
+ if (Number.isFinite(day) && Number.isFinite(hour) && day >= 1 && day <= 31 && hour <= 23) {
269
+ const tz = m[6]?.trim();
270
+ const probeYear = new Date(nowMs).getUTCFullYear();
271
+ for (const year of [probeYear, probeYear + 1]) {
272
+ const epoch = wallClockToEpoch(year, mon, day, hour, minute, tz);
273
+ if (epoch != null && epoch > nowMs - 60000)
274
+ return epoch;
275
+ }
276
+ return null;
277
+ }
278
+ }
217
279
  }
218
- const tz = m[6]?.trim();
219
- const probeYear = new Date(nowMs).getUTCFullYear();
220
- for (const year of [probeYear, probeYear + 1]) {
221
- const epoch = wallClockToEpoch(year, mon, day, hour, minute, tz);
222
- if (epoch != null && epoch > nowMs - 60000)
223
- return epoch;
280
+ const tm = text.match(/resets\s+(?:at\s+)?(?!(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\b)(\d{1,2})(?::(\d{2}))?\s*([ap]m)?\s*(?:\(([^)]+)\))?/i);
281
+ if (tm) {
282
+ let hour = Number(tm[1]);
283
+ const minute = tm[2] ? Number(tm[2]) : 0;
284
+ const ampm = tm[3]?.toLowerCase();
285
+ if (ampm === "pm" && hour < 12)
286
+ hour += 12;
287
+ if (ampm === "am" && hour === 12)
288
+ hour = 0;
289
+ if (!Number.isFinite(hour) || hour > 23 || hour < 0 || !Number.isFinite(minute) || minute > 59) {
290
+ return null;
291
+ }
292
+ const tz = tm[4]?.trim();
293
+ for (let dayOffset = 0;dayOffset <= 2; dayOffset++) {
294
+ const dp = tzDateParts(new Date(nowMs + dayOffset * 86400000), tz);
295
+ if (dp == null)
296
+ return null;
297
+ const epoch = wallClockToEpoch(dp.year, dp.month, dp.day, hour, minute, tz);
298
+ if (epoch != null && epoch > nowMs)
299
+ return epoch;
300
+ }
301
+ return null;
224
302
  }
225
303
  return null;
226
304
  }
305
+ function tzDateParts(d, tz) {
306
+ if (!tz) {
307
+ return { year: d.getUTCFullYear(), month: d.getUTCMonth(), day: d.getUTCDate() };
308
+ }
309
+ try {
310
+ const fmt = new Intl.DateTimeFormat("en-US", {
311
+ timeZone: tz,
312
+ year: "numeric",
313
+ month: "2-digit",
314
+ day: "2-digit"
315
+ });
316
+ const parts = Object.fromEntries(fmt.formatToParts(d).filter((p) => p.type !== "literal").map((p) => [p.type, p.value]));
317
+ return {
318
+ year: Number(parts.year),
319
+ month: Number(parts.month) - 1,
320
+ day: Number(parts.day)
321
+ };
322
+ } catch {
323
+ return null;
324
+ }
325
+ }
227
326
  function wallClockToEpoch(year, month, day, hour, minute, tz) {
228
327
  const asUtc = Date.UTC(year, month, day, hour, minute, 0);
229
328
  if (!tz)
@@ -250,6 +349,16 @@ function wallClockToEpoch(year, month, day, hour, minute, tz) {
250
349
  var DEFAULT_POLL_MS2 = 5000;
251
350
  var DEFAULT_STABILITY_THRESHOLD = 3;
252
351
  var DEFAULT_COOLDOWN_MS = 60000;
352
+ var DEFAULT_CONFIRM_MODAL_POLLS = 3;
353
+ var DEFAULT_MANIFEST_STALL_POLLS = 60;
354
+ var DEFAULT_PERMISSION_PROMPT_POLLS = 3;
355
+ function envInt(name, fallback) {
356
+ const raw = process.env[name];
357
+ if (raw === undefined || raw.trim() === "")
358
+ return fallback;
359
+ const n = Number.parseInt(raw, 10);
360
+ return Number.isFinite(n) && n > 0 ? n : fallback;
361
+ }
253
362
  function defaultSleep2(ms) {
254
363
  return new Promise((r) => setTimeout(r, ms));
255
364
  }
@@ -266,7 +375,15 @@ async function runWedgeWatchdog(opts) {
266
375
  const signature = opts.wedgeSignature ?? WEDGE_FOOTER_SIGNATURE;
267
376
  const rateLimitSignature = opts.rateLimitSignature === null ? null : opts.rateLimitSignature ?? RATE_LIMIT_MENU_SIGNATURE;
268
377
  const onRateLimitMenu = opts.onRateLimitMenu;
378
+ const overageDecision = opts.overageDecision;
269
379
  const parseReset = opts.parseReset ?? parseWeeklyReset;
380
+ const confirmModalSignature = opts.confirmModalSignature === null ? null : opts.confirmModalSignature ?? CONFIRM_MODAL_SIGNATURE;
381
+ const confirmModalPolls = opts.confirmModalPolls ?? envInt("SWITCHROOM_WEDGE_CONFIRM_POLLS", DEFAULT_CONFIRM_MODAL_POLLS);
382
+ const permissionPromptSignature = opts.permissionPromptSignature === null ? null : opts.permissionPromptSignature ?? PERMISSION_PROMPT_SIGNATURE;
383
+ const permissionPromptPolls = opts.permissionPromptPolls ?? envInt("SWITCHROOM_WEDGE_PERMISSION_POLLS", DEFAULT_PERMISSION_PROMPT_POLLS);
384
+ const manifestStallSignature = opts.manifestStallSignature === null ? null : opts.manifestStallSignature ?? MANIFESTING_SIGNATURE;
385
+ const manifestStallPolls = opts.manifestStallPolls ?? envInt("SWITCHROOM_WEDGE_MANIFEST_POLLS", DEFAULT_MANIFEST_STALL_POLLS);
386
+ const requestRestart = opts.requestRestart;
270
387
  const maxPolls = opts.maxPolls ?? Number.POSITIVE_INFINITY;
271
388
  const now = opts.now ?? Date.now;
272
389
  const sleep = opts.sleep ?? defaultSleep2;
@@ -277,7 +394,16 @@ async function runWedgeWatchdog(opts) {
277
394
  let cooldownUntil = 0;
278
395
  let fires = 0;
279
396
  let rateLimitFires = 0;
397
+ let overageCreditSelections = 0;
398
+ let confirmModalFires = 0;
399
+ let permissionPromptFires = 0;
400
+ let restartEscalations = 0;
280
401
  let polls = 0;
402
+ let confirmModalPresent = 0;
403
+ let permissionPromptPresent = 0;
404
+ let manifestStallPresent = 0;
405
+ let confirmCooldownUntil = 0;
406
+ let permissionCooldownUntil = 0;
281
407
  while (polls < maxPolls) {
282
408
  polls++;
283
409
  let text = "";
@@ -288,7 +414,28 @@ async function runWedgeWatchdog(opts) {
288
414
  text = "";
289
415
  }
290
416
  const isRateLimitMenu = !!text && rateLimitSignature !== null && rateLimitSignature.test(text);
291
- const isBlockingModal = !isRateLimitMenu && !!text && signature.test(text) && !deferToPrompts.some((p) => p.match.test(text));
417
+ const isPermissionPrompt = !isRateLimitMenu && !!text && permissionPromptSignature !== null && permissionPromptSignature.test(text);
418
+ const isConfirmModal = !isRateLimitMenu && !isPermissionPrompt && !!text && confirmModalSignature !== null && confirmModalSignature.test(text);
419
+ const isBlockingModal = !isRateLimitMenu && !isPermissionPrompt && !isConfirmModal && !!text && signature.test(text) && !deferToPrompts.some((p) => p.match.test(text));
420
+ const isManifestStall = !!text && manifestStallSignature !== null && manifestStallSignature.test(text) && STOP_HOOK_ERROR_SIGNATURE.test(text);
421
+ if (isManifestStall) {
422
+ manifestStallPresent++;
423
+ if (manifestStallPresent >= manifestStallPolls) {
424
+ const detail = `Manifesting + stop-hook-error present ${manifestStallPresent} polls ` + `(~${Math.round(manifestStallPresent * pollIntervalMs / 1000)}s) with no progress`;
425
+ console.error(`[wedge-watchdog] ${opts.agentName}: manifest-stall wedge \u2014 ${detail}; ` + (requestRestart ? "escalating to kill + handoff restart" : "no requestRestart wired \u2014 logging only"));
426
+ if (requestRestart) {
427
+ try {
428
+ requestRestart(opts.agentName, detail);
429
+ } catch (err) {
430
+ console.error(`[wedge-watchdog] ${opts.agentName}: requestRestart threw: ${err.message}`);
431
+ }
432
+ restartEscalations++;
433
+ }
434
+ manifestStallPresent = 0;
435
+ }
436
+ } else {
437
+ manifestStallPresent = 0;
438
+ }
292
439
  if (isRateLimitMenu) {
293
440
  const key = stabilityKey(text);
294
441
  if (key === lastKey) {
@@ -299,24 +446,81 @@ async function runWedgeWatchdog(opts) {
299
446
  }
300
447
  if (stableCount >= stabilityThreshold && now() >= cooldownUntil) {
301
448
  const resetAt = parseReset(text, now());
302
- console.error(`[wedge-watchdog] ${opts.agentName}: rate-limit (weekly-quota) menu detected ` + `after ${stableCount} stable polls \u2014 signalling failover` + (resetAt != null ? ` (resets ${new Date(resetAt).toISOString()})` : " (reset unparsed)") + ` then parking with Esc`);
303
- if (onRateLimitMenu) {
449
+ let useCredits = false;
450
+ if (overageDecision) {
451
+ try {
452
+ useCredits = await overageDecision(opts.agentName) === true;
453
+ } catch (err) {
454
+ console.error(`[wedge-watchdog] ${opts.agentName}: overageDecision threw: ${err.message} \u2014 defaulting to Esc-park + failover`);
455
+ useCredits = false;
456
+ }
457
+ }
458
+ const nav = useCredits ? usageCreditsMenuNav(text) : null;
459
+ if (useCredits && nav) {
460
+ console.error(`[wedge-watchdog] ${opts.agentName}: rate-limit menu \u2014 broker confirms overage ACTIVE for the active account; ` + `selecting "usage credits" (${nav.join(" ")}) instead of failover. Anthropic overage billing will apply.`);
461
+ try {
462
+ send(opts.agentName, nav);
463
+ } catch (err) {
464
+ console.error(`[wedge-watchdog] ${opts.agentName}: send threw: ${err.message}`);
465
+ }
466
+ fires++;
467
+ overageCreditSelections++;
468
+ } else {
469
+ if (useCredits && !nav) {
470
+ console.error(`[wedge-watchdog] ${opts.agentName}: overage authorized but the "usage credits" option could not be located in the pane \u2014 failing safe to Esc-park + failover`);
471
+ }
472
+ console.error(`[wedge-watchdog] ${opts.agentName}: rate-limit (weekly-quota) menu detected ` + `after ${stableCount} stable polls \u2014 signalling failover` + (resetAt != null ? ` (resets ${new Date(resetAt).toISOString()})` : " (reset unparsed)") + ` then parking with Esc`);
473
+ if (onRateLimitMenu) {
474
+ try {
475
+ onRateLimitMenu(opts.agentName, resetAt);
476
+ } catch (err) {
477
+ console.error(`[wedge-watchdog] ${opts.agentName}: onRateLimitMenu threw: ${err.message}`);
478
+ }
479
+ }
304
480
  try {
305
- onRateLimitMenu(opts.agentName, resetAt);
481
+ send(opts.agentName, ["Escape"]);
306
482
  } catch (err) {
307
- console.error(`[wedge-watchdog] ${opts.agentName}: onRateLimitMenu threw: ${err.message}`);
483
+ console.error(`[wedge-watchdog] ${opts.agentName}: send threw: ${err.message}`);
308
484
  }
485
+ fires++;
486
+ rateLimitFires++;
309
487
  }
488
+ cooldownUntil = now() + cooldownMs;
489
+ stableCount = 0;
490
+ lastKey = null;
491
+ }
492
+ } else if (isPermissionPrompt) {
493
+ permissionPromptPresent++;
494
+ stableCount = 0;
495
+ lastKey = null;
496
+ if (permissionPromptPresent >= permissionPromptPolls && now() >= permissionCooldownUntil) {
497
+ console.error(`[wedge-watchdog] ${opts.agentName}: dismissing stuck per-tool ` + `permission prompt (Esc == decline == safe DENY) after ` + `${permissionPromptPresent} polls present ` + `(~${Math.round(permissionPromptPresent * pollIntervalMs / 1000)}s) \u2014 ` + `the prompt rendered as an interactive TUI with no TTL auto-deny, ` + `freezing the turn; no human to answer it`);
310
498
  try {
311
499
  send(opts.agentName, ["Escape"]);
312
500
  } catch (err) {
313
501
  console.error(`[wedge-watchdog] ${opts.agentName}: send threw: ${err.message}`);
314
502
  }
315
503
  fires++;
316
- rateLimitFires++;
317
- cooldownUntil = now() + cooldownMs;
318
- stableCount = 0;
319
- lastKey = null;
504
+ permissionPromptFires++;
505
+ permissionCooldownUntil = now() + cooldownMs;
506
+ permissionPromptPresent = 0;
507
+ }
508
+ } else if (isConfirmModal) {
509
+ confirmModalPresent++;
510
+ stableCount = 0;
511
+ lastKey = null;
512
+ permissionPromptPresent = 0;
513
+ if (confirmModalPresent >= confirmModalPolls && now() >= confirmCooldownUntil) {
514
+ console.error(`[wedge-watchdog] ${opts.agentName}: dismissing stuck confirmation modal ` + `(Esc == "No, go back") after ${confirmModalPresent} polls present ` + `(~${Math.round(confirmModalPresent * pollIntervalMs / 1000)}s, flicker-immune) ` + `\u2014 no human to answer it`);
515
+ try {
516
+ send(opts.agentName, ["Escape"]);
517
+ } catch (err) {
518
+ console.error(`[wedge-watchdog] ${opts.agentName}: send threw: ${err.message}`);
519
+ }
520
+ fires++;
521
+ confirmModalFires++;
522
+ confirmCooldownUntil = now() + cooldownMs;
523
+ confirmModalPresent = 0;
320
524
  }
321
525
  } else if (isBlockingModal) {
322
526
  const key = stabilityKey(text);
@@ -341,10 +545,21 @@ async function runWedgeWatchdog(opts) {
341
545
  } else {
342
546
  stableCount = 0;
343
547
  lastKey = null;
548
+ confirmModalPresent = 0;
549
+ permissionPromptPresent = 0;
344
550
  }
345
551
  await sleep(pollIntervalMs);
346
552
  }
347
- return { fires, rateLimitFires, polls, reason: "max-polls" };
553
+ return {
554
+ fires,
555
+ rateLimitFires,
556
+ overageCreditSelections,
557
+ confirmModalFires,
558
+ permissionPromptFires,
559
+ restartEscalations,
560
+ polls,
561
+ reason: "max-polls"
562
+ };
348
563
  }
349
564
 
350
565
  // src/agents/rate-limit-signal.ts
@@ -414,7 +629,4596 @@ function signalQuotaWall(agentName, resetAt, opts = {}) {
414
629
  });
415
630
  }
416
631
 
417
- // src/cli/autoaccept-poll.ts
632
+ // src/auth/broker/client.ts
633
+ import * as net from "node:net";
634
+ import { homedir } from "node:os";
635
+ import { randomUUID } from "node:crypto";
636
+ import { join as join2 } from "node:path";
637
+
638
+ // ../../switchroom/node_modules/.bun/zod@3.25.76/node_modules/zod/v3/external.js
639
+ var exports_external = {};
640
+ __export(exports_external, {
641
+ void: () => voidType,
642
+ util: () => util,
643
+ unknown: () => unknownType,
644
+ union: () => unionType,
645
+ undefined: () => undefinedType,
646
+ tuple: () => tupleType,
647
+ transformer: () => effectsType,
648
+ symbol: () => symbolType,
649
+ string: () => stringType,
650
+ strictObject: () => strictObjectType,
651
+ setErrorMap: () => setErrorMap,
652
+ set: () => setType,
653
+ record: () => recordType,
654
+ quotelessJson: () => quotelessJson,
655
+ promise: () => promiseType,
656
+ preprocess: () => preprocessType,
657
+ pipeline: () => pipelineType,
658
+ ostring: () => ostring,
659
+ optional: () => optionalType,
660
+ onumber: () => onumber,
661
+ oboolean: () => oboolean,
662
+ objectUtil: () => objectUtil,
663
+ object: () => objectType,
664
+ number: () => numberType,
665
+ nullable: () => nullableType,
666
+ null: () => nullType,
667
+ never: () => neverType,
668
+ nativeEnum: () => nativeEnumType,
669
+ nan: () => nanType,
670
+ map: () => mapType,
671
+ makeIssue: () => makeIssue,
672
+ literal: () => literalType,
673
+ lazy: () => lazyType,
674
+ late: () => late,
675
+ isValid: () => isValid,
676
+ isDirty: () => isDirty,
677
+ isAsync: () => isAsync,
678
+ isAborted: () => isAborted,
679
+ intersection: () => intersectionType,
680
+ instanceof: () => instanceOfType,
681
+ getParsedType: () => getParsedType,
682
+ getErrorMap: () => getErrorMap,
683
+ function: () => functionType,
684
+ enum: () => enumType,
685
+ effect: () => effectsType,
686
+ discriminatedUnion: () => discriminatedUnionType,
687
+ defaultErrorMap: () => en_default,
688
+ datetimeRegex: () => datetimeRegex,
689
+ date: () => dateType,
690
+ custom: () => custom,
691
+ coerce: () => coerce,
692
+ boolean: () => booleanType,
693
+ bigint: () => bigIntType,
694
+ array: () => arrayType,
695
+ any: () => anyType,
696
+ addIssueToContext: () => addIssueToContext,
697
+ ZodVoid: () => ZodVoid,
698
+ ZodUnknown: () => ZodUnknown,
699
+ ZodUnion: () => ZodUnion,
700
+ ZodUndefined: () => ZodUndefined,
701
+ ZodType: () => ZodType,
702
+ ZodTuple: () => ZodTuple,
703
+ ZodTransformer: () => ZodEffects,
704
+ ZodSymbol: () => ZodSymbol,
705
+ ZodString: () => ZodString,
706
+ ZodSet: () => ZodSet,
707
+ ZodSchema: () => ZodType,
708
+ ZodRecord: () => ZodRecord,
709
+ ZodReadonly: () => ZodReadonly,
710
+ ZodPromise: () => ZodPromise,
711
+ ZodPipeline: () => ZodPipeline,
712
+ ZodParsedType: () => ZodParsedType,
713
+ ZodOptional: () => ZodOptional,
714
+ ZodObject: () => ZodObject,
715
+ ZodNumber: () => ZodNumber,
716
+ ZodNullable: () => ZodNullable,
717
+ ZodNull: () => ZodNull,
718
+ ZodNever: () => ZodNever,
719
+ ZodNativeEnum: () => ZodNativeEnum,
720
+ ZodNaN: () => ZodNaN,
721
+ ZodMap: () => ZodMap,
722
+ ZodLiteral: () => ZodLiteral,
723
+ ZodLazy: () => ZodLazy,
724
+ ZodIssueCode: () => ZodIssueCode,
725
+ ZodIntersection: () => ZodIntersection,
726
+ ZodFunction: () => ZodFunction,
727
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
728
+ ZodError: () => ZodError,
729
+ ZodEnum: () => ZodEnum,
730
+ ZodEffects: () => ZodEffects,
731
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
732
+ ZodDefault: () => ZodDefault,
733
+ ZodDate: () => ZodDate,
734
+ ZodCatch: () => ZodCatch,
735
+ ZodBranded: () => ZodBranded,
736
+ ZodBoolean: () => ZodBoolean,
737
+ ZodBigInt: () => ZodBigInt,
738
+ ZodArray: () => ZodArray,
739
+ ZodAny: () => ZodAny,
740
+ Schema: () => ZodType,
741
+ ParseStatus: () => ParseStatus,
742
+ OK: () => OK,
743
+ NEVER: () => NEVER,
744
+ INVALID: () => INVALID,
745
+ EMPTY_PATH: () => EMPTY_PATH,
746
+ DIRTY: () => DIRTY,
747
+ BRAND: () => BRAND
748
+ });
749
+
750
+ // ../../switchroom/node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/util.js
751
+ var util;
752
+ (function(util2) {
753
+ util2.assertEqual = (_) => {};
754
+ function assertIs(_arg) {}
755
+ util2.assertIs = assertIs;
756
+ function assertNever(_x) {
757
+ throw new Error;
758
+ }
759
+ util2.assertNever = assertNever;
760
+ util2.arrayToEnum = (items) => {
761
+ const obj = {};
762
+ for (const item of items) {
763
+ obj[item] = item;
764
+ }
765
+ return obj;
766
+ };
767
+ util2.getValidEnumValues = (obj) => {
768
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
769
+ const filtered = {};
770
+ for (const k of validKeys) {
771
+ filtered[k] = obj[k];
772
+ }
773
+ return util2.objectValues(filtered);
774
+ };
775
+ util2.objectValues = (obj) => {
776
+ return util2.objectKeys(obj).map(function(e) {
777
+ return obj[e];
778
+ });
779
+ };
780
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
781
+ const keys = [];
782
+ for (const key in object) {
783
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
784
+ keys.push(key);
785
+ }
786
+ }
787
+ return keys;
788
+ };
789
+ util2.find = (arr, checker) => {
790
+ for (const item of arr) {
791
+ if (checker(item))
792
+ return item;
793
+ }
794
+ return;
795
+ };
796
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
797
+ function joinValues(array, separator = " | ") {
798
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
799
+ }
800
+ util2.joinValues = joinValues;
801
+ util2.jsonStringifyReplacer = (_, value) => {
802
+ if (typeof value === "bigint") {
803
+ return value.toString();
804
+ }
805
+ return value;
806
+ };
807
+ })(util || (util = {}));
808
+ var objectUtil;
809
+ (function(objectUtil2) {
810
+ objectUtil2.mergeShapes = (first, second) => {
811
+ return {
812
+ ...first,
813
+ ...second
814
+ };
815
+ };
816
+ })(objectUtil || (objectUtil = {}));
817
+ var ZodParsedType = util.arrayToEnum([
818
+ "string",
819
+ "nan",
820
+ "number",
821
+ "integer",
822
+ "float",
823
+ "boolean",
824
+ "date",
825
+ "bigint",
826
+ "symbol",
827
+ "function",
828
+ "undefined",
829
+ "null",
830
+ "array",
831
+ "object",
832
+ "unknown",
833
+ "promise",
834
+ "void",
835
+ "never",
836
+ "map",
837
+ "set"
838
+ ]);
839
+ var getParsedType = (data) => {
840
+ const t = typeof data;
841
+ switch (t) {
842
+ case "undefined":
843
+ return ZodParsedType.undefined;
844
+ case "string":
845
+ return ZodParsedType.string;
846
+ case "number":
847
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
848
+ case "boolean":
849
+ return ZodParsedType.boolean;
850
+ case "function":
851
+ return ZodParsedType.function;
852
+ case "bigint":
853
+ return ZodParsedType.bigint;
854
+ case "symbol":
855
+ return ZodParsedType.symbol;
856
+ case "object":
857
+ if (Array.isArray(data)) {
858
+ return ZodParsedType.array;
859
+ }
860
+ if (data === null) {
861
+ return ZodParsedType.null;
862
+ }
863
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
864
+ return ZodParsedType.promise;
865
+ }
866
+ if (typeof Map !== "undefined" && data instanceof Map) {
867
+ return ZodParsedType.map;
868
+ }
869
+ if (typeof Set !== "undefined" && data instanceof Set) {
870
+ return ZodParsedType.set;
871
+ }
872
+ if (typeof Date !== "undefined" && data instanceof Date) {
873
+ return ZodParsedType.date;
874
+ }
875
+ return ZodParsedType.object;
876
+ default:
877
+ return ZodParsedType.unknown;
878
+ }
879
+ };
880
+
881
+ // ../../switchroom/node_modules/.bun/zod@3.25.76/node_modules/zod/v3/ZodError.js
882
+ var ZodIssueCode = util.arrayToEnum([
883
+ "invalid_type",
884
+ "invalid_literal",
885
+ "custom",
886
+ "invalid_union",
887
+ "invalid_union_discriminator",
888
+ "invalid_enum_value",
889
+ "unrecognized_keys",
890
+ "invalid_arguments",
891
+ "invalid_return_type",
892
+ "invalid_date",
893
+ "invalid_string",
894
+ "too_small",
895
+ "too_big",
896
+ "invalid_intersection_types",
897
+ "not_multiple_of",
898
+ "not_finite"
899
+ ]);
900
+ var quotelessJson = (obj) => {
901
+ const json = JSON.stringify(obj, null, 2);
902
+ return json.replace(/"([^"]+)":/g, "$1:");
903
+ };
904
+
905
+ class ZodError extends Error {
906
+ get errors() {
907
+ return this.issues;
908
+ }
909
+ constructor(issues) {
910
+ super();
911
+ this.issues = [];
912
+ this.addIssue = (sub) => {
913
+ this.issues = [...this.issues, sub];
914
+ };
915
+ this.addIssues = (subs = []) => {
916
+ this.issues = [...this.issues, ...subs];
917
+ };
918
+ const actualProto = new.target.prototype;
919
+ if (Object.setPrototypeOf) {
920
+ Object.setPrototypeOf(this, actualProto);
921
+ } else {
922
+ this.__proto__ = actualProto;
923
+ }
924
+ this.name = "ZodError";
925
+ this.issues = issues;
926
+ }
927
+ format(_mapper) {
928
+ const mapper = _mapper || function(issue) {
929
+ return issue.message;
930
+ };
931
+ const fieldErrors = { _errors: [] };
932
+ const processError = (error) => {
933
+ for (const issue of error.issues) {
934
+ if (issue.code === "invalid_union") {
935
+ issue.unionErrors.map(processError);
936
+ } else if (issue.code === "invalid_return_type") {
937
+ processError(issue.returnTypeError);
938
+ } else if (issue.code === "invalid_arguments") {
939
+ processError(issue.argumentsError);
940
+ } else if (issue.path.length === 0) {
941
+ fieldErrors._errors.push(mapper(issue));
942
+ } else {
943
+ let curr = fieldErrors;
944
+ let i = 0;
945
+ while (i < issue.path.length) {
946
+ const el = issue.path[i];
947
+ const terminal = i === issue.path.length - 1;
948
+ if (!terminal) {
949
+ curr[el] = curr[el] || { _errors: [] };
950
+ } else {
951
+ curr[el] = curr[el] || { _errors: [] };
952
+ curr[el]._errors.push(mapper(issue));
953
+ }
954
+ curr = curr[el];
955
+ i++;
956
+ }
957
+ }
958
+ }
959
+ };
960
+ processError(this);
961
+ return fieldErrors;
962
+ }
963
+ static assert(value) {
964
+ if (!(value instanceof ZodError)) {
965
+ throw new Error(`Not a ZodError: ${value}`);
966
+ }
967
+ }
968
+ toString() {
969
+ return this.message;
970
+ }
971
+ get message() {
972
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
973
+ }
974
+ get isEmpty() {
975
+ return this.issues.length === 0;
976
+ }
977
+ flatten(mapper = (issue) => issue.message) {
978
+ const fieldErrors = {};
979
+ const formErrors = [];
980
+ for (const sub of this.issues) {
981
+ if (sub.path.length > 0) {
982
+ const firstEl = sub.path[0];
983
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
984
+ fieldErrors[firstEl].push(mapper(sub));
985
+ } else {
986
+ formErrors.push(mapper(sub));
987
+ }
988
+ }
989
+ return { formErrors, fieldErrors };
990
+ }
991
+ get formErrors() {
992
+ return this.flatten();
993
+ }
994
+ }
995
+ ZodError.create = (issues) => {
996
+ const error = new ZodError(issues);
997
+ return error;
998
+ };
999
+
1000
+ // ../../switchroom/node_modules/.bun/zod@3.25.76/node_modules/zod/v3/locales/en.js
1001
+ var errorMap = (issue, _ctx) => {
1002
+ let message;
1003
+ switch (issue.code) {
1004
+ case ZodIssueCode.invalid_type:
1005
+ if (issue.received === ZodParsedType.undefined) {
1006
+ message = "Required";
1007
+ } else {
1008
+ message = `Expected ${issue.expected}, received ${issue.received}`;
1009
+ }
1010
+ break;
1011
+ case ZodIssueCode.invalid_literal:
1012
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
1013
+ break;
1014
+ case ZodIssueCode.unrecognized_keys:
1015
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
1016
+ break;
1017
+ case ZodIssueCode.invalid_union:
1018
+ message = `Invalid input`;
1019
+ break;
1020
+ case ZodIssueCode.invalid_union_discriminator:
1021
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
1022
+ break;
1023
+ case ZodIssueCode.invalid_enum_value:
1024
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
1025
+ break;
1026
+ case ZodIssueCode.invalid_arguments:
1027
+ message = `Invalid function arguments`;
1028
+ break;
1029
+ case ZodIssueCode.invalid_return_type:
1030
+ message = `Invalid function return type`;
1031
+ break;
1032
+ case ZodIssueCode.invalid_date:
1033
+ message = `Invalid date`;
1034
+ break;
1035
+ case ZodIssueCode.invalid_string:
1036
+ if (typeof issue.validation === "object") {
1037
+ if ("includes" in issue.validation) {
1038
+ message = `Invalid input: must include "${issue.validation.includes}"`;
1039
+ if (typeof issue.validation.position === "number") {
1040
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
1041
+ }
1042
+ } else if ("startsWith" in issue.validation) {
1043
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
1044
+ } else if ("endsWith" in issue.validation) {
1045
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
1046
+ } else {
1047
+ util.assertNever(issue.validation);
1048
+ }
1049
+ } else if (issue.validation !== "regex") {
1050
+ message = `Invalid ${issue.validation}`;
1051
+ } else {
1052
+ message = "Invalid";
1053
+ }
1054
+ break;
1055
+ case ZodIssueCode.too_small:
1056
+ if (issue.type === "array")
1057
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
1058
+ else if (issue.type === "string")
1059
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
1060
+ else if (issue.type === "number")
1061
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1062
+ else if (issue.type === "bigint")
1063
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1064
+ else if (issue.type === "date")
1065
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
1066
+ else
1067
+ message = "Invalid input";
1068
+ break;
1069
+ case ZodIssueCode.too_big:
1070
+ if (issue.type === "array")
1071
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
1072
+ else if (issue.type === "string")
1073
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
1074
+ else if (issue.type === "number")
1075
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1076
+ else if (issue.type === "bigint")
1077
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1078
+ else if (issue.type === "date")
1079
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
1080
+ else
1081
+ message = "Invalid input";
1082
+ break;
1083
+ case ZodIssueCode.custom:
1084
+ message = `Invalid input`;
1085
+ break;
1086
+ case ZodIssueCode.invalid_intersection_types:
1087
+ message = `Intersection results could not be merged`;
1088
+ break;
1089
+ case ZodIssueCode.not_multiple_of:
1090
+ message = `Number must be a multiple of ${issue.multipleOf}`;
1091
+ break;
1092
+ case ZodIssueCode.not_finite:
1093
+ message = "Number must be finite";
1094
+ break;
1095
+ default:
1096
+ message = _ctx.defaultError;
1097
+ util.assertNever(issue);
1098
+ }
1099
+ return { message };
1100
+ };
1101
+ var en_default = errorMap;
1102
+
1103
+ // ../../switchroom/node_modules/.bun/zod@3.25.76/node_modules/zod/v3/errors.js
1104
+ var overrideErrorMap = en_default;
1105
+ function setErrorMap(map) {
1106
+ overrideErrorMap = map;
1107
+ }
1108
+ function getErrorMap() {
1109
+ return overrideErrorMap;
1110
+ }
1111
+ // ../../switchroom/node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
1112
+ var makeIssue = (params) => {
1113
+ const { data, path, errorMaps, issueData } = params;
1114
+ const fullPath = [...path, ...issueData.path || []];
1115
+ const fullIssue = {
1116
+ ...issueData,
1117
+ path: fullPath
1118
+ };
1119
+ if (issueData.message !== undefined) {
1120
+ return {
1121
+ ...issueData,
1122
+ path: fullPath,
1123
+ message: issueData.message
1124
+ };
1125
+ }
1126
+ let errorMessage = "";
1127
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
1128
+ for (const map of maps) {
1129
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
1130
+ }
1131
+ return {
1132
+ ...issueData,
1133
+ path: fullPath,
1134
+ message: errorMessage
1135
+ };
1136
+ };
1137
+ var EMPTY_PATH = [];
1138
+ function addIssueToContext(ctx, issueData) {
1139
+ const overrideMap = getErrorMap();
1140
+ const issue = makeIssue({
1141
+ issueData,
1142
+ data: ctx.data,
1143
+ path: ctx.path,
1144
+ errorMaps: [
1145
+ ctx.common.contextualErrorMap,
1146
+ ctx.schemaErrorMap,
1147
+ overrideMap,
1148
+ overrideMap === en_default ? undefined : en_default
1149
+ ].filter((x) => !!x)
1150
+ });
1151
+ ctx.common.issues.push(issue);
1152
+ }
1153
+
1154
+ class ParseStatus {
1155
+ constructor() {
1156
+ this.value = "valid";
1157
+ }
1158
+ dirty() {
1159
+ if (this.value === "valid")
1160
+ this.value = "dirty";
1161
+ }
1162
+ abort() {
1163
+ if (this.value !== "aborted")
1164
+ this.value = "aborted";
1165
+ }
1166
+ static mergeArray(status, results) {
1167
+ const arrayValue = [];
1168
+ for (const s of results) {
1169
+ if (s.status === "aborted")
1170
+ return INVALID;
1171
+ if (s.status === "dirty")
1172
+ status.dirty();
1173
+ arrayValue.push(s.value);
1174
+ }
1175
+ return { status: status.value, value: arrayValue };
1176
+ }
1177
+ static async mergeObjectAsync(status, pairs) {
1178
+ const syncPairs = [];
1179
+ for (const pair of pairs) {
1180
+ const key = await pair.key;
1181
+ const value = await pair.value;
1182
+ syncPairs.push({
1183
+ key,
1184
+ value
1185
+ });
1186
+ }
1187
+ return ParseStatus.mergeObjectSync(status, syncPairs);
1188
+ }
1189
+ static mergeObjectSync(status, pairs) {
1190
+ const finalObject = {};
1191
+ for (const pair of pairs) {
1192
+ const { key, value } = pair;
1193
+ if (key.status === "aborted")
1194
+ return INVALID;
1195
+ if (value.status === "aborted")
1196
+ return INVALID;
1197
+ if (key.status === "dirty")
1198
+ status.dirty();
1199
+ if (value.status === "dirty")
1200
+ status.dirty();
1201
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1202
+ finalObject[key.value] = value.value;
1203
+ }
1204
+ }
1205
+ return { status: status.value, value: finalObject };
1206
+ }
1207
+ }
1208
+ var INVALID = Object.freeze({
1209
+ status: "aborted"
1210
+ });
1211
+ var DIRTY = (value) => ({ status: "dirty", value });
1212
+ var OK = (value) => ({ status: "valid", value });
1213
+ var isAborted = (x) => x.status === "aborted";
1214
+ var isDirty = (x) => x.status === "dirty";
1215
+ var isValid = (x) => x.status === "valid";
1216
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1217
+ // ../../switchroom/node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
1218
+ var errorUtil;
1219
+ (function(errorUtil2) {
1220
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1221
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
1222
+ })(errorUtil || (errorUtil = {}));
1223
+
1224
+ // ../../switchroom/node_modules/.bun/zod@3.25.76/node_modules/zod/v3/types.js
1225
+ class ParseInputLazyPath {
1226
+ constructor(parent, value, path, key) {
1227
+ this._cachedPath = [];
1228
+ this.parent = parent;
1229
+ this.data = value;
1230
+ this._path = path;
1231
+ this._key = key;
1232
+ }
1233
+ get path() {
1234
+ if (!this._cachedPath.length) {
1235
+ if (Array.isArray(this._key)) {
1236
+ this._cachedPath.push(...this._path, ...this._key);
1237
+ } else {
1238
+ this._cachedPath.push(...this._path, this._key);
1239
+ }
1240
+ }
1241
+ return this._cachedPath;
1242
+ }
1243
+ }
1244
+ var handleResult = (ctx, result) => {
1245
+ if (isValid(result)) {
1246
+ return { success: true, data: result.value };
1247
+ } else {
1248
+ if (!ctx.common.issues.length) {
1249
+ throw new Error("Validation failed but no issues detected.");
1250
+ }
1251
+ return {
1252
+ success: false,
1253
+ get error() {
1254
+ if (this._error)
1255
+ return this._error;
1256
+ const error = new ZodError(ctx.common.issues);
1257
+ this._error = error;
1258
+ return this._error;
1259
+ }
1260
+ };
1261
+ }
1262
+ };
1263
+ function processCreateParams(params) {
1264
+ if (!params)
1265
+ return {};
1266
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
1267
+ if (errorMap2 && (invalid_type_error || required_error)) {
1268
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
1269
+ }
1270
+ if (errorMap2)
1271
+ return { errorMap: errorMap2, description };
1272
+ const customMap = (iss, ctx) => {
1273
+ const { message } = params;
1274
+ if (iss.code === "invalid_enum_value") {
1275
+ return { message: message ?? ctx.defaultError };
1276
+ }
1277
+ if (typeof ctx.data === "undefined") {
1278
+ return { message: message ?? required_error ?? ctx.defaultError };
1279
+ }
1280
+ if (iss.code !== "invalid_type")
1281
+ return { message: ctx.defaultError };
1282
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
1283
+ };
1284
+ return { errorMap: customMap, description };
1285
+ }
1286
+
1287
+ class ZodType {
1288
+ get description() {
1289
+ return this._def.description;
1290
+ }
1291
+ _getType(input) {
1292
+ return getParsedType(input.data);
1293
+ }
1294
+ _getOrReturnCtx(input, ctx) {
1295
+ return ctx || {
1296
+ common: input.parent.common,
1297
+ data: input.data,
1298
+ parsedType: getParsedType(input.data),
1299
+ schemaErrorMap: this._def.errorMap,
1300
+ path: input.path,
1301
+ parent: input.parent
1302
+ };
1303
+ }
1304
+ _processInputParams(input) {
1305
+ return {
1306
+ status: new ParseStatus,
1307
+ ctx: {
1308
+ common: input.parent.common,
1309
+ data: input.data,
1310
+ parsedType: getParsedType(input.data),
1311
+ schemaErrorMap: this._def.errorMap,
1312
+ path: input.path,
1313
+ parent: input.parent
1314
+ }
1315
+ };
1316
+ }
1317
+ _parseSync(input) {
1318
+ const result = this._parse(input);
1319
+ if (isAsync(result)) {
1320
+ throw new Error("Synchronous parse encountered promise.");
1321
+ }
1322
+ return result;
1323
+ }
1324
+ _parseAsync(input) {
1325
+ const result = this._parse(input);
1326
+ return Promise.resolve(result);
1327
+ }
1328
+ parse(data, params) {
1329
+ const result = this.safeParse(data, params);
1330
+ if (result.success)
1331
+ return result.data;
1332
+ throw result.error;
1333
+ }
1334
+ safeParse(data, params) {
1335
+ const ctx = {
1336
+ common: {
1337
+ issues: [],
1338
+ async: params?.async ?? false,
1339
+ contextualErrorMap: params?.errorMap
1340
+ },
1341
+ path: params?.path || [],
1342
+ schemaErrorMap: this._def.errorMap,
1343
+ parent: null,
1344
+ data,
1345
+ parsedType: getParsedType(data)
1346
+ };
1347
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1348
+ return handleResult(ctx, result);
1349
+ }
1350
+ "~validate"(data) {
1351
+ const ctx = {
1352
+ common: {
1353
+ issues: [],
1354
+ async: !!this["~standard"].async
1355
+ },
1356
+ path: [],
1357
+ schemaErrorMap: this._def.errorMap,
1358
+ parent: null,
1359
+ data,
1360
+ parsedType: getParsedType(data)
1361
+ };
1362
+ if (!this["~standard"].async) {
1363
+ try {
1364
+ const result = this._parseSync({ data, path: [], parent: ctx });
1365
+ return isValid(result) ? {
1366
+ value: result.value
1367
+ } : {
1368
+ issues: ctx.common.issues
1369
+ };
1370
+ } catch (err) {
1371
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
1372
+ this["~standard"].async = true;
1373
+ }
1374
+ ctx.common = {
1375
+ issues: [],
1376
+ async: true
1377
+ };
1378
+ }
1379
+ }
1380
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1381
+ value: result.value
1382
+ } : {
1383
+ issues: ctx.common.issues
1384
+ });
1385
+ }
1386
+ async parseAsync(data, params) {
1387
+ const result = await this.safeParseAsync(data, params);
1388
+ if (result.success)
1389
+ return result.data;
1390
+ throw result.error;
1391
+ }
1392
+ async safeParseAsync(data, params) {
1393
+ const ctx = {
1394
+ common: {
1395
+ issues: [],
1396
+ contextualErrorMap: params?.errorMap,
1397
+ async: true
1398
+ },
1399
+ path: params?.path || [],
1400
+ schemaErrorMap: this._def.errorMap,
1401
+ parent: null,
1402
+ data,
1403
+ parsedType: getParsedType(data)
1404
+ };
1405
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1406
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1407
+ return handleResult(ctx, result);
1408
+ }
1409
+ refine(check, message) {
1410
+ const getIssueProperties = (val) => {
1411
+ if (typeof message === "string" || typeof message === "undefined") {
1412
+ return { message };
1413
+ } else if (typeof message === "function") {
1414
+ return message(val);
1415
+ } else {
1416
+ return message;
1417
+ }
1418
+ };
1419
+ return this._refinement((val, ctx) => {
1420
+ const result = check(val);
1421
+ const setError = () => ctx.addIssue({
1422
+ code: ZodIssueCode.custom,
1423
+ ...getIssueProperties(val)
1424
+ });
1425
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1426
+ return result.then((data) => {
1427
+ if (!data) {
1428
+ setError();
1429
+ return false;
1430
+ } else {
1431
+ return true;
1432
+ }
1433
+ });
1434
+ }
1435
+ if (!result) {
1436
+ setError();
1437
+ return false;
1438
+ } else {
1439
+ return true;
1440
+ }
1441
+ });
1442
+ }
1443
+ refinement(check, refinementData) {
1444
+ return this._refinement((val, ctx) => {
1445
+ if (!check(val)) {
1446
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1447
+ return false;
1448
+ } else {
1449
+ return true;
1450
+ }
1451
+ });
1452
+ }
1453
+ _refinement(refinement) {
1454
+ return new ZodEffects({
1455
+ schema: this,
1456
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1457
+ effect: { type: "refinement", refinement }
1458
+ });
1459
+ }
1460
+ superRefine(refinement) {
1461
+ return this._refinement(refinement);
1462
+ }
1463
+ constructor(def) {
1464
+ this.spa = this.safeParseAsync;
1465
+ this._def = def;
1466
+ this.parse = this.parse.bind(this);
1467
+ this.safeParse = this.safeParse.bind(this);
1468
+ this.parseAsync = this.parseAsync.bind(this);
1469
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1470
+ this.spa = this.spa.bind(this);
1471
+ this.refine = this.refine.bind(this);
1472
+ this.refinement = this.refinement.bind(this);
1473
+ this.superRefine = this.superRefine.bind(this);
1474
+ this.optional = this.optional.bind(this);
1475
+ this.nullable = this.nullable.bind(this);
1476
+ this.nullish = this.nullish.bind(this);
1477
+ this.array = this.array.bind(this);
1478
+ this.promise = this.promise.bind(this);
1479
+ this.or = this.or.bind(this);
1480
+ this.and = this.and.bind(this);
1481
+ this.transform = this.transform.bind(this);
1482
+ this.brand = this.brand.bind(this);
1483
+ this.default = this.default.bind(this);
1484
+ this.catch = this.catch.bind(this);
1485
+ this.describe = this.describe.bind(this);
1486
+ this.pipe = this.pipe.bind(this);
1487
+ this.readonly = this.readonly.bind(this);
1488
+ this.isNullable = this.isNullable.bind(this);
1489
+ this.isOptional = this.isOptional.bind(this);
1490
+ this["~standard"] = {
1491
+ version: 1,
1492
+ vendor: "zod",
1493
+ validate: (data) => this["~validate"](data)
1494
+ };
1495
+ }
1496
+ optional() {
1497
+ return ZodOptional.create(this, this._def);
1498
+ }
1499
+ nullable() {
1500
+ return ZodNullable.create(this, this._def);
1501
+ }
1502
+ nullish() {
1503
+ return this.nullable().optional();
1504
+ }
1505
+ array() {
1506
+ return ZodArray.create(this);
1507
+ }
1508
+ promise() {
1509
+ return ZodPromise.create(this, this._def);
1510
+ }
1511
+ or(option) {
1512
+ return ZodUnion.create([this, option], this._def);
1513
+ }
1514
+ and(incoming) {
1515
+ return ZodIntersection.create(this, incoming, this._def);
1516
+ }
1517
+ transform(transform) {
1518
+ return new ZodEffects({
1519
+ ...processCreateParams(this._def),
1520
+ schema: this,
1521
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1522
+ effect: { type: "transform", transform }
1523
+ });
1524
+ }
1525
+ default(def) {
1526
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1527
+ return new ZodDefault({
1528
+ ...processCreateParams(this._def),
1529
+ innerType: this,
1530
+ defaultValue: defaultValueFunc,
1531
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1532
+ });
1533
+ }
1534
+ brand() {
1535
+ return new ZodBranded({
1536
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1537
+ type: this,
1538
+ ...processCreateParams(this._def)
1539
+ });
1540
+ }
1541
+ catch(def) {
1542
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1543
+ return new ZodCatch({
1544
+ ...processCreateParams(this._def),
1545
+ innerType: this,
1546
+ catchValue: catchValueFunc,
1547
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1548
+ });
1549
+ }
1550
+ describe(description) {
1551
+ const This = this.constructor;
1552
+ return new This({
1553
+ ...this._def,
1554
+ description
1555
+ });
1556
+ }
1557
+ pipe(target) {
1558
+ return ZodPipeline.create(this, target);
1559
+ }
1560
+ readonly() {
1561
+ return ZodReadonly.create(this);
1562
+ }
1563
+ isOptional() {
1564
+ return this.safeParse(undefined).success;
1565
+ }
1566
+ isNullable() {
1567
+ return this.safeParse(null).success;
1568
+ }
1569
+ }
1570
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1571
+ var cuid2Regex = /^[0-9a-z]+$/;
1572
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1573
+ 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;
1574
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1575
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1576
+ 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)?)??$/;
1577
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1578
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1579
+ var emojiRegex;
1580
+ 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])$/;
1581
+ 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])$/;
1582
+ 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]))$/;
1583
+ 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])$/;
1584
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1585
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1586
+ 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])))`;
1587
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
1588
+ function timeRegexSource(args) {
1589
+ let secondsRegexSource = `[0-5]\\d`;
1590
+ if (args.precision) {
1591
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1592
+ } else if (args.precision == null) {
1593
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1594
+ }
1595
+ const secondsQuantifier = args.precision ? "+" : "?";
1596
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1597
+ }
1598
+ function timeRegex(args) {
1599
+ return new RegExp(`^${timeRegexSource(args)}$`);
1600
+ }
1601
+ function datetimeRegex(args) {
1602
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1603
+ const opts = [];
1604
+ opts.push(args.local ? `Z?` : `Z`);
1605
+ if (args.offset)
1606
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1607
+ regex = `${regex}(${opts.join("|")})`;
1608
+ return new RegExp(`^${regex}$`);
1609
+ }
1610
+ function isValidIP(ip, version) {
1611
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1612
+ return true;
1613
+ }
1614
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1615
+ return true;
1616
+ }
1617
+ return false;
1618
+ }
1619
+ function isValidJWT(jwt, alg) {
1620
+ if (!jwtRegex.test(jwt))
1621
+ return false;
1622
+ try {
1623
+ const [header] = jwt.split(".");
1624
+ if (!header)
1625
+ return false;
1626
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1627
+ const decoded = JSON.parse(atob(base64));
1628
+ if (typeof decoded !== "object" || decoded === null)
1629
+ return false;
1630
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1631
+ return false;
1632
+ if (!decoded.alg)
1633
+ return false;
1634
+ if (alg && decoded.alg !== alg)
1635
+ return false;
1636
+ return true;
1637
+ } catch {
1638
+ return false;
1639
+ }
1640
+ }
1641
+ function isValidCidr(ip, version) {
1642
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1643
+ return true;
1644
+ }
1645
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1646
+ return true;
1647
+ }
1648
+ return false;
1649
+ }
1650
+
1651
+ class ZodString extends ZodType {
1652
+ _parse(input) {
1653
+ if (this._def.coerce) {
1654
+ input.data = String(input.data);
1655
+ }
1656
+ const parsedType = this._getType(input);
1657
+ if (parsedType !== ZodParsedType.string) {
1658
+ const ctx2 = this._getOrReturnCtx(input);
1659
+ addIssueToContext(ctx2, {
1660
+ code: ZodIssueCode.invalid_type,
1661
+ expected: ZodParsedType.string,
1662
+ received: ctx2.parsedType
1663
+ });
1664
+ return INVALID;
1665
+ }
1666
+ const status = new ParseStatus;
1667
+ let ctx = undefined;
1668
+ for (const check of this._def.checks) {
1669
+ if (check.kind === "min") {
1670
+ if (input.data.length < check.value) {
1671
+ ctx = this._getOrReturnCtx(input, ctx);
1672
+ addIssueToContext(ctx, {
1673
+ code: ZodIssueCode.too_small,
1674
+ minimum: check.value,
1675
+ type: "string",
1676
+ inclusive: true,
1677
+ exact: false,
1678
+ message: check.message
1679
+ });
1680
+ status.dirty();
1681
+ }
1682
+ } else if (check.kind === "max") {
1683
+ if (input.data.length > check.value) {
1684
+ ctx = this._getOrReturnCtx(input, ctx);
1685
+ addIssueToContext(ctx, {
1686
+ code: ZodIssueCode.too_big,
1687
+ maximum: check.value,
1688
+ type: "string",
1689
+ inclusive: true,
1690
+ exact: false,
1691
+ message: check.message
1692
+ });
1693
+ status.dirty();
1694
+ }
1695
+ } else if (check.kind === "length") {
1696
+ const tooBig = input.data.length > check.value;
1697
+ const tooSmall = input.data.length < check.value;
1698
+ if (tooBig || tooSmall) {
1699
+ ctx = this._getOrReturnCtx(input, ctx);
1700
+ if (tooBig) {
1701
+ addIssueToContext(ctx, {
1702
+ code: ZodIssueCode.too_big,
1703
+ maximum: check.value,
1704
+ type: "string",
1705
+ inclusive: true,
1706
+ exact: true,
1707
+ message: check.message
1708
+ });
1709
+ } else if (tooSmall) {
1710
+ addIssueToContext(ctx, {
1711
+ code: ZodIssueCode.too_small,
1712
+ minimum: check.value,
1713
+ type: "string",
1714
+ inclusive: true,
1715
+ exact: true,
1716
+ message: check.message
1717
+ });
1718
+ }
1719
+ status.dirty();
1720
+ }
1721
+ } else if (check.kind === "email") {
1722
+ if (!emailRegex.test(input.data)) {
1723
+ ctx = this._getOrReturnCtx(input, ctx);
1724
+ addIssueToContext(ctx, {
1725
+ validation: "email",
1726
+ code: ZodIssueCode.invalid_string,
1727
+ message: check.message
1728
+ });
1729
+ status.dirty();
1730
+ }
1731
+ } else if (check.kind === "emoji") {
1732
+ if (!emojiRegex) {
1733
+ emojiRegex = new RegExp(_emojiRegex, "u");
1734
+ }
1735
+ if (!emojiRegex.test(input.data)) {
1736
+ ctx = this._getOrReturnCtx(input, ctx);
1737
+ addIssueToContext(ctx, {
1738
+ validation: "emoji",
1739
+ code: ZodIssueCode.invalid_string,
1740
+ message: check.message
1741
+ });
1742
+ status.dirty();
1743
+ }
1744
+ } else if (check.kind === "uuid") {
1745
+ if (!uuidRegex.test(input.data)) {
1746
+ ctx = this._getOrReturnCtx(input, ctx);
1747
+ addIssueToContext(ctx, {
1748
+ validation: "uuid",
1749
+ code: ZodIssueCode.invalid_string,
1750
+ message: check.message
1751
+ });
1752
+ status.dirty();
1753
+ }
1754
+ } else if (check.kind === "nanoid") {
1755
+ if (!nanoidRegex.test(input.data)) {
1756
+ ctx = this._getOrReturnCtx(input, ctx);
1757
+ addIssueToContext(ctx, {
1758
+ validation: "nanoid",
1759
+ code: ZodIssueCode.invalid_string,
1760
+ message: check.message
1761
+ });
1762
+ status.dirty();
1763
+ }
1764
+ } else if (check.kind === "cuid") {
1765
+ if (!cuidRegex.test(input.data)) {
1766
+ ctx = this._getOrReturnCtx(input, ctx);
1767
+ addIssueToContext(ctx, {
1768
+ validation: "cuid",
1769
+ code: ZodIssueCode.invalid_string,
1770
+ message: check.message
1771
+ });
1772
+ status.dirty();
1773
+ }
1774
+ } else if (check.kind === "cuid2") {
1775
+ if (!cuid2Regex.test(input.data)) {
1776
+ ctx = this._getOrReturnCtx(input, ctx);
1777
+ addIssueToContext(ctx, {
1778
+ validation: "cuid2",
1779
+ code: ZodIssueCode.invalid_string,
1780
+ message: check.message
1781
+ });
1782
+ status.dirty();
1783
+ }
1784
+ } else if (check.kind === "ulid") {
1785
+ if (!ulidRegex.test(input.data)) {
1786
+ ctx = this._getOrReturnCtx(input, ctx);
1787
+ addIssueToContext(ctx, {
1788
+ validation: "ulid",
1789
+ code: ZodIssueCode.invalid_string,
1790
+ message: check.message
1791
+ });
1792
+ status.dirty();
1793
+ }
1794
+ } else if (check.kind === "url") {
1795
+ try {
1796
+ new URL(input.data);
1797
+ } catch {
1798
+ ctx = this._getOrReturnCtx(input, ctx);
1799
+ addIssueToContext(ctx, {
1800
+ validation: "url",
1801
+ code: ZodIssueCode.invalid_string,
1802
+ message: check.message
1803
+ });
1804
+ status.dirty();
1805
+ }
1806
+ } else if (check.kind === "regex") {
1807
+ check.regex.lastIndex = 0;
1808
+ const testResult = check.regex.test(input.data);
1809
+ if (!testResult) {
1810
+ ctx = this._getOrReturnCtx(input, ctx);
1811
+ addIssueToContext(ctx, {
1812
+ validation: "regex",
1813
+ code: ZodIssueCode.invalid_string,
1814
+ message: check.message
1815
+ });
1816
+ status.dirty();
1817
+ }
1818
+ } else if (check.kind === "trim") {
1819
+ input.data = input.data.trim();
1820
+ } else if (check.kind === "includes") {
1821
+ if (!input.data.includes(check.value, check.position)) {
1822
+ ctx = this._getOrReturnCtx(input, ctx);
1823
+ addIssueToContext(ctx, {
1824
+ code: ZodIssueCode.invalid_string,
1825
+ validation: { includes: check.value, position: check.position },
1826
+ message: check.message
1827
+ });
1828
+ status.dirty();
1829
+ }
1830
+ } else if (check.kind === "toLowerCase") {
1831
+ input.data = input.data.toLowerCase();
1832
+ } else if (check.kind === "toUpperCase") {
1833
+ input.data = input.data.toUpperCase();
1834
+ } else if (check.kind === "startsWith") {
1835
+ if (!input.data.startsWith(check.value)) {
1836
+ ctx = this._getOrReturnCtx(input, ctx);
1837
+ addIssueToContext(ctx, {
1838
+ code: ZodIssueCode.invalid_string,
1839
+ validation: { startsWith: check.value },
1840
+ message: check.message
1841
+ });
1842
+ status.dirty();
1843
+ }
1844
+ } else if (check.kind === "endsWith") {
1845
+ if (!input.data.endsWith(check.value)) {
1846
+ ctx = this._getOrReturnCtx(input, ctx);
1847
+ addIssueToContext(ctx, {
1848
+ code: ZodIssueCode.invalid_string,
1849
+ validation: { endsWith: check.value },
1850
+ message: check.message
1851
+ });
1852
+ status.dirty();
1853
+ }
1854
+ } else if (check.kind === "datetime") {
1855
+ const regex = datetimeRegex(check);
1856
+ if (!regex.test(input.data)) {
1857
+ ctx = this._getOrReturnCtx(input, ctx);
1858
+ addIssueToContext(ctx, {
1859
+ code: ZodIssueCode.invalid_string,
1860
+ validation: "datetime",
1861
+ message: check.message
1862
+ });
1863
+ status.dirty();
1864
+ }
1865
+ } else if (check.kind === "date") {
1866
+ const regex = dateRegex;
1867
+ if (!regex.test(input.data)) {
1868
+ ctx = this._getOrReturnCtx(input, ctx);
1869
+ addIssueToContext(ctx, {
1870
+ code: ZodIssueCode.invalid_string,
1871
+ validation: "date",
1872
+ message: check.message
1873
+ });
1874
+ status.dirty();
1875
+ }
1876
+ } else if (check.kind === "time") {
1877
+ const regex = timeRegex(check);
1878
+ if (!regex.test(input.data)) {
1879
+ ctx = this._getOrReturnCtx(input, ctx);
1880
+ addIssueToContext(ctx, {
1881
+ code: ZodIssueCode.invalid_string,
1882
+ validation: "time",
1883
+ message: check.message
1884
+ });
1885
+ status.dirty();
1886
+ }
1887
+ } else if (check.kind === "duration") {
1888
+ if (!durationRegex.test(input.data)) {
1889
+ ctx = this._getOrReturnCtx(input, ctx);
1890
+ addIssueToContext(ctx, {
1891
+ validation: "duration",
1892
+ code: ZodIssueCode.invalid_string,
1893
+ message: check.message
1894
+ });
1895
+ status.dirty();
1896
+ }
1897
+ } else if (check.kind === "ip") {
1898
+ if (!isValidIP(input.data, check.version)) {
1899
+ ctx = this._getOrReturnCtx(input, ctx);
1900
+ addIssueToContext(ctx, {
1901
+ validation: "ip",
1902
+ code: ZodIssueCode.invalid_string,
1903
+ message: check.message
1904
+ });
1905
+ status.dirty();
1906
+ }
1907
+ } else if (check.kind === "jwt") {
1908
+ if (!isValidJWT(input.data, check.alg)) {
1909
+ ctx = this._getOrReturnCtx(input, ctx);
1910
+ addIssueToContext(ctx, {
1911
+ validation: "jwt",
1912
+ code: ZodIssueCode.invalid_string,
1913
+ message: check.message
1914
+ });
1915
+ status.dirty();
1916
+ }
1917
+ } else if (check.kind === "cidr") {
1918
+ if (!isValidCidr(input.data, check.version)) {
1919
+ ctx = this._getOrReturnCtx(input, ctx);
1920
+ addIssueToContext(ctx, {
1921
+ validation: "cidr",
1922
+ code: ZodIssueCode.invalid_string,
1923
+ message: check.message
1924
+ });
1925
+ status.dirty();
1926
+ }
1927
+ } else if (check.kind === "base64") {
1928
+ if (!base64Regex.test(input.data)) {
1929
+ ctx = this._getOrReturnCtx(input, ctx);
1930
+ addIssueToContext(ctx, {
1931
+ validation: "base64",
1932
+ code: ZodIssueCode.invalid_string,
1933
+ message: check.message
1934
+ });
1935
+ status.dirty();
1936
+ }
1937
+ } else if (check.kind === "base64url") {
1938
+ if (!base64urlRegex.test(input.data)) {
1939
+ ctx = this._getOrReturnCtx(input, ctx);
1940
+ addIssueToContext(ctx, {
1941
+ validation: "base64url",
1942
+ code: ZodIssueCode.invalid_string,
1943
+ message: check.message
1944
+ });
1945
+ status.dirty();
1946
+ }
1947
+ } else {
1948
+ util.assertNever(check);
1949
+ }
1950
+ }
1951
+ return { status: status.value, value: input.data };
1952
+ }
1953
+ _regex(regex, validation, message) {
1954
+ return this.refinement((data) => regex.test(data), {
1955
+ validation,
1956
+ code: ZodIssueCode.invalid_string,
1957
+ ...errorUtil.errToObj(message)
1958
+ });
1959
+ }
1960
+ _addCheck(check) {
1961
+ return new ZodString({
1962
+ ...this._def,
1963
+ checks: [...this._def.checks, check]
1964
+ });
1965
+ }
1966
+ email(message) {
1967
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1968
+ }
1969
+ url(message) {
1970
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1971
+ }
1972
+ emoji(message) {
1973
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1974
+ }
1975
+ uuid(message) {
1976
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1977
+ }
1978
+ nanoid(message) {
1979
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1980
+ }
1981
+ cuid(message) {
1982
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1983
+ }
1984
+ cuid2(message) {
1985
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1986
+ }
1987
+ ulid(message) {
1988
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1989
+ }
1990
+ base64(message) {
1991
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1992
+ }
1993
+ base64url(message) {
1994
+ return this._addCheck({
1995
+ kind: "base64url",
1996
+ ...errorUtil.errToObj(message)
1997
+ });
1998
+ }
1999
+ jwt(options) {
2000
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
2001
+ }
2002
+ ip(options) {
2003
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
2004
+ }
2005
+ cidr(options) {
2006
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
2007
+ }
2008
+ datetime(options) {
2009
+ if (typeof options === "string") {
2010
+ return this._addCheck({
2011
+ kind: "datetime",
2012
+ precision: null,
2013
+ offset: false,
2014
+ local: false,
2015
+ message: options
2016
+ });
2017
+ }
2018
+ return this._addCheck({
2019
+ kind: "datetime",
2020
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
2021
+ offset: options?.offset ?? false,
2022
+ local: options?.local ?? false,
2023
+ ...errorUtil.errToObj(options?.message)
2024
+ });
2025
+ }
2026
+ date(message) {
2027
+ return this._addCheck({ kind: "date", message });
2028
+ }
2029
+ time(options) {
2030
+ if (typeof options === "string") {
2031
+ return this._addCheck({
2032
+ kind: "time",
2033
+ precision: null,
2034
+ message: options
2035
+ });
2036
+ }
2037
+ return this._addCheck({
2038
+ kind: "time",
2039
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
2040
+ ...errorUtil.errToObj(options?.message)
2041
+ });
2042
+ }
2043
+ duration(message) {
2044
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
2045
+ }
2046
+ regex(regex, message) {
2047
+ return this._addCheck({
2048
+ kind: "regex",
2049
+ regex,
2050
+ ...errorUtil.errToObj(message)
2051
+ });
2052
+ }
2053
+ includes(value, options) {
2054
+ return this._addCheck({
2055
+ kind: "includes",
2056
+ value,
2057
+ position: options?.position,
2058
+ ...errorUtil.errToObj(options?.message)
2059
+ });
2060
+ }
2061
+ startsWith(value, message) {
2062
+ return this._addCheck({
2063
+ kind: "startsWith",
2064
+ value,
2065
+ ...errorUtil.errToObj(message)
2066
+ });
2067
+ }
2068
+ endsWith(value, message) {
2069
+ return this._addCheck({
2070
+ kind: "endsWith",
2071
+ value,
2072
+ ...errorUtil.errToObj(message)
2073
+ });
2074
+ }
2075
+ min(minLength, message) {
2076
+ return this._addCheck({
2077
+ kind: "min",
2078
+ value: minLength,
2079
+ ...errorUtil.errToObj(message)
2080
+ });
2081
+ }
2082
+ max(maxLength, message) {
2083
+ return this._addCheck({
2084
+ kind: "max",
2085
+ value: maxLength,
2086
+ ...errorUtil.errToObj(message)
2087
+ });
2088
+ }
2089
+ length(len, message) {
2090
+ return this._addCheck({
2091
+ kind: "length",
2092
+ value: len,
2093
+ ...errorUtil.errToObj(message)
2094
+ });
2095
+ }
2096
+ nonempty(message) {
2097
+ return this.min(1, errorUtil.errToObj(message));
2098
+ }
2099
+ trim() {
2100
+ return new ZodString({
2101
+ ...this._def,
2102
+ checks: [...this._def.checks, { kind: "trim" }]
2103
+ });
2104
+ }
2105
+ toLowerCase() {
2106
+ return new ZodString({
2107
+ ...this._def,
2108
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
2109
+ });
2110
+ }
2111
+ toUpperCase() {
2112
+ return new ZodString({
2113
+ ...this._def,
2114
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
2115
+ });
2116
+ }
2117
+ get isDatetime() {
2118
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
2119
+ }
2120
+ get isDate() {
2121
+ return !!this._def.checks.find((ch) => ch.kind === "date");
2122
+ }
2123
+ get isTime() {
2124
+ return !!this._def.checks.find((ch) => ch.kind === "time");
2125
+ }
2126
+ get isDuration() {
2127
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
2128
+ }
2129
+ get isEmail() {
2130
+ return !!this._def.checks.find((ch) => ch.kind === "email");
2131
+ }
2132
+ get isURL() {
2133
+ return !!this._def.checks.find((ch) => ch.kind === "url");
2134
+ }
2135
+ get isEmoji() {
2136
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
2137
+ }
2138
+ get isUUID() {
2139
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
2140
+ }
2141
+ get isNANOID() {
2142
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
2143
+ }
2144
+ get isCUID() {
2145
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
2146
+ }
2147
+ get isCUID2() {
2148
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
2149
+ }
2150
+ get isULID() {
2151
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
2152
+ }
2153
+ get isIP() {
2154
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
2155
+ }
2156
+ get isCIDR() {
2157
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
2158
+ }
2159
+ get isBase64() {
2160
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
2161
+ }
2162
+ get isBase64url() {
2163
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
2164
+ }
2165
+ get minLength() {
2166
+ let min = null;
2167
+ for (const ch of this._def.checks) {
2168
+ if (ch.kind === "min") {
2169
+ if (min === null || ch.value > min)
2170
+ min = ch.value;
2171
+ }
2172
+ }
2173
+ return min;
2174
+ }
2175
+ get maxLength() {
2176
+ let max = null;
2177
+ for (const ch of this._def.checks) {
2178
+ if (ch.kind === "max") {
2179
+ if (max === null || ch.value < max)
2180
+ max = ch.value;
2181
+ }
2182
+ }
2183
+ return max;
2184
+ }
2185
+ }
2186
+ ZodString.create = (params) => {
2187
+ return new ZodString({
2188
+ checks: [],
2189
+ typeName: ZodFirstPartyTypeKind.ZodString,
2190
+ coerce: params?.coerce ?? false,
2191
+ ...processCreateParams(params)
2192
+ });
2193
+ };
2194
+ function floatSafeRemainder(val, step) {
2195
+ const valDecCount = (val.toString().split(".")[1] || "").length;
2196
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
2197
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
2198
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
2199
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
2200
+ return valInt % stepInt / 10 ** decCount;
2201
+ }
2202
+
2203
+ class ZodNumber extends ZodType {
2204
+ constructor() {
2205
+ super(...arguments);
2206
+ this.min = this.gte;
2207
+ this.max = this.lte;
2208
+ this.step = this.multipleOf;
2209
+ }
2210
+ _parse(input) {
2211
+ if (this._def.coerce) {
2212
+ input.data = Number(input.data);
2213
+ }
2214
+ const parsedType = this._getType(input);
2215
+ if (parsedType !== ZodParsedType.number) {
2216
+ const ctx2 = this._getOrReturnCtx(input);
2217
+ addIssueToContext(ctx2, {
2218
+ code: ZodIssueCode.invalid_type,
2219
+ expected: ZodParsedType.number,
2220
+ received: ctx2.parsedType
2221
+ });
2222
+ return INVALID;
2223
+ }
2224
+ let ctx = undefined;
2225
+ const status = new ParseStatus;
2226
+ for (const check of this._def.checks) {
2227
+ if (check.kind === "int") {
2228
+ if (!util.isInteger(input.data)) {
2229
+ ctx = this._getOrReturnCtx(input, ctx);
2230
+ addIssueToContext(ctx, {
2231
+ code: ZodIssueCode.invalid_type,
2232
+ expected: "integer",
2233
+ received: "float",
2234
+ message: check.message
2235
+ });
2236
+ status.dirty();
2237
+ }
2238
+ } else if (check.kind === "min") {
2239
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2240
+ if (tooSmall) {
2241
+ ctx = this._getOrReturnCtx(input, ctx);
2242
+ addIssueToContext(ctx, {
2243
+ code: ZodIssueCode.too_small,
2244
+ minimum: check.value,
2245
+ type: "number",
2246
+ inclusive: check.inclusive,
2247
+ exact: false,
2248
+ message: check.message
2249
+ });
2250
+ status.dirty();
2251
+ }
2252
+ } else if (check.kind === "max") {
2253
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2254
+ if (tooBig) {
2255
+ ctx = this._getOrReturnCtx(input, ctx);
2256
+ addIssueToContext(ctx, {
2257
+ code: ZodIssueCode.too_big,
2258
+ maximum: check.value,
2259
+ type: "number",
2260
+ inclusive: check.inclusive,
2261
+ exact: false,
2262
+ message: check.message
2263
+ });
2264
+ status.dirty();
2265
+ }
2266
+ } else if (check.kind === "multipleOf") {
2267
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
2268
+ ctx = this._getOrReturnCtx(input, ctx);
2269
+ addIssueToContext(ctx, {
2270
+ code: ZodIssueCode.not_multiple_of,
2271
+ multipleOf: check.value,
2272
+ message: check.message
2273
+ });
2274
+ status.dirty();
2275
+ }
2276
+ } else if (check.kind === "finite") {
2277
+ if (!Number.isFinite(input.data)) {
2278
+ ctx = this._getOrReturnCtx(input, ctx);
2279
+ addIssueToContext(ctx, {
2280
+ code: ZodIssueCode.not_finite,
2281
+ message: check.message
2282
+ });
2283
+ status.dirty();
2284
+ }
2285
+ } else {
2286
+ util.assertNever(check);
2287
+ }
2288
+ }
2289
+ return { status: status.value, value: input.data };
2290
+ }
2291
+ gte(value, message) {
2292
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2293
+ }
2294
+ gt(value, message) {
2295
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2296
+ }
2297
+ lte(value, message) {
2298
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2299
+ }
2300
+ lt(value, message) {
2301
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2302
+ }
2303
+ setLimit(kind, value, inclusive, message) {
2304
+ return new ZodNumber({
2305
+ ...this._def,
2306
+ checks: [
2307
+ ...this._def.checks,
2308
+ {
2309
+ kind,
2310
+ value,
2311
+ inclusive,
2312
+ message: errorUtil.toString(message)
2313
+ }
2314
+ ]
2315
+ });
2316
+ }
2317
+ _addCheck(check) {
2318
+ return new ZodNumber({
2319
+ ...this._def,
2320
+ checks: [...this._def.checks, check]
2321
+ });
2322
+ }
2323
+ int(message) {
2324
+ return this._addCheck({
2325
+ kind: "int",
2326
+ message: errorUtil.toString(message)
2327
+ });
2328
+ }
2329
+ positive(message) {
2330
+ return this._addCheck({
2331
+ kind: "min",
2332
+ value: 0,
2333
+ inclusive: false,
2334
+ message: errorUtil.toString(message)
2335
+ });
2336
+ }
2337
+ negative(message) {
2338
+ return this._addCheck({
2339
+ kind: "max",
2340
+ value: 0,
2341
+ inclusive: false,
2342
+ message: errorUtil.toString(message)
2343
+ });
2344
+ }
2345
+ nonpositive(message) {
2346
+ return this._addCheck({
2347
+ kind: "max",
2348
+ value: 0,
2349
+ inclusive: true,
2350
+ message: errorUtil.toString(message)
2351
+ });
2352
+ }
2353
+ nonnegative(message) {
2354
+ return this._addCheck({
2355
+ kind: "min",
2356
+ value: 0,
2357
+ inclusive: true,
2358
+ message: errorUtil.toString(message)
2359
+ });
2360
+ }
2361
+ multipleOf(value, message) {
2362
+ return this._addCheck({
2363
+ kind: "multipleOf",
2364
+ value,
2365
+ message: errorUtil.toString(message)
2366
+ });
2367
+ }
2368
+ finite(message) {
2369
+ return this._addCheck({
2370
+ kind: "finite",
2371
+ message: errorUtil.toString(message)
2372
+ });
2373
+ }
2374
+ safe(message) {
2375
+ return this._addCheck({
2376
+ kind: "min",
2377
+ inclusive: true,
2378
+ value: Number.MIN_SAFE_INTEGER,
2379
+ message: errorUtil.toString(message)
2380
+ })._addCheck({
2381
+ kind: "max",
2382
+ inclusive: true,
2383
+ value: Number.MAX_SAFE_INTEGER,
2384
+ message: errorUtil.toString(message)
2385
+ });
2386
+ }
2387
+ get minValue() {
2388
+ let min = null;
2389
+ for (const ch of this._def.checks) {
2390
+ if (ch.kind === "min") {
2391
+ if (min === null || ch.value > min)
2392
+ min = ch.value;
2393
+ }
2394
+ }
2395
+ return min;
2396
+ }
2397
+ get maxValue() {
2398
+ let max = null;
2399
+ for (const ch of this._def.checks) {
2400
+ if (ch.kind === "max") {
2401
+ if (max === null || ch.value < max)
2402
+ max = ch.value;
2403
+ }
2404
+ }
2405
+ return max;
2406
+ }
2407
+ get isInt() {
2408
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
2409
+ }
2410
+ get isFinite() {
2411
+ let max = null;
2412
+ let min = null;
2413
+ for (const ch of this._def.checks) {
2414
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
2415
+ return true;
2416
+ } else if (ch.kind === "min") {
2417
+ if (min === null || ch.value > min)
2418
+ min = ch.value;
2419
+ } else if (ch.kind === "max") {
2420
+ if (max === null || ch.value < max)
2421
+ max = ch.value;
2422
+ }
2423
+ }
2424
+ return Number.isFinite(min) && Number.isFinite(max);
2425
+ }
2426
+ }
2427
+ ZodNumber.create = (params) => {
2428
+ return new ZodNumber({
2429
+ checks: [],
2430
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
2431
+ coerce: params?.coerce || false,
2432
+ ...processCreateParams(params)
2433
+ });
2434
+ };
2435
+
2436
+ class ZodBigInt extends ZodType {
2437
+ constructor() {
2438
+ super(...arguments);
2439
+ this.min = this.gte;
2440
+ this.max = this.lte;
2441
+ }
2442
+ _parse(input) {
2443
+ if (this._def.coerce) {
2444
+ try {
2445
+ input.data = BigInt(input.data);
2446
+ } catch {
2447
+ return this._getInvalidInput(input);
2448
+ }
2449
+ }
2450
+ const parsedType = this._getType(input);
2451
+ if (parsedType !== ZodParsedType.bigint) {
2452
+ return this._getInvalidInput(input);
2453
+ }
2454
+ let ctx = undefined;
2455
+ const status = new ParseStatus;
2456
+ for (const check of this._def.checks) {
2457
+ if (check.kind === "min") {
2458
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2459
+ if (tooSmall) {
2460
+ ctx = this._getOrReturnCtx(input, ctx);
2461
+ addIssueToContext(ctx, {
2462
+ code: ZodIssueCode.too_small,
2463
+ type: "bigint",
2464
+ minimum: check.value,
2465
+ inclusive: check.inclusive,
2466
+ message: check.message
2467
+ });
2468
+ status.dirty();
2469
+ }
2470
+ } else if (check.kind === "max") {
2471
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2472
+ if (tooBig) {
2473
+ ctx = this._getOrReturnCtx(input, ctx);
2474
+ addIssueToContext(ctx, {
2475
+ code: ZodIssueCode.too_big,
2476
+ type: "bigint",
2477
+ maximum: check.value,
2478
+ inclusive: check.inclusive,
2479
+ message: check.message
2480
+ });
2481
+ status.dirty();
2482
+ }
2483
+ } else if (check.kind === "multipleOf") {
2484
+ if (input.data % check.value !== BigInt(0)) {
2485
+ ctx = this._getOrReturnCtx(input, ctx);
2486
+ addIssueToContext(ctx, {
2487
+ code: ZodIssueCode.not_multiple_of,
2488
+ multipleOf: check.value,
2489
+ message: check.message
2490
+ });
2491
+ status.dirty();
2492
+ }
2493
+ } else {
2494
+ util.assertNever(check);
2495
+ }
2496
+ }
2497
+ return { status: status.value, value: input.data };
2498
+ }
2499
+ _getInvalidInput(input) {
2500
+ const ctx = this._getOrReturnCtx(input);
2501
+ addIssueToContext(ctx, {
2502
+ code: ZodIssueCode.invalid_type,
2503
+ expected: ZodParsedType.bigint,
2504
+ received: ctx.parsedType
2505
+ });
2506
+ return INVALID;
2507
+ }
2508
+ gte(value, message) {
2509
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2510
+ }
2511
+ gt(value, message) {
2512
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2513
+ }
2514
+ lte(value, message) {
2515
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2516
+ }
2517
+ lt(value, message) {
2518
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2519
+ }
2520
+ setLimit(kind, value, inclusive, message) {
2521
+ return new ZodBigInt({
2522
+ ...this._def,
2523
+ checks: [
2524
+ ...this._def.checks,
2525
+ {
2526
+ kind,
2527
+ value,
2528
+ inclusive,
2529
+ message: errorUtil.toString(message)
2530
+ }
2531
+ ]
2532
+ });
2533
+ }
2534
+ _addCheck(check) {
2535
+ return new ZodBigInt({
2536
+ ...this._def,
2537
+ checks: [...this._def.checks, check]
2538
+ });
2539
+ }
2540
+ positive(message) {
2541
+ return this._addCheck({
2542
+ kind: "min",
2543
+ value: BigInt(0),
2544
+ inclusive: false,
2545
+ message: errorUtil.toString(message)
2546
+ });
2547
+ }
2548
+ negative(message) {
2549
+ return this._addCheck({
2550
+ kind: "max",
2551
+ value: BigInt(0),
2552
+ inclusive: false,
2553
+ message: errorUtil.toString(message)
2554
+ });
2555
+ }
2556
+ nonpositive(message) {
2557
+ return this._addCheck({
2558
+ kind: "max",
2559
+ value: BigInt(0),
2560
+ inclusive: true,
2561
+ message: errorUtil.toString(message)
2562
+ });
2563
+ }
2564
+ nonnegative(message) {
2565
+ return this._addCheck({
2566
+ kind: "min",
2567
+ value: BigInt(0),
2568
+ inclusive: true,
2569
+ message: errorUtil.toString(message)
2570
+ });
2571
+ }
2572
+ multipleOf(value, message) {
2573
+ return this._addCheck({
2574
+ kind: "multipleOf",
2575
+ value,
2576
+ message: errorUtil.toString(message)
2577
+ });
2578
+ }
2579
+ get minValue() {
2580
+ let min = null;
2581
+ for (const ch of this._def.checks) {
2582
+ if (ch.kind === "min") {
2583
+ if (min === null || ch.value > min)
2584
+ min = ch.value;
2585
+ }
2586
+ }
2587
+ return min;
2588
+ }
2589
+ get maxValue() {
2590
+ let max = null;
2591
+ for (const ch of this._def.checks) {
2592
+ if (ch.kind === "max") {
2593
+ if (max === null || ch.value < max)
2594
+ max = ch.value;
2595
+ }
2596
+ }
2597
+ return max;
2598
+ }
2599
+ }
2600
+ ZodBigInt.create = (params) => {
2601
+ return new ZodBigInt({
2602
+ checks: [],
2603
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2604
+ coerce: params?.coerce ?? false,
2605
+ ...processCreateParams(params)
2606
+ });
2607
+ };
2608
+
2609
+ class ZodBoolean extends ZodType {
2610
+ _parse(input) {
2611
+ if (this._def.coerce) {
2612
+ input.data = Boolean(input.data);
2613
+ }
2614
+ const parsedType = this._getType(input);
2615
+ if (parsedType !== ZodParsedType.boolean) {
2616
+ const ctx = this._getOrReturnCtx(input);
2617
+ addIssueToContext(ctx, {
2618
+ code: ZodIssueCode.invalid_type,
2619
+ expected: ZodParsedType.boolean,
2620
+ received: ctx.parsedType
2621
+ });
2622
+ return INVALID;
2623
+ }
2624
+ return OK(input.data);
2625
+ }
2626
+ }
2627
+ ZodBoolean.create = (params) => {
2628
+ return new ZodBoolean({
2629
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2630
+ coerce: params?.coerce || false,
2631
+ ...processCreateParams(params)
2632
+ });
2633
+ };
2634
+
2635
+ class ZodDate extends ZodType {
2636
+ _parse(input) {
2637
+ if (this._def.coerce) {
2638
+ input.data = new Date(input.data);
2639
+ }
2640
+ const parsedType = this._getType(input);
2641
+ if (parsedType !== ZodParsedType.date) {
2642
+ const ctx2 = this._getOrReturnCtx(input);
2643
+ addIssueToContext(ctx2, {
2644
+ code: ZodIssueCode.invalid_type,
2645
+ expected: ZodParsedType.date,
2646
+ received: ctx2.parsedType
2647
+ });
2648
+ return INVALID;
2649
+ }
2650
+ if (Number.isNaN(input.data.getTime())) {
2651
+ const ctx2 = this._getOrReturnCtx(input);
2652
+ addIssueToContext(ctx2, {
2653
+ code: ZodIssueCode.invalid_date
2654
+ });
2655
+ return INVALID;
2656
+ }
2657
+ const status = new ParseStatus;
2658
+ let ctx = undefined;
2659
+ for (const check of this._def.checks) {
2660
+ if (check.kind === "min") {
2661
+ if (input.data.getTime() < check.value) {
2662
+ ctx = this._getOrReturnCtx(input, ctx);
2663
+ addIssueToContext(ctx, {
2664
+ code: ZodIssueCode.too_small,
2665
+ message: check.message,
2666
+ inclusive: true,
2667
+ exact: false,
2668
+ minimum: check.value,
2669
+ type: "date"
2670
+ });
2671
+ status.dirty();
2672
+ }
2673
+ } else if (check.kind === "max") {
2674
+ if (input.data.getTime() > check.value) {
2675
+ ctx = this._getOrReturnCtx(input, ctx);
2676
+ addIssueToContext(ctx, {
2677
+ code: ZodIssueCode.too_big,
2678
+ message: check.message,
2679
+ inclusive: true,
2680
+ exact: false,
2681
+ maximum: check.value,
2682
+ type: "date"
2683
+ });
2684
+ status.dirty();
2685
+ }
2686
+ } else {
2687
+ util.assertNever(check);
2688
+ }
2689
+ }
2690
+ return {
2691
+ status: status.value,
2692
+ value: new Date(input.data.getTime())
2693
+ };
2694
+ }
2695
+ _addCheck(check) {
2696
+ return new ZodDate({
2697
+ ...this._def,
2698
+ checks: [...this._def.checks, check]
2699
+ });
2700
+ }
2701
+ min(minDate, message) {
2702
+ return this._addCheck({
2703
+ kind: "min",
2704
+ value: minDate.getTime(),
2705
+ message: errorUtil.toString(message)
2706
+ });
2707
+ }
2708
+ max(maxDate, message) {
2709
+ return this._addCheck({
2710
+ kind: "max",
2711
+ value: maxDate.getTime(),
2712
+ message: errorUtil.toString(message)
2713
+ });
2714
+ }
2715
+ get minDate() {
2716
+ let min = null;
2717
+ for (const ch of this._def.checks) {
2718
+ if (ch.kind === "min") {
2719
+ if (min === null || ch.value > min)
2720
+ min = ch.value;
2721
+ }
2722
+ }
2723
+ return min != null ? new Date(min) : null;
2724
+ }
2725
+ get maxDate() {
2726
+ let max = null;
2727
+ for (const ch of this._def.checks) {
2728
+ if (ch.kind === "max") {
2729
+ if (max === null || ch.value < max)
2730
+ max = ch.value;
2731
+ }
2732
+ }
2733
+ return max != null ? new Date(max) : null;
2734
+ }
2735
+ }
2736
+ ZodDate.create = (params) => {
2737
+ return new ZodDate({
2738
+ checks: [],
2739
+ coerce: params?.coerce || false,
2740
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2741
+ ...processCreateParams(params)
2742
+ });
2743
+ };
2744
+
2745
+ class ZodSymbol extends ZodType {
2746
+ _parse(input) {
2747
+ const parsedType = this._getType(input);
2748
+ if (parsedType !== ZodParsedType.symbol) {
2749
+ const ctx = this._getOrReturnCtx(input);
2750
+ addIssueToContext(ctx, {
2751
+ code: ZodIssueCode.invalid_type,
2752
+ expected: ZodParsedType.symbol,
2753
+ received: ctx.parsedType
2754
+ });
2755
+ return INVALID;
2756
+ }
2757
+ return OK(input.data);
2758
+ }
2759
+ }
2760
+ ZodSymbol.create = (params) => {
2761
+ return new ZodSymbol({
2762
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2763
+ ...processCreateParams(params)
2764
+ });
2765
+ };
2766
+
2767
+ class ZodUndefined extends ZodType {
2768
+ _parse(input) {
2769
+ const parsedType = this._getType(input);
2770
+ if (parsedType !== ZodParsedType.undefined) {
2771
+ const ctx = this._getOrReturnCtx(input);
2772
+ addIssueToContext(ctx, {
2773
+ code: ZodIssueCode.invalid_type,
2774
+ expected: ZodParsedType.undefined,
2775
+ received: ctx.parsedType
2776
+ });
2777
+ return INVALID;
2778
+ }
2779
+ return OK(input.data);
2780
+ }
2781
+ }
2782
+ ZodUndefined.create = (params) => {
2783
+ return new ZodUndefined({
2784
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2785
+ ...processCreateParams(params)
2786
+ });
2787
+ };
2788
+
2789
+ class ZodNull extends ZodType {
2790
+ _parse(input) {
2791
+ const parsedType = this._getType(input);
2792
+ if (parsedType !== ZodParsedType.null) {
2793
+ const ctx = this._getOrReturnCtx(input);
2794
+ addIssueToContext(ctx, {
2795
+ code: ZodIssueCode.invalid_type,
2796
+ expected: ZodParsedType.null,
2797
+ received: ctx.parsedType
2798
+ });
2799
+ return INVALID;
2800
+ }
2801
+ return OK(input.data);
2802
+ }
2803
+ }
2804
+ ZodNull.create = (params) => {
2805
+ return new ZodNull({
2806
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2807
+ ...processCreateParams(params)
2808
+ });
2809
+ };
2810
+
2811
+ class ZodAny extends ZodType {
2812
+ constructor() {
2813
+ super(...arguments);
2814
+ this._any = true;
2815
+ }
2816
+ _parse(input) {
2817
+ return OK(input.data);
2818
+ }
2819
+ }
2820
+ ZodAny.create = (params) => {
2821
+ return new ZodAny({
2822
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2823
+ ...processCreateParams(params)
2824
+ });
2825
+ };
2826
+
2827
+ class ZodUnknown extends ZodType {
2828
+ constructor() {
2829
+ super(...arguments);
2830
+ this._unknown = true;
2831
+ }
2832
+ _parse(input) {
2833
+ return OK(input.data);
2834
+ }
2835
+ }
2836
+ ZodUnknown.create = (params) => {
2837
+ return new ZodUnknown({
2838
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2839
+ ...processCreateParams(params)
2840
+ });
2841
+ };
2842
+
2843
+ class ZodNever extends ZodType {
2844
+ _parse(input) {
2845
+ const ctx = this._getOrReturnCtx(input);
2846
+ addIssueToContext(ctx, {
2847
+ code: ZodIssueCode.invalid_type,
2848
+ expected: ZodParsedType.never,
2849
+ received: ctx.parsedType
2850
+ });
2851
+ return INVALID;
2852
+ }
2853
+ }
2854
+ ZodNever.create = (params) => {
2855
+ return new ZodNever({
2856
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2857
+ ...processCreateParams(params)
2858
+ });
2859
+ };
2860
+
2861
+ class ZodVoid extends ZodType {
2862
+ _parse(input) {
2863
+ const parsedType = this._getType(input);
2864
+ if (parsedType !== ZodParsedType.undefined) {
2865
+ const ctx = this._getOrReturnCtx(input);
2866
+ addIssueToContext(ctx, {
2867
+ code: ZodIssueCode.invalid_type,
2868
+ expected: ZodParsedType.void,
2869
+ received: ctx.parsedType
2870
+ });
2871
+ return INVALID;
2872
+ }
2873
+ return OK(input.data);
2874
+ }
2875
+ }
2876
+ ZodVoid.create = (params) => {
2877
+ return new ZodVoid({
2878
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2879
+ ...processCreateParams(params)
2880
+ });
2881
+ };
2882
+
2883
+ class ZodArray extends ZodType {
2884
+ _parse(input) {
2885
+ const { ctx, status } = this._processInputParams(input);
2886
+ const def = this._def;
2887
+ if (ctx.parsedType !== ZodParsedType.array) {
2888
+ addIssueToContext(ctx, {
2889
+ code: ZodIssueCode.invalid_type,
2890
+ expected: ZodParsedType.array,
2891
+ received: ctx.parsedType
2892
+ });
2893
+ return INVALID;
2894
+ }
2895
+ if (def.exactLength !== null) {
2896
+ const tooBig = ctx.data.length > def.exactLength.value;
2897
+ const tooSmall = ctx.data.length < def.exactLength.value;
2898
+ if (tooBig || tooSmall) {
2899
+ addIssueToContext(ctx, {
2900
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2901
+ minimum: tooSmall ? def.exactLength.value : undefined,
2902
+ maximum: tooBig ? def.exactLength.value : undefined,
2903
+ type: "array",
2904
+ inclusive: true,
2905
+ exact: true,
2906
+ message: def.exactLength.message
2907
+ });
2908
+ status.dirty();
2909
+ }
2910
+ }
2911
+ if (def.minLength !== null) {
2912
+ if (ctx.data.length < def.minLength.value) {
2913
+ addIssueToContext(ctx, {
2914
+ code: ZodIssueCode.too_small,
2915
+ minimum: def.minLength.value,
2916
+ type: "array",
2917
+ inclusive: true,
2918
+ exact: false,
2919
+ message: def.minLength.message
2920
+ });
2921
+ status.dirty();
2922
+ }
2923
+ }
2924
+ if (def.maxLength !== null) {
2925
+ if (ctx.data.length > def.maxLength.value) {
2926
+ addIssueToContext(ctx, {
2927
+ code: ZodIssueCode.too_big,
2928
+ maximum: def.maxLength.value,
2929
+ type: "array",
2930
+ inclusive: true,
2931
+ exact: false,
2932
+ message: def.maxLength.message
2933
+ });
2934
+ status.dirty();
2935
+ }
2936
+ }
2937
+ if (ctx.common.async) {
2938
+ return Promise.all([...ctx.data].map((item, i) => {
2939
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2940
+ })).then((result2) => {
2941
+ return ParseStatus.mergeArray(status, result2);
2942
+ });
2943
+ }
2944
+ const result = [...ctx.data].map((item, i) => {
2945
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2946
+ });
2947
+ return ParseStatus.mergeArray(status, result);
2948
+ }
2949
+ get element() {
2950
+ return this._def.type;
2951
+ }
2952
+ min(minLength, message) {
2953
+ return new ZodArray({
2954
+ ...this._def,
2955
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2956
+ });
2957
+ }
2958
+ max(maxLength, message) {
2959
+ return new ZodArray({
2960
+ ...this._def,
2961
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
2962
+ });
2963
+ }
2964
+ length(len, message) {
2965
+ return new ZodArray({
2966
+ ...this._def,
2967
+ exactLength: { value: len, message: errorUtil.toString(message) }
2968
+ });
2969
+ }
2970
+ nonempty(message) {
2971
+ return this.min(1, message);
2972
+ }
2973
+ }
2974
+ ZodArray.create = (schema, params) => {
2975
+ return new ZodArray({
2976
+ type: schema,
2977
+ minLength: null,
2978
+ maxLength: null,
2979
+ exactLength: null,
2980
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2981
+ ...processCreateParams(params)
2982
+ });
2983
+ };
2984
+ function deepPartialify(schema) {
2985
+ if (schema instanceof ZodObject) {
2986
+ const newShape = {};
2987
+ for (const key in schema.shape) {
2988
+ const fieldSchema = schema.shape[key];
2989
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2990
+ }
2991
+ return new ZodObject({
2992
+ ...schema._def,
2993
+ shape: () => newShape
2994
+ });
2995
+ } else if (schema instanceof ZodArray) {
2996
+ return new ZodArray({
2997
+ ...schema._def,
2998
+ type: deepPartialify(schema.element)
2999
+ });
3000
+ } else if (schema instanceof ZodOptional) {
3001
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
3002
+ } else if (schema instanceof ZodNullable) {
3003
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
3004
+ } else if (schema instanceof ZodTuple) {
3005
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
3006
+ } else {
3007
+ return schema;
3008
+ }
3009
+ }
3010
+
3011
+ class ZodObject extends ZodType {
3012
+ constructor() {
3013
+ super(...arguments);
3014
+ this._cached = null;
3015
+ this.nonstrict = this.passthrough;
3016
+ this.augment = this.extend;
3017
+ }
3018
+ _getCached() {
3019
+ if (this._cached !== null)
3020
+ return this._cached;
3021
+ const shape = this._def.shape();
3022
+ const keys = util.objectKeys(shape);
3023
+ this._cached = { shape, keys };
3024
+ return this._cached;
3025
+ }
3026
+ _parse(input) {
3027
+ const parsedType = this._getType(input);
3028
+ if (parsedType !== ZodParsedType.object) {
3029
+ const ctx2 = this._getOrReturnCtx(input);
3030
+ addIssueToContext(ctx2, {
3031
+ code: ZodIssueCode.invalid_type,
3032
+ expected: ZodParsedType.object,
3033
+ received: ctx2.parsedType
3034
+ });
3035
+ return INVALID;
3036
+ }
3037
+ const { status, ctx } = this._processInputParams(input);
3038
+ const { shape, keys: shapeKeys } = this._getCached();
3039
+ const extraKeys = [];
3040
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
3041
+ for (const key in ctx.data) {
3042
+ if (!shapeKeys.includes(key)) {
3043
+ extraKeys.push(key);
3044
+ }
3045
+ }
3046
+ }
3047
+ const pairs = [];
3048
+ for (const key of shapeKeys) {
3049
+ const keyValidator = shape[key];
3050
+ const value = ctx.data[key];
3051
+ pairs.push({
3052
+ key: { status: "valid", value: key },
3053
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
3054
+ alwaysSet: key in ctx.data
3055
+ });
3056
+ }
3057
+ if (this._def.catchall instanceof ZodNever) {
3058
+ const unknownKeys = this._def.unknownKeys;
3059
+ if (unknownKeys === "passthrough") {
3060
+ for (const key of extraKeys) {
3061
+ pairs.push({
3062
+ key: { status: "valid", value: key },
3063
+ value: { status: "valid", value: ctx.data[key] }
3064
+ });
3065
+ }
3066
+ } else if (unknownKeys === "strict") {
3067
+ if (extraKeys.length > 0) {
3068
+ addIssueToContext(ctx, {
3069
+ code: ZodIssueCode.unrecognized_keys,
3070
+ keys: extraKeys
3071
+ });
3072
+ status.dirty();
3073
+ }
3074
+ } else if (unknownKeys === "strip") {} else {
3075
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
3076
+ }
3077
+ } else {
3078
+ const catchall = this._def.catchall;
3079
+ for (const key of extraKeys) {
3080
+ const value = ctx.data[key];
3081
+ pairs.push({
3082
+ key: { status: "valid", value: key },
3083
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
3084
+ alwaysSet: key in ctx.data
3085
+ });
3086
+ }
3087
+ }
3088
+ if (ctx.common.async) {
3089
+ return Promise.resolve().then(async () => {
3090
+ const syncPairs = [];
3091
+ for (const pair of pairs) {
3092
+ const key = await pair.key;
3093
+ const value = await pair.value;
3094
+ syncPairs.push({
3095
+ key,
3096
+ value,
3097
+ alwaysSet: pair.alwaysSet
3098
+ });
3099
+ }
3100
+ return syncPairs;
3101
+ }).then((syncPairs) => {
3102
+ return ParseStatus.mergeObjectSync(status, syncPairs);
3103
+ });
3104
+ } else {
3105
+ return ParseStatus.mergeObjectSync(status, pairs);
3106
+ }
3107
+ }
3108
+ get shape() {
3109
+ return this._def.shape();
3110
+ }
3111
+ strict(message) {
3112
+ errorUtil.errToObj;
3113
+ return new ZodObject({
3114
+ ...this._def,
3115
+ unknownKeys: "strict",
3116
+ ...message !== undefined ? {
3117
+ errorMap: (issue, ctx) => {
3118
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
3119
+ if (issue.code === "unrecognized_keys")
3120
+ return {
3121
+ message: errorUtil.errToObj(message).message ?? defaultError
3122
+ };
3123
+ return {
3124
+ message: defaultError
3125
+ };
3126
+ }
3127
+ } : {}
3128
+ });
3129
+ }
3130
+ strip() {
3131
+ return new ZodObject({
3132
+ ...this._def,
3133
+ unknownKeys: "strip"
3134
+ });
3135
+ }
3136
+ passthrough() {
3137
+ return new ZodObject({
3138
+ ...this._def,
3139
+ unknownKeys: "passthrough"
3140
+ });
3141
+ }
3142
+ extend(augmentation) {
3143
+ return new ZodObject({
3144
+ ...this._def,
3145
+ shape: () => ({
3146
+ ...this._def.shape(),
3147
+ ...augmentation
3148
+ })
3149
+ });
3150
+ }
3151
+ merge(merging) {
3152
+ const merged = new ZodObject({
3153
+ unknownKeys: merging._def.unknownKeys,
3154
+ catchall: merging._def.catchall,
3155
+ shape: () => ({
3156
+ ...this._def.shape(),
3157
+ ...merging._def.shape()
3158
+ }),
3159
+ typeName: ZodFirstPartyTypeKind.ZodObject
3160
+ });
3161
+ return merged;
3162
+ }
3163
+ setKey(key, schema) {
3164
+ return this.augment({ [key]: schema });
3165
+ }
3166
+ catchall(index) {
3167
+ return new ZodObject({
3168
+ ...this._def,
3169
+ catchall: index
3170
+ });
3171
+ }
3172
+ pick(mask) {
3173
+ const shape = {};
3174
+ for (const key of util.objectKeys(mask)) {
3175
+ if (mask[key] && this.shape[key]) {
3176
+ shape[key] = this.shape[key];
3177
+ }
3178
+ }
3179
+ return new ZodObject({
3180
+ ...this._def,
3181
+ shape: () => shape
3182
+ });
3183
+ }
3184
+ omit(mask) {
3185
+ const shape = {};
3186
+ for (const key of util.objectKeys(this.shape)) {
3187
+ if (!mask[key]) {
3188
+ shape[key] = this.shape[key];
3189
+ }
3190
+ }
3191
+ return new ZodObject({
3192
+ ...this._def,
3193
+ shape: () => shape
3194
+ });
3195
+ }
3196
+ deepPartial() {
3197
+ return deepPartialify(this);
3198
+ }
3199
+ partial(mask) {
3200
+ const newShape = {};
3201
+ for (const key of util.objectKeys(this.shape)) {
3202
+ const fieldSchema = this.shape[key];
3203
+ if (mask && !mask[key]) {
3204
+ newShape[key] = fieldSchema;
3205
+ } else {
3206
+ newShape[key] = fieldSchema.optional();
3207
+ }
3208
+ }
3209
+ return new ZodObject({
3210
+ ...this._def,
3211
+ shape: () => newShape
3212
+ });
3213
+ }
3214
+ required(mask) {
3215
+ const newShape = {};
3216
+ for (const key of util.objectKeys(this.shape)) {
3217
+ if (mask && !mask[key]) {
3218
+ newShape[key] = this.shape[key];
3219
+ } else {
3220
+ const fieldSchema = this.shape[key];
3221
+ let newField = fieldSchema;
3222
+ while (newField instanceof ZodOptional) {
3223
+ newField = newField._def.innerType;
3224
+ }
3225
+ newShape[key] = newField;
3226
+ }
3227
+ }
3228
+ return new ZodObject({
3229
+ ...this._def,
3230
+ shape: () => newShape
3231
+ });
3232
+ }
3233
+ keyof() {
3234
+ return createZodEnum(util.objectKeys(this.shape));
3235
+ }
3236
+ }
3237
+ ZodObject.create = (shape, params) => {
3238
+ return new ZodObject({
3239
+ shape: () => shape,
3240
+ unknownKeys: "strip",
3241
+ catchall: ZodNever.create(),
3242
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3243
+ ...processCreateParams(params)
3244
+ });
3245
+ };
3246
+ ZodObject.strictCreate = (shape, params) => {
3247
+ return new ZodObject({
3248
+ shape: () => shape,
3249
+ unknownKeys: "strict",
3250
+ catchall: ZodNever.create(),
3251
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3252
+ ...processCreateParams(params)
3253
+ });
3254
+ };
3255
+ ZodObject.lazycreate = (shape, params) => {
3256
+ return new ZodObject({
3257
+ shape,
3258
+ unknownKeys: "strip",
3259
+ catchall: ZodNever.create(),
3260
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3261
+ ...processCreateParams(params)
3262
+ });
3263
+ };
3264
+
3265
+ class ZodUnion extends ZodType {
3266
+ _parse(input) {
3267
+ const { ctx } = this._processInputParams(input);
3268
+ const options = this._def.options;
3269
+ function handleResults(results) {
3270
+ for (const result of results) {
3271
+ if (result.result.status === "valid") {
3272
+ return result.result;
3273
+ }
3274
+ }
3275
+ for (const result of results) {
3276
+ if (result.result.status === "dirty") {
3277
+ ctx.common.issues.push(...result.ctx.common.issues);
3278
+ return result.result;
3279
+ }
3280
+ }
3281
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
3282
+ addIssueToContext(ctx, {
3283
+ code: ZodIssueCode.invalid_union,
3284
+ unionErrors
3285
+ });
3286
+ return INVALID;
3287
+ }
3288
+ if (ctx.common.async) {
3289
+ return Promise.all(options.map(async (option) => {
3290
+ const childCtx = {
3291
+ ...ctx,
3292
+ common: {
3293
+ ...ctx.common,
3294
+ issues: []
3295
+ },
3296
+ parent: null
3297
+ };
3298
+ return {
3299
+ result: await option._parseAsync({
3300
+ data: ctx.data,
3301
+ path: ctx.path,
3302
+ parent: childCtx
3303
+ }),
3304
+ ctx: childCtx
3305
+ };
3306
+ })).then(handleResults);
3307
+ } else {
3308
+ let dirty = undefined;
3309
+ const issues = [];
3310
+ for (const option of options) {
3311
+ const childCtx = {
3312
+ ...ctx,
3313
+ common: {
3314
+ ...ctx.common,
3315
+ issues: []
3316
+ },
3317
+ parent: null
3318
+ };
3319
+ const result = option._parseSync({
3320
+ data: ctx.data,
3321
+ path: ctx.path,
3322
+ parent: childCtx
3323
+ });
3324
+ if (result.status === "valid") {
3325
+ return result;
3326
+ } else if (result.status === "dirty" && !dirty) {
3327
+ dirty = { result, ctx: childCtx };
3328
+ }
3329
+ if (childCtx.common.issues.length) {
3330
+ issues.push(childCtx.common.issues);
3331
+ }
3332
+ }
3333
+ if (dirty) {
3334
+ ctx.common.issues.push(...dirty.ctx.common.issues);
3335
+ return dirty.result;
3336
+ }
3337
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
3338
+ addIssueToContext(ctx, {
3339
+ code: ZodIssueCode.invalid_union,
3340
+ unionErrors
3341
+ });
3342
+ return INVALID;
3343
+ }
3344
+ }
3345
+ get options() {
3346
+ return this._def.options;
3347
+ }
3348
+ }
3349
+ ZodUnion.create = (types, params) => {
3350
+ return new ZodUnion({
3351
+ options: types,
3352
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
3353
+ ...processCreateParams(params)
3354
+ });
3355
+ };
3356
+ var getDiscriminator = (type) => {
3357
+ if (type instanceof ZodLazy) {
3358
+ return getDiscriminator(type.schema);
3359
+ } else if (type instanceof ZodEffects) {
3360
+ return getDiscriminator(type.innerType());
3361
+ } else if (type instanceof ZodLiteral) {
3362
+ return [type.value];
3363
+ } else if (type instanceof ZodEnum) {
3364
+ return type.options;
3365
+ } else if (type instanceof ZodNativeEnum) {
3366
+ return util.objectValues(type.enum);
3367
+ } else if (type instanceof ZodDefault) {
3368
+ return getDiscriminator(type._def.innerType);
3369
+ } else if (type instanceof ZodUndefined) {
3370
+ return [undefined];
3371
+ } else if (type instanceof ZodNull) {
3372
+ return [null];
3373
+ } else if (type instanceof ZodOptional) {
3374
+ return [undefined, ...getDiscriminator(type.unwrap())];
3375
+ } else if (type instanceof ZodNullable) {
3376
+ return [null, ...getDiscriminator(type.unwrap())];
3377
+ } else if (type instanceof ZodBranded) {
3378
+ return getDiscriminator(type.unwrap());
3379
+ } else if (type instanceof ZodReadonly) {
3380
+ return getDiscriminator(type.unwrap());
3381
+ } else if (type instanceof ZodCatch) {
3382
+ return getDiscriminator(type._def.innerType);
3383
+ } else {
3384
+ return [];
3385
+ }
3386
+ };
3387
+
3388
+ class ZodDiscriminatedUnion extends ZodType {
3389
+ _parse(input) {
3390
+ const { ctx } = this._processInputParams(input);
3391
+ if (ctx.parsedType !== ZodParsedType.object) {
3392
+ addIssueToContext(ctx, {
3393
+ code: ZodIssueCode.invalid_type,
3394
+ expected: ZodParsedType.object,
3395
+ received: ctx.parsedType
3396
+ });
3397
+ return INVALID;
3398
+ }
3399
+ const discriminator = this.discriminator;
3400
+ const discriminatorValue = ctx.data[discriminator];
3401
+ const option = this.optionsMap.get(discriminatorValue);
3402
+ if (!option) {
3403
+ addIssueToContext(ctx, {
3404
+ code: ZodIssueCode.invalid_union_discriminator,
3405
+ options: Array.from(this.optionsMap.keys()),
3406
+ path: [discriminator]
3407
+ });
3408
+ return INVALID;
3409
+ }
3410
+ if (ctx.common.async) {
3411
+ return option._parseAsync({
3412
+ data: ctx.data,
3413
+ path: ctx.path,
3414
+ parent: ctx
3415
+ });
3416
+ } else {
3417
+ return option._parseSync({
3418
+ data: ctx.data,
3419
+ path: ctx.path,
3420
+ parent: ctx
3421
+ });
3422
+ }
3423
+ }
3424
+ get discriminator() {
3425
+ return this._def.discriminator;
3426
+ }
3427
+ get options() {
3428
+ return this._def.options;
3429
+ }
3430
+ get optionsMap() {
3431
+ return this._def.optionsMap;
3432
+ }
3433
+ static create(discriminator, options, params) {
3434
+ const optionsMap = new Map;
3435
+ for (const type of options) {
3436
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3437
+ if (!discriminatorValues.length) {
3438
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3439
+ }
3440
+ for (const value of discriminatorValues) {
3441
+ if (optionsMap.has(value)) {
3442
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3443
+ }
3444
+ optionsMap.set(value, type);
3445
+ }
3446
+ }
3447
+ return new ZodDiscriminatedUnion({
3448
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3449
+ discriminator,
3450
+ options,
3451
+ optionsMap,
3452
+ ...processCreateParams(params)
3453
+ });
3454
+ }
3455
+ }
3456
+ function mergeValues(a, b) {
3457
+ const aType = getParsedType(a);
3458
+ const bType = getParsedType(b);
3459
+ if (a === b) {
3460
+ return { valid: true, data: a };
3461
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3462
+ const bKeys = util.objectKeys(b);
3463
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3464
+ const newObj = { ...a, ...b };
3465
+ for (const key of sharedKeys) {
3466
+ const sharedValue = mergeValues(a[key], b[key]);
3467
+ if (!sharedValue.valid) {
3468
+ return { valid: false };
3469
+ }
3470
+ newObj[key] = sharedValue.data;
3471
+ }
3472
+ return { valid: true, data: newObj };
3473
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3474
+ if (a.length !== b.length) {
3475
+ return { valid: false };
3476
+ }
3477
+ const newArray = [];
3478
+ for (let index = 0;index < a.length; index++) {
3479
+ const itemA = a[index];
3480
+ const itemB = b[index];
3481
+ const sharedValue = mergeValues(itemA, itemB);
3482
+ if (!sharedValue.valid) {
3483
+ return { valid: false };
3484
+ }
3485
+ newArray.push(sharedValue.data);
3486
+ }
3487
+ return { valid: true, data: newArray };
3488
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
3489
+ return { valid: true, data: a };
3490
+ } else {
3491
+ return { valid: false };
3492
+ }
3493
+ }
3494
+
3495
+ class ZodIntersection extends ZodType {
3496
+ _parse(input) {
3497
+ const { status, ctx } = this._processInputParams(input);
3498
+ const handleParsed = (parsedLeft, parsedRight) => {
3499
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3500
+ return INVALID;
3501
+ }
3502
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
3503
+ if (!merged.valid) {
3504
+ addIssueToContext(ctx, {
3505
+ code: ZodIssueCode.invalid_intersection_types
3506
+ });
3507
+ return INVALID;
3508
+ }
3509
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3510
+ status.dirty();
3511
+ }
3512
+ return { status: status.value, value: merged.data };
3513
+ };
3514
+ if (ctx.common.async) {
3515
+ return Promise.all([
3516
+ this._def.left._parseAsync({
3517
+ data: ctx.data,
3518
+ path: ctx.path,
3519
+ parent: ctx
3520
+ }),
3521
+ this._def.right._parseAsync({
3522
+ data: ctx.data,
3523
+ path: ctx.path,
3524
+ parent: ctx
3525
+ })
3526
+ ]).then(([left, right]) => handleParsed(left, right));
3527
+ } else {
3528
+ return handleParsed(this._def.left._parseSync({
3529
+ data: ctx.data,
3530
+ path: ctx.path,
3531
+ parent: ctx
3532
+ }), this._def.right._parseSync({
3533
+ data: ctx.data,
3534
+ path: ctx.path,
3535
+ parent: ctx
3536
+ }));
3537
+ }
3538
+ }
3539
+ }
3540
+ ZodIntersection.create = (left, right, params) => {
3541
+ return new ZodIntersection({
3542
+ left,
3543
+ right,
3544
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
3545
+ ...processCreateParams(params)
3546
+ });
3547
+ };
3548
+
3549
+ class ZodTuple extends ZodType {
3550
+ _parse(input) {
3551
+ const { status, ctx } = this._processInputParams(input);
3552
+ if (ctx.parsedType !== ZodParsedType.array) {
3553
+ addIssueToContext(ctx, {
3554
+ code: ZodIssueCode.invalid_type,
3555
+ expected: ZodParsedType.array,
3556
+ received: ctx.parsedType
3557
+ });
3558
+ return INVALID;
3559
+ }
3560
+ if (ctx.data.length < this._def.items.length) {
3561
+ addIssueToContext(ctx, {
3562
+ code: ZodIssueCode.too_small,
3563
+ minimum: this._def.items.length,
3564
+ inclusive: true,
3565
+ exact: false,
3566
+ type: "array"
3567
+ });
3568
+ return INVALID;
3569
+ }
3570
+ const rest = this._def.rest;
3571
+ if (!rest && ctx.data.length > this._def.items.length) {
3572
+ addIssueToContext(ctx, {
3573
+ code: ZodIssueCode.too_big,
3574
+ maximum: this._def.items.length,
3575
+ inclusive: true,
3576
+ exact: false,
3577
+ type: "array"
3578
+ });
3579
+ status.dirty();
3580
+ }
3581
+ const items = [...ctx.data].map((item, itemIndex) => {
3582
+ const schema = this._def.items[itemIndex] || this._def.rest;
3583
+ if (!schema)
3584
+ return null;
3585
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3586
+ }).filter((x) => !!x);
3587
+ if (ctx.common.async) {
3588
+ return Promise.all(items).then((results) => {
3589
+ return ParseStatus.mergeArray(status, results);
3590
+ });
3591
+ } else {
3592
+ return ParseStatus.mergeArray(status, items);
3593
+ }
3594
+ }
3595
+ get items() {
3596
+ return this._def.items;
3597
+ }
3598
+ rest(rest) {
3599
+ return new ZodTuple({
3600
+ ...this._def,
3601
+ rest
3602
+ });
3603
+ }
3604
+ }
3605
+ ZodTuple.create = (schemas, params) => {
3606
+ if (!Array.isArray(schemas)) {
3607
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3608
+ }
3609
+ return new ZodTuple({
3610
+ items: schemas,
3611
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3612
+ rest: null,
3613
+ ...processCreateParams(params)
3614
+ });
3615
+ };
3616
+
3617
+ class ZodRecord extends ZodType {
3618
+ get keySchema() {
3619
+ return this._def.keyType;
3620
+ }
3621
+ get valueSchema() {
3622
+ return this._def.valueType;
3623
+ }
3624
+ _parse(input) {
3625
+ const { status, ctx } = this._processInputParams(input);
3626
+ if (ctx.parsedType !== ZodParsedType.object) {
3627
+ addIssueToContext(ctx, {
3628
+ code: ZodIssueCode.invalid_type,
3629
+ expected: ZodParsedType.object,
3630
+ received: ctx.parsedType
3631
+ });
3632
+ return INVALID;
3633
+ }
3634
+ const pairs = [];
3635
+ const keyType = this._def.keyType;
3636
+ const valueType = this._def.valueType;
3637
+ for (const key in ctx.data) {
3638
+ pairs.push({
3639
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3640
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3641
+ alwaysSet: key in ctx.data
3642
+ });
3643
+ }
3644
+ if (ctx.common.async) {
3645
+ return ParseStatus.mergeObjectAsync(status, pairs);
3646
+ } else {
3647
+ return ParseStatus.mergeObjectSync(status, pairs);
3648
+ }
3649
+ }
3650
+ get element() {
3651
+ return this._def.valueType;
3652
+ }
3653
+ static create(first, second, third) {
3654
+ if (second instanceof ZodType) {
3655
+ return new ZodRecord({
3656
+ keyType: first,
3657
+ valueType: second,
3658
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3659
+ ...processCreateParams(third)
3660
+ });
3661
+ }
3662
+ return new ZodRecord({
3663
+ keyType: ZodString.create(),
3664
+ valueType: first,
3665
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3666
+ ...processCreateParams(second)
3667
+ });
3668
+ }
3669
+ }
3670
+
3671
+ class ZodMap extends ZodType {
3672
+ get keySchema() {
3673
+ return this._def.keyType;
3674
+ }
3675
+ get valueSchema() {
3676
+ return this._def.valueType;
3677
+ }
3678
+ _parse(input) {
3679
+ const { status, ctx } = this._processInputParams(input);
3680
+ if (ctx.parsedType !== ZodParsedType.map) {
3681
+ addIssueToContext(ctx, {
3682
+ code: ZodIssueCode.invalid_type,
3683
+ expected: ZodParsedType.map,
3684
+ received: ctx.parsedType
3685
+ });
3686
+ return INVALID;
3687
+ }
3688
+ const keyType = this._def.keyType;
3689
+ const valueType = this._def.valueType;
3690
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3691
+ return {
3692
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3693
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3694
+ };
3695
+ });
3696
+ if (ctx.common.async) {
3697
+ const finalMap = new Map;
3698
+ return Promise.resolve().then(async () => {
3699
+ for (const pair of pairs) {
3700
+ const key = await pair.key;
3701
+ const value = await pair.value;
3702
+ if (key.status === "aborted" || value.status === "aborted") {
3703
+ return INVALID;
3704
+ }
3705
+ if (key.status === "dirty" || value.status === "dirty") {
3706
+ status.dirty();
3707
+ }
3708
+ finalMap.set(key.value, value.value);
3709
+ }
3710
+ return { status: status.value, value: finalMap };
3711
+ });
3712
+ } else {
3713
+ const finalMap = new Map;
3714
+ for (const pair of pairs) {
3715
+ const key = pair.key;
3716
+ const value = pair.value;
3717
+ if (key.status === "aborted" || value.status === "aborted") {
3718
+ return INVALID;
3719
+ }
3720
+ if (key.status === "dirty" || value.status === "dirty") {
3721
+ status.dirty();
3722
+ }
3723
+ finalMap.set(key.value, value.value);
3724
+ }
3725
+ return { status: status.value, value: finalMap };
3726
+ }
3727
+ }
3728
+ }
3729
+ ZodMap.create = (keyType, valueType, params) => {
3730
+ return new ZodMap({
3731
+ valueType,
3732
+ keyType,
3733
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3734
+ ...processCreateParams(params)
3735
+ });
3736
+ };
3737
+
3738
+ class ZodSet extends ZodType {
3739
+ _parse(input) {
3740
+ const { status, ctx } = this._processInputParams(input);
3741
+ if (ctx.parsedType !== ZodParsedType.set) {
3742
+ addIssueToContext(ctx, {
3743
+ code: ZodIssueCode.invalid_type,
3744
+ expected: ZodParsedType.set,
3745
+ received: ctx.parsedType
3746
+ });
3747
+ return INVALID;
3748
+ }
3749
+ const def = this._def;
3750
+ if (def.minSize !== null) {
3751
+ if (ctx.data.size < def.minSize.value) {
3752
+ addIssueToContext(ctx, {
3753
+ code: ZodIssueCode.too_small,
3754
+ minimum: def.minSize.value,
3755
+ type: "set",
3756
+ inclusive: true,
3757
+ exact: false,
3758
+ message: def.minSize.message
3759
+ });
3760
+ status.dirty();
3761
+ }
3762
+ }
3763
+ if (def.maxSize !== null) {
3764
+ if (ctx.data.size > def.maxSize.value) {
3765
+ addIssueToContext(ctx, {
3766
+ code: ZodIssueCode.too_big,
3767
+ maximum: def.maxSize.value,
3768
+ type: "set",
3769
+ inclusive: true,
3770
+ exact: false,
3771
+ message: def.maxSize.message
3772
+ });
3773
+ status.dirty();
3774
+ }
3775
+ }
3776
+ const valueType = this._def.valueType;
3777
+ function finalizeSet(elements2) {
3778
+ const parsedSet = new Set;
3779
+ for (const element of elements2) {
3780
+ if (element.status === "aborted")
3781
+ return INVALID;
3782
+ if (element.status === "dirty")
3783
+ status.dirty();
3784
+ parsedSet.add(element.value);
3785
+ }
3786
+ return { status: status.value, value: parsedSet };
3787
+ }
3788
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3789
+ if (ctx.common.async) {
3790
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3791
+ } else {
3792
+ return finalizeSet(elements);
3793
+ }
3794
+ }
3795
+ min(minSize, message) {
3796
+ return new ZodSet({
3797
+ ...this._def,
3798
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3799
+ });
3800
+ }
3801
+ max(maxSize, message) {
3802
+ return new ZodSet({
3803
+ ...this._def,
3804
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3805
+ });
3806
+ }
3807
+ size(size, message) {
3808
+ return this.min(size, message).max(size, message);
3809
+ }
3810
+ nonempty(message) {
3811
+ return this.min(1, message);
3812
+ }
3813
+ }
3814
+ ZodSet.create = (valueType, params) => {
3815
+ return new ZodSet({
3816
+ valueType,
3817
+ minSize: null,
3818
+ maxSize: null,
3819
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3820
+ ...processCreateParams(params)
3821
+ });
3822
+ };
3823
+
3824
+ class ZodFunction extends ZodType {
3825
+ constructor() {
3826
+ super(...arguments);
3827
+ this.validate = this.implement;
3828
+ }
3829
+ _parse(input) {
3830
+ const { ctx } = this._processInputParams(input);
3831
+ if (ctx.parsedType !== ZodParsedType.function) {
3832
+ addIssueToContext(ctx, {
3833
+ code: ZodIssueCode.invalid_type,
3834
+ expected: ZodParsedType.function,
3835
+ received: ctx.parsedType
3836
+ });
3837
+ return INVALID;
3838
+ }
3839
+ function makeArgsIssue(args, error) {
3840
+ return makeIssue({
3841
+ data: args,
3842
+ path: ctx.path,
3843
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3844
+ issueData: {
3845
+ code: ZodIssueCode.invalid_arguments,
3846
+ argumentsError: error
3847
+ }
3848
+ });
3849
+ }
3850
+ function makeReturnsIssue(returns, error) {
3851
+ return makeIssue({
3852
+ data: returns,
3853
+ path: ctx.path,
3854
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3855
+ issueData: {
3856
+ code: ZodIssueCode.invalid_return_type,
3857
+ returnTypeError: error
3858
+ }
3859
+ });
3860
+ }
3861
+ const params = { errorMap: ctx.common.contextualErrorMap };
3862
+ const fn = ctx.data;
3863
+ if (this._def.returns instanceof ZodPromise) {
3864
+ const me = this;
3865
+ return OK(async function(...args) {
3866
+ const error = new ZodError([]);
3867
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3868
+ error.addIssue(makeArgsIssue(args, e));
3869
+ throw error;
3870
+ });
3871
+ const result = await Reflect.apply(fn, this, parsedArgs);
3872
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3873
+ error.addIssue(makeReturnsIssue(result, e));
3874
+ throw error;
3875
+ });
3876
+ return parsedReturns;
3877
+ });
3878
+ } else {
3879
+ const me = this;
3880
+ return OK(function(...args) {
3881
+ const parsedArgs = me._def.args.safeParse(args, params);
3882
+ if (!parsedArgs.success) {
3883
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3884
+ }
3885
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3886
+ const parsedReturns = me._def.returns.safeParse(result, params);
3887
+ if (!parsedReturns.success) {
3888
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3889
+ }
3890
+ return parsedReturns.data;
3891
+ });
3892
+ }
3893
+ }
3894
+ parameters() {
3895
+ return this._def.args;
3896
+ }
3897
+ returnType() {
3898
+ return this._def.returns;
3899
+ }
3900
+ args(...items) {
3901
+ return new ZodFunction({
3902
+ ...this._def,
3903
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3904
+ });
3905
+ }
3906
+ returns(returnType) {
3907
+ return new ZodFunction({
3908
+ ...this._def,
3909
+ returns: returnType
3910
+ });
3911
+ }
3912
+ implement(func) {
3913
+ const validatedFunc = this.parse(func);
3914
+ return validatedFunc;
3915
+ }
3916
+ strictImplement(func) {
3917
+ const validatedFunc = this.parse(func);
3918
+ return validatedFunc;
3919
+ }
3920
+ static create(args, returns, params) {
3921
+ return new ZodFunction({
3922
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3923
+ returns: returns || ZodUnknown.create(),
3924
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3925
+ ...processCreateParams(params)
3926
+ });
3927
+ }
3928
+ }
3929
+
3930
+ class ZodLazy extends ZodType {
3931
+ get schema() {
3932
+ return this._def.getter();
3933
+ }
3934
+ _parse(input) {
3935
+ const { ctx } = this._processInputParams(input);
3936
+ const lazySchema = this._def.getter();
3937
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3938
+ }
3939
+ }
3940
+ ZodLazy.create = (getter, params) => {
3941
+ return new ZodLazy({
3942
+ getter,
3943
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3944
+ ...processCreateParams(params)
3945
+ });
3946
+ };
3947
+
3948
+ class ZodLiteral extends ZodType {
3949
+ _parse(input) {
3950
+ if (input.data !== this._def.value) {
3951
+ const ctx = this._getOrReturnCtx(input);
3952
+ addIssueToContext(ctx, {
3953
+ received: ctx.data,
3954
+ code: ZodIssueCode.invalid_literal,
3955
+ expected: this._def.value
3956
+ });
3957
+ return INVALID;
3958
+ }
3959
+ return { status: "valid", value: input.data };
3960
+ }
3961
+ get value() {
3962
+ return this._def.value;
3963
+ }
3964
+ }
3965
+ ZodLiteral.create = (value, params) => {
3966
+ return new ZodLiteral({
3967
+ value,
3968
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3969
+ ...processCreateParams(params)
3970
+ });
3971
+ };
3972
+ function createZodEnum(values, params) {
3973
+ return new ZodEnum({
3974
+ values,
3975
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3976
+ ...processCreateParams(params)
3977
+ });
3978
+ }
3979
+
3980
+ class ZodEnum extends ZodType {
3981
+ _parse(input) {
3982
+ if (typeof input.data !== "string") {
3983
+ const ctx = this._getOrReturnCtx(input);
3984
+ const expectedValues = this._def.values;
3985
+ addIssueToContext(ctx, {
3986
+ expected: util.joinValues(expectedValues),
3987
+ received: ctx.parsedType,
3988
+ code: ZodIssueCode.invalid_type
3989
+ });
3990
+ return INVALID;
3991
+ }
3992
+ if (!this._cache) {
3993
+ this._cache = new Set(this._def.values);
3994
+ }
3995
+ if (!this._cache.has(input.data)) {
3996
+ const ctx = this._getOrReturnCtx(input);
3997
+ const expectedValues = this._def.values;
3998
+ addIssueToContext(ctx, {
3999
+ received: ctx.data,
4000
+ code: ZodIssueCode.invalid_enum_value,
4001
+ options: expectedValues
4002
+ });
4003
+ return INVALID;
4004
+ }
4005
+ return OK(input.data);
4006
+ }
4007
+ get options() {
4008
+ return this._def.values;
4009
+ }
4010
+ get enum() {
4011
+ const enumValues = {};
4012
+ for (const val of this._def.values) {
4013
+ enumValues[val] = val;
4014
+ }
4015
+ return enumValues;
4016
+ }
4017
+ get Values() {
4018
+ const enumValues = {};
4019
+ for (const val of this._def.values) {
4020
+ enumValues[val] = val;
4021
+ }
4022
+ return enumValues;
4023
+ }
4024
+ get Enum() {
4025
+ const enumValues = {};
4026
+ for (const val of this._def.values) {
4027
+ enumValues[val] = val;
4028
+ }
4029
+ return enumValues;
4030
+ }
4031
+ extract(values, newDef = this._def) {
4032
+ return ZodEnum.create(values, {
4033
+ ...this._def,
4034
+ ...newDef
4035
+ });
4036
+ }
4037
+ exclude(values, newDef = this._def) {
4038
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4039
+ ...this._def,
4040
+ ...newDef
4041
+ });
4042
+ }
4043
+ }
4044
+ ZodEnum.create = createZodEnum;
4045
+
4046
+ class ZodNativeEnum extends ZodType {
4047
+ _parse(input) {
4048
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
4049
+ const ctx = this._getOrReturnCtx(input);
4050
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
4051
+ const expectedValues = util.objectValues(nativeEnumValues);
4052
+ addIssueToContext(ctx, {
4053
+ expected: util.joinValues(expectedValues),
4054
+ received: ctx.parsedType,
4055
+ code: ZodIssueCode.invalid_type
4056
+ });
4057
+ return INVALID;
4058
+ }
4059
+ if (!this._cache) {
4060
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
4061
+ }
4062
+ if (!this._cache.has(input.data)) {
4063
+ const expectedValues = util.objectValues(nativeEnumValues);
4064
+ addIssueToContext(ctx, {
4065
+ received: ctx.data,
4066
+ code: ZodIssueCode.invalid_enum_value,
4067
+ options: expectedValues
4068
+ });
4069
+ return INVALID;
4070
+ }
4071
+ return OK(input.data);
4072
+ }
4073
+ get enum() {
4074
+ return this._def.values;
4075
+ }
4076
+ }
4077
+ ZodNativeEnum.create = (values, params) => {
4078
+ return new ZodNativeEnum({
4079
+ values,
4080
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
4081
+ ...processCreateParams(params)
4082
+ });
4083
+ };
4084
+
4085
+ class ZodPromise extends ZodType {
4086
+ unwrap() {
4087
+ return this._def.type;
4088
+ }
4089
+ _parse(input) {
4090
+ const { ctx } = this._processInputParams(input);
4091
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
4092
+ addIssueToContext(ctx, {
4093
+ code: ZodIssueCode.invalid_type,
4094
+ expected: ZodParsedType.promise,
4095
+ received: ctx.parsedType
4096
+ });
4097
+ return INVALID;
4098
+ }
4099
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
4100
+ return OK(promisified.then((data) => {
4101
+ return this._def.type.parseAsync(data, {
4102
+ path: ctx.path,
4103
+ errorMap: ctx.common.contextualErrorMap
4104
+ });
4105
+ }));
4106
+ }
4107
+ }
4108
+ ZodPromise.create = (schema, params) => {
4109
+ return new ZodPromise({
4110
+ type: schema,
4111
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
4112
+ ...processCreateParams(params)
4113
+ });
4114
+ };
4115
+
4116
+ class ZodEffects extends ZodType {
4117
+ innerType() {
4118
+ return this._def.schema;
4119
+ }
4120
+ sourceType() {
4121
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
4122
+ }
4123
+ _parse(input) {
4124
+ const { status, ctx } = this._processInputParams(input);
4125
+ const effect = this._def.effect || null;
4126
+ const checkCtx = {
4127
+ addIssue: (arg) => {
4128
+ addIssueToContext(ctx, arg);
4129
+ if (arg.fatal) {
4130
+ status.abort();
4131
+ } else {
4132
+ status.dirty();
4133
+ }
4134
+ },
4135
+ get path() {
4136
+ return ctx.path;
4137
+ }
4138
+ };
4139
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
4140
+ if (effect.type === "preprocess") {
4141
+ const processed = effect.transform(ctx.data, checkCtx);
4142
+ if (ctx.common.async) {
4143
+ return Promise.resolve(processed).then(async (processed2) => {
4144
+ if (status.value === "aborted")
4145
+ return INVALID;
4146
+ const result = await this._def.schema._parseAsync({
4147
+ data: processed2,
4148
+ path: ctx.path,
4149
+ parent: ctx
4150
+ });
4151
+ if (result.status === "aborted")
4152
+ return INVALID;
4153
+ if (result.status === "dirty")
4154
+ return DIRTY(result.value);
4155
+ if (status.value === "dirty")
4156
+ return DIRTY(result.value);
4157
+ return result;
4158
+ });
4159
+ } else {
4160
+ if (status.value === "aborted")
4161
+ return INVALID;
4162
+ const result = this._def.schema._parseSync({
4163
+ data: processed,
4164
+ path: ctx.path,
4165
+ parent: ctx
4166
+ });
4167
+ if (result.status === "aborted")
4168
+ return INVALID;
4169
+ if (result.status === "dirty")
4170
+ return DIRTY(result.value);
4171
+ if (status.value === "dirty")
4172
+ return DIRTY(result.value);
4173
+ return result;
4174
+ }
4175
+ }
4176
+ if (effect.type === "refinement") {
4177
+ const executeRefinement = (acc) => {
4178
+ const result = effect.refinement(acc, checkCtx);
4179
+ if (ctx.common.async) {
4180
+ return Promise.resolve(result);
4181
+ }
4182
+ if (result instanceof Promise) {
4183
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
4184
+ }
4185
+ return acc;
4186
+ };
4187
+ if (ctx.common.async === false) {
4188
+ const inner = this._def.schema._parseSync({
4189
+ data: ctx.data,
4190
+ path: ctx.path,
4191
+ parent: ctx
4192
+ });
4193
+ if (inner.status === "aborted")
4194
+ return INVALID;
4195
+ if (inner.status === "dirty")
4196
+ status.dirty();
4197
+ executeRefinement(inner.value);
4198
+ return { status: status.value, value: inner.value };
4199
+ } else {
4200
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
4201
+ if (inner.status === "aborted")
4202
+ return INVALID;
4203
+ if (inner.status === "dirty")
4204
+ status.dirty();
4205
+ return executeRefinement(inner.value).then(() => {
4206
+ return { status: status.value, value: inner.value };
4207
+ });
4208
+ });
4209
+ }
4210
+ }
4211
+ if (effect.type === "transform") {
4212
+ if (ctx.common.async === false) {
4213
+ const base = this._def.schema._parseSync({
4214
+ data: ctx.data,
4215
+ path: ctx.path,
4216
+ parent: ctx
4217
+ });
4218
+ if (!isValid(base))
4219
+ return INVALID;
4220
+ const result = effect.transform(base.value, checkCtx);
4221
+ if (result instanceof Promise) {
4222
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
4223
+ }
4224
+ return { status: status.value, value: result };
4225
+ } else {
4226
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
4227
+ if (!isValid(base))
4228
+ return INVALID;
4229
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
4230
+ status: status.value,
4231
+ value: result
4232
+ }));
4233
+ });
4234
+ }
4235
+ }
4236
+ util.assertNever(effect);
4237
+ }
4238
+ }
4239
+ ZodEffects.create = (schema, effect, params) => {
4240
+ return new ZodEffects({
4241
+ schema,
4242
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4243
+ effect,
4244
+ ...processCreateParams(params)
4245
+ });
4246
+ };
4247
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
4248
+ return new ZodEffects({
4249
+ schema,
4250
+ effect: { type: "preprocess", transform: preprocess },
4251
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4252
+ ...processCreateParams(params)
4253
+ });
4254
+ };
4255
+ class ZodOptional extends ZodType {
4256
+ _parse(input) {
4257
+ const parsedType = this._getType(input);
4258
+ if (parsedType === ZodParsedType.undefined) {
4259
+ return OK(undefined);
4260
+ }
4261
+ return this._def.innerType._parse(input);
4262
+ }
4263
+ unwrap() {
4264
+ return this._def.innerType;
4265
+ }
4266
+ }
4267
+ ZodOptional.create = (type, params) => {
4268
+ return new ZodOptional({
4269
+ innerType: type,
4270
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
4271
+ ...processCreateParams(params)
4272
+ });
4273
+ };
4274
+
4275
+ class ZodNullable extends ZodType {
4276
+ _parse(input) {
4277
+ const parsedType = this._getType(input);
4278
+ if (parsedType === ZodParsedType.null) {
4279
+ return OK(null);
4280
+ }
4281
+ return this._def.innerType._parse(input);
4282
+ }
4283
+ unwrap() {
4284
+ return this._def.innerType;
4285
+ }
4286
+ }
4287
+ ZodNullable.create = (type, params) => {
4288
+ return new ZodNullable({
4289
+ innerType: type,
4290
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
4291
+ ...processCreateParams(params)
4292
+ });
4293
+ };
4294
+
4295
+ class ZodDefault extends ZodType {
4296
+ _parse(input) {
4297
+ const { ctx } = this._processInputParams(input);
4298
+ let data = ctx.data;
4299
+ if (ctx.parsedType === ZodParsedType.undefined) {
4300
+ data = this._def.defaultValue();
4301
+ }
4302
+ return this._def.innerType._parse({
4303
+ data,
4304
+ path: ctx.path,
4305
+ parent: ctx
4306
+ });
4307
+ }
4308
+ removeDefault() {
4309
+ return this._def.innerType;
4310
+ }
4311
+ }
4312
+ ZodDefault.create = (type, params) => {
4313
+ return new ZodDefault({
4314
+ innerType: type,
4315
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
4316
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
4317
+ ...processCreateParams(params)
4318
+ });
4319
+ };
4320
+
4321
+ class ZodCatch extends ZodType {
4322
+ _parse(input) {
4323
+ const { ctx } = this._processInputParams(input);
4324
+ const newCtx = {
4325
+ ...ctx,
4326
+ common: {
4327
+ ...ctx.common,
4328
+ issues: []
4329
+ }
4330
+ };
4331
+ const result = this._def.innerType._parse({
4332
+ data: newCtx.data,
4333
+ path: newCtx.path,
4334
+ parent: {
4335
+ ...newCtx
4336
+ }
4337
+ });
4338
+ if (isAsync(result)) {
4339
+ return result.then((result2) => {
4340
+ return {
4341
+ status: "valid",
4342
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
4343
+ get error() {
4344
+ return new ZodError(newCtx.common.issues);
4345
+ },
4346
+ input: newCtx.data
4347
+ })
4348
+ };
4349
+ });
4350
+ } else {
4351
+ return {
4352
+ status: "valid",
4353
+ value: result.status === "valid" ? result.value : this._def.catchValue({
4354
+ get error() {
4355
+ return new ZodError(newCtx.common.issues);
4356
+ },
4357
+ input: newCtx.data
4358
+ })
4359
+ };
4360
+ }
4361
+ }
4362
+ removeCatch() {
4363
+ return this._def.innerType;
4364
+ }
4365
+ }
4366
+ ZodCatch.create = (type, params) => {
4367
+ return new ZodCatch({
4368
+ innerType: type,
4369
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
4370
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4371
+ ...processCreateParams(params)
4372
+ });
4373
+ };
4374
+
4375
+ class ZodNaN extends ZodType {
4376
+ _parse(input) {
4377
+ const parsedType = this._getType(input);
4378
+ if (parsedType !== ZodParsedType.nan) {
4379
+ const ctx = this._getOrReturnCtx(input);
4380
+ addIssueToContext(ctx, {
4381
+ code: ZodIssueCode.invalid_type,
4382
+ expected: ZodParsedType.nan,
4383
+ received: ctx.parsedType
4384
+ });
4385
+ return INVALID;
4386
+ }
4387
+ return { status: "valid", value: input.data };
4388
+ }
4389
+ }
4390
+ ZodNaN.create = (params) => {
4391
+ return new ZodNaN({
4392
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
4393
+ ...processCreateParams(params)
4394
+ });
4395
+ };
4396
+ var BRAND = Symbol("zod_brand");
4397
+
4398
+ class ZodBranded extends ZodType {
4399
+ _parse(input) {
4400
+ const { ctx } = this._processInputParams(input);
4401
+ const data = ctx.data;
4402
+ return this._def.type._parse({
4403
+ data,
4404
+ path: ctx.path,
4405
+ parent: ctx
4406
+ });
4407
+ }
4408
+ unwrap() {
4409
+ return this._def.type;
4410
+ }
4411
+ }
4412
+
4413
+ class ZodPipeline extends ZodType {
4414
+ _parse(input) {
4415
+ const { status, ctx } = this._processInputParams(input);
4416
+ if (ctx.common.async) {
4417
+ const handleAsync = async () => {
4418
+ const inResult = await this._def.in._parseAsync({
4419
+ data: ctx.data,
4420
+ path: ctx.path,
4421
+ parent: ctx
4422
+ });
4423
+ if (inResult.status === "aborted")
4424
+ return INVALID;
4425
+ if (inResult.status === "dirty") {
4426
+ status.dirty();
4427
+ return DIRTY(inResult.value);
4428
+ } else {
4429
+ return this._def.out._parseAsync({
4430
+ data: inResult.value,
4431
+ path: ctx.path,
4432
+ parent: ctx
4433
+ });
4434
+ }
4435
+ };
4436
+ return handleAsync();
4437
+ } else {
4438
+ const inResult = this._def.in._parseSync({
4439
+ data: ctx.data,
4440
+ path: ctx.path,
4441
+ parent: ctx
4442
+ });
4443
+ if (inResult.status === "aborted")
4444
+ return INVALID;
4445
+ if (inResult.status === "dirty") {
4446
+ status.dirty();
4447
+ return {
4448
+ status: "dirty",
4449
+ value: inResult.value
4450
+ };
4451
+ } else {
4452
+ return this._def.out._parseSync({
4453
+ data: inResult.value,
4454
+ path: ctx.path,
4455
+ parent: ctx
4456
+ });
4457
+ }
4458
+ }
4459
+ }
4460
+ static create(a, b) {
4461
+ return new ZodPipeline({
4462
+ in: a,
4463
+ out: b,
4464
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
4465
+ });
4466
+ }
4467
+ }
4468
+
4469
+ class ZodReadonly extends ZodType {
4470
+ _parse(input) {
4471
+ const result = this._def.innerType._parse(input);
4472
+ const freeze = (data) => {
4473
+ if (isValid(data)) {
4474
+ data.value = Object.freeze(data.value);
4475
+ }
4476
+ return data;
4477
+ };
4478
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4479
+ }
4480
+ unwrap() {
4481
+ return this._def.innerType;
4482
+ }
4483
+ }
4484
+ ZodReadonly.create = (type, params) => {
4485
+ return new ZodReadonly({
4486
+ innerType: type,
4487
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4488
+ ...processCreateParams(params)
4489
+ });
4490
+ };
4491
+ function cleanParams(params, data) {
4492
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
4493
+ const p2 = typeof p === "string" ? { message: p } : p;
4494
+ return p2;
4495
+ }
4496
+ function custom(check, _params = {}, fatal) {
4497
+ if (check)
4498
+ return ZodAny.create().superRefine((data, ctx) => {
4499
+ const r = check(data);
4500
+ if (r instanceof Promise) {
4501
+ return r.then((r2) => {
4502
+ if (!r2) {
4503
+ const params = cleanParams(_params, data);
4504
+ const _fatal = params.fatal ?? fatal ?? true;
4505
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4506
+ }
4507
+ });
4508
+ }
4509
+ if (!r) {
4510
+ const params = cleanParams(_params, data);
4511
+ const _fatal = params.fatal ?? fatal ?? true;
4512
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4513
+ }
4514
+ return;
4515
+ });
4516
+ return ZodAny.create();
4517
+ }
4518
+ var late = {
4519
+ object: ZodObject.lazycreate
4520
+ };
4521
+ var ZodFirstPartyTypeKind;
4522
+ (function(ZodFirstPartyTypeKind2) {
4523
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
4524
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
4525
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
4526
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
4527
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
4528
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
4529
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
4530
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
4531
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
4532
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
4533
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
4534
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
4535
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
4536
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
4537
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
4538
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
4539
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4540
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
4541
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
4542
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
4543
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
4544
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
4545
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
4546
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
4547
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
4548
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
4549
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
4550
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4551
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4552
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4553
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4554
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4555
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4556
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4557
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4558
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4559
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4560
+ var instanceOfType = (cls, params = {
4561
+ message: `Input not instance of ${cls.name}`
4562
+ }) => custom((data) => data instanceof cls, params);
4563
+ var stringType = ZodString.create;
4564
+ var numberType = ZodNumber.create;
4565
+ var nanType = ZodNaN.create;
4566
+ var bigIntType = ZodBigInt.create;
4567
+ var booleanType = ZodBoolean.create;
4568
+ var dateType = ZodDate.create;
4569
+ var symbolType = ZodSymbol.create;
4570
+ var undefinedType = ZodUndefined.create;
4571
+ var nullType = ZodNull.create;
4572
+ var anyType = ZodAny.create;
4573
+ var unknownType = ZodUnknown.create;
4574
+ var neverType = ZodNever.create;
4575
+ var voidType = ZodVoid.create;
4576
+ var arrayType = ZodArray.create;
4577
+ var objectType = ZodObject.create;
4578
+ var strictObjectType = ZodObject.strictCreate;
4579
+ var unionType = ZodUnion.create;
4580
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
4581
+ var intersectionType = ZodIntersection.create;
4582
+ var tupleType = ZodTuple.create;
4583
+ var recordType = ZodRecord.create;
4584
+ var mapType = ZodMap.create;
4585
+ var setType = ZodSet.create;
4586
+ var functionType = ZodFunction.create;
4587
+ var lazyType = ZodLazy.create;
4588
+ var literalType = ZodLiteral.create;
4589
+ var enumType = ZodEnum.create;
4590
+ var nativeEnumType = ZodNativeEnum.create;
4591
+ var promiseType = ZodPromise.create;
4592
+ var effectsType = ZodEffects.create;
4593
+ var optionalType = ZodOptional.create;
4594
+ var nullableType = ZodNullable.create;
4595
+ var preprocessType = ZodEffects.createWithPreprocess;
4596
+ var pipelineType = ZodPipeline.create;
4597
+ var ostring = () => stringType().optional();
4598
+ var onumber = () => numberType().optional();
4599
+ var oboolean = () => booleanType().optional();
4600
+ var coerce = {
4601
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
4602
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4603
+ boolean: (arg) => ZodBoolean.create({
4604
+ ...arg,
4605
+ coerce: true
4606
+ }),
4607
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4608
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
4609
+ };
4610
+ var NEVER = INVALID;
4611
+ // src/auth/broker/protocol.ts
4612
+ var MAX_FRAME_BYTES = 64 * 1024;
4613
+ var PROTOCOL_VERSION = 1;
4614
+ var ProviderNameSchema = exports_external.enum(["anthropic", "google", "microsoft"]);
4615
+ var GetCredentialsRequestSchema = exports_external.object({
4616
+ v: exports_external.literal(PROTOCOL_VERSION),
4617
+ op: exports_external.literal("get-credentials"),
4618
+ id: exports_external.string().min(1),
4619
+ provider: ProviderNameSchema.optional()
4620
+ });
4621
+ var ListStateRequestSchema = exports_external.object({
4622
+ v: exports_external.literal(PROTOCOL_VERSION),
4623
+ op: exports_external.literal("list-state"),
4624
+ id: exports_external.string().min(1)
4625
+ });
4626
+ var SetActiveRequestSchema = exports_external.object({
4627
+ v: exports_external.literal(PROTOCOL_VERSION),
4628
+ op: exports_external.literal("set-active"),
4629
+ id: exports_external.string().min(1),
4630
+ account: exports_external.string().min(1),
4631
+ provider: ProviderNameSchema.optional()
4632
+ });
4633
+ var MarkExhaustedRequestSchema = exports_external.object({
4634
+ v: exports_external.literal(PROTOCOL_VERSION),
4635
+ op: exports_external.literal("mark-exhausted"),
4636
+ id: exports_external.string().min(1),
4637
+ until: exports_external.number().int().positive().optional()
4638
+ });
4639
+ var RefreshAccountRequestSchema = exports_external.object({
4640
+ v: exports_external.literal(PROTOCOL_VERSION),
4641
+ op: exports_external.literal("refresh-account"),
4642
+ id: exports_external.string().min(1),
4643
+ account: exports_external.string().min(1),
4644
+ provider: ProviderNameSchema.optional()
4645
+ });
4646
+ var AnthropicCredentialsSchema = exports_external.object({
4647
+ claudeAiOauth: exports_external.object({
4648
+ accessToken: exports_external.string(),
4649
+ refreshToken: exports_external.string().optional(),
4650
+ expiresAt: exports_external.number().optional(),
4651
+ scopes: exports_external.array(exports_external.string()).optional(),
4652
+ subscriptionType: exports_external.string().optional(),
4653
+ rateLimitTier: exports_external.string().optional()
4654
+ })
4655
+ });
4656
+ var GoogleCredentialsSchema = exports_external.object({
4657
+ googleOauth: exports_external.object({
4658
+ accessToken: exports_external.string(),
4659
+ refreshToken: exports_external.string(),
4660
+ expiresAt: exports_external.number(),
4661
+ scope: exports_external.string(),
4662
+ clientId: exports_external.string(),
4663
+ accountEmail: exports_external.string(),
4664
+ tokenType: exports_external.literal("Bearer")
4665
+ })
4666
+ });
4667
+ var MicrosoftCredentialsSchema = exports_external.object({
4668
+ microsoftOauth: exports_external.object({
4669
+ accessToken: exports_external.string(),
4670
+ refreshToken: exports_external.string(),
4671
+ expiresAt: exports_external.number(),
4672
+ scope: exports_external.string(),
4673
+ clientId: exports_external.string(),
4674
+ accountEmail: exports_external.string(),
4675
+ tokenType: exports_external.literal("Bearer"),
4676
+ tenantId: exports_external.string(),
4677
+ accountType: exports_external.enum(["personal", "work"]),
4678
+ homeAccountId: exports_external.string()
4679
+ })
4680
+ });
4681
+ var ProviderCredentialsSchema = exports_external.union([
4682
+ AnthropicCredentialsSchema,
4683
+ GoogleCredentialsSchema,
4684
+ MicrosoftCredentialsSchema
4685
+ ]);
4686
+ var AddAccountRequestSchema = exports_external.object({
4687
+ v: exports_external.literal(PROTOCOL_VERSION),
4688
+ op: exports_external.literal("add-account"),
4689
+ id: exports_external.string().min(1),
4690
+ label: exports_external.string().min(1),
4691
+ provider: ProviderNameSchema.optional(),
4692
+ credentials: ProviderCredentialsSchema,
4693
+ replace: exports_external.boolean().optional()
4694
+ });
4695
+ var RmAccountRequestSchema = exports_external.object({
4696
+ v: exports_external.literal(PROTOCOL_VERSION),
4697
+ op: exports_external.literal("rm-account"),
4698
+ id: exports_external.string().min(1),
4699
+ label: exports_external.string().min(1),
4700
+ provider: ProviderNameSchema.optional()
4701
+ });
4702
+ var SetOverrideRequestSchema = exports_external.object({
4703
+ v: exports_external.literal(PROTOCOL_VERSION),
4704
+ op: exports_external.literal("set-override"),
4705
+ id: exports_external.string().min(1),
4706
+ agent: exports_external.string().min(1),
4707
+ account: exports_external.string().min(1).nullable()
4708
+ });
4709
+ var ListGoogleAccountsRequestSchema = exports_external.object({
4710
+ v: exports_external.literal(PROTOCOL_VERSION),
4711
+ op: exports_external.literal("list-google-accounts"),
4712
+ id: exports_external.string().min(1)
4713
+ });
4714
+ var ListMicrosoftAccountsRequestSchema = exports_external.object({
4715
+ v: exports_external.literal(PROTOCOL_VERSION),
4716
+ op: exports_external.literal("list-microsoft-accounts"),
4717
+ id: exports_external.string().min(1)
4718
+ });
4719
+ var ProbeQuotaRequestSchema = exports_external.object({
4720
+ v: exports_external.literal(PROTOCOL_VERSION),
4721
+ op: exports_external.literal("probe-quota"),
4722
+ id: exports_external.string().min(1),
4723
+ accounts: exports_external.array(exports_external.string().min(1)).min(1).max(32),
4724
+ timeoutMs: exports_external.number().int().positive().max(60000).optional(),
4725
+ forceLive: exports_external.boolean().optional()
4726
+ });
4727
+ var ClaimNotificationRequestSchema = exports_external.object({
4728
+ v: exports_external.literal(PROTOCOL_VERSION),
4729
+ op: exports_external.literal("claim-notification"),
4730
+ id: exports_external.string().min(1),
4731
+ key: exports_external.string().min(1).max(512),
4732
+ windowMs: exports_external.number().int().positive().max(86400000)
4733
+ });
4734
+ var RequestSchema = exports_external.discriminatedUnion("op", [
4735
+ GetCredentialsRequestSchema,
4736
+ ListStateRequestSchema,
4737
+ SetActiveRequestSchema,
4738
+ MarkExhaustedRequestSchema,
4739
+ RefreshAccountRequestSchema,
4740
+ AddAccountRequestSchema,
4741
+ RmAccountRequestSchema,
4742
+ SetOverrideRequestSchema,
4743
+ ListGoogleAccountsRequestSchema,
4744
+ ListMicrosoftAccountsRequestSchema,
4745
+ ProbeQuotaRequestSchema,
4746
+ ClaimNotificationRequestSchema
4747
+ ]);
4748
+ var GetCredentialsDataSchema = exports_external.object({
4749
+ account: exports_external.string(),
4750
+ credentials: exports_external.unknown(),
4751
+ expiresAt: exports_external.number().optional()
4752
+ });
4753
+ var AccountStateSchema = exports_external.object({
4754
+ label: exports_external.string(),
4755
+ expiresAt: exports_external.number().optional(),
4756
+ exhausted: exports_external.boolean(),
4757
+ exhausted_until: exports_external.number().optional(),
4758
+ threshold_violations: exports_external.number().int().nonnegative().optional(),
4759
+ last_refreshed_at: exports_external.number().optional()
4760
+ });
4761
+ var AgentStateSchema = exports_external.object({
4762
+ name: exports_external.string(),
4763
+ account: exports_external.string(),
4764
+ override: exports_external.string().nullable()
4765
+ });
4766
+ var ConsumerStateSchema = exports_external.object({
4767
+ name: exports_external.string(),
4768
+ account: exports_external.string(),
4769
+ last_seen_at: exports_external.number().nullable()
4770
+ });
4771
+ var ListStateDataSchema = exports_external.object({
4772
+ active: exports_external.string(),
4773
+ fallback_order: exports_external.array(exports_external.string()),
4774
+ accounts: exports_external.array(AccountStateSchema),
4775
+ agents: exports_external.array(AgentStateSchema),
4776
+ consumers: exports_external.array(ConsumerStateSchema),
4777
+ active_overage_serving: exports_external.boolean().optional()
4778
+ });
4779
+ var SetActiveDataSchema = exports_external.object({
4780
+ active: exports_external.string(),
4781
+ fanned: exports_external.array(exports_external.string())
4782
+ });
4783
+ var MarkExhaustedDataSchema = exports_external.object({
4784
+ account: exports_external.string(),
4785
+ rolled: exports_external.array(exports_external.string()),
4786
+ rolledTo: exports_external.string().nullable().optional()
4787
+ });
4788
+ var RefreshAccountDataSchema = exports_external.object({
4789
+ account: exports_external.string(),
4790
+ expiresAt: exports_external.number().optional()
4791
+ });
4792
+ var AddAccountDataSchema = exports_external.object({
4793
+ label: exports_external.string(),
4794
+ expiresAt: exports_external.number().optional()
4795
+ });
4796
+ var RmAccountDataSchema = exports_external.object({
4797
+ label: exports_external.string()
4798
+ });
4799
+ var SetOverrideDataSchema = exports_external.object({
4800
+ agent: exports_external.string(),
4801
+ account: exports_external.string().nullable()
4802
+ });
4803
+ var ClaimNotificationDataSchema = exports_external.object({
4804
+ granted: exports_external.boolean()
4805
+ });
4806
+ var GoogleAccountStateSchema = exports_external.object({
4807
+ account: exports_external.string(),
4808
+ expiresAt: exports_external.number(),
4809
+ scope: exports_external.string(),
4810
+ clientId: exports_external.string()
4811
+ });
4812
+ var ListGoogleAccountsDataSchema = exports_external.object({
4813
+ accounts: exports_external.array(GoogleAccountStateSchema)
4814
+ });
4815
+ var MicrosoftAccountStateSchema = exports_external.object({
4816
+ account: exports_external.string(),
4817
+ expiresAt: exports_external.number(),
4818
+ scope: exports_external.string(),
4819
+ clientId: exports_external.string(),
4820
+ accountType: exports_external.enum(["personal", "work"])
4821
+ });
4822
+ var ListMicrosoftAccountsDataSchema = exports_external.object({
4823
+ accounts: exports_external.array(MicrosoftAccountStateSchema)
4824
+ });
4825
+ var ErrorBodySchema = exports_external.object({
4826
+ code: exports_external.enum([
4827
+ "FORBIDDEN",
4828
+ "INVALID_ARGS",
4829
+ "UNKNOWN_VERB",
4830
+ "VERSION_MISMATCH",
4831
+ "ACCOUNT_NOT_FOUND",
4832
+ "ACCOUNT_ALREADY_EXISTS",
4833
+ "CONFIG_INVALID",
4834
+ "DRIFT_DETECTED",
4835
+ "REFRESH_FAILED",
4836
+ "INTERNAL"
4837
+ ]),
4838
+ message: exports_external.string()
4839
+ });
4840
+ var SuccessResponseSchema = exports_external.object({
4841
+ v: exports_external.literal(PROTOCOL_VERSION),
4842
+ id: exports_external.string(),
4843
+ ok: exports_external.literal(true),
4844
+ data: exports_external.unknown()
4845
+ });
4846
+ var ErrorResponseSchema = exports_external.object({
4847
+ v: exports_external.literal(PROTOCOL_VERSION),
4848
+ id: exports_external.string(),
4849
+ ok: exports_external.literal(false),
4850
+ error: ErrorBodySchema
4851
+ });
4852
+ var ResponseSchema = exports_external.discriminatedUnion("ok", [
4853
+ SuccessResponseSchema,
4854
+ ErrorResponseSchema
4855
+ ]);
4856
+ function encodeRequest(req) {
4857
+ const line = JSON.stringify(RequestSchema.parse(req)) + `
4858
+ `;
4859
+ if (Buffer.byteLength(line, "utf-8") > MAX_FRAME_BYTES) {
4860
+ throw new Error(`auth-broker request exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES})`);
4861
+ }
4862
+ return line;
4863
+ }
4864
+ function decodeResponse(line) {
4865
+ const trimmed = line.endsWith(`
4866
+ `) ? line.slice(0, -1) : line;
4867
+ let parsed;
4868
+ try {
4869
+ parsed = JSON.parse(trimmed);
4870
+ } catch {
4871
+ throw new Error("auth-broker response is not valid JSON");
4872
+ }
4873
+ return ResponseSchema.parse(parsed);
4874
+ }
4875
+
4876
+ // src/auth/broker/client.ts
4877
+ var DEFAULT_TIMEOUT_MS = 5000;
4878
+ function reviveDate(v) {
4879
+ if (v == null)
4880
+ return null;
4881
+ if (v instanceof Date)
4882
+ return Number.isNaN(v.getTime()) ? null : v;
4883
+ const d = new Date(v);
4884
+ return Number.isNaN(d.getTime()) ? null : d;
4885
+ }
4886
+ function operatorSocketPath(home = homedir()) {
4887
+ return join2(home, ".switchroom", "state", "auth-broker-operator", "sock");
4888
+ }
4889
+ function resolveAuthBrokerSocketPath(opts) {
4890
+ if (opts?.socket)
4891
+ return opts.socket;
4892
+ const env = process.env.SWITCHROOM_AUTH_BROKER_SOCKET;
4893
+ if (env && env.length > 0)
4894
+ return env;
4895
+ return operatorSocketPath(opts?.home);
4896
+ }
4897
+
4898
+ class AuthBrokerError extends Error {
4899
+ code;
4900
+ constructor(code, message) {
4901
+ super(message);
4902
+ this.code = code;
4903
+ this.name = "AuthBrokerError";
4904
+ }
4905
+ }
4906
+
4907
+ class AuthBrokerUnreachableError extends Error {
4908
+ reason;
4909
+ socketPath;
4910
+ constructor(reason, socketPath) {
4911
+ super(`auth-broker unreachable at ${socketPath}: ${reason}. ` + `The broker may be down; existing credentials remain valid until expiry.`);
4912
+ this.reason = reason;
4913
+ this.socketPath = socketPath;
4914
+ this.name = "AuthBrokerUnreachableError";
4915
+ }
4916
+ }
4917
+
4918
+ class AuthBrokerClient {
4919
+ socketPath;
4920
+ timeoutMs;
4921
+ socket = null;
4922
+ connecting = null;
4923
+ buffer = "";
4924
+ pending = new Map;
4925
+ closed = false;
4926
+ constructor(opts = {}) {
4927
+ this.socketPath = resolveAuthBrokerSocketPath(opts);
4928
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
4929
+ }
4930
+ getSocketPath() {
4931
+ return this.socketPath;
4932
+ }
4933
+ async close() {
4934
+ this.closed = true;
4935
+ const sock = this.socket;
4936
+ this.socket = null;
4937
+ this.connecting = null;
4938
+ for (const [, p] of this.pending) {
4939
+ clearTimeout(p.timer);
4940
+ p.reject(new Error("auth-broker client closed"));
4941
+ }
4942
+ this.pending.clear();
4943
+ if (sock) {
4944
+ sock.destroy();
4945
+ }
4946
+ }
4947
+ async getCredentials(provider) {
4948
+ const base = {
4949
+ v: PROTOCOL_VERSION,
4950
+ id: randomUUID(),
4951
+ op: "get-credentials"
4952
+ };
4953
+ const req = provider !== undefined ? { ...base, provider } : base;
4954
+ const data = await this.send(req);
4955
+ return data;
4956
+ }
4957
+ async listState() {
4958
+ const data = await this.send({
4959
+ v: PROTOCOL_VERSION,
4960
+ id: randomUUID(),
4961
+ op: "list-state"
4962
+ });
4963
+ return data;
4964
+ }
4965
+ async listGoogleAccounts() {
4966
+ const data = await this.send({
4967
+ v: PROTOCOL_VERSION,
4968
+ id: randomUUID(),
4969
+ op: "list-google-accounts"
4970
+ });
4971
+ return data;
4972
+ }
4973
+ async listMicrosoftAccounts() {
4974
+ const data = await this.send({
4975
+ v: PROTOCOL_VERSION,
4976
+ id: randomUUID(),
4977
+ op: "list-microsoft-accounts"
4978
+ });
4979
+ return data;
4980
+ }
4981
+ async probeQuota(accounts, timeoutMs, forceLive) {
4982
+ const data = await this.send({
4983
+ v: PROTOCOL_VERSION,
4984
+ id: randomUUID(),
4985
+ op: "probe-quota",
4986
+ accounts: [...accounts],
4987
+ ...timeoutMs !== undefined ? { timeoutMs } : {},
4988
+ ...forceLive ? { forceLive: true } : {}
4989
+ });
4990
+ const parsed = data;
4991
+ for (const entry of parsed.results) {
4992
+ if (entry.result.ok) {
4993
+ entry.result.data.fiveHourResetAt = reviveDate(entry.result.data.fiveHourResetAt);
4994
+ entry.result.data.sevenDayResetAt = reviveDate(entry.result.data.sevenDayResetAt);
4995
+ }
4996
+ }
4997
+ return parsed;
4998
+ }
4999
+ async setActive(account) {
5000
+ const data = await this.send({
5001
+ v: PROTOCOL_VERSION,
5002
+ id: randomUUID(),
5003
+ op: "set-active",
5004
+ account
5005
+ });
5006
+ return data;
5007
+ }
5008
+ async markExhausted(until) {
5009
+ const req = until !== undefined ? { v: PROTOCOL_VERSION, id: randomUUID(), op: "mark-exhausted", until } : { v: PROTOCOL_VERSION, id: randomUUID(), op: "mark-exhausted" };
5010
+ const data = await this.send(req);
5011
+ return data;
5012
+ }
5013
+ async claimNotification(key, windowMs) {
5014
+ const data = await this.send({
5015
+ v: PROTOCOL_VERSION,
5016
+ id: randomUUID(),
5017
+ op: "claim-notification",
5018
+ key,
5019
+ windowMs
5020
+ });
5021
+ return data;
5022
+ }
5023
+ async refreshAccount(account) {
5024
+ const data = await this.send({
5025
+ v: PROTOCOL_VERSION,
5026
+ id: randomUUID(),
5027
+ op: "refresh-account",
5028
+ account
5029
+ });
5030
+ return data;
5031
+ }
5032
+ async addAccount(label, credentials, replace, provider) {
5033
+ const base = {
5034
+ v: PROTOCOL_VERSION,
5035
+ id: randomUUID(),
5036
+ op: "add-account",
5037
+ label,
5038
+ credentials
5039
+ };
5040
+ const withReplace = replace ? { ...base, replace: true } : base;
5041
+ const req = provider !== undefined ? { ...withReplace, provider } : withReplace;
5042
+ const data = await this.send(req);
5043
+ return data;
5044
+ }
5045
+ async rmAccount(label, provider) {
5046
+ const base = {
5047
+ v: PROTOCOL_VERSION,
5048
+ id: randomUUID(),
5049
+ op: "rm-account",
5050
+ label
5051
+ };
5052
+ const req = provider !== undefined ? { ...base, provider } : base;
5053
+ const data = await this.send(req);
5054
+ return data;
5055
+ }
5056
+ async setOverride(agent, account) {
5057
+ const data = await this.send({
5058
+ v: PROTOCOL_VERSION,
5059
+ id: randomUUID(),
5060
+ op: "set-override",
5061
+ agent,
5062
+ account
5063
+ });
5064
+ return data;
5065
+ }
5066
+ async ensureConnected() {
5067
+ if (this.closed) {
5068
+ throw new Error("auth-broker client is closed");
5069
+ }
5070
+ if (this.socket && !this.socket.destroyed)
5071
+ return this.socket;
5072
+ if (this.connecting)
5073
+ return this.connecting;
5074
+ this.connecting = new Promise((resolve, reject) => {
5075
+ const sock = new net.Socket;
5076
+ const onError = (err) => {
5077
+ sock.removeAllListeners();
5078
+ sock.destroy();
5079
+ const code = err.code ?? "ERR";
5080
+ let reason;
5081
+ if (code === "ENOENT")
5082
+ reason = "socket file not found";
5083
+ else if (code === "ECONNREFUSED")
5084
+ reason = "connection refused";
5085
+ else if (code === "EACCES")
5086
+ reason = "access denied";
5087
+ else
5088
+ reason = err.message;
5089
+ reject(new AuthBrokerUnreachableError(reason, this.socketPath));
5090
+ };
5091
+ sock.once("error", onError);
5092
+ sock.once("connect", () => {
5093
+ sock.removeListener("error", onError);
5094
+ sock.on("data", (chunk) => this.onData(chunk));
5095
+ sock.on("error", (err) => this.onSocketError(err));
5096
+ sock.on("close", () => this.onSocketClose());
5097
+ this.socket = sock;
5098
+ resolve(sock);
5099
+ });
5100
+ sock.connect({ path: this.socketPath });
5101
+ });
5102
+ try {
5103
+ return await this.connecting;
5104
+ } finally {
5105
+ this.connecting = null;
5106
+ }
5107
+ }
5108
+ onData(chunk) {
5109
+ this.buffer += chunk.toString("utf8");
5110
+ let idx;
5111
+ while ((idx = this.buffer.indexOf(`
5112
+ `)) !== -1) {
5113
+ const line = this.buffer.slice(0, idx);
5114
+ this.buffer = this.buffer.slice(idx + 1);
5115
+ if (line.length === 0)
5116
+ continue;
5117
+ let resp;
5118
+ try {
5119
+ resp = decodeResponse(line);
5120
+ } catch (err) {
5121
+ const msg = `unparseable auth-broker response: ${err instanceof Error ? err.message : String(err)}`;
5122
+ this.failAll(new AuthBrokerUnreachableError(msg, this.socketPath));
5123
+ return;
5124
+ }
5125
+ const p = this.pending.get(resp.id);
5126
+ if (!p) {
5127
+ continue;
5128
+ }
5129
+ this.pending.delete(resp.id);
5130
+ clearTimeout(p.timer);
5131
+ p.resolve(resp);
5132
+ }
5133
+ }
5134
+ onSocketError(err) {
5135
+ this.failAll(new AuthBrokerUnreachableError(err.message, this.socketPath));
5136
+ if (this.socket) {
5137
+ this.socket.destroy();
5138
+ this.socket = null;
5139
+ }
5140
+ }
5141
+ onSocketClose() {
5142
+ if (this.pending.size > 0) {
5143
+ this.failAll(new AuthBrokerUnreachableError("connection closed mid-request", this.socketPath));
5144
+ }
5145
+ this.socket = null;
5146
+ }
5147
+ failAll(err) {
5148
+ for (const [, p] of this.pending) {
5149
+ clearTimeout(p.timer);
5150
+ p.reject(err);
5151
+ }
5152
+ this.pending.clear();
5153
+ }
5154
+ async send(req) {
5155
+ const sock = await this.ensureConnected();
5156
+ const id = req.id;
5157
+ const frame = encodeRequest(req);
5158
+ return new Promise((resolve, reject) => {
5159
+ const timer = setTimeout(() => {
5160
+ this.pending.delete(id);
5161
+ reject(new AuthBrokerUnreachableError(`request ${req.op} timed out after ${this.timeoutMs}ms`, this.socketPath));
5162
+ }, this.timeoutMs);
5163
+ this.pending.set(id, {
5164
+ resolve: (resp) => {
5165
+ if (resp.ok) {
5166
+ resolve(resp.data);
5167
+ } else {
5168
+ reject(new AuthBrokerError(resp.error.code, resp.error.message));
5169
+ }
5170
+ },
5171
+ reject,
5172
+ timer
5173
+ });
5174
+ sock.write(frame, (err) => {
5175
+ if (err) {
5176
+ const p = this.pending.get(id);
5177
+ if (p) {
5178
+ clearTimeout(p.timer);
5179
+ this.pending.delete(id);
5180
+ }
5181
+ reject(new AuthBrokerUnreachableError(`failed to send ${req.op}: ${err.message}`, this.socketPath));
5182
+ }
5183
+ });
5184
+ });
5185
+ }
5186
+ }
5187
+ async function withAuthBrokerClient(fn, opts) {
5188
+ const client = new AuthBrokerClient(opts);
5189
+ try {
5190
+ return await fn(client);
5191
+ } finally {
5192
+ await client.close();
5193
+ }
5194
+ }
5195
+
5196
+ // src/agents/overage-decision.ts
5197
+ async function queryActiveOverageServing(opts) {
5198
+ try {
5199
+ return await withAuthBrokerClient(async (client) => {
5200
+ const state = await client.listState();
5201
+ return state.active_overage_serving === true;
5202
+ }, opts);
5203
+ } catch (err) {
5204
+ console.error(`[overage-decision] broker overage query failed: ${err.message} \u2014 defaulting to no-overage (Esc-park)`);
5205
+ return false;
5206
+ }
5207
+ }
5208
+
5209
+ // src/cli/autoaccept-poll.ts
5210
+ function requestWedgeRestart(agentName, reason) {
5211
+ const socket = `switchroom-${agentName}`;
5212
+ console.error(`[autoaccept-poll] ${agentName}: manifest-stall recovery \u2014 ${reason}; ` + `sending tmux interrupt (C-c). If this recurs, a hard ` + `'switchroom agent restart ${agentName}' is warranted.`);
5213
+ try {
5214
+ execFileSync3("tmux", ["-L", socket, "send-keys", "-t", agentName, "C-c"], {
5215
+ timeout: 3000,
5216
+ stdio: ["ignore", "pipe", "pipe"]
5217
+ });
5218
+ } catch (err) {
5219
+ console.error(`[autoaccept-poll] ${agentName}: wedge interrupt send-keys failed: ${err.message}`);
5220
+ }
5221
+ }
418
5222
  async function main() {
419
5223
  const agentName = process.argv[2];
420
5224
  if (!agentName) {
@@ -432,16 +5236,19 @@ async function main() {
432
5236
  process.exit(0);
433
5237
  }
434
5238
  const rateLimitDetect = process.env.SWITCHROOM_RATE_LIMIT_DETECT !== "0";
5239
+ const overageSelect = rateLimitDetect && process.env.SWITCHROOM_RATE_LIMIT_OVERAGE !== "0";
435
5240
  try {
436
- console.error(`[autoaccept-poll] ${agentName}: entering wedge-watchdog (continuous)` + (rateLimitDetect ? " +rate-limit-detect" : " (rate-limit-detect OFF)"));
5241
+ console.error(`[autoaccept-poll] ${agentName}: entering wedge-watchdog (continuous)` + (rateLimitDetect ? " +rate-limit-detect" : " (rate-limit-detect OFF)") + (overageSelect ? " +overage-carveout" : ""));
437
5242
  const res = await runWedgeWatchdog({
438
5243
  agentName,
439
5244
  rateLimitSignature: rateLimitDetect ? undefined : null,
440
5245
  onRateLimitMenu: rateLimitDetect ? (name, resetAt) => {
441
5246
  signalQuotaWall(name, resetAt);
442
- } : undefined
5247
+ } : undefined,
5248
+ overageDecision: overageSelect ? () => queryActiveOverageServing() : undefined,
5249
+ requestRestart: requestWedgeRestart
443
5250
  });
444
- console.error(`[autoaccept-poll] ${agentName}: wedge-watchdog returned reason=${res.reason} fires=${res.fires} rateLimitFires=${res.rateLimitFires}`);
5251
+ console.error(`[autoaccept-poll] ${agentName}: wedge-watchdog returned reason=${res.reason} fires=${res.fires} rateLimitFires=${res.rateLimitFires} overageCreditSelections=${res.overageCreditSelections} confirmModalFires=${res.confirmModalFires} permissionPromptFires=${res.permissionPromptFires} restartEscalations=${res.restartEscalations}`);
445
5252
  } catch (err) {
446
5253
  console.error(`[autoaccept-poll] ${agentName}: wedge-watchdog unexpected throw: ${err.message}`);
447
5254
  }