@alfe.ai/gateway 0.0.3 → 0.0.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 (2) hide show
  1. package/dist/health.js +3096 -182
  2. package/package.json +2 -2
package/dist/health.js CHANGED
@@ -5,10 +5,9 @@ import { homedir } from "node:os";
5
5
  import pino from "pino";
6
6
  import { chmodSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
7
7
  import { getEndpointFromToken, readConfig } from "@alfe.ai/config";
8
- import { AlfeApiClient, AuthService } from "@alfe/api-client";
8
+ import crypto from "crypto";
9
9
  import { parse } from "smol-toml";
10
10
  import WebSocket from "ws";
11
- import crypto from "crypto";
12
11
  import { createConnection, createServer } from "node:net";
13
12
  import { execSync, spawn } from "node:child_process";
14
13
  import { IntegrationManager, IntegrationManagerAdapter, OpenClawApplier } from "@alfe.ai/integrations";
@@ -92,186 +91,6 @@ function createLogger$1() {
92
91
  }
93
92
  const logger$1 = createLogger$1();
94
93
  //#endregion
95
- //#region src/config.ts
96
- /**
97
- * Daemon configuration — reads ~/.alfe/config.toml and resolves agent identity.
98
- *
99
- * Bootstrap flow:
100
- * 1. Read api_key from ~/.alfe/config.toml (via @alfe.ai/config)
101
- * 2. Derive API endpoint from token prefix
102
- * 3. Call /auth/validate to get tenantId (orgId)
103
- * 4. Use tokenId as agent identity for cloud registration
104
- */
105
- const ALFE_DIR = join(homedir(), ".alfe");
106
- const SOCKET_PATH = join(ALFE_DIR, "gateway.sock");
107
- const PID_PATH = join(ALFE_DIR, "gateway.pid");
108
- /**
109
- * Resolve agent identity by validating the api_key with the auth service.
110
- * Returns agentId (derived from tokenId) and orgId (tenantId).
111
- */
112
- async function resolveAgentIdentity(apiKey, apiEndpoint) {
113
- const auth = new AuthService(new AlfeApiClient({
114
- apiBaseUrl: apiEndpoint,
115
- getToken: () => Promise.resolve(apiKey)
116
- }));
117
- const maxAttempts = 3;
118
- const delayMs = 3e3;
119
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
120
- const result = await auth.validate(apiKey);
121
- if (!result.ok) {
122
- if (result.status === 401 || result.status === 403) throw new Error(`Token validation failed: ${result.error}. Is your API key valid? Run \`alfe login\` to reconfigure.`);
123
- if (attempt < maxAttempts) {
124
- await new Promise((r) => setTimeout(r, delayMs));
125
- continue;
126
- }
127
- throw new Error(`Token validation failed after ${String(maxAttempts)} attempts: ${result.error}. Is your API key valid? Run \`alfe login\` to reconfigure.`);
128
- }
129
- if (!result.data.valid) throw new Error("API key invalid: validation failed. Run `alfe login` to reconfigure.");
130
- const orgId = result.data.tenantId;
131
- if (!orgId) throw new Error("Token validation returned no tenantId — cannot determine org.");
132
- return {
133
- agentId: result.data.tokenId ?? deriveAgentId(apiKey),
134
- orgId,
135
- runtime: result.data.runtime ?? "openclaw"
136
- };
137
- }
138
- throw new Error("Token validation failed: exhausted retries.");
139
- }
140
- /**
141
- * Derive a stable agent ID from an API key (fallback when tokenId not available).
142
- */
143
- function deriveAgentId(apiKey) {
144
- let hash = 0;
145
- for (let i = 0; i < apiKey.length; i++) {
146
- const chr = apiKey.charCodeAt(i);
147
- hash = (hash << 5) - hash + chr | 0;
148
- }
149
- return `agent-${Math.abs(hash).toString(36)}`;
150
- }
151
- /**
152
- * Derive the cloud gateway WebSocket URL from the API endpoint.
153
- * The cloud gateway runs on Fly.io — its URL follows a convention.
154
- */
155
- function deriveGatewayWsUrl(apiEndpoint) {
156
- if (apiEndpoint.includes("dev.alfe.ai")) return process.env.ALFE_GATEWAY_WS_URL ?? "wss://gateway.dev.alfe.ai/ws";
157
- if (apiEndpoint.includes("test.alfe.ai")) return process.env.ALFE_GATEWAY_WS_URL ?? "wss://gateway.test.alfe.ai/ws";
158
- return process.env.ALFE_GATEWAY_WS_URL ?? "wss://gateway.alfe.ai/ws";
159
- }
160
- /**
161
- * Parse [runtimes.*] sections from config.toml.
162
- * Returns a map of runtime name → RuntimeConfig.
163
- *
164
- * Example config.toml:
165
- * [runtimes.openclaw]
166
- * workspace = "~/.openclaw"
167
- */
168
- async function loadRuntimeConfigs() {
169
- const configPath = join(ALFE_DIR, "config.toml");
170
- if (!existsSync(configPath)) return {};
171
- try {
172
- const runtimes = parse(await readFile(configPath, "utf-8")).runtimes;
173
- if (!runtimes) return {};
174
- const result = {};
175
- for (const [name, cfg] of Object.entries(runtimes)) if (typeof cfg.workspace === "string") result[name] = { workspace: cfg.workspace.startsWith("~/") ? join(homedir(), cfg.workspace.slice(2)) : cfg.workspace };
176
- return result;
177
- } catch {
178
- return {};
179
- }
180
- }
181
- /**
182
- * Whether the daemon is running in managed mode (ECS Fargate container).
183
- * In managed mode, configuration comes from environment variables instead
184
- * of ~/.alfe/config.toml, and IPC/PID features are disabled.
185
- */
186
- function isManagedMode() {
187
- return process.env.ALFE_MANAGED === "true";
188
- }
189
- /**
190
- * Load configuration for managed mode (ECS Fargate).
191
- * All config comes from environment variables — no local files needed.
192
- */
193
- async function loadManagedConfig() {
194
- const apiKey = process.env.ALFE_API_KEY;
195
- const apiEndpoint = process.env.ALFE_API_ENDPOINT;
196
- if (!apiKey || !apiEndpoint) throw new Error("ALFE_API_KEY and ALFE_API_ENDPOINT required in managed mode");
197
- const identity = await resolveAgentIdentity(apiKey, apiEndpoint);
198
- return {
199
- apiKey,
200
- apiEndpoint,
201
- gatewayWsUrl: process.env.ALFE_GATEWAY_WS_URL ?? deriveGatewayWsUrl(apiEndpoint),
202
- socketPath: "",
203
- pidPath: "",
204
- agentId: identity.agentId,
205
- orgId: identity.orgId,
206
- runtime: identity.runtime,
207
- runtimes: identity.runtime === "openclaw" ? { openclaw: { workspace: join(homedir(), ".openclaw") } } : {}
208
- };
209
- }
210
- /**
211
- * Load full daemon configuration.
212
- * Reads config.toml, validates the API key, resolves agent identity,
213
- * and parses runtime configurations.
214
- *
215
- * In managed mode, loads from environment variables instead.
216
- */
217
- async function loadDaemonConfig() {
218
- if (isManagedMode()) return loadManagedConfig();
219
- let alfeConfig;
220
- try {
221
- alfeConfig = await readConfig();
222
- } catch {
223
- throw new Error("Alfe not configured. Run `alfe login` first.");
224
- }
225
- const apiEndpoint = alfeConfig.gateway ?? getEndpointFromToken(alfeConfig.api_key);
226
- const identity = await resolveAgentIdentity(alfeConfig.api_key, apiEndpoint);
227
- const gatewayWsUrl = alfeConfig.gateway_url ?? deriveGatewayWsUrl(apiEndpoint);
228
- const runtimes = await loadRuntimeConfigs();
229
- return {
230
- apiKey: alfeConfig.api_key,
231
- apiEndpoint,
232
- gatewayWsUrl,
233
- socketPath: process.env.ALFE_GATEWAY_SOCKET ?? SOCKET_PATH,
234
- pidPath: PID_PATH,
235
- agentId: identity.agentId,
236
- orgId: identity.orgId,
237
- runtime: identity.runtime,
238
- runtimes
239
- };
240
- }
241
- /**
242
- * Fetch agent workspace config from the API.
243
- *
244
- * 1. GET /agents/me/workspace → { templateKey }
245
- * 2. If templateKey set, GET /templates/:key/files → persona file contents
246
- *
247
- * Returns null if the agent has no template assigned or the fetch fails.
248
- */
249
- async function fetchAgentConfig(apiKey, apiEndpoint) {
250
- try {
251
- const wsResponse = await fetch(`${apiEndpoint}/agents/me/workspace`, {
252
- method: "GET",
253
- headers: { "Authorization": `Bearer ${apiKey}` }
254
- });
255
- if (!wsResponse.ok) return null;
256
- const templateKey = (await wsResponse.json()).data?.templateKey;
257
- if (!templateKey) return null;
258
- const filesResponse = await fetch(`${apiEndpoint}/templates/${encodeURIComponent(templateKey)}/files`, {
259
- method: "GET",
260
- headers: { "Authorization": `Bearer ${apiKey}` }
261
- });
262
- if (!filesResponse.ok) return {
263
- templateKey,
264
- files: {}
265
- };
266
- return {
267
- templateKey,
268
- files: (await filesResponse.json()).data?.files ?? {}
269
- };
270
- } catch {
271
- return null;
272
- }
273
- }
274
- //#endregion
275
94
  //#region ../../packages-internal/ids/dist/prefixes.js
276
95
  const ID_PREFIXES = {
277
96
  agent: "agt",
@@ -423,10 +242,3105 @@ var import_index_umd = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
423
242
  function createId(prefix) {
424
243
  return `${prefix}_${(0, import_index_umd.ulid)()}`;
425
244
  }
245
+ function correlationId() {
246
+ return createId(ID_PREFIXES.correlation);
247
+ }
426
248
  function pluginConnectionId() {
427
249
  return createId(ID_PREFIXES.pluginConnection);
428
250
  }
429
251
  //#endregion
252
+ //#region ../../packages-internal/api-client/dist/client.js
253
+ /**
254
+ * @alfe/api-client — Typed HTTP client for Alfe services.
255
+ *
256
+ * Platform-agnostic: works in React Native and browser environments.
257
+ * Uses standard fetch() API — no Node.js dependencies.
258
+ */
259
+ var AlfeApiClient = class {
260
+ apiBaseUrl;
261
+ getToken;
262
+ onAuthFailure;
263
+ constructor(options) {
264
+ this.apiBaseUrl = options.apiBaseUrl;
265
+ this.getToken = options.getToken;
266
+ this.onAuthFailure = options.onAuthFailure;
267
+ }
268
+ /** Shared fetch logic — handles auth, 401, and network errors. */
269
+ async _fetch(path, options) {
270
+ try {
271
+ const token = await this.getToken();
272
+ if (!token) {
273
+ this.onAuthFailure?.();
274
+ return {
275
+ ok: false,
276
+ result: {
277
+ ok: false,
278
+ error: "No auth token available",
279
+ status: 401
280
+ }
281
+ };
282
+ }
283
+ const url = `${this.apiBaseUrl}${path}`;
284
+ const headers = new Headers(options?.headers);
285
+ headers.set("Authorization", `Bearer ${token}`);
286
+ headers.set("Content-Type", "application/json");
287
+ headers.set("x-correlation-id", correlationId());
288
+ const res = await fetch(url, {
289
+ ...options,
290
+ headers
291
+ });
292
+ if (res.status === 401) {
293
+ this.onAuthFailure?.();
294
+ return {
295
+ ok: false,
296
+ result: {
297
+ ok: false,
298
+ error: "Session expired",
299
+ status: 401
300
+ }
301
+ };
302
+ }
303
+ const body = await res.json();
304
+ if (!res.ok) return {
305
+ ok: false,
306
+ result: {
307
+ ok: false,
308
+ error: body.message || `API error: ${String(res.status)}`,
309
+ status: res.status
310
+ }
311
+ };
312
+ return {
313
+ ok: true,
314
+ res,
315
+ body
316
+ };
317
+ } catch (err) {
318
+ return {
319
+ ok: false,
320
+ result: {
321
+ ok: false,
322
+ error: err instanceof Error ? err.message : "Network error"
323
+ }
324
+ };
325
+ }
326
+ }
327
+ /**
328
+ * Make an authenticated request to an Alfe API endpoint.
329
+ * Unwraps the @auriclabs/api-core `{ data, timestamp, requestId }` envelope.
330
+ */
331
+ async request(path, options) {
332
+ const result = await this._fetch(path, options);
333
+ if (!result.ok) return result.result;
334
+ return {
335
+ ok: true,
336
+ data: result.body.data
337
+ };
338
+ }
339
+ /**
340
+ * Make an authenticated request that returns the body directly (no envelope unwrap).
341
+ * Use for APIs that don't use the @auriclabs/api-core response format (e.g. gateway).
342
+ */
343
+ async rawRequest(path, options) {
344
+ const result = await this._fetch(path, options);
345
+ if (!result.ok) return result.result;
346
+ return {
347
+ ok: true,
348
+ data: result.body
349
+ };
350
+ }
351
+ getApiBaseUrl() {
352
+ return this.apiBaseUrl;
353
+ }
354
+ };
355
+ //#endregion
356
+ //#region ../../packages-internal/api-client/dist/services/auth.js
357
+ var AuthService = class {
358
+ client;
359
+ constructor(client) {
360
+ this.client = client;
361
+ }
362
+ prefix = "/auth";
363
+ validate(token) {
364
+ return this.client.request(`${this.prefix}/validate`, {
365
+ method: "POST",
366
+ body: JSON.stringify({ token })
367
+ });
368
+ }
369
+ listTokens() {
370
+ return this.client.request(`${this.prefix}/tokens`);
371
+ }
372
+ createToken(data) {
373
+ return this.client.request(`${this.prefix}/tokens`, {
374
+ method: "POST",
375
+ body: JSON.stringify(data)
376
+ });
377
+ }
378
+ deleteToken(tokenId) {
379
+ return this.client.request(`${this.prefix}/tokens/${tokenId}`, { method: "DELETE" });
380
+ }
381
+ };
382
+ //#endregion
383
+ //#region ../../packages-internal/types/dist/lib/enum-values.js
384
+ /**
385
+ * Converts a const enum object into a non-empty readonly tuple.
386
+ *
387
+ * Satisfies both `z.enum()` and ElectroDB `type` field requirements
388
+ * (both need `readonly [string, ...string[]]`).
389
+ */
390
+ function enumValues(obj) {
391
+ return Object.values(obj);
392
+ }
393
+ Object.freeze({ status: "aborted" });
394
+ function $constructor(name, initializer, params) {
395
+ function init(inst, def) {
396
+ if (!inst._zod) Object.defineProperty(inst, "_zod", {
397
+ value: {
398
+ def,
399
+ constr: _,
400
+ traits: /* @__PURE__ */ new Set()
401
+ },
402
+ enumerable: false
403
+ });
404
+ if (inst._zod.traits.has(name)) return;
405
+ inst._zod.traits.add(name);
406
+ initializer(inst, def);
407
+ const proto = _.prototype;
408
+ const keys = Object.keys(proto);
409
+ for (let i = 0; i < keys.length; i++) {
410
+ const k = keys[i];
411
+ if (!(k in inst)) inst[k] = proto[k].bind(inst);
412
+ }
413
+ }
414
+ const Parent = params?.Parent ?? Object;
415
+ class Definition extends Parent {}
416
+ Object.defineProperty(Definition, "name", { value: name });
417
+ function _(def) {
418
+ var _a;
419
+ const inst = params?.Parent ? new Definition() : this;
420
+ init(inst, def);
421
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
422
+ for (const fn of inst._zod.deferred) fn();
423
+ return inst;
424
+ }
425
+ Object.defineProperty(_, "init", { value: init });
426
+ Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
427
+ if (params?.Parent && inst instanceof params.Parent) return true;
428
+ return inst?._zod?.traits?.has(name);
429
+ } });
430
+ Object.defineProperty(_, "name", { value: name });
431
+ return _;
432
+ }
433
+ var $ZodAsyncError = class extends Error {
434
+ constructor() {
435
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
436
+ }
437
+ };
438
+ var $ZodEncodeError = class extends Error {
439
+ constructor(name) {
440
+ super(`Encountered unidirectional transform during encode: ${name}`);
441
+ this.name = "ZodEncodeError";
442
+ }
443
+ };
444
+ const globalConfig = {};
445
+ function config$1(newConfig) {
446
+ if (newConfig) Object.assign(globalConfig, newConfig);
447
+ return globalConfig;
448
+ }
449
+ //#endregion
450
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js
451
+ function getEnumValues(entries) {
452
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
453
+ return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
454
+ }
455
+ function jsonStringifyReplacer(_, value) {
456
+ if (typeof value === "bigint") return value.toString();
457
+ return value;
458
+ }
459
+ function cached(getter) {
460
+ return { get value() {
461
+ {
462
+ const value = getter();
463
+ Object.defineProperty(this, "value", { value });
464
+ return value;
465
+ }
466
+ throw new Error("cached value already set");
467
+ } };
468
+ }
469
+ function nullish(input) {
470
+ return input === null || input === void 0;
471
+ }
472
+ function cleanRegex(source) {
473
+ const start = source.startsWith("^") ? 1 : 0;
474
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
475
+ return source.slice(start, end);
476
+ }
477
+ function floatSafeRemainder(val, step) {
478
+ const valDecCount = (val.toString().split(".")[1] || "").length;
479
+ const stepString = step.toString();
480
+ let stepDecCount = (stepString.split(".")[1] || "").length;
481
+ if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
482
+ const match = stepString.match(/\d?e-(\d?)/);
483
+ if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
484
+ }
485
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
486
+ return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
487
+ }
488
+ const EVALUATING = Symbol("evaluating");
489
+ function defineLazy(object, key, getter) {
490
+ let value = void 0;
491
+ Object.defineProperty(object, key, {
492
+ get() {
493
+ if (value === EVALUATING) return;
494
+ if (value === void 0) {
495
+ value = EVALUATING;
496
+ value = getter();
497
+ }
498
+ return value;
499
+ },
500
+ set(v) {
501
+ Object.defineProperty(object, key, { value: v });
502
+ },
503
+ configurable: true
504
+ });
505
+ }
506
+ function assignProp(target, prop, value) {
507
+ Object.defineProperty(target, prop, {
508
+ value,
509
+ writable: true,
510
+ enumerable: true,
511
+ configurable: true
512
+ });
513
+ }
514
+ function mergeDefs(...defs) {
515
+ const mergedDescriptors = {};
516
+ for (const def of defs) Object.assign(mergedDescriptors, Object.getOwnPropertyDescriptors(def));
517
+ return Object.defineProperties({}, mergedDescriptors);
518
+ }
519
+ function esc(str) {
520
+ return JSON.stringify(str);
521
+ }
522
+ const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
523
+ function isObject$1(data) {
524
+ return typeof data === "object" && data !== null && !Array.isArray(data);
525
+ }
526
+ const allowsEval = cached(() => {
527
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
528
+ try {
529
+ new Function("");
530
+ return true;
531
+ } catch (_) {
532
+ return false;
533
+ }
534
+ });
535
+ function isPlainObject$1(o) {
536
+ if (isObject$1(o) === false) return false;
537
+ const ctor = o.constructor;
538
+ if (ctor === void 0) return true;
539
+ if (typeof ctor !== "function") return true;
540
+ const prot = ctor.prototype;
541
+ if (isObject$1(prot) === false) return false;
542
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
543
+ return true;
544
+ }
545
+ function shallowClone(o) {
546
+ if (isPlainObject$1(o)) return { ...o };
547
+ if (Array.isArray(o)) return [...o];
548
+ return o;
549
+ }
550
+ const propertyKeyTypes = new Set([
551
+ "string",
552
+ "number",
553
+ "symbol"
554
+ ]);
555
+ function escapeRegex(str) {
556
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
557
+ }
558
+ function clone(inst, def, params) {
559
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
560
+ if (!def || params?.parent) cl._zod.parent = inst;
561
+ return cl;
562
+ }
563
+ function normalizeParams(_params) {
564
+ const params = _params;
565
+ if (!params) return {};
566
+ if (typeof params === "string") return { error: () => params };
567
+ if (params?.message !== void 0) {
568
+ if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
569
+ params.error = params.message;
570
+ }
571
+ delete params.message;
572
+ if (typeof params.error === "string") return {
573
+ ...params,
574
+ error: () => params.error
575
+ };
576
+ return params;
577
+ }
578
+ function optionalKeys(shape) {
579
+ return Object.keys(shape).filter((k) => {
580
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
581
+ });
582
+ }
583
+ const NUMBER_FORMAT_RANGES = {
584
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
585
+ int32: [-2147483648, 2147483647],
586
+ uint32: [0, 4294967295],
587
+ float32: [-34028234663852886e22, 34028234663852886e22],
588
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
589
+ };
590
+ function pick(schema, mask) {
591
+ const currDef = schema._zod.def;
592
+ const checks = currDef.checks;
593
+ if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
594
+ return clone(schema, mergeDefs(schema._zod.def, {
595
+ get shape() {
596
+ const newShape = {};
597
+ for (const key in mask) {
598
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
599
+ if (!mask[key]) continue;
600
+ newShape[key] = currDef.shape[key];
601
+ }
602
+ assignProp(this, "shape", newShape);
603
+ return newShape;
604
+ },
605
+ checks: []
606
+ }));
607
+ }
608
+ function omit(schema, mask) {
609
+ const currDef = schema._zod.def;
610
+ const checks = currDef.checks;
611
+ if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
612
+ return clone(schema, mergeDefs(schema._zod.def, {
613
+ get shape() {
614
+ const newShape = { ...schema._zod.def.shape };
615
+ for (const key in mask) {
616
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
617
+ if (!mask[key]) continue;
618
+ delete newShape[key];
619
+ }
620
+ assignProp(this, "shape", newShape);
621
+ return newShape;
622
+ },
623
+ checks: []
624
+ }));
625
+ }
626
+ function extend$1(schema, shape) {
627
+ if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
628
+ const checks = schema._zod.def.checks;
629
+ if (checks && checks.length > 0) {
630
+ const existingShape = schema._zod.def.shape;
631
+ for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
632
+ }
633
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
634
+ const _shape = {
635
+ ...schema._zod.def.shape,
636
+ ...shape
637
+ };
638
+ assignProp(this, "shape", _shape);
639
+ return _shape;
640
+ } }));
641
+ }
642
+ function safeExtend(schema, shape) {
643
+ if (!isPlainObject$1(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
644
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
645
+ const _shape = {
646
+ ...schema._zod.def.shape,
647
+ ...shape
648
+ };
649
+ assignProp(this, "shape", _shape);
650
+ return _shape;
651
+ } }));
652
+ }
653
+ function merge$1(a, b) {
654
+ return clone(a, mergeDefs(a._zod.def, {
655
+ get shape() {
656
+ const _shape = {
657
+ ...a._zod.def.shape,
658
+ ...b._zod.def.shape
659
+ };
660
+ assignProp(this, "shape", _shape);
661
+ return _shape;
662
+ },
663
+ get catchall() {
664
+ return b._zod.def.catchall;
665
+ },
666
+ checks: []
667
+ }));
668
+ }
669
+ function partial(Class, schema, mask) {
670
+ const checks = schema._zod.def.checks;
671
+ if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
672
+ return clone(schema, mergeDefs(schema._zod.def, {
673
+ get shape() {
674
+ const oldShape = schema._zod.def.shape;
675
+ const shape = { ...oldShape };
676
+ if (mask) for (const key in mask) {
677
+ if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
678
+ if (!mask[key]) continue;
679
+ shape[key] = Class ? new Class({
680
+ type: "optional",
681
+ innerType: oldShape[key]
682
+ }) : oldShape[key];
683
+ }
684
+ else for (const key in oldShape) shape[key] = Class ? new Class({
685
+ type: "optional",
686
+ innerType: oldShape[key]
687
+ }) : oldShape[key];
688
+ assignProp(this, "shape", shape);
689
+ return shape;
690
+ },
691
+ checks: []
692
+ }));
693
+ }
694
+ function required(Class, schema, mask) {
695
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
696
+ const oldShape = schema._zod.def.shape;
697
+ const shape = { ...oldShape };
698
+ if (mask) for (const key in mask) {
699
+ if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
700
+ if (!mask[key]) continue;
701
+ shape[key] = new Class({
702
+ type: "nonoptional",
703
+ innerType: oldShape[key]
704
+ });
705
+ }
706
+ else for (const key in oldShape) shape[key] = new Class({
707
+ type: "nonoptional",
708
+ innerType: oldShape[key]
709
+ });
710
+ assignProp(this, "shape", shape);
711
+ return shape;
712
+ } }));
713
+ }
714
+ function aborted(x, startIndex = 0) {
715
+ if (x.aborted === true) return true;
716
+ for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
717
+ return false;
718
+ }
719
+ function prefixIssues(path, issues) {
720
+ return issues.map((iss) => {
721
+ var _a;
722
+ (_a = iss).path ?? (_a.path = []);
723
+ iss.path.unshift(path);
724
+ return iss;
725
+ });
726
+ }
727
+ function unwrapMessage(message) {
728
+ return typeof message === "string" ? message : message?.message;
729
+ }
730
+ function finalizeIssue(iss, ctx, config) {
731
+ const full = {
732
+ ...iss,
733
+ path: iss.path ?? []
734
+ };
735
+ if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
736
+ delete full.inst;
737
+ delete full.continue;
738
+ if (!ctx?.reportInput) delete full.input;
739
+ return full;
740
+ }
741
+ function getLengthableOrigin(input) {
742
+ if (Array.isArray(input)) return "array";
743
+ if (typeof input === "string") return "string";
744
+ return "unknown";
745
+ }
746
+ function issue(...args) {
747
+ const [iss, input, inst] = args;
748
+ if (typeof iss === "string") return {
749
+ message: iss,
750
+ code: "custom",
751
+ input,
752
+ inst
753
+ };
754
+ return { ...iss };
755
+ }
756
+ //#endregion
757
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js
758
+ const initializer$1 = (inst, def) => {
759
+ inst.name = "$ZodError";
760
+ Object.defineProperty(inst, "_zod", {
761
+ value: inst._zod,
762
+ enumerable: false
763
+ });
764
+ Object.defineProperty(inst, "issues", {
765
+ value: def,
766
+ enumerable: false
767
+ });
768
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
769
+ Object.defineProperty(inst, "toString", {
770
+ value: () => inst.message,
771
+ enumerable: false
772
+ });
773
+ };
774
+ const $ZodError = $constructor("$ZodError", initializer$1);
775
+ const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
776
+ function flattenError(error, mapper = (issue) => issue.message) {
777
+ const fieldErrors = {};
778
+ const formErrors = [];
779
+ for (const sub of error.issues) if (sub.path.length > 0) {
780
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
781
+ fieldErrors[sub.path[0]].push(mapper(sub));
782
+ } else formErrors.push(mapper(sub));
783
+ return {
784
+ formErrors,
785
+ fieldErrors
786
+ };
787
+ }
788
+ function formatError(error, mapper = (issue) => issue.message) {
789
+ const fieldErrors = { _errors: [] };
790
+ const processError = (error) => {
791
+ for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }));
792
+ else if (issue.code === "invalid_key") processError({ issues: issue.issues });
793
+ else if (issue.code === "invalid_element") processError({ issues: issue.issues });
794
+ else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
795
+ else {
796
+ let curr = fieldErrors;
797
+ let i = 0;
798
+ while (i < issue.path.length) {
799
+ const el = issue.path[i];
800
+ if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
801
+ else {
802
+ curr[el] = curr[el] || { _errors: [] };
803
+ curr[el]._errors.push(mapper(issue));
804
+ }
805
+ curr = curr[el];
806
+ i++;
807
+ }
808
+ }
809
+ };
810
+ processError(error);
811
+ return fieldErrors;
812
+ }
813
+ //#endregion
814
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js
815
+ const _parse = (_Err) => (schema, value, _ctx, _params) => {
816
+ const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
817
+ const result = schema._zod.run({
818
+ value,
819
+ issues: []
820
+ }, ctx);
821
+ if (result instanceof Promise) throw new $ZodAsyncError();
822
+ if (result.issues.length) {
823
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())));
824
+ captureStackTrace(e, _params?.callee);
825
+ throw e;
826
+ }
827
+ return result.value;
828
+ };
829
+ const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
830
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
831
+ let result = schema._zod.run({
832
+ value,
833
+ issues: []
834
+ }, ctx);
835
+ if (result instanceof Promise) result = await result;
836
+ if (result.issues.length) {
837
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())));
838
+ captureStackTrace(e, params?.callee);
839
+ throw e;
840
+ }
841
+ return result.value;
842
+ };
843
+ const _safeParse = (_Err) => (schema, value, _ctx) => {
844
+ const ctx = _ctx ? {
845
+ ..._ctx,
846
+ async: false
847
+ } : { async: false };
848
+ const result = schema._zod.run({
849
+ value,
850
+ issues: []
851
+ }, ctx);
852
+ if (result instanceof Promise) throw new $ZodAsyncError();
853
+ return result.issues.length ? {
854
+ success: false,
855
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())))
856
+ } : {
857
+ success: true,
858
+ data: result.value
859
+ };
860
+ };
861
+ const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
862
+ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
863
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
864
+ let result = schema._zod.run({
865
+ value,
866
+ issues: []
867
+ }, ctx);
868
+ if (result instanceof Promise) result = await result;
869
+ return result.issues.length ? {
870
+ success: false,
871
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())))
872
+ } : {
873
+ success: true,
874
+ data: result.value
875
+ };
876
+ };
877
+ const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
878
+ const _encode = (_Err) => (schema, value, _ctx) => {
879
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
880
+ return _parse(_Err)(schema, value, ctx);
881
+ };
882
+ const _decode = (_Err) => (schema, value, _ctx) => {
883
+ return _parse(_Err)(schema, value, _ctx);
884
+ };
885
+ const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
886
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
887
+ return _parseAsync(_Err)(schema, value, ctx);
888
+ };
889
+ const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
890
+ return _parseAsync(_Err)(schema, value, _ctx);
891
+ };
892
+ const _safeEncode = (_Err) => (schema, value, _ctx) => {
893
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
894
+ return _safeParse(_Err)(schema, value, ctx);
895
+ };
896
+ const _safeDecode = (_Err) => (schema, value, _ctx) => {
897
+ return _safeParse(_Err)(schema, value, _ctx);
898
+ };
899
+ const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
900
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
901
+ return _safeParseAsync(_Err)(schema, value, ctx);
902
+ };
903
+ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
904
+ return _safeParseAsync(_Err)(schema, value, _ctx);
905
+ };
906
+ const integer = /^-?\d+$/;
907
+ const number$1 = /^-?\d+(?:\.\d+)?$/;
908
+ //#endregion
909
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js
910
+ const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
911
+ var _a;
912
+ inst._zod ?? (inst._zod = {});
913
+ inst._zod.def = def;
914
+ (_a = inst._zod).onattach ?? (_a.onattach = []);
915
+ });
916
+ const numericOriginMap = {
917
+ number: "number",
918
+ bigint: "bigint",
919
+ object: "date"
920
+ };
921
+ const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
922
+ $ZodCheck.init(inst, def);
923
+ const origin = numericOriginMap[typeof def.value];
924
+ inst._zod.onattach.push((inst) => {
925
+ const bag = inst._zod.bag;
926
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
927
+ if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
928
+ else bag.exclusiveMaximum = def.value;
929
+ });
930
+ inst._zod.check = (payload) => {
931
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
932
+ payload.issues.push({
933
+ origin,
934
+ code: "too_big",
935
+ maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
936
+ input: payload.value,
937
+ inclusive: def.inclusive,
938
+ inst,
939
+ continue: !def.abort
940
+ });
941
+ };
942
+ });
943
+ const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
944
+ $ZodCheck.init(inst, def);
945
+ const origin = numericOriginMap[typeof def.value];
946
+ inst._zod.onattach.push((inst) => {
947
+ const bag = inst._zod.bag;
948
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
949
+ if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
950
+ else bag.exclusiveMinimum = def.value;
951
+ });
952
+ inst._zod.check = (payload) => {
953
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
954
+ payload.issues.push({
955
+ origin,
956
+ code: "too_small",
957
+ minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
958
+ input: payload.value,
959
+ inclusive: def.inclusive,
960
+ inst,
961
+ continue: !def.abort
962
+ });
963
+ };
964
+ });
965
+ const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
966
+ $ZodCheck.init(inst, def);
967
+ inst._zod.onattach.push((inst) => {
968
+ var _a;
969
+ (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
970
+ });
971
+ inst._zod.check = (payload) => {
972
+ if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
973
+ if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
974
+ payload.issues.push({
975
+ origin: typeof payload.value,
976
+ code: "not_multiple_of",
977
+ divisor: def.value,
978
+ input: payload.value,
979
+ inst,
980
+ continue: !def.abort
981
+ });
982
+ };
983
+ });
984
+ const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
985
+ $ZodCheck.init(inst, def);
986
+ def.format = def.format || "float64";
987
+ const isInt = def.format?.includes("int");
988
+ const origin = isInt ? "int" : "number";
989
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
990
+ inst._zod.onattach.push((inst) => {
991
+ const bag = inst._zod.bag;
992
+ bag.format = def.format;
993
+ bag.minimum = minimum;
994
+ bag.maximum = maximum;
995
+ if (isInt) bag.pattern = integer;
996
+ });
997
+ inst._zod.check = (payload) => {
998
+ const input = payload.value;
999
+ if (isInt) {
1000
+ if (!Number.isInteger(input)) {
1001
+ payload.issues.push({
1002
+ expected: origin,
1003
+ format: def.format,
1004
+ code: "invalid_type",
1005
+ continue: false,
1006
+ input,
1007
+ inst
1008
+ });
1009
+ return;
1010
+ }
1011
+ if (!Number.isSafeInteger(input)) {
1012
+ if (input > 0) payload.issues.push({
1013
+ input,
1014
+ code: "too_big",
1015
+ maximum: Number.MAX_SAFE_INTEGER,
1016
+ note: "Integers must be within the safe integer range.",
1017
+ inst,
1018
+ origin,
1019
+ inclusive: true,
1020
+ continue: !def.abort
1021
+ });
1022
+ else payload.issues.push({
1023
+ input,
1024
+ code: "too_small",
1025
+ minimum: Number.MIN_SAFE_INTEGER,
1026
+ note: "Integers must be within the safe integer range.",
1027
+ inst,
1028
+ origin,
1029
+ inclusive: true,
1030
+ continue: !def.abort
1031
+ });
1032
+ return;
1033
+ }
1034
+ }
1035
+ if (input < minimum) payload.issues.push({
1036
+ origin: "number",
1037
+ input,
1038
+ code: "too_small",
1039
+ minimum,
1040
+ inclusive: true,
1041
+ inst,
1042
+ continue: !def.abort
1043
+ });
1044
+ if (input > maximum) payload.issues.push({
1045
+ origin: "number",
1046
+ input,
1047
+ code: "too_big",
1048
+ maximum,
1049
+ inclusive: true,
1050
+ inst,
1051
+ continue: !def.abort
1052
+ });
1053
+ };
1054
+ });
1055
+ const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
1056
+ var _a;
1057
+ $ZodCheck.init(inst, def);
1058
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1059
+ const val = payload.value;
1060
+ return !nullish(val) && val.length !== void 0;
1061
+ });
1062
+ inst._zod.onattach.push((inst) => {
1063
+ const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
1064
+ if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
1065
+ });
1066
+ inst._zod.check = (payload) => {
1067
+ const input = payload.value;
1068
+ if (input.length <= def.maximum) return;
1069
+ const origin = getLengthableOrigin(input);
1070
+ payload.issues.push({
1071
+ origin,
1072
+ code: "too_big",
1073
+ maximum: def.maximum,
1074
+ inclusive: true,
1075
+ input,
1076
+ inst,
1077
+ continue: !def.abort
1078
+ });
1079
+ };
1080
+ });
1081
+ const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
1082
+ var _a;
1083
+ $ZodCheck.init(inst, def);
1084
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1085
+ const val = payload.value;
1086
+ return !nullish(val) && val.length !== void 0;
1087
+ });
1088
+ inst._zod.onattach.push((inst) => {
1089
+ const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
1090
+ if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
1091
+ });
1092
+ inst._zod.check = (payload) => {
1093
+ const input = payload.value;
1094
+ if (input.length >= def.minimum) return;
1095
+ const origin = getLengthableOrigin(input);
1096
+ payload.issues.push({
1097
+ origin,
1098
+ code: "too_small",
1099
+ minimum: def.minimum,
1100
+ inclusive: true,
1101
+ input,
1102
+ inst,
1103
+ continue: !def.abort
1104
+ });
1105
+ };
1106
+ });
1107
+ const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
1108
+ var _a;
1109
+ $ZodCheck.init(inst, def);
1110
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1111
+ const val = payload.value;
1112
+ return !nullish(val) && val.length !== void 0;
1113
+ });
1114
+ inst._zod.onattach.push((inst) => {
1115
+ const bag = inst._zod.bag;
1116
+ bag.minimum = def.length;
1117
+ bag.maximum = def.length;
1118
+ bag.length = def.length;
1119
+ });
1120
+ inst._zod.check = (payload) => {
1121
+ const input = payload.value;
1122
+ const length = input.length;
1123
+ if (length === def.length) return;
1124
+ const origin = getLengthableOrigin(input);
1125
+ const tooBig = length > def.length;
1126
+ payload.issues.push({
1127
+ origin,
1128
+ ...tooBig ? {
1129
+ code: "too_big",
1130
+ maximum: def.length
1131
+ } : {
1132
+ code: "too_small",
1133
+ minimum: def.length
1134
+ },
1135
+ inclusive: true,
1136
+ exact: true,
1137
+ input: payload.value,
1138
+ inst,
1139
+ continue: !def.abort
1140
+ });
1141
+ };
1142
+ });
1143
+ const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
1144
+ $ZodCheck.init(inst, def);
1145
+ inst._zod.check = (payload) => {
1146
+ payload.value = def.tx(payload.value);
1147
+ };
1148
+ });
1149
+ //#endregion
1150
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js
1151
+ var Doc = class {
1152
+ constructor(args = []) {
1153
+ this.content = [];
1154
+ this.indent = 0;
1155
+ if (this) this.args = args;
1156
+ }
1157
+ indented(fn) {
1158
+ this.indent += 1;
1159
+ fn(this);
1160
+ this.indent -= 1;
1161
+ }
1162
+ write(arg) {
1163
+ if (typeof arg === "function") {
1164
+ arg(this, { execution: "sync" });
1165
+ arg(this, { execution: "async" });
1166
+ return;
1167
+ }
1168
+ const lines = arg.split("\n").filter((x) => x);
1169
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
1170
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
1171
+ for (const line of dedented) this.content.push(line);
1172
+ }
1173
+ compile() {
1174
+ const F = Function;
1175
+ const args = this?.args;
1176
+ const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
1177
+ return new F(...args, lines.join("\n"));
1178
+ }
1179
+ };
1180
+ //#endregion
1181
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js
1182
+ const version = {
1183
+ major: 4,
1184
+ minor: 3,
1185
+ patch: 6
1186
+ };
1187
+ //#endregion
1188
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js
1189
+ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
1190
+ var _a;
1191
+ inst ?? (inst = {});
1192
+ inst._zod.def = def;
1193
+ inst._zod.bag = inst._zod.bag || {};
1194
+ inst._zod.version = version;
1195
+ const checks = [...inst._zod.def.checks ?? []];
1196
+ if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
1197
+ for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
1198
+ if (checks.length === 0) {
1199
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
1200
+ inst._zod.deferred?.push(() => {
1201
+ inst._zod.run = inst._zod.parse;
1202
+ });
1203
+ } else {
1204
+ const runChecks = (payload, checks, ctx) => {
1205
+ let isAborted = aborted(payload);
1206
+ let asyncResult;
1207
+ for (const ch of checks) {
1208
+ if (ch._zod.def.when) {
1209
+ if (!ch._zod.def.when(payload)) continue;
1210
+ } else if (isAborted) continue;
1211
+ const currLen = payload.issues.length;
1212
+ const _ = ch._zod.check(payload);
1213
+ if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
1214
+ if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
1215
+ await _;
1216
+ if (payload.issues.length === currLen) return;
1217
+ if (!isAborted) isAborted = aborted(payload, currLen);
1218
+ });
1219
+ else {
1220
+ if (payload.issues.length === currLen) continue;
1221
+ if (!isAborted) isAborted = aborted(payload, currLen);
1222
+ }
1223
+ }
1224
+ if (asyncResult) return asyncResult.then(() => {
1225
+ return payload;
1226
+ });
1227
+ return payload;
1228
+ };
1229
+ const handleCanaryResult = (canary, payload, ctx) => {
1230
+ if (aborted(canary)) {
1231
+ canary.aborted = true;
1232
+ return canary;
1233
+ }
1234
+ const checkResult = runChecks(payload, checks, ctx);
1235
+ if (checkResult instanceof Promise) {
1236
+ if (ctx.async === false) throw new $ZodAsyncError();
1237
+ return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
1238
+ }
1239
+ return inst._zod.parse(checkResult, ctx);
1240
+ };
1241
+ inst._zod.run = (payload, ctx) => {
1242
+ if (ctx.skipChecks) return inst._zod.parse(payload, ctx);
1243
+ if (ctx.direction === "backward") {
1244
+ const canary = inst._zod.parse({
1245
+ value: payload.value,
1246
+ issues: []
1247
+ }, {
1248
+ ...ctx,
1249
+ skipChecks: true
1250
+ });
1251
+ if (canary instanceof Promise) return canary.then((canary) => {
1252
+ return handleCanaryResult(canary, payload, ctx);
1253
+ });
1254
+ return handleCanaryResult(canary, payload, ctx);
1255
+ }
1256
+ const result = inst._zod.parse(payload, ctx);
1257
+ if (result instanceof Promise) {
1258
+ if (ctx.async === false) throw new $ZodAsyncError();
1259
+ return result.then((result) => runChecks(result, checks, ctx));
1260
+ }
1261
+ return runChecks(result, checks, ctx);
1262
+ };
1263
+ }
1264
+ defineLazy(inst, "~standard", () => ({
1265
+ validate: (value) => {
1266
+ try {
1267
+ const r = safeParse$1(inst, value);
1268
+ return r.success ? { value: r.data } : { issues: r.error?.issues };
1269
+ } catch (_) {
1270
+ return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
1271
+ }
1272
+ },
1273
+ vendor: "zod",
1274
+ version: 1
1275
+ }));
1276
+ });
1277
+ const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
1278
+ $ZodType.init(inst, def);
1279
+ inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
1280
+ inst._zod.parse = (payload, _ctx) => {
1281
+ if (def.coerce) try {
1282
+ payload.value = Number(payload.value);
1283
+ } catch (_) {}
1284
+ const input = payload.value;
1285
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
1286
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
1287
+ payload.issues.push({
1288
+ expected: "number",
1289
+ code: "invalid_type",
1290
+ input,
1291
+ inst,
1292
+ ...received ? { received } : {}
1293
+ });
1294
+ return payload;
1295
+ };
1296
+ });
1297
+ const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
1298
+ $ZodCheckNumberFormat.init(inst, def);
1299
+ $ZodNumber.init(inst, def);
1300
+ });
1301
+ const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
1302
+ $ZodType.init(inst, def);
1303
+ inst._zod.parse = (payload) => payload;
1304
+ });
1305
+ const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
1306
+ $ZodType.init(inst, def);
1307
+ inst._zod.parse = (payload, _ctx) => {
1308
+ payload.issues.push({
1309
+ expected: "never",
1310
+ code: "invalid_type",
1311
+ input: payload.value,
1312
+ inst
1313
+ });
1314
+ return payload;
1315
+ };
1316
+ });
1317
+ function handleArrayResult(result, final, index) {
1318
+ if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
1319
+ final.value[index] = result.value;
1320
+ }
1321
+ const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
1322
+ $ZodType.init(inst, def);
1323
+ inst._zod.parse = (payload, ctx) => {
1324
+ const input = payload.value;
1325
+ if (!Array.isArray(input)) {
1326
+ payload.issues.push({
1327
+ expected: "array",
1328
+ code: "invalid_type",
1329
+ input,
1330
+ inst
1331
+ });
1332
+ return payload;
1333
+ }
1334
+ payload.value = Array(input.length);
1335
+ const proms = [];
1336
+ for (let i = 0; i < input.length; i++) {
1337
+ const item = input[i];
1338
+ const result = def.element._zod.run({
1339
+ value: item,
1340
+ issues: []
1341
+ }, ctx);
1342
+ if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
1343
+ else handleArrayResult(result, payload, i);
1344
+ }
1345
+ if (proms.length) return Promise.all(proms).then(() => payload);
1346
+ return payload;
1347
+ };
1348
+ });
1349
+ function handlePropertyResult(result, final, key, input, isOptionalOut) {
1350
+ if (result.issues.length) {
1351
+ if (isOptionalOut && !(key in input)) return;
1352
+ final.issues.push(...prefixIssues(key, result.issues));
1353
+ }
1354
+ if (result.value === void 0) {
1355
+ if (key in input) final.value[key] = void 0;
1356
+ } else final.value[key] = result.value;
1357
+ }
1358
+ function normalizeDef(def) {
1359
+ const keys = Object.keys(def.shape);
1360
+ for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1361
+ const okeys = optionalKeys(def.shape);
1362
+ return {
1363
+ ...def,
1364
+ keys,
1365
+ keySet: new Set(keys),
1366
+ numKeys: keys.length,
1367
+ optionalKeys: new Set(okeys)
1368
+ };
1369
+ }
1370
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
1371
+ const unrecognized = [];
1372
+ const keySet = def.keySet;
1373
+ const _catchall = def.catchall._zod;
1374
+ const t = _catchall.def.type;
1375
+ const isOptionalOut = _catchall.optout === "optional";
1376
+ for (const key in input) {
1377
+ if (keySet.has(key)) continue;
1378
+ if (t === "never") {
1379
+ unrecognized.push(key);
1380
+ continue;
1381
+ }
1382
+ const r = _catchall.run({
1383
+ value: input[key],
1384
+ issues: []
1385
+ }, ctx);
1386
+ if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
1387
+ else handlePropertyResult(r, payload, key, input, isOptionalOut);
1388
+ }
1389
+ if (unrecognized.length) payload.issues.push({
1390
+ code: "unrecognized_keys",
1391
+ keys: unrecognized,
1392
+ input,
1393
+ inst
1394
+ });
1395
+ if (!proms.length) return payload;
1396
+ return Promise.all(proms).then(() => {
1397
+ return payload;
1398
+ });
1399
+ }
1400
+ const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
1401
+ $ZodType.init(inst, def);
1402
+ if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) {
1403
+ const sh = def.shape;
1404
+ Object.defineProperty(def, "shape", { get: () => {
1405
+ const newSh = { ...sh };
1406
+ Object.defineProperty(def, "shape", { value: newSh });
1407
+ return newSh;
1408
+ } });
1409
+ }
1410
+ const _normalized = cached(() => normalizeDef(def));
1411
+ defineLazy(inst._zod, "propValues", () => {
1412
+ const shape = def.shape;
1413
+ const propValues = {};
1414
+ for (const key in shape) {
1415
+ const field = shape[key]._zod;
1416
+ if (field.values) {
1417
+ propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
1418
+ for (const v of field.values) propValues[key].add(v);
1419
+ }
1420
+ }
1421
+ return propValues;
1422
+ });
1423
+ const isObject = isObject$1;
1424
+ const catchall = def.catchall;
1425
+ let value;
1426
+ inst._zod.parse = (payload, ctx) => {
1427
+ value ?? (value = _normalized.value);
1428
+ const input = payload.value;
1429
+ if (!isObject(input)) {
1430
+ payload.issues.push({
1431
+ expected: "object",
1432
+ code: "invalid_type",
1433
+ input,
1434
+ inst
1435
+ });
1436
+ return payload;
1437
+ }
1438
+ payload.value = {};
1439
+ const proms = [];
1440
+ const shape = value.shape;
1441
+ for (const key of value.keys) {
1442
+ const el = shape[key];
1443
+ const isOptionalOut = el._zod.optout === "optional";
1444
+ const r = el._zod.run({
1445
+ value: input[key],
1446
+ issues: []
1447
+ }, ctx);
1448
+ if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
1449
+ else handlePropertyResult(r, payload, key, input, isOptionalOut);
1450
+ }
1451
+ if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
1452
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
1453
+ };
1454
+ });
1455
+ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
1456
+ $ZodObject.init(inst, def);
1457
+ const superParse = inst._zod.parse;
1458
+ const _normalized = cached(() => normalizeDef(def));
1459
+ const generateFastpass = (shape) => {
1460
+ const doc = new Doc([
1461
+ "shape",
1462
+ "payload",
1463
+ "ctx"
1464
+ ]);
1465
+ const normalized = _normalized.value;
1466
+ const parseStr = (key) => {
1467
+ const k = esc(key);
1468
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
1469
+ };
1470
+ doc.write(`const input = payload.value;`);
1471
+ const ids = Object.create(null);
1472
+ let counter = 0;
1473
+ for (const key of normalized.keys) ids[key] = `key_${counter++}`;
1474
+ doc.write(`const newResult = {};`);
1475
+ for (const key of normalized.keys) {
1476
+ const id = ids[key];
1477
+ const k = esc(key);
1478
+ const isOptionalOut = shape[key]?._zod?.optout === "optional";
1479
+ doc.write(`const ${id} = ${parseStr(key)};`);
1480
+ if (isOptionalOut) doc.write(`
1481
+ if (${id}.issues.length) {
1482
+ if (${k} in input) {
1483
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1484
+ ...iss,
1485
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
1486
+ })));
1487
+ }
1488
+ }
1489
+
1490
+ if (${id}.value === undefined) {
1491
+ if (${k} in input) {
1492
+ newResult[${k}] = undefined;
1493
+ }
1494
+ } else {
1495
+ newResult[${k}] = ${id}.value;
1496
+ }
1497
+
1498
+ `);
1499
+ else doc.write(`
1500
+ if (${id}.issues.length) {
1501
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1502
+ ...iss,
1503
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
1504
+ })));
1505
+ }
1506
+
1507
+ if (${id}.value === undefined) {
1508
+ if (${k} in input) {
1509
+ newResult[${k}] = undefined;
1510
+ }
1511
+ } else {
1512
+ newResult[${k}] = ${id}.value;
1513
+ }
1514
+
1515
+ `);
1516
+ }
1517
+ doc.write(`payload.value = newResult;`);
1518
+ doc.write(`return payload;`);
1519
+ const fn = doc.compile();
1520
+ return (payload, ctx) => fn(shape, payload, ctx);
1521
+ };
1522
+ let fastpass;
1523
+ const isObject = isObject$1;
1524
+ const jit = !globalConfig.jitless;
1525
+ const fastEnabled = jit && allowsEval.value;
1526
+ const catchall = def.catchall;
1527
+ let value;
1528
+ inst._zod.parse = (payload, ctx) => {
1529
+ value ?? (value = _normalized.value);
1530
+ const input = payload.value;
1531
+ if (!isObject(input)) {
1532
+ payload.issues.push({
1533
+ expected: "object",
1534
+ code: "invalid_type",
1535
+ input,
1536
+ inst
1537
+ });
1538
+ return payload;
1539
+ }
1540
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1541
+ if (!fastpass) fastpass = generateFastpass(def.shape);
1542
+ payload = fastpass(payload, ctx);
1543
+ if (!catchall) return payload;
1544
+ return handleCatchall([], input, payload, ctx, value, inst);
1545
+ }
1546
+ return superParse(payload, ctx);
1547
+ };
1548
+ });
1549
+ function handleUnionResults(results, final, inst, ctx) {
1550
+ for (const result of results) if (result.issues.length === 0) {
1551
+ final.value = result.value;
1552
+ return final;
1553
+ }
1554
+ const nonaborted = results.filter((r) => !aborted(r));
1555
+ if (nonaborted.length === 1) {
1556
+ final.value = nonaborted[0].value;
1557
+ return nonaborted[0];
1558
+ }
1559
+ final.issues.push({
1560
+ code: "invalid_union",
1561
+ input: final.value,
1562
+ inst,
1563
+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())))
1564
+ });
1565
+ return final;
1566
+ }
1567
+ const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
1568
+ $ZodType.init(inst, def);
1569
+ defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
1570
+ defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
1571
+ defineLazy(inst._zod, "values", () => {
1572
+ if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1573
+ });
1574
+ defineLazy(inst._zod, "pattern", () => {
1575
+ if (def.options.every((o) => o._zod.pattern)) {
1576
+ const patterns = def.options.map((o) => o._zod.pattern);
1577
+ return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1578
+ }
1579
+ });
1580
+ const single = def.options.length === 1;
1581
+ const first = def.options[0]._zod.run;
1582
+ inst._zod.parse = (payload, ctx) => {
1583
+ if (single) return first(payload, ctx);
1584
+ let async = false;
1585
+ const results = [];
1586
+ for (const option of def.options) {
1587
+ const result = option._zod.run({
1588
+ value: payload.value,
1589
+ issues: []
1590
+ }, ctx);
1591
+ if (result instanceof Promise) {
1592
+ results.push(result);
1593
+ async = true;
1594
+ } else {
1595
+ if (result.issues.length === 0) return result;
1596
+ results.push(result);
1597
+ }
1598
+ }
1599
+ if (!async) return handleUnionResults(results, payload, inst, ctx);
1600
+ return Promise.all(results).then((results) => {
1601
+ return handleUnionResults(results, payload, inst, ctx);
1602
+ });
1603
+ };
1604
+ });
1605
+ const $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
1606
+ $ZodType.init(inst, def);
1607
+ inst._zod.parse = (payload, ctx) => {
1608
+ const input = payload.value;
1609
+ const left = def.left._zod.run({
1610
+ value: input,
1611
+ issues: []
1612
+ }, ctx);
1613
+ const right = def.right._zod.run({
1614
+ value: input,
1615
+ issues: []
1616
+ }, ctx);
1617
+ if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => {
1618
+ return handleIntersectionResults(payload, left, right);
1619
+ });
1620
+ return handleIntersectionResults(payload, left, right);
1621
+ };
1622
+ });
1623
+ function mergeValues(a, b) {
1624
+ if (a === b) return {
1625
+ valid: true,
1626
+ data: a
1627
+ };
1628
+ if (a instanceof Date && b instanceof Date && +a === +b) return {
1629
+ valid: true,
1630
+ data: a
1631
+ };
1632
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
1633
+ const bKeys = Object.keys(b);
1634
+ const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1635
+ const newObj = {
1636
+ ...a,
1637
+ ...b
1638
+ };
1639
+ for (const key of sharedKeys) {
1640
+ const sharedValue = mergeValues(a[key], b[key]);
1641
+ if (!sharedValue.valid) return {
1642
+ valid: false,
1643
+ mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
1644
+ };
1645
+ newObj[key] = sharedValue.data;
1646
+ }
1647
+ return {
1648
+ valid: true,
1649
+ data: newObj
1650
+ };
1651
+ }
1652
+ if (Array.isArray(a) && Array.isArray(b)) {
1653
+ if (a.length !== b.length) return {
1654
+ valid: false,
1655
+ mergeErrorPath: []
1656
+ };
1657
+ const newArray = [];
1658
+ for (let index = 0; index < a.length; index++) {
1659
+ const itemA = a[index];
1660
+ const itemB = b[index];
1661
+ const sharedValue = mergeValues(itemA, itemB);
1662
+ if (!sharedValue.valid) return {
1663
+ valid: false,
1664
+ mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
1665
+ };
1666
+ newArray.push(sharedValue.data);
1667
+ }
1668
+ return {
1669
+ valid: true,
1670
+ data: newArray
1671
+ };
1672
+ }
1673
+ return {
1674
+ valid: false,
1675
+ mergeErrorPath: []
1676
+ };
1677
+ }
1678
+ function handleIntersectionResults(result, left, right) {
1679
+ const unrecKeys = /* @__PURE__ */ new Map();
1680
+ let unrecIssue;
1681
+ for (const iss of left.issues) if (iss.code === "unrecognized_keys") {
1682
+ unrecIssue ?? (unrecIssue = iss);
1683
+ for (const k of iss.keys) {
1684
+ if (!unrecKeys.has(k)) unrecKeys.set(k, {});
1685
+ unrecKeys.get(k).l = true;
1686
+ }
1687
+ } else result.issues.push(iss);
1688
+ for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) {
1689
+ if (!unrecKeys.has(k)) unrecKeys.set(k, {});
1690
+ unrecKeys.get(k).r = true;
1691
+ }
1692
+ else result.issues.push(iss);
1693
+ const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
1694
+ if (bothKeys.length && unrecIssue) result.issues.push({
1695
+ ...unrecIssue,
1696
+ keys: bothKeys
1697
+ });
1698
+ if (aborted(result)) return result;
1699
+ const merged = mergeValues(left.value, right.value);
1700
+ if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
1701
+ result.value = merged.data;
1702
+ return result;
1703
+ }
1704
+ const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
1705
+ $ZodType.init(inst, def);
1706
+ const values = getEnumValues(def.entries);
1707
+ const valuesSet = new Set(values);
1708
+ inst._zod.values = valuesSet;
1709
+ inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
1710
+ inst._zod.parse = (payload, _ctx) => {
1711
+ const input = payload.value;
1712
+ if (valuesSet.has(input)) return payload;
1713
+ payload.issues.push({
1714
+ code: "invalid_value",
1715
+ values,
1716
+ input,
1717
+ inst
1718
+ });
1719
+ return payload;
1720
+ };
1721
+ });
1722
+ const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
1723
+ $ZodType.init(inst, def);
1724
+ inst._zod.parse = (payload, ctx) => {
1725
+ if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
1726
+ const _out = def.transform(payload.value, payload);
1727
+ if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
1728
+ payload.value = output;
1729
+ return payload;
1730
+ });
1731
+ if (_out instanceof Promise) throw new $ZodAsyncError();
1732
+ payload.value = _out;
1733
+ return payload;
1734
+ };
1735
+ });
1736
+ function handleOptionalResult(result, input) {
1737
+ if (result.issues.length && input === void 0) return {
1738
+ issues: [],
1739
+ value: void 0
1740
+ };
1741
+ return result;
1742
+ }
1743
+ const $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
1744
+ $ZodType.init(inst, def);
1745
+ inst._zod.optin = "optional";
1746
+ inst._zod.optout = "optional";
1747
+ defineLazy(inst._zod, "values", () => {
1748
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, void 0]) : void 0;
1749
+ });
1750
+ defineLazy(inst._zod, "pattern", () => {
1751
+ const pattern = def.innerType._zod.pattern;
1752
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
1753
+ });
1754
+ inst._zod.parse = (payload, ctx) => {
1755
+ if (def.innerType._zod.optin === "optional") {
1756
+ const result = def.innerType._zod.run(payload, ctx);
1757
+ if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, payload.value));
1758
+ return handleOptionalResult(result, payload.value);
1759
+ }
1760
+ if (payload.value === void 0) return payload;
1761
+ return def.innerType._zod.run(payload, ctx);
1762
+ };
1763
+ });
1764
+ const $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
1765
+ $ZodOptional.init(inst, def);
1766
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1767
+ defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
1768
+ inst._zod.parse = (payload, ctx) => {
1769
+ return def.innerType._zod.run(payload, ctx);
1770
+ };
1771
+ });
1772
+ const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
1773
+ $ZodType.init(inst, def);
1774
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1775
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1776
+ defineLazy(inst._zod, "pattern", () => {
1777
+ const pattern = def.innerType._zod.pattern;
1778
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
1779
+ });
1780
+ defineLazy(inst._zod, "values", () => {
1781
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : void 0;
1782
+ });
1783
+ inst._zod.parse = (payload, ctx) => {
1784
+ if (payload.value === null) return payload;
1785
+ return def.innerType._zod.run(payload, ctx);
1786
+ };
1787
+ });
1788
+ const $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
1789
+ $ZodType.init(inst, def);
1790
+ inst._zod.optin = "optional";
1791
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1792
+ inst._zod.parse = (payload, ctx) => {
1793
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1794
+ if (payload.value === void 0) {
1795
+ payload.value = def.defaultValue;
1796
+ /**
1797
+ * $ZodDefault returns the default value immediately in forward direction.
1798
+ * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
1799
+ return payload;
1800
+ }
1801
+ const result = def.innerType._zod.run(payload, ctx);
1802
+ if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));
1803
+ return handleDefaultResult(result, def);
1804
+ };
1805
+ });
1806
+ function handleDefaultResult(payload, def) {
1807
+ if (payload.value === void 0) payload.value = def.defaultValue;
1808
+ return payload;
1809
+ }
1810
+ const $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
1811
+ $ZodType.init(inst, def);
1812
+ inst._zod.optin = "optional";
1813
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1814
+ inst._zod.parse = (payload, ctx) => {
1815
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1816
+ if (payload.value === void 0) payload.value = def.defaultValue;
1817
+ return def.innerType._zod.run(payload, ctx);
1818
+ };
1819
+ });
1820
+ const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
1821
+ $ZodType.init(inst, def);
1822
+ defineLazy(inst._zod, "values", () => {
1823
+ const v = def.innerType._zod.values;
1824
+ return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
1825
+ });
1826
+ inst._zod.parse = (payload, ctx) => {
1827
+ const result = def.innerType._zod.run(payload, ctx);
1828
+ if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst));
1829
+ return handleNonOptionalResult(result, inst);
1830
+ };
1831
+ });
1832
+ function handleNonOptionalResult(payload, inst) {
1833
+ if (!payload.issues.length && payload.value === void 0) payload.issues.push({
1834
+ code: "invalid_type",
1835
+ expected: "nonoptional",
1836
+ input: payload.value,
1837
+ inst
1838
+ });
1839
+ return payload;
1840
+ }
1841
+ const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
1842
+ $ZodType.init(inst, def);
1843
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1844
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1845
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1846
+ inst._zod.parse = (payload, ctx) => {
1847
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1848
+ const result = def.innerType._zod.run(payload, ctx);
1849
+ if (result instanceof Promise) return result.then((result) => {
1850
+ payload.value = result.value;
1851
+ if (result.issues.length) {
1852
+ payload.value = def.catchValue({
1853
+ ...payload,
1854
+ error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())) },
1855
+ input: payload.value
1856
+ });
1857
+ payload.issues = [];
1858
+ }
1859
+ return payload;
1860
+ });
1861
+ payload.value = result.value;
1862
+ if (result.issues.length) {
1863
+ payload.value = def.catchValue({
1864
+ ...payload,
1865
+ error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())) },
1866
+ input: payload.value
1867
+ });
1868
+ payload.issues = [];
1869
+ }
1870
+ return payload;
1871
+ };
1872
+ });
1873
+ const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
1874
+ $ZodType.init(inst, def);
1875
+ defineLazy(inst._zod, "values", () => def.in._zod.values);
1876
+ defineLazy(inst._zod, "optin", () => def.in._zod.optin);
1877
+ defineLazy(inst._zod, "optout", () => def.out._zod.optout);
1878
+ defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
1879
+ inst._zod.parse = (payload, ctx) => {
1880
+ if (ctx.direction === "backward") {
1881
+ const right = def.out._zod.run(payload, ctx);
1882
+ if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx));
1883
+ return handlePipeResult(right, def.in, ctx);
1884
+ }
1885
+ const left = def.in._zod.run(payload, ctx);
1886
+ if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx));
1887
+ return handlePipeResult(left, def.out, ctx);
1888
+ };
1889
+ });
1890
+ function handlePipeResult(left, next, ctx) {
1891
+ if (left.issues.length) {
1892
+ left.aborted = true;
1893
+ return left;
1894
+ }
1895
+ return next._zod.run({
1896
+ value: left.value,
1897
+ issues: left.issues
1898
+ }, ctx);
1899
+ }
1900
+ const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
1901
+ $ZodType.init(inst, def);
1902
+ defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
1903
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1904
+ defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
1905
+ defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
1906
+ inst._zod.parse = (payload, ctx) => {
1907
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1908
+ const result = def.innerType._zod.run(payload, ctx);
1909
+ if (result instanceof Promise) return result.then(handleReadonlyResult);
1910
+ return handleReadonlyResult(result);
1911
+ };
1912
+ });
1913
+ function handleReadonlyResult(payload) {
1914
+ payload.value = Object.freeze(payload.value);
1915
+ return payload;
1916
+ }
1917
+ const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
1918
+ $ZodCheck.init(inst, def);
1919
+ $ZodType.init(inst, def);
1920
+ inst._zod.parse = (payload, _) => {
1921
+ return payload;
1922
+ };
1923
+ inst._zod.check = (payload) => {
1924
+ const input = payload.value;
1925
+ const r = def.fn(input);
1926
+ if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst));
1927
+ handleRefineResult(r, payload, input, inst);
1928
+ };
1929
+ });
1930
+ function handleRefineResult(result, payload, input, inst) {
1931
+ if (!result) {
1932
+ const _iss = {
1933
+ code: "custom",
1934
+ input,
1935
+ inst,
1936
+ path: [...inst._zod.def.path ?? []],
1937
+ continue: !inst._zod.def.abort
1938
+ };
1939
+ if (inst._zod.def.params) _iss.params = inst._zod.def.params;
1940
+ payload.issues.push(issue(_iss));
1941
+ }
1942
+ }
1943
+ //#endregion
1944
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js
1945
+ var _a;
1946
+ var $ZodRegistry = class {
1947
+ constructor() {
1948
+ this._map = /* @__PURE__ */ new WeakMap();
1949
+ this._idmap = /* @__PURE__ */ new Map();
1950
+ }
1951
+ add(schema, ..._meta) {
1952
+ const meta = _meta[0];
1953
+ this._map.set(schema, meta);
1954
+ if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema);
1955
+ return this;
1956
+ }
1957
+ clear() {
1958
+ this._map = /* @__PURE__ */ new WeakMap();
1959
+ this._idmap = /* @__PURE__ */ new Map();
1960
+ return this;
1961
+ }
1962
+ remove(schema) {
1963
+ const meta = this._map.get(schema);
1964
+ if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
1965
+ this._map.delete(schema);
1966
+ return this;
1967
+ }
1968
+ get(schema) {
1969
+ const p = schema._zod.parent;
1970
+ if (p) {
1971
+ const pm = { ...this.get(p) ?? {} };
1972
+ delete pm.id;
1973
+ const f = {
1974
+ ...pm,
1975
+ ...this._map.get(schema)
1976
+ };
1977
+ return Object.keys(f).length ? f : void 0;
1978
+ }
1979
+ return this._map.get(schema);
1980
+ }
1981
+ has(schema) {
1982
+ return this._map.has(schema);
1983
+ }
1984
+ };
1985
+ function registry() {
1986
+ return new $ZodRegistry();
1987
+ }
1988
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
1989
+ const globalRegistry = globalThis.__zod_globalRegistry;
1990
+ //#endregion
1991
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js
1992
+ /* @__NO_SIDE_EFFECTS__ */
1993
+ function _number(Class, params) {
1994
+ return new Class({
1995
+ type: "number",
1996
+ checks: [],
1997
+ ...normalizeParams(params)
1998
+ });
1999
+ }
2000
+ /* @__NO_SIDE_EFFECTS__ */
2001
+ function _int(Class, params) {
2002
+ return new Class({
2003
+ type: "number",
2004
+ check: "number_format",
2005
+ abort: false,
2006
+ format: "safeint",
2007
+ ...normalizeParams(params)
2008
+ });
2009
+ }
2010
+ /* @__NO_SIDE_EFFECTS__ */
2011
+ function _unknown(Class) {
2012
+ return new Class({ type: "unknown" });
2013
+ }
2014
+ /* @__NO_SIDE_EFFECTS__ */
2015
+ function _never(Class, params) {
2016
+ return new Class({
2017
+ type: "never",
2018
+ ...normalizeParams(params)
2019
+ });
2020
+ }
2021
+ /* @__NO_SIDE_EFFECTS__ */
2022
+ function _lt(value, params) {
2023
+ return new $ZodCheckLessThan({
2024
+ check: "less_than",
2025
+ ...normalizeParams(params),
2026
+ value,
2027
+ inclusive: false
2028
+ });
2029
+ }
2030
+ /* @__NO_SIDE_EFFECTS__ */
2031
+ function _lte(value, params) {
2032
+ return new $ZodCheckLessThan({
2033
+ check: "less_than",
2034
+ ...normalizeParams(params),
2035
+ value,
2036
+ inclusive: true
2037
+ });
2038
+ }
2039
+ /* @__NO_SIDE_EFFECTS__ */
2040
+ function _gt(value, params) {
2041
+ return new $ZodCheckGreaterThan({
2042
+ check: "greater_than",
2043
+ ...normalizeParams(params),
2044
+ value,
2045
+ inclusive: false
2046
+ });
2047
+ }
2048
+ /* @__NO_SIDE_EFFECTS__ */
2049
+ function _gte(value, params) {
2050
+ return new $ZodCheckGreaterThan({
2051
+ check: "greater_than",
2052
+ ...normalizeParams(params),
2053
+ value,
2054
+ inclusive: true
2055
+ });
2056
+ }
2057
+ /* @__NO_SIDE_EFFECTS__ */
2058
+ function _multipleOf(value, params) {
2059
+ return new $ZodCheckMultipleOf({
2060
+ check: "multiple_of",
2061
+ ...normalizeParams(params),
2062
+ value
2063
+ });
2064
+ }
2065
+ /* @__NO_SIDE_EFFECTS__ */
2066
+ function _maxLength(maximum, params) {
2067
+ return new $ZodCheckMaxLength({
2068
+ check: "max_length",
2069
+ ...normalizeParams(params),
2070
+ maximum
2071
+ });
2072
+ }
2073
+ /* @__NO_SIDE_EFFECTS__ */
2074
+ function _minLength(minimum, params) {
2075
+ return new $ZodCheckMinLength({
2076
+ check: "min_length",
2077
+ ...normalizeParams(params),
2078
+ minimum
2079
+ });
2080
+ }
2081
+ /* @__NO_SIDE_EFFECTS__ */
2082
+ function _length(length, params) {
2083
+ return new $ZodCheckLengthEquals({
2084
+ check: "length_equals",
2085
+ ...normalizeParams(params),
2086
+ length
2087
+ });
2088
+ }
2089
+ /* @__NO_SIDE_EFFECTS__ */
2090
+ function _overwrite(tx) {
2091
+ return new $ZodCheckOverwrite({
2092
+ check: "overwrite",
2093
+ tx
2094
+ });
2095
+ }
2096
+ /* @__NO_SIDE_EFFECTS__ */
2097
+ function _array(Class, element, params) {
2098
+ return new Class({
2099
+ type: "array",
2100
+ element,
2101
+ ...normalizeParams(params)
2102
+ });
2103
+ }
2104
+ /* @__NO_SIDE_EFFECTS__ */
2105
+ function _refine(Class, fn, _params) {
2106
+ return new Class({
2107
+ type: "custom",
2108
+ check: "custom",
2109
+ fn,
2110
+ ...normalizeParams(_params)
2111
+ });
2112
+ }
2113
+ /* @__NO_SIDE_EFFECTS__ */
2114
+ function _superRefine(fn) {
2115
+ const ch = /* @__PURE__ */ _check((payload) => {
2116
+ payload.addIssue = (issue$2) => {
2117
+ if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def));
2118
+ else {
2119
+ const _issue = issue$2;
2120
+ if (_issue.fatal) _issue.continue = false;
2121
+ _issue.code ?? (_issue.code = "custom");
2122
+ _issue.input ?? (_issue.input = payload.value);
2123
+ _issue.inst ?? (_issue.inst = ch);
2124
+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
2125
+ payload.issues.push(issue(_issue));
2126
+ }
2127
+ };
2128
+ return fn(payload.value, payload);
2129
+ });
2130
+ return ch;
2131
+ }
2132
+ /* @__NO_SIDE_EFFECTS__ */
2133
+ function _check(fn, params) {
2134
+ const ch = new $ZodCheck({
2135
+ check: "custom",
2136
+ ...normalizeParams(params)
2137
+ });
2138
+ ch._zod.check = fn;
2139
+ return ch;
2140
+ }
2141
+ //#endregion
2142
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js
2143
+ function initializeContext(params) {
2144
+ let target = params?.target ?? "draft-2020-12";
2145
+ if (target === "draft-4") target = "draft-04";
2146
+ if (target === "draft-7") target = "draft-07";
2147
+ return {
2148
+ processors: params.processors ?? {},
2149
+ metadataRegistry: params?.metadata ?? globalRegistry,
2150
+ target,
2151
+ unrepresentable: params?.unrepresentable ?? "throw",
2152
+ override: params?.override ?? (() => {}),
2153
+ io: params?.io ?? "output",
2154
+ counter: 0,
2155
+ seen: /* @__PURE__ */ new Map(),
2156
+ cycles: params?.cycles ?? "ref",
2157
+ reused: params?.reused ?? "inline",
2158
+ external: params?.external ?? void 0
2159
+ };
2160
+ }
2161
+ function process$1(schema, ctx, _params = {
2162
+ path: [],
2163
+ schemaPath: []
2164
+ }) {
2165
+ var _a;
2166
+ const def = schema._zod.def;
2167
+ const seen = ctx.seen.get(schema);
2168
+ if (seen) {
2169
+ seen.count++;
2170
+ if (_params.schemaPath.includes(schema)) seen.cycle = _params.path;
2171
+ return seen.schema;
2172
+ }
2173
+ const result = {
2174
+ schema: {},
2175
+ count: 1,
2176
+ cycle: void 0,
2177
+ path: _params.path
2178
+ };
2179
+ ctx.seen.set(schema, result);
2180
+ const overrideSchema = schema._zod.toJSONSchema?.();
2181
+ if (overrideSchema) result.schema = overrideSchema;
2182
+ else {
2183
+ const params = {
2184
+ ..._params,
2185
+ schemaPath: [..._params.schemaPath, schema],
2186
+ path: _params.path
2187
+ };
2188
+ if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params);
2189
+ else {
2190
+ const _json = result.schema;
2191
+ const processor = ctx.processors[def.type];
2192
+ if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
2193
+ processor(schema, ctx, _json, params);
2194
+ }
2195
+ const parent = schema._zod.parent;
2196
+ if (parent) {
2197
+ if (!result.ref) result.ref = parent;
2198
+ process$1(parent, ctx, params);
2199
+ ctx.seen.get(parent).isParent = true;
2200
+ }
2201
+ }
2202
+ const meta = ctx.metadataRegistry.get(schema);
2203
+ if (meta) Object.assign(result.schema, meta);
2204
+ if (ctx.io === "input" && isTransforming(schema)) {
2205
+ delete result.schema.examples;
2206
+ delete result.schema.default;
2207
+ }
2208
+ if (ctx.io === "input" && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
2209
+ delete result.schema._prefault;
2210
+ return ctx.seen.get(schema).schema;
2211
+ }
2212
+ function extractDefs(ctx, schema) {
2213
+ const root = ctx.seen.get(schema);
2214
+ if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2215
+ const idToSchema = /* @__PURE__ */ new Map();
2216
+ for (const entry of ctx.seen.entries()) {
2217
+ const id = ctx.metadataRegistry.get(entry[0])?.id;
2218
+ if (id) {
2219
+ const existing = idToSchema.get(id);
2220
+ if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
2221
+ idToSchema.set(id, entry[0]);
2222
+ }
2223
+ }
2224
+ const makeURI = (entry) => {
2225
+ const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
2226
+ if (ctx.external) {
2227
+ const externalId = ctx.external.registry.get(entry[0])?.id;
2228
+ const uriGenerator = ctx.external.uri ?? ((id) => id);
2229
+ if (externalId) return { ref: uriGenerator(externalId) };
2230
+ const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
2231
+ entry[1].defId = id;
2232
+ return {
2233
+ defId: id,
2234
+ ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}`
2235
+ };
2236
+ }
2237
+ if (entry[1] === root) return { ref: "#" };
2238
+ const defUriPrefix = `#/${defsSegment}/`;
2239
+ const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
2240
+ return {
2241
+ defId,
2242
+ ref: defUriPrefix + defId
2243
+ };
2244
+ };
2245
+ const extractToDef = (entry) => {
2246
+ if (entry[1].schema.$ref) return;
2247
+ const seen = entry[1];
2248
+ const { ref, defId } = makeURI(entry);
2249
+ seen.def = { ...seen.schema };
2250
+ if (defId) seen.defId = defId;
2251
+ const schema = seen.schema;
2252
+ for (const key in schema) delete schema[key];
2253
+ schema.$ref = ref;
2254
+ };
2255
+ if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) {
2256
+ const seen = entry[1];
2257
+ if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
2258
+
2259
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
2260
+ }
2261
+ for (const entry of ctx.seen.entries()) {
2262
+ const seen = entry[1];
2263
+ if (schema === entry[0]) {
2264
+ extractToDef(entry);
2265
+ continue;
2266
+ }
2267
+ if (ctx.external) {
2268
+ const ext = ctx.external.registry.get(entry[0])?.id;
2269
+ if (schema !== entry[0] && ext) {
2270
+ extractToDef(entry);
2271
+ continue;
2272
+ }
2273
+ }
2274
+ if (ctx.metadataRegistry.get(entry[0])?.id) {
2275
+ extractToDef(entry);
2276
+ continue;
2277
+ }
2278
+ if (seen.cycle) {
2279
+ extractToDef(entry);
2280
+ continue;
2281
+ }
2282
+ if (seen.count > 1) {
2283
+ if (ctx.reused === "ref") {
2284
+ extractToDef(entry);
2285
+ continue;
2286
+ }
2287
+ }
2288
+ }
2289
+ }
2290
+ function finalize(ctx, schema) {
2291
+ const root = ctx.seen.get(schema);
2292
+ if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2293
+ const flattenRef = (zodSchema) => {
2294
+ const seen = ctx.seen.get(zodSchema);
2295
+ if (seen.ref === null) return;
2296
+ const schema = seen.def ?? seen.schema;
2297
+ const _cached = { ...schema };
2298
+ const ref = seen.ref;
2299
+ seen.ref = null;
2300
+ if (ref) {
2301
+ flattenRef(ref);
2302
+ const refSeen = ctx.seen.get(ref);
2303
+ const refSchema = refSeen.schema;
2304
+ if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
2305
+ schema.allOf = schema.allOf ?? [];
2306
+ schema.allOf.push(refSchema);
2307
+ } else Object.assign(schema, refSchema);
2308
+ Object.assign(schema, _cached);
2309
+ if (zodSchema._zod.parent === ref) for (const key in schema) {
2310
+ if (key === "$ref" || key === "allOf") continue;
2311
+ if (!(key in _cached)) delete schema[key];
2312
+ }
2313
+ if (refSchema.$ref && refSeen.def) for (const key in schema) {
2314
+ if (key === "$ref" || key === "allOf") continue;
2315
+ if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key];
2316
+ }
2317
+ }
2318
+ const parent = zodSchema._zod.parent;
2319
+ if (parent && parent !== ref) {
2320
+ flattenRef(parent);
2321
+ const parentSeen = ctx.seen.get(parent);
2322
+ if (parentSeen?.schema.$ref) {
2323
+ schema.$ref = parentSeen.schema.$ref;
2324
+ if (parentSeen.def) for (const key in schema) {
2325
+ if (key === "$ref" || key === "allOf") continue;
2326
+ if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key];
2327
+ }
2328
+ }
2329
+ }
2330
+ ctx.override({
2331
+ zodSchema,
2332
+ jsonSchema: schema,
2333
+ path: seen.path ?? []
2334
+ });
2335
+ };
2336
+ for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]);
2337
+ const result = {};
2338
+ if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema";
2339
+ else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#";
2340
+ else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#";
2341
+ else if (ctx.target === "openapi-3.0") {}
2342
+ if (ctx.external?.uri) {
2343
+ const id = ctx.external.registry.get(schema)?.id;
2344
+ if (!id) throw new Error("Schema is missing an `id` property");
2345
+ result.$id = ctx.external.uri(id);
2346
+ }
2347
+ Object.assign(result, root.def ?? root.schema);
2348
+ const defs = ctx.external?.defs ?? {};
2349
+ for (const entry of ctx.seen.entries()) {
2350
+ const seen = entry[1];
2351
+ if (seen.def && seen.defId) defs[seen.defId] = seen.def;
2352
+ }
2353
+ if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs;
2354
+ else result.definitions = defs;
2355
+ try {
2356
+ const finalized = JSON.parse(JSON.stringify(result));
2357
+ Object.defineProperty(finalized, "~standard", {
2358
+ value: {
2359
+ ...schema["~standard"],
2360
+ jsonSchema: {
2361
+ input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
2362
+ output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
2363
+ }
2364
+ },
2365
+ enumerable: false,
2366
+ writable: false
2367
+ });
2368
+ return finalized;
2369
+ } catch (_err) {
2370
+ throw new Error("Error converting schema to JSON.");
2371
+ }
2372
+ }
2373
+ function isTransforming(_schema, _ctx) {
2374
+ const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
2375
+ if (ctx.seen.has(_schema)) return false;
2376
+ ctx.seen.add(_schema);
2377
+ const def = _schema._zod.def;
2378
+ if (def.type === "transform") return true;
2379
+ if (def.type === "array") return isTransforming(def.element, ctx);
2380
+ if (def.type === "set") return isTransforming(def.valueType, ctx);
2381
+ if (def.type === "lazy") return isTransforming(def.getter(), ctx);
2382
+ if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx);
2383
+ if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
2384
+ if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
2385
+ if (def.type === "pipe") return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
2386
+ if (def.type === "object") {
2387
+ for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true;
2388
+ return false;
2389
+ }
2390
+ if (def.type === "union") {
2391
+ for (const option of def.options) if (isTransforming(option, ctx)) return true;
2392
+ return false;
2393
+ }
2394
+ if (def.type === "tuple") {
2395
+ for (const item of def.items) if (isTransforming(item, ctx)) return true;
2396
+ if (def.rest && isTransforming(def.rest, ctx)) return true;
2397
+ return false;
2398
+ }
2399
+ return false;
2400
+ }
2401
+ /**
2402
+ * Creates a toJSONSchema method for a schema instance.
2403
+ * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.
2404
+ */
2405
+ const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
2406
+ const ctx = initializeContext({
2407
+ ...params,
2408
+ processors
2409
+ });
2410
+ process$1(schema, ctx);
2411
+ extractDefs(ctx, schema);
2412
+ return finalize(ctx, schema);
2413
+ };
2414
+ const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
2415
+ const { libraryOptions, target } = params ?? {};
2416
+ const ctx = initializeContext({
2417
+ ...libraryOptions ?? {},
2418
+ target,
2419
+ io,
2420
+ processors
2421
+ });
2422
+ process$1(schema, ctx);
2423
+ extractDefs(ctx, schema);
2424
+ return finalize(ctx, schema);
2425
+ };
2426
+ //#endregion
2427
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js
2428
+ const numberProcessor = (schema, ctx, _json, _params) => {
2429
+ const json = _json;
2430
+ const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
2431
+ if (typeof format === "string" && format.includes("int")) json.type = "integer";
2432
+ else json.type = "number";
2433
+ if (typeof exclusiveMinimum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
2434
+ json.minimum = exclusiveMinimum;
2435
+ json.exclusiveMinimum = true;
2436
+ } else json.exclusiveMinimum = exclusiveMinimum;
2437
+ if (typeof minimum === "number") {
2438
+ json.minimum = minimum;
2439
+ if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") if (exclusiveMinimum >= minimum) delete json.minimum;
2440
+ else delete json.exclusiveMinimum;
2441
+ }
2442
+ if (typeof exclusiveMaximum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
2443
+ json.maximum = exclusiveMaximum;
2444
+ json.exclusiveMaximum = true;
2445
+ } else json.exclusiveMaximum = exclusiveMaximum;
2446
+ if (typeof maximum === "number") {
2447
+ json.maximum = maximum;
2448
+ if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") if (exclusiveMaximum <= maximum) delete json.maximum;
2449
+ else delete json.exclusiveMaximum;
2450
+ }
2451
+ if (typeof multipleOf === "number") json.multipleOf = multipleOf;
2452
+ };
2453
+ const neverProcessor = (_schema, _ctx, json, _params) => {
2454
+ json.not = {};
2455
+ };
2456
+ const unknownProcessor = (_schema, _ctx, _json, _params) => {};
2457
+ const enumProcessor = (schema, _ctx, json, _params) => {
2458
+ const def = schema._zod.def;
2459
+ const values = getEnumValues(def.entries);
2460
+ if (values.every((v) => typeof v === "number")) json.type = "number";
2461
+ if (values.every((v) => typeof v === "string")) json.type = "string";
2462
+ json.enum = values;
2463
+ };
2464
+ const customProcessor = (_schema, ctx, _json, _params) => {
2465
+ if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
2466
+ };
2467
+ const transformProcessor = (_schema, ctx, _json, _params) => {
2468
+ if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
2469
+ };
2470
+ const arrayProcessor = (schema, ctx, _json, params) => {
2471
+ const json = _json;
2472
+ const def = schema._zod.def;
2473
+ const { minimum, maximum } = schema._zod.bag;
2474
+ if (typeof minimum === "number") json.minItems = minimum;
2475
+ if (typeof maximum === "number") json.maxItems = maximum;
2476
+ json.type = "array";
2477
+ json.items = process$1(def.element, ctx, {
2478
+ ...params,
2479
+ path: [...params.path, "items"]
2480
+ });
2481
+ };
2482
+ const objectProcessor = (schema, ctx, _json, params) => {
2483
+ const json = _json;
2484
+ const def = schema._zod.def;
2485
+ json.type = "object";
2486
+ json.properties = {};
2487
+ const shape = def.shape;
2488
+ for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
2489
+ ...params,
2490
+ path: [
2491
+ ...params.path,
2492
+ "properties",
2493
+ key
2494
+ ]
2495
+ });
2496
+ const allKeys = new Set(Object.keys(shape));
2497
+ const requiredKeys = new Set([...allKeys].filter((key) => {
2498
+ const v = def.shape[key]._zod;
2499
+ if (ctx.io === "input") return v.optin === void 0;
2500
+ else return v.optout === void 0;
2501
+ }));
2502
+ if (requiredKeys.size > 0) json.required = Array.from(requiredKeys);
2503
+ if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
2504
+ else if (!def.catchall) {
2505
+ if (ctx.io === "output") json.additionalProperties = false;
2506
+ } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
2507
+ ...params,
2508
+ path: [...params.path, "additionalProperties"]
2509
+ });
2510
+ };
2511
+ const unionProcessor = (schema, ctx, json, params) => {
2512
+ const def = schema._zod.def;
2513
+ const isExclusive = def.inclusive === false;
2514
+ const options = def.options.map((x, i) => process$1(x, ctx, {
2515
+ ...params,
2516
+ path: [
2517
+ ...params.path,
2518
+ isExclusive ? "oneOf" : "anyOf",
2519
+ i
2520
+ ]
2521
+ }));
2522
+ if (isExclusive) json.oneOf = options;
2523
+ else json.anyOf = options;
2524
+ };
2525
+ const intersectionProcessor = (schema, ctx, json, params) => {
2526
+ const def = schema._zod.def;
2527
+ const a = process$1(def.left, ctx, {
2528
+ ...params,
2529
+ path: [
2530
+ ...params.path,
2531
+ "allOf",
2532
+ 0
2533
+ ]
2534
+ });
2535
+ const b = process$1(def.right, ctx, {
2536
+ ...params,
2537
+ path: [
2538
+ ...params.path,
2539
+ "allOf",
2540
+ 1
2541
+ ]
2542
+ });
2543
+ const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
2544
+ json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
2545
+ };
2546
+ const nullableProcessor = (schema, ctx, json, params) => {
2547
+ const def = schema._zod.def;
2548
+ const inner = process$1(def.innerType, ctx, params);
2549
+ const seen = ctx.seen.get(schema);
2550
+ if (ctx.target === "openapi-3.0") {
2551
+ seen.ref = def.innerType;
2552
+ json.nullable = true;
2553
+ } else json.anyOf = [inner, { type: "null" }];
2554
+ };
2555
+ const nonoptionalProcessor = (schema, ctx, _json, params) => {
2556
+ const def = schema._zod.def;
2557
+ process$1(def.innerType, ctx, params);
2558
+ const seen = ctx.seen.get(schema);
2559
+ seen.ref = def.innerType;
2560
+ };
2561
+ const defaultProcessor = (schema, ctx, json, params) => {
2562
+ const def = schema._zod.def;
2563
+ process$1(def.innerType, ctx, params);
2564
+ const seen = ctx.seen.get(schema);
2565
+ seen.ref = def.innerType;
2566
+ json.default = JSON.parse(JSON.stringify(def.defaultValue));
2567
+ };
2568
+ const prefaultProcessor = (schema, ctx, json, params) => {
2569
+ const def = schema._zod.def;
2570
+ process$1(def.innerType, ctx, params);
2571
+ const seen = ctx.seen.get(schema);
2572
+ seen.ref = def.innerType;
2573
+ if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
2574
+ };
2575
+ const catchProcessor = (schema, ctx, json, params) => {
2576
+ const def = schema._zod.def;
2577
+ process$1(def.innerType, ctx, params);
2578
+ const seen = ctx.seen.get(schema);
2579
+ seen.ref = def.innerType;
2580
+ let catchValue;
2581
+ try {
2582
+ catchValue = def.catchValue(void 0);
2583
+ } catch {
2584
+ throw new Error("Dynamic catch values are not supported in JSON Schema");
2585
+ }
2586
+ json.default = catchValue;
2587
+ };
2588
+ const pipeProcessor = (schema, ctx, _json, params) => {
2589
+ const def = schema._zod.def;
2590
+ const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
2591
+ process$1(innerType, ctx, params);
2592
+ const seen = ctx.seen.get(schema);
2593
+ seen.ref = innerType;
2594
+ };
2595
+ const readonlyProcessor = (schema, ctx, json, params) => {
2596
+ const def = schema._zod.def;
2597
+ process$1(def.innerType, ctx, params);
2598
+ const seen = ctx.seen.get(schema);
2599
+ seen.ref = def.innerType;
2600
+ json.readOnly = true;
2601
+ };
2602
+ const optionalProcessor = (schema, ctx, _json, params) => {
2603
+ const def = schema._zod.def;
2604
+ process$1(def.innerType, ctx, params);
2605
+ const seen = ctx.seen.get(schema);
2606
+ seen.ref = def.innerType;
2607
+ };
2608
+ //#endregion
2609
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js
2610
+ const initializer = (inst, issues) => {
2611
+ $ZodError.init(inst, issues);
2612
+ inst.name = "ZodError";
2613
+ Object.defineProperties(inst, {
2614
+ format: { value: (mapper) => formatError(inst, mapper) },
2615
+ flatten: { value: (mapper) => flattenError(inst, mapper) },
2616
+ addIssue: { value: (issue) => {
2617
+ inst.issues.push(issue);
2618
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2619
+ } },
2620
+ addIssues: { value: (issues) => {
2621
+ inst.issues.push(...issues);
2622
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2623
+ } },
2624
+ isEmpty: { get() {
2625
+ return inst.issues.length === 0;
2626
+ } }
2627
+ });
2628
+ };
2629
+ $constructor("ZodError", initializer);
2630
+ const ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
2631
+ //#endregion
2632
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js
2633
+ const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
2634
+ const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
2635
+ const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
2636
+ const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
2637
+ const encode$2 = /* @__PURE__ */ _encode(ZodRealError);
2638
+ const decode = /* @__PURE__ */ _decode(ZodRealError);
2639
+ const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
2640
+ const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
2641
+ const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
2642
+ const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
2643
+ const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
2644
+ const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
2645
+ //#endregion
2646
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js
2647
+ const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
2648
+ $ZodType.init(inst, def);
2649
+ Object.assign(inst["~standard"], { jsonSchema: {
2650
+ input: createStandardJSONSchemaMethod(inst, "input"),
2651
+ output: createStandardJSONSchemaMethod(inst, "output")
2652
+ } });
2653
+ inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
2654
+ inst.def = def;
2655
+ inst.type = def.type;
2656
+ Object.defineProperty(inst, "_def", { value: def });
2657
+ inst.check = (...checks) => {
2658
+ return inst.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
2659
+ check: ch,
2660
+ def: { check: "custom" },
2661
+ onattach: []
2662
+ } } : ch)] }), { parent: true });
2663
+ };
2664
+ inst.with = inst.check;
2665
+ inst.clone = (def, params) => clone(inst, def, params);
2666
+ inst.brand = () => inst;
2667
+ inst.register = ((reg, meta) => {
2668
+ reg.add(inst, meta);
2669
+ return inst;
2670
+ });
2671
+ inst.parse = (data, params) => parse$1(inst, data, params, { callee: inst.parse });
2672
+ inst.safeParse = (data, params) => safeParse(inst, data, params);
2673
+ inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
2674
+ inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
2675
+ inst.spa = inst.safeParseAsync;
2676
+ inst.encode = (data, params) => encode$2(inst, data, params);
2677
+ inst.decode = (data, params) => decode(inst, data, params);
2678
+ inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
2679
+ inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
2680
+ inst.safeEncode = (data, params) => safeEncode(inst, data, params);
2681
+ inst.safeDecode = (data, params) => safeDecode(inst, data, params);
2682
+ inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
2683
+ inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
2684
+ inst.refine = (check, params) => inst.check(refine(check, params));
2685
+ inst.superRefine = (refinement) => inst.check(superRefine(refinement));
2686
+ inst.overwrite = (fn) => inst.check(/* @__PURE__ */ _overwrite(fn));
2687
+ inst.optional = () => optional(inst);
2688
+ inst.exactOptional = () => exactOptional(inst);
2689
+ inst.nullable = () => nullable(inst);
2690
+ inst.nullish = () => optional(nullable(inst));
2691
+ inst.nonoptional = (params) => nonoptional(inst, params);
2692
+ inst.array = () => array(inst);
2693
+ inst.or = (arg) => union([inst, arg]);
2694
+ inst.and = (arg) => intersection(inst, arg);
2695
+ inst.transform = (tx) => pipe(inst, transform(tx));
2696
+ inst.default = (def) => _default(inst, def);
2697
+ inst.prefault = (def) => prefault(inst, def);
2698
+ inst.catch = (params) => _catch(inst, params);
2699
+ inst.pipe = (target) => pipe(inst, target);
2700
+ inst.readonly = () => readonly(inst);
2701
+ inst.describe = (description) => {
2702
+ const cl = inst.clone();
2703
+ globalRegistry.add(cl, { description });
2704
+ return cl;
2705
+ };
2706
+ Object.defineProperty(inst, "description", {
2707
+ get() {
2708
+ return globalRegistry.get(inst)?.description;
2709
+ },
2710
+ configurable: true
2711
+ });
2712
+ inst.meta = (...args) => {
2713
+ if (args.length === 0) return globalRegistry.get(inst);
2714
+ const cl = inst.clone();
2715
+ globalRegistry.add(cl, args[0]);
2716
+ return cl;
2717
+ };
2718
+ inst.isOptional = () => inst.safeParse(void 0).success;
2719
+ inst.isNullable = () => inst.safeParse(null).success;
2720
+ inst.apply = (fn) => fn(inst);
2721
+ return inst;
2722
+ });
2723
+ const ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
2724
+ $ZodNumber.init(inst, def);
2725
+ ZodType.init(inst, def);
2726
+ inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
2727
+ inst.gt = (value, params) => inst.check(/* @__PURE__ */ _gt(value, params));
2728
+ inst.gte = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
2729
+ inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
2730
+ inst.lt = (value, params) => inst.check(/* @__PURE__ */ _lt(value, params));
2731
+ inst.lte = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
2732
+ inst.max = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
2733
+ inst.int = (params) => inst.check(int(params));
2734
+ inst.safe = (params) => inst.check(int(params));
2735
+ inst.positive = (params) => inst.check(/* @__PURE__ */ _gt(0, params));
2736
+ inst.nonnegative = (params) => inst.check(/* @__PURE__ */ _gte(0, params));
2737
+ inst.negative = (params) => inst.check(/* @__PURE__ */ _lt(0, params));
2738
+ inst.nonpositive = (params) => inst.check(/* @__PURE__ */ _lte(0, params));
2739
+ inst.multipleOf = (value, params) => inst.check(/* @__PURE__ */ _multipleOf(value, params));
2740
+ inst.step = (value, params) => inst.check(/* @__PURE__ */ _multipleOf(value, params));
2741
+ inst.finite = () => inst;
2742
+ const bag = inst._zod.bag;
2743
+ inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
2744
+ inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
2745
+ inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
2746
+ inst.isFinite = true;
2747
+ inst.format = bag.format ?? null;
2748
+ });
2749
+ function number(params) {
2750
+ return /* @__PURE__ */ _number(ZodNumber, params);
2751
+ }
2752
+ const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
2753
+ $ZodNumberFormat.init(inst, def);
2754
+ ZodNumber.init(inst, def);
2755
+ });
2756
+ function int(params) {
2757
+ return /* @__PURE__ */ _int(ZodNumberFormat, params);
2758
+ }
2759
+ const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
2760
+ $ZodUnknown.init(inst, def);
2761
+ ZodType.init(inst, def);
2762
+ inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params);
2763
+ });
2764
+ function unknown() {
2765
+ return /* @__PURE__ */ _unknown(ZodUnknown);
2766
+ }
2767
+ const ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
2768
+ $ZodNever.init(inst, def);
2769
+ ZodType.init(inst, def);
2770
+ inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
2771
+ });
2772
+ function never(params) {
2773
+ return /* @__PURE__ */ _never(ZodNever, params);
2774
+ }
2775
+ const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
2776
+ $ZodArray.init(inst, def);
2777
+ ZodType.init(inst, def);
2778
+ inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
2779
+ inst.element = def.element;
2780
+ inst.min = (minLength, params) => inst.check(/* @__PURE__ */ _minLength(minLength, params));
2781
+ inst.nonempty = (params) => inst.check(/* @__PURE__ */ _minLength(1, params));
2782
+ inst.max = (maxLength, params) => inst.check(/* @__PURE__ */ _maxLength(maxLength, params));
2783
+ inst.length = (len, params) => inst.check(/* @__PURE__ */ _length(len, params));
2784
+ inst.unwrap = () => inst.element;
2785
+ });
2786
+ function array(element, params) {
2787
+ return /* @__PURE__ */ _array(ZodArray, element, params);
2788
+ }
2789
+ const ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
2790
+ $ZodObjectJIT.init(inst, def);
2791
+ ZodType.init(inst, def);
2792
+ inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
2793
+ defineLazy(inst, "shape", () => {
2794
+ return def.shape;
2795
+ });
2796
+ inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
2797
+ inst.catchall = (catchall) => inst.clone({
2798
+ ...inst._zod.def,
2799
+ catchall
2800
+ });
2801
+ inst.passthrough = () => inst.clone({
2802
+ ...inst._zod.def,
2803
+ catchall: unknown()
2804
+ });
2805
+ inst.loose = () => inst.clone({
2806
+ ...inst._zod.def,
2807
+ catchall: unknown()
2808
+ });
2809
+ inst.strict = () => inst.clone({
2810
+ ...inst._zod.def,
2811
+ catchall: never()
2812
+ });
2813
+ inst.strip = () => inst.clone({
2814
+ ...inst._zod.def,
2815
+ catchall: void 0
2816
+ });
2817
+ inst.extend = (incoming) => {
2818
+ return extend$1(inst, incoming);
2819
+ };
2820
+ inst.safeExtend = (incoming) => {
2821
+ return safeExtend(inst, incoming);
2822
+ };
2823
+ inst.merge = (other) => merge$1(inst, other);
2824
+ inst.pick = (mask) => pick(inst, mask);
2825
+ inst.omit = (mask) => omit(inst, mask);
2826
+ inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
2827
+ inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
2828
+ });
2829
+ function object(shape, params) {
2830
+ return new ZodObject({
2831
+ type: "object",
2832
+ shape: shape ?? {},
2833
+ ...normalizeParams(params)
2834
+ });
2835
+ }
2836
+ const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
2837
+ $ZodUnion.init(inst, def);
2838
+ ZodType.init(inst, def);
2839
+ inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
2840
+ inst.options = def.options;
2841
+ });
2842
+ function union(options, params) {
2843
+ return new ZodUnion({
2844
+ type: "union",
2845
+ options,
2846
+ ...normalizeParams(params)
2847
+ });
2848
+ }
2849
+ const ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
2850
+ $ZodIntersection.init(inst, def);
2851
+ ZodType.init(inst, def);
2852
+ inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
2853
+ });
2854
+ function intersection(left, right) {
2855
+ return new ZodIntersection({
2856
+ type: "intersection",
2857
+ left,
2858
+ right
2859
+ });
2860
+ }
2861
+ const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
2862
+ $ZodEnum.init(inst, def);
2863
+ ZodType.init(inst, def);
2864
+ inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
2865
+ inst.enum = def.entries;
2866
+ inst.options = Object.values(def.entries);
2867
+ const keys = new Set(Object.keys(def.entries));
2868
+ inst.extract = (values, params) => {
2869
+ const newEntries = {};
2870
+ for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
2871
+ else throw new Error(`Key ${value} not found in enum`);
2872
+ return new ZodEnum({
2873
+ ...def,
2874
+ checks: [],
2875
+ ...normalizeParams(params),
2876
+ entries: newEntries
2877
+ });
2878
+ };
2879
+ inst.exclude = (values, params) => {
2880
+ const newEntries = { ...def.entries };
2881
+ for (const value of values) if (keys.has(value)) delete newEntries[value];
2882
+ else throw new Error(`Key ${value} not found in enum`);
2883
+ return new ZodEnum({
2884
+ ...def,
2885
+ checks: [],
2886
+ ...normalizeParams(params),
2887
+ entries: newEntries
2888
+ });
2889
+ };
2890
+ });
2891
+ function _enum(values, params) {
2892
+ return new ZodEnum({
2893
+ type: "enum",
2894
+ entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values,
2895
+ ...normalizeParams(params)
2896
+ });
2897
+ }
2898
+ const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
2899
+ $ZodTransform.init(inst, def);
2900
+ ZodType.init(inst, def);
2901
+ inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
2902
+ inst._zod.parse = (payload, _ctx) => {
2903
+ if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
2904
+ payload.addIssue = (issue$1) => {
2905
+ if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def));
2906
+ else {
2907
+ const _issue = issue$1;
2908
+ if (_issue.fatal) _issue.continue = false;
2909
+ _issue.code ?? (_issue.code = "custom");
2910
+ _issue.input ?? (_issue.input = payload.value);
2911
+ _issue.inst ?? (_issue.inst = inst);
2912
+ payload.issues.push(issue(_issue));
2913
+ }
2914
+ };
2915
+ const output = def.transform(payload.value, payload);
2916
+ if (output instanceof Promise) return output.then((output) => {
2917
+ payload.value = output;
2918
+ return payload;
2919
+ });
2920
+ payload.value = output;
2921
+ return payload;
2922
+ };
2923
+ });
2924
+ function transform(fn) {
2925
+ return new ZodTransform({
2926
+ type: "transform",
2927
+ transform: fn
2928
+ });
2929
+ }
2930
+ const ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
2931
+ $ZodOptional.init(inst, def);
2932
+ ZodType.init(inst, def);
2933
+ inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
2934
+ inst.unwrap = () => inst._zod.def.innerType;
2935
+ });
2936
+ function optional(innerType) {
2937
+ return new ZodOptional({
2938
+ type: "optional",
2939
+ innerType
2940
+ });
2941
+ }
2942
+ const ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
2943
+ $ZodExactOptional.init(inst, def);
2944
+ ZodType.init(inst, def);
2945
+ inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
2946
+ inst.unwrap = () => inst._zod.def.innerType;
2947
+ });
2948
+ function exactOptional(innerType) {
2949
+ return new ZodExactOptional({
2950
+ type: "optional",
2951
+ innerType
2952
+ });
2953
+ }
2954
+ const ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
2955
+ $ZodNullable.init(inst, def);
2956
+ ZodType.init(inst, def);
2957
+ inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
2958
+ inst.unwrap = () => inst._zod.def.innerType;
2959
+ });
2960
+ function nullable(innerType) {
2961
+ return new ZodNullable({
2962
+ type: "nullable",
2963
+ innerType
2964
+ });
2965
+ }
2966
+ const ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
2967
+ $ZodDefault.init(inst, def);
2968
+ ZodType.init(inst, def);
2969
+ inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
2970
+ inst.unwrap = () => inst._zod.def.innerType;
2971
+ inst.removeDefault = inst.unwrap;
2972
+ });
2973
+ function _default(innerType, defaultValue) {
2974
+ return new ZodDefault({
2975
+ type: "default",
2976
+ innerType,
2977
+ get defaultValue() {
2978
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
2979
+ }
2980
+ });
2981
+ }
2982
+ const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
2983
+ $ZodPrefault.init(inst, def);
2984
+ ZodType.init(inst, def);
2985
+ inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
2986
+ inst.unwrap = () => inst._zod.def.innerType;
2987
+ });
2988
+ function prefault(innerType, defaultValue) {
2989
+ return new ZodPrefault({
2990
+ type: "prefault",
2991
+ innerType,
2992
+ get defaultValue() {
2993
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
2994
+ }
2995
+ });
2996
+ }
2997
+ const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
2998
+ $ZodNonOptional.init(inst, def);
2999
+ ZodType.init(inst, def);
3000
+ inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
3001
+ inst.unwrap = () => inst._zod.def.innerType;
3002
+ });
3003
+ function nonoptional(innerType, params) {
3004
+ return new ZodNonOptional({
3005
+ type: "nonoptional",
3006
+ innerType,
3007
+ ...normalizeParams(params)
3008
+ });
3009
+ }
3010
+ const ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
3011
+ $ZodCatch.init(inst, def);
3012
+ ZodType.init(inst, def);
3013
+ inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
3014
+ inst.unwrap = () => inst._zod.def.innerType;
3015
+ inst.removeCatch = inst.unwrap;
3016
+ });
3017
+ function _catch(innerType, catchValue) {
3018
+ return new ZodCatch({
3019
+ type: "catch",
3020
+ innerType,
3021
+ catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
3022
+ });
3023
+ }
3024
+ const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
3025
+ $ZodPipe.init(inst, def);
3026
+ ZodType.init(inst, def);
3027
+ inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
3028
+ inst.in = def.in;
3029
+ inst.out = def.out;
3030
+ });
3031
+ function pipe(in_, out) {
3032
+ return new ZodPipe({
3033
+ type: "pipe",
3034
+ in: in_,
3035
+ out
3036
+ });
3037
+ }
3038
+ const ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
3039
+ $ZodReadonly.init(inst, def);
3040
+ ZodType.init(inst, def);
3041
+ inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
3042
+ inst.unwrap = () => inst._zod.def.innerType;
3043
+ });
3044
+ function readonly(innerType) {
3045
+ return new ZodReadonly({
3046
+ type: "readonly",
3047
+ innerType
3048
+ });
3049
+ }
3050
+ const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
3051
+ $ZodCustom.init(inst, def);
3052
+ ZodType.init(inst, def);
3053
+ inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
3054
+ });
3055
+ function refine(fn, _params = {}) {
3056
+ return /* @__PURE__ */ _refine(ZodCustom, fn, _params);
3057
+ }
3058
+ function superRefine(fn) {
3059
+ return /* @__PURE__ */ _superRefine(fn);
3060
+ }
3061
+ enumValues({
3062
+ Active: "active",
3063
+ PastDue: "past_due",
3064
+ Canceled: "canceled",
3065
+ Incomplete: "incomplete"
3066
+ });
3067
+ enumValues({
3068
+ Anthropic: "anthropic",
3069
+ OpenAI: "openai"
3070
+ });
3071
+ enumValues({
3072
+ Month: "month",
3073
+ Year: "year"
3074
+ });
3075
+ object({ gracePeriodDays: number().int().positive().optional() });
3076
+ enumValues({
3077
+ Active: "active",
3078
+ Inactive: "inactive",
3079
+ Deleted: "deleted"
3080
+ });
3081
+ enumValues({
3082
+ SelfHosted: "self-hosted",
3083
+ Managed: "managed"
3084
+ });
3085
+ enumValues({
3086
+ OpenClaw: "openclaw",
3087
+ NanoClaw: "nanoclaw"
3088
+ });
3089
+ enumValues({
3090
+ None: "none",
3091
+ Pending: "pending",
3092
+ Provisioning: "provisioning",
3093
+ Running: "running",
3094
+ Stopped: "stopped",
3095
+ Failed: "failed",
3096
+ BillingSuspended: "billing_suspended"
3097
+ });
3098
+ enumValues({
3099
+ Active: "active",
3100
+ Removed: "removed"
3101
+ });
3102
+ enumValues({
3103
+ Installing: "installing",
3104
+ Active: "active",
3105
+ Error: "error",
3106
+ Removing: "removing",
3107
+ Inactive: "inactive",
3108
+ Unknown: "unknown"
3109
+ });
3110
+ enumValues({
3111
+ Active: "active",
3112
+ Depleted: "depleted",
3113
+ Paused: "paused"
3114
+ });
3115
+ enumValues({
3116
+ Usage: "usage",
3117
+ TopUp: "top_up",
3118
+ SubscriptionCredit: "subscription_credit",
3119
+ AutoRecharge: "auto_recharge",
3120
+ AdminGift: "admin_gift",
3121
+ Refund: "refund"
3122
+ });
3123
+ enumValues({
3124
+ Pending: "pending",
3125
+ Completed: "completed",
3126
+ Failed: "failed"
3127
+ });
3128
+ enumValues({
3129
+ Hour: "hour",
3130
+ Day: "day",
3131
+ Week: "week",
3132
+ Month: "month"
3133
+ });
3134
+ enumValues({
3135
+ Synced: "synced",
3136
+ Stale: "stale",
3137
+ Error: "error"
3138
+ });
3139
+ enumValues({
3140
+ Standard: "STANDARD",
3141
+ GlacierIR: "GLACIER_IR"
3142
+ });
3143
+ enumValues({
3144
+ Push: "push",
3145
+ Pull: "pull",
3146
+ Delete: "delete",
3147
+ Restore: "restore"
3148
+ });
3149
+ enumValues({
3150
+ Success: "success",
3151
+ Error: "error"
3152
+ });
3153
+ enumValues({
3154
+ User: "user",
3155
+ Agent: "agent",
3156
+ Support: "support"
3157
+ });
3158
+ enumValues({
3159
+ Dev: "dev",
3160
+ Test: "test",
3161
+ Live: "live"
3162
+ });
3163
+ //#endregion
3164
+ //#region src/config.ts
3165
+ /**
3166
+ * Daemon configuration — reads ~/.alfe/config.toml and resolves agent identity.
3167
+ *
3168
+ * Bootstrap flow:
3169
+ * 1. Read api_key from ~/.alfe/config.toml (via @alfe.ai/config)
3170
+ * 2. Derive API endpoint from token prefix
3171
+ * 3. Call /auth/validate to get tenantId (orgId)
3172
+ * 4. Use tokenId as agent identity for cloud registration
3173
+ */
3174
+ const ALFE_DIR = join(homedir(), ".alfe");
3175
+ const SOCKET_PATH = join(ALFE_DIR, "gateway.sock");
3176
+ const PID_PATH = join(ALFE_DIR, "gateway.pid");
3177
+ /**
3178
+ * Resolve agent identity by validating the api_key with the auth service.
3179
+ * Returns agentId (derived from tokenId) and orgId (tenantId).
3180
+ */
3181
+ async function resolveAgentIdentity(apiKey, apiEndpoint) {
3182
+ const auth = new AuthService(new AlfeApiClient({
3183
+ apiBaseUrl: apiEndpoint,
3184
+ getToken: () => Promise.resolve(apiKey)
3185
+ }));
3186
+ const maxAttempts = 3;
3187
+ const delayMs = 3e3;
3188
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
3189
+ const result = await auth.validate(apiKey);
3190
+ if (!result.ok) {
3191
+ if (result.status === 401 || result.status === 403) throw new Error(`Token validation failed: ${result.error}. Is your API key valid? Run \`alfe login\` to reconfigure.`);
3192
+ if (attempt < maxAttempts) {
3193
+ await new Promise((r) => setTimeout(r, delayMs));
3194
+ continue;
3195
+ }
3196
+ throw new Error(`Token validation failed after ${String(maxAttempts)} attempts: ${result.error}. Is your API key valid? Run \`alfe login\` to reconfigure.`);
3197
+ }
3198
+ if (!result.data.valid) throw new Error("API key invalid: validation failed. Run `alfe login` to reconfigure.");
3199
+ const orgId = result.data.tenantId;
3200
+ if (!orgId) throw new Error("Token validation returned no tenantId — cannot determine org.");
3201
+ return {
3202
+ agentId: result.data.tokenId ?? deriveAgentId(apiKey),
3203
+ orgId,
3204
+ runtime: result.data.runtime ?? "openclaw"
3205
+ };
3206
+ }
3207
+ throw new Error("Token validation failed: exhausted retries.");
3208
+ }
3209
+ /**
3210
+ * Derive a stable agent ID from an API key (fallback when tokenId not available).
3211
+ */
3212
+ function deriveAgentId(apiKey) {
3213
+ let hash = 0;
3214
+ for (let i = 0; i < apiKey.length; i++) {
3215
+ const chr = apiKey.charCodeAt(i);
3216
+ hash = (hash << 5) - hash + chr | 0;
3217
+ }
3218
+ return `agent-${Math.abs(hash).toString(36)}`;
3219
+ }
3220
+ /**
3221
+ * Derive the cloud gateway WebSocket URL from the API endpoint.
3222
+ * The cloud gateway runs on Fly.io — its URL follows a convention.
3223
+ */
3224
+ function deriveGatewayWsUrl(apiEndpoint) {
3225
+ if (apiEndpoint.includes("dev.alfe.ai")) return process.env.ALFE_GATEWAY_WS_URL ?? "wss://gateway.dev.alfe.ai/ws";
3226
+ if (apiEndpoint.includes("test.alfe.ai")) return process.env.ALFE_GATEWAY_WS_URL ?? "wss://gateway.test.alfe.ai/ws";
3227
+ return process.env.ALFE_GATEWAY_WS_URL ?? "wss://gateway.alfe.ai/ws";
3228
+ }
3229
+ /**
3230
+ * Parse [runtimes.*] sections from config.toml.
3231
+ * Returns a map of runtime name → RuntimeConfig.
3232
+ *
3233
+ * Example config.toml:
3234
+ * [runtimes.openclaw]
3235
+ * workspace = "~/.openclaw"
3236
+ */
3237
+ async function loadRuntimeConfigs() {
3238
+ const configPath = join(ALFE_DIR, "config.toml");
3239
+ if (!existsSync(configPath)) return {};
3240
+ try {
3241
+ const runtimes = parse(await readFile(configPath, "utf-8")).runtimes;
3242
+ if (!runtimes) return {};
3243
+ const result = {};
3244
+ for (const [name, cfg] of Object.entries(runtimes)) if (typeof cfg.workspace === "string") result[name] = { workspace: cfg.workspace.startsWith("~/") ? join(homedir(), cfg.workspace.slice(2)) : cfg.workspace };
3245
+ return result;
3246
+ } catch {
3247
+ return {};
3248
+ }
3249
+ }
3250
+ /**
3251
+ * Whether the daemon is running in managed mode (ECS Fargate container).
3252
+ * In managed mode, configuration comes from environment variables instead
3253
+ * of ~/.alfe/config.toml, and IPC/PID features are disabled.
3254
+ */
3255
+ function isManagedMode() {
3256
+ return process.env.ALFE_MANAGED === "true";
3257
+ }
3258
+ /**
3259
+ * Load configuration for managed mode (ECS Fargate).
3260
+ * All config comes from environment variables — no local files needed.
3261
+ */
3262
+ async function loadManagedConfig() {
3263
+ const apiKey = process.env.ALFE_API_KEY;
3264
+ const apiEndpoint = process.env.ALFE_API_ENDPOINT;
3265
+ if (!apiKey || !apiEndpoint) throw new Error("ALFE_API_KEY and ALFE_API_ENDPOINT required in managed mode");
3266
+ const identity = await resolveAgentIdentity(apiKey, apiEndpoint);
3267
+ return {
3268
+ apiKey,
3269
+ apiEndpoint,
3270
+ gatewayWsUrl: process.env.ALFE_GATEWAY_WS_URL ?? deriveGatewayWsUrl(apiEndpoint),
3271
+ socketPath: "",
3272
+ pidPath: "",
3273
+ agentId: identity.agentId,
3274
+ orgId: identity.orgId,
3275
+ runtime: identity.runtime,
3276
+ runtimes: identity.runtime === "openclaw" ? { openclaw: { workspace: join(homedir(), ".openclaw") } } : {}
3277
+ };
3278
+ }
3279
+ /**
3280
+ * Load full daemon configuration.
3281
+ * Reads config.toml, validates the API key, resolves agent identity,
3282
+ * and parses runtime configurations.
3283
+ *
3284
+ * In managed mode, loads from environment variables instead.
3285
+ */
3286
+ async function loadDaemonConfig() {
3287
+ if (isManagedMode()) return loadManagedConfig();
3288
+ let alfeConfig;
3289
+ try {
3290
+ alfeConfig = await readConfig();
3291
+ } catch {
3292
+ throw new Error("Alfe not configured. Run `alfe login` first.");
3293
+ }
3294
+ const apiEndpoint = alfeConfig.gateway ?? getEndpointFromToken(alfeConfig.api_key);
3295
+ const identity = await resolveAgentIdentity(alfeConfig.api_key, apiEndpoint);
3296
+ const gatewayWsUrl = alfeConfig.gateway_url ?? deriveGatewayWsUrl(apiEndpoint);
3297
+ const runtimes = await loadRuntimeConfigs();
3298
+ return {
3299
+ apiKey: alfeConfig.api_key,
3300
+ apiEndpoint,
3301
+ gatewayWsUrl,
3302
+ socketPath: process.env.ALFE_GATEWAY_SOCKET ?? SOCKET_PATH,
3303
+ pidPath: PID_PATH,
3304
+ agentId: identity.agentId,
3305
+ orgId: identity.orgId,
3306
+ runtime: identity.runtime,
3307
+ runtimes
3308
+ };
3309
+ }
3310
+ /**
3311
+ * Fetch agent workspace config from the API.
3312
+ *
3313
+ * 1. GET /agents/me/workspace → { templateKey }
3314
+ * 2. If templateKey set, GET /templates/:key/files → persona file contents
3315
+ *
3316
+ * Returns null if the agent has no template assigned or the fetch fails.
3317
+ */
3318
+ async function fetchAgentConfig(apiKey, apiEndpoint) {
3319
+ try {
3320
+ const wsResponse = await fetch(`${apiEndpoint}/agents/me/workspace`, {
3321
+ method: "GET",
3322
+ headers: { "Authorization": `Bearer ${apiKey}` }
3323
+ });
3324
+ if (!wsResponse.ok) return null;
3325
+ const templateKey = (await wsResponse.json()).data?.templateKey;
3326
+ if (!templateKey) return null;
3327
+ const filesResponse = await fetch(`${apiEndpoint}/templates/${encodeURIComponent(templateKey)}/files`, {
3328
+ method: "GET",
3329
+ headers: { "Authorization": `Bearer ${apiKey}` }
3330
+ });
3331
+ if (!filesResponse.ok) return {
3332
+ templateKey,
3333
+ files: {}
3334
+ };
3335
+ return {
3336
+ templateKey,
3337
+ files: (await filesResponse.json()).data?.files ?? {}
3338
+ };
3339
+ } catch {
3340
+ return null;
3341
+ }
3342
+ }
3343
+ //#endregion
430
3344
  //#region src/protocol.ts
431
3345
  /**
432
3346
  * Map a cloud command name to an IPC method name.