@victor-software-house/pi-openai-proxy 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,4256 @@
1
+ #!/usr/bin/env node
2
+ import { AuthStorage, ModelRegistry } from "@mariozechner/pi-coding-agent";
3
+ import { randomBytes } from "node:crypto";
4
+ import * as z from "zod";
5
+ import { completeSimple, streamSimple } from "@mariozechner/pi-ai";
6
+ import { Hono } from "hono";
7
+ import { stream } from "hono/streaming";
8
+ //#region \0rolldown/runtime.js
9
+ var __defProp = Object.defineProperty;
10
+ var __exportAll = (all, no_symbols) => {
11
+ let target = {};
12
+ for (var name in all) __defProp(target, name, {
13
+ get: all[name],
14
+ enumerable: true
15
+ });
16
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
17
+ return target;
18
+ };
19
+ //#endregion
20
+ //#region src/config/env.ts
21
+ /**
22
+ * Environment and configuration loading.
23
+ *
24
+ * Defaults:
25
+ * - Bind to 127.0.0.1 (safe for local use)
26
+ * - Port 4141
27
+ * - Proxy auth disabled
28
+ * - Agentic mode disabled
29
+ * - Remote image URLs disabled
30
+ * - 50 MB request body limit
31
+ * - 120s upstream timeout
32
+ */
33
+ /** Default request body size limit: 50 MB (accommodates base64 image payloads). */
34
+ const DEFAULT_MAX_BODY_SIZE = 50 * 1024 * 1024;
35
+ /** Default upstream request timeout: 120 seconds. */
36
+ const DEFAULT_UPSTREAM_TIMEOUT_MS = 12e4;
37
+ function parsePositiveInt(raw, fallback) {
38
+ if (raw === void 0) return fallback;
39
+ const n = Number.parseInt(raw, 10);
40
+ if (!Number.isFinite(n) || n <= 0) return fallback;
41
+ return n;
42
+ }
43
+ function loadConfig() {
44
+ return {
45
+ host: process.env.PI_PROXY_HOST ?? "127.0.0.1",
46
+ port: Number.parseInt(process.env.PI_PROXY_PORT ?? "4141", 10),
47
+ proxyAuthToken: process.env.PI_PROXY_AUTH_TOKEN,
48
+ agenticEnabled: process.env.PI_PROXY_AGENTIC === "true",
49
+ remoteImagesEnabled: process.env.PI_PROXY_REMOTE_IMAGES === "true",
50
+ maxBodySize: parsePositiveInt(process.env.PI_PROXY_MAX_BODY_SIZE, DEFAULT_MAX_BODY_SIZE),
51
+ upstreamTimeoutMs: parsePositiveInt(process.env.PI_PROXY_UPSTREAM_TIMEOUT_MS, DEFAULT_UPSTREAM_TIMEOUT_MS)
52
+ };
53
+ }
54
+ //#endregion
55
+ //#region src/pi/registry.ts
56
+ let registry;
57
+ let authStorage;
58
+ /**
59
+ * Initialize the registry. Call once at startup.
60
+ * Returns the load error if models.json failed to parse, or undefined on success.
61
+ */
62
+ function initRegistry() {
63
+ authStorage = AuthStorage.create();
64
+ registry = new ModelRegistry(authStorage);
65
+ return registry.getError();
66
+ }
67
+ function getRegistry() {
68
+ if (registry === void 0) throw new Error("ModelRegistry not initialized. Call initRegistry() first.");
69
+ return registry;
70
+ }
71
+ /**
72
+ * Get all models available (have auth configured).
73
+ */
74
+ function getAvailableModels() {
75
+ return getRegistry().getAvailable();
76
+ }
77
+ //#endregion
78
+ //#region src/server/errors.ts
79
+ function makeError(message, type, param, code) {
80
+ return { error: {
81
+ message,
82
+ type,
83
+ param,
84
+ code
85
+ } };
86
+ }
87
+ function invalidRequest(message, param) {
88
+ return makeError(message, "invalid_request_error", param ?? null, null);
89
+ }
90
+ function modelNotFound(modelId) {
91
+ return makeError(`The model '${modelId}' does not exist`, "invalid_request_error", "model", "model_not_found");
92
+ }
93
+ function unsupportedParameter(param, message) {
94
+ return makeError(message ?? `Unsupported parameter: '${param}'`, "invalid_request_error", param, "unsupported_parameter");
95
+ }
96
+ function authenticationError(message) {
97
+ return makeError(message, "authentication_error", null, null);
98
+ }
99
+ function upstreamError(message, code) {
100
+ return makeError(message, "server_error", null, code ?? "upstream_error");
101
+ }
102
+ function mapUpstreamError(err) {
103
+ const message = err instanceof Error ? err.message : "Unknown upstream error";
104
+ if (message.includes("rate") && message.includes("limit")) return {
105
+ status: 429,
106
+ body: upstreamError("Upstream rate limit exceeded", "rate_limit")
107
+ };
108
+ if (message.includes("timeout") || message.includes("ETIMEDOUT")) return {
109
+ status: 504,
110
+ body: upstreamError("Upstream request timed out", "timeout")
111
+ };
112
+ if (message.includes("401") || message.includes("403") || message.includes("Unauthorized")) return {
113
+ status: 502,
114
+ body: upstreamError("Upstream authentication failed", "upstream_auth_error")
115
+ };
116
+ if (message.includes("529") || message.includes("overloaded")) return {
117
+ status: 503,
118
+ body: upstreamError("Upstream provider is overloaded", "provider_overloaded")
119
+ };
120
+ return {
121
+ status: 502,
122
+ body: upstreamError("Upstream provider error")
123
+ };
124
+ }
125
+ //#endregion
126
+ //#region src/server/logging.ts
127
+ function timestamp() {
128
+ return (/* @__PURE__ */ new Date()).toISOString();
129
+ }
130
+ function logRequest(ctx) {
131
+ const entry = {
132
+ ts: timestamp(),
133
+ level: "info",
134
+ event: "request",
135
+ requestId: ctx.requestId,
136
+ clientRequestId: ctx.clientRequestId,
137
+ method: ctx.method,
138
+ path: ctx.path
139
+ };
140
+ console.error(JSON.stringify(entry));
141
+ }
142
+ function logResponse(ctx, status, durationMs) {
143
+ const entry = {
144
+ ts: timestamp(),
145
+ level: "info",
146
+ event: "response",
147
+ requestId: ctx.requestId,
148
+ status,
149
+ durationMs: Math.round(durationMs)
150
+ };
151
+ console.error(JSON.stringify(entry));
152
+ }
153
+ function logError(ctx, message, detail) {
154
+ const entry = {
155
+ ts: timestamp(),
156
+ level: "error",
157
+ event: "error",
158
+ requestId: ctx.requestId,
159
+ message,
160
+ detail
161
+ };
162
+ console.error(JSON.stringify(entry));
163
+ }
164
+ function logDisconnect(ctx) {
165
+ const entry = {
166
+ ts: timestamp(),
167
+ level: "info",
168
+ event: "disconnect",
169
+ requestId: ctx.requestId
170
+ };
171
+ console.error(JSON.stringify(entry));
172
+ }
173
+ function logStartup(host, port, modelCount) {
174
+ const entry = {
175
+ ts: timestamp(),
176
+ level: "info",
177
+ event: "startup",
178
+ host,
179
+ port,
180
+ modelCount
181
+ };
182
+ console.error(JSON.stringify(entry));
183
+ }
184
+ function logShutdown(signal) {
185
+ const entry = {
186
+ ts: timestamp(),
187
+ level: "info",
188
+ event: "shutdown",
189
+ signal
190
+ };
191
+ console.error(JSON.stringify(entry));
192
+ }
193
+ //#endregion
194
+ //#region src/server/request-id.ts
195
+ /**
196
+ * Per-request proxy request ID generation.
197
+ *
198
+ * Format: "piproxy-{random}" to be easily distinguishable from upstream IDs.
199
+ */
200
+ function generateRequestId() {
201
+ return `piproxy-${randomBytes(12).toString("hex")}`;
202
+ }
203
+ //#endregion
204
+ //#region src/server/middleware.ts
205
+ /**
206
+ * Inject request ID, upstream API key, and logging context into every request.
207
+ */
208
+ function requestIdMiddleware() {
209
+ return async (c, next) => {
210
+ const requestId = generateRequestId();
211
+ const clientRequestId = c.req.header("x-client-request-id");
212
+ const upstreamApiKey = c.req.header("x-pi-upstream-api-key");
213
+ const start = performance.now();
214
+ c.set("requestId", requestId);
215
+ c.set("clientRequestId", clientRequestId);
216
+ c.set("upstreamApiKey", upstreamApiKey);
217
+ logRequest({
218
+ requestId,
219
+ clientRequestId,
220
+ method: c.req.method,
221
+ path: c.req.path
222
+ });
223
+ c.header("x-request-id", requestId);
224
+ if (clientRequestId !== void 0) c.header("x-client-request-id", clientRequestId);
225
+ await next();
226
+ const duration = performance.now() - start;
227
+ logResponse({
228
+ requestId,
229
+ clientRequestId,
230
+ method: c.req.method,
231
+ path: c.req.path
232
+ }, c.res.status, duration);
233
+ };
234
+ }
235
+ /**
236
+ * Optional proxy auth middleware.
237
+ * Only active when PI_PROXY_AUTH_TOKEN is set.
238
+ */
239
+ function proxyAuthMiddleware(config) {
240
+ return async (c, next) => {
241
+ if (config.proxyAuthToken === void 0) {
242
+ await next();
243
+ return;
244
+ }
245
+ const authHeader = c.req.header("authorization");
246
+ if (authHeader === void 0) return c.json(authenticationError("Missing Authorization header"), 401);
247
+ if ((authHeader.startsWith("Bearer ") ? authHeader.slice(7) : void 0) !== config.proxyAuthToken) return c.json(authenticationError("Invalid proxy authentication token"), 401);
248
+ await next();
249
+ };
250
+ }
251
+ /**
252
+ * Client disconnect detection middleware.
253
+ * Creates an AbortController for upstream cancellation.
254
+ */
255
+ function disconnectMiddleware() {
256
+ return async (c, next) => {
257
+ const controller = new AbortController();
258
+ c.set("abortController", controller);
259
+ const reqSignal = c.req.raw.signal;
260
+ if (reqSignal !== void 0) {
261
+ const onAbort = () => {
262
+ logDisconnect({
263
+ requestId: c.get("requestId"),
264
+ method: c.req.method,
265
+ path: c.req.path
266
+ });
267
+ controller.abort();
268
+ };
269
+ if (reqSignal.aborted) onAbort();
270
+ else reqSignal.addEventListener("abort", onAbort, { once: true });
271
+ }
272
+ await next();
273
+ };
274
+ }
275
+ /**
276
+ * Request body size limit middleware.
277
+ * Rejects requests with Content-Length exceeding the configured maximum.
278
+ * Only applies to POST/PUT/PATCH methods.
279
+ */
280
+ function bodySizeLimitMiddleware(config) {
281
+ return async (c, next) => {
282
+ const method = c.req.method;
283
+ if (method !== "POST" && method !== "PUT" && method !== "PATCH") {
284
+ await next();
285
+ return;
286
+ }
287
+ const contentLength = c.req.header("content-length");
288
+ if (contentLength !== void 0) {
289
+ const length = Number.parseInt(contentLength, 10);
290
+ if (Number.isFinite(length) && length > config.maxBodySize) return c.json(invalidRequest(`Request body too large. Maximum size: ${String(config.maxBodySize)} bytes`), 413);
291
+ }
292
+ await next();
293
+ };
294
+ }
295
+ //#endregion
296
+ //#region src/openai/messages.ts
297
+ const toolArgsSchema = z.record(z.string().trim(), z.unknown());
298
+ /**
299
+ * Convert OpenAI messages array into a pi Context.
300
+ *
301
+ * System and developer messages are merged into `systemPrompt`.
302
+ * Conversation messages are mapped into pi message types.
303
+ */
304
+ function convertMessages(messages) {
305
+ const systemParts = [];
306
+ const piMessages = [];
307
+ for (let i = 0; i < messages.length; i++) {
308
+ const msg = messages[i];
309
+ if (msg === void 0) continue;
310
+ if (msg.role === "system") systemParts.push(msg.content);
311
+ else if (msg.role === "developer") systemParts.push(msg.content);
312
+ else if (msg.role === "user") {
313
+ const userMsg = convertUserMessage(msg.content, i);
314
+ if (!userMsg.ok) return userMsg;
315
+ piMessages.push(userMsg.message);
316
+ } else if (msg.role === "assistant") {
317
+ const assistantMsg = convertAssistantMessage(msg.content ?? null, msg.tool_calls);
318
+ piMessages.push(assistantMsg);
319
+ } else if (msg.role === "tool") {
320
+ const toolMsg = convertToolMessage(msg.content, msg.tool_call_id);
321
+ piMessages.push(toolMsg);
322
+ }
323
+ }
324
+ const context = { messages: piMessages };
325
+ if (systemParts.length > 0) context.systemPrompt = systemParts.join("\n\n");
326
+ return {
327
+ ok: true,
328
+ context
329
+ };
330
+ }
331
+ function convertUserMessage(content, index) {
332
+ if (typeof content === "string") return {
333
+ ok: true,
334
+ message: {
335
+ role: "user",
336
+ content,
337
+ timestamp: Date.now()
338
+ }
339
+ };
340
+ const parts = [];
341
+ for (let j = 0; j < content.length; j++) {
342
+ const part = content[j];
343
+ if (part === void 0) continue;
344
+ if (part.type === "text") parts.push({
345
+ type: "text",
346
+ text: part.text ?? ""
347
+ });
348
+ else if (part.type === "image_url") {
349
+ const url = part.image_url?.url ?? "";
350
+ if (url.startsWith("data:")) {
351
+ const result = parseAndValidateDataUri(url);
352
+ if (!result.ok) return {
353
+ ok: false,
354
+ message: `${result.message} at messages[${String(index)}].content[${String(j)}]`,
355
+ param: `messages[${String(index)}].content[${String(j)}].image_url.url`
356
+ };
357
+ parts.push({
358
+ type: "image",
359
+ data: result.parsed.data,
360
+ mimeType: result.parsed.mimeType
361
+ });
362
+ } else return {
363
+ ok: false,
364
+ message: "Remote image URLs are not supported. Use base64 data URIs instead.",
365
+ param: `messages[${String(index)}].content[${String(j)}].image_url.url`
366
+ };
367
+ } else return {
368
+ ok: false,
369
+ message: `Unsupported content part type: '${part.type}'`,
370
+ param: `messages[${String(index)}].content[${String(j)}].type`
371
+ };
372
+ }
373
+ return {
374
+ ok: true,
375
+ message: {
376
+ role: "user",
377
+ content: parts,
378
+ timestamp: Date.now()
379
+ }
380
+ };
381
+ }
382
+ function convertAssistantMessage(textContent, toolCalls) {
383
+ const content = [];
384
+ if (textContent !== null && textContent.length > 0) content.push({
385
+ type: "text",
386
+ text: textContent
387
+ });
388
+ if (toolCalls !== void 0) for (const tc of toolCalls) {
389
+ let args = {};
390
+ try {
391
+ const parsed = toolArgsSchema.safeParse(JSON.parse(tc.function.arguments));
392
+ if (parsed.success) args = parsed.data;
393
+ } catch {}
394
+ content.push({
395
+ type: "toolCall",
396
+ id: tc.id,
397
+ name: tc.function.name,
398
+ arguments: args
399
+ });
400
+ }
401
+ return {
402
+ role: "assistant",
403
+ content,
404
+ api: "openai-completions",
405
+ provider: "proxy",
406
+ model: "history",
407
+ usage: {
408
+ input: 0,
409
+ output: 0,
410
+ cacheRead: 0,
411
+ cacheWrite: 0,
412
+ totalTokens: 0,
413
+ cost: {
414
+ input: 0,
415
+ output: 0,
416
+ cacheRead: 0,
417
+ cacheWrite: 0,
418
+ total: 0
419
+ }
420
+ },
421
+ stopReason: "stop",
422
+ timestamp: Date.now()
423
+ };
424
+ }
425
+ function convertToolMessage(content, toolCallId) {
426
+ return {
427
+ role: "toolResult",
428
+ toolCallId,
429
+ toolName: "",
430
+ content: [{
431
+ type: "text",
432
+ text: content
433
+ }],
434
+ isError: false,
435
+ timestamp: Date.now()
436
+ };
437
+ }
438
+ /**
439
+ * Supported image MIME types for base64 data URIs.
440
+ */
441
+ const SUPPORTED_IMAGE_MIME_TYPES = new Set([
442
+ "image/png",
443
+ "image/jpeg",
444
+ "image/gif",
445
+ "image/webp"
446
+ ]);
447
+ /**
448
+ * Maximum base64 payload size (20 MB of base64 text, ~15 MB decoded).
449
+ */
450
+ const MAX_BASE64_PAYLOAD_SIZE = 20 * 1024 * 1024;
451
+ function parseAndValidateDataUri(uri) {
452
+ const match = /^data:([^;]+);base64,(.+)$/.exec(uri);
453
+ if (match === null) return {
454
+ ok: false,
455
+ message: "Invalid base64 data URI format"
456
+ };
457
+ const mimeType = match[1];
458
+ const data = match[2];
459
+ if (mimeType === void 0 || data === void 0) return {
460
+ ok: false,
461
+ message: "Invalid base64 data URI format"
462
+ };
463
+ if (!SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) return {
464
+ ok: false,
465
+ message: `Unsupported image MIME type '${mimeType}'. Supported: ${[...SUPPORTED_IMAGE_MIME_TYPES].join(", ")}`
466
+ };
467
+ if (data.length > MAX_BASE64_PAYLOAD_SIZE) return {
468
+ ok: false,
469
+ message: `Image payload exceeds maximum size of ${String(MAX_BASE64_PAYLOAD_SIZE)} bytes`
470
+ };
471
+ return {
472
+ ok: true,
473
+ parsed: {
474
+ data,
475
+ mimeType
476
+ }
477
+ };
478
+ }
479
+ //#endregion
480
+ //#region src/openai/models.ts
481
+ /**
482
+ * Convert a pi Model to an OpenAI model object.
483
+ */
484
+ function toOpenAIModel(model) {
485
+ return {
486
+ id: `${model.provider}/${model.id}`,
487
+ object: "model",
488
+ created: 0,
489
+ owned_by: model.provider,
490
+ x_pi: {
491
+ api: model.api,
492
+ reasoning: model.reasoning,
493
+ input: model.input,
494
+ context_window: model.contextWindow,
495
+ max_tokens: model.maxTokens
496
+ }
497
+ };
498
+ }
499
+ /**
500
+ * Build the full model list response.
501
+ */
502
+ function buildModelList(models) {
503
+ return {
504
+ object: "list",
505
+ data: models.map(toOpenAIModel)
506
+ };
507
+ }
508
+ //#endregion
509
+ //#region src/openai/responses.ts
510
+ /** Pi StopReason -> OpenAI finish_reason */
511
+ const FINISH_REASON_MAP = {
512
+ stop: "stop",
513
+ length: "length",
514
+ toolUse: "tool_calls",
515
+ error: "stop",
516
+ aborted: "stop"
517
+ };
518
+ /**
519
+ * Map pi StopReason to OpenAI finish_reason.
520
+ */
521
+ function mapFinishReason(reason) {
522
+ return FINISH_REASON_MAP[reason];
523
+ }
524
+ /**
525
+ * Map pi Usage to OpenAI usage.
526
+ */
527
+ function mapUsage(usage) {
528
+ return {
529
+ prompt_tokens: usage.input,
530
+ completion_tokens: usage.output,
531
+ total_tokens: usage.totalTokens
532
+ };
533
+ }
534
+ /**
535
+ * Build a complete non-streaming OpenAI response from a pi AssistantMessage.
536
+ */
537
+ function buildChatCompletion(requestId, canonicalModelId, message) {
538
+ const textParts = message.content.filter((c) => c.type === "text");
539
+ const textContent = textParts.length > 0 ? textParts.map((t) => t.text).join("") : null;
540
+ const toolCalls = message.content.filter((c) => c.type === "toolCall").map((tc) => ({
541
+ id: tc.id,
542
+ type: "function",
543
+ function: {
544
+ name: tc.name,
545
+ arguments: JSON.stringify(tc.arguments)
546
+ }
547
+ }));
548
+ const messageBody = toolCalls.length > 0 ? {
549
+ role: "assistant",
550
+ content: textContent,
551
+ tool_calls: toolCalls
552
+ } : {
553
+ role: "assistant",
554
+ content: textContent
555
+ };
556
+ return {
557
+ id: requestId,
558
+ object: "chat.completion",
559
+ created: Math.floor(Date.now() / 1e3),
560
+ model: canonicalModelId,
561
+ choices: [{
562
+ index: 0,
563
+ message: messageBody,
564
+ finish_reason: mapFinishReason(message.stopReason)
565
+ }],
566
+ usage: mapUsage(message.usage),
567
+ x_pi: {
568
+ cost: message.usage.cost,
569
+ cache_read_tokens: message.usage.cacheRead,
570
+ cache_write_tokens: message.usage.cacheWrite
571
+ }
572
+ };
573
+ }
574
+ //#endregion
575
+ //#region src/openai/sse.ts
576
+ /**
577
+ * Encode a single SSE data frame.
578
+ */
579
+ function encodeSSE(chunk) {
580
+ return `data: ${JSON.stringify(chunk)}\n\n`;
581
+ }
582
+ /**
583
+ * Encode the terminal [DONE] frame.
584
+ */
585
+ function encodeDone() {
586
+ return "data: [DONE]\n\n";
587
+ }
588
+ /**
589
+ * Create an async generator that yields SSE text frames from a pi event stream.
590
+ */
591
+ async function* streamToSSE(events, requestId, model, includeUsage) {
592
+ const created = Math.floor(Date.now() / 1e3);
593
+ let sentFirstChunk = false;
594
+ let finishReason = null;
595
+ let finalUsage;
596
+ const toolCallIndexes = /* @__PURE__ */ new Map();
597
+ for await (const event of events) switch (event.type) {
598
+ case "start":
599
+ yield encodeSSE({
600
+ id: requestId,
601
+ object: "chat.completion.chunk",
602
+ created,
603
+ model,
604
+ choices: [{
605
+ index: 0,
606
+ delta: { role: "assistant" },
607
+ finish_reason: null
608
+ }]
609
+ });
610
+ sentFirstChunk = true;
611
+ break;
612
+ case "text_delta":
613
+ if (!sentFirstChunk) {
614
+ yield encodeSSE({
615
+ id: requestId,
616
+ object: "chat.completion.chunk",
617
+ created,
618
+ model,
619
+ choices: [{
620
+ index: 0,
621
+ delta: {
622
+ role: "assistant",
623
+ content: event.delta
624
+ },
625
+ finish_reason: null
626
+ }]
627
+ });
628
+ sentFirstChunk = true;
629
+ } else yield encodeSSE({
630
+ id: requestId,
631
+ object: "chat.completion.chunk",
632
+ created,
633
+ model,
634
+ choices: [{
635
+ index: 0,
636
+ delta: { content: event.delta },
637
+ finish_reason: null
638
+ }]
639
+ });
640
+ break;
641
+ case "toolcall_start": {
642
+ const ci = event.contentIndex;
643
+ const toolCallContent = event.partial.content[ci];
644
+ if (toolCallContent !== void 0 && toolCallContent.type === "toolCall") {
645
+ const tcIndex = toolCallIndexes.size;
646
+ toolCallIndexes.set(ci, true);
647
+ yield encodeSSE({
648
+ id: requestId,
649
+ object: "chat.completion.chunk",
650
+ created,
651
+ model,
652
+ choices: [{
653
+ index: 0,
654
+ delta: { tool_calls: [{
655
+ index: tcIndex,
656
+ id: toolCallContent.id,
657
+ type: "function",
658
+ function: {
659
+ name: toolCallContent.name,
660
+ arguments: ""
661
+ }
662
+ }] },
663
+ finish_reason: null
664
+ }]
665
+ });
666
+ }
667
+ break;
668
+ }
669
+ case "toolcall_delta": {
670
+ let tcIndex = 0;
671
+ let found = false;
672
+ for (const [ci] of toolCallIndexes) {
673
+ if (ci === event.contentIndex) {
674
+ found = true;
675
+ break;
676
+ }
677
+ tcIndex++;
678
+ }
679
+ if (!found) break;
680
+ yield encodeSSE({
681
+ id: requestId,
682
+ object: "chat.completion.chunk",
683
+ created,
684
+ model,
685
+ choices: [{
686
+ index: 0,
687
+ delta: { tool_calls: [{
688
+ index: tcIndex,
689
+ function: { arguments: event.delta }
690
+ }] },
691
+ finish_reason: null
692
+ }]
693
+ });
694
+ break;
695
+ }
696
+ case "done":
697
+ finishReason = mapFinishReason(event.reason);
698
+ finalUsage = event.message.usage;
699
+ break;
700
+ case "error": {
701
+ const errorMessage = event.error.errorMessage ?? "Upstream provider error";
702
+ yield `data: ${JSON.stringify({ error: {
703
+ message: errorMessage,
704
+ type: "server_error",
705
+ param: null,
706
+ code: "upstream_error"
707
+ } })}\n\n`;
708
+ yield encodeDone();
709
+ return;
710
+ }
711
+ default: break;
712
+ }
713
+ if (finishReason !== null) yield encodeSSE({
714
+ id: requestId,
715
+ object: "chat.completion.chunk",
716
+ created,
717
+ model,
718
+ choices: [{
719
+ index: 0,
720
+ delta: {},
721
+ finish_reason: finishReason
722
+ }]
723
+ });
724
+ if (includeUsage && finalUsage !== void 0) yield encodeSSE({
725
+ id: requestId,
726
+ object: "chat.completion.chunk",
727
+ created,
728
+ model,
729
+ choices: [],
730
+ usage: mapUsage(finalUsage)
731
+ });
732
+ yield encodeDone();
733
+ }
734
+ //#endregion
735
+ //#region node_modules/@sinclair/typebox/build/esm/type/guard/value.mjs
736
+ /** Returns true if this value is an async iterator */
737
+ function IsAsyncIterator$2(value) {
738
+ return IsObject$3(value) && !IsArray$3(value) && !IsUint8Array$2(value) && Symbol.asyncIterator in value;
739
+ }
740
+ /** Returns true if this value is an array */
741
+ function IsArray$3(value) {
742
+ return Array.isArray(value);
743
+ }
744
+ /** Returns true if this value is bigint */
745
+ function IsBigInt$2(value) {
746
+ return typeof value === "bigint";
747
+ }
748
+ /** Returns true if this value is a boolean */
749
+ function IsBoolean$2(value) {
750
+ return typeof value === "boolean";
751
+ }
752
+ /** Returns true if this value is a Date object */
753
+ function IsDate$2(value) {
754
+ return value instanceof globalThis.Date;
755
+ }
756
+ /** Returns true if this value is a function */
757
+ function IsFunction$2(value) {
758
+ return typeof value === "function";
759
+ }
760
+ /** Returns true if this value is an iterator */
761
+ function IsIterator$2(value) {
762
+ return IsObject$3(value) && !IsArray$3(value) && !IsUint8Array$2(value) && Symbol.iterator in value;
763
+ }
764
+ /** Returns true if this value is null */
765
+ function IsNull$2(value) {
766
+ return value === null;
767
+ }
768
+ /** Returns true if this value is number */
769
+ function IsNumber$3(value) {
770
+ return typeof value === "number";
771
+ }
772
+ /** Returns true if this value is an object */
773
+ function IsObject$3(value) {
774
+ return typeof value === "object" && value !== null;
775
+ }
776
+ /** Returns true if this value is RegExp */
777
+ function IsRegExp$2(value) {
778
+ return value instanceof globalThis.RegExp;
779
+ }
780
+ /** Returns true if this value is string */
781
+ function IsString$2(value) {
782
+ return typeof value === "string";
783
+ }
784
+ /** Returns true if this value is symbol */
785
+ function IsSymbol$2(value) {
786
+ return typeof value === "symbol";
787
+ }
788
+ /** Returns true if this value is a Uint8Array */
789
+ function IsUint8Array$2(value) {
790
+ return value instanceof globalThis.Uint8Array;
791
+ }
792
+ /** Returns true if this value is undefined */
793
+ function IsUndefined$3(value) {
794
+ return value === void 0;
795
+ }
796
+ //#endregion
797
+ //#region node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs
798
+ function ArrayType(value) {
799
+ return value.map((value) => Visit$2(value));
800
+ }
801
+ function DateType(value) {
802
+ return new Date(value.getTime());
803
+ }
804
+ function Uint8ArrayType(value) {
805
+ return new Uint8Array(value);
806
+ }
807
+ function RegExpType(value) {
808
+ return new RegExp(value.source, value.flags);
809
+ }
810
+ function ObjectType(value) {
811
+ const result = {};
812
+ for (const key of Object.getOwnPropertyNames(value)) result[key] = Visit$2(value[key]);
813
+ for (const key of Object.getOwnPropertySymbols(value)) result[key] = Visit$2(value[key]);
814
+ return result;
815
+ }
816
+ function Visit$2(value) {
817
+ return IsArray$3(value) ? ArrayType(value) : IsDate$2(value) ? DateType(value) : IsUint8Array$2(value) ? Uint8ArrayType(value) : IsRegExp$2(value) ? RegExpType(value) : IsObject$3(value) ? ObjectType(value) : value;
818
+ }
819
+ /** Clones a value */
820
+ function Clone(value) {
821
+ return Visit$2(value);
822
+ }
823
+ //#endregion
824
+ //#region node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs
825
+ /** Clones a Type */
826
+ function CloneType(schema, options) {
827
+ return options === void 0 ? Clone(schema) : Clone({
828
+ ...options,
829
+ ...schema
830
+ });
831
+ }
832
+ //#endregion
833
+ //#region node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs
834
+ /** Returns true of this value is an object type */
835
+ function IsObject$2(value) {
836
+ return value !== null && typeof value === "object";
837
+ }
838
+ /** Returns true if this value is an array, but not a typed array */
839
+ function IsArray$2(value) {
840
+ return globalThis.Array.isArray(value) && !globalThis.ArrayBuffer.isView(value);
841
+ }
842
+ /** Returns true if this value is an undefined */
843
+ function IsUndefined$2(value) {
844
+ return value === void 0;
845
+ }
846
+ /** Returns true if this value is an number */
847
+ function IsNumber$2(value) {
848
+ return typeof value === "number";
849
+ }
850
+ //#endregion
851
+ //#region node_modules/@sinclair/typebox/build/esm/system/policy.mjs
852
+ var TypeSystemPolicy;
853
+ (function(TypeSystemPolicy) {
854
+ /**
855
+ * Configures the instantiation behavior of TypeBox types. The `default` option assigns raw JavaScript
856
+ * references for embedded types, which may cause side effects if type properties are explicitly updated
857
+ * outside the TypeBox type builder. The `clone` option creates copies of any shared types upon creation,
858
+ * preventing unintended side effects. The `freeze` option applies `Object.freeze()` to the type, making
859
+ * it fully readonly and immutable. Implementations should use `default` whenever possible, as it is the
860
+ * fastest way to instantiate types. The default setting is `default`.
861
+ */
862
+ TypeSystemPolicy.InstanceMode = "default";
863
+ /** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
864
+ TypeSystemPolicy.ExactOptionalPropertyTypes = false;
865
+ /** Sets whether arrays should be treated as a kind of objects. The default is `false` */
866
+ TypeSystemPolicy.AllowArrayObject = false;
867
+ /** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
868
+ TypeSystemPolicy.AllowNaN = false;
869
+ /** Sets whether `null` should validate for void types. The default is `false` */
870
+ TypeSystemPolicy.AllowNullVoid = false;
871
+ /** Checks this value using the ExactOptionalPropertyTypes policy */
872
+ function IsExactOptionalProperty(value, key) {
873
+ return TypeSystemPolicy.ExactOptionalPropertyTypes ? key in value : value[key] !== void 0;
874
+ }
875
+ TypeSystemPolicy.IsExactOptionalProperty = IsExactOptionalProperty;
876
+ /** Checks this value using the AllowArrayObjects policy */
877
+ function IsObjectLike(value) {
878
+ const isObject = IsObject$2(value);
879
+ return TypeSystemPolicy.AllowArrayObject ? isObject : isObject && !IsArray$2(value);
880
+ }
881
+ TypeSystemPolicy.IsObjectLike = IsObjectLike;
882
+ /** Checks this value as a record using the AllowArrayObjects policy */
883
+ function IsRecordLike(value) {
884
+ return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array);
885
+ }
886
+ TypeSystemPolicy.IsRecordLike = IsRecordLike;
887
+ /** Checks this value using the AllowNaN policy */
888
+ function IsNumberLike(value) {
889
+ return TypeSystemPolicy.AllowNaN ? IsNumber$2(value) : Number.isFinite(value);
890
+ }
891
+ TypeSystemPolicy.IsNumberLike = IsNumberLike;
892
+ /** Checks this value using the AllowVoidNull policy */
893
+ function IsVoidLike(value) {
894
+ const isUndefined = IsUndefined$2(value);
895
+ return TypeSystemPolicy.AllowNullVoid ? isUndefined || value === null : isUndefined;
896
+ }
897
+ TypeSystemPolicy.IsVoidLike = IsVoidLike;
898
+ })(TypeSystemPolicy || (TypeSystemPolicy = {}));
899
+ //#endregion
900
+ //#region node_modules/@sinclair/typebox/build/esm/type/create/immutable.mjs
901
+ function ImmutableArray(value) {
902
+ return globalThis.Object.freeze(value).map((value) => Immutable(value));
903
+ }
904
+ function ImmutableDate(value) {
905
+ return value;
906
+ }
907
+ function ImmutableUint8Array(value) {
908
+ return value;
909
+ }
910
+ function ImmutableRegExp(value) {
911
+ return value;
912
+ }
913
+ function ImmutableObject(value) {
914
+ const result = {};
915
+ for (const key of Object.getOwnPropertyNames(value)) result[key] = Immutable(value[key]);
916
+ for (const key of Object.getOwnPropertySymbols(value)) result[key] = Immutable(value[key]);
917
+ return globalThis.Object.freeze(result);
918
+ }
919
+ /** Specialized deep immutable value. Applies freeze recursively to the given value */
920
+ function Immutable(value) {
921
+ return IsArray$3(value) ? ImmutableArray(value) : IsDate$2(value) ? ImmutableDate(value) : IsUint8Array$2(value) ? ImmutableUint8Array(value) : IsRegExp$2(value) ? ImmutableRegExp(value) : IsObject$3(value) ? ImmutableObject(value) : value;
922
+ }
923
+ //#endregion
924
+ //#region node_modules/@sinclair/typebox/build/esm/type/create/type.mjs
925
+ /** Creates TypeBox schematics using the configured InstanceMode */
926
+ function CreateType(schema, options) {
927
+ const result = options !== void 0 ? {
928
+ ...options,
929
+ ...schema
930
+ } : schema;
931
+ switch (TypeSystemPolicy.InstanceMode) {
932
+ case "freeze": return Immutable(result);
933
+ case "clone": return Clone(result);
934
+ default: return result;
935
+ }
936
+ }
937
+ //#endregion
938
+ //#region node_modules/@sinclair/typebox/build/esm/type/error/error.mjs
939
+ /** The base Error type thrown for all TypeBox exceptions */
940
+ var TypeBoxError = class extends Error {
941
+ constructor(message) {
942
+ super(message);
943
+ }
944
+ };
945
+ //#endregion
946
+ //#region node_modules/@sinclair/typebox/build/esm/type/symbols/symbols.mjs
947
+ /** Symbol key applied to transform types */
948
+ const TransformKind = Symbol.for("TypeBox.Transform");
949
+ /** Symbol key applied to readonly types */
950
+ const ReadonlyKind = Symbol.for("TypeBox.Readonly");
951
+ /** Symbol key applied to optional types */
952
+ const OptionalKind = Symbol.for("TypeBox.Optional");
953
+ /** Symbol key applied to types */
954
+ const Hint = Symbol.for("TypeBox.Hint");
955
+ /** Symbol key applied to types */
956
+ const Kind = Symbol.for("TypeBox.Kind");
957
+ //#endregion
958
+ //#region node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs
959
+ /** `[Kind-Only]` Returns true if this value has a Readonly symbol */
960
+ function IsReadonly(value) {
961
+ return IsObject$3(value) && value[ReadonlyKind] === "Readonly";
962
+ }
963
+ /** `[Kind-Only]` Returns true if this value has a Optional symbol */
964
+ function IsOptional$1(value) {
965
+ return IsObject$3(value) && value[OptionalKind] === "Optional";
966
+ }
967
+ /** `[Kind-Only]` Returns true if the given value is TAny */
968
+ function IsAny$1(value) {
969
+ return IsKindOf$1(value, "Any");
970
+ }
971
+ /** `[Kind-Only]` Returns true if the given value is TArgument */
972
+ function IsArgument$1(value) {
973
+ return IsKindOf$1(value, "Argument");
974
+ }
975
+ /** `[Kind-Only]` Returns true if the given value is TArray */
976
+ function IsArray$1(value) {
977
+ return IsKindOf$1(value, "Array");
978
+ }
979
+ /** `[Kind-Only]` Returns true if the given value is TAsyncIterator */
980
+ function IsAsyncIterator$1(value) {
981
+ return IsKindOf$1(value, "AsyncIterator");
982
+ }
983
+ /** `[Kind-Only]` Returns true if the given value is TBigInt */
984
+ function IsBigInt$1(value) {
985
+ return IsKindOf$1(value, "BigInt");
986
+ }
987
+ /** `[Kind-Only]` Returns true if the given value is TBoolean */
988
+ function IsBoolean$1(value) {
989
+ return IsKindOf$1(value, "Boolean");
990
+ }
991
+ /** `[Kind-Only]` Returns true if the given value is TComputed */
992
+ function IsComputed$1(value) {
993
+ return IsKindOf$1(value, "Computed");
994
+ }
995
+ /** `[Kind-Only]` Returns true if the given value is TConstructor */
996
+ function IsConstructor$1(value) {
997
+ return IsKindOf$1(value, "Constructor");
998
+ }
999
+ /** `[Kind-Only]` Returns true if the given value is TDate */
1000
+ function IsDate$1(value) {
1001
+ return IsKindOf$1(value, "Date");
1002
+ }
1003
+ /** `[Kind-Only]` Returns true if the given value is TFunction */
1004
+ function IsFunction$1(value) {
1005
+ return IsKindOf$1(value, "Function");
1006
+ }
1007
+ /** `[Kind-Only]` Returns true if the given value is TInteger */
1008
+ function IsInteger$1(value) {
1009
+ return IsKindOf$1(value, "Integer");
1010
+ }
1011
+ /** `[Kind-Only]` Returns true if the given value is TIntersect */
1012
+ function IsIntersect$1(value) {
1013
+ return IsKindOf$1(value, "Intersect");
1014
+ }
1015
+ /** `[Kind-Only]` Returns true if the given value is TIterator */
1016
+ function IsIterator$1(value) {
1017
+ return IsKindOf$1(value, "Iterator");
1018
+ }
1019
+ /** `[Kind-Only]` Returns true if the given value is a TKind with the given name. */
1020
+ function IsKindOf$1(value, kind) {
1021
+ return IsObject$3(value) && Kind in value && value[Kind] === kind;
1022
+ }
1023
+ /** `[Kind-Only]` Returns true if the given value is TLiteralValue */
1024
+ function IsLiteralValue$1(value) {
1025
+ return IsBoolean$2(value) || IsNumber$3(value) || IsString$2(value);
1026
+ }
1027
+ /** `[Kind-Only]` Returns true if the given value is TLiteral */
1028
+ function IsLiteral$1(value) {
1029
+ return IsKindOf$1(value, "Literal");
1030
+ }
1031
+ /** `[Kind-Only]` Returns true if the given value is a TMappedKey */
1032
+ function IsMappedKey$1(value) {
1033
+ return IsKindOf$1(value, "MappedKey");
1034
+ }
1035
+ /** `[Kind-Only]` Returns true if the given value is TMappedResult */
1036
+ function IsMappedResult$1(value) {
1037
+ return IsKindOf$1(value, "MappedResult");
1038
+ }
1039
+ /** `[Kind-Only]` Returns true if the given value is TNever */
1040
+ function IsNever$1(value) {
1041
+ return IsKindOf$1(value, "Never");
1042
+ }
1043
+ /** `[Kind-Only]` Returns true if the given value is TNot */
1044
+ function IsNot$1(value) {
1045
+ return IsKindOf$1(value, "Not");
1046
+ }
1047
+ /** `[Kind-Only]` Returns true if the given value is TNull */
1048
+ function IsNull$1(value) {
1049
+ return IsKindOf$1(value, "Null");
1050
+ }
1051
+ /** `[Kind-Only]` Returns true if the given value is TNumber */
1052
+ function IsNumber$1(value) {
1053
+ return IsKindOf$1(value, "Number");
1054
+ }
1055
+ /** `[Kind-Only]` Returns true if the given value is TObject */
1056
+ function IsObject$1(value) {
1057
+ return IsKindOf$1(value, "Object");
1058
+ }
1059
+ /** `[Kind-Only]` Returns true if the given value is TPromise */
1060
+ function IsPromise$1(value) {
1061
+ return IsKindOf$1(value, "Promise");
1062
+ }
1063
+ /** `[Kind-Only]` Returns true if the given value is TRecord */
1064
+ function IsRecord$1(value) {
1065
+ return IsKindOf$1(value, "Record");
1066
+ }
1067
+ /** `[Kind-Only]` Returns true if the given value is TRef */
1068
+ function IsRef$1(value) {
1069
+ return IsKindOf$1(value, "Ref");
1070
+ }
1071
+ /** `[Kind-Only]` Returns true if the given value is TRegExp */
1072
+ function IsRegExp$1(value) {
1073
+ return IsKindOf$1(value, "RegExp");
1074
+ }
1075
+ /** `[Kind-Only]` Returns true if the given value is TString */
1076
+ function IsString$1(value) {
1077
+ return IsKindOf$1(value, "String");
1078
+ }
1079
+ /** `[Kind-Only]` Returns true if the given value is TSymbol */
1080
+ function IsSymbol$1(value) {
1081
+ return IsKindOf$1(value, "Symbol");
1082
+ }
1083
+ /** `[Kind-Only]` Returns true if the given value is TTemplateLiteral */
1084
+ function IsTemplateLiteral$1(value) {
1085
+ return IsKindOf$1(value, "TemplateLiteral");
1086
+ }
1087
+ /** `[Kind-Only]` Returns true if the given value is TThis */
1088
+ function IsThis$1(value) {
1089
+ return IsKindOf$1(value, "This");
1090
+ }
1091
+ /** `[Kind-Only]` Returns true of this value is TTransform */
1092
+ function IsTransform$1(value) {
1093
+ return IsObject$3(value) && TransformKind in value;
1094
+ }
1095
+ /** `[Kind-Only]` Returns true if the given value is TTuple */
1096
+ function IsTuple$1(value) {
1097
+ return IsKindOf$1(value, "Tuple");
1098
+ }
1099
+ /** `[Kind-Only]` Returns true if the given value is TUndefined */
1100
+ function IsUndefined$1(value) {
1101
+ return IsKindOf$1(value, "Undefined");
1102
+ }
1103
+ /** `[Kind-Only]` Returns true if the given value is TUnion */
1104
+ function IsUnion$1(value) {
1105
+ return IsKindOf$1(value, "Union");
1106
+ }
1107
+ /** `[Kind-Only]` Returns true if the given value is TUint8Array */
1108
+ function IsUint8Array$1(value) {
1109
+ return IsKindOf$1(value, "Uint8Array");
1110
+ }
1111
+ /** `[Kind-Only]` Returns true if the given value is TUnknown */
1112
+ function IsUnknown$1(value) {
1113
+ return IsKindOf$1(value, "Unknown");
1114
+ }
1115
+ /** `[Kind-Only]` Returns true if the given value is a raw TUnsafe */
1116
+ function IsUnsafe$1(value) {
1117
+ return IsKindOf$1(value, "Unsafe");
1118
+ }
1119
+ /** `[Kind-Only]` Returns true if the given value is TVoid */
1120
+ function IsVoid$1(value) {
1121
+ return IsKindOf$1(value, "Void");
1122
+ }
1123
+ /** `[Kind-Only]` Returns true if the given value is TKind */
1124
+ function IsKind$1(value) {
1125
+ return IsObject$3(value) && Kind in value && IsString$2(value[Kind]);
1126
+ }
1127
+ /** `[Kind-Only]` Returns true if the given value is TSchema */
1128
+ function IsSchema$1(value) {
1129
+ return IsAny$1(value) || IsArgument$1(value) || IsArray$1(value) || IsBoolean$1(value) || IsBigInt$1(value) || IsAsyncIterator$1(value) || IsComputed$1(value) || IsConstructor$1(value) || IsDate$1(value) || IsFunction$1(value) || IsInteger$1(value) || IsIntersect$1(value) || IsIterator$1(value) || IsLiteral$1(value) || IsMappedKey$1(value) || IsMappedResult$1(value) || IsNever$1(value) || IsNot$1(value) || IsNull$1(value) || IsNumber$1(value) || IsObject$1(value) || IsPromise$1(value) || IsRecord$1(value) || IsRef$1(value) || IsRegExp$1(value) || IsString$1(value) || IsSymbol$1(value) || IsTemplateLiteral$1(value) || IsThis$1(value) || IsTuple$1(value) || IsUndefined$1(value) || IsUnion$1(value) || IsUint8Array$1(value) || IsUnknown$1(value) || IsUnsafe$1(value) || IsVoid$1(value) || IsKind$1(value);
1130
+ }
1131
+ //#endregion
1132
+ //#region node_modules/@sinclair/typebox/build/esm/type/guard/type.mjs
1133
+ const KnownTypes = [
1134
+ "Argument",
1135
+ "Any",
1136
+ "Array",
1137
+ "AsyncIterator",
1138
+ "BigInt",
1139
+ "Boolean",
1140
+ "Computed",
1141
+ "Constructor",
1142
+ "Date",
1143
+ "Enum",
1144
+ "Function",
1145
+ "Integer",
1146
+ "Intersect",
1147
+ "Iterator",
1148
+ "Literal",
1149
+ "MappedKey",
1150
+ "MappedResult",
1151
+ "Not",
1152
+ "Null",
1153
+ "Number",
1154
+ "Object",
1155
+ "Promise",
1156
+ "Record",
1157
+ "Ref",
1158
+ "RegExp",
1159
+ "String",
1160
+ "Symbol",
1161
+ "TemplateLiteral",
1162
+ "This",
1163
+ "Tuple",
1164
+ "Undefined",
1165
+ "Union",
1166
+ "Uint8Array",
1167
+ "Unknown",
1168
+ "Void"
1169
+ ];
1170
+ function IsPattern(value) {
1171
+ try {
1172
+ new RegExp(value);
1173
+ return true;
1174
+ } catch {
1175
+ return false;
1176
+ }
1177
+ }
1178
+ function IsControlCharacterFree(value) {
1179
+ if (!IsString$2(value)) return false;
1180
+ for (let i = 0; i < value.length; i++) {
1181
+ const code = value.charCodeAt(i);
1182
+ if (code >= 7 && code <= 13 || code === 27 || code === 127) return false;
1183
+ }
1184
+ return true;
1185
+ }
1186
+ function IsAdditionalProperties(value) {
1187
+ return IsOptionalBoolean(value) || IsSchema(value);
1188
+ }
1189
+ function IsOptionalBigInt(value) {
1190
+ return IsUndefined$3(value) || IsBigInt$2(value);
1191
+ }
1192
+ function IsOptionalNumber(value) {
1193
+ return IsUndefined$3(value) || IsNumber$3(value);
1194
+ }
1195
+ function IsOptionalBoolean(value) {
1196
+ return IsUndefined$3(value) || IsBoolean$2(value);
1197
+ }
1198
+ function IsOptionalString(value) {
1199
+ return IsUndefined$3(value) || IsString$2(value);
1200
+ }
1201
+ function IsOptionalPattern(value) {
1202
+ return IsUndefined$3(value) || IsString$2(value) && IsControlCharacterFree(value) && IsPattern(value);
1203
+ }
1204
+ function IsOptionalFormat(value) {
1205
+ return IsUndefined$3(value) || IsString$2(value) && IsControlCharacterFree(value);
1206
+ }
1207
+ function IsOptionalSchema(value) {
1208
+ return IsUndefined$3(value) || IsSchema(value);
1209
+ }
1210
+ /** Returns true if this value has a Optional symbol */
1211
+ function IsOptional(value) {
1212
+ return IsObject$3(value) && value[OptionalKind] === "Optional";
1213
+ }
1214
+ /** Returns true if the given value is TAny */
1215
+ function IsAny(value) {
1216
+ return IsKindOf(value, "Any") && IsOptionalString(value.$id);
1217
+ }
1218
+ /** Returns true if the given value is TArgument */
1219
+ function IsArgument(value) {
1220
+ return IsKindOf(value, "Argument") && IsNumber$3(value.index);
1221
+ }
1222
+ /** Returns true if the given value is TArray */
1223
+ function IsArray(value) {
1224
+ return IsKindOf(value, "Array") && value.type === "array" && IsOptionalString(value.$id) && IsSchema(value.items) && IsOptionalNumber(value.minItems) && IsOptionalNumber(value.maxItems) && IsOptionalBoolean(value.uniqueItems) && IsOptionalSchema(value.contains) && IsOptionalNumber(value.minContains) && IsOptionalNumber(value.maxContains);
1225
+ }
1226
+ /** Returns true if the given value is TAsyncIterator */
1227
+ function IsAsyncIterator(value) {
1228
+ return IsKindOf(value, "AsyncIterator") && value.type === "AsyncIterator" && IsOptionalString(value.$id) && IsSchema(value.items);
1229
+ }
1230
+ /** Returns true if the given value is TBigInt */
1231
+ function IsBigInt(value) {
1232
+ return IsKindOf(value, "BigInt") && value.type === "bigint" && IsOptionalString(value.$id) && IsOptionalBigInt(value.exclusiveMaximum) && IsOptionalBigInt(value.exclusiveMinimum) && IsOptionalBigInt(value.maximum) && IsOptionalBigInt(value.minimum) && IsOptionalBigInt(value.multipleOf);
1233
+ }
1234
+ /** Returns true if the given value is TBoolean */
1235
+ function IsBoolean(value) {
1236
+ return IsKindOf(value, "Boolean") && value.type === "boolean" && IsOptionalString(value.$id);
1237
+ }
1238
+ /** Returns true if the given value is TComputed */
1239
+ function IsComputed(value) {
1240
+ return IsKindOf(value, "Computed") && IsString$2(value.target) && IsArray$3(value.parameters) && value.parameters.every((schema) => IsSchema(schema));
1241
+ }
1242
+ /** Returns true if the given value is TConstructor */
1243
+ function IsConstructor(value) {
1244
+ return IsKindOf(value, "Constructor") && value.type === "Constructor" && IsOptionalString(value.$id) && IsArray$3(value.parameters) && value.parameters.every((schema) => IsSchema(schema)) && IsSchema(value.returns);
1245
+ }
1246
+ /** Returns true if the given value is TDate */
1247
+ function IsDate(value) {
1248
+ return IsKindOf(value, "Date") && value.type === "Date" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximumTimestamp) && IsOptionalNumber(value.exclusiveMinimumTimestamp) && IsOptionalNumber(value.maximumTimestamp) && IsOptionalNumber(value.minimumTimestamp) && IsOptionalNumber(value.multipleOfTimestamp);
1249
+ }
1250
+ /** Returns true if the given value is TFunction */
1251
+ function IsFunction(value) {
1252
+ return IsKindOf(value, "Function") && value.type === "Function" && IsOptionalString(value.$id) && IsArray$3(value.parameters) && value.parameters.every((schema) => IsSchema(schema)) && IsSchema(value.returns);
1253
+ }
1254
+ /** Returns true if the given value is TInteger */
1255
+ function IsInteger(value) {
1256
+ return IsKindOf(value, "Integer") && value.type === "integer" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximum) && IsOptionalNumber(value.exclusiveMinimum) && IsOptionalNumber(value.maximum) && IsOptionalNumber(value.minimum) && IsOptionalNumber(value.multipleOf);
1257
+ }
1258
+ /** Returns true if the given schema is TProperties */
1259
+ function IsProperties(value) {
1260
+ return IsObject$3(value) && Object.entries(value).every(([key, schema]) => IsControlCharacterFree(key) && IsSchema(schema));
1261
+ }
1262
+ /** Returns true if the given value is TIntersect */
1263
+ function IsIntersect(value) {
1264
+ return IsKindOf(value, "Intersect") && (IsString$2(value.type) && value.type !== "object" ? false : true) && IsArray$3(value.allOf) && value.allOf.every((schema) => IsSchema(schema) && !IsTransform(schema)) && IsOptionalString(value.type) && (IsOptionalBoolean(value.unevaluatedProperties) || IsOptionalSchema(value.unevaluatedProperties)) && IsOptionalString(value.$id);
1265
+ }
1266
+ /** Returns true if the given value is TIterator */
1267
+ function IsIterator(value) {
1268
+ return IsKindOf(value, "Iterator") && value.type === "Iterator" && IsOptionalString(value.$id) && IsSchema(value.items);
1269
+ }
1270
+ /** Returns true if the given value is a TKind with the given name. */
1271
+ function IsKindOf(value, kind) {
1272
+ return IsObject$3(value) && Kind in value && value[Kind] === kind;
1273
+ }
1274
+ /** Returns true if the given value is TLiteral<string> */
1275
+ function IsLiteralString(value) {
1276
+ return IsLiteral(value) && IsString$2(value.const);
1277
+ }
1278
+ /** Returns true if the given value is TLiteral<number> */
1279
+ function IsLiteralNumber(value) {
1280
+ return IsLiteral(value) && IsNumber$3(value.const);
1281
+ }
1282
+ /** Returns true if the given value is TLiteral<boolean> */
1283
+ function IsLiteralBoolean(value) {
1284
+ return IsLiteral(value) && IsBoolean$2(value.const);
1285
+ }
1286
+ /** Returns true if the given value is TLiteral */
1287
+ function IsLiteral(value) {
1288
+ return IsKindOf(value, "Literal") && IsOptionalString(value.$id) && IsLiteralValue(value.const);
1289
+ }
1290
+ /** Returns true if the given value is a TLiteralValue */
1291
+ function IsLiteralValue(value) {
1292
+ return IsBoolean$2(value) || IsNumber$3(value) || IsString$2(value);
1293
+ }
1294
+ /** Returns true if the given value is a TMappedKey */
1295
+ function IsMappedKey(value) {
1296
+ return IsKindOf(value, "MappedKey") && IsArray$3(value.keys) && value.keys.every((key) => IsNumber$3(key) || IsString$2(key));
1297
+ }
1298
+ /** Returns true if the given value is TMappedResult */
1299
+ function IsMappedResult(value) {
1300
+ return IsKindOf(value, "MappedResult") && IsProperties(value.properties);
1301
+ }
1302
+ /** Returns true if the given value is TNever */
1303
+ function IsNever(value) {
1304
+ return IsKindOf(value, "Never") && IsObject$3(value.not) && Object.getOwnPropertyNames(value.not).length === 0;
1305
+ }
1306
+ /** Returns true if the given value is TNot */
1307
+ function IsNot(value) {
1308
+ return IsKindOf(value, "Not") && IsSchema(value.not);
1309
+ }
1310
+ /** Returns true if the given value is TNull */
1311
+ function IsNull(value) {
1312
+ return IsKindOf(value, "Null") && value.type === "null" && IsOptionalString(value.$id);
1313
+ }
1314
+ /** Returns true if the given value is TNumber */
1315
+ function IsNumber(value) {
1316
+ return IsKindOf(value, "Number") && value.type === "number" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximum) && IsOptionalNumber(value.exclusiveMinimum) && IsOptionalNumber(value.maximum) && IsOptionalNumber(value.minimum) && IsOptionalNumber(value.multipleOf);
1317
+ }
1318
+ /** Returns true if the given value is TObject */
1319
+ function IsObject(value) {
1320
+ return IsKindOf(value, "Object") && value.type === "object" && IsOptionalString(value.$id) && IsProperties(value.properties) && IsAdditionalProperties(value.additionalProperties) && IsOptionalNumber(value.minProperties) && IsOptionalNumber(value.maxProperties);
1321
+ }
1322
+ /** Returns true if the given value is TPromise */
1323
+ function IsPromise(value) {
1324
+ return IsKindOf(value, "Promise") && value.type === "Promise" && IsOptionalString(value.$id) && IsSchema(value.item);
1325
+ }
1326
+ /** Returns true if the given value is TRecord */
1327
+ function IsRecord(value) {
1328
+ return IsKindOf(value, "Record") && value.type === "object" && IsOptionalString(value.$id) && IsAdditionalProperties(value.additionalProperties) && IsObject$3(value.patternProperties) && ((schema) => {
1329
+ const keys = Object.getOwnPropertyNames(schema.patternProperties);
1330
+ return keys.length === 1 && IsPattern(keys[0]) && IsObject$3(schema.patternProperties) && IsSchema(schema.patternProperties[keys[0]]);
1331
+ })(value);
1332
+ }
1333
+ /** Returns true if the given value is TRef */
1334
+ function IsRef(value) {
1335
+ return IsKindOf(value, "Ref") && IsOptionalString(value.$id) && IsString$2(value.$ref);
1336
+ }
1337
+ /** Returns true if the given value is TRegExp */
1338
+ function IsRegExp(value) {
1339
+ return IsKindOf(value, "RegExp") && IsOptionalString(value.$id) && IsString$2(value.source) && IsString$2(value.flags) && IsOptionalNumber(value.maxLength) && IsOptionalNumber(value.minLength);
1340
+ }
1341
+ /** Returns true if the given value is TString */
1342
+ function IsString(value) {
1343
+ return IsKindOf(value, "String") && value.type === "string" && IsOptionalString(value.$id) && IsOptionalNumber(value.minLength) && IsOptionalNumber(value.maxLength) && IsOptionalPattern(value.pattern) && IsOptionalFormat(value.format);
1344
+ }
1345
+ /** Returns true if the given value is TSymbol */
1346
+ function IsSymbol(value) {
1347
+ return IsKindOf(value, "Symbol") && value.type === "symbol" && IsOptionalString(value.$id);
1348
+ }
1349
+ /** Returns true if the given value is TTemplateLiteral */
1350
+ function IsTemplateLiteral(value) {
1351
+ return IsKindOf(value, "TemplateLiteral") && value.type === "string" && IsString$2(value.pattern) && value.pattern[0] === "^" && value.pattern[value.pattern.length - 1] === "$";
1352
+ }
1353
+ /** Returns true if the given value is TThis */
1354
+ function IsThis(value) {
1355
+ return IsKindOf(value, "This") && IsOptionalString(value.$id) && IsString$2(value.$ref);
1356
+ }
1357
+ /** Returns true of this value is TTransform */
1358
+ function IsTransform(value) {
1359
+ return IsObject$3(value) && TransformKind in value;
1360
+ }
1361
+ /** Returns true if the given value is TTuple */
1362
+ function IsTuple(value) {
1363
+ return IsKindOf(value, "Tuple") && value.type === "array" && IsOptionalString(value.$id) && IsNumber$3(value.minItems) && IsNumber$3(value.maxItems) && value.minItems === value.maxItems && (IsUndefined$3(value.items) && IsUndefined$3(value.additionalItems) && value.minItems === 0 || IsArray$3(value.items) && value.items.every((schema) => IsSchema(schema)));
1364
+ }
1365
+ /** Returns true if the given value is TUndefined */
1366
+ function IsUndefined(value) {
1367
+ return IsKindOf(value, "Undefined") && value.type === "undefined" && IsOptionalString(value.$id);
1368
+ }
1369
+ /** Returns true if the given value is TUnion */
1370
+ function IsUnion(value) {
1371
+ return IsKindOf(value, "Union") && IsOptionalString(value.$id) && IsObject$3(value) && IsArray$3(value.anyOf) && value.anyOf.every((schema) => IsSchema(schema));
1372
+ }
1373
+ /** Returns true if the given value is TUint8Array */
1374
+ function IsUint8Array(value) {
1375
+ return IsKindOf(value, "Uint8Array") && value.type === "Uint8Array" && IsOptionalString(value.$id) && IsOptionalNumber(value.minByteLength) && IsOptionalNumber(value.maxByteLength);
1376
+ }
1377
+ /** Returns true if the given value is TUnknown */
1378
+ function IsUnknown(value) {
1379
+ return IsKindOf(value, "Unknown") && IsOptionalString(value.$id);
1380
+ }
1381
+ /** Returns true if the given value is a raw TUnsafe */
1382
+ function IsUnsafe(value) {
1383
+ return IsKindOf(value, "Unsafe");
1384
+ }
1385
+ /** Returns true if the given value is TVoid */
1386
+ function IsVoid(value) {
1387
+ return IsKindOf(value, "Void") && value.type === "void" && IsOptionalString(value.$id);
1388
+ }
1389
+ /** Returns true if the given value is TKind */
1390
+ function IsKind(value) {
1391
+ return IsObject$3(value) && Kind in value && IsString$2(value[Kind]) && !KnownTypes.includes(value[Kind]);
1392
+ }
1393
+ /** Returns true if the given value is TSchema */
1394
+ function IsSchema(value) {
1395
+ return IsObject$3(value) && (IsAny(value) || IsArgument(value) || IsArray(value) || IsBoolean(value) || IsBigInt(value) || IsAsyncIterator(value) || IsComputed(value) || IsConstructor(value) || IsDate(value) || IsFunction(value) || IsInteger(value) || IsIntersect(value) || IsIterator(value) || IsLiteral(value) || IsMappedKey(value) || IsMappedResult(value) || IsNever(value) || IsNot(value) || IsNull(value) || IsNumber(value) || IsObject(value) || IsPromise(value) || IsRecord(value) || IsRef(value) || IsRegExp(value) || IsString(value) || IsSymbol(value) || IsTemplateLiteral(value) || IsThis(value) || IsTuple(value) || IsUndefined(value) || IsUnion(value) || IsUint8Array(value) || IsUnknown(value) || IsUnsafe(value) || IsVoid(value) || IsKind(value));
1396
+ }
1397
+ //#endregion
1398
+ //#region node_modules/@sinclair/typebox/build/esm/type/patterns/patterns.mjs
1399
+ const PatternBoolean = "(true|false)";
1400
+ const PatternNumber = "(0|[1-9][0-9]*)";
1401
+ const PatternString = "(.*)";
1402
+ const PatternNever = "(?!.*)";
1403
+ `${PatternBoolean}`;
1404
+ const PatternNumberExact = `^${PatternNumber}$`;
1405
+ const PatternStringExact = `^${PatternString}$`;
1406
+ const PatternNeverExact = `^${PatternNever}$`;
1407
+ //#endregion
1408
+ //#region node_modules/@sinclair/typebox/build/esm/type/sets/set.mjs
1409
+ /** Returns true if element right is in the set of left */
1410
+ function SetIncludes(T, S) {
1411
+ return T.includes(S);
1412
+ }
1413
+ /** Returns a distinct set of elements */
1414
+ function SetDistinct(T) {
1415
+ return [...new Set(T)];
1416
+ }
1417
+ /** Returns the Intersect of the given sets */
1418
+ function SetIntersect(T, S) {
1419
+ return T.filter((L) => S.includes(L));
1420
+ }
1421
+ function SetIntersectManyResolve(T, Init) {
1422
+ return T.reduce((Acc, L) => {
1423
+ return SetIntersect(Acc, L);
1424
+ }, Init);
1425
+ }
1426
+ function SetIntersectMany(T) {
1427
+ return T.length === 1 ? T[0] : T.length > 1 ? SetIntersectManyResolve(T.slice(1), T[0]) : [];
1428
+ }
1429
+ /** Returns the Union of multiple sets */
1430
+ function SetUnionMany(T) {
1431
+ const Acc = [];
1432
+ for (const L of T) Acc.push(...L);
1433
+ return Acc;
1434
+ }
1435
+ //#endregion
1436
+ //#region node_modules/@sinclair/typebox/build/esm/type/any/any.mjs
1437
+ /** `[Json]` Creates an Any type */
1438
+ function Any(options) {
1439
+ return CreateType({ [Kind]: "Any" }, options);
1440
+ }
1441
+ //#endregion
1442
+ //#region node_modules/@sinclair/typebox/build/esm/type/array/array.mjs
1443
+ /** `[Json]` Creates an Array type */
1444
+ function Array$1(items, options) {
1445
+ return CreateType({
1446
+ [Kind]: "Array",
1447
+ type: "array",
1448
+ items
1449
+ }, options);
1450
+ }
1451
+ //#endregion
1452
+ //#region node_modules/@sinclair/typebox/build/esm/type/argument/argument.mjs
1453
+ /** `[JavaScript]` Creates an Argument Type. */
1454
+ function Argument(index) {
1455
+ return CreateType({
1456
+ [Kind]: "Argument",
1457
+ index
1458
+ });
1459
+ }
1460
+ //#endregion
1461
+ //#region node_modules/@sinclair/typebox/build/esm/type/async-iterator/async-iterator.mjs
1462
+ /** `[JavaScript]` Creates a AsyncIterator type */
1463
+ function AsyncIterator(items, options) {
1464
+ return CreateType({
1465
+ [Kind]: "AsyncIterator",
1466
+ type: "AsyncIterator",
1467
+ items
1468
+ }, options);
1469
+ }
1470
+ //#endregion
1471
+ //#region node_modules/@sinclair/typebox/build/esm/type/computed/computed.mjs
1472
+ /** `[Internal]` Creates a deferred computed type. This type is used exclusively in modules to defer resolution of computable types that contain interior references */
1473
+ function Computed(target, parameters, options) {
1474
+ return CreateType({
1475
+ [Kind]: "Computed",
1476
+ target,
1477
+ parameters
1478
+ }, options);
1479
+ }
1480
+ //#endregion
1481
+ //#region node_modules/@sinclair/typebox/build/esm/type/discard/discard.mjs
1482
+ function DiscardKey(value, key) {
1483
+ const { [key]: _, ...rest } = value;
1484
+ return rest;
1485
+ }
1486
+ /** Discards property keys from the given value. This function returns a shallow Clone. */
1487
+ function Discard(value, keys) {
1488
+ return keys.reduce((acc, key) => DiscardKey(acc, key), value);
1489
+ }
1490
+ //#endregion
1491
+ //#region node_modules/@sinclair/typebox/build/esm/type/never/never.mjs
1492
+ /** `[Json]` Creates a Never type */
1493
+ function Never(options) {
1494
+ return CreateType({
1495
+ [Kind]: "Never",
1496
+ not: {}
1497
+ }, options);
1498
+ }
1499
+ //#endregion
1500
+ //#region node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-result.mjs
1501
+ function MappedResult(properties) {
1502
+ return CreateType({
1503
+ [Kind]: "MappedResult",
1504
+ properties
1505
+ });
1506
+ }
1507
+ //#endregion
1508
+ //#region node_modules/@sinclair/typebox/build/esm/type/constructor/constructor.mjs
1509
+ /** `[JavaScript]` Creates a Constructor type */
1510
+ function Constructor(parameters, returns, options) {
1511
+ return CreateType({
1512
+ [Kind]: "Constructor",
1513
+ type: "Constructor",
1514
+ parameters,
1515
+ returns
1516
+ }, options);
1517
+ }
1518
+ //#endregion
1519
+ //#region node_modules/@sinclair/typebox/build/esm/type/function/function.mjs
1520
+ /** `[JavaScript]` Creates a Function type */
1521
+ function Function(parameters, returns, options) {
1522
+ return CreateType({
1523
+ [Kind]: "Function",
1524
+ type: "Function",
1525
+ parameters,
1526
+ returns
1527
+ }, options);
1528
+ }
1529
+ //#endregion
1530
+ //#region node_modules/@sinclair/typebox/build/esm/type/union/union-create.mjs
1531
+ function UnionCreate(T, options) {
1532
+ return CreateType({
1533
+ [Kind]: "Union",
1534
+ anyOf: T
1535
+ }, options);
1536
+ }
1537
+ //#endregion
1538
+ //#region node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs
1539
+ function IsUnionOptional(types) {
1540
+ return types.some((type) => IsOptional$1(type));
1541
+ }
1542
+ function RemoveOptionalFromRest$1(types) {
1543
+ return types.map((left) => IsOptional$1(left) ? RemoveOptionalFromType$1(left) : left);
1544
+ }
1545
+ function RemoveOptionalFromType$1(T) {
1546
+ return Discard(T, [OptionalKind]);
1547
+ }
1548
+ function ResolveUnion(types, options) {
1549
+ return IsUnionOptional(types) ? Optional(UnionCreate(RemoveOptionalFromRest$1(types), options)) : UnionCreate(RemoveOptionalFromRest$1(types), options);
1550
+ }
1551
+ /** `[Json]` Creates an evaluated Union type */
1552
+ function UnionEvaluated(T, options) {
1553
+ return T.length === 1 ? CreateType(T[0], options) : T.length === 0 ? Never(options) : ResolveUnion(T, options);
1554
+ }
1555
+ //#endregion
1556
+ //#region node_modules/@sinclair/typebox/build/esm/type/union/union.mjs
1557
+ /** `[Json]` Creates a Union type */
1558
+ function Union(types, options) {
1559
+ return types.length === 0 ? Never(options) : types.length === 1 ? CreateType(types[0], options) : UnionCreate(types, options);
1560
+ }
1561
+ //#endregion
1562
+ //#region node_modules/@sinclair/typebox/build/esm/type/template-literal/parse.mjs
1563
+ var TemplateLiteralParserError = class extends TypeBoxError {};
1564
+ function Unescape(pattern) {
1565
+ return pattern.replace(/\\\$/g, "$").replace(/\\\*/g, "*").replace(/\\\^/g, "^").replace(/\\\|/g, "|").replace(/\\\(/g, "(").replace(/\\\)/g, ")");
1566
+ }
1567
+ function IsNonEscaped(pattern, index, char) {
1568
+ return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92;
1569
+ }
1570
+ function IsOpenParen(pattern, index) {
1571
+ return IsNonEscaped(pattern, index, "(");
1572
+ }
1573
+ function IsCloseParen(pattern, index) {
1574
+ return IsNonEscaped(pattern, index, ")");
1575
+ }
1576
+ function IsSeparator(pattern, index) {
1577
+ return IsNonEscaped(pattern, index, "|");
1578
+ }
1579
+ function IsGroup(pattern) {
1580
+ if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1))) return false;
1581
+ let count = 0;
1582
+ for (let index = 0; index < pattern.length; index++) {
1583
+ if (IsOpenParen(pattern, index)) count += 1;
1584
+ if (IsCloseParen(pattern, index)) count -= 1;
1585
+ if (count === 0 && index !== pattern.length - 1) return false;
1586
+ }
1587
+ return true;
1588
+ }
1589
+ function InGroup(pattern) {
1590
+ return pattern.slice(1, pattern.length - 1);
1591
+ }
1592
+ function IsPrecedenceOr(pattern) {
1593
+ let count = 0;
1594
+ for (let index = 0; index < pattern.length; index++) {
1595
+ if (IsOpenParen(pattern, index)) count += 1;
1596
+ if (IsCloseParen(pattern, index)) count -= 1;
1597
+ if (IsSeparator(pattern, index) && count === 0) return true;
1598
+ }
1599
+ return false;
1600
+ }
1601
+ function IsPrecedenceAnd(pattern) {
1602
+ for (let index = 0; index < pattern.length; index++) if (IsOpenParen(pattern, index)) return true;
1603
+ return false;
1604
+ }
1605
+ function Or(pattern) {
1606
+ let [count, start] = [0, 0];
1607
+ const expressions = [];
1608
+ for (let index = 0; index < pattern.length; index++) {
1609
+ if (IsOpenParen(pattern, index)) count += 1;
1610
+ if (IsCloseParen(pattern, index)) count -= 1;
1611
+ if (IsSeparator(pattern, index) && count === 0) {
1612
+ const range = pattern.slice(start, index);
1613
+ if (range.length > 0) expressions.push(TemplateLiteralParse(range));
1614
+ start = index + 1;
1615
+ }
1616
+ }
1617
+ const range = pattern.slice(start);
1618
+ if (range.length > 0) expressions.push(TemplateLiteralParse(range));
1619
+ if (expressions.length === 0) return {
1620
+ type: "const",
1621
+ const: ""
1622
+ };
1623
+ if (expressions.length === 1) return expressions[0];
1624
+ return {
1625
+ type: "or",
1626
+ expr: expressions
1627
+ };
1628
+ }
1629
+ function And(pattern) {
1630
+ function Group(value, index) {
1631
+ if (!IsOpenParen(value, index)) throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`);
1632
+ let count = 0;
1633
+ for (let scan = index; scan < value.length; scan++) {
1634
+ if (IsOpenParen(value, scan)) count += 1;
1635
+ if (IsCloseParen(value, scan)) count -= 1;
1636
+ if (count === 0) return [index, scan];
1637
+ }
1638
+ throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`);
1639
+ }
1640
+ function Range(pattern, index) {
1641
+ for (let scan = index; scan < pattern.length; scan++) if (IsOpenParen(pattern, scan)) return [index, scan];
1642
+ return [index, pattern.length];
1643
+ }
1644
+ const expressions = [];
1645
+ for (let index = 0; index < pattern.length; index++) if (IsOpenParen(pattern, index)) {
1646
+ const [start, end] = Group(pattern, index);
1647
+ const range = pattern.slice(start, end + 1);
1648
+ expressions.push(TemplateLiteralParse(range));
1649
+ index = end;
1650
+ } else {
1651
+ const [start, end] = Range(pattern, index);
1652
+ const range = pattern.slice(start, end);
1653
+ if (range.length > 0) expressions.push(TemplateLiteralParse(range));
1654
+ index = end - 1;
1655
+ }
1656
+ return expressions.length === 0 ? {
1657
+ type: "const",
1658
+ const: ""
1659
+ } : expressions.length === 1 ? expressions[0] : {
1660
+ type: "and",
1661
+ expr: expressions
1662
+ };
1663
+ }
1664
+ /** Parses a pattern and returns an expression tree */
1665
+ function TemplateLiteralParse(pattern) {
1666
+ return IsGroup(pattern) ? TemplateLiteralParse(InGroup(pattern)) : IsPrecedenceOr(pattern) ? Or(pattern) : IsPrecedenceAnd(pattern) ? And(pattern) : {
1667
+ type: "const",
1668
+ const: Unescape(pattern)
1669
+ };
1670
+ }
1671
+ /** Parses a pattern and strips forward and trailing ^ and $ */
1672
+ function TemplateLiteralParseExact(pattern) {
1673
+ return TemplateLiteralParse(pattern.slice(1, pattern.length - 1));
1674
+ }
1675
+ //#endregion
1676
+ //#region node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs
1677
+ var TemplateLiteralFiniteError = class extends TypeBoxError {};
1678
+ function IsNumberExpression(expression) {
1679
+ return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "0" && expression.expr[1].type === "const" && expression.expr[1].const === "[1-9][0-9]*";
1680
+ }
1681
+ function IsBooleanExpression(expression) {
1682
+ return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "true" && expression.expr[1].type === "const" && expression.expr[1].const === "false";
1683
+ }
1684
+ function IsStringExpression(expression) {
1685
+ return expression.type === "const" && expression.const === ".*";
1686
+ }
1687
+ function IsTemplateLiteralExpressionFinite(expression) {
1688
+ return IsNumberExpression(expression) || IsStringExpression(expression) ? false : IsBooleanExpression(expression) ? true : expression.type === "and" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) : expression.type === "or" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) : expression.type === "const" ? true : (() => {
1689
+ throw new TemplateLiteralFiniteError(`Unknown expression type`);
1690
+ })();
1691
+ }
1692
+ /** Returns true if this TemplateLiteral resolves to a finite set of values */
1693
+ function IsTemplateLiteralFinite(schema) {
1694
+ return IsTemplateLiteralExpressionFinite(TemplateLiteralParseExact(schema.pattern));
1695
+ }
1696
+ //#endregion
1697
+ //#region node_modules/@sinclair/typebox/build/esm/type/template-literal/generate.mjs
1698
+ var TemplateLiteralGenerateError = class extends TypeBoxError {};
1699
+ function* GenerateReduce(buffer) {
1700
+ if (buffer.length === 1) return yield* buffer[0];
1701
+ for (const left of buffer[0]) for (const right of GenerateReduce(buffer.slice(1))) yield `${left}${right}`;
1702
+ }
1703
+ function* GenerateAnd(expression) {
1704
+ return yield* GenerateReduce(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate(expr)]));
1705
+ }
1706
+ function* GenerateOr(expression) {
1707
+ for (const expr of expression.expr) yield* TemplateLiteralExpressionGenerate(expr);
1708
+ }
1709
+ function* GenerateConst(expression) {
1710
+ return yield expression.const;
1711
+ }
1712
+ function* TemplateLiteralExpressionGenerate(expression) {
1713
+ return expression.type === "and" ? yield* GenerateAnd(expression) : expression.type === "or" ? yield* GenerateOr(expression) : expression.type === "const" ? yield* GenerateConst(expression) : (() => {
1714
+ throw new TemplateLiteralGenerateError("Unknown expression");
1715
+ })();
1716
+ }
1717
+ /** Generates a tuple of strings from the given TemplateLiteral. Returns an empty tuple if infinite. */
1718
+ function TemplateLiteralGenerate(schema) {
1719
+ const expression = TemplateLiteralParseExact(schema.pattern);
1720
+ return IsTemplateLiteralExpressionFinite(expression) ? [...TemplateLiteralExpressionGenerate(expression)] : [];
1721
+ }
1722
+ //#endregion
1723
+ //#region node_modules/@sinclair/typebox/build/esm/type/literal/literal.mjs
1724
+ /** `[Json]` Creates a Literal type */
1725
+ function Literal(value, options) {
1726
+ return CreateType({
1727
+ [Kind]: "Literal",
1728
+ const: value,
1729
+ type: typeof value
1730
+ }, options);
1731
+ }
1732
+ //#endregion
1733
+ //#region node_modules/@sinclair/typebox/build/esm/type/boolean/boolean.mjs
1734
+ /** `[Json]` Creates a Boolean type */
1735
+ function Boolean(options) {
1736
+ return CreateType({
1737
+ [Kind]: "Boolean",
1738
+ type: "boolean"
1739
+ }, options);
1740
+ }
1741
+ //#endregion
1742
+ //#region node_modules/@sinclair/typebox/build/esm/type/bigint/bigint.mjs
1743
+ /** `[JavaScript]` Creates a BigInt type */
1744
+ function BigInt(options) {
1745
+ return CreateType({
1746
+ [Kind]: "BigInt",
1747
+ type: "bigint"
1748
+ }, options);
1749
+ }
1750
+ //#endregion
1751
+ //#region node_modules/@sinclair/typebox/build/esm/type/number/number.mjs
1752
+ /** `[Json]` Creates a Number type */
1753
+ function Number$1(options) {
1754
+ return CreateType({
1755
+ [Kind]: "Number",
1756
+ type: "number"
1757
+ }, options);
1758
+ }
1759
+ //#endregion
1760
+ //#region node_modules/@sinclair/typebox/build/esm/type/string/string.mjs
1761
+ /** `[Json]` Creates a String type */
1762
+ function String$1(options) {
1763
+ return CreateType({
1764
+ [Kind]: "String",
1765
+ type: "string"
1766
+ }, options);
1767
+ }
1768
+ //#endregion
1769
+ //#region node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs
1770
+ function* FromUnion$9(syntax) {
1771
+ const trim = syntax.trim().replace(/"|'/g, "");
1772
+ return trim === "boolean" ? yield Boolean() : trim === "number" ? yield Number$1() : trim === "bigint" ? yield BigInt() : trim === "string" ? yield String$1() : yield (() => {
1773
+ const literals = trim.split("|").map((literal) => Literal(literal.trim()));
1774
+ return literals.length === 0 ? Never() : literals.length === 1 ? literals[0] : UnionEvaluated(literals);
1775
+ })();
1776
+ }
1777
+ function* FromTerminal(syntax) {
1778
+ if (syntax[1] !== "{") return yield* [Literal("$"), ...FromSyntax(syntax.slice(1))];
1779
+ for (let i = 2; i < syntax.length; i++) if (syntax[i] === "}") {
1780
+ const L = FromUnion$9(syntax.slice(2, i));
1781
+ const R = FromSyntax(syntax.slice(i + 1));
1782
+ return yield* [...L, ...R];
1783
+ }
1784
+ yield Literal(syntax);
1785
+ }
1786
+ function* FromSyntax(syntax) {
1787
+ for (let i = 0; i < syntax.length; i++) if (syntax[i] === "$") return yield* [Literal(syntax.slice(0, i)), ...FromTerminal(syntax.slice(i))];
1788
+ yield Literal(syntax);
1789
+ }
1790
+ /** Parses TemplateLiteralSyntax and returns a tuple of TemplateLiteralKinds */
1791
+ function TemplateLiteralSyntax(syntax) {
1792
+ return [...FromSyntax(syntax)];
1793
+ }
1794
+ //#endregion
1795
+ //#region node_modules/@sinclair/typebox/build/esm/type/template-literal/pattern.mjs
1796
+ var TemplateLiteralPatternError = class extends TypeBoxError {};
1797
+ function Escape(value) {
1798
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1799
+ }
1800
+ function Visit$1(schema, acc) {
1801
+ return IsTemplateLiteral$1(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) : IsUnion$1(schema) ? `(${schema.anyOf.map((schema) => Visit$1(schema, acc)).join("|")})` : IsNumber$1(schema) ? `${acc}${PatternNumber}` : IsInteger$1(schema) ? `${acc}${PatternNumber}` : IsBigInt$1(schema) ? `${acc}${PatternNumber}` : IsString$1(schema) ? `${acc}${PatternString}` : IsLiteral$1(schema) ? `${acc}${Escape(schema.const.toString())}` : IsBoolean$1(schema) ? `${acc}${PatternBoolean}` : (() => {
1802
+ throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`);
1803
+ })();
1804
+ }
1805
+ function TemplateLiteralPattern(kinds) {
1806
+ return `^${kinds.map((schema) => Visit$1(schema, "")).join("")}\$`;
1807
+ }
1808
+ //#endregion
1809
+ //#region node_modules/@sinclair/typebox/build/esm/type/template-literal/union.mjs
1810
+ /** Returns a Union from the given TemplateLiteral */
1811
+ function TemplateLiteralToUnion(schema) {
1812
+ return UnionEvaluated(TemplateLiteralGenerate(schema).map((S) => Literal(S)));
1813
+ }
1814
+ //#endregion
1815
+ //#region node_modules/@sinclair/typebox/build/esm/type/template-literal/template-literal.mjs
1816
+ /** `[Json]` Creates a TemplateLiteral type */
1817
+ function TemplateLiteral(unresolved, options) {
1818
+ const pattern = IsString$2(unresolved) ? TemplateLiteralPattern(TemplateLiteralSyntax(unresolved)) : TemplateLiteralPattern(unresolved);
1819
+ return CreateType({
1820
+ [Kind]: "TemplateLiteral",
1821
+ type: "string",
1822
+ pattern
1823
+ }, options);
1824
+ }
1825
+ //#endregion
1826
+ //#region node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs
1827
+ function FromTemplateLiteral$2(templateLiteral) {
1828
+ return TemplateLiteralGenerate(templateLiteral).map((key) => key.toString());
1829
+ }
1830
+ function FromUnion$8(types) {
1831
+ const result = [];
1832
+ for (const type of types) result.push(...IndexPropertyKeys(type));
1833
+ return result;
1834
+ }
1835
+ function FromLiteral$1(literalValue) {
1836
+ return [literalValue.toString()];
1837
+ }
1838
+ /** Returns a tuple of PropertyKeys derived from the given TSchema */
1839
+ function IndexPropertyKeys(type) {
1840
+ return [...new Set(IsTemplateLiteral$1(type) ? FromTemplateLiteral$2(type) : IsUnion$1(type) ? FromUnion$8(type.anyOf) : IsLiteral$1(type) ? FromLiteral$1(type.const) : IsNumber$1(type) ? ["[number]"] : IsInteger$1(type) ? ["[number]"] : [])];
1841
+ }
1842
+ //#endregion
1843
+ //#region node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-result.mjs
1844
+ function FromProperties$18(type, properties, options) {
1845
+ const result = {};
1846
+ for (const K2 of Object.getOwnPropertyNames(properties)) result[K2] = Index(type, IndexPropertyKeys(properties[K2]), options);
1847
+ return result;
1848
+ }
1849
+ function FromMappedResult$11(type, mappedResult, options) {
1850
+ return FromProperties$18(type, mappedResult.properties, options);
1851
+ }
1852
+ function IndexFromMappedResult(type, mappedResult, options) {
1853
+ return MappedResult(FromMappedResult$11(type, mappedResult, options));
1854
+ }
1855
+ //#endregion
1856
+ //#region node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs
1857
+ function FromRest$6(types, key) {
1858
+ return types.map((type) => IndexFromPropertyKey(type, key));
1859
+ }
1860
+ function FromIntersectRest(types) {
1861
+ return types.filter((type) => !IsNever$1(type));
1862
+ }
1863
+ function FromIntersect$7(types, key) {
1864
+ return IntersectEvaluated(FromIntersectRest(FromRest$6(types, key)));
1865
+ }
1866
+ function FromUnionRest(types) {
1867
+ return types.some((L) => IsNever$1(L)) ? [] : types;
1868
+ }
1869
+ function FromUnion$7(types, key) {
1870
+ return UnionEvaluated(FromUnionRest(FromRest$6(types, key)));
1871
+ }
1872
+ function FromTuple$4(types, key) {
1873
+ return key in types ? types[key] : key === "[number]" ? UnionEvaluated(types) : Never();
1874
+ }
1875
+ function FromArray$5(type, key) {
1876
+ return key === "[number]" ? type : Never();
1877
+ }
1878
+ function FromProperty$2(properties, propertyKey) {
1879
+ return propertyKey in properties ? properties[propertyKey] : Never();
1880
+ }
1881
+ function IndexFromPropertyKey(type, propertyKey) {
1882
+ return IsIntersect$1(type) ? FromIntersect$7(type.allOf, propertyKey) : IsUnion$1(type) ? FromUnion$7(type.anyOf, propertyKey) : IsTuple$1(type) ? FromTuple$4(type.items ?? [], propertyKey) : IsArray$1(type) ? FromArray$5(type.items, propertyKey) : IsObject$1(type) ? FromProperty$2(type.properties, propertyKey) : Never();
1883
+ }
1884
+ function IndexFromPropertyKeys(type, propertyKeys) {
1885
+ return propertyKeys.map((propertyKey) => IndexFromPropertyKey(type, propertyKey));
1886
+ }
1887
+ function FromSchema(type, propertyKeys) {
1888
+ return UnionEvaluated(IndexFromPropertyKeys(type, propertyKeys));
1889
+ }
1890
+ /** `[Json]` Returns an Indexed property type for the given keys */
1891
+ function Index(type, key, options) {
1892
+ if (IsRef$1(type) || IsRef$1(key)) {
1893
+ const error = `Index types using Ref parameters require both Type and Key to be of TSchema`;
1894
+ if (!IsSchema$1(type) || !IsSchema$1(key)) throw new TypeBoxError(error);
1895
+ return Computed("Index", [type, key]);
1896
+ }
1897
+ if (IsMappedResult$1(key)) return IndexFromMappedResult(type, key, options);
1898
+ if (IsMappedKey$1(key)) return IndexFromMappedKey(type, key, options);
1899
+ return CreateType(IsSchema$1(key) ? FromSchema(type, IndexPropertyKeys(key)) : FromSchema(type, key), options);
1900
+ }
1901
+ //#endregion
1902
+ //#region node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs
1903
+ function MappedIndexPropertyKey(type, key, options) {
1904
+ return { [key]: Index(type, [key], Clone(options)) };
1905
+ }
1906
+ function MappedIndexPropertyKeys(type, propertyKeys, options) {
1907
+ return propertyKeys.reduce((result, left) => {
1908
+ return {
1909
+ ...result,
1910
+ ...MappedIndexPropertyKey(type, left, options)
1911
+ };
1912
+ }, {});
1913
+ }
1914
+ function MappedIndexProperties(type, mappedKey, options) {
1915
+ return MappedIndexPropertyKeys(type, mappedKey.keys, options);
1916
+ }
1917
+ function IndexFromMappedKey(type, mappedKey, options) {
1918
+ return MappedResult(MappedIndexProperties(type, mappedKey, options));
1919
+ }
1920
+ //#endregion
1921
+ //#region node_modules/@sinclair/typebox/build/esm/type/iterator/iterator.mjs
1922
+ /** `[JavaScript]` Creates an Iterator type */
1923
+ function Iterator(items, options) {
1924
+ return CreateType({
1925
+ [Kind]: "Iterator",
1926
+ type: "Iterator",
1927
+ items
1928
+ }, options);
1929
+ }
1930
+ //#endregion
1931
+ //#region node_modules/@sinclair/typebox/build/esm/type/object/object.mjs
1932
+ /** Creates a RequiredArray derived from the given TProperties value. */
1933
+ function RequiredArray(properties) {
1934
+ return globalThis.Object.keys(properties).filter((key) => !IsOptional$1(properties[key]));
1935
+ }
1936
+ /** `[Json]` Creates an Object type */
1937
+ function _Object(properties, options) {
1938
+ const required = RequiredArray(properties);
1939
+ return CreateType(required.length > 0 ? {
1940
+ [Kind]: "Object",
1941
+ type: "object",
1942
+ required,
1943
+ properties
1944
+ } : {
1945
+ [Kind]: "Object",
1946
+ type: "object",
1947
+ properties
1948
+ }, options);
1949
+ }
1950
+ /** `[Json]` Creates an Object type */
1951
+ var Object$1 = _Object;
1952
+ //#endregion
1953
+ //#region node_modules/@sinclair/typebox/build/esm/type/promise/promise.mjs
1954
+ /** `[JavaScript]` Creates a Promise type */
1955
+ function Promise$1(item, options) {
1956
+ return CreateType({
1957
+ [Kind]: "Promise",
1958
+ type: "Promise",
1959
+ item
1960
+ }, options);
1961
+ }
1962
+ //#endregion
1963
+ //#region node_modules/@sinclair/typebox/build/esm/type/readonly/readonly.mjs
1964
+ function RemoveReadonly(schema) {
1965
+ return CreateType(Discard(schema, [ReadonlyKind]));
1966
+ }
1967
+ function AddReadonly(schema) {
1968
+ return CreateType({
1969
+ ...schema,
1970
+ [ReadonlyKind]: "Readonly"
1971
+ });
1972
+ }
1973
+ function ReadonlyWithFlag(schema, F) {
1974
+ return F === false ? RemoveReadonly(schema) : AddReadonly(schema);
1975
+ }
1976
+ /** `[Json]` Creates a Readonly property */
1977
+ function Readonly(schema, enable) {
1978
+ const F = enable ?? true;
1979
+ return IsMappedResult$1(schema) ? ReadonlyFromMappedResult(schema, F) : ReadonlyWithFlag(schema, F);
1980
+ }
1981
+ //#endregion
1982
+ //#region node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs
1983
+ function FromProperties$17(K, F) {
1984
+ const Acc = {};
1985
+ for (const K2 of globalThis.Object.getOwnPropertyNames(K)) Acc[K2] = Readonly(K[K2], F);
1986
+ return Acc;
1987
+ }
1988
+ function FromMappedResult$10(R, F) {
1989
+ return FromProperties$17(R.properties, F);
1990
+ }
1991
+ function ReadonlyFromMappedResult(R, F) {
1992
+ return MappedResult(FromMappedResult$10(R, F));
1993
+ }
1994
+ //#endregion
1995
+ //#region node_modules/@sinclair/typebox/build/esm/type/tuple/tuple.mjs
1996
+ /** `[Json]` Creates a Tuple type */
1997
+ function Tuple(types, options) {
1998
+ return CreateType(types.length > 0 ? {
1999
+ [Kind]: "Tuple",
2000
+ type: "array",
2001
+ items: types,
2002
+ additionalItems: false,
2003
+ minItems: types.length,
2004
+ maxItems: types.length
2005
+ } : {
2006
+ [Kind]: "Tuple",
2007
+ type: "array",
2008
+ minItems: types.length,
2009
+ maxItems: types.length
2010
+ }, options);
2011
+ }
2012
+ //#endregion
2013
+ //#region node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs
2014
+ function FromMappedResult$9(K, P) {
2015
+ return K in P ? FromSchemaType(K, P[K]) : MappedResult(P);
2016
+ }
2017
+ function MappedKeyToKnownMappedResultProperties(K) {
2018
+ return { [K]: Literal(K) };
2019
+ }
2020
+ function MappedKeyToUnknownMappedResultProperties(P) {
2021
+ const Acc = {};
2022
+ for (const L of P) Acc[L] = Literal(L);
2023
+ return Acc;
2024
+ }
2025
+ function MappedKeyToMappedResultProperties(K, P) {
2026
+ return SetIncludes(P, K) ? MappedKeyToKnownMappedResultProperties(K) : MappedKeyToUnknownMappedResultProperties(P);
2027
+ }
2028
+ function FromMappedKey$3(K, P) {
2029
+ return FromMappedResult$9(K, MappedKeyToMappedResultProperties(K, P));
2030
+ }
2031
+ function FromRest$5(K, T) {
2032
+ return T.map((L) => FromSchemaType(K, L));
2033
+ }
2034
+ function FromProperties$16(K, T) {
2035
+ const Acc = {};
2036
+ for (const K2 of globalThis.Object.getOwnPropertyNames(T)) Acc[K2] = FromSchemaType(K, T[K2]);
2037
+ return Acc;
2038
+ }
2039
+ function FromSchemaType(K, T) {
2040
+ const options = { ...T };
2041
+ return IsOptional$1(T) ? Optional(FromSchemaType(K, Discard(T, [OptionalKind]))) : IsReadonly(T) ? Readonly(FromSchemaType(K, Discard(T, [ReadonlyKind]))) : IsMappedResult$1(T) ? FromMappedResult$9(K, T.properties) : IsMappedKey$1(T) ? FromMappedKey$3(K, T.keys) : IsConstructor$1(T) ? Constructor(FromRest$5(K, T.parameters), FromSchemaType(K, T.returns), options) : IsFunction$1(T) ? Function(FromRest$5(K, T.parameters), FromSchemaType(K, T.returns), options) : IsAsyncIterator$1(T) ? AsyncIterator(FromSchemaType(K, T.items), options) : IsIterator$1(T) ? Iterator(FromSchemaType(K, T.items), options) : IsIntersect$1(T) ? Intersect(FromRest$5(K, T.allOf), options) : IsUnion$1(T) ? Union(FromRest$5(K, T.anyOf), options) : IsTuple$1(T) ? Tuple(FromRest$5(K, T.items ?? []), options) : IsObject$1(T) ? Object$1(FromProperties$16(K, T.properties), options) : IsArray$1(T) ? Array$1(FromSchemaType(K, T.items), options) : IsPromise$1(T) ? Promise$1(FromSchemaType(K, T.item), options) : T;
2042
+ }
2043
+ function MappedFunctionReturnType(K, T) {
2044
+ const Acc = {};
2045
+ for (const L of K) Acc[L] = FromSchemaType(L, T);
2046
+ return Acc;
2047
+ }
2048
+ /** `[Json]` Creates a Mapped object type */
2049
+ function Mapped(key, map, options) {
2050
+ const K = IsSchema$1(key) ? IndexPropertyKeys(key) : key;
2051
+ return Object$1(MappedFunctionReturnType(K, map({
2052
+ [Kind]: "MappedKey",
2053
+ keys: K
2054
+ })), options);
2055
+ }
2056
+ //#endregion
2057
+ //#region node_modules/@sinclair/typebox/build/esm/type/optional/optional.mjs
2058
+ function RemoveOptional(schema) {
2059
+ return CreateType(Discard(schema, [OptionalKind]));
2060
+ }
2061
+ function AddOptional(schema) {
2062
+ return CreateType({
2063
+ ...schema,
2064
+ [OptionalKind]: "Optional"
2065
+ });
2066
+ }
2067
+ function OptionalWithFlag(schema, F) {
2068
+ return F === false ? RemoveOptional(schema) : AddOptional(schema);
2069
+ }
2070
+ /** `[Json]` Creates a Optional property */
2071
+ function Optional(schema, enable) {
2072
+ const F = enable ?? true;
2073
+ return IsMappedResult$1(schema) ? OptionalFromMappedResult(schema, F) : OptionalWithFlag(schema, F);
2074
+ }
2075
+ //#endregion
2076
+ //#region node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs
2077
+ function FromProperties$15(P, F) {
2078
+ const Acc = {};
2079
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P)) Acc[K2] = Optional(P[K2], F);
2080
+ return Acc;
2081
+ }
2082
+ function FromMappedResult$8(R, F) {
2083
+ return FromProperties$15(R.properties, F);
2084
+ }
2085
+ function OptionalFromMappedResult(R, F) {
2086
+ return MappedResult(FromMappedResult$8(R, F));
2087
+ }
2088
+ //#endregion
2089
+ //#region node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-create.mjs
2090
+ function IntersectCreate(T, options = {}) {
2091
+ const allObjects = T.every((schema) => IsObject$1(schema));
2092
+ const clonedUnevaluatedProperties = IsSchema$1(options.unevaluatedProperties) ? { unevaluatedProperties: options.unevaluatedProperties } : {};
2093
+ return CreateType(options.unevaluatedProperties === false || IsSchema$1(options.unevaluatedProperties) || allObjects ? {
2094
+ ...clonedUnevaluatedProperties,
2095
+ [Kind]: "Intersect",
2096
+ type: "object",
2097
+ allOf: T
2098
+ } : {
2099
+ ...clonedUnevaluatedProperties,
2100
+ [Kind]: "Intersect",
2101
+ allOf: T
2102
+ }, options);
2103
+ }
2104
+ //#endregion
2105
+ //#region node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs
2106
+ function IsIntersectOptional(types) {
2107
+ return types.every((left) => IsOptional$1(left));
2108
+ }
2109
+ function RemoveOptionalFromType(type) {
2110
+ return Discard(type, [OptionalKind]);
2111
+ }
2112
+ function RemoveOptionalFromRest(types) {
2113
+ return types.map((left) => IsOptional$1(left) ? RemoveOptionalFromType(left) : left);
2114
+ }
2115
+ function ResolveIntersect(types, options) {
2116
+ return IsIntersectOptional(types) ? Optional(IntersectCreate(RemoveOptionalFromRest(types), options)) : IntersectCreate(RemoveOptionalFromRest(types), options);
2117
+ }
2118
+ /** `[Json]` Creates an evaluated Intersect type */
2119
+ function IntersectEvaluated(types, options = {}) {
2120
+ if (types.length === 1) return CreateType(types[0], options);
2121
+ if (types.length === 0) return Never(options);
2122
+ if (types.some((schema) => IsTransform$1(schema))) throw new Error("Cannot intersect transform types");
2123
+ return ResolveIntersect(types, options);
2124
+ }
2125
+ //#endregion
2126
+ //#region node_modules/@sinclair/typebox/build/esm/type/intersect/intersect.mjs
2127
+ /** `[Json]` Creates an evaluated Intersect type */
2128
+ function Intersect(types, options) {
2129
+ if (types.length === 1) return CreateType(types[0], options);
2130
+ if (types.length === 0) return Never(options);
2131
+ if (types.some((schema) => IsTransform$1(schema))) throw new Error("Cannot intersect transform types");
2132
+ return IntersectCreate(types, options);
2133
+ }
2134
+ //#endregion
2135
+ //#region node_modules/@sinclair/typebox/build/esm/type/ref/ref.mjs
2136
+ /** `[Json]` Creates a Ref type. The referenced type must contain a $id */
2137
+ function Ref(...args) {
2138
+ const [$ref, options] = typeof args[0] === "string" ? [args[0], args[1]] : [args[0].$id, args[1]];
2139
+ if (typeof $ref !== "string") throw new TypeBoxError("Ref: $ref must be a string");
2140
+ return CreateType({
2141
+ [Kind]: "Ref",
2142
+ $ref
2143
+ }, options);
2144
+ }
2145
+ //#endregion
2146
+ //#region node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs
2147
+ function FromComputed$4(target, parameters) {
2148
+ return Computed("Awaited", [Computed(target, parameters)]);
2149
+ }
2150
+ function FromRef$3($ref) {
2151
+ return Computed("Awaited", [Ref($ref)]);
2152
+ }
2153
+ function FromIntersect$6(types) {
2154
+ return Intersect(FromRest$4(types));
2155
+ }
2156
+ function FromUnion$6(types) {
2157
+ return Union(FromRest$4(types));
2158
+ }
2159
+ function FromPromise$2(type) {
2160
+ return Awaited(type);
2161
+ }
2162
+ function FromRest$4(types) {
2163
+ return types.map((type) => Awaited(type));
2164
+ }
2165
+ /** `[JavaScript]` Constructs a type by recursively unwrapping Promise types */
2166
+ function Awaited(type, options) {
2167
+ return CreateType(IsComputed$1(type) ? FromComputed$4(type.target, type.parameters) : IsIntersect$1(type) ? FromIntersect$6(type.allOf) : IsUnion$1(type) ? FromUnion$6(type.anyOf) : IsPromise$1(type) ? FromPromise$2(type.item) : IsRef$1(type) ? FromRef$3(type.$ref) : type, options);
2168
+ }
2169
+ //#endregion
2170
+ //#region node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-keys.mjs
2171
+ function FromRest$3(types) {
2172
+ const result = [];
2173
+ for (const L of types) result.push(KeyOfPropertyKeys(L));
2174
+ return result;
2175
+ }
2176
+ function FromIntersect$5(types) {
2177
+ return SetUnionMany(FromRest$3(types));
2178
+ }
2179
+ function FromUnion$5(types) {
2180
+ return SetIntersectMany(FromRest$3(types));
2181
+ }
2182
+ function FromTuple$3(types) {
2183
+ return types.map((_, indexer) => indexer.toString());
2184
+ }
2185
+ function FromArray$4(_) {
2186
+ return ["[number]"];
2187
+ }
2188
+ function FromProperties$14(T) {
2189
+ return globalThis.Object.getOwnPropertyNames(T);
2190
+ }
2191
+ function FromPatternProperties(patternProperties) {
2192
+ if (!includePatternProperties) return [];
2193
+ return globalThis.Object.getOwnPropertyNames(patternProperties).map((key) => {
2194
+ return key[0] === "^" && key[key.length - 1] === "$" ? key.slice(1, key.length - 1) : key;
2195
+ });
2196
+ }
2197
+ /** Returns a tuple of PropertyKeys derived from the given TSchema. */
2198
+ function KeyOfPropertyKeys(type) {
2199
+ return IsIntersect$1(type) ? FromIntersect$5(type.allOf) : IsUnion$1(type) ? FromUnion$5(type.anyOf) : IsTuple$1(type) ? FromTuple$3(type.items ?? []) : IsArray$1(type) ? FromArray$4(type.items) : IsObject$1(type) ? FromProperties$14(type.properties) : IsRecord$1(type) ? FromPatternProperties(type.patternProperties) : [];
2200
+ }
2201
+ let includePatternProperties = false;
2202
+ //#endregion
2203
+ //#region node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs
2204
+ function FromComputed$3(target, parameters) {
2205
+ return Computed("KeyOf", [Computed(target, parameters)]);
2206
+ }
2207
+ function FromRef$2($ref) {
2208
+ return Computed("KeyOf", [Ref($ref)]);
2209
+ }
2210
+ function KeyOfFromType(type, options) {
2211
+ return CreateType(UnionEvaluated(KeyOfPropertyKeysToRest(KeyOfPropertyKeys(type))), options);
2212
+ }
2213
+ function KeyOfPropertyKeysToRest(propertyKeys) {
2214
+ return propertyKeys.map((L) => L === "[number]" ? Number$1() : Literal(L));
2215
+ }
2216
+ /** `[Json]` Creates a KeyOf type */
2217
+ function KeyOf(type, options) {
2218
+ return IsComputed$1(type) ? FromComputed$3(type.target, type.parameters) : IsRef$1(type) ? FromRef$2(type.$ref) : IsMappedResult$1(type) ? KeyOfFromMappedResult(type, options) : KeyOfFromType(type, options);
2219
+ }
2220
+ //#endregion
2221
+ //#region node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs
2222
+ function FromProperties$13(properties, options) {
2223
+ const result = {};
2224
+ for (const K2 of globalThis.Object.getOwnPropertyNames(properties)) result[K2] = KeyOf(properties[K2], Clone(options));
2225
+ return result;
2226
+ }
2227
+ function FromMappedResult$7(mappedResult, options) {
2228
+ return FromProperties$13(mappedResult.properties, options);
2229
+ }
2230
+ function KeyOfFromMappedResult(mappedResult, options) {
2231
+ return MappedResult(FromMappedResult$7(mappedResult, options));
2232
+ }
2233
+ //#endregion
2234
+ //#region node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs
2235
+ function CompositeKeys(T) {
2236
+ const Acc = [];
2237
+ for (const L of T) Acc.push(...KeyOfPropertyKeys(L));
2238
+ return SetDistinct(Acc);
2239
+ }
2240
+ function FilterNever(T) {
2241
+ return T.filter((L) => !IsNever$1(L));
2242
+ }
2243
+ function CompositeProperty(T, K) {
2244
+ const Acc = [];
2245
+ for (const L of T) Acc.push(...IndexFromPropertyKeys(L, [K]));
2246
+ return FilterNever(Acc);
2247
+ }
2248
+ function CompositeProperties(T, K) {
2249
+ const Acc = {};
2250
+ for (const L of K) Acc[L] = IntersectEvaluated(CompositeProperty(T, L));
2251
+ return Acc;
2252
+ }
2253
+ function Composite(T, options) {
2254
+ return Object$1(CompositeProperties(T, CompositeKeys(T)), options);
2255
+ }
2256
+ //#endregion
2257
+ //#region node_modules/@sinclair/typebox/build/esm/type/date/date.mjs
2258
+ /** `[JavaScript]` Creates a Date type */
2259
+ function Date$1(options) {
2260
+ return CreateType({
2261
+ [Kind]: "Date",
2262
+ type: "Date"
2263
+ }, options);
2264
+ }
2265
+ //#endregion
2266
+ //#region node_modules/@sinclair/typebox/build/esm/type/null/null.mjs
2267
+ /** `[Json]` Creates a Null type */
2268
+ function Null(options) {
2269
+ return CreateType({
2270
+ [Kind]: "Null",
2271
+ type: "null"
2272
+ }, options);
2273
+ }
2274
+ //#endregion
2275
+ //#region node_modules/@sinclair/typebox/build/esm/type/symbol/symbol.mjs
2276
+ /** `[JavaScript]` Creates a Symbol type */
2277
+ function Symbol$1(options) {
2278
+ return CreateType({
2279
+ [Kind]: "Symbol",
2280
+ type: "symbol"
2281
+ }, options);
2282
+ }
2283
+ //#endregion
2284
+ //#region node_modules/@sinclair/typebox/build/esm/type/undefined/undefined.mjs
2285
+ /** `[JavaScript]` Creates a Undefined type */
2286
+ function Undefined(options) {
2287
+ return CreateType({
2288
+ [Kind]: "Undefined",
2289
+ type: "undefined"
2290
+ }, options);
2291
+ }
2292
+ //#endregion
2293
+ //#region node_modules/@sinclair/typebox/build/esm/type/uint8array/uint8array.mjs
2294
+ /** `[JavaScript]` Creates a Uint8Array type */
2295
+ function Uint8Array$1(options) {
2296
+ return CreateType({
2297
+ [Kind]: "Uint8Array",
2298
+ type: "Uint8Array"
2299
+ }, options);
2300
+ }
2301
+ //#endregion
2302
+ //#region node_modules/@sinclair/typebox/build/esm/type/unknown/unknown.mjs
2303
+ /** `[Json]` Creates an Unknown type */
2304
+ function Unknown(options) {
2305
+ return CreateType({ [Kind]: "Unknown" }, options);
2306
+ }
2307
+ //#endregion
2308
+ //#region node_modules/@sinclair/typebox/build/esm/type/const/const.mjs
2309
+ function FromArray$3(T) {
2310
+ return T.map((L) => FromValue(L, false));
2311
+ }
2312
+ function FromProperties$12(value) {
2313
+ const Acc = {};
2314
+ for (const K of globalThis.Object.getOwnPropertyNames(value)) Acc[K] = Readonly(FromValue(value[K], false));
2315
+ return Acc;
2316
+ }
2317
+ function ConditionalReadonly(T, root) {
2318
+ return root === true ? T : Readonly(T);
2319
+ }
2320
+ function FromValue(value, root) {
2321
+ return IsAsyncIterator$2(value) ? ConditionalReadonly(Any(), root) : IsIterator$2(value) ? ConditionalReadonly(Any(), root) : IsArray$3(value) ? Readonly(Tuple(FromArray$3(value))) : IsUint8Array$2(value) ? Uint8Array$1() : IsDate$2(value) ? Date$1() : IsObject$3(value) ? ConditionalReadonly(Object$1(FromProperties$12(value)), root) : IsFunction$2(value) ? ConditionalReadonly(Function([], Unknown()), root) : IsUndefined$3(value) ? Undefined() : IsNull$2(value) ? Null() : IsSymbol$2(value) ? Symbol$1() : IsBigInt$2(value) ? BigInt() : IsNumber$3(value) ? Literal(value) : IsBoolean$2(value) ? Literal(value) : IsString$2(value) ? Literal(value) : Object$1({});
2322
+ }
2323
+ /** `[JavaScript]` Creates a readonly const type from the given value. */
2324
+ function Const(T, options) {
2325
+ return CreateType(FromValue(T, true), options);
2326
+ }
2327
+ //#endregion
2328
+ //#region node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/constructor-parameters.mjs
2329
+ /** `[JavaScript]` Extracts the ConstructorParameters from the given Constructor type */
2330
+ function ConstructorParameters(schema, options) {
2331
+ return IsConstructor$1(schema) ? Tuple(schema.parameters, options) : Never(options);
2332
+ }
2333
+ //#endregion
2334
+ //#region node_modules/@sinclair/typebox/build/esm/type/enum/enum.mjs
2335
+ /** `[Json]` Creates a Enum type */
2336
+ function Enum(item, options) {
2337
+ if (IsUndefined$3(item)) throw new Error("Enum undefined or empty");
2338
+ const values1 = globalThis.Object.getOwnPropertyNames(item).filter((key) => isNaN(key)).map((key) => item[key]);
2339
+ return Union([...new Set(values1)].map((value) => Literal(value)), {
2340
+ ...options,
2341
+ [Hint]: "Enum"
2342
+ });
2343
+ }
2344
+ //#endregion
2345
+ //#region node_modules/@sinclair/typebox/build/esm/type/extends/extends-check.mjs
2346
+ var ExtendsResolverError = class extends TypeBoxError {};
2347
+ var ExtendsResult;
2348
+ (function(ExtendsResult) {
2349
+ ExtendsResult[ExtendsResult["Union"] = 0] = "Union";
2350
+ ExtendsResult[ExtendsResult["True"] = 1] = "True";
2351
+ ExtendsResult[ExtendsResult["False"] = 2] = "False";
2352
+ })(ExtendsResult || (ExtendsResult = {}));
2353
+ function IntoBooleanResult(result) {
2354
+ return result === ExtendsResult.False ? result : ExtendsResult.True;
2355
+ }
2356
+ function Throw(message) {
2357
+ throw new ExtendsResolverError(message);
2358
+ }
2359
+ function IsStructuralRight(right) {
2360
+ return IsNever(right) || IsIntersect(right) || IsUnion(right) || IsUnknown(right) || IsAny(right);
2361
+ }
2362
+ function StructuralRight(left, right) {
2363
+ return IsNever(right) ? FromNeverRight(left, right) : IsIntersect(right) ? FromIntersectRight(left, right) : IsUnion(right) ? FromUnionRight(left, right) : IsUnknown(right) ? FromUnknownRight(left, right) : IsAny(right) ? FromAnyRight(left, right) : Throw("StructuralRight");
2364
+ }
2365
+ function FromAnyRight(left, right) {
2366
+ return ExtendsResult.True;
2367
+ }
2368
+ function FromAny(left, right) {
2369
+ return IsIntersect(right) ? FromIntersectRight(left, right) : IsUnion(right) && right.anyOf.some((schema) => IsAny(schema) || IsUnknown(schema)) ? ExtendsResult.True : IsUnion(right) ? ExtendsResult.Union : IsUnknown(right) ? ExtendsResult.True : IsAny(right) ? ExtendsResult.True : ExtendsResult.Union;
2370
+ }
2371
+ function FromArrayRight(left, right) {
2372
+ return IsUnknown(left) ? ExtendsResult.False : IsAny(left) ? ExtendsResult.Union : IsNever(left) ? ExtendsResult.True : ExtendsResult.False;
2373
+ }
2374
+ function FromArray$2(left, right) {
2375
+ return IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : !IsArray(right) ? ExtendsResult.False : IntoBooleanResult(Visit(left.items, right.items));
2376
+ }
2377
+ function FromAsyncIterator$2(left, right) {
2378
+ return IsStructuralRight(right) ? StructuralRight(left, right) : !IsAsyncIterator(right) ? ExtendsResult.False : IntoBooleanResult(Visit(left.items, right.items));
2379
+ }
2380
+ function FromBigInt(left, right) {
2381
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsBigInt(right) ? ExtendsResult.True : ExtendsResult.False;
2382
+ }
2383
+ function FromBooleanRight(left, right) {
2384
+ return IsLiteralBoolean(left) ? ExtendsResult.True : IsBoolean(left) ? ExtendsResult.True : ExtendsResult.False;
2385
+ }
2386
+ function FromBoolean(left, right) {
2387
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsBoolean(right) ? ExtendsResult.True : ExtendsResult.False;
2388
+ }
2389
+ function FromConstructor$2(left, right) {
2390
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : !IsConstructor(right) ? ExtendsResult.False : left.parameters.length > right.parameters.length ? ExtendsResult.False : !left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True) ? ExtendsResult.False : IntoBooleanResult(Visit(left.returns, right.returns));
2391
+ }
2392
+ function FromDate(left, right) {
2393
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsDate(right) ? ExtendsResult.True : ExtendsResult.False;
2394
+ }
2395
+ function FromFunction$2(left, right) {
2396
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : !IsFunction(right) ? ExtendsResult.False : left.parameters.length > right.parameters.length ? ExtendsResult.False : !left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True) ? ExtendsResult.False : IntoBooleanResult(Visit(left.returns, right.returns));
2397
+ }
2398
+ function FromIntegerRight(left, right) {
2399
+ return IsLiteral(left) && IsNumber$3(left.const) ? ExtendsResult.True : IsNumber(left) || IsInteger(left) ? ExtendsResult.True : ExtendsResult.False;
2400
+ }
2401
+ function FromInteger(left, right) {
2402
+ return IsInteger(right) || IsNumber(right) ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : ExtendsResult.False;
2403
+ }
2404
+ function FromIntersectRight(left, right) {
2405
+ return right.allOf.every((schema) => Visit(left, schema) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2406
+ }
2407
+ function FromIntersect$4(left, right) {
2408
+ return left.allOf.some((schema) => Visit(schema, right) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2409
+ }
2410
+ function FromIterator$2(left, right) {
2411
+ return IsStructuralRight(right) ? StructuralRight(left, right) : !IsIterator(right) ? ExtendsResult.False : IntoBooleanResult(Visit(left.items, right.items));
2412
+ }
2413
+ function FromLiteral(left, right) {
2414
+ return IsLiteral(right) && right.const === left.const ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsString(right) ? FromStringRight(left, right) : IsNumber(right) ? FromNumberRight(left, right) : IsInteger(right) ? FromIntegerRight(left, right) : IsBoolean(right) ? FromBooleanRight(left, right) : ExtendsResult.False;
2415
+ }
2416
+ function FromNeverRight(left, right) {
2417
+ return ExtendsResult.False;
2418
+ }
2419
+ function FromNever(left, right) {
2420
+ return ExtendsResult.True;
2421
+ }
2422
+ function UnwrapTNot(schema) {
2423
+ let [current, depth] = [schema, 0];
2424
+ while (true) {
2425
+ if (!IsNot(current)) break;
2426
+ current = current.not;
2427
+ depth += 1;
2428
+ }
2429
+ return depth % 2 === 0 ? current : Unknown();
2430
+ }
2431
+ function FromNot(left, right) {
2432
+ return IsNot(left) ? Visit(UnwrapTNot(left), right) : IsNot(right) ? Visit(left, UnwrapTNot(right)) : Throw("Invalid fallthrough for Not");
2433
+ }
2434
+ function FromNull(left, right) {
2435
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsNull(right) ? ExtendsResult.True : ExtendsResult.False;
2436
+ }
2437
+ function FromNumberRight(left, right) {
2438
+ return IsLiteralNumber(left) ? ExtendsResult.True : IsNumber(left) || IsInteger(left) ? ExtendsResult.True : ExtendsResult.False;
2439
+ }
2440
+ function FromNumber(left, right) {
2441
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsInteger(right) || IsNumber(right) ? ExtendsResult.True : ExtendsResult.False;
2442
+ }
2443
+ function IsObjectPropertyCount(schema, count) {
2444
+ return Object.getOwnPropertyNames(schema.properties).length === count;
2445
+ }
2446
+ function IsObjectStringLike(schema) {
2447
+ return IsObjectArrayLike(schema);
2448
+ }
2449
+ function IsObjectSymbolLike(schema) {
2450
+ return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "description" in schema.properties && IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && (IsString(schema.properties.description.anyOf[0]) && IsUndefined(schema.properties.description.anyOf[1]) || IsString(schema.properties.description.anyOf[1]) && IsUndefined(schema.properties.description.anyOf[0]));
2451
+ }
2452
+ function IsObjectNumberLike(schema) {
2453
+ return IsObjectPropertyCount(schema, 0);
2454
+ }
2455
+ function IsObjectBooleanLike(schema) {
2456
+ return IsObjectPropertyCount(schema, 0);
2457
+ }
2458
+ function IsObjectBigIntLike(schema) {
2459
+ return IsObjectPropertyCount(schema, 0);
2460
+ }
2461
+ function IsObjectDateLike(schema) {
2462
+ return IsObjectPropertyCount(schema, 0);
2463
+ }
2464
+ function IsObjectUint8ArrayLike(schema) {
2465
+ return IsObjectArrayLike(schema);
2466
+ }
2467
+ function IsObjectFunctionLike(schema) {
2468
+ const length = Number$1();
2469
+ return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "length" in schema.properties && IntoBooleanResult(Visit(schema.properties["length"], length)) === ExtendsResult.True;
2470
+ }
2471
+ function IsObjectConstructorLike(schema) {
2472
+ return IsObjectPropertyCount(schema, 0);
2473
+ }
2474
+ function IsObjectArrayLike(schema) {
2475
+ const length = Number$1();
2476
+ return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "length" in schema.properties && IntoBooleanResult(Visit(schema.properties["length"], length)) === ExtendsResult.True;
2477
+ }
2478
+ function IsObjectPromiseLike(schema) {
2479
+ const then = Function([Any()], Any());
2480
+ return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "then" in schema.properties && IntoBooleanResult(Visit(schema.properties["then"], then)) === ExtendsResult.True;
2481
+ }
2482
+ function Property(left, right) {
2483
+ return Visit(left, right) === ExtendsResult.False ? ExtendsResult.False : IsOptional(left) && !IsOptional(right) ? ExtendsResult.False : ExtendsResult.True;
2484
+ }
2485
+ function FromObjectRight(left, right) {
2486
+ return IsUnknown(left) ? ExtendsResult.False : IsAny(left) ? ExtendsResult.Union : IsNever(left) || IsLiteralString(left) && IsObjectStringLike(right) || IsLiteralNumber(left) && IsObjectNumberLike(right) || IsLiteralBoolean(left) && IsObjectBooleanLike(right) || IsSymbol(left) && IsObjectSymbolLike(right) || IsBigInt(left) && IsObjectBigIntLike(right) || IsString(left) && IsObjectStringLike(right) || IsSymbol(left) && IsObjectSymbolLike(right) || IsNumber(left) && IsObjectNumberLike(right) || IsInteger(left) && IsObjectNumberLike(right) || IsBoolean(left) && IsObjectBooleanLike(right) || IsUint8Array(left) && IsObjectUint8ArrayLike(right) || IsDate(left) && IsObjectDateLike(right) || IsConstructor(left) && IsObjectConstructorLike(right) || IsFunction(left) && IsObjectFunctionLike(right) ? ExtendsResult.True : IsRecord(left) && IsString(RecordKey$1(left)) ? right[Hint] === "Record" ? ExtendsResult.True : ExtendsResult.False : IsRecord(left) && IsNumber(RecordKey$1(left)) ? IsObjectPropertyCount(right, 0) ? ExtendsResult.True : ExtendsResult.False : ExtendsResult.False;
2487
+ }
2488
+ function FromObject$6(left, right) {
2489
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : !IsObject(right) ? ExtendsResult.False : (() => {
2490
+ for (const key of Object.getOwnPropertyNames(right.properties)) {
2491
+ if (!(key in left.properties) && !IsOptional(right.properties[key])) return ExtendsResult.False;
2492
+ if (IsOptional(right.properties[key])) return ExtendsResult.True;
2493
+ if (Property(left.properties[key], right.properties[key]) === ExtendsResult.False) return ExtendsResult.False;
2494
+ }
2495
+ return ExtendsResult.True;
2496
+ })();
2497
+ }
2498
+ function FromPromise$1(left, right) {
2499
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) && IsObjectPromiseLike(right) ? ExtendsResult.True : !IsPromise(right) ? ExtendsResult.False : IntoBooleanResult(Visit(left.item, right.item));
2500
+ }
2501
+ function RecordKey$1(schema) {
2502
+ return PatternNumberExact in schema.patternProperties ? Number$1() : PatternStringExact in schema.patternProperties ? String$1() : Throw("Unknown record key pattern");
2503
+ }
2504
+ function RecordValue$1(schema) {
2505
+ return PatternNumberExact in schema.patternProperties ? schema.patternProperties[PatternNumberExact] : PatternStringExact in schema.patternProperties ? schema.patternProperties[PatternStringExact] : Throw("Unable to get record value schema");
2506
+ }
2507
+ function FromRecordRight(left, right) {
2508
+ const [Key, Value] = [RecordKey$1(right), RecordValue$1(right)];
2509
+ return IsLiteralString(left) && IsNumber(Key) && IntoBooleanResult(Visit(left, Value)) === ExtendsResult.True ? ExtendsResult.True : IsUint8Array(left) && IsNumber(Key) ? Visit(left, Value) : IsString(left) && IsNumber(Key) ? Visit(left, Value) : IsArray(left) && IsNumber(Key) ? Visit(left, Value) : IsObject(left) ? (() => {
2510
+ for (const key of Object.getOwnPropertyNames(left.properties)) if (Property(Value, left.properties[key]) === ExtendsResult.False) return ExtendsResult.False;
2511
+ return ExtendsResult.True;
2512
+ })() : ExtendsResult.False;
2513
+ }
2514
+ function FromRecord$2(left, right) {
2515
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : !IsRecord(right) ? ExtendsResult.False : Visit(RecordValue$1(left), RecordValue$1(right));
2516
+ }
2517
+ function FromRegExp(left, right) {
2518
+ return Visit(IsRegExp(left) ? String$1() : left, IsRegExp(right) ? String$1() : right);
2519
+ }
2520
+ function FromStringRight(left, right) {
2521
+ return IsLiteral(left) && IsString$2(left.const) ? ExtendsResult.True : IsString(left) ? ExtendsResult.True : ExtendsResult.False;
2522
+ }
2523
+ function FromString(left, right) {
2524
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsString(right) ? ExtendsResult.True : ExtendsResult.False;
2525
+ }
2526
+ function FromSymbol(left, right) {
2527
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsSymbol(right) ? ExtendsResult.True : ExtendsResult.False;
2528
+ }
2529
+ function FromTemplateLiteral$1(left, right) {
2530
+ return IsTemplateLiteral(left) ? Visit(TemplateLiteralToUnion(left), right) : IsTemplateLiteral(right) ? Visit(left, TemplateLiteralToUnion(right)) : Throw("Invalid fallthrough for TemplateLiteral");
2531
+ }
2532
+ function IsArrayOfTuple(left, right) {
2533
+ return IsArray(right) && left.items !== void 0 && left.items.every((schema) => Visit(schema, right.items) === ExtendsResult.True);
2534
+ }
2535
+ function FromTupleRight(left, right) {
2536
+ return IsNever(left) ? ExtendsResult.True : IsUnknown(left) ? ExtendsResult.False : IsAny(left) ? ExtendsResult.Union : ExtendsResult.False;
2537
+ }
2538
+ function FromTuple$2(left, right) {
2539
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True : IsArray(right) && IsArrayOfTuple(left, right) ? ExtendsResult.True : !IsTuple(right) ? ExtendsResult.False : IsUndefined$3(left.items) && !IsUndefined$3(right.items) || !IsUndefined$3(left.items) && IsUndefined$3(right.items) ? ExtendsResult.False : IsUndefined$3(left.items) && !IsUndefined$3(right.items) ? ExtendsResult.True : left.items.every((schema, index) => Visit(schema, right.items[index]) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2540
+ }
2541
+ function FromUint8Array(left, right) {
2542
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsUint8Array(right) ? ExtendsResult.True : ExtendsResult.False;
2543
+ }
2544
+ function FromUndefined(left, right) {
2545
+ return IsStructuralRight(right) ? StructuralRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsRecord(right) ? FromRecordRight(left, right) : IsVoid(right) ? FromVoidRight(left, right) : IsUndefined(right) ? ExtendsResult.True : ExtendsResult.False;
2546
+ }
2547
+ function FromUnionRight(left, right) {
2548
+ return right.anyOf.some((schema) => Visit(left, schema) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2549
+ }
2550
+ function FromUnion$4(left, right) {
2551
+ return left.anyOf.every((schema) => Visit(schema, right) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2552
+ }
2553
+ function FromUnknownRight(left, right) {
2554
+ return ExtendsResult.True;
2555
+ }
2556
+ function FromUnknown(left, right) {
2557
+ return IsNever(right) ? FromNeverRight(left, right) : IsIntersect(right) ? FromIntersectRight(left, right) : IsUnion(right) ? FromUnionRight(left, right) : IsAny(right) ? FromAnyRight(left, right) : IsString(right) ? FromStringRight(left, right) : IsNumber(right) ? FromNumberRight(left, right) : IsInteger(right) ? FromIntegerRight(left, right) : IsBoolean(right) ? FromBooleanRight(left, right) : IsArray(right) ? FromArrayRight(left, right) : IsTuple(right) ? FromTupleRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsUnknown(right) ? ExtendsResult.True : ExtendsResult.False;
2558
+ }
2559
+ function FromVoidRight(left, right) {
2560
+ return IsUndefined(left) ? ExtendsResult.True : IsUndefined(left) ? ExtendsResult.True : ExtendsResult.False;
2561
+ }
2562
+ function FromVoid(left, right) {
2563
+ return IsIntersect(right) ? FromIntersectRight(left, right) : IsUnion(right) ? FromUnionRight(left, right) : IsUnknown(right) ? FromUnknownRight(left, right) : IsAny(right) ? FromAnyRight(left, right) : IsObject(right) ? FromObjectRight(left, right) : IsVoid(right) ? ExtendsResult.True : ExtendsResult.False;
2564
+ }
2565
+ function Visit(left, right) {
2566
+ return IsTemplateLiteral(left) || IsTemplateLiteral(right) ? FromTemplateLiteral$1(left, right) : IsRegExp(left) || IsRegExp(right) ? FromRegExp(left, right) : IsNot(left) || IsNot(right) ? FromNot(left, right) : IsAny(left) ? FromAny(left, right) : IsArray(left) ? FromArray$2(left, right) : IsBigInt(left) ? FromBigInt(left, right) : IsBoolean(left) ? FromBoolean(left, right) : IsAsyncIterator(left) ? FromAsyncIterator$2(left, right) : IsConstructor(left) ? FromConstructor$2(left, right) : IsDate(left) ? FromDate(left, right) : IsFunction(left) ? FromFunction$2(left, right) : IsInteger(left) ? FromInteger(left, right) : IsIntersect(left) ? FromIntersect$4(left, right) : IsIterator(left) ? FromIterator$2(left, right) : IsLiteral(left) ? FromLiteral(left, right) : IsNever(left) ? FromNever(left, right) : IsNull(left) ? FromNull(left, right) : IsNumber(left) ? FromNumber(left, right) : IsObject(left) ? FromObject$6(left, right) : IsRecord(left) ? FromRecord$2(left, right) : IsString(left) ? FromString(left, right) : IsSymbol(left) ? FromSymbol(left, right) : IsTuple(left) ? FromTuple$2(left, right) : IsPromise(left) ? FromPromise$1(left, right) : IsUint8Array(left) ? FromUint8Array(left, right) : IsUndefined(left) ? FromUndefined(left, right) : IsUnion(left) ? FromUnion$4(left, right) : IsUnknown(left) ? FromUnknown(left, right) : IsVoid(left) ? FromVoid(left, right) : Throw(`Unknown left type operand '${left[Kind]}'`);
2567
+ }
2568
+ function ExtendsCheck(left, right) {
2569
+ return Visit(left, right);
2570
+ }
2571
+ //#endregion
2572
+ //#region node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-result.mjs
2573
+ function FromProperties$11(P, Right, True, False, options) {
2574
+ const Acc = {};
2575
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P)) Acc[K2] = Extends(P[K2], Right, True, False, Clone(options));
2576
+ return Acc;
2577
+ }
2578
+ function FromMappedResult$6(Left, Right, True, False, options) {
2579
+ return FromProperties$11(Left.properties, Right, True, False, options);
2580
+ }
2581
+ function ExtendsFromMappedResult(Left, Right, True, False, options) {
2582
+ return MappedResult(FromMappedResult$6(Left, Right, True, False, options));
2583
+ }
2584
+ //#endregion
2585
+ //#region node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs
2586
+ function ExtendsResolve(left, right, trueType, falseType) {
2587
+ const R = ExtendsCheck(left, right);
2588
+ return R === ExtendsResult.Union ? Union([trueType, falseType]) : R === ExtendsResult.True ? trueType : falseType;
2589
+ }
2590
+ /** `[Json]` Creates a Conditional type */
2591
+ function Extends(L, R, T, F, options) {
2592
+ return IsMappedResult$1(L) ? ExtendsFromMappedResult(L, R, T, F, options) : IsMappedKey$1(L) ? CreateType(ExtendsFromMappedKey(L, R, T, F, options)) : CreateType(ExtendsResolve(L, R, T, F), options);
2593
+ }
2594
+ //#endregion
2595
+ //#region node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs
2596
+ function FromPropertyKey$2(K, U, L, R, options) {
2597
+ return { [K]: Extends(Literal(K), U, L, R, Clone(options)) };
2598
+ }
2599
+ function FromPropertyKeys$2(K, U, L, R, options) {
2600
+ return K.reduce((Acc, LK) => {
2601
+ return {
2602
+ ...Acc,
2603
+ ...FromPropertyKey$2(LK, U, L, R, options)
2604
+ };
2605
+ }, {});
2606
+ }
2607
+ function FromMappedKey$2(K, U, L, R, options) {
2608
+ return FromPropertyKeys$2(K.keys, U, L, R, options);
2609
+ }
2610
+ function ExtendsFromMappedKey(T, U, L, R, options) {
2611
+ return MappedResult(FromMappedKey$2(T, U, L, R, options));
2612
+ }
2613
+ //#endregion
2614
+ //#region node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-template-literal.mjs
2615
+ function ExcludeFromTemplateLiteral(L, R) {
2616
+ return Exclude(TemplateLiteralToUnion(L), R);
2617
+ }
2618
+ //#endregion
2619
+ //#region node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs
2620
+ function ExcludeRest(L, R) {
2621
+ const excluded = L.filter((inner) => ExtendsCheck(inner, R) === ExtendsResult.False);
2622
+ return excluded.length === 1 ? excluded[0] : Union(excluded);
2623
+ }
2624
+ /** `[Json]` Constructs a type by excluding from unionType all union members that are assignable to excludedMembers */
2625
+ function Exclude(L, R, options = {}) {
2626
+ if (IsTemplateLiteral$1(L)) return CreateType(ExcludeFromTemplateLiteral(L, R), options);
2627
+ if (IsMappedResult$1(L)) return CreateType(ExcludeFromMappedResult(L, R), options);
2628
+ return CreateType(IsUnion$1(L) ? ExcludeRest(L.anyOf, R) : ExtendsCheck(L, R) !== ExtendsResult.False ? Never() : L, options);
2629
+ }
2630
+ //#endregion
2631
+ //#region node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs
2632
+ function FromProperties$10(P, U) {
2633
+ const Acc = {};
2634
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P)) Acc[K2] = Exclude(P[K2], U);
2635
+ return Acc;
2636
+ }
2637
+ function FromMappedResult$5(R, T) {
2638
+ return FromProperties$10(R.properties, T);
2639
+ }
2640
+ function ExcludeFromMappedResult(R, T) {
2641
+ return MappedResult(FromMappedResult$5(R, T));
2642
+ }
2643
+ //#endregion
2644
+ //#region node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-template-literal.mjs
2645
+ function ExtractFromTemplateLiteral(L, R) {
2646
+ return Extract(TemplateLiteralToUnion(L), R);
2647
+ }
2648
+ //#endregion
2649
+ //#region node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs
2650
+ function ExtractRest(L, R) {
2651
+ const extracted = L.filter((inner) => ExtendsCheck(inner, R) !== ExtendsResult.False);
2652
+ return extracted.length === 1 ? extracted[0] : Union(extracted);
2653
+ }
2654
+ /** `[Json]` Constructs a type by extracting from type all union members that are assignable to union */
2655
+ function Extract(L, R, options) {
2656
+ if (IsTemplateLiteral$1(L)) return CreateType(ExtractFromTemplateLiteral(L, R), options);
2657
+ if (IsMappedResult$1(L)) return CreateType(ExtractFromMappedResult(L, R), options);
2658
+ return CreateType(IsUnion$1(L) ? ExtractRest(L.anyOf, R) : ExtendsCheck(L, R) !== ExtendsResult.False ? L : Never(), options);
2659
+ }
2660
+ //#endregion
2661
+ //#region node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs
2662
+ function FromProperties$9(P, T) {
2663
+ const Acc = {};
2664
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P)) Acc[K2] = Extract(P[K2], T);
2665
+ return Acc;
2666
+ }
2667
+ function FromMappedResult$4(R, T) {
2668
+ return FromProperties$9(R.properties, T);
2669
+ }
2670
+ function ExtractFromMappedResult(R, T) {
2671
+ return MappedResult(FromMappedResult$4(R, T));
2672
+ }
2673
+ //#endregion
2674
+ //#region node_modules/@sinclair/typebox/build/esm/type/instance-type/instance-type.mjs
2675
+ /** `[JavaScript]` Extracts the InstanceType from the given Constructor type */
2676
+ function InstanceType(schema, options) {
2677
+ return IsConstructor$1(schema) ? CreateType(schema.returns, options) : Never(options);
2678
+ }
2679
+ //#endregion
2680
+ //#region node_modules/@sinclair/typebox/build/esm/type/readonly-optional/readonly-optional.mjs
2681
+ /** `[Json]` Creates a Readonly and Optional property */
2682
+ function ReadonlyOptional(schema) {
2683
+ return Readonly(Optional(schema));
2684
+ }
2685
+ //#endregion
2686
+ //#region node_modules/@sinclair/typebox/build/esm/type/record/record.mjs
2687
+ function RecordCreateFromPattern(pattern, T, options) {
2688
+ return CreateType({
2689
+ [Kind]: "Record",
2690
+ type: "object",
2691
+ patternProperties: { [pattern]: T }
2692
+ }, options);
2693
+ }
2694
+ function RecordCreateFromKeys(K, T, options) {
2695
+ const result = {};
2696
+ for (const K2 of K) result[K2] = T;
2697
+ return Object$1(result, {
2698
+ ...options,
2699
+ [Hint]: "Record"
2700
+ });
2701
+ }
2702
+ function FromTemplateLiteralKey(K, T, options) {
2703
+ return IsTemplateLiteralFinite(K) ? RecordCreateFromKeys(IndexPropertyKeys(K), T, options) : RecordCreateFromPattern(K.pattern, T, options);
2704
+ }
2705
+ function FromUnionKey(key, type, options) {
2706
+ return RecordCreateFromKeys(IndexPropertyKeys(Union(key)), type, options);
2707
+ }
2708
+ function FromLiteralKey(key, type, options) {
2709
+ return RecordCreateFromKeys([key.toString()], type, options);
2710
+ }
2711
+ function FromRegExpKey(key, type, options) {
2712
+ return RecordCreateFromPattern(key.source, type, options);
2713
+ }
2714
+ function FromStringKey(key, type, options) {
2715
+ return RecordCreateFromPattern(IsUndefined$3(key.pattern) ? PatternStringExact : key.pattern, type, options);
2716
+ }
2717
+ function FromAnyKey(_, type, options) {
2718
+ return RecordCreateFromPattern(PatternStringExact, type, options);
2719
+ }
2720
+ function FromNeverKey(_key, type, options) {
2721
+ return RecordCreateFromPattern(PatternNeverExact, type, options);
2722
+ }
2723
+ function FromBooleanKey(_key, type, options) {
2724
+ return Object$1({
2725
+ true: type,
2726
+ false: type
2727
+ }, options);
2728
+ }
2729
+ function FromIntegerKey(_key, type, options) {
2730
+ return RecordCreateFromPattern(PatternNumberExact, type, options);
2731
+ }
2732
+ function FromNumberKey(_, type, options) {
2733
+ return RecordCreateFromPattern(PatternNumberExact, type, options);
2734
+ }
2735
+ /** `[Json]` Creates a Record type */
2736
+ function Record(key, type, options = {}) {
2737
+ return IsUnion$1(key) ? FromUnionKey(key.anyOf, type, options) : IsTemplateLiteral$1(key) ? FromTemplateLiteralKey(key, type, options) : IsLiteral$1(key) ? FromLiteralKey(key.const, type, options) : IsBoolean$1(key) ? FromBooleanKey(key, type, options) : IsInteger$1(key) ? FromIntegerKey(key, type, options) : IsNumber$1(key) ? FromNumberKey(key, type, options) : IsRegExp$1(key) ? FromRegExpKey(key, type, options) : IsString$1(key) ? FromStringKey(key, type, options) : IsAny$1(key) ? FromAnyKey(key, type, options) : IsNever$1(key) ? FromNeverKey(key, type, options) : Never(options);
2738
+ }
2739
+ /** Gets the Records Pattern */
2740
+ function RecordPattern(record) {
2741
+ return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0];
2742
+ }
2743
+ /** Gets the Records Key Type */
2744
+ function RecordKey(type) {
2745
+ const pattern = RecordPattern(type);
2746
+ return pattern === PatternStringExact ? String$1() : pattern === PatternNumberExact ? Number$1() : String$1({ pattern });
2747
+ }
2748
+ /** Gets a Record Value Type */
2749
+ function RecordValue(type) {
2750
+ return type.patternProperties[RecordPattern(type)];
2751
+ }
2752
+ //#endregion
2753
+ //#region node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs
2754
+ function FromConstructor$1(args, type) {
2755
+ type.parameters = FromTypes$1(args, type.parameters);
2756
+ type.returns = FromType$1(args, type.returns);
2757
+ return type;
2758
+ }
2759
+ function FromFunction$1(args, type) {
2760
+ type.parameters = FromTypes$1(args, type.parameters);
2761
+ type.returns = FromType$1(args, type.returns);
2762
+ return type;
2763
+ }
2764
+ function FromIntersect$3(args, type) {
2765
+ type.allOf = FromTypes$1(args, type.allOf);
2766
+ return type;
2767
+ }
2768
+ function FromUnion$3(args, type) {
2769
+ type.anyOf = FromTypes$1(args, type.anyOf);
2770
+ return type;
2771
+ }
2772
+ function FromTuple$1(args, type) {
2773
+ if (IsUndefined$3(type.items)) return type;
2774
+ type.items = FromTypes$1(args, type.items);
2775
+ return type;
2776
+ }
2777
+ function FromArray$1(args, type) {
2778
+ type.items = FromType$1(args, type.items);
2779
+ return type;
2780
+ }
2781
+ function FromAsyncIterator$1(args, type) {
2782
+ type.items = FromType$1(args, type.items);
2783
+ return type;
2784
+ }
2785
+ function FromIterator$1(args, type) {
2786
+ type.items = FromType$1(args, type.items);
2787
+ return type;
2788
+ }
2789
+ function FromPromise(args, type) {
2790
+ type.item = FromType$1(args, type.item);
2791
+ return type;
2792
+ }
2793
+ function FromObject$5(args, type) {
2794
+ const mappedProperties = FromProperties$8(args, type.properties);
2795
+ return {
2796
+ ...type,
2797
+ ...Object$1(mappedProperties)
2798
+ };
2799
+ }
2800
+ function FromRecord$1(args, type) {
2801
+ const result = Record(FromType$1(args, RecordKey(type)), FromType$1(args, RecordValue(type)));
2802
+ return {
2803
+ ...type,
2804
+ ...result
2805
+ };
2806
+ }
2807
+ function FromArgument(args, argument) {
2808
+ return argument.index in args ? args[argument.index] : Unknown();
2809
+ }
2810
+ function FromProperty$1(args, type) {
2811
+ const isReadonly = IsReadonly(type);
2812
+ const isOptional = IsOptional$1(type);
2813
+ const mapped = FromType$1(args, type);
2814
+ return isReadonly && isOptional ? ReadonlyOptional(mapped) : isReadonly && !isOptional ? Readonly(mapped) : !isReadonly && isOptional ? Optional(mapped) : mapped;
2815
+ }
2816
+ function FromProperties$8(args, properties) {
2817
+ return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => {
2818
+ return {
2819
+ ...result,
2820
+ [key]: FromProperty$1(args, properties[key])
2821
+ };
2822
+ }, {});
2823
+ }
2824
+ function FromTypes$1(args, types) {
2825
+ return types.map((type) => FromType$1(args, type));
2826
+ }
2827
+ function FromType$1(args, type) {
2828
+ return IsConstructor$1(type) ? FromConstructor$1(args, type) : IsFunction$1(type) ? FromFunction$1(args, type) : IsIntersect$1(type) ? FromIntersect$3(args, type) : IsUnion$1(type) ? FromUnion$3(args, type) : IsTuple$1(type) ? FromTuple$1(args, type) : IsArray$1(type) ? FromArray$1(args, type) : IsAsyncIterator$1(type) ? FromAsyncIterator$1(args, type) : IsIterator$1(type) ? FromIterator$1(args, type) : IsPromise$1(type) ? FromPromise(args, type) : IsObject$1(type) ? FromObject$5(args, type) : IsRecord$1(type) ? FromRecord$1(args, type) : IsArgument$1(type) ? FromArgument(args, type) : type;
2829
+ }
2830
+ /** `[JavaScript]` Instantiates a type with the given parameters */
2831
+ function Instantiate(type, args) {
2832
+ return FromType$1(args, CloneType(type));
2833
+ }
2834
+ //#endregion
2835
+ //#region node_modules/@sinclair/typebox/build/esm/type/integer/integer.mjs
2836
+ /** `[Json]` Creates an Integer type */
2837
+ function Integer(options) {
2838
+ return CreateType({
2839
+ [Kind]: "Integer",
2840
+ type: "integer"
2841
+ }, options);
2842
+ }
2843
+ //#endregion
2844
+ //#region node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic-from-mapped-key.mjs
2845
+ function MappedIntrinsicPropertyKey(K, M, options) {
2846
+ return { [K]: Intrinsic(Literal(K), M, Clone(options)) };
2847
+ }
2848
+ function MappedIntrinsicPropertyKeys(K, M, options) {
2849
+ return K.reduce((Acc, L) => {
2850
+ return {
2851
+ ...Acc,
2852
+ ...MappedIntrinsicPropertyKey(L, M, options)
2853
+ };
2854
+ }, {});
2855
+ }
2856
+ function MappedIntrinsicProperties(T, M, options) {
2857
+ return MappedIntrinsicPropertyKeys(T["keys"], M, options);
2858
+ }
2859
+ function IntrinsicFromMappedKey(T, M, options) {
2860
+ return MappedResult(MappedIntrinsicProperties(T, M, options));
2861
+ }
2862
+ //#endregion
2863
+ //#region node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs
2864
+ function ApplyUncapitalize(value) {
2865
+ const [first, rest] = [value.slice(0, 1), value.slice(1)];
2866
+ return [first.toLowerCase(), rest].join("");
2867
+ }
2868
+ function ApplyCapitalize(value) {
2869
+ const [first, rest] = [value.slice(0, 1), value.slice(1)];
2870
+ return [first.toUpperCase(), rest].join("");
2871
+ }
2872
+ function ApplyUppercase(value) {
2873
+ return value.toUpperCase();
2874
+ }
2875
+ function ApplyLowercase(value) {
2876
+ return value.toLowerCase();
2877
+ }
2878
+ function FromTemplateLiteral(schema, mode, options) {
2879
+ const expression = TemplateLiteralParseExact(schema.pattern);
2880
+ if (!IsTemplateLiteralExpressionFinite(expression)) return {
2881
+ ...schema,
2882
+ pattern: FromLiteralValue(schema.pattern, mode)
2883
+ };
2884
+ return TemplateLiteral([Union(FromRest$2([...TemplateLiteralExpressionGenerate(expression)].map((value) => Literal(value)), mode))], options);
2885
+ }
2886
+ function FromLiteralValue(value, mode) {
2887
+ return typeof value === "string" ? mode === "Uncapitalize" ? ApplyUncapitalize(value) : mode === "Capitalize" ? ApplyCapitalize(value) : mode === "Uppercase" ? ApplyUppercase(value) : mode === "Lowercase" ? ApplyLowercase(value) : value : value.toString();
2888
+ }
2889
+ function FromRest$2(T, M) {
2890
+ return T.map((L) => Intrinsic(L, M));
2891
+ }
2892
+ /** Applies an intrinsic string manipulation to the given type. */
2893
+ function Intrinsic(schema, mode, options = {}) {
2894
+ return IsMappedKey$1(schema) ? IntrinsicFromMappedKey(schema, mode, options) : IsTemplateLiteral$1(schema) ? FromTemplateLiteral(schema, mode, options) : IsUnion$1(schema) ? Union(FromRest$2(schema.anyOf, mode), options) : IsLiteral$1(schema) ? Literal(FromLiteralValue(schema.const, mode), options) : CreateType(schema, options);
2895
+ }
2896
+ //#endregion
2897
+ //#region node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs
2898
+ /** `[Json]` Intrinsic function to Capitalize LiteralString types */
2899
+ function Capitalize(T, options = {}) {
2900
+ return Intrinsic(T, "Capitalize", options);
2901
+ }
2902
+ //#endregion
2903
+ //#region node_modules/@sinclair/typebox/build/esm/type/intrinsic/lowercase.mjs
2904
+ /** `[Json]` Intrinsic function to Lowercase LiteralString types */
2905
+ function Lowercase(T, options = {}) {
2906
+ return Intrinsic(T, "Lowercase", options);
2907
+ }
2908
+ //#endregion
2909
+ //#region node_modules/@sinclair/typebox/build/esm/type/intrinsic/uncapitalize.mjs
2910
+ /** `[Json]` Intrinsic function to Uncapitalize LiteralString types */
2911
+ function Uncapitalize(T, options = {}) {
2912
+ return Intrinsic(T, "Uncapitalize", options);
2913
+ }
2914
+ //#endregion
2915
+ //#region node_modules/@sinclair/typebox/build/esm/type/intrinsic/uppercase.mjs
2916
+ /** `[Json]` Intrinsic function to Uppercase LiteralString types */
2917
+ function Uppercase(T, options = {}) {
2918
+ return Intrinsic(T, "Uppercase", options);
2919
+ }
2920
+ //#endregion
2921
+ //#region node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-result.mjs
2922
+ function FromProperties$7(properties, propertyKeys, options) {
2923
+ const result = {};
2924
+ for (const K2 of globalThis.Object.getOwnPropertyNames(properties)) result[K2] = Omit(properties[K2], propertyKeys, Clone(options));
2925
+ return result;
2926
+ }
2927
+ function FromMappedResult$3(mappedResult, propertyKeys, options) {
2928
+ return FromProperties$7(mappedResult.properties, propertyKeys, options);
2929
+ }
2930
+ function OmitFromMappedResult(mappedResult, propertyKeys, options) {
2931
+ return MappedResult(FromMappedResult$3(mappedResult, propertyKeys, options));
2932
+ }
2933
+ //#endregion
2934
+ //#region node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs
2935
+ function FromIntersect$2(types, propertyKeys) {
2936
+ return types.map((type) => OmitResolve(type, propertyKeys));
2937
+ }
2938
+ function FromUnion$2(types, propertyKeys) {
2939
+ return types.map((type) => OmitResolve(type, propertyKeys));
2940
+ }
2941
+ function FromProperty(properties, key) {
2942
+ const { [key]: _, ...R } = properties;
2943
+ return R;
2944
+ }
2945
+ function FromProperties$6(properties, propertyKeys) {
2946
+ return propertyKeys.reduce((T, K2) => FromProperty(T, K2), properties);
2947
+ }
2948
+ function FromObject$4(type, propertyKeys, properties) {
2949
+ const options = Discard(type, [
2950
+ TransformKind,
2951
+ "$id",
2952
+ "required",
2953
+ "properties"
2954
+ ]);
2955
+ return Object$1(FromProperties$6(properties, propertyKeys), options);
2956
+ }
2957
+ function UnionFromPropertyKeys$1(propertyKeys) {
2958
+ return Union(propertyKeys.reduce((result, key) => IsLiteralValue$1(key) ? [...result, Literal(key)] : result, []));
2959
+ }
2960
+ function OmitResolve(type, propertyKeys) {
2961
+ return IsIntersect$1(type) ? Intersect(FromIntersect$2(type.allOf, propertyKeys)) : IsUnion$1(type) ? Union(FromUnion$2(type.anyOf, propertyKeys)) : IsObject$1(type) ? FromObject$4(type, propertyKeys, type.properties) : Object$1({});
2962
+ }
2963
+ /** `[Json]` Constructs a type whose keys are picked from the given type */
2964
+ function Omit(type, key, options) {
2965
+ const typeKey = IsArray$3(key) ? UnionFromPropertyKeys$1(key) : key;
2966
+ const propertyKeys = IsSchema$1(key) ? IndexPropertyKeys(key) : key;
2967
+ const isTypeRef = IsRef$1(type);
2968
+ const isKeyRef = IsRef$1(key);
2969
+ return IsMappedResult$1(type) ? OmitFromMappedResult(type, propertyKeys, options) : IsMappedKey$1(key) ? OmitFromMappedKey(type, key, options) : isTypeRef && isKeyRef ? Computed("Omit", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed("Omit", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed("Omit", [type, typeKey], options) : CreateType({
2970
+ ...OmitResolve(type, propertyKeys),
2971
+ ...options
2972
+ });
2973
+ }
2974
+ //#endregion
2975
+ //#region node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs
2976
+ function FromPropertyKey$1(type, key, options) {
2977
+ return { [key]: Omit(type, [key], Clone(options)) };
2978
+ }
2979
+ function FromPropertyKeys$1(type, propertyKeys, options) {
2980
+ return propertyKeys.reduce((Acc, LK) => {
2981
+ return {
2982
+ ...Acc,
2983
+ ...FromPropertyKey$1(type, LK, options)
2984
+ };
2985
+ }, {});
2986
+ }
2987
+ function FromMappedKey$1(type, mappedKey, options) {
2988
+ return FromPropertyKeys$1(type, mappedKey.keys, options);
2989
+ }
2990
+ function OmitFromMappedKey(type, mappedKey, options) {
2991
+ return MappedResult(FromMappedKey$1(type, mappedKey, options));
2992
+ }
2993
+ //#endregion
2994
+ //#region node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-result.mjs
2995
+ function FromProperties$5(properties, propertyKeys, options) {
2996
+ const result = {};
2997
+ for (const K2 of globalThis.Object.getOwnPropertyNames(properties)) result[K2] = Pick(properties[K2], propertyKeys, Clone(options));
2998
+ return result;
2999
+ }
3000
+ function FromMappedResult$2(mappedResult, propertyKeys, options) {
3001
+ return FromProperties$5(mappedResult.properties, propertyKeys, options);
3002
+ }
3003
+ function PickFromMappedResult(mappedResult, propertyKeys, options) {
3004
+ return MappedResult(FromMappedResult$2(mappedResult, propertyKeys, options));
3005
+ }
3006
+ //#endregion
3007
+ //#region node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs
3008
+ function FromIntersect$1(types, propertyKeys) {
3009
+ return types.map((type) => PickResolve(type, propertyKeys));
3010
+ }
3011
+ function FromUnion$1(types, propertyKeys) {
3012
+ return types.map((type) => PickResolve(type, propertyKeys));
3013
+ }
3014
+ function FromProperties$4(properties, propertyKeys) {
3015
+ const result = {};
3016
+ for (const K2 of propertyKeys) if (K2 in properties) result[K2] = properties[K2];
3017
+ return result;
3018
+ }
3019
+ function FromObject$3(Type, keys, properties) {
3020
+ const options = Discard(Type, [
3021
+ TransformKind,
3022
+ "$id",
3023
+ "required",
3024
+ "properties"
3025
+ ]);
3026
+ return Object$1(FromProperties$4(properties, keys), options);
3027
+ }
3028
+ function UnionFromPropertyKeys(propertyKeys) {
3029
+ return Union(propertyKeys.reduce((result, key) => IsLiteralValue$1(key) ? [...result, Literal(key)] : result, []));
3030
+ }
3031
+ function PickResolve(type, propertyKeys) {
3032
+ return IsIntersect$1(type) ? Intersect(FromIntersect$1(type.allOf, propertyKeys)) : IsUnion$1(type) ? Union(FromUnion$1(type.anyOf, propertyKeys)) : IsObject$1(type) ? FromObject$3(type, propertyKeys, type.properties) : Object$1({});
3033
+ }
3034
+ /** `[Json]` Constructs a type whose keys are picked from the given type */
3035
+ function Pick(type, key, options) {
3036
+ const typeKey = IsArray$3(key) ? UnionFromPropertyKeys(key) : key;
3037
+ const propertyKeys = IsSchema$1(key) ? IndexPropertyKeys(key) : key;
3038
+ const isTypeRef = IsRef$1(type);
3039
+ const isKeyRef = IsRef$1(key);
3040
+ return IsMappedResult$1(type) ? PickFromMappedResult(type, propertyKeys, options) : IsMappedKey$1(key) ? PickFromMappedKey(type, key, options) : isTypeRef && isKeyRef ? Computed("Pick", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed("Pick", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed("Pick", [type, typeKey], options) : CreateType({
3041
+ ...PickResolve(type, propertyKeys),
3042
+ ...options
3043
+ });
3044
+ }
3045
+ //#endregion
3046
+ //#region node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs
3047
+ function FromPropertyKey(type, key, options) {
3048
+ return { [key]: Pick(type, [key], Clone(options)) };
3049
+ }
3050
+ function FromPropertyKeys(type, propertyKeys, options) {
3051
+ return propertyKeys.reduce((result, leftKey) => {
3052
+ return {
3053
+ ...result,
3054
+ ...FromPropertyKey(type, leftKey, options)
3055
+ };
3056
+ }, {});
3057
+ }
3058
+ function FromMappedKey(type, mappedKey, options) {
3059
+ return FromPropertyKeys(type, mappedKey.keys, options);
3060
+ }
3061
+ function PickFromMappedKey(type, mappedKey, options) {
3062
+ return MappedResult(FromMappedKey(type, mappedKey, options));
3063
+ }
3064
+ //#endregion
3065
+ //#region node_modules/@sinclair/typebox/build/esm/type/partial/partial.mjs
3066
+ function FromComputed$2(target, parameters) {
3067
+ return Computed("Partial", [Computed(target, parameters)]);
3068
+ }
3069
+ function FromRef$1($ref) {
3070
+ return Computed("Partial", [Ref($ref)]);
3071
+ }
3072
+ function FromProperties$3(properties) {
3073
+ const partialProperties = {};
3074
+ for (const K of globalThis.Object.getOwnPropertyNames(properties)) partialProperties[K] = Optional(properties[K]);
3075
+ return partialProperties;
3076
+ }
3077
+ function FromObject$2(type, properties) {
3078
+ const options = Discard(type, [
3079
+ TransformKind,
3080
+ "$id",
3081
+ "required",
3082
+ "properties"
3083
+ ]);
3084
+ return Object$1(FromProperties$3(properties), options);
3085
+ }
3086
+ function FromRest$1(types) {
3087
+ return types.map((type) => PartialResolve(type));
3088
+ }
3089
+ function PartialResolve(type) {
3090
+ return IsComputed$1(type) ? FromComputed$2(type.target, type.parameters) : IsRef$1(type) ? FromRef$1(type.$ref) : IsIntersect$1(type) ? Intersect(FromRest$1(type.allOf)) : IsUnion$1(type) ? Union(FromRest$1(type.anyOf)) : IsObject$1(type) ? FromObject$2(type, type.properties) : IsBigInt$1(type) ? type : IsBoolean$1(type) ? type : IsInteger$1(type) ? type : IsLiteral$1(type) ? type : IsNull$1(type) ? type : IsNumber$1(type) ? type : IsString$1(type) ? type : IsSymbol$1(type) ? type : IsUndefined$1(type) ? type : Object$1({});
3091
+ }
3092
+ /** `[Json]` Constructs a type where all properties are optional */
3093
+ function Partial(type, options) {
3094
+ if (IsMappedResult$1(type)) return PartialFromMappedResult(type, options);
3095
+ else return CreateType({
3096
+ ...PartialResolve(type),
3097
+ ...options
3098
+ });
3099
+ }
3100
+ //#endregion
3101
+ //#region node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs
3102
+ function FromProperties$2(K, options) {
3103
+ const Acc = {};
3104
+ for (const K2 of globalThis.Object.getOwnPropertyNames(K)) Acc[K2] = Partial(K[K2], Clone(options));
3105
+ return Acc;
3106
+ }
3107
+ function FromMappedResult$1(R, options) {
3108
+ return FromProperties$2(R.properties, options);
3109
+ }
3110
+ function PartialFromMappedResult(R, options) {
3111
+ return MappedResult(FromMappedResult$1(R, options));
3112
+ }
3113
+ //#endregion
3114
+ //#region node_modules/@sinclair/typebox/build/esm/type/required/required.mjs
3115
+ function FromComputed$1(target, parameters) {
3116
+ return Computed("Required", [Computed(target, parameters)]);
3117
+ }
3118
+ function FromRef($ref) {
3119
+ return Computed("Required", [Ref($ref)]);
3120
+ }
3121
+ function FromProperties$1(properties) {
3122
+ const requiredProperties = {};
3123
+ for (const K of globalThis.Object.getOwnPropertyNames(properties)) requiredProperties[K] = Discard(properties[K], [OptionalKind]);
3124
+ return requiredProperties;
3125
+ }
3126
+ function FromObject$1(type, properties) {
3127
+ const options = Discard(type, [
3128
+ TransformKind,
3129
+ "$id",
3130
+ "required",
3131
+ "properties"
3132
+ ]);
3133
+ return Object$1(FromProperties$1(properties), options);
3134
+ }
3135
+ function FromRest(types) {
3136
+ return types.map((type) => RequiredResolve(type));
3137
+ }
3138
+ function RequiredResolve(type) {
3139
+ return IsComputed$1(type) ? FromComputed$1(type.target, type.parameters) : IsRef$1(type) ? FromRef(type.$ref) : IsIntersect$1(type) ? Intersect(FromRest(type.allOf)) : IsUnion$1(type) ? Union(FromRest(type.anyOf)) : IsObject$1(type) ? FromObject$1(type, type.properties) : IsBigInt$1(type) ? type : IsBoolean$1(type) ? type : IsInteger$1(type) ? type : IsLiteral$1(type) ? type : IsNull$1(type) ? type : IsNumber$1(type) ? type : IsString$1(type) ? type : IsSymbol$1(type) ? type : IsUndefined$1(type) ? type : Object$1({});
3140
+ }
3141
+ /** `[Json]` Constructs a type where all properties are required */
3142
+ function Required(type, options) {
3143
+ if (IsMappedResult$1(type)) return RequiredFromMappedResult(type, options);
3144
+ else return CreateType({
3145
+ ...RequiredResolve(type),
3146
+ ...options
3147
+ });
3148
+ }
3149
+ //#endregion
3150
+ //#region node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs
3151
+ function FromProperties(P, options) {
3152
+ const Acc = {};
3153
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P)) Acc[K2] = Required(P[K2], options);
3154
+ return Acc;
3155
+ }
3156
+ function FromMappedResult(R, options) {
3157
+ return FromProperties(R.properties, options);
3158
+ }
3159
+ function RequiredFromMappedResult(R, options) {
3160
+ return MappedResult(FromMappedResult(R, options));
3161
+ }
3162
+ //#endregion
3163
+ //#region node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs
3164
+ function DereferenceParameters(moduleProperties, types) {
3165
+ return types.map((type) => {
3166
+ return IsRef$1(type) ? Dereference(moduleProperties, type.$ref) : FromType(moduleProperties, type);
3167
+ });
3168
+ }
3169
+ function Dereference(moduleProperties, ref) {
3170
+ return ref in moduleProperties ? IsRef$1(moduleProperties[ref]) ? Dereference(moduleProperties, moduleProperties[ref].$ref) : FromType(moduleProperties, moduleProperties[ref]) : Never();
3171
+ }
3172
+ function FromAwaited(parameters) {
3173
+ return Awaited(parameters[0]);
3174
+ }
3175
+ function FromIndex(parameters) {
3176
+ return Index(parameters[0], parameters[1]);
3177
+ }
3178
+ function FromKeyOf(parameters) {
3179
+ return KeyOf(parameters[0]);
3180
+ }
3181
+ function FromPartial(parameters) {
3182
+ return Partial(parameters[0]);
3183
+ }
3184
+ function FromOmit(parameters) {
3185
+ return Omit(parameters[0], parameters[1]);
3186
+ }
3187
+ function FromPick(parameters) {
3188
+ return Pick(parameters[0], parameters[1]);
3189
+ }
3190
+ function FromRequired(parameters) {
3191
+ return Required(parameters[0]);
3192
+ }
3193
+ function FromComputed(moduleProperties, target, parameters) {
3194
+ const dereferenced = DereferenceParameters(moduleProperties, parameters);
3195
+ return target === "Awaited" ? FromAwaited(dereferenced) : target === "Index" ? FromIndex(dereferenced) : target === "KeyOf" ? FromKeyOf(dereferenced) : target === "Partial" ? FromPartial(dereferenced) : target === "Omit" ? FromOmit(dereferenced) : target === "Pick" ? FromPick(dereferenced) : target === "Required" ? FromRequired(dereferenced) : Never();
3196
+ }
3197
+ function FromArray(moduleProperties, type) {
3198
+ return Array$1(FromType(moduleProperties, type));
3199
+ }
3200
+ function FromAsyncIterator(moduleProperties, type) {
3201
+ return AsyncIterator(FromType(moduleProperties, type));
3202
+ }
3203
+ function FromConstructor(moduleProperties, parameters, instanceType) {
3204
+ return Constructor(FromTypes(moduleProperties, parameters), FromType(moduleProperties, instanceType));
3205
+ }
3206
+ function FromFunction(moduleProperties, parameters, returnType) {
3207
+ return Function(FromTypes(moduleProperties, parameters), FromType(moduleProperties, returnType));
3208
+ }
3209
+ function FromIntersect(moduleProperties, types) {
3210
+ return Intersect(FromTypes(moduleProperties, types));
3211
+ }
3212
+ function FromIterator(moduleProperties, type) {
3213
+ return Iterator(FromType(moduleProperties, type));
3214
+ }
3215
+ function FromObject(moduleProperties, properties) {
3216
+ return Object$1(globalThis.Object.keys(properties).reduce((result, key) => {
3217
+ return {
3218
+ ...result,
3219
+ [key]: FromType(moduleProperties, properties[key])
3220
+ };
3221
+ }, {}));
3222
+ }
3223
+ function FromRecord(moduleProperties, type) {
3224
+ const [value, pattern] = [FromType(moduleProperties, RecordValue(type)), RecordPattern(type)];
3225
+ const result = CloneType(type);
3226
+ result.patternProperties[pattern] = value;
3227
+ return result;
3228
+ }
3229
+ function FromTransform(moduleProperties, transform) {
3230
+ return IsRef$1(transform) ? {
3231
+ ...Dereference(moduleProperties, transform.$ref),
3232
+ [TransformKind]: transform[TransformKind]
3233
+ } : transform;
3234
+ }
3235
+ function FromTuple(moduleProperties, types) {
3236
+ return Tuple(FromTypes(moduleProperties, types));
3237
+ }
3238
+ function FromUnion(moduleProperties, types) {
3239
+ return Union(FromTypes(moduleProperties, types));
3240
+ }
3241
+ function FromTypes(moduleProperties, types) {
3242
+ return types.map((type) => FromType(moduleProperties, type));
3243
+ }
3244
+ function FromType(moduleProperties, type) {
3245
+ return IsOptional$1(type) ? CreateType(FromType(moduleProperties, Discard(type, [OptionalKind])), type) : IsReadonly(type) ? CreateType(FromType(moduleProperties, Discard(type, [ReadonlyKind])), type) : IsTransform$1(type) ? CreateType(FromTransform(moduleProperties, type), type) : IsArray$1(type) ? CreateType(FromArray(moduleProperties, type.items), type) : IsAsyncIterator$1(type) ? CreateType(FromAsyncIterator(moduleProperties, type.items), type) : IsComputed$1(type) ? CreateType(FromComputed(moduleProperties, type.target, type.parameters)) : IsConstructor$1(type) ? CreateType(FromConstructor(moduleProperties, type.parameters, type.returns), type) : IsFunction$1(type) ? CreateType(FromFunction(moduleProperties, type.parameters, type.returns), type) : IsIntersect$1(type) ? CreateType(FromIntersect(moduleProperties, type.allOf), type) : IsIterator$1(type) ? CreateType(FromIterator(moduleProperties, type.items), type) : IsObject$1(type) ? CreateType(FromObject(moduleProperties, type.properties), type) : IsRecord$1(type) ? CreateType(FromRecord(moduleProperties, type)) : IsTuple$1(type) ? CreateType(FromTuple(moduleProperties, type.items || []), type) : IsUnion$1(type) ? CreateType(FromUnion(moduleProperties, type.anyOf), type) : type;
3246
+ }
3247
+ function ComputeType(moduleProperties, key) {
3248
+ return key in moduleProperties ? FromType(moduleProperties, moduleProperties[key]) : Never();
3249
+ }
3250
+ function ComputeModuleProperties(moduleProperties) {
3251
+ return globalThis.Object.getOwnPropertyNames(moduleProperties).reduce((result, key) => {
3252
+ return {
3253
+ ...result,
3254
+ [key]: ComputeType(moduleProperties, key)
3255
+ };
3256
+ }, {});
3257
+ }
3258
+ //#endregion
3259
+ //#region node_modules/@sinclair/typebox/build/esm/type/module/module.mjs
3260
+ var TModule = class {
3261
+ constructor($defs) {
3262
+ const computed = ComputeModuleProperties($defs);
3263
+ this.$defs = this.WithIdentifiers(computed);
3264
+ }
3265
+ /** `[Json]` Imports a Type by Key. */
3266
+ Import(key, options) {
3267
+ const $defs = {
3268
+ ...this.$defs,
3269
+ [key]: CreateType(this.$defs[key], options)
3270
+ };
3271
+ return CreateType({
3272
+ [Kind]: "Import",
3273
+ $defs,
3274
+ $ref: key
3275
+ });
3276
+ }
3277
+ WithIdentifiers($defs) {
3278
+ return globalThis.Object.getOwnPropertyNames($defs).reduce((result, key) => {
3279
+ return {
3280
+ ...result,
3281
+ [key]: {
3282
+ ...$defs[key],
3283
+ $id: key
3284
+ }
3285
+ };
3286
+ }, {});
3287
+ }
3288
+ };
3289
+ /** `[Json]` Creates a Type Definition Module. */
3290
+ function Module(properties) {
3291
+ return new TModule(properties);
3292
+ }
3293
+ //#endregion
3294
+ //#region node_modules/@sinclair/typebox/build/esm/type/not/not.mjs
3295
+ /** `[Json]` Creates a Not type */
3296
+ function Not(type, options) {
3297
+ return CreateType({
3298
+ [Kind]: "Not",
3299
+ not: type
3300
+ }, options);
3301
+ }
3302
+ //#endregion
3303
+ //#region node_modules/@sinclair/typebox/build/esm/type/parameters/parameters.mjs
3304
+ /** `[JavaScript]` Extracts the Parameters from the given Function type */
3305
+ function Parameters(schema, options) {
3306
+ return IsFunction$1(schema) ? Tuple(schema.parameters, options) : Never();
3307
+ }
3308
+ //#endregion
3309
+ //#region node_modules/@sinclair/typebox/build/esm/type/recursive/recursive.mjs
3310
+ let Ordinal = 0;
3311
+ /** `[Json]` Creates a Recursive type */
3312
+ function Recursive(callback, options = {}) {
3313
+ if (IsUndefined$3(options.$id)) options.$id = `T${Ordinal++}`;
3314
+ const thisType = CloneType(callback({
3315
+ [Kind]: "This",
3316
+ $ref: `${options.$id}`
3317
+ }));
3318
+ thisType.$id = options.$id;
3319
+ return CreateType({
3320
+ [Hint]: "Recursive",
3321
+ ...thisType
3322
+ }, options);
3323
+ }
3324
+ //#endregion
3325
+ //#region node_modules/@sinclair/typebox/build/esm/type/regexp/regexp.mjs
3326
+ /** `[JavaScript]` Creates a RegExp type */
3327
+ function RegExp$1(unresolved, options) {
3328
+ const expr = IsString$2(unresolved) ? new globalThis.RegExp(unresolved) : unresolved;
3329
+ return CreateType({
3330
+ [Kind]: "RegExp",
3331
+ type: "RegExp",
3332
+ source: expr.source,
3333
+ flags: expr.flags
3334
+ }, options);
3335
+ }
3336
+ //#endregion
3337
+ //#region node_modules/@sinclair/typebox/build/esm/type/rest/rest.mjs
3338
+ function RestResolve(T) {
3339
+ return IsIntersect$1(T) ? T.allOf : IsUnion$1(T) ? T.anyOf : IsTuple$1(T) ? T.items ?? [] : [];
3340
+ }
3341
+ /** `[Json]` Extracts interior Rest elements from Tuple, Intersect and Union types */
3342
+ function Rest(T) {
3343
+ return RestResolve(T);
3344
+ }
3345
+ //#endregion
3346
+ //#region node_modules/@sinclair/typebox/build/esm/type/return-type/return-type.mjs
3347
+ /** `[JavaScript]` Extracts the ReturnType from the given Function type */
3348
+ function ReturnType(schema, options) {
3349
+ return IsFunction$1(schema) ? CreateType(schema.returns, options) : Never(options);
3350
+ }
3351
+ //#endregion
3352
+ //#region node_modules/@sinclair/typebox/build/esm/type/transform/transform.mjs
3353
+ var TransformDecodeBuilder = class {
3354
+ constructor(schema) {
3355
+ this.schema = schema;
3356
+ }
3357
+ Decode(decode) {
3358
+ return new TransformEncodeBuilder(this.schema, decode);
3359
+ }
3360
+ };
3361
+ var TransformEncodeBuilder = class {
3362
+ constructor(schema, decode) {
3363
+ this.schema = schema;
3364
+ this.decode = decode;
3365
+ }
3366
+ EncodeTransform(encode, schema) {
3367
+ const Encode = (value) => schema[TransformKind].Encode(encode(value));
3368
+ const Decode = (value) => this.decode(schema[TransformKind].Decode(value));
3369
+ const Codec = {
3370
+ Encode,
3371
+ Decode
3372
+ };
3373
+ return {
3374
+ ...schema,
3375
+ [TransformKind]: Codec
3376
+ };
3377
+ }
3378
+ EncodeSchema(encode, schema) {
3379
+ const Codec = {
3380
+ Decode: this.decode,
3381
+ Encode: encode
3382
+ };
3383
+ return {
3384
+ ...schema,
3385
+ [TransformKind]: Codec
3386
+ };
3387
+ }
3388
+ Encode(encode) {
3389
+ return IsTransform$1(this.schema) ? this.EncodeTransform(encode, this.schema) : this.EncodeSchema(encode, this.schema);
3390
+ }
3391
+ };
3392
+ /** `[Json]` Creates a Transform type */
3393
+ function Transform(schema) {
3394
+ return new TransformDecodeBuilder(schema);
3395
+ }
3396
+ //#endregion
3397
+ //#region node_modules/@sinclair/typebox/build/esm/type/unsafe/unsafe.mjs
3398
+ /** `[Json]` Creates a Unsafe type that will infers as the generic argument T */
3399
+ function Unsafe(options = {}) {
3400
+ return CreateType({ [Kind]: options[Kind] ?? "Unsafe" }, options);
3401
+ }
3402
+ //#endregion
3403
+ //#region node_modules/@sinclair/typebox/build/esm/type/void/void.mjs
3404
+ /** `[JavaScript]` Creates a Void type */
3405
+ function Void(options) {
3406
+ return CreateType({
3407
+ [Kind]: "Void",
3408
+ type: "void"
3409
+ }, options);
3410
+ }
3411
+ //#endregion
3412
+ //#region node_modules/@sinclair/typebox/build/esm/type/type/index.mjs
3413
+ /** JavaScript Type Builder with Static Resolution for TypeScript */
3414
+ const Type = /* @__PURE__ */ __exportAll({
3415
+ Any: () => Any,
3416
+ Argument: () => Argument,
3417
+ Array: () => Array$1,
3418
+ AsyncIterator: () => AsyncIterator,
3419
+ Awaited: () => Awaited,
3420
+ BigInt: () => BigInt,
3421
+ Boolean: () => Boolean,
3422
+ Capitalize: () => Capitalize,
3423
+ Composite: () => Composite,
3424
+ Const: () => Const,
3425
+ Constructor: () => Constructor,
3426
+ ConstructorParameters: () => ConstructorParameters,
3427
+ Date: () => Date$1,
3428
+ Enum: () => Enum,
3429
+ Exclude: () => Exclude,
3430
+ Extends: () => Extends,
3431
+ Extract: () => Extract,
3432
+ Function: () => Function,
3433
+ Index: () => Index,
3434
+ InstanceType: () => InstanceType,
3435
+ Instantiate: () => Instantiate,
3436
+ Integer: () => Integer,
3437
+ Intersect: () => Intersect,
3438
+ Iterator: () => Iterator,
3439
+ KeyOf: () => KeyOf,
3440
+ Literal: () => Literal,
3441
+ Lowercase: () => Lowercase,
3442
+ Mapped: () => Mapped,
3443
+ Module: () => Module,
3444
+ Never: () => Never,
3445
+ Not: () => Not,
3446
+ Null: () => Null,
3447
+ Number: () => Number$1,
3448
+ Object: () => Object$1,
3449
+ Omit: () => Omit,
3450
+ Optional: () => Optional,
3451
+ Parameters: () => Parameters,
3452
+ Partial: () => Partial,
3453
+ Pick: () => Pick,
3454
+ Promise: () => Promise$1,
3455
+ Readonly: () => Readonly,
3456
+ ReadonlyOptional: () => ReadonlyOptional,
3457
+ Record: () => Record,
3458
+ Recursive: () => Recursive,
3459
+ Ref: () => Ref,
3460
+ RegExp: () => RegExp$1,
3461
+ Required: () => Required,
3462
+ Rest: () => Rest,
3463
+ ReturnType: () => ReturnType,
3464
+ String: () => String$1,
3465
+ Symbol: () => Symbol$1,
3466
+ TemplateLiteral: () => TemplateLiteral,
3467
+ Transform: () => Transform,
3468
+ Tuple: () => Tuple,
3469
+ Uint8Array: () => Uint8Array$1,
3470
+ Uncapitalize: () => Uncapitalize,
3471
+ Undefined: () => Undefined,
3472
+ Union: () => Union,
3473
+ Unknown: () => Unknown,
3474
+ Unsafe: () => Unsafe,
3475
+ Uppercase: () => Uppercase,
3476
+ Void: () => Void
3477
+ });
3478
+ //#endregion
3479
+ //#region src/openai/json-schema-to-typebox.ts
3480
+ function isRecord$2(value) {
3481
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3482
+ }
3483
+ /**
3484
+ * Unsupported JSON Schema keywords that we reject explicitly.
3485
+ * Note: `anyOf` is handled separately for common patterns (nullable types, simple unions).
3486
+ */
3487
+ const REJECTED_KEYWORDS = [
3488
+ "$ref",
3489
+ "oneOf",
3490
+ "allOf",
3491
+ "if",
3492
+ "then",
3493
+ "else",
3494
+ "patternProperties",
3495
+ "not"
3496
+ ];
3497
+ /**
3498
+ * Convert a JSON Schema object to a TypeBox TSchema.
3499
+ *
3500
+ * Returns a ConversionError for unsupported constructs.
3501
+ */
3502
+ function jsonSchemaToTypebox(schema, path = "") {
3503
+ if (!isRecord$2(schema)) return {
3504
+ ok: false,
3505
+ message: "Schema must be an object",
3506
+ path
3507
+ };
3508
+ for (const keyword of REJECTED_KEYWORDS) if (schema[keyword] !== void 0) return {
3509
+ ok: false,
3510
+ message: `Unsupported JSON Schema keyword '${keyword}' at ${path || "root"}`,
3511
+ path
3512
+ };
3513
+ const description = typeof schema["description"] === "string" ? schema["description"] : void 0;
3514
+ const opts = {};
3515
+ if (description !== void 0) opts["description"] = description;
3516
+ const anyOf = schema["anyOf"];
3517
+ if (Array.isArray(anyOf)) return convertAnyOf(anyOf, path, opts);
3518
+ const enumValues = schema["enum"];
3519
+ if (Array.isArray(enumValues)) return convertEnum(enumValues, path, opts);
3520
+ const rawType = schema["type"];
3521
+ if (Array.isArray(rawType)) return convertNullableType(rawType, schema, path, opts);
3522
+ if (typeof rawType !== "string") {
3523
+ if (Object.keys(schema).length === 0 || Object.keys(schema).length === 1 && description !== void 0) return {
3524
+ ok: true,
3525
+ schema: Type.Unknown(opts)
3526
+ };
3527
+ return {
3528
+ ok: false,
3529
+ message: `Missing or invalid 'type' at ${path || "root"}`,
3530
+ path
3531
+ };
3532
+ }
3533
+ switch (rawType) {
3534
+ case "object": return convertObject(schema, path, opts);
3535
+ case "string": return {
3536
+ ok: true,
3537
+ schema: Type.String(opts)
3538
+ };
3539
+ case "number": return {
3540
+ ok: true,
3541
+ schema: Type.Number(opts)
3542
+ };
3543
+ case "integer": return {
3544
+ ok: true,
3545
+ schema: Type.Integer(opts)
3546
+ };
3547
+ case "boolean": return {
3548
+ ok: true,
3549
+ schema: Type.Boolean(opts)
3550
+ };
3551
+ case "null": return {
3552
+ ok: true,
3553
+ schema: Type.Null(opts)
3554
+ };
3555
+ case "array": return convertArray(schema, path, opts);
3556
+ default: return {
3557
+ ok: false,
3558
+ message: `Unsupported type '${rawType}' at ${path || "root"}`,
3559
+ path
3560
+ };
3561
+ }
3562
+ }
3563
+ /**
3564
+ * Convert anyOf to a TypeBox Union.
3565
+ *
3566
+ * Supports:
3567
+ * - Nullable: anyOf: [{type: T}, {type: "null"}]
3568
+ * - Simple unions of supported types (max 10 branches)
3569
+ */
3570
+ function convertAnyOf(branches, path, opts) {
3571
+ if (branches.length === 0) return {
3572
+ ok: false,
3573
+ message: `Empty 'anyOf' at ${path || "root"}`,
3574
+ path
3575
+ };
3576
+ if (branches.length > 10) return {
3577
+ ok: false,
3578
+ message: `'anyOf' with more than 10 branches is not supported at ${path || "root"}`,
3579
+ path
3580
+ };
3581
+ const converted = [];
3582
+ for (let i = 0; i < branches.length; i++) {
3583
+ const branchPath = `${path || "root"}.anyOf[${String(i)}]`;
3584
+ const result = jsonSchemaToTypebox(branches[i], branchPath);
3585
+ if (!result.ok) return result;
3586
+ converted.push(result.schema);
3587
+ }
3588
+ return {
3589
+ ok: true,
3590
+ schema: Type.Union(converted, opts)
3591
+ };
3592
+ }
3593
+ function convertEnum(values, path, opts) {
3594
+ const stringValues = [];
3595
+ for (const v of values) {
3596
+ if (typeof v !== "string") return {
3597
+ ok: false,
3598
+ message: `Only string enums are supported at ${path || "root"}`,
3599
+ path
3600
+ };
3601
+ stringValues.push(v);
3602
+ }
3603
+ if (stringValues.length === 0) return {
3604
+ ok: false,
3605
+ message: `Empty enum at ${path || "root"}`,
3606
+ path
3607
+ };
3608
+ const literals = stringValues.map((v) => Type.Literal(v));
3609
+ return {
3610
+ ok: true,
3611
+ schema: Type.Union(literals, opts)
3612
+ };
3613
+ }
3614
+ function convertNullableType(typeArray, schema, path, opts) {
3615
+ const nonNullTypes = typeArray.filter((t) => t !== "null");
3616
+ if (nonNullTypes.length !== 1 || typeArray.length !== 2) return {
3617
+ ok: false,
3618
+ message: `Only [type, "null"] nullable types are supported at ${path || "root"}`,
3619
+ path
3620
+ };
3621
+ const innerType = nonNullTypes[0];
3622
+ if (typeof innerType !== "string") return {
3623
+ ok: false,
3624
+ message: `Invalid nullable type at ${path || "root"}`,
3625
+ path
3626
+ };
3627
+ const innerResult = jsonSchemaToTypebox({
3628
+ ...schema,
3629
+ type: innerType
3630
+ }, path);
3631
+ if (!innerResult.ok) return innerResult;
3632
+ return {
3633
+ ok: true,
3634
+ schema: Type.Union([innerResult.schema, Type.Null()], opts)
3635
+ };
3636
+ }
3637
+ function convertObject(schema, path, opts) {
3638
+ const rawProperties = schema["properties"];
3639
+ const rawRequired = schema["required"];
3640
+ const additionalProperties = schema["additionalProperties"];
3641
+ if (additionalProperties !== void 0 && typeof additionalProperties !== "boolean") return {
3642
+ ok: false,
3643
+ message: `'additionalProperties' as a schema is not supported at ${path || "root"}; only boolean values are allowed`,
3644
+ path
3645
+ };
3646
+ if (rawProperties === void 0) return {
3647
+ ok: true,
3648
+ schema: Type.Object({}, opts)
3649
+ };
3650
+ if (!isRecord$2(rawProperties)) return {
3651
+ ok: false,
3652
+ message: `'properties' must be an object at ${path || "root"}`,
3653
+ path
3654
+ };
3655
+ const requiredSet = /* @__PURE__ */ new Set();
3656
+ if (Array.isArray(rawRequired)) {
3657
+ for (const r of rawRequired) if (typeof r === "string") requiredSet.add(r);
3658
+ }
3659
+ const typeboxProperties = {};
3660
+ for (const [key, propSchema] of Object.entries(rawProperties)) {
3661
+ const result = jsonSchemaToTypebox(propSchema, path.length > 0 ? `${path}.${key}` : key);
3662
+ if (!result.ok) return result;
3663
+ if (requiredSet.has(key)) typeboxProperties[key] = result.schema;
3664
+ else typeboxProperties[key] = Type.Optional(result.schema);
3665
+ }
3666
+ return {
3667
+ ok: true,
3668
+ schema: Type.Object(typeboxProperties, opts)
3669
+ };
3670
+ }
3671
+ function convertArray(schema, path, opts) {
3672
+ const items = schema["items"];
3673
+ if (items === void 0) return {
3674
+ ok: true,
3675
+ schema: Type.Array(Type.Unknown(), opts)
3676
+ };
3677
+ const itemResult = jsonSchemaToTypebox(items, path.length > 0 ? `${path}.items` : "items");
3678
+ if (!itemResult.ok) return itemResult;
3679
+ return {
3680
+ ok: true,
3681
+ schema: Type.Array(itemResult.schema, opts)
3682
+ };
3683
+ }
3684
+ //#endregion
3685
+ //#region src/openai/tools.ts
3686
+ /**
3687
+ * Convert an array of OpenAI function tool definitions to pi Tool definitions.
3688
+ */
3689
+ function convertTools(openaiTools) {
3690
+ const piTools = [];
3691
+ for (let i = 0; i < openaiTools.length; i++) {
3692
+ const tool = openaiTools[i];
3693
+ if (tool === void 0) continue;
3694
+ const fn = tool.function;
3695
+ let parameters;
3696
+ if (fn.parameters !== void 0) {
3697
+ const result = jsonSchemaToTypebox(fn.parameters, `tools[${String(i)}].function.parameters`);
3698
+ if (!result.ok) return {
3699
+ ok: false,
3700
+ message: result.message,
3701
+ param: result.path
3702
+ };
3703
+ parameters = result.schema;
3704
+ } else parameters = Type.Object({});
3705
+ piTools.push({
3706
+ name: fn.name,
3707
+ description: fn.description ?? "",
3708
+ parameters
3709
+ });
3710
+ }
3711
+ return {
3712
+ ok: true,
3713
+ tools: piTools
3714
+ };
3715
+ }
3716
+ //#endregion
3717
+ //#region src/openai/schemas.ts
3718
+ /**
3719
+ * Zod schemas for the OpenAI chat-completions request subset.
3720
+ *
3721
+ * Phase 2 contract:
3722
+ * - Phase 1 supported fields: model, messages, stream, temperature,
3723
+ * max_tokens, max_completion_tokens, stop, user, stream_options
3724
+ * - Phase 2 additions: tools, tool_choice, reasoning_effort,
3725
+ * top_p, frequency_penalty, presence_penalty, seed, response_format
3726
+ * - Unknown top-level fields are rejected with 422
3727
+ * - `n > 1` is rejected
3728
+ * - `logprobs` is rejected
3729
+ */
3730
+ const textContentPartSchema = z.object({
3731
+ type: z.literal("text"),
3732
+ text: z.string().trim()
3733
+ });
3734
+ const imageUrlContentPartSchema = z.object({
3735
+ type: z.literal("image_url"),
3736
+ image_url: z.object({
3737
+ url: z.string().trim(),
3738
+ detail: z.enum([
3739
+ "auto",
3740
+ "low",
3741
+ "high"
3742
+ ]).optional()
3743
+ })
3744
+ });
3745
+ const contentPartSchema = z.discriminatedUnion("type", [textContentPartSchema, imageUrlContentPartSchema]);
3746
+ const systemMessageSchema = z.object({
3747
+ role: z.literal("system"),
3748
+ content: z.string().trim(),
3749
+ name: z.string().trim().optional()
3750
+ });
3751
+ const developerMessageSchema = z.object({
3752
+ role: z.literal("developer"),
3753
+ content: z.string().trim(),
3754
+ name: z.string().trim().optional()
3755
+ });
3756
+ const userMessageTextSchema = z.object({
3757
+ role: z.literal("user"),
3758
+ content: z.string().trim(),
3759
+ name: z.string().trim().optional()
3760
+ });
3761
+ const userMessagePartsSchema = z.object({
3762
+ role: z.literal("user"),
3763
+ content: z.array(contentPartSchema),
3764
+ name: z.string().trim().optional()
3765
+ });
3766
+ const assistantMessageSchema = z.object({
3767
+ role: z.literal("assistant"),
3768
+ content: z.string().trim().nullable().optional(),
3769
+ name: z.string().trim().optional(),
3770
+ tool_calls: z.array(z.object({
3771
+ id: z.string().trim(),
3772
+ type: z.literal("function"),
3773
+ function: z.object({
3774
+ name: z.string().trim(),
3775
+ arguments: z.string().trim()
3776
+ })
3777
+ })).optional()
3778
+ });
3779
+ const toolMessageSchema = z.object({
3780
+ role: z.literal("tool"),
3781
+ content: z.string().trim(),
3782
+ tool_call_id: z.string().trim()
3783
+ });
3784
+ const messageSchema = z.union([
3785
+ systemMessageSchema,
3786
+ developerMessageSchema,
3787
+ userMessageTextSchema,
3788
+ userMessagePartsSchema,
3789
+ assistantMessageSchema,
3790
+ toolMessageSchema
3791
+ ]);
3792
+ const streamOptionsSchema = z.object({ include_usage: z.boolean().optional() });
3793
+ /**
3794
+ * OpenAI function tool definition.
3795
+ * The `parameters` field is a JSON Schema object validated structurally;
3796
+ * semantic conversion to TypeBox happens in json-schema-to-typebox.ts.
3797
+ */
3798
+ const functionToolSchema = z.object({
3799
+ type: z.literal("function"),
3800
+ function: z.object({
3801
+ name: z.string().trim(),
3802
+ description: z.string().trim().optional(),
3803
+ parameters: z.record(z.string().trim(), z.unknown()).optional(),
3804
+ strict: z.boolean().nullable().optional()
3805
+ })
3806
+ });
3807
+ /**
3808
+ * OpenAI tool_choice: "none" | "auto" | "required" | { type: "function", function: { name: string } }
3809
+ */
3810
+ const namedToolChoiceSchema = z.object({
3811
+ type: z.literal("function"),
3812
+ function: z.object({ name: z.string().trim() })
3813
+ });
3814
+ const toolChoiceSchema = z.union([z.enum([
3815
+ "none",
3816
+ "auto",
3817
+ "required"
3818
+ ]), namedToolChoiceSchema]);
3819
+ const responseFormatSchema = z.discriminatedUnion("type", [z.object({ type: z.literal("text") }), z.object({ type: z.literal("json_object") })]);
3820
+ const chatCompletionRequestSchema = z.object({
3821
+ model: z.string().trim(),
3822
+ messages: z.array(messageSchema).min(1),
3823
+ stream: z.boolean().optional(),
3824
+ temperature: z.number().min(0).max(2).optional(),
3825
+ max_tokens: z.int().positive().optional(),
3826
+ max_completion_tokens: z.int().positive().optional(),
3827
+ stop: z.union([z.string().trim(), z.array(z.string().trim()).max(4)]).optional(),
3828
+ user: z.string().trim().optional(),
3829
+ stream_options: streamOptionsSchema.nullable().optional(),
3830
+ tools: z.array(functionToolSchema).optional(),
3831
+ tool_choice: toolChoiceSchema.optional(),
3832
+ reasoning_effort: z.enum([
3833
+ "low",
3834
+ "medium",
3835
+ "high"
3836
+ ]).optional(),
3837
+ top_p: z.number().min(0).max(1).optional(),
3838
+ frequency_penalty: z.number().min(-2).max(2).optional(),
3839
+ presence_penalty: z.number().min(-2).max(2).optional(),
3840
+ seed: z.int().optional(),
3841
+ response_format: responseFormatSchema.optional()
3842
+ }).strict();
3843
+ /**
3844
+ * Fields that are explicitly rejected with a helpful error.
3845
+ * These are not supported and won't be promoted.
3846
+ */
3847
+ const rejectedFields = [
3848
+ "n",
3849
+ "logprobs",
3850
+ "top_logprobs",
3851
+ "logit_bias",
3852
+ "functions",
3853
+ "function_call",
3854
+ "parallel_tool_calls"
3855
+ ];
3856
+ //#endregion
3857
+ //#region src/openai/validate.ts
3858
+ /**
3859
+ * Request validation: parse and reject unsupported fields.
3860
+ *
3861
+ * Phase 2 contract: unknown fields -> 422, rejected fields -> 422
3862
+ */
3863
+ function isRecord$1(value) {
3864
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3865
+ }
3866
+ /**
3867
+ * Validate a raw request body against the Phase 1 schema.
3868
+ *
3869
+ * Also checks for known rejected fields to give friendly errors.
3870
+ */
3871
+ function validateChatRequest(body) {
3872
+ if (isRecord$1(body)) {
3873
+ for (const field of rejectedFields) if (body[field] !== void 0) return {
3874
+ ok: false,
3875
+ status: 422,
3876
+ message: `'${field}' is not supported in this version of the proxy`,
3877
+ param: field
3878
+ };
3879
+ }
3880
+ const result = chatCompletionRequestSchema.safeParse(body);
3881
+ if (result.success) return {
3882
+ ok: true,
3883
+ data: result.data
3884
+ };
3885
+ const firstIssue = result.error.issues[0];
3886
+ if (firstIssue !== void 0) {
3887
+ const path = firstIssue.path.join(".");
3888
+ if (firstIssue.code === "unrecognized_keys") return {
3889
+ ok: false,
3890
+ status: 422,
3891
+ message: `Unknown parameter(s): ${firstIssue.keys.join(", ")}`,
3892
+ param: firstIssue.keys[0] ?? null
3893
+ };
3894
+ return {
3895
+ ok: false,
3896
+ status: 400,
3897
+ message: `Invalid value for '${path}': ${firstIssue.message}`,
3898
+ param: path.length > 0 ? path : null
3899
+ };
3900
+ }
3901
+ return {
3902
+ ok: false,
3903
+ status: 400,
3904
+ message: "Invalid request body",
3905
+ param: null
3906
+ };
3907
+ }
3908
+ //#endregion
3909
+ //#region src/pi/complete.ts
3910
+ function isRecord(value) {
3911
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3912
+ }
3913
+ /**
3914
+ * Map OpenAI reasoning_effort to pi ThinkingLevel.
3915
+ *
3916
+ * OpenAI: "low" | "medium" | "high"
3917
+ * Pi: "minimal" | "low" | "medium" | "high" | "xhigh"
3918
+ *
3919
+ * Direct mapping for the three shared values.
3920
+ */
3921
+ const REASONING_EFFORT_MAP = {
3922
+ low: "low",
3923
+ medium: "medium",
3924
+ high: "high"
3925
+ };
3926
+ /**
3927
+ * APIs where onPayload passthrough fields are not supported.
3928
+ * These APIs use non-standard request formats that reject standard OpenAI fields.
3929
+ */
3930
+ const SKIP_PAYLOAD_PASSTHROUGH_APIS = new Set(["openai-codex-responses"]);
3931
+ /**
3932
+ * Collect fields that need to be injected via onPayload.
3933
+ * Skips passthrough for APIs that use non-standard request formats.
3934
+ */
3935
+ function collectPayloadFields(request, api) {
3936
+ if (SKIP_PAYLOAD_PASSTHROUGH_APIS.has(api)) return;
3937
+ const fields = {};
3938
+ let hasFields = false;
3939
+ if (request.stop !== void 0) {
3940
+ fields["stop"] = request.stop;
3941
+ hasFields = true;
3942
+ }
3943
+ if (request.user !== void 0) {
3944
+ fields["user"] = request.user;
3945
+ hasFields = true;
3946
+ }
3947
+ if (request.top_p !== void 0) {
3948
+ fields["top_p"] = request.top_p;
3949
+ hasFields = true;
3950
+ }
3951
+ if (request.frequency_penalty !== void 0) {
3952
+ fields["frequency_penalty"] = request.frequency_penalty;
3953
+ hasFields = true;
3954
+ }
3955
+ if (request.presence_penalty !== void 0) {
3956
+ fields["presence_penalty"] = request.presence_penalty;
3957
+ hasFields = true;
3958
+ }
3959
+ if (request.seed !== void 0) {
3960
+ fields["seed"] = request.seed;
3961
+ hasFields = true;
3962
+ }
3963
+ if (request.response_format !== void 0) {
3964
+ fields["response_format"] = request.response_format;
3965
+ hasFields = true;
3966
+ }
3967
+ return hasFields ? fields : void 0;
3968
+ }
3969
+ /**
3970
+ * Combine a client disconnect signal with an upstream timeout into a single signal.
3971
+ * Returns the combined signal, or undefined if neither is provided.
3972
+ */
3973
+ function buildCombinedSignal(clientSignal, timeoutMs) {
3974
+ if (clientSignal === void 0 && timeoutMs === void 0) return;
3975
+ if (timeoutMs === void 0) return clientSignal;
3976
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
3977
+ if (clientSignal === void 0) return timeoutSignal;
3978
+ return AbortSignal.any([clientSignal, timeoutSignal]);
3979
+ }
3980
+ /**
3981
+ * Build pi SimpleStreamOptions from an OpenAI request.
3982
+ */
3983
+ async function buildStreamOptions(model, request, options) {
3984
+ const opts = {};
3985
+ if (request.temperature !== void 0 && model.api !== "openai-codex-responses") opts.temperature = request.temperature;
3986
+ const maxTokens = request.max_completion_tokens ?? request.max_tokens;
3987
+ if (maxTokens !== void 0) opts.maxTokens = maxTokens;
3988
+ if (request.reasoning_effort !== void 0) {
3989
+ const level = REASONING_EFFORT_MAP[request.reasoning_effort];
3990
+ if (level !== void 0) opts.reasoning = level;
3991
+ }
3992
+ const combinedSignal = buildCombinedSignal(options.signal, options.upstreamTimeoutMs);
3993
+ if (combinedSignal !== void 0) opts.signal = combinedSignal;
3994
+ if (options.upstreamApiKey !== void 0) opts.apiKey = options.upstreamApiKey;
3995
+ else {
3996
+ const apiKey = await getRegistry().getApiKey(model);
3997
+ if (apiKey !== void 0) opts.apiKey = apiKey;
3998
+ }
3999
+ const payloadFields = collectPayloadFields(request, model.api);
4000
+ if (payloadFields !== void 0) opts.onPayload = (payload) => {
4001
+ if (isRecord(payload)) for (const [key, value] of Object.entries(payloadFields)) payload[key] = value;
4002
+ return payload;
4003
+ };
4004
+ return opts;
4005
+ }
4006
+ /**
4007
+ * Non-streaming completion: returns the final AssistantMessage.
4008
+ */
4009
+ async function piComplete(model, context, request, options) {
4010
+ return completeSimple(model, context, await buildStreamOptions(model, request, options));
4011
+ }
4012
+ /**
4013
+ * Streaming completion: returns an async iterable of events.
4014
+ */
4015
+ async function piStream(model, context, request, options) {
4016
+ return streamSimple(model, context, await buildStreamOptions(model, request, options));
4017
+ }
4018
+ //#endregion
4019
+ //#region src/pi/resolve-model.ts
4020
+ /**
4021
+ * Parse a canonical model ID string into provider and model-id.
4022
+ *
4023
+ * "openai/gpt-4o" -> { provider: "openai", modelId: "gpt-4o" }
4024
+ * "openrouter/anthropic/claude-sonnet-4-20250514" -> { provider: "openrouter", modelId: "anthropic/claude-sonnet-4-20250514" }
4025
+ * "gpt-4o" -> null (shorthand, no slash)
4026
+ */
4027
+ function parseCanonicalId(input) {
4028
+ const slashIndex = input.indexOf("/");
4029
+ if (slashIndex === -1) return null;
4030
+ return {
4031
+ provider: input.slice(0, slashIndex),
4032
+ modelId: input.slice(slashIndex + 1)
4033
+ };
4034
+ }
4035
+ /**
4036
+ * Resolve a model string (canonical or shorthand) to a pi Model.
4037
+ */
4038
+ function resolveModel(input) {
4039
+ const registry = getRegistry();
4040
+ const parsed = parseCanonicalId(input);
4041
+ if (parsed !== null) {
4042
+ const model = registry.find(parsed.provider, parsed.modelId);
4043
+ if (model === void 0) return {
4044
+ ok: false,
4045
+ status: 404,
4046
+ message: `Model '${input}' not found`
4047
+ };
4048
+ return {
4049
+ ok: true,
4050
+ model
4051
+ };
4052
+ }
4053
+ const allModels = registry.getAll();
4054
+ const matches = [];
4055
+ for (const m of allModels) if (m.id === input) matches.push(m);
4056
+ if (matches.length === 0) return {
4057
+ ok: false,
4058
+ status: 404,
4059
+ message: `Model '${input}' not found`
4060
+ };
4061
+ if (matches.length === 1) {
4062
+ const match = matches[0];
4063
+ if (match === void 0) return {
4064
+ ok: false,
4065
+ status: 404,
4066
+ message: `Model '${input}' not found`
4067
+ };
4068
+ return {
4069
+ ok: true,
4070
+ model: match
4071
+ };
4072
+ }
4073
+ const candidates = matches.map((m) => `${m.provider}/${m.id}`);
4074
+ return {
4075
+ ok: false,
4076
+ status: 400,
4077
+ message: `Ambiguous model '${input}'. Matches: ${candidates.join(", ")}. Use the canonical form 'provider/model-id'.`,
4078
+ candidates
4079
+ };
4080
+ }
4081
+ //#endregion
4082
+ //#region src/server/routes.ts
4083
+ function createRoutes(config) {
4084
+ const routes = new Hono();
4085
+ routes.get("/v1/models", (c) => {
4086
+ const models = getAvailableModels();
4087
+ return c.json(buildModelList(models));
4088
+ });
4089
+ routes.get("/v1/models/*", (c) => {
4090
+ const rawPath = c.req.path;
4091
+ if (!rawPath.startsWith("/v1/models/")) return c.json(modelNotFound(""), 404);
4092
+ const modelIdEncoded = rawPath.slice(11);
4093
+ if (modelIdEncoded.length === 0) return c.json(modelNotFound(""), 404);
4094
+ const modelId = decodeURIComponent(modelIdEncoded);
4095
+ const resolution = resolveModel(modelId);
4096
+ if (!resolution.ok) {
4097
+ if (resolution.status === 400) return c.json(invalidRequest(resolution.message, "model"), 400);
4098
+ return c.json(modelNotFound(modelId), 404);
4099
+ }
4100
+ return c.json(toOpenAIModel(resolution.model));
4101
+ });
4102
+ routes.post("/v1/chat/completions", async (c) => {
4103
+ const requestId = c.get("requestId");
4104
+ const abortController = c.get("abortController");
4105
+ const upstreamApiKey = c.get("upstreamApiKey");
4106
+ let body;
4107
+ try {
4108
+ body = await c.req.json();
4109
+ } catch {
4110
+ return c.json(invalidRequest("Invalid JSON in request body"), 400);
4111
+ }
4112
+ const validation = validateChatRequest(body);
4113
+ if (!validation.ok) {
4114
+ if (validation.status === 422) return c.json(unsupportedParameter(validation.param ?? "unknown", validation.message), 422);
4115
+ return c.json(invalidRequest(validation.message, validation.param ?? void 0), 400);
4116
+ }
4117
+ const request = validation.data;
4118
+ const resolution = resolveModel(request.model);
4119
+ if (!resolution.ok) {
4120
+ if (resolution.status === 400) return c.json(invalidRequest(resolution.message, "model"), 400);
4121
+ return c.json(modelNotFound(request.model), 404);
4122
+ }
4123
+ const model = resolution.model;
4124
+ const canonicalModelId = `${model.provider}/${model.id}`;
4125
+ const conversion = convertMessages(request.messages);
4126
+ if (!conversion.ok) return c.json(invalidRequest(conversion.message, conversion.param), 400);
4127
+ const context = conversion.context;
4128
+ if (request.tools !== void 0 && request.tools.length > 0) {
4129
+ const toolConversion = convertTools(request.tools);
4130
+ if (!toolConversion.ok) return c.json(unsupportedParameter(toolConversion.param, toolConversion.message), 422);
4131
+ context.tools = toolConversion.tools;
4132
+ }
4133
+ if (upstreamApiKey === void 0) {
4134
+ if (await getRegistry().getApiKey(model) === void 0) return c.json(authenticationError(`No API key configured for provider '${model.provider}'. Configure credentials via 'pi /login' or pass X-Pi-Upstream-Api-Key header.`), 401);
4135
+ }
4136
+ const completionOptions = {
4137
+ upstreamApiKey,
4138
+ signal: abortController.signal,
4139
+ upstreamTimeoutMs: config.upstreamTimeoutMs
4140
+ };
4141
+ if (request.stream === true) {
4142
+ const includeUsage = request.stream_options !== null && request.stream_options !== void 0 && request.stream_options.include_usage === true;
4143
+ c.header("content-type", "text/event-stream");
4144
+ c.header("cache-control", "no-cache");
4145
+ c.header("connection", "keep-alive");
4146
+ return stream(c, async (stream) => {
4147
+ try {
4148
+ const eventStream = await piStream(model, context, request, completionOptions);
4149
+ for await (const frame of streamToSSE(eventStream, requestId, canonicalModelId, includeUsage)) await stream.write(frame);
4150
+ } catch (err) {
4151
+ const mapped = mapUpstreamError(err);
4152
+ logError({
4153
+ requestId,
4154
+ method: "POST",
4155
+ path: "/v1/chat/completions"
4156
+ }, mapped.body.error.message, err instanceof Error ? err.message : void 0);
4157
+ const errorChunk = JSON.stringify({ error: mapped.body.error });
4158
+ await stream.write(`data: ${errorChunk}\n\n`);
4159
+ await stream.write("data: [DONE]\n\n");
4160
+ }
4161
+ });
4162
+ }
4163
+ try {
4164
+ const message = await piComplete(model, context, request, completionOptions);
4165
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
4166
+ const errorMessage = message.errorMessage ?? "Upstream provider error";
4167
+ const mapped = mapUpstreamError(new Error(errorMessage));
4168
+ logError({
4169
+ requestId,
4170
+ method: "POST",
4171
+ path: "/v1/chat/completions"
4172
+ }, errorMessage);
4173
+ return c.json(mapped.body, mapped.status);
4174
+ }
4175
+ return c.json(buildChatCompletion(requestId, canonicalModelId, message));
4176
+ } catch (err) {
4177
+ const mapped = mapUpstreamError(err);
4178
+ logError({
4179
+ requestId,
4180
+ method: "POST",
4181
+ path: "/v1/chat/completions"
4182
+ }, mapped.body.error.message, err instanceof Error ? err.message : void 0);
4183
+ return c.json(mapped.body, mapped.status);
4184
+ }
4185
+ });
4186
+ for (const path of [
4187
+ "/v1/completions",
4188
+ "/v1/embeddings",
4189
+ "/v1/audio/*",
4190
+ "/v1/images/*",
4191
+ "/v1/assistants",
4192
+ "/v1/assistants/*",
4193
+ "/v1/threads",
4194
+ "/v1/threads/*",
4195
+ "/v1/files",
4196
+ "/v1/files/*",
4197
+ "/v1/batches",
4198
+ "/v1/batches/*",
4199
+ "/v1/fine_tuning/*"
4200
+ ]) routes.all(path, (c) => {
4201
+ return c.json(invalidRequest(`Endpoint '${c.req.path}' is not supported by this proxy`, void 0), 404);
4202
+ });
4203
+ return routes;
4204
+ }
4205
+ //#endregion
4206
+ //#region src/server/app.ts
4207
+ function createApp(config) {
4208
+ const app = new Hono();
4209
+ app.use("*", requestIdMiddleware());
4210
+ app.use("*", disconnectMiddleware());
4211
+ app.use("*", bodySizeLimitMiddleware(config));
4212
+ app.use("/v1/*", proxyAuthMiddleware(config));
4213
+ app.route("/", createRoutes(config));
4214
+ return app;
4215
+ }
4216
+ //#endregion
4217
+ //#region src/index.ts
4218
+ /**
4219
+ * pi-openai-proxy entry point.
4220
+ *
4221
+ * Initializes the pi model registry, creates the Hono app, and starts serving.
4222
+ * Implements graceful shutdown on SIGTERM/SIGINT.
4223
+ */
4224
+ const config = loadConfig();
4225
+ const loadError = initRegistry();
4226
+ if (loadError !== void 0) {
4227
+ console.error(`[warn] models.json load error: ${loadError}`);
4228
+ console.error("[warn] Continuing with built-in models only.");
4229
+ }
4230
+ const models = getAvailableModels();
4231
+ const app = createApp(config);
4232
+ logStartup(config.host, config.port, models.length);
4233
+ console.error(`pi-openai-proxy listening on http://${config.host}:${String(config.port)} (${String(models.length)} models)`);
4234
+ let shutdownInitiated = false;
4235
+ function handleShutdown(signal) {
4236
+ if (shutdownInitiated) return;
4237
+ shutdownInitiated = true;
4238
+ logShutdown(signal);
4239
+ console.error(`[info] Received ${signal}, shutting down gracefully...`);
4240
+ const SHUTDOWN_TIMEOUT_MS = 1e4;
4241
+ if (server !== void 0) server.stop();
4242
+ setTimeout(() => {
4243
+ console.error("[warn] Shutdown timeout reached, forcing exit");
4244
+ process.exit(1);
4245
+ }, SHUTDOWN_TIMEOUT_MS).unref();
4246
+ }
4247
+ process.on("SIGTERM", () => handleShutdown("SIGTERM"));
4248
+ process.on("SIGINT", () => handleShutdown("SIGINT"));
4249
+ const server = Bun.serve({
4250
+ port: config.port,
4251
+ hostname: config.host,
4252
+ fetch: app.fetch,
4253
+ idleTimeout: 255
4254
+ });
4255
+ //#endregion
4256
+ export { server as default };