@vite-hub/webhooks 0.0.0-stage → 0.4.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.
@@ -0,0 +1,1333 @@
1
+ import { t as webhooksErrors } from "./errors-1y5fWGlX.js";
2
+ import { t as isRecordOrFunction } from "./object-BJb1W_q5.js";
3
+ import * as v from "valibot";
4
+ //#region ../../node_modules/.pnpm/nostics@1.4.0/node_modules/nostics/dist/index.mjs
5
+ /**
6
+ * Transforms a value or a function that returns a value to a value.
7
+ *
8
+ * @param valFn either a value or a function that returns a value
9
+ * @param args arguments to pass to the function if `valFn` is a function
10
+ *
11
+ * @internal
12
+ */
13
+ function toValueWithArgs(valFn, ...args) {
14
+ return typeof valFn === "function" ? valFn(...args) : valFn;
15
+ }
16
+ const captureStackTrace = Error.captureStackTrace;
17
+ var Diagnostic = class Diagnostic extends Error {
18
+ /**
19
+ * Alias for {@link Error.message}: the reason this diagnostic was raised.
20
+ */
21
+ get why() {
22
+ return this.message;
23
+ }
24
+ /**
25
+ * @param init structured initializer; `why` is required
26
+ * @param captureFrom V8 stack-cutoff frame. Defaults to {@link Diagnostic}
27
+ * so the top of the trace is the `new Diagnostic(...)` call site.
28
+ * `defineDiagnostics` passes its action method to strip its own frames too.
29
+ * Ignored on engines without `Error.captureStackTrace`.
30
+ */
31
+ constructor(init, captureFrom = Diagnostic) {
32
+ super(init.why, { cause: init.cause });
33
+ this.code = this.name = init.code;
34
+ this.docs = init.docs;
35
+ this.fix = init.fix;
36
+ this.sources = init.sources;
37
+ this.data = init.data;
38
+ captureStackTrace?.(this, captureFrom);
39
+ }
40
+ /**
41
+ * Converts the diagnostic into a serializable structured object.
42
+ */
43
+ toJSON() {
44
+ return {
45
+ name: this.name,
46
+ why: this.why,
47
+ fix: this.fix,
48
+ docs: this.docs,
49
+ sources: this.sources,
50
+ cause: this.cause,
51
+ data: this.data,
52
+ stack: this.stack
53
+ };
54
+ }
55
+ };
56
+ /**
57
+ * Resolves the docs URL for a code from a `docsBase` (string template or
58
+ * resolver function). Shared by {@link defineDiagnostics} and
59
+ * {@link defineProdDiagnostics}. Per-code `docs` overrides are handled by the
60
+ * caller; this only covers the `docsBase`-derived case.
61
+ *
62
+ * @internal
63
+ */
64
+ function deriveDocs(docsBase, code) {
65
+ return typeof docsBase === "string" ? `${docsBase}/${code.toLowerCase()}` : docsBase?.(code);
66
+ }
67
+ /**
68
+ * Runtime of {@link Diagnostics.is}: matches diagnostics tagged with `id`.
69
+ *
70
+ * @internal
71
+ */
72
+ const createRegistryIs = (id) => (error) => error instanceof Diagnostic && id in error;
73
+ /**
74
+ * Creates a typed diagnostics object from a set of code definitions. Each
75
+ * code becomes a callable {@link DiagnosticHandle}: invoke to report, or
76
+ * `throw` the result to raise. No `new` required, no proxy.
77
+ */
78
+ /* @__NO_SIDE_EFFECTS__ */
79
+ function defineDiagnostics(options) {
80
+ const reporters = options.reporters ?? [];
81
+ const id = Symbol();
82
+ const result = Object.defineProperty({}, "is", { value: createRegistryIs(id) });
83
+ const { docsBase } = options;
84
+ for (const code of Object.keys(options.codes)) {
85
+ const def = options.codes[code];
86
+ const docs = def.docs === false ? void 0 : def.docs || deriveDocs(docsBase, code);
87
+ const handle = (params = {}, reporterOptions = {}) => {
88
+ const diagnostic = new Diagnostic({
89
+ code,
90
+ why: toValueWithArgs(def.why, params),
91
+ fix: toValueWithArgs(def.fix, params),
92
+ docs,
93
+ cause: params.cause,
94
+ sources: params.sources,
95
+ data: toValueWithArgs(def.data, params)
96
+ }, handle);
97
+ diagnostic[id] = 1;
98
+ for (const reporter of reporters) reporter(diagnostic, reporterOptions);
99
+ return diagnostic;
100
+ };
101
+ handle.is = (err) => result.is(err) && err.code === code;
102
+ result[code] = handle;
103
+ }
104
+ return result;
105
+ }
106
+ //#endregion
107
+ //#region ../internal/src/error-diagnostics.ts
108
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
109
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
110
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
111
+ codes: {
112
+ INTERNAL_R0012: {
113
+ ...dynamicError,
114
+ fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
115
+ },
116
+ INTERNAL_R0013: {
117
+ ...dynamicError,
118
+ fix: "Check that the provider token can manage the resource in the path that the message names. `error.kind` and `error.codes` hold the provider failure."
119
+ },
120
+ INTERNAL_R0014: {
121
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
122
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
123
+ },
124
+ INTERNAL_R0020: {
125
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
126
+ why: ({ message }) => message === void 0 ? "" : String(message)
127
+ },
128
+ INTERNAL_R0021: {
129
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
130
+ why: ({ message }) => message === void 0 ? "" : String(message)
131
+ },
132
+ INTERNAL_R0022: {
133
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
134
+ why: ({ message }) => message === void 0 ? "" : String(message)
135
+ },
136
+ INTERNAL_R0024: {
137
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
138
+ why: ({ message }) => message === void 0 ? "" : String(message)
139
+ },
140
+ INTERNAL_R0023: {
141
+ fix: "Ask for access to the section of this operation.",
142
+ why: ({ message }) => message === void 0 ? "" : String(message)
143
+ },
144
+ INTERNAL_B0001: {
145
+ ...dynamicError,
146
+ fix: "Give the resource that the message names another name or binding in the `vitehub()` options of its feature, so that two different Cloudflare resources do not share one name."
147
+ },
148
+ INTERNAL_B0015: {
149
+ ...dynamicError,
150
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
151
+ },
152
+ INTERNAL_B0016: {
153
+ ...dynamicError,
154
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
155
+ },
156
+ INTERNAL_B0017: {
157
+ ...dynamicError,
158
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
159
+ },
160
+ INTERNAL_B0018: {
161
+ ...dynamicError,
162
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
163
+ },
164
+ INTERNAL_B0019: {
165
+ ...dynamicError,
166
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
167
+ },
168
+ INTERNAL_B0020: {
169
+ ...dynamicError,
170
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
171
+ },
172
+ INTERNAL_B0021: {
173
+ ...dynamicError,
174
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
175
+ },
176
+ INTERNAL_B0022: {
177
+ ...dynamicError,
178
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
179
+ },
180
+ INTERNAL_B0025: {
181
+ ...dynamicError,
182
+ fix: "Replace the `new URL(\"./...\", import.meta.url)` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` of that file."
183
+ },
184
+ INTERNAL_B0026: {
185
+ ...dynamicError,
186
+ fix: "Replace the computed `import()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` or with `import(\"<literal path>\")`."
187
+ },
188
+ INTERNAL_B0027: {
189
+ ...dynamicError,
190
+ fix: "Replace the computed `require()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import`."
191
+ },
192
+ INTERNAL_B0028: {
193
+ ...dynamicError,
194
+ fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
195
+ },
196
+ INTERNAL_B0029: {
197
+ ...dynamicError,
198
+ fix: "Stop the other builds that write the same Deno output folder, delete the `.vitehub-lock` folder next to that output folder, such as `.output.vitehub-lock`, then build again."
199
+ },
200
+ INTERNAL_B0031: {
201
+ ...dynamicError,
202
+ fix: "Import `./schedule/deno-cron.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./schedule/deno-cron.mjs\", import.meta.url).href)` outside any condition."
203
+ },
204
+ INTERNAL_B0032: {
205
+ ...dynamicError,
206
+ fix: "Import `./server/index.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./server/index.mjs\", import.meta.url).href)` outside any condition."
207
+ },
208
+ INTERNAL_B0035: {
209
+ ...dynamicError,
210
+ fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
211
+ },
212
+ INTERNAL_B0039: {
213
+ ...dynamicError,
214
+ fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
215
+ },
216
+ INTERNAL_B0040: {
217
+ ...dynamicError,
218
+ fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
219
+ },
220
+ INTERNAL_B0043: {
221
+ ...dynamicError,
222
+ fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
223
+ },
224
+ INTERNAL_B0046: {
225
+ ...dynamicError,
226
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
227
+ },
228
+ INTERNAL_B0047: {
229
+ ...dynamicError,
230
+ fix: "Correct the `package.json` file that the message names so that it holds one JSON object, or run `pnpm install` again to restore an installed package."
231
+ },
232
+ INTERNAL_B0048: {
233
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
234
+ why: ({ message }) => message === void 0 ? "" : String(message)
235
+ },
236
+ INTERNAL_B0049: {
237
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
238
+ why: ({ message }) => message === void 0 ? "" : String(message)
239
+ },
240
+ INTERNAL_B0050: {
241
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
242
+ why: ({ message }) => message === void 0 ? "" : String(message)
243
+ },
244
+ INTERNAL_B0051: {
245
+ why: ({ field, generated, name, path, project, scope }) => `The Cloudflare ${path} entry "${name}"${scope} is written by ViteHub and by the project's Wrangler config with a different ${field}: ${generated} and ${project}.`,
246
+ fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
247
+ },
248
+ INTERNAL_B0052: {
249
+ why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
250
+ fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
251
+ },
252
+ INTERNAL_R0025: {
253
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
254
+ why: ({ message }) => message === void 0 ? "" : String(message)
255
+ },
256
+ INTERNAL_R0026: {
257
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
258
+ fix: "Review the operation, then run it again with --yes to confirm the change."
259
+ },
260
+ INTERNAL_C0001: {
261
+ ...dynamicError,
262
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
263
+ },
264
+ INTERNAL_C0002: {
265
+ ...dynamicError,
266
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
267
+ },
268
+ INTERNAL_R0001: {
269
+ ...dynamicError,
270
+ fix: "Set `host` in `vitehub()`, or in the `vitehub` options of `nuxt.config.ts`, to `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. Or remove `host` so that ViteHub finds the host from the environment."
271
+ },
272
+ INTERNAL_R0002: {
273
+ ...dynamicError,
274
+ fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
275
+ },
276
+ INTERNAL_R0004: {
277
+ ...dynamicError,
278
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
279
+ },
280
+ INTERNAL_R0005: {
281
+ ...dynamicError,
282
+ fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
283
+ },
284
+ INTERNAL_R0006: {
285
+ ...dynamicError,
286
+ fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
287
+ },
288
+ INTERNAL_R0007: {
289
+ ...dynamicError,
290
+ fix: "Set `maxResponseBytes` of the HTTP request to a positive integer no greater than the limit that the message names, or remove it to use the default."
291
+ },
292
+ INTERNAL_R0008: {
293
+ ...dynamicError,
294
+ fix: "Make the value that the message names match its schema: the input, query, or body that you send, or the response schema that you declare for the request."
295
+ },
296
+ INTERNAL_R0009: {
297
+ ...dynamicError,
298
+ fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
299
+ },
300
+ INTERNAL_R0010: {
301
+ ...dynamicError,
302
+ fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
303
+ },
304
+ INTERNAL_R0011: {
305
+ ...dynamicError,
306
+ fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
307
+ },
308
+ INTERNAL_CONSOLE_KEY_NAME_INVALID: {
309
+ why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
310
+ fix: "Name the Console key with 1 to 64 characters from A-Z, 0-9, and _, such as `CI`. The app reads its public key from `VITEHUB_CONSOLE_KEY_<NAME>`."
311
+ },
312
+ INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
313
+ why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
314
+ fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
315
+ },
316
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
317
+ why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
318
+ fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
319
+ },
320
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
321
+ why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
322
+ fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
323
+ },
324
+ INTERNAL_DEV_SERVER_NOT_FOUND: {
325
+ why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
326
+ fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
327
+ },
328
+ INTERNAL_FORGE_NOT_INSTALLED: {
329
+ why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
330
+ fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
331
+ },
332
+ INTERNAL_MCP_ARGUMENTS_INVALID: {
333
+ why: ({ detail }) => detail,
334
+ fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
335
+ },
336
+ INTERNAL_MCP_METHOD_FAILED: {
337
+ why: ({ name }) => `${name} failed on the server.`,
338
+ fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
339
+ },
340
+ INTERNAL_MCP_RESOURCE_NOT_FOUND: {
341
+ why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
342
+ fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
343
+ },
344
+ INTERNAL_PRESET_OPTION_UNKNOWN: {
345
+ why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
346
+ fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
347
+ },
348
+ INTERNAL_PRESET_TUPLE_INVALID: {
349
+ why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
350
+ fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
351
+ },
352
+ INTERNAL_SECRET_PURPOSE_MISSING: {
353
+ why: "[vitehub] A derived secret requires a purpose.",
354
+ fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
355
+ },
356
+ INTERNAL_SECRET_TOO_SHORT: {
357
+ why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
358
+ fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
359
+ },
360
+ INTERNAL_SQLITE_ARGUMENT_INVALID: {
361
+ why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
362
+ fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
363
+ },
364
+ INTERNAL_SQLITE_INTEGER_UNSAFE: {
365
+ why: "Received integer which cannot be safely represented as a JavaScript number",
366
+ fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
367
+ },
368
+ INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
369
+ why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
370
+ fix: "Ask for the `draft-07`, `draft-2020-12`, or `openapi-3.0` JSON Schema target, or pass one of them as `withValibotJsonSchema(schema, { target })`."
371
+ }
372
+ }
373
+ });
374
+ //#endregion
375
+ //#region ../internal/src/standard-schema.ts
376
+ function readOwn(value, key) {
377
+ if (value === null || Object(value) !== value) return;
378
+ try {
379
+ return Reflect.get(Object(value), key);
380
+ } catch {
381
+ return;
382
+ }
383
+ }
384
+ /**
385
+ * Read a Standard JSON Schema projection without throwing.
386
+ *
387
+ * Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
388
+ * (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
389
+ */
390
+ function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
391
+ const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
392
+ const project = readOwn(jsonSchema, direction);
393
+ if (typeof project !== "function") return;
394
+ try {
395
+ const result = project.call(jsonSchema, libraryOptions ? {
396
+ target,
397
+ libraryOptions
398
+ } : { target });
399
+ return isRecordOrFunction(result) ? result : void 0;
400
+ } catch {
401
+ return;
402
+ }
403
+ }
404
+ //#endregion
405
+ //#region ../../node_modules/.pnpm/@valibot+to-json-schema@1.8.0_valibot@1.5.0_typescript@6.0.3_/node_modules/@valibot/to-json-schema/dist/index.mjs
406
+ /**
407
+ * Adds an error message to the errors array.
408
+ *
409
+ * @param errors The array of error messages.
410
+ * @param message The error message to add.
411
+ *
412
+ * @returns The new errors.
413
+ */
414
+ function addError(errors, message) {
415
+ if (errors) {
416
+ errors.push(message);
417
+ return errors;
418
+ }
419
+ return [message];
420
+ }
421
+ const ESCAPE_REGEX = /[.*+?^${}()|[\]\\]/g;
422
+ /**
423
+ * Escapes special regex characters in a string.
424
+ *
425
+ * @param string The string to escape.
426
+ *
427
+ * @returns The escaped string.
428
+ */
429
+ function escapeRegExp(string) {
430
+ return string.replace(ESCAPE_REGEX, "\\$&");
431
+ }
432
+ /**
433
+ * Throws an error or logs a warning based on the configuration.
434
+ *
435
+ * @param message The message to throw or log.
436
+ * @param config The conversion configuration.
437
+ */
438
+ function handleError(message, config) {
439
+ switch (config?.errorMode) {
440
+ case "ignore": break;
441
+ case "warn":
442
+ console.warn(message);
443
+ break;
444
+ default: throw new Error(message);
445
+ }
446
+ }
447
+ /**
448
+ * Whether a value is JSON compatible for a const keyword.
449
+ *
450
+ * @param value The value to check.
451
+ *
452
+ * @returns Whether the value is JSON compatible.
453
+ */
454
+ function isJsonConstValue(value) {
455
+ return typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || typeof value === "string";
456
+ }
457
+ /**
458
+ * Whether values are JSON compatible for an enum keyword.
459
+ *
460
+ * @param values The values to check.
461
+ *
462
+ * @returns Whether the values are JSON compatible.
463
+ */
464
+ function isJsonEnumValues(values) {
465
+ return values.every(isJsonConstValue);
466
+ }
467
+ /**
468
+ * Schema reference map with collision-free reference ID allocation.
469
+ */
470
+ var ReferenceMap = class extends Map {
471
+ /**
472
+ * Creates an empty schema reference map.
473
+ */
474
+ constructor() {
475
+ super();
476
+ this.count = 0;
477
+ this.usedIds = /* @__PURE__ */ new Set();
478
+ }
479
+ /**
480
+ * Adds a schema reference and reserves its ID.
481
+ *
482
+ * @param schema The Valibot schema.
483
+ * @param referenceId The reference ID.
484
+ *
485
+ * @returns The reference map.
486
+ */
487
+ set(schema, referenceId) {
488
+ this.usedIds.add(referenceId);
489
+ return super.set(schema, referenceId);
490
+ }
491
+ /**
492
+ * Creates a reference ID that is not yet used.
493
+ *
494
+ * @param definitions The JSON Schema definitions.
495
+ *
496
+ * @returns The unused reference ID.
497
+ */
498
+ createId(definitions) {
499
+ while (this.usedIds.has(`${this.count}`) || `${this.count}` in definitions) this.count++;
500
+ return `${this.count++}`;
501
+ }
502
+ };
503
+ /**
504
+ * Returns the stricter lower bound.
505
+ *
506
+ * @param current The current lower bound.
507
+ * @param value The new lower bound.
508
+ *
509
+ * @returns The stricter lower bound.
510
+ */
511
+ function getLowerBound(current, value) {
512
+ if (typeof current !== "number" || !Number.isFinite(current) || value > current) return value;
513
+ return current;
514
+ }
515
+ /**
516
+ * Returns the stricter upper bound.
517
+ *
518
+ * @param current The current upper bound.
519
+ * @param value The new upper bound.
520
+ *
521
+ * @returns The stricter upper bound.
522
+ */
523
+ function getUpperBound(current, value) {
524
+ if (typeof current !== "number" || !Number.isFinite(current) || value < current) return value;
525
+ return current;
526
+ }
527
+ /**
528
+ * Returns the combined not restriction.
529
+ *
530
+ * @param current The current not restriction.
531
+ * @param value The new not restriction.
532
+ *
533
+ * @returns The combined not restriction.
534
+ */
535
+ /* @__NO_SIDE_EFFECTS__ */
536
+ function getNotRestriction(current, value) {
537
+ return current !== void 0 ? { anyOf: [current, value] } : value;
538
+ }
539
+ /**
540
+ * Intersects allowed values with an existing enum restriction.
541
+ *
542
+ * @param jsonSchema The JSON Schema object.
543
+ * @param values The allowed values.
544
+ */
545
+ function intersectEnum(jsonSchema, values) {
546
+ let enumValues = jsonSchema.enum ?? values;
547
+ if (jsonSchema.enum) {
548
+ const valueSet = new Set(values);
549
+ enumValues = enumValues.filter((value) => valueSet.has(value));
550
+ }
551
+ if (enumValues.length) jsonSchema.enum = [...new Set(enumValues)];
552
+ else {
553
+ delete jsonSchema.enum;
554
+ jsonSchema.not = /* @__PURE__ */ getNotRestriction(jsonSchema.not, {});
555
+ }
556
+ }
557
+ /**
558
+ * Converts any supported Valibot action to the JSON Schema format.
559
+ *
560
+ * @param jsonSchema The JSON Schema object.
561
+ * @param valibotAction The Valibot action object.
562
+ * @param config The conversion configuration.
563
+ *
564
+ * @returns The converted JSON Schema.
565
+ */
566
+ function convertAction(jsonSchema, valibotAction, config) {
567
+ if (config?.ignoreActions?.includes(valibotAction.type)) return jsonSchema;
568
+ let errors;
569
+ switch (valibotAction.type) {
570
+ case "base64":
571
+ jsonSchema.contentEncoding = "base64";
572
+ break;
573
+ case "bic":
574
+ case "cuid2":
575
+ case "decimal":
576
+ case "digits":
577
+ case "domain":
578
+ case "emoji":
579
+ case "hash":
580
+ case "hexadecimal":
581
+ case "hex_color":
582
+ case "isrc":
583
+ case "iso_time_second":
584
+ case "iso_week":
585
+ case "ksuid":
586
+ case "mac":
587
+ case "mac48":
588
+ case "mac64":
589
+ case "nanoid":
590
+ case "octal":
591
+ case "slug":
592
+ case "ulid":
593
+ if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
594
+ else jsonSchema.pattern = valibotAction.requirement.source;
595
+ break;
596
+ case "description":
597
+ jsonSchema.description = valibotAction.description;
598
+ break;
599
+ case "email":
600
+ case "rfc_email":
601
+ jsonSchema.format = "email";
602
+ break;
603
+ case "ends_with":
604
+ if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
605
+ else jsonSchema.pattern = `${escapeRegExp(valibotAction.requirement)}$`;
606
+ break;
607
+ case "empty":
608
+ if (jsonSchema.type === "array") jsonSchema.maxItems = 0;
609
+ else {
610
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
611
+ jsonSchema.maxLength = 0;
612
+ }
613
+ break;
614
+ case "entries":
615
+ if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
616
+ errors = addError(errors, "The requirement of the \"entries\" action must be a non-negative integer.");
617
+ break;
618
+ }
619
+ jsonSchema.minProperties = getLowerBound(jsonSchema.minProperties, valibotAction.requirement);
620
+ jsonSchema.maxProperties = getUpperBound(jsonSchema.maxProperties, valibotAction.requirement);
621
+ break;
622
+ case "examples":
623
+ if (Array.isArray(jsonSchema.examples)) jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.examples];
624
+ else jsonSchema.examples = valibotAction.examples;
625
+ break;
626
+ case "gt_value":
627
+ if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") {
628
+ errors = addError(errors, `The "gt_value" action is not supported on type "${jsonSchema.type}".`);
629
+ break;
630
+ }
631
+ if (!Number.isFinite(valibotAction.requirement)) {
632
+ errors = addError(errors, "The requirement of the \"gt_value\" action is not JSON compatible.");
633
+ break;
634
+ }
635
+ if (config?.target === "openapi-3.0") {
636
+ errors = addError(errors, "The \"gt_value\" action is not supported for OpenAPI 3.0.");
637
+ break;
638
+ }
639
+ jsonSchema.exclusiveMinimum = getLowerBound(jsonSchema.exclusiveMinimum, valibotAction.requirement);
640
+ break;
641
+ case "includes":
642
+ if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
643
+ else jsonSchema.pattern = escapeRegExp(valibotAction.requirement);
644
+ break;
645
+ case "integer":
646
+ jsonSchema.type = "integer";
647
+ break;
648
+ case "ipv4":
649
+ jsonSchema.format = "ipv4";
650
+ break;
651
+ case "ipv6":
652
+ jsonSchema.format = "ipv6";
653
+ break;
654
+ case "iso_date":
655
+ jsonSchema.format = "date";
656
+ break;
657
+ case "iso_date_time":
658
+ case "iso_timestamp":
659
+ jsonSchema.format = "date-time";
660
+ break;
661
+ case "iso_time":
662
+ jsonSchema.format = "time";
663
+ break;
664
+ case "jws_compact":
665
+ if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
666
+ else jsonSchema.pattern = valibotAction.requirement.source;
667
+ break;
668
+ case "length":
669
+ if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
670
+ errors = addError(errors, "The requirement of the \"length\" action must be a non-negative integer.");
671
+ break;
672
+ }
673
+ if (jsonSchema.type === "array") {
674
+ jsonSchema.minItems = getLowerBound(jsonSchema.minItems, valibotAction.requirement);
675
+ jsonSchema.maxItems = getUpperBound(jsonSchema.maxItems, valibotAction.requirement);
676
+ } else {
677
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
678
+ jsonSchema.minLength = getLowerBound(jsonSchema.minLength, valibotAction.requirement);
679
+ jsonSchema.maxLength = getUpperBound(jsonSchema.maxLength, valibotAction.requirement);
680
+ }
681
+ break;
682
+ case "lt_value":
683
+ if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") {
684
+ errors = addError(errors, `The "lt_value" action is not supported on type "${jsonSchema.type}".`);
685
+ break;
686
+ }
687
+ if (!Number.isFinite(valibotAction.requirement)) {
688
+ errors = addError(errors, "The requirement of the \"lt_value\" action is not JSON compatible.");
689
+ break;
690
+ }
691
+ if (config?.target === "openapi-3.0") {
692
+ errors = addError(errors, "The \"lt_value\" action is not supported for OpenAPI 3.0.");
693
+ break;
694
+ }
695
+ jsonSchema.exclusiveMaximum = getUpperBound(jsonSchema.exclusiveMaximum, valibotAction.requirement);
696
+ break;
697
+ case "max_entries":
698
+ if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
699
+ errors = addError(errors, "The requirement of the \"max_entries\" action must be a non-negative integer.");
700
+ break;
701
+ }
702
+ jsonSchema.maxProperties = getUpperBound(jsonSchema.maxProperties, valibotAction.requirement);
703
+ break;
704
+ case "max_length":
705
+ if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
706
+ errors = addError(errors, "The requirement of the \"max_length\" action must be a non-negative integer.");
707
+ break;
708
+ }
709
+ if (jsonSchema.type === "array") jsonSchema.maxItems = getUpperBound(jsonSchema.maxItems, valibotAction.requirement);
710
+ else {
711
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
712
+ jsonSchema.maxLength = getUpperBound(jsonSchema.maxLength, valibotAction.requirement);
713
+ }
714
+ break;
715
+ case "max_value":
716
+ if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") {
717
+ errors = addError(errors, `The "max_value" action is not supported on type "${jsonSchema.type}".`);
718
+ break;
719
+ }
720
+ if (!Number.isFinite(valibotAction.requirement)) {
721
+ errors = addError(errors, "The requirement of the \"max_value\" action is not JSON compatible.");
722
+ break;
723
+ }
724
+ jsonSchema.maximum = getUpperBound(jsonSchema.maximum, valibotAction.requirement);
725
+ break;
726
+ case "metadata":
727
+ if (typeof valibotAction.metadata.title === "string") jsonSchema.title = valibotAction.metadata.title;
728
+ if (typeof valibotAction.metadata.description === "string") jsonSchema.description = valibotAction.metadata.description;
729
+ if (Array.isArray(valibotAction.metadata.examples)) if (Array.isArray(jsonSchema.examples)) jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.metadata.examples];
730
+ else jsonSchema.examples = valibotAction.metadata.examples;
731
+ for (const key of Object.keys(valibotAction.metadata)) if (key !== "title" && key !== "description" && key !== "examples" && key !== "__proto__") jsonSchema[key] = valibotAction.metadata[key];
732
+ break;
733
+ case "min_entries":
734
+ if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
735
+ errors = addError(errors, "The requirement of the \"min_entries\" action must be a non-negative integer.");
736
+ break;
737
+ }
738
+ jsonSchema.minProperties = getLowerBound(jsonSchema.minProperties, valibotAction.requirement);
739
+ break;
740
+ case "min_length":
741
+ if (!Number.isInteger(valibotAction.requirement) || valibotAction.requirement < 0) {
742
+ errors = addError(errors, "The requirement of the \"min_length\" action must be a non-negative integer.");
743
+ break;
744
+ }
745
+ if (jsonSchema.type === "array") jsonSchema.minItems = getLowerBound(jsonSchema.minItems, valibotAction.requirement);
746
+ else {
747
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
748
+ jsonSchema.minLength = getLowerBound(jsonSchema.minLength, valibotAction.requirement);
749
+ }
750
+ break;
751
+ case "min_value":
752
+ if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") {
753
+ errors = addError(errors, `The "min_value" action is not supported on type "${jsonSchema.type}".`);
754
+ break;
755
+ }
756
+ if (!Number.isFinite(valibotAction.requirement)) {
757
+ errors = addError(errors, "The requirement of the \"min_value\" action is not JSON compatible.");
758
+ break;
759
+ }
760
+ jsonSchema.minimum = getLowerBound(jsonSchema.minimum, valibotAction.requirement);
761
+ break;
762
+ case "multiple_of":
763
+ jsonSchema.multipleOf = valibotAction.requirement;
764
+ break;
765
+ case "non_empty":
766
+ if (jsonSchema.type === "array") jsonSchema.minItems = getLowerBound(jsonSchema.minItems, 1);
767
+ else {
768
+ if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
769
+ jsonSchema.minLength = getLowerBound(jsonSchema.minLength, 1);
770
+ }
771
+ break;
772
+ case "not_value":
773
+ if (!isJsonConstValue(valibotAction.requirement)) {
774
+ errors = addError(errors, "The requirement of the \"not_value\" action is not JSON compatible.");
775
+ break;
776
+ }
777
+ jsonSchema.not = /* @__PURE__ */ getNotRestriction(jsonSchema.not, config?.target === "openapi-3.0" ? { enum: [valibotAction.requirement] } : { const: valibotAction.requirement });
778
+ break;
779
+ case "not_values":
780
+ if (!isJsonEnumValues(valibotAction.requirement)) {
781
+ errors = addError(errors, "A requirement of the \"not_values\" action is not JSON compatible.");
782
+ break;
783
+ }
784
+ if (valibotAction.requirement.length) jsonSchema.not = /* @__PURE__ */ getNotRestriction(jsonSchema.not, { enum: [...new Set(valibotAction.requirement)] });
785
+ break;
786
+ case "regex":
787
+ if (valibotAction.requirement.flags) errors = addError(errors, "RegExp flags are not supported by JSON Schema.");
788
+ if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
789
+ else jsonSchema.pattern = valibotAction.requirement.source;
790
+ break;
791
+ case "safe_integer":
792
+ jsonSchema.type = "integer";
793
+ jsonSchema.minimum = getLowerBound(jsonSchema.minimum, Number.MIN_SAFE_INTEGER);
794
+ jsonSchema.maximum = getUpperBound(jsonSchema.maximum, Number.MAX_SAFE_INTEGER);
795
+ break;
796
+ case "starts_with":
797
+ if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
798
+ else jsonSchema.pattern = `^${escapeRegExp(valibotAction.requirement)}`;
799
+ break;
800
+ case "title":
801
+ jsonSchema.title = valibotAction.title;
802
+ break;
803
+ case "url":
804
+ jsonSchema.format = "uri";
805
+ break;
806
+ case "uuid":
807
+ jsonSchema.format = "uuid";
808
+ break;
809
+ case "value":
810
+ if (!isJsonConstValue(valibotAction.requirement)) {
811
+ errors = addError(errors, "The requirement of the \"value\" action is not JSON compatible.");
812
+ break;
813
+ }
814
+ if (config?.target === "openapi-3.0") intersectEnum(jsonSchema, [valibotAction.requirement]);
815
+ else if ("const" in jsonSchema && jsonSchema.const !== valibotAction.requirement) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with a different "const" restriction.`);
816
+ else jsonSchema.const = valibotAction.requirement;
817
+ break;
818
+ case "values":
819
+ if (!isJsonEnumValues(valibotAction.requirement)) {
820
+ errors = addError(errors, "A requirement of the \"values\" action is not JSON compatible.");
821
+ break;
822
+ }
823
+ intersectEnum(jsonSchema, valibotAction.requirement);
824
+ break;
825
+ default: errors = addError(errors, `The "${valibotAction.type}" action cannot be converted to JSON Schema.`);
826
+ }
827
+ if (config?.overrideAction) {
828
+ const actionOverride = config.overrideAction({
829
+ valibotAction,
830
+ jsonSchema,
831
+ errors
832
+ });
833
+ if (actionOverride) return { ...actionOverride };
834
+ }
835
+ if (errors) for (const message of errors) handleError(message, config);
836
+ return jsonSchema;
837
+ }
838
+ /**
839
+ * Flattens a Valibot pipe by recursively expanding nested pipes.
840
+ *
841
+ * @param pipe The pipeline to flatten.
842
+ *
843
+ * @returns A flat pipeline.
844
+ */
845
+ function flattenPipe(pipe) {
846
+ return pipe.flatMap((item) => "pipe" in item ? flattenPipe(item.pipe) : item);
847
+ }
848
+ /**
849
+ * Returns the JSON Pointer reference for a definition key.
850
+ *
851
+ * @param referenceId The unescaped definition key.
852
+ *
853
+ * @returns The encoded JSON Pointer fragment.
854
+ */
855
+ function getDefinitionRef(referenceId) {
856
+ return `#/$defs/${referenceId.replaceAll("~", "~0").replaceAll("/", "~1")}`;
857
+ }
858
+ /**
859
+ * Converts any supported Valibot schema to the JSON Schema format.
860
+ *
861
+ * @param jsonSchema The JSON Schema object.
862
+ * @param valibotSchema The Valibot schema object.
863
+ * @param config The conversion configuration.
864
+ * @param context The conversion context.
865
+ * @param skipRef Whether to skip using a reference.
866
+ *
867
+ * @returns The converted JSON Schema.
868
+ */
869
+ function convertSchema(jsonSchema, valibotSchema, config, context, skipRef = false) {
870
+ if (!skipRef) {
871
+ const referenceId = context.referenceMap.get(valibotSchema);
872
+ if (referenceId) {
873
+ jsonSchema.$ref = getDefinitionRef(referenceId);
874
+ if (config?.overrideRef) {
875
+ const refOverride = config.overrideRef({
876
+ ...context,
877
+ referenceId,
878
+ valibotSchema,
879
+ jsonSchema
880
+ });
881
+ if (refOverride) jsonSchema.$ref = refOverride;
882
+ }
883
+ return jsonSchema;
884
+ }
885
+ }
886
+ if ("pipe" in valibotSchema) {
887
+ const flatPipe = flattenPipe(valibotSchema.pipe);
888
+ let startIndex = 0;
889
+ let stopIndex = flatPipe.length - 1;
890
+ if (config?.typeMode === "input") {
891
+ const inputStopIndex = flatPipe.slice(1).findIndex((item) => item.kind === "schema" || item.kind === "transformation" && (item.type === "find_item" || item.type === "parse_json" || item.type === "raw_transform" || item.type === "reduce_items" || item.type === "stringify_json" || item.type === "to_bigint" || item.type === "to_boolean" || item.type === "to_date" || item.type === "to_number" || item.type === "to_string" || item.type === "transform"));
892
+ if (inputStopIndex !== -1) stopIndex = inputStopIndex;
893
+ } else if (config?.typeMode === "output") {
894
+ const outputStartIndex = flatPipe.findLastIndex((item) => item.kind === "schema");
895
+ if (outputStartIndex !== -1) startIndex = outputStartIndex;
896
+ }
897
+ for (let index = startIndex; index <= stopIndex; index++) {
898
+ const valibotPipeItem = flatPipe[index];
899
+ if (valibotPipeItem.kind === "schema") {
900
+ if (index > startIndex) handleError("Set the \"typeMode\" config to \"input\" or \"output\" to convert pipelines with multiple schemas.", config);
901
+ jsonSchema = convertSchema(jsonSchema, valibotPipeItem, config, context, true);
902
+ } else jsonSchema = convertAction(jsonSchema, valibotPipeItem, config);
903
+ }
904
+ return jsonSchema;
905
+ }
906
+ let errors;
907
+ switch (valibotSchema.type) {
908
+ case "boolean":
909
+ jsonSchema.type = "boolean";
910
+ break;
911
+ case "null":
912
+ if (config?.target === "openapi-3.0") jsonSchema.enum = [null];
913
+ else jsonSchema.type = "null";
914
+ break;
915
+ case "number":
916
+ jsonSchema.type = "number";
917
+ break;
918
+ case "string":
919
+ jsonSchema.type = "string";
920
+ break;
921
+ case "array":
922
+ jsonSchema.type = "array";
923
+ jsonSchema.items = convertSchema({}, valibotSchema.item, config, context);
924
+ break;
925
+ case "tuple":
926
+ case "tuple_with_rest":
927
+ case "loose_tuple":
928
+ case "strict_tuple":
929
+ jsonSchema.type = "array";
930
+ if (config?.target === "openapi-3.0") {
931
+ jsonSchema.items = { anyOf: [] };
932
+ jsonSchema.minItems = valibotSchema.items.length;
933
+ for (const item of valibotSchema.items) jsonSchema.items.anyOf.push(convertSchema({}, item, config, context));
934
+ if (valibotSchema.type === "tuple_with_rest") jsonSchema.items.anyOf.push(convertSchema({}, valibotSchema.rest, config, context));
935
+ else if (valibotSchema.type === "strict_tuple" || valibotSchema.type === "tuple") jsonSchema.maxItems = valibotSchema.items.length;
936
+ } else if (config?.target === "draft-2020-12") {
937
+ jsonSchema.prefixItems = [];
938
+ jsonSchema.minItems = valibotSchema.items.length;
939
+ for (const item of valibotSchema.items) jsonSchema.prefixItems.push(convertSchema({}, item, config, context));
940
+ if (valibotSchema.type === "tuple_with_rest") jsonSchema.items = convertSchema({}, valibotSchema.rest, config, context);
941
+ else if (valibotSchema.type === "strict_tuple") jsonSchema.items = false;
942
+ } else {
943
+ jsonSchema.items = [];
944
+ jsonSchema.minItems = valibotSchema.items.length;
945
+ for (const item of valibotSchema.items) jsonSchema.items.push(convertSchema({}, item, config, context));
946
+ if (valibotSchema.type === "tuple_with_rest") jsonSchema.additionalItems = convertSchema({}, valibotSchema.rest, config, context);
947
+ else if (valibotSchema.type === "strict_tuple") jsonSchema.additionalItems = false;
948
+ }
949
+ break;
950
+ case "object":
951
+ case "object_with_rest":
952
+ case "loose_object":
953
+ case "strict_object":
954
+ jsonSchema.type = "object";
955
+ jsonSchema.properties = {};
956
+ jsonSchema.required = [];
957
+ for (const key in valibotSchema.entries) {
958
+ const entry = valibotSchema.entries[key];
959
+ jsonSchema.properties[key] = convertSchema({}, entry, config, context);
960
+ if (entry.type !== "exact_optional" && entry.type !== "nullish" && entry.type !== "optional") jsonSchema.required.push(key);
961
+ }
962
+ if (valibotSchema.type === "object_with_rest") jsonSchema.additionalProperties = convertSchema({}, valibotSchema.rest, config, context);
963
+ else if (valibotSchema.type === "strict_object") jsonSchema.additionalProperties = false;
964
+ break;
965
+ case "record":
966
+ if (config?.target === "openapi-3.0" && "pipe" in valibotSchema.key) errors = addError(errors, "The \"record\" schema with a schema for the key that contains a \"pipe\" cannot be converted to JSON Schema.");
967
+ if (valibotSchema.key.type !== "string") errors = addError(errors, `The "record" schema with the "${valibotSchema.key.type}" schema for the key cannot be converted to JSON Schema.`);
968
+ jsonSchema.type = "object";
969
+ if (config?.target !== "openapi-3.0") jsonSchema.propertyNames = convertSchema({}, valibotSchema.key, config, context);
970
+ jsonSchema.additionalProperties = convertSchema({}, valibotSchema.value, config, context);
971
+ break;
972
+ case "any":
973
+ case "unknown": break;
974
+ case "never":
975
+ jsonSchema.not = {};
976
+ break;
977
+ case "nullable":
978
+ case "nullish":
979
+ if (config?.target === "openapi-3.0") {
980
+ const innerSchema = convertSchema({}, valibotSchema.wrapped, config, context);
981
+ Object.assign(jsonSchema, innerSchema);
982
+ jsonSchema.nullable = true;
983
+ } else jsonSchema.anyOf = [convertSchema({}, valibotSchema.wrapped, config, context), { type: "null" }];
984
+ if (valibotSchema.default !== void 0) jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default;
985
+ break;
986
+ case "exact_optional":
987
+ case "optional":
988
+ case "undefinedable":
989
+ jsonSchema = convertSchema(jsonSchema, valibotSchema.wrapped, config, context);
990
+ if (valibotSchema.default !== void 0) jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default;
991
+ break;
992
+ case "literal":
993
+ if (!isJsonConstValue(valibotSchema.literal)) {
994
+ errors = addError(errors, "The value of the \"literal\" schema is not JSON compatible.");
995
+ break;
996
+ }
997
+ if (config?.target === "openapi-3.0") jsonSchema.enum = [valibotSchema.literal];
998
+ else jsonSchema.const = valibotSchema.literal;
999
+ break;
1000
+ case "enum":
1001
+ case "picklist": {
1002
+ const options = valibotSchema.options;
1003
+ if (!options.every((option) => typeof option === "string" || typeof option === "number" && Number.isFinite(option))) {
1004
+ errors = addError(errors, `An option of the "${valibotSchema.type}" schema is not JSON compatible.`);
1005
+ break;
1006
+ }
1007
+ jsonSchema.enum = options;
1008
+ if (options.every((option) => typeof option === "string")) jsonSchema.type = "string";
1009
+ else if (options.every((option) => typeof option === "number")) jsonSchema.type = "number";
1010
+ else if (config?.target !== "openapi-3.0") jsonSchema.type = ["string", "number"];
1011
+ break;
1012
+ }
1013
+ case "union":
1014
+ jsonSchema.anyOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
1015
+ break;
1016
+ case "variant":
1017
+ jsonSchema.oneOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
1018
+ break;
1019
+ case "intersect":
1020
+ jsonSchema.allOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
1021
+ break;
1022
+ case "lazy": {
1023
+ let wrappedValibotSchema = context.getterMap.get(valibotSchema.getter);
1024
+ if (!wrappedValibotSchema) {
1025
+ wrappedValibotSchema = valibotSchema.getter(void 0);
1026
+ context.getterMap.set(valibotSchema.getter, wrappedValibotSchema);
1027
+ }
1028
+ let referenceId = context.referenceMap.get(wrappedValibotSchema);
1029
+ if (!referenceId) {
1030
+ referenceId = context.referenceMap.createId(context.definitions);
1031
+ context.referenceMap.set(wrappedValibotSchema, referenceId);
1032
+ context.definitions[referenceId] = convertSchema({}, wrappedValibotSchema, config, context, true);
1033
+ }
1034
+ jsonSchema.$ref = getDefinitionRef(referenceId);
1035
+ if (config?.overrideRef) {
1036
+ const refOverride = config.overrideRef({
1037
+ ...context,
1038
+ referenceId,
1039
+ valibotSchema: wrappedValibotSchema,
1040
+ jsonSchema
1041
+ });
1042
+ if (refOverride) jsonSchema.$ref = refOverride;
1043
+ }
1044
+ break;
1045
+ }
1046
+ default: errors = addError(errors, `The "${valibotSchema.type}" schema cannot be converted to JSON Schema.`);
1047
+ }
1048
+ if (config?.overrideSchema) {
1049
+ const schemaOverride = config.overrideSchema({
1050
+ ...context,
1051
+ referenceId: context.referenceMap.get(valibotSchema),
1052
+ valibotSchema,
1053
+ jsonSchema,
1054
+ errors
1055
+ });
1056
+ if (schemaOverride) return { ...schemaOverride };
1057
+ }
1058
+ if (errors) for (const message of errors) handleError(message, config);
1059
+ return jsonSchema;
1060
+ }
1061
+ /**
1062
+ * Converts a Valibot schema to the JSON Schema format.
1063
+ *
1064
+ * @param schema The Valibot schema object.
1065
+ * @param config The JSON Schema configuration.
1066
+ *
1067
+ * @returns The converted JSON Schema.
1068
+ */
1069
+ function toJsonSchema(schema, config) {
1070
+ const context = {
1071
+ definitions: {},
1072
+ referenceMap: new ReferenceMap(),
1073
+ getterMap: /* @__PURE__ */ new Map()
1074
+ };
1075
+ const definitions = config?.definitions ?? void 0;
1076
+ if (definitions) {
1077
+ for (const key in definitions) context.referenceMap.set(definitions[key], key);
1078
+ for (const key in definitions) context.definitions[key] = convertSchema({}, definitions[key], config, context, true);
1079
+ }
1080
+ const jsonSchema = convertSchema({}, schema, config, context);
1081
+ const target = config?.target ?? "draft-07";
1082
+ if (target === "draft-2020-12") jsonSchema.$schema = "https://json-schema.org/draft/2020-12/schema";
1083
+ else if (target === "draft-07") jsonSchema.$schema = "http://json-schema.org/draft-07/schema#";
1084
+ if (context.referenceMap.size) jsonSchema.$defs = context.definitions;
1085
+ return jsonSchema;
1086
+ }
1087
+ //#endregion
1088
+ //#region ../internal/src/valibot.ts
1089
+ const valibotTargets = /* @__PURE__ */ new Set([
1090
+ "draft-07",
1091
+ "draft-2020-12",
1092
+ "openapi-3.0"
1093
+ ]);
1094
+ function isValibotTarget(value) {
1095
+ return valibotTargets.has(String(value));
1096
+ }
1097
+ /**
1098
+ * Add Standard JSON Schema conversion to a plain Valibot schema. Valibot schemas validate as Standard Schema but carry
1099
+ * no JSON Schema, so forms, tools, and model providers would get no shape for them. Other schemas, Valibot schemas that
1100
+ * already convert, and async Valibot schemas return unchanged. The copy keeps every Valibot property, so validation
1101
+ * does not change.
1102
+ *
1103
+ * `target` fixes the JSON Schema dialect. Without it, each conversion uses the dialect that the caller asks for.
1104
+ */
1105
+ function withValibotJsonSchema(schema, options = {}) {
1106
+ const standard = schema["~standard"];
1107
+ if (standard.vendor !== "valibot" || Reflect.get(schema, "async") === true) return schema;
1108
+ if (Object.hasOwn(standard, "jsonSchema") && standard.jsonSchema) return schema;
1109
+ const convert = (typeMode) => (request) => {
1110
+ const target = options.target ?? request.target;
1111
+ if (!isValibotTarget(target)) throw internalErrorDiagnostics.INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED({ target: String(target) });
1112
+ return toJsonSchema(schema, {
1113
+ target,
1114
+ typeMode,
1115
+ errorMode: "ignore"
1116
+ });
1117
+ };
1118
+ return {
1119
+ ...schema,
1120
+ "~standard": {
1121
+ ...standard,
1122
+ jsonSchema: {
1123
+ input: convert("input"),
1124
+ output: convert("output")
1125
+ }
1126
+ }
1127
+ };
1128
+ }
1129
+ //#endregion
1130
+ //#region ../internal/src/operation-definition.ts
1131
+ const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
1132
+ const kinds = /* @__PURE__ */ new Set([
1133
+ "read",
1134
+ "write",
1135
+ "destructive"
1136
+ ]);
1137
+ function invalidDefinition(name, reason) {
1138
+ return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
1139
+ }
1140
+ function checkDefinition(definition) {
1141
+ if (!isRecordOrFunction(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
1142
+ const { name } = definition;
1143
+ if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
1144
+ if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
1145
+ const { section } = definition;
1146
+ if (section !== false && !(section instanceof Function) && !isSectionId(section)) throw invalidDefinition(name, "section must be a Console section id, a function, or false; section ids cannot contain ':'.");
1147
+ if (definition.scope !== void 0 && (!(definition.scope instanceof Function) || String(section) !== section)) throw invalidDefinition(name, "scope must be a function, and it needs a section id.");
1148
+ if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
1149
+ const input = definition.input;
1150
+ if (!isRecordOrFunction(input) || !isRecordOrFunction(input["~standard"]) || !(input["~standard"].validate instanceof Function)) throw invalidDefinition(name, "input must be a Standard Schema, such as a valibot object.");
1151
+ if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
1152
+ const { maxRequestBytes } = definition;
1153
+ if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
1154
+ if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
1155
+ const { mcp } = definition;
1156
+ if (mcp !== void 0 && mcp !== false && (!isRecordOrFunction(mcp) || mcp.title !== void 0 && (String(mcp.title) !== mcp.title || !mcp.title) || mcp.format !== void 0 && !(mcp.format instanceof Function))) throw invalidDefinition(name, "mcp must be false, or an object with a title string and a format function.");
1157
+ }
1158
+ /** The default limit of a call, in bytes. */
1159
+ const defaultRequestBytes = 65536;
1160
+ /** Input keys that the generated CLI commands read themselves. */
1161
+ const reservedOperationFlags = [
1162
+ "input",
1163
+ "json",
1164
+ "timeout",
1165
+ "url",
1166
+ "yes"
1167
+ ];
1168
+ /**
1169
+ * Define one operation. The Console, the CLI, MCP, and agent tools call the same definition. Contribute it with
1170
+ * `vitehub: { operations: [{ module, export }] }` on a Vite plugin.
1171
+ */
1172
+ function defineOperation(definition) {
1173
+ checkDefinition(definition);
1174
+ const defined = {
1175
+ ...definition,
1176
+ input: withValibotJsonSchema(definition.input)
1177
+ };
1178
+ const properties = operationInputJsonSchema(defined).properties;
1179
+ const clashes = isRecordOrFunction(properties) ? Object.keys(properties).filter((key) => reservedOperationFlags.includes(key)) : [];
1180
+ if (clashes.length) throw invalidDefinition(definition.name, `the input key ${clashes.map((key) => JSON.stringify(key)).join(", ")} is a CLI flag of every command (${reservedOperationFlags.join(", ")}). Rename it.`);
1181
+ return defined;
1182
+ }
1183
+ function isSectionId(section) {
1184
+ return typeof section === "string" && section !== "" && !section.includes(":");
1185
+ }
1186
+ /** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
1187
+ function operationInputJsonSchema(operation) {
1188
+ return standardJsonSchema(operation.input, "input") ?? { type: "object" };
1189
+ }
1190
+ //#endregion
1191
+ //#region src/operations.ts
1192
+ const runtime = () => import("./runtime.js");
1193
+ /** The HTTP status that the CLI, the Console, and Agents report for each code of a failed operation. */
1194
+ const statuses = {
1195
+ WEBHOOKS_BODY_INVALID: 400,
1196
+ WEBHOOKS_DATABASE_MISSING: 409,
1197
+ WEBHOOKS_DELIVERY_ACTIVE: 409,
1198
+ WEBHOOKS_DELIVERY_NOT_FOUND: 404,
1199
+ WEBHOOKS_DELIVERY_NOT_PENDING: 409,
1200
+ WEBHOOKS_NOT_FOUND: 404,
1201
+ WEBHOOKS_NOT_INSTALLED: 409,
1202
+ WEBHOOKS_SECRET_UNSET: 409,
1203
+ WEBHOOKS_STORE_FAILED: 500,
1204
+ WEBHOOKS_URL_INVALID: 409,
1205
+ WEBHOOKS_URL_UNSET: 409,
1206
+ WEBHOOKS_WAKE_FAILED: 502
1207
+ };
1208
+ /** Gives a Webhooks error the status that the surfaces report. Other errors pass unchanged. */
1209
+ function failure(error) {
1210
+ return webhooksErrors.is(error) ? Object.assign(error, { status: statuses[error.code] ?? 500 }) : error;
1211
+ }
1212
+ /** Runs a runtime function and throws its error, so the operation fails with the code, `why`, and `fix`. */
1213
+ async function unwrap(run) {
1214
+ let result;
1215
+ try {
1216
+ result = await run();
1217
+ } catch (error) {
1218
+ throw failure(error);
1219
+ }
1220
+ if (result[0]) throw failure(result[0]);
1221
+ return result[1];
1222
+ }
1223
+ function defineWebhooksOperation(definition) {
1224
+ return defineOperation({
1225
+ ...definition,
1226
+ cli: {
1227
+ namespace: "webhooks",
1228
+ ...definition.cli
1229
+ },
1230
+ section: "webhooks",
1231
+ user: false
1232
+ });
1233
+ }
1234
+ const webhookName = v.pipe(v.string(), v.minLength(1), v.description("The webhook name, the file name of server/webhooks/<name>.ts."));
1235
+ const deliveryId = v.pipe(v.string(), v.minLength(1), v.description("The delivery id, such as whd_..."));
1236
+ const limit = v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(500), v.description("At most this many, from 1 to 500. Default: 100.")));
1237
+ /**
1238
+ * The `webhooks.*` operations. The Console, `vitehub webhooks`, and MCP run them on the app's operation RPC, `POST
1239
+ * /_vitehub/rpc`.
1240
+ */
1241
+ const webhooksOperations = [
1242
+ defineWebhooksOperation({
1243
+ cli: { default: true },
1244
+ description: "List the webhooks of the app: the names of their URL and secret variables, whether each is set, the URL host, the signature, and the debounce. Never the URL path, the query, or the secret.",
1245
+ input: v.strictObject({}),
1246
+ kind: "read",
1247
+ name: "webhooks.list",
1248
+ run: async () => {
1249
+ const { listWebhooks } = await runtime();
1250
+ try {
1251
+ return listWebhooks();
1252
+ } catch (error) {
1253
+ throw failure(error);
1254
+ }
1255
+ }
1256
+ }),
1257
+ defineWebhooksOperation({
1258
+ description: "List webhook deliveries, newest first, with their state, attempts, last status, and last error.",
1259
+ input: v.strictObject({
1260
+ webhook: v.optional(webhookName),
1261
+ state: v.optional(v.picklist([
1262
+ "pending",
1263
+ "sending",
1264
+ "sent",
1265
+ "dead",
1266
+ "cancelled"
1267
+ ])),
1268
+ limit,
1269
+ before: v.optional(v.pipe(v.strictObject({
1270
+ createdAt: v.number(),
1271
+ id: v.string()
1272
+ }), v.description("The createdAt and id of the last delivery of the previous page.")))
1273
+ }),
1274
+ kind: "read",
1275
+ name: "webhooks.deliveries",
1276
+ run: async (input) => unwrap(async () => (await runtime()).listWebhookDeliveries(input))
1277
+ }),
1278
+ defineWebhooksOperation({
1279
+ description: "List the pending webhook deliveries, the soonest due first: the debounce timers that wait now.",
1280
+ input: v.strictObject({
1281
+ webhook: v.optional(webhookName),
1282
+ limit
1283
+ }),
1284
+ kind: "read",
1285
+ name: "webhooks.pending",
1286
+ run: async (input) => unwrap(async () => (await runtime()).listPendingWebhookDeliveries(input))
1287
+ }),
1288
+ defineWebhooksOperation({
1289
+ cli: { positional: ["id"] },
1290
+ description: "Show one webhook delivery with its body.",
1291
+ input: v.strictObject({ id: deliveryId }),
1292
+ kind: "read",
1293
+ name: "webhooks.get",
1294
+ run: async (input) => unwrap(async () => (await runtime()).getWebhookDelivery(input.id))
1295
+ }),
1296
+ defineWebhooksOperation({
1297
+ cli: { positional: ["name"] },
1298
+ description: "Send a test delivery to a webhook now, without its debounce, with the event webhooks.test. The body is a JSON value; the default is { test: true, webhook: <name> }.",
1299
+ input: v.strictObject({
1300
+ name: webhookName,
1301
+ body: v.optional(v.unknown())
1302
+ }),
1303
+ kind: "write",
1304
+ name: "webhooks.test",
1305
+ run: async (input) => unwrap(async () => (await runtime()).testWebhook(input.name, input.body === void 0 ? {} : { body: input.body }))
1306
+ }),
1307
+ defineWebhooksOperation({
1308
+ cli: { positional: ["id"] },
1309
+ description: "Deliver a pending webhook delivery now, without the rest of its debounce.",
1310
+ input: v.strictObject({ id: deliveryId }),
1311
+ kind: "write",
1312
+ name: "webhooks.flush",
1313
+ run: async (input) => unwrap(async () => (await runtime()).flushWebhookDelivery(input.id))
1314
+ }),
1315
+ defineWebhooksOperation({
1316
+ cli: { positional: ["id"] },
1317
+ description: "Cancel a pending webhook delivery, so it is never sent.",
1318
+ input: v.strictObject({ id: deliveryId }),
1319
+ kind: "write",
1320
+ name: "webhooks.cancel",
1321
+ run: async (input) => unwrap(async () => (await runtime()).cancelWebhookDelivery(input.id))
1322
+ }),
1323
+ defineWebhooksOperation({
1324
+ cli: { positional: ["id"] },
1325
+ description: "Send a sent, dead, or cancelled webhook delivery again now, as a new delivery with the same body and event.",
1326
+ input: v.strictObject({ id: deliveryId }),
1327
+ kind: "write",
1328
+ name: "webhooks.redeliver",
1329
+ run: async (input) => unwrap(async () => (await runtime()).redeliverWebhookDelivery(input.id))
1330
+ })
1331
+ ];
1332
+ //#endregion
1333
+ export { webhooksOperations };