@tempad-dev/mcp 0.3.4 → 0.3.6

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.
package/dist/hub.mjs ADDED
@@ -0,0 +1,4321 @@
1
+ import { a as SOCK_PATH, c as log, i as RUNTIME_DIR, o as ensureDir, r as PACKAGE_VERSION, s as ensureFile, t as ASSET_DIR } from "./shared-DisdM-7P.mjs";
2
+ import { createServer } from "node:net";
3
+ import { dirname, join } from "node:path";
4
+ import { URL as URL$1, fileURLToPath } from "node:url";
5
+ import { chmodSync, createReadStream, createWriteStream, existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { nanoid } from "nanoid";
9
+ import { WebSocketServer } from "ws";
10
+ import { createHash } from "node:crypto";
11
+ import { createServer as createServer$1 } from "node:http";
12
+ import { Transform, pipeline } from "node:stream";
13
+
14
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/core.js
15
+ /** A special constant with type `never` */
16
+ const NEVER = Object.freeze({ status: "aborted" });
17
+ function $constructor(name, initializer$2, params) {
18
+ function init(inst, def) {
19
+ var _a;
20
+ Object.defineProperty(inst, "_zod", {
21
+ value: inst._zod ?? {},
22
+ enumerable: false
23
+ });
24
+ (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set());
25
+ inst._zod.traits.add(name);
26
+ initializer$2(inst, def);
27
+ for (const k in _.prototype) if (!(k in inst)) Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
28
+ inst._zod.constr = _;
29
+ inst._zod.def = def;
30
+ }
31
+ const Parent = params?.Parent ?? Object;
32
+ class Definition extends Parent {}
33
+ Object.defineProperty(Definition, "name", { value: name });
34
+ function _(def) {
35
+ var _a;
36
+ const inst = params?.Parent ? new Definition() : this;
37
+ init(inst, def);
38
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
39
+ for (const fn of inst._zod.deferred) fn();
40
+ return inst;
41
+ }
42
+ Object.defineProperty(_, "init", { value: init });
43
+ Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
44
+ if (params?.Parent && inst instanceof params.Parent) return true;
45
+ return inst?._zod?.traits?.has(name);
46
+ } });
47
+ Object.defineProperty(_, "name", { value: name });
48
+ return _;
49
+ }
50
+ var $ZodAsyncError = class extends Error {
51
+ constructor() {
52
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
53
+ }
54
+ };
55
+ var $ZodEncodeError = class extends Error {
56
+ constructor(name) {
57
+ super(`Encountered unidirectional transform during encode: ${name}`);
58
+ this.name = "ZodEncodeError";
59
+ }
60
+ };
61
+ const globalConfig = {};
62
+ function config(newConfig) {
63
+ if (newConfig) Object.assign(globalConfig, newConfig);
64
+ return globalConfig;
65
+ }
66
+
67
+ //#endregion
68
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/util.js
69
+ function getEnumValues(entries) {
70
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
71
+ return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
72
+ }
73
+ function jsonStringifyReplacer(_, value) {
74
+ if (typeof value === "bigint") return value.toString();
75
+ return value;
76
+ }
77
+ function cached(getter) {
78
+ return { get value() {
79
+ {
80
+ const value = getter();
81
+ Object.defineProperty(this, "value", { value });
82
+ return value;
83
+ }
84
+ throw new Error("cached value already set");
85
+ } };
86
+ }
87
+ function nullish(input) {
88
+ return input === null || input === void 0;
89
+ }
90
+ function cleanRegex(source) {
91
+ const start = source.startsWith("^") ? 1 : 0;
92
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
93
+ return source.slice(start, end);
94
+ }
95
+ function floatSafeRemainder(val, step) {
96
+ const valDecCount = (val.toString().split(".")[1] || "").length;
97
+ const stepString = step.toString();
98
+ let stepDecCount = (stepString.split(".")[1] || "").length;
99
+ if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
100
+ const match = stepString.match(/\d?e-(\d?)/);
101
+ if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
102
+ }
103
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
104
+ return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
105
+ }
106
+ const EVALUATING = Symbol("evaluating");
107
+ function defineLazy(object$1, key, getter) {
108
+ let value = void 0;
109
+ Object.defineProperty(object$1, key, {
110
+ get() {
111
+ if (value === EVALUATING) return;
112
+ if (value === void 0) {
113
+ value = EVALUATING;
114
+ value = getter();
115
+ }
116
+ return value;
117
+ },
118
+ set(v) {
119
+ Object.defineProperty(object$1, key, { value: v });
120
+ },
121
+ configurable: true
122
+ });
123
+ }
124
+ function assignProp(target, prop, value) {
125
+ Object.defineProperty(target, prop, {
126
+ value,
127
+ writable: true,
128
+ enumerable: true,
129
+ configurable: true
130
+ });
131
+ }
132
+ function mergeDefs(...defs) {
133
+ const mergedDescriptors = {};
134
+ for (const def of defs) {
135
+ const descriptors = Object.getOwnPropertyDescriptors(def);
136
+ Object.assign(mergedDescriptors, descriptors);
137
+ }
138
+ return Object.defineProperties({}, mergedDescriptors);
139
+ }
140
+ function esc(str) {
141
+ return JSON.stringify(str);
142
+ }
143
+ const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
144
+ function isObject(data) {
145
+ return typeof data === "object" && data !== null && !Array.isArray(data);
146
+ }
147
+ const allowsEval = cached(() => {
148
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
149
+ try {
150
+ new Function("");
151
+ return true;
152
+ } catch (_) {
153
+ return false;
154
+ }
155
+ });
156
+ function isPlainObject(o) {
157
+ if (isObject(o) === false) return false;
158
+ const ctor = o.constructor;
159
+ if (ctor === void 0) return true;
160
+ const prot = ctor.prototype;
161
+ if (isObject(prot) === false) return false;
162
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
163
+ return true;
164
+ }
165
+ function shallowClone(o) {
166
+ if (isPlainObject(o)) return { ...o };
167
+ if (Array.isArray(o)) return [...o];
168
+ return o;
169
+ }
170
+ const propertyKeyTypes = new Set([
171
+ "string",
172
+ "number",
173
+ "symbol"
174
+ ]);
175
+ function escapeRegex(str) {
176
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
177
+ }
178
+ function clone(inst, def, params) {
179
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
180
+ if (!def || params?.parent) cl._zod.parent = inst;
181
+ return cl;
182
+ }
183
+ function normalizeParams(_params) {
184
+ const params = _params;
185
+ if (!params) return {};
186
+ if (typeof params === "string") return { error: () => params };
187
+ if (params?.message !== void 0) {
188
+ if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
189
+ params.error = params.message;
190
+ }
191
+ delete params.message;
192
+ if (typeof params.error === "string") return {
193
+ ...params,
194
+ error: () => params.error
195
+ };
196
+ return params;
197
+ }
198
+ function optionalKeys(shape) {
199
+ return Object.keys(shape).filter((k) => {
200
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
201
+ });
202
+ }
203
+ const NUMBER_FORMAT_RANGES = {
204
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
205
+ int32: [-2147483648, 2147483647],
206
+ uint32: [0, 4294967295],
207
+ float32: [-34028234663852886e22, 34028234663852886e22],
208
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
209
+ };
210
+ function pick(schema, mask) {
211
+ const currDef = schema._zod.def;
212
+ return clone(schema, mergeDefs(schema._zod.def, {
213
+ get shape() {
214
+ const newShape = {};
215
+ for (const key in mask) {
216
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
217
+ if (!mask[key]) continue;
218
+ newShape[key] = currDef.shape[key];
219
+ }
220
+ assignProp(this, "shape", newShape);
221
+ return newShape;
222
+ },
223
+ checks: []
224
+ }));
225
+ }
226
+ function omit(schema, mask) {
227
+ const currDef = schema._zod.def;
228
+ return clone(schema, mergeDefs(schema._zod.def, {
229
+ get shape() {
230
+ const newShape = { ...schema._zod.def.shape };
231
+ for (const key in mask) {
232
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
233
+ if (!mask[key]) continue;
234
+ delete newShape[key];
235
+ }
236
+ assignProp(this, "shape", newShape);
237
+ return newShape;
238
+ },
239
+ checks: []
240
+ }));
241
+ }
242
+ function extend(schema, shape) {
243
+ if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
244
+ const checks = schema._zod.def.checks;
245
+ if (checks && checks.length > 0) throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");
246
+ return clone(schema, mergeDefs(schema._zod.def, {
247
+ get shape() {
248
+ const _shape = {
249
+ ...schema._zod.def.shape,
250
+ ...shape
251
+ };
252
+ assignProp(this, "shape", _shape);
253
+ return _shape;
254
+ },
255
+ checks: []
256
+ }));
257
+ }
258
+ function safeExtend(schema, shape) {
259
+ if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
260
+ return clone(schema, {
261
+ ...schema._zod.def,
262
+ get shape() {
263
+ const _shape = {
264
+ ...schema._zod.def.shape,
265
+ ...shape
266
+ };
267
+ assignProp(this, "shape", _shape);
268
+ return _shape;
269
+ },
270
+ checks: schema._zod.def.checks
271
+ });
272
+ }
273
+ function merge(a, b) {
274
+ return clone(a, mergeDefs(a._zod.def, {
275
+ get shape() {
276
+ const _shape = {
277
+ ...a._zod.def.shape,
278
+ ...b._zod.def.shape
279
+ };
280
+ assignProp(this, "shape", _shape);
281
+ return _shape;
282
+ },
283
+ get catchall() {
284
+ return b._zod.def.catchall;
285
+ },
286
+ checks: []
287
+ }));
288
+ }
289
+ function partial(Class, schema, mask) {
290
+ return clone(schema, mergeDefs(schema._zod.def, {
291
+ get shape() {
292
+ const oldShape = schema._zod.def.shape;
293
+ const shape = { ...oldShape };
294
+ if (mask) for (const key in mask) {
295
+ if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
296
+ if (!mask[key]) continue;
297
+ shape[key] = Class ? new Class({
298
+ type: "optional",
299
+ innerType: oldShape[key]
300
+ }) : oldShape[key];
301
+ }
302
+ else for (const key in oldShape) shape[key] = Class ? new Class({
303
+ type: "optional",
304
+ innerType: oldShape[key]
305
+ }) : oldShape[key];
306
+ assignProp(this, "shape", shape);
307
+ return shape;
308
+ },
309
+ checks: []
310
+ }));
311
+ }
312
+ function required(Class, schema, mask) {
313
+ return clone(schema, mergeDefs(schema._zod.def, {
314
+ get shape() {
315
+ const oldShape = schema._zod.def.shape;
316
+ const shape = { ...oldShape };
317
+ if (mask) for (const key in mask) {
318
+ if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
319
+ if (!mask[key]) continue;
320
+ shape[key] = new Class({
321
+ type: "nonoptional",
322
+ innerType: oldShape[key]
323
+ });
324
+ }
325
+ else for (const key in oldShape) shape[key] = new Class({
326
+ type: "nonoptional",
327
+ innerType: oldShape[key]
328
+ });
329
+ assignProp(this, "shape", shape);
330
+ return shape;
331
+ },
332
+ checks: []
333
+ }));
334
+ }
335
+ function aborted(x, startIndex = 0) {
336
+ if (x.aborted === true) return true;
337
+ for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
338
+ return false;
339
+ }
340
+ function prefixIssues(path, issues) {
341
+ return issues.map((iss) => {
342
+ var _a;
343
+ (_a = iss).path ?? (_a.path = []);
344
+ iss.path.unshift(path);
345
+ return iss;
346
+ });
347
+ }
348
+ function unwrapMessage(message) {
349
+ return typeof message === "string" ? message : message?.message;
350
+ }
351
+ function finalizeIssue(iss, ctx, config$1) {
352
+ const full = {
353
+ ...iss,
354
+ path: iss.path ?? []
355
+ };
356
+ if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config$1.customError?.(iss)) ?? unwrapMessage(config$1.localeError?.(iss)) ?? "Invalid input";
357
+ delete full.inst;
358
+ delete full.continue;
359
+ if (!ctx?.reportInput) delete full.input;
360
+ return full;
361
+ }
362
+ function getLengthableOrigin(input) {
363
+ if (Array.isArray(input)) return "array";
364
+ if (typeof input === "string") return "string";
365
+ return "unknown";
366
+ }
367
+ function issue(...args) {
368
+ const [iss, input, inst] = args;
369
+ if (typeof iss === "string") return {
370
+ message: iss,
371
+ code: "custom",
372
+ input,
373
+ inst
374
+ };
375
+ return { ...iss };
376
+ }
377
+
378
+ //#endregion
379
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/errors.js
380
+ const initializer$1 = (inst, def) => {
381
+ inst.name = "$ZodError";
382
+ Object.defineProperty(inst, "_zod", {
383
+ value: inst._zod,
384
+ enumerable: false
385
+ });
386
+ Object.defineProperty(inst, "issues", {
387
+ value: def,
388
+ enumerable: false
389
+ });
390
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
391
+ Object.defineProperty(inst, "toString", {
392
+ value: () => inst.message,
393
+ enumerable: false
394
+ });
395
+ };
396
+ const $ZodError = $constructor("$ZodError", initializer$1);
397
+ const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
398
+ function flattenError(error, mapper = (issue$1) => issue$1.message) {
399
+ const fieldErrors = {};
400
+ const formErrors = [];
401
+ for (const sub of error.issues) if (sub.path.length > 0) {
402
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
403
+ fieldErrors[sub.path[0]].push(mapper(sub));
404
+ } else formErrors.push(mapper(sub));
405
+ return {
406
+ formErrors,
407
+ fieldErrors
408
+ };
409
+ }
410
+ function formatError(error, mapper = (issue$1) => issue$1.message) {
411
+ const fieldErrors = { _errors: [] };
412
+ const processError = (error$1) => {
413
+ for (const issue$1 of error$1.issues) if (issue$1.code === "invalid_union" && issue$1.errors.length) issue$1.errors.map((issues) => processError({ issues }));
414
+ else if (issue$1.code === "invalid_key") processError({ issues: issue$1.issues });
415
+ else if (issue$1.code === "invalid_element") processError({ issues: issue$1.issues });
416
+ else if (issue$1.path.length === 0) fieldErrors._errors.push(mapper(issue$1));
417
+ else {
418
+ let curr = fieldErrors;
419
+ let i = 0;
420
+ while (i < issue$1.path.length) {
421
+ const el = issue$1.path[i];
422
+ if (!(i === issue$1.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
423
+ else {
424
+ curr[el] = curr[el] || { _errors: [] };
425
+ curr[el]._errors.push(mapper(issue$1));
426
+ }
427
+ curr = curr[el];
428
+ i++;
429
+ }
430
+ }
431
+ };
432
+ processError(error);
433
+ return fieldErrors;
434
+ }
435
+
436
+ //#endregion
437
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/parse.js
438
+ const _parse = (_Err) => (schema, value, _ctx, _params) => {
439
+ const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
440
+ const result = schema._zod.run({
441
+ value,
442
+ issues: []
443
+ }, ctx);
444
+ if (result instanceof Promise) throw new $ZodAsyncError();
445
+ if (result.issues.length) {
446
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
447
+ captureStackTrace(e, _params?.callee);
448
+ throw e;
449
+ }
450
+ return result.value;
451
+ };
452
+ const parse$1 = /* @__PURE__ */ _parse($ZodRealError);
453
+ const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
454
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
455
+ let result = schema._zod.run({
456
+ value,
457
+ issues: []
458
+ }, ctx);
459
+ if (result instanceof Promise) result = await result;
460
+ if (result.issues.length) {
461
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
462
+ captureStackTrace(e, params?.callee);
463
+ throw e;
464
+ }
465
+ return result.value;
466
+ };
467
+ const parseAsync$1 = /* @__PURE__ */ _parseAsync($ZodRealError);
468
+ const _safeParse = (_Err) => (schema, value, _ctx) => {
469
+ const ctx = _ctx ? {
470
+ ..._ctx,
471
+ async: false
472
+ } : { async: false };
473
+ const result = schema._zod.run({
474
+ value,
475
+ issues: []
476
+ }, ctx);
477
+ if (result instanceof Promise) throw new $ZodAsyncError();
478
+ return result.issues.length ? {
479
+ success: false,
480
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
481
+ } : {
482
+ success: true,
483
+ data: result.value
484
+ };
485
+ };
486
+ const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
487
+ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
488
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
489
+ let result = schema._zod.run({
490
+ value,
491
+ issues: []
492
+ }, ctx);
493
+ if (result instanceof Promise) result = await result;
494
+ return result.issues.length ? {
495
+ success: false,
496
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
497
+ } : {
498
+ success: true,
499
+ data: result.value
500
+ };
501
+ };
502
+ const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
503
+ const _encode = (_Err) => (schema, value, _ctx) => {
504
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
505
+ return _parse(_Err)(schema, value, ctx);
506
+ };
507
+ const encode$1 = /* @__PURE__ */ _encode($ZodRealError);
508
+ const _decode = (_Err) => (schema, value, _ctx) => {
509
+ return _parse(_Err)(schema, value, _ctx);
510
+ };
511
+ const decode$1 = /* @__PURE__ */ _decode($ZodRealError);
512
+ const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
513
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
514
+ return _parseAsync(_Err)(schema, value, ctx);
515
+ };
516
+ const encodeAsync$1 = /* @__PURE__ */ _encodeAsync($ZodRealError);
517
+ const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
518
+ return _parseAsync(_Err)(schema, value, _ctx);
519
+ };
520
+ const decodeAsync$1 = /* @__PURE__ */ _decodeAsync($ZodRealError);
521
+ const _safeEncode = (_Err) => (schema, value, _ctx) => {
522
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
523
+ return _safeParse(_Err)(schema, value, ctx);
524
+ };
525
+ const safeEncode$1 = /* @__PURE__ */ _safeEncode($ZodRealError);
526
+ const _safeDecode = (_Err) => (schema, value, _ctx) => {
527
+ return _safeParse(_Err)(schema, value, _ctx);
528
+ };
529
+ const safeDecode$1 = /* @__PURE__ */ _safeDecode($ZodRealError);
530
+ const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
531
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
532
+ return _safeParseAsync(_Err)(schema, value, ctx);
533
+ };
534
+ const safeEncodeAsync$1 = /* @__PURE__ */ _safeEncodeAsync($ZodRealError);
535
+ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
536
+ return _safeParseAsync(_Err)(schema, value, _ctx);
537
+ };
538
+ const safeDecodeAsync$1 = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);
539
+
540
+ //#endregion
541
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/regexes.js
542
+ const cuid = /^[cC][^\s-]{8,}$/;
543
+ const cuid2 = /^[0-9a-z]+$/;
544
+ const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
545
+ const xid = /^[0-9a-vA-V]{20}$/;
546
+ const ksuid = /^[A-Za-z0-9]{27}$/;
547
+ const nanoid$1 = /^[a-zA-Z0-9_-]{21}$/;
548
+ /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
549
+ const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
550
+ /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
551
+ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
552
+ /** Returns a regex for validating an RFC 9562/4122 UUID.
553
+ *
554
+ * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
555
+ const uuid = (version$1) => {
556
+ if (!version$1) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
557
+ return /* @__PURE__ */ new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version$1}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
558
+ };
559
+ /** Practical email validation */
560
+ const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
561
+ const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
562
+ function emoji() {
563
+ return new RegExp(_emoji$1, "u");
564
+ }
565
+ const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
566
+ const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
567
+ const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
568
+ const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
569
+ const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
570
+ const base64url = /^[A-Za-z0-9_-]*$/;
571
+ const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
572
+ const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
573
+ const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
574
+ const date$1 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
575
+ function timeSource(args) {
576
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
577
+ return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
578
+ }
579
+ function time$1(args) {
580
+ return /* @__PURE__ */ new RegExp(`^${timeSource(args)}$`);
581
+ }
582
+ function datetime$1(args) {
583
+ const time$2 = timeSource({ precision: args.precision });
584
+ const opts = ["Z"];
585
+ if (args.local) opts.push("");
586
+ if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
587
+ const timeRegex = `${time$2}(?:${opts.join("|")})`;
588
+ return /* @__PURE__ */ new RegExp(`^${dateSource}T(?:${timeRegex})$`);
589
+ }
590
+ const string$1 = (params) => {
591
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
592
+ return /* @__PURE__ */ new RegExp(`^${regex}$`);
593
+ };
594
+ const integer = /^-?\d+$/;
595
+ const number$1 = /^-?\d+(?:\.\d+)?/;
596
+ const boolean$1 = /^(?:true|false)$/i;
597
+ const lowercase = /^[^A-Z]*$/;
598
+ const uppercase = /^[^a-z]*$/;
599
+
600
+ //#endregion
601
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/checks.js
602
+ const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
603
+ var _a;
604
+ inst._zod ?? (inst._zod = {});
605
+ inst._zod.def = def;
606
+ (_a = inst._zod).onattach ?? (_a.onattach = []);
607
+ });
608
+ const numericOriginMap = {
609
+ number: "number",
610
+ bigint: "bigint",
611
+ object: "date"
612
+ };
613
+ const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
614
+ $ZodCheck.init(inst, def);
615
+ const origin = numericOriginMap[typeof def.value];
616
+ inst._zod.onattach.push((inst$1) => {
617
+ const bag = inst$1._zod.bag;
618
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
619
+ if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
620
+ else bag.exclusiveMaximum = def.value;
621
+ });
622
+ inst._zod.check = (payload) => {
623
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
624
+ payload.issues.push({
625
+ origin,
626
+ code: "too_big",
627
+ maximum: def.value,
628
+ input: payload.value,
629
+ inclusive: def.inclusive,
630
+ inst,
631
+ continue: !def.abort
632
+ });
633
+ };
634
+ });
635
+ const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
636
+ $ZodCheck.init(inst, def);
637
+ const origin = numericOriginMap[typeof def.value];
638
+ inst._zod.onattach.push((inst$1) => {
639
+ const bag = inst$1._zod.bag;
640
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
641
+ if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
642
+ else bag.exclusiveMinimum = def.value;
643
+ });
644
+ inst._zod.check = (payload) => {
645
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
646
+ payload.issues.push({
647
+ origin,
648
+ code: "too_small",
649
+ minimum: def.value,
650
+ input: payload.value,
651
+ inclusive: def.inclusive,
652
+ inst,
653
+ continue: !def.abort
654
+ });
655
+ };
656
+ });
657
+ const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
658
+ $ZodCheck.init(inst, def);
659
+ inst._zod.onattach.push((inst$1) => {
660
+ var _a;
661
+ (_a = inst$1._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
662
+ });
663
+ inst._zod.check = (payload) => {
664
+ if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
665
+ if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
666
+ payload.issues.push({
667
+ origin: typeof payload.value,
668
+ code: "not_multiple_of",
669
+ divisor: def.value,
670
+ input: payload.value,
671
+ inst,
672
+ continue: !def.abort
673
+ });
674
+ };
675
+ });
676
+ const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
677
+ $ZodCheck.init(inst, def);
678
+ def.format = def.format || "float64";
679
+ const isInt = def.format?.includes("int");
680
+ const origin = isInt ? "int" : "number";
681
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
682
+ inst._zod.onattach.push((inst$1) => {
683
+ const bag = inst$1._zod.bag;
684
+ bag.format = def.format;
685
+ bag.minimum = minimum;
686
+ bag.maximum = maximum;
687
+ if (isInt) bag.pattern = integer;
688
+ });
689
+ inst._zod.check = (payload) => {
690
+ const input = payload.value;
691
+ if (isInt) {
692
+ if (!Number.isInteger(input)) {
693
+ payload.issues.push({
694
+ expected: origin,
695
+ format: def.format,
696
+ code: "invalid_type",
697
+ continue: false,
698
+ input,
699
+ inst
700
+ });
701
+ return;
702
+ }
703
+ if (!Number.isSafeInteger(input)) {
704
+ if (input > 0) payload.issues.push({
705
+ input,
706
+ code: "too_big",
707
+ maximum: Number.MAX_SAFE_INTEGER,
708
+ note: "Integers must be within the safe integer range.",
709
+ inst,
710
+ origin,
711
+ continue: !def.abort
712
+ });
713
+ else payload.issues.push({
714
+ input,
715
+ code: "too_small",
716
+ minimum: Number.MIN_SAFE_INTEGER,
717
+ note: "Integers must be within the safe integer range.",
718
+ inst,
719
+ origin,
720
+ continue: !def.abort
721
+ });
722
+ return;
723
+ }
724
+ }
725
+ if (input < minimum) payload.issues.push({
726
+ origin: "number",
727
+ input,
728
+ code: "too_small",
729
+ minimum,
730
+ inclusive: true,
731
+ inst,
732
+ continue: !def.abort
733
+ });
734
+ if (input > maximum) payload.issues.push({
735
+ origin: "number",
736
+ input,
737
+ code: "too_big",
738
+ maximum,
739
+ inst
740
+ });
741
+ };
742
+ });
743
+ const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
744
+ var _a;
745
+ $ZodCheck.init(inst, def);
746
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
747
+ const val = payload.value;
748
+ return !nullish(val) && val.length !== void 0;
749
+ });
750
+ inst._zod.onattach.push((inst$1) => {
751
+ const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
752
+ if (def.maximum < curr) inst$1._zod.bag.maximum = def.maximum;
753
+ });
754
+ inst._zod.check = (payload) => {
755
+ const input = payload.value;
756
+ if (input.length <= def.maximum) return;
757
+ const origin = getLengthableOrigin(input);
758
+ payload.issues.push({
759
+ origin,
760
+ code: "too_big",
761
+ maximum: def.maximum,
762
+ inclusive: true,
763
+ input,
764
+ inst,
765
+ continue: !def.abort
766
+ });
767
+ };
768
+ });
769
+ const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
770
+ var _a;
771
+ $ZodCheck.init(inst, def);
772
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
773
+ const val = payload.value;
774
+ return !nullish(val) && val.length !== void 0;
775
+ });
776
+ inst._zod.onattach.push((inst$1) => {
777
+ const curr = inst$1._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
778
+ if (def.minimum > curr) inst$1._zod.bag.minimum = def.minimum;
779
+ });
780
+ inst._zod.check = (payload) => {
781
+ const input = payload.value;
782
+ if (input.length >= def.minimum) return;
783
+ const origin = getLengthableOrigin(input);
784
+ payload.issues.push({
785
+ origin,
786
+ code: "too_small",
787
+ minimum: def.minimum,
788
+ inclusive: true,
789
+ input,
790
+ inst,
791
+ continue: !def.abort
792
+ });
793
+ };
794
+ });
795
+ const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
796
+ var _a;
797
+ $ZodCheck.init(inst, def);
798
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
799
+ const val = payload.value;
800
+ return !nullish(val) && val.length !== void 0;
801
+ });
802
+ inst._zod.onattach.push((inst$1) => {
803
+ const bag = inst$1._zod.bag;
804
+ bag.minimum = def.length;
805
+ bag.maximum = def.length;
806
+ bag.length = def.length;
807
+ });
808
+ inst._zod.check = (payload) => {
809
+ const input = payload.value;
810
+ const length = input.length;
811
+ if (length === def.length) return;
812
+ const origin = getLengthableOrigin(input);
813
+ const tooBig = length > def.length;
814
+ payload.issues.push({
815
+ origin,
816
+ ...tooBig ? {
817
+ code: "too_big",
818
+ maximum: def.length
819
+ } : {
820
+ code: "too_small",
821
+ minimum: def.length
822
+ },
823
+ inclusive: true,
824
+ exact: true,
825
+ input: payload.value,
826
+ inst,
827
+ continue: !def.abort
828
+ });
829
+ };
830
+ });
831
+ const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
832
+ var _a, _b;
833
+ $ZodCheck.init(inst, def);
834
+ inst._zod.onattach.push((inst$1) => {
835
+ const bag = inst$1._zod.bag;
836
+ bag.format = def.format;
837
+ if (def.pattern) {
838
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
839
+ bag.patterns.add(def.pattern);
840
+ }
841
+ });
842
+ if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
843
+ def.pattern.lastIndex = 0;
844
+ if (def.pattern.test(payload.value)) return;
845
+ payload.issues.push({
846
+ origin: "string",
847
+ code: "invalid_format",
848
+ format: def.format,
849
+ input: payload.value,
850
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
851
+ inst,
852
+ continue: !def.abort
853
+ });
854
+ });
855
+ else (_b = inst._zod).check ?? (_b.check = () => {});
856
+ });
857
+ const $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
858
+ $ZodCheckStringFormat.init(inst, def);
859
+ inst._zod.check = (payload) => {
860
+ def.pattern.lastIndex = 0;
861
+ if (def.pattern.test(payload.value)) return;
862
+ payload.issues.push({
863
+ origin: "string",
864
+ code: "invalid_format",
865
+ format: "regex",
866
+ input: payload.value,
867
+ pattern: def.pattern.toString(),
868
+ inst,
869
+ continue: !def.abort
870
+ });
871
+ };
872
+ });
873
+ const $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
874
+ def.pattern ?? (def.pattern = lowercase);
875
+ $ZodCheckStringFormat.init(inst, def);
876
+ });
877
+ const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
878
+ def.pattern ?? (def.pattern = uppercase);
879
+ $ZodCheckStringFormat.init(inst, def);
880
+ });
881
+ const $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
882
+ $ZodCheck.init(inst, def);
883
+ const escapedRegex = escapeRegex(def.includes);
884
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
885
+ def.pattern = pattern;
886
+ inst._zod.onattach.push((inst$1) => {
887
+ const bag = inst$1._zod.bag;
888
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
889
+ bag.patterns.add(pattern);
890
+ });
891
+ inst._zod.check = (payload) => {
892
+ if (payload.value.includes(def.includes, def.position)) return;
893
+ payload.issues.push({
894
+ origin: "string",
895
+ code: "invalid_format",
896
+ format: "includes",
897
+ includes: def.includes,
898
+ input: payload.value,
899
+ inst,
900
+ continue: !def.abort
901
+ });
902
+ };
903
+ });
904
+ const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
905
+ $ZodCheck.init(inst, def);
906
+ const pattern = /* @__PURE__ */ new RegExp(`^${escapeRegex(def.prefix)}.*`);
907
+ def.pattern ?? (def.pattern = pattern);
908
+ inst._zod.onattach.push((inst$1) => {
909
+ const bag = inst$1._zod.bag;
910
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
911
+ bag.patterns.add(pattern);
912
+ });
913
+ inst._zod.check = (payload) => {
914
+ if (payload.value.startsWith(def.prefix)) return;
915
+ payload.issues.push({
916
+ origin: "string",
917
+ code: "invalid_format",
918
+ format: "starts_with",
919
+ prefix: def.prefix,
920
+ input: payload.value,
921
+ inst,
922
+ continue: !def.abort
923
+ });
924
+ };
925
+ });
926
+ const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
927
+ $ZodCheck.init(inst, def);
928
+ const pattern = /* @__PURE__ */ new RegExp(`.*${escapeRegex(def.suffix)}$`);
929
+ def.pattern ?? (def.pattern = pattern);
930
+ inst._zod.onattach.push((inst$1) => {
931
+ const bag = inst$1._zod.bag;
932
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
933
+ bag.patterns.add(pattern);
934
+ });
935
+ inst._zod.check = (payload) => {
936
+ if (payload.value.endsWith(def.suffix)) return;
937
+ payload.issues.push({
938
+ origin: "string",
939
+ code: "invalid_format",
940
+ format: "ends_with",
941
+ suffix: def.suffix,
942
+ input: payload.value,
943
+ inst,
944
+ continue: !def.abort
945
+ });
946
+ };
947
+ });
948
+ const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
949
+ $ZodCheck.init(inst, def);
950
+ inst._zod.check = (payload) => {
951
+ payload.value = def.tx(payload.value);
952
+ };
953
+ });
954
+
955
+ //#endregion
956
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/doc.js
957
+ var Doc = class {
958
+ constructor(args = []) {
959
+ this.content = [];
960
+ this.indent = 0;
961
+ if (this) this.args = args;
962
+ }
963
+ indented(fn) {
964
+ this.indent += 1;
965
+ fn(this);
966
+ this.indent -= 1;
967
+ }
968
+ write(arg) {
969
+ if (typeof arg === "function") {
970
+ arg(this, { execution: "sync" });
971
+ arg(this, { execution: "async" });
972
+ return;
973
+ }
974
+ const lines = arg.split("\n").filter((x) => x);
975
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
976
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
977
+ for (const line of dedented) this.content.push(line);
978
+ }
979
+ compile() {
980
+ const F = Function;
981
+ const args = this?.args;
982
+ const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
983
+ return new F(...args, lines.join("\n"));
984
+ }
985
+ };
986
+
987
+ //#endregion
988
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/versions.js
989
+ const version = {
990
+ major: 4,
991
+ minor: 1,
992
+ patch: 12
993
+ };
994
+
995
+ //#endregion
996
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/schemas.js
997
+ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
998
+ var _a;
999
+ inst ?? (inst = {});
1000
+ inst._zod.def = def;
1001
+ inst._zod.bag = inst._zod.bag || {};
1002
+ inst._zod.version = version;
1003
+ const checks = [...inst._zod.def.checks ?? []];
1004
+ if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
1005
+ for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
1006
+ if (checks.length === 0) {
1007
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
1008
+ inst._zod.deferred?.push(() => {
1009
+ inst._zod.run = inst._zod.parse;
1010
+ });
1011
+ } else {
1012
+ const runChecks = (payload, checks$1, ctx) => {
1013
+ let isAborted = aborted(payload);
1014
+ let asyncResult;
1015
+ for (const ch of checks$1) {
1016
+ if (ch._zod.def.when) {
1017
+ if (!ch._zod.def.when(payload)) continue;
1018
+ } else if (isAborted) continue;
1019
+ const currLen = payload.issues.length;
1020
+ const _ = ch._zod.check(payload);
1021
+ if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
1022
+ if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
1023
+ await _;
1024
+ if (payload.issues.length === currLen) return;
1025
+ if (!isAborted) isAborted = aborted(payload, currLen);
1026
+ });
1027
+ else {
1028
+ if (payload.issues.length === currLen) continue;
1029
+ if (!isAborted) isAborted = aborted(payload, currLen);
1030
+ }
1031
+ }
1032
+ if (asyncResult) return asyncResult.then(() => {
1033
+ return payload;
1034
+ });
1035
+ return payload;
1036
+ };
1037
+ const handleCanaryResult = (canary, payload, ctx) => {
1038
+ if (aborted(canary)) {
1039
+ canary.aborted = true;
1040
+ return canary;
1041
+ }
1042
+ const checkResult = runChecks(payload, checks, ctx);
1043
+ if (checkResult instanceof Promise) {
1044
+ if (ctx.async === false) throw new $ZodAsyncError();
1045
+ return checkResult.then((checkResult$1) => inst._zod.parse(checkResult$1, ctx));
1046
+ }
1047
+ return inst._zod.parse(checkResult, ctx);
1048
+ };
1049
+ inst._zod.run = (payload, ctx) => {
1050
+ if (ctx.skipChecks) return inst._zod.parse(payload, ctx);
1051
+ if (ctx.direction === "backward") {
1052
+ const canary = inst._zod.parse({
1053
+ value: payload.value,
1054
+ issues: []
1055
+ }, {
1056
+ ...ctx,
1057
+ skipChecks: true
1058
+ });
1059
+ if (canary instanceof Promise) return canary.then((canary$1) => {
1060
+ return handleCanaryResult(canary$1, payload, ctx);
1061
+ });
1062
+ return handleCanaryResult(canary, payload, ctx);
1063
+ }
1064
+ const result = inst._zod.parse(payload, ctx);
1065
+ if (result instanceof Promise) {
1066
+ if (ctx.async === false) throw new $ZodAsyncError();
1067
+ return result.then((result$1) => runChecks(result$1, checks, ctx));
1068
+ }
1069
+ return runChecks(result, checks, ctx);
1070
+ };
1071
+ }
1072
+ inst["~standard"] = {
1073
+ validate: (value) => {
1074
+ try {
1075
+ const r = safeParse$1(inst, value);
1076
+ return r.success ? { value: r.data } : { issues: r.error?.issues };
1077
+ } catch (_) {
1078
+ return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
1079
+ }
1080
+ },
1081
+ vendor: "zod",
1082
+ version: 1
1083
+ };
1084
+ });
1085
+ const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
1086
+ $ZodType.init(inst, def);
1087
+ inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
1088
+ inst._zod.parse = (payload, _) => {
1089
+ if (def.coerce) try {
1090
+ payload.value = String(payload.value);
1091
+ } catch (_$1) {}
1092
+ if (typeof payload.value === "string") return payload;
1093
+ payload.issues.push({
1094
+ expected: "string",
1095
+ code: "invalid_type",
1096
+ input: payload.value,
1097
+ inst
1098
+ });
1099
+ return payload;
1100
+ };
1101
+ });
1102
+ const $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
1103
+ $ZodCheckStringFormat.init(inst, def);
1104
+ $ZodString.init(inst, def);
1105
+ });
1106
+ const $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
1107
+ def.pattern ?? (def.pattern = guid);
1108
+ $ZodStringFormat.init(inst, def);
1109
+ });
1110
+ const $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
1111
+ if (def.version) {
1112
+ const v = {
1113
+ v1: 1,
1114
+ v2: 2,
1115
+ v3: 3,
1116
+ v4: 4,
1117
+ v5: 5,
1118
+ v6: 6,
1119
+ v7: 7,
1120
+ v8: 8
1121
+ }[def.version];
1122
+ if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
1123
+ def.pattern ?? (def.pattern = uuid(v));
1124
+ } else def.pattern ?? (def.pattern = uuid());
1125
+ $ZodStringFormat.init(inst, def);
1126
+ });
1127
+ const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
1128
+ def.pattern ?? (def.pattern = email);
1129
+ $ZodStringFormat.init(inst, def);
1130
+ });
1131
+ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1132
+ $ZodStringFormat.init(inst, def);
1133
+ inst._zod.check = (payload) => {
1134
+ try {
1135
+ const trimmed = payload.value.trim();
1136
+ const url = new URL(trimmed);
1137
+ if (def.hostname) {
1138
+ def.hostname.lastIndex = 0;
1139
+ if (!def.hostname.test(url.hostname)) payload.issues.push({
1140
+ code: "invalid_format",
1141
+ format: "url",
1142
+ note: "Invalid hostname",
1143
+ pattern: hostname.source,
1144
+ input: payload.value,
1145
+ inst,
1146
+ continue: !def.abort
1147
+ });
1148
+ }
1149
+ if (def.protocol) {
1150
+ def.protocol.lastIndex = 0;
1151
+ if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
1152
+ code: "invalid_format",
1153
+ format: "url",
1154
+ note: "Invalid protocol",
1155
+ pattern: def.protocol.source,
1156
+ input: payload.value,
1157
+ inst,
1158
+ continue: !def.abort
1159
+ });
1160
+ }
1161
+ if (def.normalize) payload.value = url.href;
1162
+ else payload.value = trimmed;
1163
+ return;
1164
+ } catch (_) {
1165
+ payload.issues.push({
1166
+ code: "invalid_format",
1167
+ format: "url",
1168
+ input: payload.value,
1169
+ inst,
1170
+ continue: !def.abort
1171
+ });
1172
+ }
1173
+ };
1174
+ });
1175
+ const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
1176
+ def.pattern ?? (def.pattern = emoji());
1177
+ $ZodStringFormat.init(inst, def);
1178
+ });
1179
+ const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
1180
+ def.pattern ?? (def.pattern = nanoid$1);
1181
+ $ZodStringFormat.init(inst, def);
1182
+ });
1183
+ const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
1184
+ def.pattern ?? (def.pattern = cuid);
1185
+ $ZodStringFormat.init(inst, def);
1186
+ });
1187
+ const $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
1188
+ def.pattern ?? (def.pattern = cuid2);
1189
+ $ZodStringFormat.init(inst, def);
1190
+ });
1191
+ const $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
1192
+ def.pattern ?? (def.pattern = ulid);
1193
+ $ZodStringFormat.init(inst, def);
1194
+ });
1195
+ const $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
1196
+ def.pattern ?? (def.pattern = xid);
1197
+ $ZodStringFormat.init(inst, def);
1198
+ });
1199
+ const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
1200
+ def.pattern ?? (def.pattern = ksuid);
1201
+ $ZodStringFormat.init(inst, def);
1202
+ });
1203
+ const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
1204
+ def.pattern ?? (def.pattern = datetime$1(def));
1205
+ $ZodStringFormat.init(inst, def);
1206
+ });
1207
+ const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
1208
+ def.pattern ?? (def.pattern = date$1);
1209
+ $ZodStringFormat.init(inst, def);
1210
+ });
1211
+ const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
1212
+ def.pattern ?? (def.pattern = time$1(def));
1213
+ $ZodStringFormat.init(inst, def);
1214
+ });
1215
+ const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
1216
+ def.pattern ?? (def.pattern = duration$1);
1217
+ $ZodStringFormat.init(inst, def);
1218
+ });
1219
+ const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
1220
+ def.pattern ?? (def.pattern = ipv4);
1221
+ $ZodStringFormat.init(inst, def);
1222
+ inst._zod.onattach.push((inst$1) => {
1223
+ const bag = inst$1._zod.bag;
1224
+ bag.format = `ipv4`;
1225
+ });
1226
+ });
1227
+ const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
1228
+ def.pattern ?? (def.pattern = ipv6);
1229
+ $ZodStringFormat.init(inst, def);
1230
+ inst._zod.onattach.push((inst$1) => {
1231
+ const bag = inst$1._zod.bag;
1232
+ bag.format = `ipv6`;
1233
+ });
1234
+ inst._zod.check = (payload) => {
1235
+ try {
1236
+ new URL(`http://[${payload.value}]`);
1237
+ } catch {
1238
+ payload.issues.push({
1239
+ code: "invalid_format",
1240
+ format: "ipv6",
1241
+ input: payload.value,
1242
+ inst,
1243
+ continue: !def.abort
1244
+ });
1245
+ }
1246
+ };
1247
+ });
1248
+ const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
1249
+ def.pattern ?? (def.pattern = cidrv4);
1250
+ $ZodStringFormat.init(inst, def);
1251
+ });
1252
+ const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
1253
+ def.pattern ?? (def.pattern = cidrv6);
1254
+ $ZodStringFormat.init(inst, def);
1255
+ inst._zod.check = (payload) => {
1256
+ const parts = payload.value.split("/");
1257
+ try {
1258
+ if (parts.length !== 2) throw new Error();
1259
+ const [address, prefix] = parts;
1260
+ if (!prefix) throw new Error();
1261
+ const prefixNum = Number(prefix);
1262
+ if (`${prefixNum}` !== prefix) throw new Error();
1263
+ if (prefixNum < 0 || prefixNum > 128) throw new Error();
1264
+ new URL(`http://[${address}]`);
1265
+ } catch {
1266
+ payload.issues.push({
1267
+ code: "invalid_format",
1268
+ format: "cidrv6",
1269
+ input: payload.value,
1270
+ inst,
1271
+ continue: !def.abort
1272
+ });
1273
+ }
1274
+ };
1275
+ });
1276
+ function isValidBase64(data) {
1277
+ if (data === "") return true;
1278
+ if (data.length % 4 !== 0) return false;
1279
+ try {
1280
+ atob(data);
1281
+ return true;
1282
+ } catch {
1283
+ return false;
1284
+ }
1285
+ }
1286
+ const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
1287
+ def.pattern ?? (def.pattern = base64);
1288
+ $ZodStringFormat.init(inst, def);
1289
+ inst._zod.onattach.push((inst$1) => {
1290
+ inst$1._zod.bag.contentEncoding = "base64";
1291
+ });
1292
+ inst._zod.check = (payload) => {
1293
+ if (isValidBase64(payload.value)) return;
1294
+ payload.issues.push({
1295
+ code: "invalid_format",
1296
+ format: "base64",
1297
+ input: payload.value,
1298
+ inst,
1299
+ continue: !def.abort
1300
+ });
1301
+ };
1302
+ });
1303
+ function isValidBase64URL(data) {
1304
+ if (!base64url.test(data)) return false;
1305
+ const base64$1 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
1306
+ return isValidBase64(base64$1.padEnd(Math.ceil(base64$1.length / 4) * 4, "="));
1307
+ }
1308
+ const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
1309
+ def.pattern ?? (def.pattern = base64url);
1310
+ $ZodStringFormat.init(inst, def);
1311
+ inst._zod.onattach.push((inst$1) => {
1312
+ inst$1._zod.bag.contentEncoding = "base64url";
1313
+ });
1314
+ inst._zod.check = (payload) => {
1315
+ if (isValidBase64URL(payload.value)) return;
1316
+ payload.issues.push({
1317
+ code: "invalid_format",
1318
+ format: "base64url",
1319
+ input: payload.value,
1320
+ inst,
1321
+ continue: !def.abort
1322
+ });
1323
+ };
1324
+ });
1325
+ const $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
1326
+ def.pattern ?? (def.pattern = e164);
1327
+ $ZodStringFormat.init(inst, def);
1328
+ });
1329
+ function isValidJWT(token, algorithm = null) {
1330
+ try {
1331
+ const tokensParts = token.split(".");
1332
+ if (tokensParts.length !== 3) return false;
1333
+ const [header] = tokensParts;
1334
+ if (!header) return false;
1335
+ const parsedHeader = JSON.parse(atob(header));
1336
+ if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
1337
+ if (!parsedHeader.alg) return false;
1338
+ if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
1339
+ return true;
1340
+ } catch {
1341
+ return false;
1342
+ }
1343
+ }
1344
+ const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
1345
+ $ZodStringFormat.init(inst, def);
1346
+ inst._zod.check = (payload) => {
1347
+ if (isValidJWT(payload.value, def.alg)) return;
1348
+ payload.issues.push({
1349
+ code: "invalid_format",
1350
+ format: "jwt",
1351
+ input: payload.value,
1352
+ inst,
1353
+ continue: !def.abort
1354
+ });
1355
+ };
1356
+ });
1357
+ const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
1358
+ $ZodType.init(inst, def);
1359
+ inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
1360
+ inst._zod.parse = (payload, _ctx) => {
1361
+ if (def.coerce) try {
1362
+ payload.value = Number(payload.value);
1363
+ } catch (_) {}
1364
+ const input = payload.value;
1365
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
1366
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
1367
+ payload.issues.push({
1368
+ expected: "number",
1369
+ code: "invalid_type",
1370
+ input,
1371
+ inst,
1372
+ ...received ? { received } : {}
1373
+ });
1374
+ return payload;
1375
+ };
1376
+ });
1377
+ const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
1378
+ $ZodCheckNumberFormat.init(inst, def);
1379
+ $ZodNumber.init(inst, def);
1380
+ });
1381
+ const $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
1382
+ $ZodType.init(inst, def);
1383
+ inst._zod.pattern = boolean$1;
1384
+ inst._zod.parse = (payload, _ctx) => {
1385
+ if (def.coerce) try {
1386
+ payload.value = Boolean(payload.value);
1387
+ } catch (_) {}
1388
+ const input = payload.value;
1389
+ if (typeof input === "boolean") return payload;
1390
+ payload.issues.push({
1391
+ expected: "boolean",
1392
+ code: "invalid_type",
1393
+ input,
1394
+ inst
1395
+ });
1396
+ return payload;
1397
+ };
1398
+ });
1399
+ const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
1400
+ $ZodType.init(inst, def);
1401
+ inst._zod.parse = (payload) => payload;
1402
+ });
1403
+ const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
1404
+ $ZodType.init(inst, def);
1405
+ inst._zod.parse = (payload, _ctx) => {
1406
+ payload.issues.push({
1407
+ expected: "never",
1408
+ code: "invalid_type",
1409
+ input: payload.value,
1410
+ inst
1411
+ });
1412
+ return payload;
1413
+ };
1414
+ });
1415
+ function handleArrayResult(result, final, index) {
1416
+ if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
1417
+ final.value[index] = result.value;
1418
+ }
1419
+ const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
1420
+ $ZodType.init(inst, def);
1421
+ inst._zod.parse = (payload, ctx) => {
1422
+ const input = payload.value;
1423
+ if (!Array.isArray(input)) {
1424
+ payload.issues.push({
1425
+ expected: "array",
1426
+ code: "invalid_type",
1427
+ input,
1428
+ inst
1429
+ });
1430
+ return payload;
1431
+ }
1432
+ payload.value = Array(input.length);
1433
+ const proms = [];
1434
+ for (let i = 0; i < input.length; i++) {
1435
+ const item = input[i];
1436
+ const result = def.element._zod.run({
1437
+ value: item,
1438
+ issues: []
1439
+ }, ctx);
1440
+ if (result instanceof Promise) proms.push(result.then((result$1) => handleArrayResult(result$1, payload, i)));
1441
+ else handleArrayResult(result, payload, i);
1442
+ }
1443
+ if (proms.length) return Promise.all(proms).then(() => payload);
1444
+ return payload;
1445
+ };
1446
+ });
1447
+ function handlePropertyResult(result, final, key, input) {
1448
+ if (result.issues.length) final.issues.push(...prefixIssues(key, result.issues));
1449
+ if (result.value === void 0) {
1450
+ if (key in input) final.value[key] = void 0;
1451
+ } else final.value[key] = result.value;
1452
+ }
1453
+ function normalizeDef(def) {
1454
+ const keys = Object.keys(def.shape);
1455
+ 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`);
1456
+ const okeys = optionalKeys(def.shape);
1457
+ return {
1458
+ ...def,
1459
+ keys,
1460
+ keySet: new Set(keys),
1461
+ numKeys: keys.length,
1462
+ optionalKeys: new Set(okeys)
1463
+ };
1464
+ }
1465
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
1466
+ const unrecognized = [];
1467
+ const keySet = def.keySet;
1468
+ const _catchall = def.catchall._zod;
1469
+ const t = _catchall.def.type;
1470
+ for (const key of Object.keys(input)) {
1471
+ if (keySet.has(key)) continue;
1472
+ if (t === "never") {
1473
+ unrecognized.push(key);
1474
+ continue;
1475
+ }
1476
+ const r = _catchall.run({
1477
+ value: input[key],
1478
+ issues: []
1479
+ }, ctx);
1480
+ if (r instanceof Promise) proms.push(r.then((r$1) => handlePropertyResult(r$1, payload, key, input)));
1481
+ else handlePropertyResult(r, payload, key, input);
1482
+ }
1483
+ if (unrecognized.length) payload.issues.push({
1484
+ code: "unrecognized_keys",
1485
+ keys: unrecognized,
1486
+ input,
1487
+ inst
1488
+ });
1489
+ if (!proms.length) return payload;
1490
+ return Promise.all(proms).then(() => {
1491
+ return payload;
1492
+ });
1493
+ }
1494
+ const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
1495
+ $ZodType.init(inst, def);
1496
+ if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) {
1497
+ const sh = def.shape;
1498
+ Object.defineProperty(def, "shape", { get: () => {
1499
+ const newSh = { ...sh };
1500
+ Object.defineProperty(def, "shape", { value: newSh });
1501
+ return newSh;
1502
+ } });
1503
+ }
1504
+ const _normalized = cached(() => normalizeDef(def));
1505
+ defineLazy(inst._zod, "propValues", () => {
1506
+ const shape = def.shape;
1507
+ const propValues = {};
1508
+ for (const key in shape) {
1509
+ const field = shape[key]._zod;
1510
+ if (field.values) {
1511
+ propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
1512
+ for (const v of field.values) propValues[key].add(v);
1513
+ }
1514
+ }
1515
+ return propValues;
1516
+ });
1517
+ const isObject$1 = isObject;
1518
+ const catchall = def.catchall;
1519
+ let value;
1520
+ inst._zod.parse = (payload, ctx) => {
1521
+ value ?? (value = _normalized.value);
1522
+ const input = payload.value;
1523
+ if (!isObject$1(input)) {
1524
+ payload.issues.push({
1525
+ expected: "object",
1526
+ code: "invalid_type",
1527
+ input,
1528
+ inst
1529
+ });
1530
+ return payload;
1531
+ }
1532
+ payload.value = {};
1533
+ const proms = [];
1534
+ const shape = value.shape;
1535
+ for (const key of value.keys) {
1536
+ const r = shape[key]._zod.run({
1537
+ value: input[key],
1538
+ issues: []
1539
+ }, ctx);
1540
+ if (r instanceof Promise) proms.push(r.then((r$1) => handlePropertyResult(r$1, payload, key, input)));
1541
+ else handlePropertyResult(r, payload, key, input);
1542
+ }
1543
+ if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
1544
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
1545
+ };
1546
+ });
1547
+ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
1548
+ $ZodObject.init(inst, def);
1549
+ const superParse = inst._zod.parse;
1550
+ const _normalized = cached(() => normalizeDef(def));
1551
+ const generateFastpass = (shape) => {
1552
+ const doc = new Doc([
1553
+ "shape",
1554
+ "payload",
1555
+ "ctx"
1556
+ ]);
1557
+ const normalized = _normalized.value;
1558
+ const parseStr = (key) => {
1559
+ const k = esc(key);
1560
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
1561
+ };
1562
+ doc.write(`const input = payload.value;`);
1563
+ const ids = Object.create(null);
1564
+ let counter = 0;
1565
+ for (const key of normalized.keys) ids[key] = `key_${counter++}`;
1566
+ doc.write(`const newResult = {};`);
1567
+ for (const key of normalized.keys) {
1568
+ const id = ids[key];
1569
+ const k = esc(key);
1570
+ doc.write(`const ${id} = ${parseStr(key)};`);
1571
+ doc.write(`
1572
+ if (${id}.issues.length) {
1573
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1574
+ ...iss,
1575
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
1576
+ })));
1577
+ }
1578
+
1579
+
1580
+ if (${id}.value === undefined) {
1581
+ if (${k} in input) {
1582
+ newResult[${k}] = undefined;
1583
+ }
1584
+ } else {
1585
+ newResult[${k}] = ${id}.value;
1586
+ }
1587
+
1588
+ `);
1589
+ }
1590
+ doc.write(`payload.value = newResult;`);
1591
+ doc.write(`return payload;`);
1592
+ const fn = doc.compile();
1593
+ return (payload, ctx) => fn(shape, payload, ctx);
1594
+ };
1595
+ let fastpass;
1596
+ const isObject$1 = isObject;
1597
+ const jit = !globalConfig.jitless;
1598
+ const allowsEval$1 = allowsEval;
1599
+ const fastEnabled = jit && allowsEval$1.value;
1600
+ const catchall = def.catchall;
1601
+ let value;
1602
+ inst._zod.parse = (payload, ctx) => {
1603
+ value ?? (value = _normalized.value);
1604
+ const input = payload.value;
1605
+ if (!isObject$1(input)) {
1606
+ payload.issues.push({
1607
+ expected: "object",
1608
+ code: "invalid_type",
1609
+ input,
1610
+ inst
1611
+ });
1612
+ return payload;
1613
+ }
1614
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1615
+ if (!fastpass) fastpass = generateFastpass(def.shape);
1616
+ payload = fastpass(payload, ctx);
1617
+ if (!catchall) return payload;
1618
+ return handleCatchall([], input, payload, ctx, value, inst);
1619
+ }
1620
+ return superParse(payload, ctx);
1621
+ };
1622
+ });
1623
+ function handleUnionResults(results, final, inst, ctx) {
1624
+ for (const result of results) if (result.issues.length === 0) {
1625
+ final.value = result.value;
1626
+ return final;
1627
+ }
1628
+ const nonaborted = results.filter((r) => !aborted(r));
1629
+ if (nonaborted.length === 1) {
1630
+ final.value = nonaborted[0].value;
1631
+ return nonaborted[0];
1632
+ }
1633
+ final.issues.push({
1634
+ code: "invalid_union",
1635
+ input: final.value,
1636
+ inst,
1637
+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1638
+ });
1639
+ return final;
1640
+ }
1641
+ const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
1642
+ $ZodType.init(inst, def);
1643
+ defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
1644
+ defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
1645
+ defineLazy(inst._zod, "values", () => {
1646
+ if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1647
+ });
1648
+ defineLazy(inst._zod, "pattern", () => {
1649
+ if (def.options.every((o) => o._zod.pattern)) {
1650
+ const patterns = def.options.map((o) => o._zod.pattern);
1651
+ return /* @__PURE__ */ new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1652
+ }
1653
+ });
1654
+ const single = def.options.length === 1;
1655
+ const first = def.options[0]._zod.run;
1656
+ inst._zod.parse = (payload, ctx) => {
1657
+ if (single) return first(payload, ctx);
1658
+ let async = false;
1659
+ const results = [];
1660
+ for (const option of def.options) {
1661
+ const result = option._zod.run({
1662
+ value: payload.value,
1663
+ issues: []
1664
+ }, ctx);
1665
+ if (result instanceof Promise) {
1666
+ results.push(result);
1667
+ async = true;
1668
+ } else {
1669
+ if (result.issues.length === 0) return result;
1670
+ results.push(result);
1671
+ }
1672
+ }
1673
+ if (!async) return handleUnionResults(results, payload, inst, ctx);
1674
+ return Promise.all(results).then((results$1) => {
1675
+ return handleUnionResults(results$1, payload, inst, ctx);
1676
+ });
1677
+ };
1678
+ });
1679
+ const $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
1680
+ $ZodUnion.init(inst, def);
1681
+ const _super = inst._zod.parse;
1682
+ defineLazy(inst._zod, "propValues", () => {
1683
+ const propValues = {};
1684
+ for (const option of def.options) {
1685
+ const pv = option._zod.propValues;
1686
+ if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
1687
+ for (const [k, v] of Object.entries(pv)) {
1688
+ if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set();
1689
+ for (const val of v) propValues[k].add(val);
1690
+ }
1691
+ }
1692
+ return propValues;
1693
+ });
1694
+ const disc = cached(() => {
1695
+ const opts = def.options;
1696
+ const map = /* @__PURE__ */ new Map();
1697
+ for (const o of opts) {
1698
+ const values = o._zod.propValues?.[def.discriminator];
1699
+ if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
1700
+ for (const v of values) {
1701
+ if (map.has(v)) throw new Error(`Duplicate discriminator value "${String(v)}"`);
1702
+ map.set(v, o);
1703
+ }
1704
+ }
1705
+ return map;
1706
+ });
1707
+ inst._zod.parse = (payload, ctx) => {
1708
+ const input = payload.value;
1709
+ if (!isObject(input)) {
1710
+ payload.issues.push({
1711
+ code: "invalid_type",
1712
+ expected: "object",
1713
+ input,
1714
+ inst
1715
+ });
1716
+ return payload;
1717
+ }
1718
+ const opt = disc.value.get(input?.[def.discriminator]);
1719
+ if (opt) return opt._zod.run(payload, ctx);
1720
+ if (def.unionFallback) return _super(payload, ctx);
1721
+ payload.issues.push({
1722
+ code: "invalid_union",
1723
+ errors: [],
1724
+ note: "No matching discriminator",
1725
+ discriminator: def.discriminator,
1726
+ input,
1727
+ path: [def.discriminator],
1728
+ inst
1729
+ });
1730
+ return payload;
1731
+ };
1732
+ });
1733
+ const $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
1734
+ $ZodType.init(inst, def);
1735
+ inst._zod.parse = (payload, ctx) => {
1736
+ const input = payload.value;
1737
+ const left = def.left._zod.run({
1738
+ value: input,
1739
+ issues: []
1740
+ }, ctx);
1741
+ const right = def.right._zod.run({
1742
+ value: input,
1743
+ issues: []
1744
+ }, ctx);
1745
+ if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left$1, right$1]) => {
1746
+ return handleIntersectionResults(payload, left$1, right$1);
1747
+ });
1748
+ return handleIntersectionResults(payload, left, right);
1749
+ };
1750
+ });
1751
+ function mergeValues(a, b) {
1752
+ if (a === b) return {
1753
+ valid: true,
1754
+ data: a
1755
+ };
1756
+ if (a instanceof Date && b instanceof Date && +a === +b) return {
1757
+ valid: true,
1758
+ data: a
1759
+ };
1760
+ if (isPlainObject(a) && isPlainObject(b)) {
1761
+ const bKeys = Object.keys(b);
1762
+ const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1763
+ const newObj = {
1764
+ ...a,
1765
+ ...b
1766
+ };
1767
+ for (const key of sharedKeys) {
1768
+ const sharedValue = mergeValues(a[key], b[key]);
1769
+ if (!sharedValue.valid) return {
1770
+ valid: false,
1771
+ mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
1772
+ };
1773
+ newObj[key] = sharedValue.data;
1774
+ }
1775
+ return {
1776
+ valid: true,
1777
+ data: newObj
1778
+ };
1779
+ }
1780
+ if (Array.isArray(a) && Array.isArray(b)) {
1781
+ if (a.length !== b.length) return {
1782
+ valid: false,
1783
+ mergeErrorPath: []
1784
+ };
1785
+ const newArray = [];
1786
+ for (let index = 0; index < a.length; index++) {
1787
+ const itemA = a[index];
1788
+ const itemB = b[index];
1789
+ const sharedValue = mergeValues(itemA, itemB);
1790
+ if (!sharedValue.valid) return {
1791
+ valid: false,
1792
+ mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
1793
+ };
1794
+ newArray.push(sharedValue.data);
1795
+ }
1796
+ return {
1797
+ valid: true,
1798
+ data: newArray
1799
+ };
1800
+ }
1801
+ return {
1802
+ valid: false,
1803
+ mergeErrorPath: []
1804
+ };
1805
+ }
1806
+ function handleIntersectionResults(result, left, right) {
1807
+ if (left.issues.length) result.issues.push(...left.issues);
1808
+ if (right.issues.length) result.issues.push(...right.issues);
1809
+ if (aborted(result)) return result;
1810
+ const merged = mergeValues(left.value, right.value);
1811
+ if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
1812
+ result.value = merged.data;
1813
+ return result;
1814
+ }
1815
+ const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
1816
+ $ZodType.init(inst, def);
1817
+ const values = getEnumValues(def.entries);
1818
+ const valuesSet = new Set(values);
1819
+ inst._zod.values = valuesSet;
1820
+ inst._zod.pattern = /* @__PURE__ */ new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
1821
+ inst._zod.parse = (payload, _ctx) => {
1822
+ const input = payload.value;
1823
+ if (valuesSet.has(input)) return payload;
1824
+ payload.issues.push({
1825
+ code: "invalid_value",
1826
+ values,
1827
+ input,
1828
+ inst
1829
+ });
1830
+ return payload;
1831
+ };
1832
+ });
1833
+ const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
1834
+ $ZodType.init(inst, def);
1835
+ if (def.values.length === 0) throw new Error("Cannot create literal schema with no valid values");
1836
+ inst._zod.values = new Set(def.values);
1837
+ inst._zod.pattern = /* @__PURE__ */ new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
1838
+ inst._zod.parse = (payload, _ctx) => {
1839
+ const input = payload.value;
1840
+ if (inst._zod.values.has(input)) return payload;
1841
+ payload.issues.push({
1842
+ code: "invalid_value",
1843
+ values: def.values,
1844
+ input,
1845
+ inst
1846
+ });
1847
+ return payload;
1848
+ };
1849
+ });
1850
+ const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
1851
+ $ZodType.init(inst, def);
1852
+ inst._zod.parse = (payload, ctx) => {
1853
+ if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
1854
+ const _out = def.transform(payload.value, payload);
1855
+ if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
1856
+ payload.value = output;
1857
+ return payload;
1858
+ });
1859
+ if (_out instanceof Promise) throw new $ZodAsyncError();
1860
+ payload.value = _out;
1861
+ return payload;
1862
+ };
1863
+ });
1864
+ function handleOptionalResult(result, input) {
1865
+ if (result.issues.length && input === void 0) return {
1866
+ issues: [],
1867
+ value: void 0
1868
+ };
1869
+ return result;
1870
+ }
1871
+ const $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
1872
+ $ZodType.init(inst, def);
1873
+ inst._zod.optin = "optional";
1874
+ inst._zod.optout = "optional";
1875
+ defineLazy(inst._zod, "values", () => {
1876
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, void 0]) : void 0;
1877
+ });
1878
+ defineLazy(inst._zod, "pattern", () => {
1879
+ const pattern = def.innerType._zod.pattern;
1880
+ return pattern ? /* @__PURE__ */ new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
1881
+ });
1882
+ inst._zod.parse = (payload, ctx) => {
1883
+ if (def.innerType._zod.optin === "optional") {
1884
+ const result = def.innerType._zod.run(payload, ctx);
1885
+ if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, payload.value));
1886
+ return handleOptionalResult(result, payload.value);
1887
+ }
1888
+ if (payload.value === void 0) return payload;
1889
+ return def.innerType._zod.run(payload, ctx);
1890
+ };
1891
+ });
1892
+ const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
1893
+ $ZodType.init(inst, def);
1894
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1895
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1896
+ defineLazy(inst._zod, "pattern", () => {
1897
+ const pattern = def.innerType._zod.pattern;
1898
+ return pattern ? /* @__PURE__ */ new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
1899
+ });
1900
+ defineLazy(inst._zod, "values", () => {
1901
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : void 0;
1902
+ });
1903
+ inst._zod.parse = (payload, ctx) => {
1904
+ if (payload.value === null) return payload;
1905
+ return def.innerType._zod.run(payload, ctx);
1906
+ };
1907
+ });
1908
+ const $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
1909
+ $ZodType.init(inst, def);
1910
+ inst._zod.optin = "optional";
1911
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1912
+ inst._zod.parse = (payload, ctx) => {
1913
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1914
+ if (payload.value === void 0) {
1915
+ payload.value = def.defaultValue;
1916
+ /**
1917
+ * $ZodDefault returns the default value immediately in forward direction.
1918
+ * 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. */
1919
+ return payload;
1920
+ }
1921
+ const result = def.innerType._zod.run(payload, ctx);
1922
+ if (result instanceof Promise) return result.then((result$1) => handleDefaultResult(result$1, def));
1923
+ return handleDefaultResult(result, def);
1924
+ };
1925
+ });
1926
+ function handleDefaultResult(payload, def) {
1927
+ if (payload.value === void 0) payload.value = def.defaultValue;
1928
+ return payload;
1929
+ }
1930
+ const $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
1931
+ $ZodType.init(inst, def);
1932
+ inst._zod.optin = "optional";
1933
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1934
+ inst._zod.parse = (payload, ctx) => {
1935
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1936
+ if (payload.value === void 0) payload.value = def.defaultValue;
1937
+ return def.innerType._zod.run(payload, ctx);
1938
+ };
1939
+ });
1940
+ const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
1941
+ $ZodType.init(inst, def);
1942
+ defineLazy(inst._zod, "values", () => {
1943
+ const v = def.innerType._zod.values;
1944
+ return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
1945
+ });
1946
+ inst._zod.parse = (payload, ctx) => {
1947
+ const result = def.innerType._zod.run(payload, ctx);
1948
+ if (result instanceof Promise) return result.then((result$1) => handleNonOptionalResult(result$1, inst));
1949
+ return handleNonOptionalResult(result, inst);
1950
+ };
1951
+ });
1952
+ function handleNonOptionalResult(payload, inst) {
1953
+ if (!payload.issues.length && payload.value === void 0) payload.issues.push({
1954
+ code: "invalid_type",
1955
+ expected: "nonoptional",
1956
+ input: payload.value,
1957
+ inst
1958
+ });
1959
+ return payload;
1960
+ }
1961
+ const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
1962
+ $ZodType.init(inst, def);
1963
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1964
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1965
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1966
+ inst._zod.parse = (payload, ctx) => {
1967
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1968
+ const result = def.innerType._zod.run(payload, ctx);
1969
+ if (result instanceof Promise) return result.then((result$1) => {
1970
+ payload.value = result$1.value;
1971
+ if (result$1.issues.length) {
1972
+ payload.value = def.catchValue({
1973
+ ...payload,
1974
+ error: { issues: result$1.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
1975
+ input: payload.value
1976
+ });
1977
+ payload.issues = [];
1978
+ }
1979
+ return payload;
1980
+ });
1981
+ payload.value = result.value;
1982
+ if (result.issues.length) {
1983
+ payload.value = def.catchValue({
1984
+ ...payload,
1985
+ error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
1986
+ input: payload.value
1987
+ });
1988
+ payload.issues = [];
1989
+ }
1990
+ return payload;
1991
+ };
1992
+ });
1993
+ const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
1994
+ $ZodType.init(inst, def);
1995
+ defineLazy(inst._zod, "values", () => def.in._zod.values);
1996
+ defineLazy(inst._zod, "optin", () => def.in._zod.optin);
1997
+ defineLazy(inst._zod, "optout", () => def.out._zod.optout);
1998
+ defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
1999
+ inst._zod.parse = (payload, ctx) => {
2000
+ if (ctx.direction === "backward") {
2001
+ const right = def.out._zod.run(payload, ctx);
2002
+ if (right instanceof Promise) return right.then((right$1) => handlePipeResult(right$1, def.in, ctx));
2003
+ return handlePipeResult(right, def.in, ctx);
2004
+ }
2005
+ const left = def.in._zod.run(payload, ctx);
2006
+ if (left instanceof Promise) return left.then((left$1) => handlePipeResult(left$1, def.out, ctx));
2007
+ return handlePipeResult(left, def.out, ctx);
2008
+ };
2009
+ });
2010
+ function handlePipeResult(left, next, ctx) {
2011
+ if (left.issues.length) {
2012
+ left.aborted = true;
2013
+ return left;
2014
+ }
2015
+ return next._zod.run({
2016
+ value: left.value,
2017
+ issues: left.issues
2018
+ }, ctx);
2019
+ }
2020
+ const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
2021
+ $ZodType.init(inst, def);
2022
+ defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
2023
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2024
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2025
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2026
+ inst._zod.parse = (payload, ctx) => {
2027
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
2028
+ const result = def.innerType._zod.run(payload, ctx);
2029
+ if (result instanceof Promise) return result.then(handleReadonlyResult);
2030
+ return handleReadonlyResult(result);
2031
+ };
2032
+ });
2033
+ function handleReadonlyResult(payload) {
2034
+ payload.value = Object.freeze(payload.value);
2035
+ return payload;
2036
+ }
2037
+ const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
2038
+ $ZodCheck.init(inst, def);
2039
+ $ZodType.init(inst, def);
2040
+ inst._zod.parse = (payload, _) => {
2041
+ return payload;
2042
+ };
2043
+ inst._zod.check = (payload) => {
2044
+ const input = payload.value;
2045
+ const r = def.fn(input);
2046
+ if (r instanceof Promise) return r.then((r$1) => handleRefineResult(r$1, payload, input, inst));
2047
+ handleRefineResult(r, payload, input, inst);
2048
+ };
2049
+ });
2050
+ function handleRefineResult(result, payload, input, inst) {
2051
+ if (!result) {
2052
+ const _iss = {
2053
+ code: "custom",
2054
+ input,
2055
+ inst,
2056
+ path: [...inst._zod.def.path ?? []],
2057
+ continue: !inst._zod.def.abort
2058
+ };
2059
+ if (inst._zod.def.params) _iss.params = inst._zod.def.params;
2060
+ payload.issues.push(issue(_iss));
2061
+ }
2062
+ }
2063
+
2064
+ //#endregion
2065
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/registries.js
2066
+ var $ZodRegistry = class {
2067
+ constructor() {
2068
+ this._map = /* @__PURE__ */ new WeakMap();
2069
+ this._idmap = /* @__PURE__ */ new Map();
2070
+ }
2071
+ add(schema, ..._meta) {
2072
+ const meta = _meta[0];
2073
+ this._map.set(schema, meta);
2074
+ if (meta && typeof meta === "object" && "id" in meta) {
2075
+ if (this._idmap.has(meta.id)) throw new Error(`ID ${meta.id} already exists in the registry`);
2076
+ this._idmap.set(meta.id, schema);
2077
+ }
2078
+ return this;
2079
+ }
2080
+ clear() {
2081
+ this._map = /* @__PURE__ */ new WeakMap();
2082
+ this._idmap = /* @__PURE__ */ new Map();
2083
+ return this;
2084
+ }
2085
+ remove(schema) {
2086
+ const meta = this._map.get(schema);
2087
+ if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
2088
+ this._map.delete(schema);
2089
+ return this;
2090
+ }
2091
+ get(schema) {
2092
+ const p = schema._zod.parent;
2093
+ if (p) {
2094
+ const pm = { ...this.get(p) ?? {} };
2095
+ delete pm.id;
2096
+ const f = {
2097
+ ...pm,
2098
+ ...this._map.get(schema)
2099
+ };
2100
+ return Object.keys(f).length ? f : void 0;
2101
+ }
2102
+ return this._map.get(schema);
2103
+ }
2104
+ has(schema) {
2105
+ return this._map.has(schema);
2106
+ }
2107
+ };
2108
+ function registry() {
2109
+ return new $ZodRegistry();
2110
+ }
2111
+ const globalRegistry = /* @__PURE__ */ registry();
2112
+
2113
+ //#endregion
2114
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/api.js
2115
+ function _string(Class, params) {
2116
+ return new Class({
2117
+ type: "string",
2118
+ ...normalizeParams(params)
2119
+ });
2120
+ }
2121
+ function _email(Class, params) {
2122
+ return new Class({
2123
+ type: "string",
2124
+ format: "email",
2125
+ check: "string_format",
2126
+ abort: false,
2127
+ ...normalizeParams(params)
2128
+ });
2129
+ }
2130
+ function _guid(Class, params) {
2131
+ return new Class({
2132
+ type: "string",
2133
+ format: "guid",
2134
+ check: "string_format",
2135
+ abort: false,
2136
+ ...normalizeParams(params)
2137
+ });
2138
+ }
2139
+ function _uuid(Class, params) {
2140
+ return new Class({
2141
+ type: "string",
2142
+ format: "uuid",
2143
+ check: "string_format",
2144
+ abort: false,
2145
+ ...normalizeParams(params)
2146
+ });
2147
+ }
2148
+ function _uuidv4(Class, params) {
2149
+ return new Class({
2150
+ type: "string",
2151
+ format: "uuid",
2152
+ check: "string_format",
2153
+ abort: false,
2154
+ version: "v4",
2155
+ ...normalizeParams(params)
2156
+ });
2157
+ }
2158
+ function _uuidv6(Class, params) {
2159
+ return new Class({
2160
+ type: "string",
2161
+ format: "uuid",
2162
+ check: "string_format",
2163
+ abort: false,
2164
+ version: "v6",
2165
+ ...normalizeParams(params)
2166
+ });
2167
+ }
2168
+ function _uuidv7(Class, params) {
2169
+ return new Class({
2170
+ type: "string",
2171
+ format: "uuid",
2172
+ check: "string_format",
2173
+ abort: false,
2174
+ version: "v7",
2175
+ ...normalizeParams(params)
2176
+ });
2177
+ }
2178
+ function _url(Class, params) {
2179
+ return new Class({
2180
+ type: "string",
2181
+ format: "url",
2182
+ check: "string_format",
2183
+ abort: false,
2184
+ ...normalizeParams(params)
2185
+ });
2186
+ }
2187
+ function _emoji(Class, params) {
2188
+ return new Class({
2189
+ type: "string",
2190
+ format: "emoji",
2191
+ check: "string_format",
2192
+ abort: false,
2193
+ ...normalizeParams(params)
2194
+ });
2195
+ }
2196
+ function _nanoid(Class, params) {
2197
+ return new Class({
2198
+ type: "string",
2199
+ format: "nanoid",
2200
+ check: "string_format",
2201
+ abort: false,
2202
+ ...normalizeParams(params)
2203
+ });
2204
+ }
2205
+ function _cuid(Class, params) {
2206
+ return new Class({
2207
+ type: "string",
2208
+ format: "cuid",
2209
+ check: "string_format",
2210
+ abort: false,
2211
+ ...normalizeParams(params)
2212
+ });
2213
+ }
2214
+ function _cuid2(Class, params) {
2215
+ return new Class({
2216
+ type: "string",
2217
+ format: "cuid2",
2218
+ check: "string_format",
2219
+ abort: false,
2220
+ ...normalizeParams(params)
2221
+ });
2222
+ }
2223
+ function _ulid(Class, params) {
2224
+ return new Class({
2225
+ type: "string",
2226
+ format: "ulid",
2227
+ check: "string_format",
2228
+ abort: false,
2229
+ ...normalizeParams(params)
2230
+ });
2231
+ }
2232
+ function _xid(Class, params) {
2233
+ return new Class({
2234
+ type: "string",
2235
+ format: "xid",
2236
+ check: "string_format",
2237
+ abort: false,
2238
+ ...normalizeParams(params)
2239
+ });
2240
+ }
2241
+ function _ksuid(Class, params) {
2242
+ return new Class({
2243
+ type: "string",
2244
+ format: "ksuid",
2245
+ check: "string_format",
2246
+ abort: false,
2247
+ ...normalizeParams(params)
2248
+ });
2249
+ }
2250
+ function _ipv4(Class, params) {
2251
+ return new Class({
2252
+ type: "string",
2253
+ format: "ipv4",
2254
+ check: "string_format",
2255
+ abort: false,
2256
+ ...normalizeParams(params)
2257
+ });
2258
+ }
2259
+ function _ipv6(Class, params) {
2260
+ return new Class({
2261
+ type: "string",
2262
+ format: "ipv6",
2263
+ check: "string_format",
2264
+ abort: false,
2265
+ ...normalizeParams(params)
2266
+ });
2267
+ }
2268
+ function _cidrv4(Class, params) {
2269
+ return new Class({
2270
+ type: "string",
2271
+ format: "cidrv4",
2272
+ check: "string_format",
2273
+ abort: false,
2274
+ ...normalizeParams(params)
2275
+ });
2276
+ }
2277
+ function _cidrv6(Class, params) {
2278
+ return new Class({
2279
+ type: "string",
2280
+ format: "cidrv6",
2281
+ check: "string_format",
2282
+ abort: false,
2283
+ ...normalizeParams(params)
2284
+ });
2285
+ }
2286
+ function _base64(Class, params) {
2287
+ return new Class({
2288
+ type: "string",
2289
+ format: "base64",
2290
+ check: "string_format",
2291
+ abort: false,
2292
+ ...normalizeParams(params)
2293
+ });
2294
+ }
2295
+ function _base64url(Class, params) {
2296
+ return new Class({
2297
+ type: "string",
2298
+ format: "base64url",
2299
+ check: "string_format",
2300
+ abort: false,
2301
+ ...normalizeParams(params)
2302
+ });
2303
+ }
2304
+ function _e164(Class, params) {
2305
+ return new Class({
2306
+ type: "string",
2307
+ format: "e164",
2308
+ check: "string_format",
2309
+ abort: false,
2310
+ ...normalizeParams(params)
2311
+ });
2312
+ }
2313
+ function _jwt(Class, params) {
2314
+ return new Class({
2315
+ type: "string",
2316
+ format: "jwt",
2317
+ check: "string_format",
2318
+ abort: false,
2319
+ ...normalizeParams(params)
2320
+ });
2321
+ }
2322
+ function _isoDateTime(Class, params) {
2323
+ return new Class({
2324
+ type: "string",
2325
+ format: "datetime",
2326
+ check: "string_format",
2327
+ offset: false,
2328
+ local: false,
2329
+ precision: null,
2330
+ ...normalizeParams(params)
2331
+ });
2332
+ }
2333
+ function _isoDate(Class, params) {
2334
+ return new Class({
2335
+ type: "string",
2336
+ format: "date",
2337
+ check: "string_format",
2338
+ ...normalizeParams(params)
2339
+ });
2340
+ }
2341
+ function _isoTime(Class, params) {
2342
+ return new Class({
2343
+ type: "string",
2344
+ format: "time",
2345
+ check: "string_format",
2346
+ precision: null,
2347
+ ...normalizeParams(params)
2348
+ });
2349
+ }
2350
+ function _isoDuration(Class, params) {
2351
+ return new Class({
2352
+ type: "string",
2353
+ format: "duration",
2354
+ check: "string_format",
2355
+ ...normalizeParams(params)
2356
+ });
2357
+ }
2358
+ function _number(Class, params) {
2359
+ return new Class({
2360
+ type: "number",
2361
+ checks: [],
2362
+ ...normalizeParams(params)
2363
+ });
2364
+ }
2365
+ function _int(Class, params) {
2366
+ return new Class({
2367
+ type: "number",
2368
+ check: "number_format",
2369
+ abort: false,
2370
+ format: "safeint",
2371
+ ...normalizeParams(params)
2372
+ });
2373
+ }
2374
+ function _boolean(Class, params) {
2375
+ return new Class({
2376
+ type: "boolean",
2377
+ ...normalizeParams(params)
2378
+ });
2379
+ }
2380
+ function _unknown(Class) {
2381
+ return new Class({ type: "unknown" });
2382
+ }
2383
+ function _never(Class, params) {
2384
+ return new Class({
2385
+ type: "never",
2386
+ ...normalizeParams(params)
2387
+ });
2388
+ }
2389
+ function _lt(value, params) {
2390
+ return new $ZodCheckLessThan({
2391
+ check: "less_than",
2392
+ ...normalizeParams(params),
2393
+ value,
2394
+ inclusive: false
2395
+ });
2396
+ }
2397
+ function _lte(value, params) {
2398
+ return new $ZodCheckLessThan({
2399
+ check: "less_than",
2400
+ ...normalizeParams(params),
2401
+ value,
2402
+ inclusive: true
2403
+ });
2404
+ }
2405
+ function _gt(value, params) {
2406
+ return new $ZodCheckGreaterThan({
2407
+ check: "greater_than",
2408
+ ...normalizeParams(params),
2409
+ value,
2410
+ inclusive: false
2411
+ });
2412
+ }
2413
+ function _gte(value, params) {
2414
+ return new $ZodCheckGreaterThan({
2415
+ check: "greater_than",
2416
+ ...normalizeParams(params),
2417
+ value,
2418
+ inclusive: true
2419
+ });
2420
+ }
2421
+ function _multipleOf(value, params) {
2422
+ return new $ZodCheckMultipleOf({
2423
+ check: "multiple_of",
2424
+ ...normalizeParams(params),
2425
+ value
2426
+ });
2427
+ }
2428
+ function _maxLength(maximum, params) {
2429
+ return new $ZodCheckMaxLength({
2430
+ check: "max_length",
2431
+ ...normalizeParams(params),
2432
+ maximum
2433
+ });
2434
+ }
2435
+ function _minLength(minimum, params) {
2436
+ return new $ZodCheckMinLength({
2437
+ check: "min_length",
2438
+ ...normalizeParams(params),
2439
+ minimum
2440
+ });
2441
+ }
2442
+ function _length(length, params) {
2443
+ return new $ZodCheckLengthEquals({
2444
+ check: "length_equals",
2445
+ ...normalizeParams(params),
2446
+ length
2447
+ });
2448
+ }
2449
+ function _regex(pattern, params) {
2450
+ return new $ZodCheckRegex({
2451
+ check: "string_format",
2452
+ format: "regex",
2453
+ ...normalizeParams(params),
2454
+ pattern
2455
+ });
2456
+ }
2457
+ function _lowercase(params) {
2458
+ return new $ZodCheckLowerCase({
2459
+ check: "string_format",
2460
+ format: "lowercase",
2461
+ ...normalizeParams(params)
2462
+ });
2463
+ }
2464
+ function _uppercase(params) {
2465
+ return new $ZodCheckUpperCase({
2466
+ check: "string_format",
2467
+ format: "uppercase",
2468
+ ...normalizeParams(params)
2469
+ });
2470
+ }
2471
+ function _includes(includes, params) {
2472
+ return new $ZodCheckIncludes({
2473
+ check: "string_format",
2474
+ format: "includes",
2475
+ ...normalizeParams(params),
2476
+ includes
2477
+ });
2478
+ }
2479
+ function _startsWith(prefix, params) {
2480
+ return new $ZodCheckStartsWith({
2481
+ check: "string_format",
2482
+ format: "starts_with",
2483
+ ...normalizeParams(params),
2484
+ prefix
2485
+ });
2486
+ }
2487
+ function _endsWith(suffix, params) {
2488
+ return new $ZodCheckEndsWith({
2489
+ check: "string_format",
2490
+ format: "ends_with",
2491
+ ...normalizeParams(params),
2492
+ suffix
2493
+ });
2494
+ }
2495
+ function _overwrite(tx) {
2496
+ return new $ZodCheckOverwrite({
2497
+ check: "overwrite",
2498
+ tx
2499
+ });
2500
+ }
2501
+ function _normalize(form) {
2502
+ return _overwrite((input) => input.normalize(form));
2503
+ }
2504
+ function _trim() {
2505
+ return _overwrite((input) => input.trim());
2506
+ }
2507
+ function _toLowerCase() {
2508
+ return _overwrite((input) => input.toLowerCase());
2509
+ }
2510
+ function _toUpperCase() {
2511
+ return _overwrite((input) => input.toUpperCase());
2512
+ }
2513
+ function _array(Class, element, params) {
2514
+ return new Class({
2515
+ type: "array",
2516
+ element,
2517
+ ...normalizeParams(params)
2518
+ });
2519
+ }
2520
+ function _refine(Class, fn, _params) {
2521
+ return new Class({
2522
+ type: "custom",
2523
+ check: "custom",
2524
+ fn,
2525
+ ...normalizeParams(_params)
2526
+ });
2527
+ }
2528
+ function _superRefine(fn) {
2529
+ const ch = _check((payload) => {
2530
+ payload.addIssue = (issue$1) => {
2531
+ if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
2532
+ else {
2533
+ const _issue = issue$1;
2534
+ if (_issue.fatal) _issue.continue = false;
2535
+ _issue.code ?? (_issue.code = "custom");
2536
+ _issue.input ?? (_issue.input = payload.value);
2537
+ _issue.inst ?? (_issue.inst = ch);
2538
+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
2539
+ payload.issues.push(issue(_issue));
2540
+ }
2541
+ };
2542
+ return fn(payload.value, payload);
2543
+ });
2544
+ return ch;
2545
+ }
2546
+ function _check(fn, params) {
2547
+ const ch = new $ZodCheck({
2548
+ check: "custom",
2549
+ ...normalizeParams(params)
2550
+ });
2551
+ ch._zod.check = fn;
2552
+ return ch;
2553
+ }
2554
+
2555
+ //#endregion
2556
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/iso.js
2557
+ const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
2558
+ $ZodISODateTime.init(inst, def);
2559
+ ZodStringFormat.init(inst, def);
2560
+ });
2561
+ function datetime(params) {
2562
+ return _isoDateTime(ZodISODateTime, params);
2563
+ }
2564
+ const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
2565
+ $ZodISODate.init(inst, def);
2566
+ ZodStringFormat.init(inst, def);
2567
+ });
2568
+ function date(params) {
2569
+ return _isoDate(ZodISODate, params);
2570
+ }
2571
+ const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
2572
+ $ZodISOTime.init(inst, def);
2573
+ ZodStringFormat.init(inst, def);
2574
+ });
2575
+ function time(params) {
2576
+ return _isoTime(ZodISOTime, params);
2577
+ }
2578
+ const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
2579
+ $ZodISODuration.init(inst, def);
2580
+ ZodStringFormat.init(inst, def);
2581
+ });
2582
+ function duration(params) {
2583
+ return _isoDuration(ZodISODuration, params);
2584
+ }
2585
+
2586
+ //#endregion
2587
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/errors.js
2588
+ const initializer = (inst, issues) => {
2589
+ $ZodError.init(inst, issues);
2590
+ inst.name = "ZodError";
2591
+ Object.defineProperties(inst, {
2592
+ format: { value: (mapper) => formatError(inst, mapper) },
2593
+ flatten: { value: (mapper) => flattenError(inst, mapper) },
2594
+ addIssue: { value: (issue$1) => {
2595
+ inst.issues.push(issue$1);
2596
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2597
+ } },
2598
+ addIssues: { value: (issues$1) => {
2599
+ inst.issues.push(...issues$1);
2600
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2601
+ } },
2602
+ isEmpty: { get() {
2603
+ return inst.issues.length === 0;
2604
+ } }
2605
+ });
2606
+ };
2607
+ const ZodError = $constructor("ZodError", initializer);
2608
+ const ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
2609
+
2610
+ //#endregion
2611
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/parse.js
2612
+ const parse = /* @__PURE__ */ _parse(ZodRealError);
2613
+ const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
2614
+ const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
2615
+ const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
2616
+ const encode = /* @__PURE__ */ _encode(ZodRealError);
2617
+ const decode = /* @__PURE__ */ _decode(ZodRealError);
2618
+ const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
2619
+ const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
2620
+ const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
2621
+ const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
2622
+ const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
2623
+ const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
2624
+
2625
+ //#endregion
2626
+ //#region ../../node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/schemas.js
2627
+ const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
2628
+ $ZodType.init(inst, def);
2629
+ inst.def = def;
2630
+ inst.type = def.type;
2631
+ Object.defineProperty(inst, "_def", { value: def });
2632
+ inst.check = (...checks) => {
2633
+ return inst.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
2634
+ check: ch,
2635
+ def: { check: "custom" },
2636
+ onattach: []
2637
+ } } : ch)] }));
2638
+ };
2639
+ inst.clone = (def$1, params) => clone(inst, def$1, params);
2640
+ inst.brand = () => inst;
2641
+ inst.register = ((reg, meta) => {
2642
+ reg.add(inst, meta);
2643
+ return inst;
2644
+ });
2645
+ inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
2646
+ inst.safeParse = (data, params) => safeParse(inst, data, params);
2647
+ inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
2648
+ inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
2649
+ inst.spa = inst.safeParseAsync;
2650
+ inst.encode = (data, params) => encode(inst, data, params);
2651
+ inst.decode = (data, params) => decode(inst, data, params);
2652
+ inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
2653
+ inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
2654
+ inst.safeEncode = (data, params) => safeEncode(inst, data, params);
2655
+ inst.safeDecode = (data, params) => safeDecode(inst, data, params);
2656
+ inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
2657
+ inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
2658
+ inst.refine = (check, params) => inst.check(refine(check, params));
2659
+ inst.superRefine = (refinement) => inst.check(superRefine(refinement));
2660
+ inst.overwrite = (fn) => inst.check(_overwrite(fn));
2661
+ inst.optional = () => optional(inst);
2662
+ inst.nullable = () => nullable(inst);
2663
+ inst.nullish = () => optional(nullable(inst));
2664
+ inst.nonoptional = (params) => nonoptional(inst, params);
2665
+ inst.array = () => array(inst);
2666
+ inst.or = (arg) => union([inst, arg]);
2667
+ inst.and = (arg) => intersection(inst, arg);
2668
+ inst.transform = (tx) => pipe(inst, transform(tx));
2669
+ inst.default = (def$1) => _default(inst, def$1);
2670
+ inst.prefault = (def$1) => prefault(inst, def$1);
2671
+ inst.catch = (params) => _catch(inst, params);
2672
+ inst.pipe = (target) => pipe(inst, target);
2673
+ inst.readonly = () => readonly(inst);
2674
+ inst.describe = (description) => {
2675
+ const cl = inst.clone();
2676
+ globalRegistry.add(cl, { description });
2677
+ return cl;
2678
+ };
2679
+ Object.defineProperty(inst, "description", {
2680
+ get() {
2681
+ return globalRegistry.get(inst)?.description;
2682
+ },
2683
+ configurable: true
2684
+ });
2685
+ inst.meta = (...args) => {
2686
+ if (args.length === 0) return globalRegistry.get(inst);
2687
+ const cl = inst.clone();
2688
+ globalRegistry.add(cl, args[0]);
2689
+ return cl;
2690
+ };
2691
+ inst.isOptional = () => inst.safeParse(void 0).success;
2692
+ inst.isNullable = () => inst.safeParse(null).success;
2693
+ return inst;
2694
+ });
2695
+ /** @internal */
2696
+ const _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
2697
+ $ZodString.init(inst, def);
2698
+ ZodType.init(inst, def);
2699
+ const bag = inst._zod.bag;
2700
+ inst.format = bag.format ?? null;
2701
+ inst.minLength = bag.minimum ?? null;
2702
+ inst.maxLength = bag.maximum ?? null;
2703
+ inst.regex = (...args) => inst.check(_regex(...args));
2704
+ inst.includes = (...args) => inst.check(_includes(...args));
2705
+ inst.startsWith = (...args) => inst.check(_startsWith(...args));
2706
+ inst.endsWith = (...args) => inst.check(_endsWith(...args));
2707
+ inst.min = (...args) => inst.check(_minLength(...args));
2708
+ inst.max = (...args) => inst.check(_maxLength(...args));
2709
+ inst.length = (...args) => inst.check(_length(...args));
2710
+ inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
2711
+ inst.lowercase = (params) => inst.check(_lowercase(params));
2712
+ inst.uppercase = (params) => inst.check(_uppercase(params));
2713
+ inst.trim = () => inst.check(_trim());
2714
+ inst.normalize = (...args) => inst.check(_normalize(...args));
2715
+ inst.toLowerCase = () => inst.check(_toLowerCase());
2716
+ inst.toUpperCase = () => inst.check(_toUpperCase());
2717
+ });
2718
+ const ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
2719
+ $ZodString.init(inst, def);
2720
+ _ZodString.init(inst, def);
2721
+ inst.email = (params) => inst.check(_email(ZodEmail, params));
2722
+ inst.url = (params) => inst.check(_url(ZodURL, params));
2723
+ inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
2724
+ inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
2725
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
2726
+ inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
2727
+ inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
2728
+ inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
2729
+ inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
2730
+ inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
2731
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
2732
+ inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
2733
+ inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
2734
+ inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
2735
+ inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
2736
+ inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
2737
+ inst.xid = (params) => inst.check(_xid(ZodXID, params));
2738
+ inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
2739
+ inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
2740
+ inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
2741
+ inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
2742
+ inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
2743
+ inst.e164 = (params) => inst.check(_e164(ZodE164, params));
2744
+ inst.datetime = (params) => inst.check(datetime(params));
2745
+ inst.date = (params) => inst.check(date(params));
2746
+ inst.time = (params) => inst.check(time(params));
2747
+ inst.duration = (params) => inst.check(duration(params));
2748
+ });
2749
+ function string(params) {
2750
+ return _string(ZodString, params);
2751
+ }
2752
+ const ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
2753
+ $ZodStringFormat.init(inst, def);
2754
+ _ZodString.init(inst, def);
2755
+ });
2756
+ const ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
2757
+ $ZodEmail.init(inst, def);
2758
+ ZodStringFormat.init(inst, def);
2759
+ });
2760
+ const ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
2761
+ $ZodGUID.init(inst, def);
2762
+ ZodStringFormat.init(inst, def);
2763
+ });
2764
+ const ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
2765
+ $ZodUUID.init(inst, def);
2766
+ ZodStringFormat.init(inst, def);
2767
+ });
2768
+ const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
2769
+ $ZodURL.init(inst, def);
2770
+ ZodStringFormat.init(inst, def);
2771
+ });
2772
+ const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
2773
+ $ZodEmoji.init(inst, def);
2774
+ ZodStringFormat.init(inst, def);
2775
+ });
2776
+ const ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
2777
+ $ZodNanoID.init(inst, def);
2778
+ ZodStringFormat.init(inst, def);
2779
+ });
2780
+ const ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
2781
+ $ZodCUID.init(inst, def);
2782
+ ZodStringFormat.init(inst, def);
2783
+ });
2784
+ const ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
2785
+ $ZodCUID2.init(inst, def);
2786
+ ZodStringFormat.init(inst, def);
2787
+ });
2788
+ const ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
2789
+ $ZodULID.init(inst, def);
2790
+ ZodStringFormat.init(inst, def);
2791
+ });
2792
+ const ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
2793
+ $ZodXID.init(inst, def);
2794
+ ZodStringFormat.init(inst, def);
2795
+ });
2796
+ const ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
2797
+ $ZodKSUID.init(inst, def);
2798
+ ZodStringFormat.init(inst, def);
2799
+ });
2800
+ const ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
2801
+ $ZodIPv4.init(inst, def);
2802
+ ZodStringFormat.init(inst, def);
2803
+ });
2804
+ const ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
2805
+ $ZodIPv6.init(inst, def);
2806
+ ZodStringFormat.init(inst, def);
2807
+ });
2808
+ const ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
2809
+ $ZodCIDRv4.init(inst, def);
2810
+ ZodStringFormat.init(inst, def);
2811
+ });
2812
+ const ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
2813
+ $ZodCIDRv6.init(inst, def);
2814
+ ZodStringFormat.init(inst, def);
2815
+ });
2816
+ const ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
2817
+ $ZodBase64.init(inst, def);
2818
+ ZodStringFormat.init(inst, def);
2819
+ });
2820
+ const ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
2821
+ $ZodBase64URL.init(inst, def);
2822
+ ZodStringFormat.init(inst, def);
2823
+ });
2824
+ const ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
2825
+ $ZodE164.init(inst, def);
2826
+ ZodStringFormat.init(inst, def);
2827
+ });
2828
+ const ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
2829
+ $ZodJWT.init(inst, def);
2830
+ ZodStringFormat.init(inst, def);
2831
+ });
2832
+ const ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
2833
+ $ZodNumber.init(inst, def);
2834
+ ZodType.init(inst, def);
2835
+ inst.gt = (value, params) => inst.check(_gt(value, params));
2836
+ inst.gte = (value, params) => inst.check(_gte(value, params));
2837
+ inst.min = (value, params) => inst.check(_gte(value, params));
2838
+ inst.lt = (value, params) => inst.check(_lt(value, params));
2839
+ inst.lte = (value, params) => inst.check(_lte(value, params));
2840
+ inst.max = (value, params) => inst.check(_lte(value, params));
2841
+ inst.int = (params) => inst.check(int(params));
2842
+ inst.safe = (params) => inst.check(int(params));
2843
+ inst.positive = (params) => inst.check(_gt(0, params));
2844
+ inst.nonnegative = (params) => inst.check(_gte(0, params));
2845
+ inst.negative = (params) => inst.check(_lt(0, params));
2846
+ inst.nonpositive = (params) => inst.check(_lte(0, params));
2847
+ inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
2848
+ inst.step = (value, params) => inst.check(_multipleOf(value, params));
2849
+ inst.finite = () => inst;
2850
+ const bag = inst._zod.bag;
2851
+ inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
2852
+ inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
2853
+ inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
2854
+ inst.isFinite = true;
2855
+ inst.format = bag.format ?? null;
2856
+ });
2857
+ function number(params) {
2858
+ return _number(ZodNumber, params);
2859
+ }
2860
+ const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
2861
+ $ZodNumberFormat.init(inst, def);
2862
+ ZodNumber.init(inst, def);
2863
+ });
2864
+ function int(params) {
2865
+ return _int(ZodNumberFormat, params);
2866
+ }
2867
+ const ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
2868
+ $ZodBoolean.init(inst, def);
2869
+ ZodType.init(inst, def);
2870
+ });
2871
+ function boolean(params) {
2872
+ return _boolean(ZodBoolean, params);
2873
+ }
2874
+ const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
2875
+ $ZodUnknown.init(inst, def);
2876
+ ZodType.init(inst, def);
2877
+ });
2878
+ function unknown() {
2879
+ return _unknown(ZodUnknown);
2880
+ }
2881
+ const ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
2882
+ $ZodNever.init(inst, def);
2883
+ ZodType.init(inst, def);
2884
+ });
2885
+ function never(params) {
2886
+ return _never(ZodNever, params);
2887
+ }
2888
+ const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
2889
+ $ZodArray.init(inst, def);
2890
+ ZodType.init(inst, def);
2891
+ inst.element = def.element;
2892
+ inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
2893
+ inst.nonempty = (params) => inst.check(_minLength(1, params));
2894
+ inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
2895
+ inst.length = (len, params) => inst.check(_length(len, params));
2896
+ inst.unwrap = () => inst.element;
2897
+ });
2898
+ function array(element, params) {
2899
+ return _array(ZodArray, element, params);
2900
+ }
2901
+ const ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
2902
+ $ZodObjectJIT.init(inst, def);
2903
+ ZodType.init(inst, def);
2904
+ defineLazy(inst, "shape", () => {
2905
+ return def.shape;
2906
+ });
2907
+ inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
2908
+ inst.catchall = (catchall) => inst.clone({
2909
+ ...inst._zod.def,
2910
+ catchall
2911
+ });
2912
+ inst.passthrough = () => inst.clone({
2913
+ ...inst._zod.def,
2914
+ catchall: unknown()
2915
+ });
2916
+ inst.loose = () => inst.clone({
2917
+ ...inst._zod.def,
2918
+ catchall: unknown()
2919
+ });
2920
+ inst.strict = () => inst.clone({
2921
+ ...inst._zod.def,
2922
+ catchall: never()
2923
+ });
2924
+ inst.strip = () => inst.clone({
2925
+ ...inst._zod.def,
2926
+ catchall: void 0
2927
+ });
2928
+ inst.extend = (incoming) => {
2929
+ return extend(inst, incoming);
2930
+ };
2931
+ inst.safeExtend = (incoming) => {
2932
+ return safeExtend(inst, incoming);
2933
+ };
2934
+ inst.merge = (other) => merge(inst, other);
2935
+ inst.pick = (mask) => pick(inst, mask);
2936
+ inst.omit = (mask) => omit(inst, mask);
2937
+ inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
2938
+ inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
2939
+ });
2940
+ function object(shape, params) {
2941
+ return new ZodObject({
2942
+ type: "object",
2943
+ shape: shape ?? {},
2944
+ ...normalizeParams(params)
2945
+ });
2946
+ }
2947
+ const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
2948
+ $ZodUnion.init(inst, def);
2949
+ ZodType.init(inst, def);
2950
+ inst.options = def.options;
2951
+ });
2952
+ function union(options, params) {
2953
+ return new ZodUnion({
2954
+ type: "union",
2955
+ options,
2956
+ ...normalizeParams(params)
2957
+ });
2958
+ }
2959
+ const ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
2960
+ ZodUnion.init(inst, def);
2961
+ $ZodDiscriminatedUnion.init(inst, def);
2962
+ });
2963
+ function discriminatedUnion(discriminator, options, params) {
2964
+ return new ZodDiscriminatedUnion({
2965
+ type: "union",
2966
+ options,
2967
+ discriminator,
2968
+ ...normalizeParams(params)
2969
+ });
2970
+ }
2971
+ const ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
2972
+ $ZodIntersection.init(inst, def);
2973
+ ZodType.init(inst, def);
2974
+ });
2975
+ function intersection(left, right) {
2976
+ return new ZodIntersection({
2977
+ type: "intersection",
2978
+ left,
2979
+ right
2980
+ });
2981
+ }
2982
+ const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
2983
+ $ZodEnum.init(inst, def);
2984
+ ZodType.init(inst, def);
2985
+ inst.enum = def.entries;
2986
+ inst.options = Object.values(def.entries);
2987
+ const keys = new Set(Object.keys(def.entries));
2988
+ inst.extract = (values, params) => {
2989
+ const newEntries = {};
2990
+ for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
2991
+ else throw new Error(`Key ${value} not found in enum`);
2992
+ return new ZodEnum({
2993
+ ...def,
2994
+ checks: [],
2995
+ ...normalizeParams(params),
2996
+ entries: newEntries
2997
+ });
2998
+ };
2999
+ inst.exclude = (values, params) => {
3000
+ const newEntries = { ...def.entries };
3001
+ for (const value of values) if (keys.has(value)) delete newEntries[value];
3002
+ else throw new Error(`Key ${value} not found in enum`);
3003
+ return new ZodEnum({
3004
+ ...def,
3005
+ checks: [],
3006
+ ...normalizeParams(params),
3007
+ entries: newEntries
3008
+ });
3009
+ };
3010
+ });
3011
+ function _enum(values, params) {
3012
+ return new ZodEnum({
3013
+ type: "enum",
3014
+ entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values,
3015
+ ...normalizeParams(params)
3016
+ });
3017
+ }
3018
+ const ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
3019
+ $ZodLiteral.init(inst, def);
3020
+ ZodType.init(inst, def);
3021
+ inst.values = new Set(def.values);
3022
+ Object.defineProperty(inst, "value", { get() {
3023
+ if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
3024
+ return def.values[0];
3025
+ } });
3026
+ });
3027
+ function literal(value, params) {
3028
+ return new ZodLiteral({
3029
+ type: "literal",
3030
+ values: Array.isArray(value) ? value : [value],
3031
+ ...normalizeParams(params)
3032
+ });
3033
+ }
3034
+ const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
3035
+ $ZodTransform.init(inst, def);
3036
+ ZodType.init(inst, def);
3037
+ inst._zod.parse = (payload, _ctx) => {
3038
+ if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
3039
+ payload.addIssue = (issue$1) => {
3040
+ if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def));
3041
+ else {
3042
+ const _issue = issue$1;
3043
+ if (_issue.fatal) _issue.continue = false;
3044
+ _issue.code ?? (_issue.code = "custom");
3045
+ _issue.input ?? (_issue.input = payload.value);
3046
+ _issue.inst ?? (_issue.inst = inst);
3047
+ payload.issues.push(issue(_issue));
3048
+ }
3049
+ };
3050
+ const output = def.transform(payload.value, payload);
3051
+ if (output instanceof Promise) return output.then((output$1) => {
3052
+ payload.value = output$1;
3053
+ return payload;
3054
+ });
3055
+ payload.value = output;
3056
+ return payload;
3057
+ };
3058
+ });
3059
+ function transform(fn) {
3060
+ return new ZodTransform({
3061
+ type: "transform",
3062
+ transform: fn
3063
+ });
3064
+ }
3065
+ const ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
3066
+ $ZodOptional.init(inst, def);
3067
+ ZodType.init(inst, def);
3068
+ inst.unwrap = () => inst._zod.def.innerType;
3069
+ });
3070
+ function optional(innerType) {
3071
+ return new ZodOptional({
3072
+ type: "optional",
3073
+ innerType
3074
+ });
3075
+ }
3076
+ const ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
3077
+ $ZodNullable.init(inst, def);
3078
+ ZodType.init(inst, def);
3079
+ inst.unwrap = () => inst._zod.def.innerType;
3080
+ });
3081
+ function nullable(innerType) {
3082
+ return new ZodNullable({
3083
+ type: "nullable",
3084
+ innerType
3085
+ });
3086
+ }
3087
+ const ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
3088
+ $ZodDefault.init(inst, def);
3089
+ ZodType.init(inst, def);
3090
+ inst.unwrap = () => inst._zod.def.innerType;
3091
+ inst.removeDefault = inst.unwrap;
3092
+ });
3093
+ function _default(innerType, defaultValue) {
3094
+ return new ZodDefault({
3095
+ type: "default",
3096
+ innerType,
3097
+ get defaultValue() {
3098
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3099
+ }
3100
+ });
3101
+ }
3102
+ const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
3103
+ $ZodPrefault.init(inst, def);
3104
+ ZodType.init(inst, def);
3105
+ inst.unwrap = () => inst._zod.def.innerType;
3106
+ });
3107
+ function prefault(innerType, defaultValue) {
3108
+ return new ZodPrefault({
3109
+ type: "prefault",
3110
+ innerType,
3111
+ get defaultValue() {
3112
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3113
+ }
3114
+ });
3115
+ }
3116
+ const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
3117
+ $ZodNonOptional.init(inst, def);
3118
+ ZodType.init(inst, def);
3119
+ inst.unwrap = () => inst._zod.def.innerType;
3120
+ });
3121
+ function nonoptional(innerType, params) {
3122
+ return new ZodNonOptional({
3123
+ type: "nonoptional",
3124
+ innerType,
3125
+ ...normalizeParams(params)
3126
+ });
3127
+ }
3128
+ const ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
3129
+ $ZodCatch.init(inst, def);
3130
+ ZodType.init(inst, def);
3131
+ inst.unwrap = () => inst._zod.def.innerType;
3132
+ inst.removeCatch = inst.unwrap;
3133
+ });
3134
+ function _catch(innerType, catchValue) {
3135
+ return new ZodCatch({
3136
+ type: "catch",
3137
+ innerType,
3138
+ catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
3139
+ });
3140
+ }
3141
+ const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
3142
+ $ZodPipe.init(inst, def);
3143
+ ZodType.init(inst, def);
3144
+ inst.in = def.in;
3145
+ inst.out = def.out;
3146
+ });
3147
+ function pipe(in_, out) {
3148
+ return new ZodPipe({
3149
+ type: "pipe",
3150
+ in: in_,
3151
+ out
3152
+ });
3153
+ }
3154
+ const ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
3155
+ $ZodReadonly.init(inst, def);
3156
+ ZodType.init(inst, def);
3157
+ inst.unwrap = () => inst._zod.def.innerType;
3158
+ });
3159
+ function readonly(innerType) {
3160
+ return new ZodReadonly({
3161
+ type: "readonly",
3162
+ innerType
3163
+ });
3164
+ }
3165
+ const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
3166
+ $ZodCustom.init(inst, def);
3167
+ ZodType.init(inst, def);
3168
+ });
3169
+ function refine(fn, _params = {}) {
3170
+ return _refine(ZodCustom, fn, _params);
3171
+ }
3172
+ function superRefine(fn) {
3173
+ return _superRefine(fn);
3174
+ }
3175
+
3176
+ //#endregion
3177
+ //#region ../mcp-shared/dist/index.js
3178
+ const MCP_PORT_CANDIDATES = [
3179
+ 6220,
3180
+ 7431,
3181
+ 8127
3182
+ ];
3183
+ const MCP_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
3184
+ const MCP_TOOL_TIMEOUT_MS = 15e3;
3185
+ const MCP_AUTO_ACTIVATE_GRACE_MS = 1500;
3186
+ const MCP_MAX_ASSET_BYTES = 8 * 1024 * 1024;
3187
+ const MCP_ASSET_RESOURCE_NAME = "tempad-assets";
3188
+ const MCP_ASSET_URI_PREFIX = "asset://tempad/";
3189
+ const MCP_ASSET_URI_TEMPLATE = `${MCP_ASSET_URI_PREFIX}{hash}`;
3190
+ const MCP_HASH_HEX_LENGTH = 8;
3191
+ const MCP_HASH_PATTERN = new RegExp(`^[a-f0-9]{${MCP_HASH_HEX_LENGTH}}$`, "i");
3192
+ const RegisteredMessageSchema = object({
3193
+ type: literal("registered"),
3194
+ id: string()
3195
+ });
3196
+ const StateMessageSchema = object({
3197
+ type: literal("state"),
3198
+ activeId: string().nullable(),
3199
+ count: number().nonnegative(),
3200
+ port: number().positive(),
3201
+ assetServerUrl: string().url()
3202
+ });
3203
+ const ToolCallPayloadSchema = object({
3204
+ name: string(),
3205
+ args: unknown()
3206
+ });
3207
+ const ToolCallMessageSchema = object({
3208
+ type: literal("toolCall"),
3209
+ id: string(),
3210
+ payload: ToolCallPayloadSchema
3211
+ });
3212
+ const MessageToExtensionSchema = discriminatedUnion("type", [
3213
+ RegisteredMessageSchema,
3214
+ StateMessageSchema,
3215
+ ToolCallMessageSchema
3216
+ ]);
3217
+ const ActivateMessageSchema = object({ type: literal("activate") });
3218
+ const ToolResultMessageSchema = object({
3219
+ type: literal("toolResult"),
3220
+ id: string(),
3221
+ payload: unknown().optional(),
3222
+ error: unknown().optional()
3223
+ });
3224
+ const MessageFromExtensionSchema = discriminatedUnion("type", [ActivateMessageSchema, ToolResultMessageSchema]);
3225
+ const AssetDescriptorSchema = object({
3226
+ hash: string().min(1),
3227
+ url: string().url(),
3228
+ mimeType: string().min(1),
3229
+ size: number().int().nonnegative(),
3230
+ resourceUri: string().regex(/^asset:\/\/tempad\/[a-f0-9]{8}$/i),
3231
+ width: number().int().positive().optional(),
3232
+ height: number().int().positive().optional()
3233
+ });
3234
+ const GetCodeParametersSchema = object({
3235
+ nodeId: string().describe("Optional target node id; omit to use the current single selection when pulling the baseline snapshot.").optional(),
3236
+ preferredLang: _enum(["jsx", "vue"]).describe("Preferred output language to bias the snapshot; otherwise uses the design’s hint/detected language, then falls back to JSX.").optional(),
3237
+ resolveTokens: boolean().describe("Inline token values instead of references for quick renders; default false returns token metadata so you can map into your theming system.").optional()
3238
+ });
3239
+ const GetTokenDefsParametersSchema = object({
3240
+ names: array(string().regex(/^--[a-zA-Z0-9-_]+$/)).min(1).describe("Canonical token names (CSS variable form) from get_code.usedTokens or your own list to resolve, e.g., --color-primary."),
3241
+ includeAllModes: boolean().describe("Include all token modes (light/dark/etc.) instead of just the active one to mirror responsive tokens; default false.").optional()
3242
+ });
3243
+ const GetScreenshotParametersSchema = object({ nodeId: string().describe("Optional node id to screenshot; defaults to the current single selection. Useful when layout/overlap is uncertain (auto-layout none/inferred).").optional() });
3244
+ const GetStructureParametersSchema = object({
3245
+ nodeId: string().describe("Optional node id to outline; defaults to the current single selection. Useful when auto-layout hints are none/inferred or you need explicit geometry for refactors.").optional(),
3246
+ options: object({ depth: number().int().positive().describe("Limit traversal depth; defaults to full tree (subject to safety caps).").optional() }).optional()
3247
+ });
3248
+ const GetAssetsParametersSchema = object({ hashes: array(string().regex(MCP_HASH_PATTERN)).min(1).describe("Asset hashes returned from get_code (or other tools) to download/resolve exact bytes for rasterized images or SVGs before routing through your asset pipeline.") });
3249
+ const GetAssetsResultSchema = object({
3250
+ assets: array(AssetDescriptorSchema),
3251
+ missing: array(string().min(1))
3252
+ });
3253
+
3254
+ //#endregion
3255
+ //#region src/config.ts
3256
+ function parsePositiveInt(envValue, fallback) {
3257
+ const parsed = envValue ? Number.parseInt(envValue, 10) : NaN;
3258
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
3259
+ }
3260
+ function resolveToolTimeoutMs() {
3261
+ return parsePositiveInt(process.env.TEMPAD_MCP_TOOL_TIMEOUT, MCP_TOOL_TIMEOUT_MS);
3262
+ }
3263
+ function resolveAutoActivateGraceMs() {
3264
+ return parsePositiveInt(process.env.TEMPAD_MCP_AUTO_ACTIVATE_GRACE, MCP_AUTO_ACTIVATE_GRACE_MS);
3265
+ }
3266
+ function resolveMaxAssetSizeBytes() {
3267
+ return parsePositiveInt(process.env.TEMPAD_MCP_MAX_ASSET_BYTES, MCP_MAX_ASSET_BYTES);
3268
+ }
3269
+ function getMcpServerConfig() {
3270
+ return {
3271
+ wsPortCandidates: [...MCP_PORT_CANDIDATES],
3272
+ toolTimeoutMs: resolveToolTimeoutMs(),
3273
+ maxPayloadBytes: MCP_MAX_PAYLOAD_BYTES,
3274
+ autoActivateGraceMs: resolveAutoActivateGraceMs(),
3275
+ maxAssetSizeBytes: resolveMaxAssetSizeBytes()
3276
+ };
3277
+ }
3278
+
3279
+ //#endregion
3280
+ //#region src/asset-http-server.ts
3281
+ const LOOPBACK_HOST = "127.0.0.1";
3282
+ const { maxAssetSizeBytes } = getMcpServerConfig();
3283
+ function createAssetHttpServer(store) {
3284
+ const server = createServer$1(handleRequest);
3285
+ let port$1 = null;
3286
+ async function start() {
3287
+ if (port$1 !== null) return;
3288
+ await new Promise((resolve$1, reject$1) => {
3289
+ const onError = (error) => {
3290
+ server.off("listening", onListening);
3291
+ reject$1(error);
3292
+ };
3293
+ const onListening = () => {
3294
+ server.off("error", onError);
3295
+ const address = server.address();
3296
+ if (address && typeof address === "object") {
3297
+ port$1 = address.port;
3298
+ resolve$1();
3299
+ } else reject$1(/* @__PURE__ */ new Error("Failed to determine HTTP server port."));
3300
+ };
3301
+ server.once("error", onError);
3302
+ server.once("listening", onListening);
3303
+ server.listen(0, LOOPBACK_HOST);
3304
+ });
3305
+ log.info({ port: port$1 }, "Asset HTTP server ready.");
3306
+ }
3307
+ function stop() {
3308
+ if (port$1 === null) return;
3309
+ server.close();
3310
+ port$1 = null;
3311
+ }
3312
+ function getBaseUrl() {
3313
+ if (port$1 === null) throw new Error("Asset HTTP server is not running.");
3314
+ return `http://${LOOPBACK_HOST}:${port$1}`;
3315
+ }
3316
+ function handleRequest(req, res) {
3317
+ res.setHeader("Access-Control-Allow-Origin", "*");
3318
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
3319
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Asset-Width, X-Asset-Height");
3320
+ if (req.method === "OPTIONS") {
3321
+ res.writeHead(204);
3322
+ res.end();
3323
+ return;
3324
+ }
3325
+ if (!req.url) {
3326
+ res.writeHead(400);
3327
+ res.end("Missing URL");
3328
+ return;
3329
+ }
3330
+ const segments = new URL$1(req.url, getBaseUrl()).pathname.split("/").filter(Boolean);
3331
+ if (segments.length !== 2 || segments[0] !== "assets") {
3332
+ res.writeHead(404);
3333
+ res.end("Not Found");
3334
+ return;
3335
+ }
3336
+ const hash = segments[1];
3337
+ if (req.method === "POST") {
3338
+ handleUpload(req, res, hash);
3339
+ return;
3340
+ }
3341
+ if (req.method === "GET") {
3342
+ handleDownload(req, res, hash);
3343
+ return;
3344
+ }
3345
+ res.writeHead(405);
3346
+ res.end("Method Not Allowed");
3347
+ }
3348
+ function handleDownload(req, res, hash) {
3349
+ const record = store.get(hash);
3350
+ if (!record) {
3351
+ res.writeHead(404);
3352
+ res.end("Not Found");
3353
+ return;
3354
+ }
3355
+ let stat;
3356
+ try {
3357
+ stat = statSync(record.filePath);
3358
+ } catch (error) {
3359
+ if (error.code === "ENOENT") {
3360
+ store.remove(hash, { removeFile: false });
3361
+ res.writeHead(404);
3362
+ res.end("Not Found");
3363
+ } else {
3364
+ log.error({
3365
+ error,
3366
+ hash
3367
+ }, "Failed to stat asset file.");
3368
+ res.writeHead(500);
3369
+ res.end("Internal Server Error");
3370
+ }
3371
+ return;
3372
+ }
3373
+ res.writeHead(200, {
3374
+ "Content-Type": record.mimeType,
3375
+ "Content-Length": stat.size.toString(),
3376
+ "Cache-Control": "public, max-age=31536000, immutable"
3377
+ });
3378
+ const stream = createReadStream(record.filePath);
3379
+ stream.on("error", (error) => {
3380
+ log.warn({
3381
+ error,
3382
+ hash
3383
+ }, "Failed to stream asset file.");
3384
+ if (!res.headersSent) res.writeHead(500);
3385
+ res.end("Internal Server Error");
3386
+ });
3387
+ stream.on("open", () => {
3388
+ store.touch(hash);
3389
+ });
3390
+ stream.pipe(res);
3391
+ }
3392
+ function handleUpload(req, res, hash) {
3393
+ if (!MCP_HASH_PATTERN.test(hash)) {
3394
+ res.writeHead(400);
3395
+ res.end("Invalid Hash Format");
3396
+ return;
3397
+ }
3398
+ const mimeType = req.headers["content-type"] || "application/octet-stream";
3399
+ const filePath = join(ASSET_DIR, hash);
3400
+ const width = parseInt(req.headers["x-asset-width"], 10);
3401
+ const height = parseInt(req.headers["x-asset-height"], 10);
3402
+ const metadata = !isNaN(width) && !isNaN(height) && width > 0 && height > 0 ? {
3403
+ width,
3404
+ height
3405
+ } : void 0;
3406
+ if (store.has(hash) && existsSync(filePath)) {
3407
+ req.resume();
3408
+ const existing = store.get(hash);
3409
+ let changed = false;
3410
+ if (metadata) {
3411
+ existing.metadata = metadata;
3412
+ changed = true;
3413
+ }
3414
+ if (existing.mimeType !== mimeType) {
3415
+ existing.mimeType = mimeType;
3416
+ changed = true;
3417
+ }
3418
+ if (changed) store.upsert(existing);
3419
+ store.touch(hash);
3420
+ res.writeHead(200);
3421
+ res.end("OK");
3422
+ return;
3423
+ }
3424
+ const tmpPath = `${filePath}.tmp.${nanoid()}`;
3425
+ const writeStream = createWriteStream(tmpPath);
3426
+ const hasher = createHash("sha256");
3427
+ let size = 0;
3428
+ const cleanup = () => {
3429
+ if (existsSync(tmpPath)) try {
3430
+ unlinkSync(tmpPath);
3431
+ } catch (e) {
3432
+ log.warn({
3433
+ error: e,
3434
+ tmpPath
3435
+ }, "Failed to cleanup temp file.");
3436
+ }
3437
+ };
3438
+ pipeline(req, new Transform({ transform(chunk, encoding, callback) {
3439
+ size += chunk.length;
3440
+ if (size > maxAssetSizeBytes) {
3441
+ callback(/* @__PURE__ */ new Error("PayloadTooLarge"));
3442
+ return;
3443
+ }
3444
+ hasher.update(chunk);
3445
+ callback(null, chunk);
3446
+ } }), writeStream, (err) => {
3447
+ if (err) {
3448
+ cleanup();
3449
+ if (err.message === "PayloadTooLarge") {
3450
+ res.writeHead(413);
3451
+ res.end("Payload Too Large");
3452
+ } else if (err.code === "ERR_STREAM_PREMATURE_CLOSE") log.warn({ hash }, "Upload request closed prematurely.");
3453
+ else {
3454
+ log.error({
3455
+ error: err,
3456
+ hash
3457
+ }, "Upload pipeline failed.");
3458
+ if (!res.headersSent) {
3459
+ res.writeHead(500);
3460
+ res.end("Internal Server Error");
3461
+ }
3462
+ }
3463
+ return;
3464
+ }
3465
+ if (hasher.digest("hex") !== hash) {
3466
+ cleanup();
3467
+ res.writeHead(400);
3468
+ res.end("Hash Mismatch");
3469
+ return;
3470
+ }
3471
+ try {
3472
+ renameSync(tmpPath, filePath);
3473
+ } catch (error) {
3474
+ log.error({
3475
+ error,
3476
+ hash
3477
+ }, "Failed to rename temp file to asset.");
3478
+ cleanup();
3479
+ res.writeHead(500);
3480
+ res.end("Internal Server Error");
3481
+ return;
3482
+ }
3483
+ store.upsert({
3484
+ hash,
3485
+ filePath,
3486
+ mimeType,
3487
+ size,
3488
+ metadata
3489
+ });
3490
+ log.info({
3491
+ hash,
3492
+ size
3493
+ }, "Stored uploaded asset via HTTP.");
3494
+ res.writeHead(201);
3495
+ res.end("Created");
3496
+ });
3497
+ }
3498
+ return {
3499
+ start,
3500
+ stop,
3501
+ getBaseUrl
3502
+ };
3503
+ }
3504
+
3505
+ //#endregion
3506
+ //#region src/asset-store.ts
3507
+ const INDEX_FILENAME = "assets.json";
3508
+ const DEFAULT_INDEX_PATH = join(ASSET_DIR, INDEX_FILENAME);
3509
+ function readIndex(indexPath) {
3510
+ if (!existsSync(indexPath)) return [];
3511
+ try {
3512
+ const raw = readFileSync(indexPath, "utf8").trim();
3513
+ if (!raw) return [];
3514
+ const parsed = JSON.parse(raw);
3515
+ return Array.isArray(parsed) ? parsed : [];
3516
+ } catch (error) {
3517
+ log.warn({
3518
+ error,
3519
+ indexPath
3520
+ }, "Failed to read asset catalog; starting fresh.");
3521
+ return [];
3522
+ }
3523
+ }
3524
+ function writeIndex(indexPath, values) {
3525
+ writeFileSync(indexPath, JSON.stringify(values, null, 2), "utf8");
3526
+ }
3527
+ function createAssetStore(options = {}) {
3528
+ ensureDir(ASSET_DIR);
3529
+ const indexPath = options.indexPath ?? DEFAULT_INDEX_PATH;
3530
+ ensureFile(indexPath);
3531
+ const records = /* @__PURE__ */ new Map();
3532
+ let persistTimer = null;
3533
+ function loadExisting() {
3534
+ const list$1 = readIndex(indexPath);
3535
+ for (const record of list$1) if (record?.hash && record?.filePath) records.set(record.hash, record);
3536
+ }
3537
+ function persist() {
3538
+ if (persistTimer) return;
3539
+ persistTimer = setTimeout(() => {
3540
+ persistTimer = null;
3541
+ writeIndex(indexPath, [...records.values()]);
3542
+ }, 5e3);
3543
+ if (typeof persistTimer.unref === "function") persistTimer.unref();
3544
+ }
3545
+ function flush() {
3546
+ if (persistTimer) {
3547
+ clearTimeout(persistTimer);
3548
+ persistTimer = null;
3549
+ }
3550
+ writeIndex(indexPath, [...records.values()]);
3551
+ }
3552
+ function list() {
3553
+ return [...records.values()];
3554
+ }
3555
+ function has(hash) {
3556
+ return records.has(hash);
3557
+ }
3558
+ function get(hash) {
3559
+ return records.get(hash);
3560
+ }
3561
+ function getMany(hashes) {
3562
+ return hashes.map((hash) => records.get(hash)).filter((record) => !!record);
3563
+ }
3564
+ function upsert(input) {
3565
+ const now = Date.now();
3566
+ const record = {
3567
+ ...input,
3568
+ uploadedAt: input.uploadedAt ?? now,
3569
+ lastAccess: input.lastAccess ?? now
3570
+ };
3571
+ records.set(record.hash, record);
3572
+ persist();
3573
+ return record;
3574
+ }
3575
+ function touch(hash) {
3576
+ const existing = records.get(hash);
3577
+ if (!existing) return void 0;
3578
+ existing.lastAccess = Date.now();
3579
+ persist();
3580
+ return existing;
3581
+ }
3582
+ function remove(hash, { removeFile = true } = {}) {
3583
+ const record = records.get(hash);
3584
+ if (!record) return;
3585
+ records.delete(hash);
3586
+ persist();
3587
+ if (removeFile) try {
3588
+ rmSync(record.filePath, { force: true });
3589
+ } catch (error) {
3590
+ log.warn({
3591
+ hash,
3592
+ error
3593
+ }, "Failed to remove asset file on delete.");
3594
+ }
3595
+ }
3596
+ function reconcile() {
3597
+ let changed = false;
3598
+ for (const [hash, record] of records) if (!existsSync(record.filePath)) {
3599
+ records.delete(hash);
3600
+ changed = true;
3601
+ }
3602
+ try {
3603
+ const files = readdirSync(ASSET_DIR);
3604
+ const now = Date.now();
3605
+ for (const file of files) {
3606
+ if (file === INDEX_FILENAME) continue;
3607
+ if (file.includes(".tmp.")) {
3608
+ try {
3609
+ const filePath = join(ASSET_DIR, file);
3610
+ if (now - statSync(filePath).mtimeMs > 3600 * 1e3) {
3611
+ rmSync(filePath, { force: true });
3612
+ log.info({ file }, "Cleaned up stale temp file.");
3613
+ }
3614
+ } catch (e) {
3615
+ log.debug({
3616
+ error: e,
3617
+ file
3618
+ }, "Failed to cleanup stale temp file.");
3619
+ }
3620
+ continue;
3621
+ }
3622
+ if (!MCP_HASH_PATTERN.test(file)) continue;
3623
+ if (!records.has(file)) {
3624
+ const filePath = join(ASSET_DIR, file);
3625
+ try {
3626
+ const stat = statSync(filePath);
3627
+ records.set(file, {
3628
+ hash: file,
3629
+ filePath,
3630
+ mimeType: "application/octet-stream",
3631
+ size: stat.size,
3632
+ uploadedAt: stat.birthtimeMs,
3633
+ lastAccess: stat.atimeMs
3634
+ });
3635
+ changed = true;
3636
+ log.info({ hash: file }, "Recovered orphan asset file.");
3637
+ } catch (e) {
3638
+ log.warn({
3639
+ error: e,
3640
+ file
3641
+ }, "Failed to stat orphan file.");
3642
+ }
3643
+ }
3644
+ }
3645
+ } catch (error) {
3646
+ log.warn({ error }, "Failed to scan asset directory for orphans.");
3647
+ }
3648
+ if (changed) flush();
3649
+ }
3650
+ loadExisting();
3651
+ reconcile();
3652
+ return {
3653
+ list,
3654
+ has,
3655
+ get,
3656
+ getMany,
3657
+ upsert,
3658
+ touch,
3659
+ remove,
3660
+ reconcile,
3661
+ flush
3662
+ };
3663
+ }
3664
+
3665
+ //#endregion
3666
+ //#region src/request.ts
3667
+ const pendingCalls = /* @__PURE__ */ new Map();
3668
+ function register(extensionId, timeout) {
3669
+ const requestId = nanoid();
3670
+ return {
3671
+ promise: new Promise((resolve$1, reject$1) => {
3672
+ const timer = setTimeout(() => {
3673
+ pendingCalls.delete(requestId);
3674
+ reject$1(/* @__PURE__ */ new Error(`Extension did not respond within ${timeout / 1e3}s.`));
3675
+ }, timeout);
3676
+ pendingCalls.set(requestId, {
3677
+ resolve: resolve$1,
3678
+ reject: reject$1,
3679
+ timer,
3680
+ extensionId
3681
+ });
3682
+ }),
3683
+ requestId
3684
+ };
3685
+ }
3686
+ function resolve(requestId, payload) {
3687
+ const call = pendingCalls.get(requestId);
3688
+ if (call) {
3689
+ const { timer, resolve: finish } = call;
3690
+ clearTimeout(timer);
3691
+ finish(payload);
3692
+ pendingCalls.delete(requestId);
3693
+ } else log.warn({ reqId: requestId }, "Received result for unknown/timed-out call.");
3694
+ }
3695
+ function reject(requestId, error) {
3696
+ const call = pendingCalls.get(requestId);
3697
+ if (call) {
3698
+ const { timer, reject: fail } = call;
3699
+ clearTimeout(timer);
3700
+ fail(error);
3701
+ pendingCalls.delete(requestId);
3702
+ } else log.warn({ reqId: requestId }, "Received error for unknown/timed-out call.");
3703
+ }
3704
+ function cleanupForExtension(extensionId) {
3705
+ for (const [reqId, call] of pendingCalls.entries()) {
3706
+ const { timer, reject: fail, extensionId: extId } = call;
3707
+ if (extId === extensionId) {
3708
+ clearTimeout(timer);
3709
+ fail(/* @__PURE__ */ new Error("Extension disconnected before providing a result."));
3710
+ pendingCalls.delete(reqId);
3711
+ log.warn({
3712
+ reqId,
3713
+ extId: extensionId
3714
+ }, "Rejected pending call from disconnected extension.");
3715
+ }
3716
+ }
3717
+ }
3718
+ function cleanupAll() {
3719
+ pendingCalls.forEach((call, reqId) => {
3720
+ const { timer, reject: fail } = call;
3721
+ clearTimeout(timer);
3722
+ fail(/* @__PURE__ */ new Error("Hub is shutting down."));
3723
+ log.debug({ reqId }, "Rejected pending tool call due to shutdown.");
3724
+ });
3725
+ pendingCalls.clear();
3726
+ }
3727
+
3728
+ //#endregion
3729
+ //#region src/tools.ts
3730
+ const HERE = dirname(fileURLToPath(import.meta.url));
3731
+ const MCP_INSTRUCTIONS = readFileSync(join(HERE, "instructions.md"), "utf8");
3732
+ function extTool(definition) {
3733
+ return definition;
3734
+ }
3735
+ function hubTool(definition) {
3736
+ return definition;
3737
+ }
3738
+ const TOOL_DEFS = [
3739
+ extTool({
3740
+ name: "get_code",
3741
+ description: "Get a high-fidelity code snapshot for a nodeId/current selection, including assets/usedTokens and codegen preset/config. Start here, then refactor into your component/styling/file/naming conventions; strip any data-* hints. If no data-hint-auto-layout is present, layout is explicit; if any hint is none/inferred, pair with get_structure/get_screenshot to confirm hierarchy/overlap. Use data-hint-component plus repetition to decide on reusable components. Replace resource URIs with your canonical asset system as needed.",
3742
+ parameters: GetCodeParametersSchema,
3743
+ target: "extension",
3744
+ format: createCodeToolResponse
3745
+ }),
3746
+ extTool({
3747
+ name: "get_token_defs",
3748
+ description: "Resolve canonical token names to values (including modes) for tokens referenced by get_code. Use this to map into your design token/theming system, including responsive tokens.",
3749
+ parameters: GetTokenDefsParametersSchema,
3750
+ target: "extension",
3751
+ exposed: false
3752
+ }),
3753
+ extTool({
3754
+ name: "get_screenshot",
3755
+ description: "Capture a rendered screenshot for a nodeId/current selection for visual verification. Useful for confirming layering/overlap/masks/shadows/translucency when auto-layout hints are none/inferred.",
3756
+ parameters: GetScreenshotParametersSchema,
3757
+ target: "extension",
3758
+ format: createScreenshotToolResponse
3759
+ }),
3760
+ extTool({
3761
+ name: "get_structure",
3762
+ description: "Get a structural + geometry outline for a nodeId/current selection to understand hierarchy and layout intent. Use when auto-layout hints are none/inferred or you need explicit bounds for refactors/component extraction.",
3763
+ parameters: GetStructureParametersSchema,
3764
+ target: "extension"
3765
+ }),
3766
+ hubTool({
3767
+ name: "get_assets",
3768
+ description: "Resolve asset hashes to downloadable URLs/URIs for assets referenced by get_code, preserving vectors exactly. Pull bytes before routing through your asset/icon pipeline.",
3769
+ parameters: GetAssetsParametersSchema,
3770
+ target: "hub",
3771
+ outputSchema: GetAssetsResultSchema,
3772
+ exposed: false
3773
+ })
3774
+ ];
3775
+ function createToolErrorResponse(toolName, error) {
3776
+ return { content: [{
3777
+ type: "text",
3778
+ text: `Tool "${toolName}" failed: ${error instanceof Error ? error.message || "Unknown error occurred." : typeof error === "string" ? error : "Unknown error occurred."}`
3779
+ }] };
3780
+ }
3781
+ function formatBytes$1(bytes) {
3782
+ if (bytes < 1024) return `${bytes} B`;
3783
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
3784
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
3785
+ }
3786
+ function createCodeToolResponse(payload) {
3787
+ if (!isCodeResult(payload)) throw new Error("Invalid get_code payload received from extension.");
3788
+ const summary = [];
3789
+ const codeSize = Buffer.byteLength(payload.code, "utf8");
3790
+ summary.push(`Generated \`${payload.lang}\` snippet (${formatBytes$1(codeSize)}).`);
3791
+ if (payload.message) summary.push(payload.message);
3792
+ summary.push(payload.assets.length ? `Assets attached: ${payload.assets.length}. Fetch bytes via resources/read using resourceUri.` : "No binary assets were attached to this response.");
3793
+ const tokenCount = payload.usedTokens ? Object.keys(payload.usedTokens.tokens ?? {}).length : 0;
3794
+ if (tokenCount) summary.push(`Token references included: ${tokenCount}.`);
3795
+ summary.push("Read structuredContent for the full code string and asset metadata.");
3796
+ const assetLinks = payload.assets.length > 0 ? payload.assets.map((asset) => createAssetResourceLinkBlock$1(asset)) : [];
3797
+ return {
3798
+ content: [{
3799
+ type: "text",
3800
+ text: summary.join("\n")
3801
+ }, ...assetLinks],
3802
+ structuredContent: payload
3803
+ };
3804
+ }
3805
+ function createScreenshotToolResponse(payload) {
3806
+ if (!isScreenshotResult(payload)) throw new Error("Invalid get_screenshot payload received from extension.");
3807
+ return {
3808
+ content: [
3809
+ {
3810
+ type: "text",
3811
+ text: describeScreenshot(payload)
3812
+ },
3813
+ {
3814
+ type: "text",
3815
+ text: `![Screenshot](${payload.asset.url})`
3816
+ },
3817
+ createResourceLinkBlock(payload.asset, payload)
3818
+ ],
3819
+ structuredContent: payload
3820
+ };
3821
+ }
3822
+ function createResourceLinkBlock(asset, result) {
3823
+ return {
3824
+ type: "resource_link",
3825
+ name: "Screenshot",
3826
+ uri: asset.resourceUri,
3827
+ mimeType: asset.mimeType,
3828
+ description: `Screenshot ${result.width}x${result.height} @${result.scale}x - Download: ${asset.url}`
3829
+ };
3830
+ }
3831
+ function describeScreenshot(result) {
3832
+ return `Screenshot ${result.width}x${result.height} @${result.scale}x (${formatBytes$1(result.bytes)})`;
3833
+ }
3834
+ function isScreenshotResult(payload) {
3835
+ if (typeof payload !== "object" || !payload) return false;
3836
+ const candidate = payload;
3837
+ return typeof candidate.asset === "object" && candidate.asset !== null && typeof candidate.width === "number" && typeof candidate.height === "number" && typeof candidate.scale === "number" && typeof candidate.bytes === "number" && typeof candidate.format === "string";
3838
+ }
3839
+ function isCodeResult(payload) {
3840
+ if (typeof payload !== "object" || !payload) return false;
3841
+ const candidate = payload;
3842
+ return typeof candidate.code === "string" && typeof candidate.lang === "string" && Array.isArray(candidate.assets);
3843
+ }
3844
+ function createAssetResourceLinkBlock$1(asset) {
3845
+ return {
3846
+ type: "resource_link",
3847
+ name: formatAssetResourceName$1(asset.hash),
3848
+ uri: asset.resourceUri,
3849
+ mimeType: asset.mimeType,
3850
+ description: `${describeAsset$1(asset)} - Download: ${asset.url}`
3851
+ };
3852
+ }
3853
+ function describeAsset$1(asset) {
3854
+ return `${asset.mimeType} (${formatBytes$1(asset.size)})`;
3855
+ }
3856
+ function formatAssetResourceName$1(hash) {
3857
+ return `asset:${hash.slice(0, 8)}`;
3858
+ }
3859
+ function coercePayloadToToolResponse(payload) {
3860
+ if (payload && typeof payload === "object" && Array.isArray(payload.content)) return payload;
3861
+ return { content: [{
3862
+ type: "text",
3863
+ text: typeof payload === "string" ? payload : JSON.stringify(payload, null, 2)
3864
+ }] };
3865
+ }
3866
+
3867
+ //#endregion
3868
+ //#region src/hub.ts
3869
+ const SHUTDOWN_TIMEOUT = 2e3;
3870
+ const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, autoActivateGraceMs } = getMcpServerConfig();
3871
+ log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
3872
+ const extensions = [];
3873
+ let consumerCount = 0;
3874
+ let autoActivateTimer = null;
3875
+ let selectedWsPort = 0;
3876
+ const mcp = new McpServer({
3877
+ name: "tempad-dev-mcp",
3878
+ version: PACKAGE_VERSION
3879
+ }, MCP_INSTRUCTIONS ? { instructions: MCP_INSTRUCTIONS } : void 0);
3880
+ function enrichToolDefinition(tool) {
3881
+ if (tool.target === "extension") return tool;
3882
+ switch (tool.name) {
3883
+ case "get_assets": return {
3884
+ ...tool,
3885
+ handler: handleGetAssets
3886
+ };
3887
+ default: throw new Error("No handler configured for hub tool.");
3888
+ }
3889
+ }
3890
+ const TOOL_DEFINITIONS = TOOL_DEFS.map((tool) => enrichToolDefinition(tool));
3891
+ function hasFormatter(tool) {
3892
+ return tool.target === "extension" && "format" in tool;
3893
+ }
3894
+ const TOOL_BY_NAME = Object.fromEntries(TOOL_DEFINITIONS.map((tool) => [tool.name, tool]));
3895
+ function getToolDefinition(name) {
3896
+ return TOOL_BY_NAME[name];
3897
+ }
3898
+ const assetStore = createAssetStore();
3899
+ const assetHttpServer = createAssetHttpServer(assetStore);
3900
+ await assetHttpServer.start();
3901
+ registerAssetResources();
3902
+ function registerAssetResources() {
3903
+ const template = new ResourceTemplate(MCP_ASSET_URI_TEMPLATE, { list: async () => ({ resources: assetStore.list().filter((record) => existsSync(record.filePath)).map((record) => ({
3904
+ uri: buildAssetResourceUri(record.hash),
3905
+ name: formatAssetResourceName(record.hash),
3906
+ description: `${record.mimeType} (${formatBytes(record.size)})`,
3907
+ mimeType: record.mimeType
3908
+ })) }) });
3909
+ mcp.registerResource(MCP_ASSET_RESOURCE_NAME, template, { description: "Binary assets captured by the TemPad Dev hub." }, async (_uri, variables) => {
3910
+ return readAssetResource(typeof variables.hash === "string" ? variables.hash : "");
3911
+ });
3912
+ }
3913
+ async function readAssetResource(hash) {
3914
+ if (!hash) throw new Error("Missing asset hash in resource URI.");
3915
+ const record = assetStore.get(hash);
3916
+ if (!record) throw new Error(`Asset ${hash} not found.`);
3917
+ if (!existsSync(record.filePath)) {
3918
+ assetStore.remove(hash, { removeFile: false });
3919
+ throw new Error(`Asset ${hash} file is missing.`);
3920
+ }
3921
+ const stat = statSync(record.filePath);
3922
+ const estimatedSize = Math.ceil(stat.size / 3) * 4;
3923
+ if (estimatedSize > maxPayloadBytes) throw new Error(`Asset ${hash} is too large (${formatBytes(stat.size)}, encoded: ${formatBytes(estimatedSize)}) to read via MCP protocol. Use HTTP download.`);
3924
+ assetStore.touch(hash);
3925
+ const buffer = readFileSync(record.filePath);
3926
+ const resourceUri = buildAssetResourceUri(hash);
3927
+ if (isTextualMime(record.mimeType)) return { contents: [{
3928
+ uri: resourceUri,
3929
+ mimeType: record.mimeType,
3930
+ text: buffer.toString("utf8")
3931
+ }] };
3932
+ return { contents: [{
3933
+ uri: resourceUri,
3934
+ mimeType: record.mimeType,
3935
+ blob: buffer.toString("base64")
3936
+ }] };
3937
+ }
3938
+ function isTextualMime(mimeType) {
3939
+ return mimeType === "image/svg+xml" || mimeType.startsWith("text/");
3940
+ }
3941
+ function buildAssetResourceUri(hash) {
3942
+ return `${MCP_ASSET_URI_PREFIX}${hash}`;
3943
+ }
3944
+ function formatAssetResourceName(hash) {
3945
+ return `asset:${hash.slice(0, 8)}`;
3946
+ }
3947
+ function buildAssetDescriptor(record) {
3948
+ return {
3949
+ hash: record.hash,
3950
+ url: `${assetHttpServer.getBaseUrl()}/assets/${record.hash}`,
3951
+ mimeType: record.mimeType,
3952
+ size: record.size,
3953
+ resourceUri: buildAssetResourceUri(record.hash),
3954
+ width: record.metadata?.width,
3955
+ height: record.metadata?.height
3956
+ };
3957
+ }
3958
+ function createAssetResourceLinkBlock(asset) {
3959
+ return {
3960
+ type: "resource_link",
3961
+ name: formatAssetResourceName(asset.hash),
3962
+ uri: asset.resourceUri,
3963
+ mimeType: asset.mimeType,
3964
+ description: `${describeAsset(asset)} - Download: ${asset.url}`
3965
+ };
3966
+ }
3967
+ function describeAsset(asset) {
3968
+ return `${asset.mimeType} (${formatBytes(asset.size)})`;
3969
+ }
3970
+ function registerTools() {
3971
+ const registered = [];
3972
+ for (const tool of TOOL_DEFINITIONS) {
3973
+ if ("exposed" in tool && tool.exposed === false) continue;
3974
+ registerTool(tool);
3975
+ registered.push(tool.name);
3976
+ }
3977
+ log.info({ tools: registered }, "Registered tools.");
3978
+ }
3979
+ registerTools();
3980
+ function registerTool(tool) {
3981
+ if (tool.target === "extension") registerProxiedTool(tool);
3982
+ else registerLocalTool(tool);
3983
+ }
3984
+ function registerProxiedTool(tool) {
3985
+ const registerToolFn = mcp.registerTool.bind(mcp);
3986
+ const schema = tool.parameters;
3987
+ const handler = async (args) => {
3988
+ try {
3989
+ const parsedArgs = schema.parse(args);
3990
+ const activeExt = extensions.find((e) => e.active);
3991
+ if (!activeExt) throw new Error("No active TemPad Dev extension available.");
3992
+ const { promise, requestId } = register(activeExt.id, toolTimeoutMs);
3993
+ const message = {
3994
+ type: "toolCall",
3995
+ id: requestId,
3996
+ payload: {
3997
+ name: tool.name,
3998
+ args: parsedArgs
3999
+ }
4000
+ };
4001
+ activeExt.ws.send(JSON.stringify(message));
4002
+ log.info({
4003
+ tool: tool.name,
4004
+ req: requestId,
4005
+ extId: activeExt.id
4006
+ }, "Forwarded tool call.");
4007
+ const payload = await promise;
4008
+ return createToolResponse(tool.name, payload);
4009
+ } catch (error) {
4010
+ log.error({
4011
+ tool: tool.name,
4012
+ error
4013
+ }, "Tool invocation failed before reaching extension.");
4014
+ return createToolErrorResponse(tool.name, error);
4015
+ }
4016
+ };
4017
+ registerToolFn(tool.name, {
4018
+ description: tool.description,
4019
+ inputSchema: schema
4020
+ }, handler);
4021
+ }
4022
+ function registerLocalTool(tool) {
4023
+ const schema = tool.parameters;
4024
+ const handler = tool.handler;
4025
+ const registerToolFn = mcp.registerTool.bind(mcp);
4026
+ const registrationOptions = {
4027
+ description: tool.description,
4028
+ inputSchema: schema
4029
+ };
4030
+ if (tool.outputSchema) registrationOptions.outputSchema = tool.outputSchema;
4031
+ const registerHandler = async (args) => {
4032
+ try {
4033
+ return await handler(schema.parse(args));
4034
+ } catch (error) {
4035
+ log.error({
4036
+ tool: tool.name,
4037
+ error
4038
+ }, "Local tool invocation failed.");
4039
+ return createToolErrorResponse(tool.name, error);
4040
+ }
4041
+ };
4042
+ registerToolFn(tool.name, registrationOptions, registerHandler);
4043
+ }
4044
+ function createToolResponse(toolName, payload) {
4045
+ const definition = getToolDefinition(toolName);
4046
+ if (definition && hasFormatter(definition)) try {
4047
+ const formatter = definition.format;
4048
+ return formatter(payload);
4049
+ } catch (error) {
4050
+ log.warn({
4051
+ tool: toolName,
4052
+ error
4053
+ }, "Failed to format tool result; returning raw payload.");
4054
+ return coercePayloadToToolResponse(payload);
4055
+ }
4056
+ return coercePayloadToToolResponse(payload);
4057
+ }
4058
+ async function handleGetAssets({ hashes }) {
4059
+ if (hashes.length > 100) throw new Error("Too many hashes requested. Limit is 100.");
4060
+ const unique = Array.from(new Set(hashes));
4061
+ const records = assetStore.getMany(unique).filter((record) => {
4062
+ if (existsSync(record.filePath)) return true;
4063
+ assetStore.remove(record.hash, { removeFile: false });
4064
+ return false;
4065
+ });
4066
+ const found = new Set(records.map((record) => record.hash));
4067
+ const payload = GetAssetsResultSchema.parse({
4068
+ assets: records.map((record) => buildAssetDescriptor(record)),
4069
+ missing: unique.filter((hash) => !found.has(hash))
4070
+ });
4071
+ const summary = [];
4072
+ summary.push(payload.assets.length ? `Resolved ${payload.assets.length} asset${payload.assets.length === 1 ? "" : "s"}.` : "No assets were resolved for the requested hashes.");
4073
+ if (payload.missing.length) summary.push(`Missing: ${payload.missing.join(", ")}`);
4074
+ summary.push("Use resources/read with each resourceUri or fetch the fallback URL to download bytes.");
4075
+ return {
4076
+ content: [{
4077
+ type: "text",
4078
+ text: summary.join("\n")
4079
+ }, ...payload.assets.map((asset) => createAssetResourceLinkBlock(asset))],
4080
+ structuredContent: payload
4081
+ };
4082
+ }
4083
+ function getActiveId() {
4084
+ return extensions.find((e) => e.active)?.id ?? null;
4085
+ }
4086
+ function setActive(targetId) {
4087
+ extensions.forEach((e) => {
4088
+ e.active = targetId !== null && e.id === targetId;
4089
+ });
4090
+ }
4091
+ function clearAutoActivateTimer() {
4092
+ if (autoActivateTimer) {
4093
+ clearTimeout(autoActivateTimer);
4094
+ autoActivateTimer = null;
4095
+ }
4096
+ }
4097
+ function scheduleAutoActivate() {
4098
+ clearAutoActivateTimer();
4099
+ if (extensions.length !== 1 || getActiveId()) return;
4100
+ const target = extensions[0];
4101
+ autoActivateTimer = setTimeout(() => {
4102
+ autoActivateTimer = null;
4103
+ if (extensions.length === 1 && !getActiveId()) {
4104
+ setActive(target.id);
4105
+ log.info({ id: target.id }, "Auto-activated sole extension after grace period.");
4106
+ broadcastState();
4107
+ }
4108
+ }, autoActivateGraceMs);
4109
+ }
4110
+ function unrefTimer(timer) {
4111
+ if (typeof timer === "object" && timer !== null) {
4112
+ const handle = timer;
4113
+ if (typeof handle.unref === "function") handle.unref();
4114
+ }
4115
+ }
4116
+ function broadcastState() {
4117
+ const activeId = getActiveId();
4118
+ const message = {
4119
+ type: "state",
4120
+ activeId,
4121
+ count: extensions.length,
4122
+ port: selectedWsPort,
4123
+ assetServerUrl: assetHttpServer.getBaseUrl()
4124
+ };
4125
+ extensions.forEach((ext) => ext.ws.send(JSON.stringify(message)));
4126
+ log.debug({
4127
+ activeId,
4128
+ count: extensions.length
4129
+ }, "Broadcasted state.");
4130
+ }
4131
+ function rawDataToBuffer(raw) {
4132
+ if (typeof raw === "string") return Buffer.from(raw);
4133
+ if (Buffer.isBuffer(raw)) return raw;
4134
+ if (raw instanceof ArrayBuffer) return Buffer.from(raw);
4135
+ return Buffer.concat(raw);
4136
+ }
4137
+ function formatBytes(bytes) {
4138
+ if (bytes < 1024) return `${bytes} B`;
4139
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
4140
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
4141
+ }
4142
+ function shutdown() {
4143
+ log.info("Hub is shutting down...");
4144
+ assetStore.flush();
4145
+ assetHttpServer.stop();
4146
+ netServer.close(() => log.info("Net server closed."));
4147
+ wss?.close(() => log.info("WebSocket server closed."));
4148
+ cleanupAll();
4149
+ unrefTimer(setTimeout(() => {
4150
+ log.warn("Shutdown timed out. Forcing exit.");
4151
+ process.exit(1);
4152
+ }, SHUTDOWN_TIMEOUT));
4153
+ }
4154
+ try {
4155
+ ensureDir(RUNTIME_DIR);
4156
+ if (process.platform !== "win32" && existsSync(SOCK_PATH)) {
4157
+ log.warn({ sock: SOCK_PATH }, "Removing stale socket file.");
4158
+ rmSync(SOCK_PATH);
4159
+ }
4160
+ } catch (error) {
4161
+ log.error({ err: error }, "Failed to initialize runtime environment.");
4162
+ process.exit(1);
4163
+ }
4164
+ const netServer = createServer((sock) => {
4165
+ consumerCount++;
4166
+ log.info(`Consumer connected. Total: ${consumerCount}`);
4167
+ const transport = new StdioServerTransport(sock, sock);
4168
+ mcp.connect(transport).catch((err) => {
4169
+ log.error({ err }, "Failed to attach MCP transport.");
4170
+ transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
4171
+ sock.destroy();
4172
+ });
4173
+ sock.on("error", (err) => {
4174
+ log.warn({ err }, "Consumer socket error.");
4175
+ transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
4176
+ });
4177
+ sock.on("close", async () => {
4178
+ await transport.close();
4179
+ consumerCount--;
4180
+ log.info(`Consumer disconnected. Remaining: ${consumerCount}`);
4181
+ if (consumerCount === 0) {
4182
+ log.info("Last consumer disconnected. Shutting down.");
4183
+ shutdown();
4184
+ }
4185
+ });
4186
+ });
4187
+ netServer.on("error", (err) => {
4188
+ log.error({ err }, "Net server error.");
4189
+ process.exit(1);
4190
+ });
4191
+ netServer.listen(SOCK_PATH, () => {
4192
+ try {
4193
+ if (process.platform !== "win32") chmodSync(SOCK_PATH, 384);
4194
+ } catch (err) {
4195
+ log.error({ err }, "Failed to set socket permissions. Shutting down.");
4196
+ process.exit(1);
4197
+ }
4198
+ log.info({ sock: SOCK_PATH }, "Hub socket ready.");
4199
+ });
4200
+ async function startWebSocketServer() {
4201
+ for (const candidate of wsPortCandidates) {
4202
+ const server = new WebSocketServer({
4203
+ host: "127.0.0.1",
4204
+ port: candidate,
4205
+ maxPayload: maxPayloadBytes
4206
+ });
4207
+ try {
4208
+ await new Promise((resolve$1, reject$1) => {
4209
+ const onError = (err) => {
4210
+ server.off("listening", onListening);
4211
+ reject$1(err);
4212
+ };
4213
+ const onListening = () => {
4214
+ server.off("error", onError);
4215
+ resolve$1();
4216
+ };
4217
+ server.once("error", onError);
4218
+ server.once("listening", onListening);
4219
+ });
4220
+ return {
4221
+ wss: server,
4222
+ port: candidate
4223
+ };
4224
+ } catch (err) {
4225
+ server.close();
4226
+ const errno = err;
4227
+ if (errno.code === "EADDRINUSE") {
4228
+ log.warn({ port: candidate }, "WebSocket port in use, trying next candidate.");
4229
+ continue;
4230
+ }
4231
+ log.error({
4232
+ err: errno,
4233
+ port: candidate
4234
+ }, "Failed to start WebSocket server.");
4235
+ process.exit(1);
4236
+ }
4237
+ }
4238
+ log.error({ candidates: wsPortCandidates }, "Unable to start WebSocket server on any candidate port.");
4239
+ process.exit(1);
4240
+ }
4241
+ const { wss, port } = await startWebSocketServer();
4242
+ selectedWsPort = port;
4243
+ wss.on("error", (err) => {
4244
+ log.error({ err }, "WebSocket server critical error. Exiting.");
4245
+ process.exit(1);
4246
+ });
4247
+ wss.on("connection", (ws) => {
4248
+ const ext = {
4249
+ id: nanoid(),
4250
+ ws,
4251
+ active: false
4252
+ };
4253
+ extensions.push(ext);
4254
+ log.info({ id: ext.id }, `Extension connected. Total: ${extensions.length}`);
4255
+ const message = {
4256
+ type: "registered",
4257
+ id: ext.id
4258
+ };
4259
+ ws.send(JSON.stringify(message));
4260
+ broadcastState();
4261
+ scheduleAutoActivate();
4262
+ ws.on("message", (raw, isBinary) => {
4263
+ if (isBinary) {
4264
+ log.warn({ extId: ext.id }, "Unexpected binary message received.");
4265
+ return;
4266
+ }
4267
+ const messageBuffer = rawDataToBuffer(raw);
4268
+ let parsedJson;
4269
+ try {
4270
+ parsedJson = JSON.parse(messageBuffer.toString("utf-8"));
4271
+ } catch (e) {
4272
+ log.warn({
4273
+ err: e,
4274
+ extId: ext.id
4275
+ }, "Failed to parse message.");
4276
+ return;
4277
+ }
4278
+ const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
4279
+ if (!parseResult.success) {
4280
+ log.warn({
4281
+ error: parseResult.error.flatten(),
4282
+ extId: ext.id
4283
+ }, "Invalid message shape.");
4284
+ return;
4285
+ }
4286
+ const msg = parseResult.data;
4287
+ switch (msg.type) {
4288
+ case "activate":
4289
+ setActive(ext.id);
4290
+ log.info({ id: ext.id }, "Extension activated.");
4291
+ broadcastState();
4292
+ scheduleAutoActivate();
4293
+ break;
4294
+ case "toolResult": {
4295
+ const { id, payload, error } = msg;
4296
+ if (error) reject(id, error instanceof Error ? error : new Error(String(error)));
4297
+ else resolve(id, payload);
4298
+ break;
4299
+ }
4300
+ }
4301
+ });
4302
+ ws.on("close", () => {
4303
+ const index = extensions.findIndex((e) => e.id === ext.id);
4304
+ if (index > -1) extensions.splice(index, 1);
4305
+ log.info({ id: ext.id }, `Extension disconnected. Remaining: ${extensions.length}`);
4306
+ cleanupForExtension(ext.id);
4307
+ if (ext.active) {
4308
+ log.warn({ id: ext.id }, "Active extension disconnected.");
4309
+ setActive(null);
4310
+ }
4311
+ broadcastState();
4312
+ scheduleAutoActivate();
4313
+ });
4314
+ });
4315
+ log.info({ port: selectedWsPort }, "WebSocket server ready.");
4316
+ process.on("SIGINT", shutdown);
4317
+ process.on("SIGTERM", shutdown);
4318
+
4319
+ //#endregion
4320
+ export { };
4321
+ //# sourceMappingURL=hub.mjs.map