rolldown
Version:
Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.
1,647 lines (1,632 loc) • 148 kB
JavaScript
import { BindingAttachDebugInfo, BindingBundler, BindingCallableBuiltinPlugin, BindingChunkModuleOrderBy, BindingJsx, BindingLogLevel, BindingPluginOrder, BindingWatcher, ParallelJsPluginRegistry, augmentCodeLocation, error, logCycleLoading, logDuplicateJsxConfig, logInputHookInOutputPlugin, logInvalidLogPosition, logMultiplyNotifyOption, logPluginError, parseAst, shutdownAsyncRuntime, startAsyncRuntime } from "./parse-ast-index-BsbuAWqn.mjs";
import { arraify, noop, unimplemented, unreachable, unsupported } from "./misc-CQeo-AFx.mjs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import colors from "ansis";
import * as filter from "@rolldown/pluginutils";
import fsp from "node:fs/promises";
import os from "node:os";
import { Worker } from "node:worker_threads";
//#region package.json
var version = "1.0.0-beta.33";
var description$1 = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.";
//#endregion
//#region src/utils/normalize-string-or-regex.ts
function normalizedStringOrRegex(pattern) {
if (!pattern) return void 0;
if (!isReadonlyArray(pattern)) return [pattern];
return pattern;
}
function isReadonlyArray(input) {
return Array.isArray(input);
}
//#endregion
//#region src/builtin-plugin/utils.ts
function makeBuiltinPluginCallable(plugin) {
let callablePlugin = new BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin));
const wrappedPlugin = plugin;
for (const key in callablePlugin) wrappedPlugin[key] = async function(...args$1) {
try {
return await callablePlugin[key](...args$1);
} catch (e$1) {
if (e$1 instanceof Error && !e$1.stack?.includes("at ")) Error.captureStackTrace(e$1, wrappedPlugin[key]);
return error(logPluginError(e$1, plugin.name, {
hook: key,
id: key === "transform" ? args$1[2] : void 0
}));
}
};
return wrappedPlugin;
}
function bindingifyBuiltInPlugin(plugin) {
return {
__name: plugin.name,
options: plugin._options
};
}
//#endregion
//#region src/builtin-plugin/constructors.ts
var BuiltinPlugin = class {
constructor(name, _options) {
this.name = name;
this._options = _options;
}
};
function modulePreloadPolyfillPlugin(config) {
return new BuiltinPlugin("builtin:module-preload-polyfill", config);
}
function dynamicImportVarsPlugin(config) {
if (config) {
config.include = normalizedStringOrRegex(config.include);
config.exclude = normalizedStringOrRegex(config.exclude);
}
return new BuiltinPlugin("builtin:dynamic-import-vars", config);
}
function importGlobPlugin(config) {
return new BuiltinPlugin("builtin:import-glob", config);
}
function reporterPlugin(config) {
return new BuiltinPlugin("builtin:reporter", config);
}
function manifestPlugin(config) {
return new BuiltinPlugin("builtin:manifest", config);
}
function wasmHelperPlugin(config) {
return new BuiltinPlugin("builtin:wasm-helper", config);
}
function wasmFallbackPlugin() {
const builtinPlugin = new BuiltinPlugin("builtin:wasm-fallback");
return makeBuiltinPluginCallable(builtinPlugin);
}
function loadFallbackPlugin() {
return new BuiltinPlugin("builtin:load-fallback");
}
function jsonPlugin(config) {
const builtinPlugin = new BuiltinPlugin("builtin:json", config);
return makeBuiltinPluginCallable(builtinPlugin);
}
function buildImportAnalysisPlugin(config) {
return new BuiltinPlugin("builtin:build-import-analysis", config);
}
function viteResolvePlugin(config) {
const builtinPlugin = new BuiltinPlugin("builtin:vite-resolve", config);
return makeBuiltinPluginCallable(builtinPlugin);
}
function isolatedDeclarationPlugin(config) {
return new BuiltinPlugin("builtin:isolated-declaration", config);
}
function assetPlugin(config) {
return new BuiltinPlugin("builtin:asset", config);
}
function webWorkerPostPlugin() {
return new BuiltinPlugin("builtin:web-worker-post");
}
function oxcRuntimePlugin(config) {
return new BuiltinPlugin("builtin:oxc-runtime", config);
}
//#endregion
//#region src/log/logging.ts
const LOG_LEVEL_SILENT = "silent";
const LOG_LEVEL_ERROR = "error";
const LOG_LEVEL_WARN = "warn";
const LOG_LEVEL_INFO = "info";
const LOG_LEVEL_DEBUG = "debug";
const logLevelPriority = {
[LOG_LEVEL_DEBUG]: 0,
[LOG_LEVEL_INFO]: 1,
[LOG_LEVEL_WARN]: 2,
[LOG_LEVEL_SILENT]: 3
};
//#endregion
//#region src/log/log-handler.ts
const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
function getLogHandler(level, code, logger, pluginName, logLevel) {
if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
return (log, pos) => {
if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
log = normalizeLog(log);
if (log.code && !log.pluginCode) log.pluginCode = log.code;
log.code = code;
log.plugin = pluginName;
logger(level, log);
};
}
//#endregion
//#region src/log/logger.ts
function getLogger(plugins, onLog, logLevel, watchMode) {
const minimalPriority = logLevelPriority[logLevel];
const logger = (level, log, skipped = /* @__PURE__ */ new Set()) => {
const logPriority = logLevelPriority[level];
if (logPriority < minimalPriority) return;
for (const plugin of getSortedPlugins("onLog", plugins)) {
if (skipped.has(plugin)) continue;
const { onLog: pluginOnLog } = plugin;
if (pluginOnLog) {
const getLogHandler$1 = (level$1) => {
if (logLevelPriority[level$1] < minimalPriority) return () => {};
return (log$1) => logger(level$1, normalizeLog(log$1), new Set(skipped).add(plugin));
};
const handler = "handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
if (handler.call({
debug: getLogHandler$1(LOG_LEVEL_DEBUG),
error: (log$1) => error(normalizeLog(log$1)),
info: getLogHandler$1(LOG_LEVEL_INFO),
meta: {
rollupVersion: "4.23.0",
rolldownVersion: VERSION,
watchMode
},
warn: getLogHandler$1(LOG_LEVEL_WARN),
pluginName: plugin.name || "unknown"
}, level, log) === false) return;
}
}
onLog(level, log);
};
return logger;
}
const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
const { onwarn, onLog } = config;
const defaultOnLog = getDefaultOnLog(printLog, onwarn);
if (onLog) {
const minimalPriority = logLevelPriority[logLevel];
return (level, log) => onLog(level, addLogToString(log), (level$1, handledLog) => {
if (level$1 === LOG_LEVEL_ERROR) return error(normalizeLog(handledLog));
if (logLevelPriority[level$1] >= minimalPriority) defaultOnLog(level$1, normalizeLog(handledLog));
});
}
return defaultOnLog;
};
const getDefaultOnLog = (printLog, onwarn) => onwarn ? (level, log) => {
if (level === LOG_LEVEL_WARN) onwarn(addLogToString(log), (warning) => printLog(LOG_LEVEL_WARN, normalizeLog(warning)));
else printLog(level, log);
} : printLog;
const addLogToString = (log) => {
Object.defineProperty(log, "toString", {
value: () => getExtendedLogMessage(log),
writable: true
});
return log;
};
const defaultPrintLog = (level, log) => {
const message = getExtendedLogMessage(log);
switch (level) {
case LOG_LEVEL_WARN: return console.warn(message);
case LOG_LEVEL_DEBUG: return console.debug(message);
default: return console.info(message);
}
};
const getExtendedLogMessage = (log) => {
let prefix = "";
if (log.plugin) prefix += `(${log.plugin} plugin) `;
if (log.loc) prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
return prefix + log.message;
};
function relativeId(id) {
if (!path.isAbsolute(id)) return id;
return path.relative(path.resolve(), id);
}
//#endregion
//#region src/utils/normalize-hook.ts
function normalizeHook(hook) {
if (typeof hook === "function" || typeof hook === "string") return {
handler: hook,
options: {},
meta: {}
};
if (typeof hook === "object" && hook !== null) {
const { handler, order,...options } = hook;
return {
handler,
options,
meta: { order }
};
}
unreachable("Invalid hook type");
}
//#endregion
//#region src/constants/plugin.ts
const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES = [
"options",
"buildStart",
"resolveId",
"load",
"transform",
"moduleParsed",
"buildEnd",
"onLog",
"resolveDynamicImport",
"closeBundle",
"closeWatcher",
"watchChange"
];
const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES = [
"augmentChunkHash",
"outputOptions",
"renderChunk",
"renderStart",
"renderError",
"writeBundle",
"generateBundle"
];
const ENUMERATED_PLUGIN_HOOK_NAMES = [
...ENUMERATED_INPUT_PLUGIN_HOOK_NAMES,
...ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES,
"footer",
"banner",
"intro",
"outro"
];
/**
* Names of all defined hooks. It's like
* ```js
* const DEFINED_HOOK_NAMES ={
* options: 'options',
* buildStart: 'buildStart',
* ...
* }
* ```
*/
const DEFINED_HOOK_NAMES = {
[ENUMERATED_PLUGIN_HOOK_NAMES[0]]: ENUMERATED_PLUGIN_HOOK_NAMES[0],
[ENUMERATED_PLUGIN_HOOK_NAMES[1]]: ENUMERATED_PLUGIN_HOOK_NAMES[1],
[ENUMERATED_PLUGIN_HOOK_NAMES[2]]: ENUMERATED_PLUGIN_HOOK_NAMES[2],
[ENUMERATED_PLUGIN_HOOK_NAMES[3]]: ENUMERATED_PLUGIN_HOOK_NAMES[3],
[ENUMERATED_PLUGIN_HOOK_NAMES[4]]: ENUMERATED_PLUGIN_HOOK_NAMES[4],
[ENUMERATED_PLUGIN_HOOK_NAMES[5]]: ENUMERATED_PLUGIN_HOOK_NAMES[5],
[ENUMERATED_PLUGIN_HOOK_NAMES[6]]: ENUMERATED_PLUGIN_HOOK_NAMES[6],
[ENUMERATED_PLUGIN_HOOK_NAMES[7]]: ENUMERATED_PLUGIN_HOOK_NAMES[7],
[ENUMERATED_PLUGIN_HOOK_NAMES[8]]: ENUMERATED_PLUGIN_HOOK_NAMES[8],
[ENUMERATED_PLUGIN_HOOK_NAMES[9]]: ENUMERATED_PLUGIN_HOOK_NAMES[9],
[ENUMERATED_PLUGIN_HOOK_NAMES[10]]: ENUMERATED_PLUGIN_HOOK_NAMES[10],
[ENUMERATED_PLUGIN_HOOK_NAMES[11]]: ENUMERATED_PLUGIN_HOOK_NAMES[11],
[ENUMERATED_PLUGIN_HOOK_NAMES[12]]: ENUMERATED_PLUGIN_HOOK_NAMES[12],
[ENUMERATED_PLUGIN_HOOK_NAMES[13]]: ENUMERATED_PLUGIN_HOOK_NAMES[13],
[ENUMERATED_PLUGIN_HOOK_NAMES[14]]: ENUMERATED_PLUGIN_HOOK_NAMES[14],
[ENUMERATED_PLUGIN_HOOK_NAMES[15]]: ENUMERATED_PLUGIN_HOOK_NAMES[15],
[ENUMERATED_PLUGIN_HOOK_NAMES[16]]: ENUMERATED_PLUGIN_HOOK_NAMES[16],
[ENUMERATED_PLUGIN_HOOK_NAMES[17]]: ENUMERATED_PLUGIN_HOOK_NAMES[17],
[ENUMERATED_PLUGIN_HOOK_NAMES[18]]: ENUMERATED_PLUGIN_HOOK_NAMES[18],
[ENUMERATED_PLUGIN_HOOK_NAMES[19]]: ENUMERATED_PLUGIN_HOOK_NAMES[19],
[ENUMERATED_PLUGIN_HOOK_NAMES[20]]: ENUMERATED_PLUGIN_HOOK_NAMES[20],
[ENUMERATED_PLUGIN_HOOK_NAMES[21]]: ENUMERATED_PLUGIN_HOOK_NAMES[21],
[ENUMERATED_PLUGIN_HOOK_NAMES[22]]: ENUMERATED_PLUGIN_HOOK_NAMES[22]
};
//#endregion
//#region src/utils/async-flatten.ts
async function asyncFlatten(array$1) {
do
array$1 = (await Promise.all(array$1)).flat(Infinity);
while (array$1.some((v) => v?.then));
return array$1;
}
//#endregion
//#region src/utils/normalize-plugin-option.ts
const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
function checkOutputPluginOption(plugins, onLog) {
for (const plugin of plugins) for (const hook of ENUMERATED_INPUT_PLUGIN_HOOK_NAMES) if (hook in plugin) {
delete plugin[hook];
onLog(LOG_LEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
}
return plugins;
}
function normalizePlugins(plugins, anonymousPrefix) {
for (const [index, plugin] of plugins.entries()) {
if ("_parallel" in plugin) continue;
if (plugin instanceof BuiltinPlugin) continue;
if (!plugin.name) plugin.name = `${anonymousPrefix}${index + 1}`;
}
return plugins;
}
const ANONYMOUS_PLUGIN_PREFIX = "at position ";
const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = "at output position ";
const BUILTIN_PLUGINS = [oxcRuntimePlugin({ resolveBase: fileURLToPath(import.meta.url) })];
//#endregion
//#region src/plugin/minimal-plugin-context.ts
var MinimalPluginContextImpl = class {
info;
warn;
debug;
meta;
constructor(onLog, logLevel, pluginName, watchMode, hookName) {
this.pluginName = pluginName;
this.hookName = hookName;
this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
this.meta = {
rollupVersion: "4.23.0",
rolldownVersion: VERSION,
watchMode
};
}
error(e$1) {
return error(logPluginError(normalizeLog(e$1), this.pluginName, { hook: this.hookName }));
}
};
//#endregion
//#region src/plugin/plugin-driver.ts
var PluginDriver = class {
static async callOptionsHook(inputOptions, watchMode = false) {
const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins)));
const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel, watchMode);
for (const plugin of plugins) {
const name = plugin.name || "unknown";
const options = plugin.options;
if (options) {
const { handler } = normalizeHook(options);
const result = await handler.call(new MinimalPluginContextImpl(logger, logLevel, name, watchMode, "onLog"), inputOptions);
if (result) inputOptions = result;
}
}
return inputOptions;
}
static callOutputOptionsHook(rawPlugins, outputOptions, onLog, logLevel, watchMode) {
const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins));
for (const plugin of sortedPlugins) {
const name = plugin.name || "unknown";
const options = plugin.outputOptions;
if (options) {
const { handler } = normalizeHook(options);
const result = handler.call(new MinimalPluginContextImpl(onLog, logLevel, name, watchMode), outputOptions);
if (result) outputOptions = result;
}
}
return outputOptions;
}
};
function getObjectPlugins(plugins) {
return plugins.filter((plugin) => {
if (!plugin) return void 0;
if ("_parallel" in plugin) return void 0;
if (plugin instanceof BuiltinPlugin) return void 0;
return plugin;
});
}
function getSortedPlugins(hookName, plugins) {
const pre = [];
const normal = [];
const post = [];
for (const plugin of plugins) {
const hook = plugin[hookName];
if (hook) {
if (typeof hook === "object") {
if (hook.order === "pre") {
pre.push(plugin);
continue;
}
if (hook.order === "post") {
post.push(plugin);
continue;
}
}
normal.push(plugin);
}
}
return [
...pre,
...normal,
...post
];
}
//#endregion
//#region ../../node_modules/.pnpm/valibot@1.1.0_typescript@5.9.2/node_modules/valibot/dist/index.js
var store$1;
/* @__NO_SIDE_EFFECTS__ */
function getGlobalConfig(config2) {
return {
lang: config2?.lang ?? store$1?.lang,
message: config2?.message,
abortEarly: config2?.abortEarly ?? store$1?.abortEarly,
abortPipeEarly: config2?.abortPipeEarly ?? store$1?.abortPipeEarly
};
}
var store2;
/* @__NO_SIDE_EFFECTS__ */
function getGlobalMessage(lang) {
return store2?.get(lang);
}
var store3;
/* @__NO_SIDE_EFFECTS__ */
function getSchemaMessage(lang) {
return store3?.get(lang);
}
var store4;
/* @__NO_SIDE_EFFECTS__ */
function getSpecificMessage(reference, lang) {
return store4?.get(reference)?.get(lang);
}
/* @__NO_SIDE_EFFECTS__ */
function _stringify(input) {
const type = typeof input;
if (type === "string") return `"${input}"`;
if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
return type;
}
function _addIssue(context, label, dataset, config2, other) {
const input = other && "input" in other ? other.input : dataset.value;
const expected = other?.expected ?? context.expects ?? null;
const received = other?.received ?? /* @__PURE__ */ _stringify(input);
const issue = {
kind: context.kind,
type: context.type,
input,
expected,
received,
message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
requirement: context.requirement,
path: other?.path,
issues: other?.issues,
lang: config2.lang,
abortEarly: config2.abortEarly,
abortPipeEarly: config2.abortPipeEarly
};
const isSchema = context.kind === "schema";
const message2 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config2.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
if (message2 !== void 0) issue.message = typeof message2 === "function" ? message2(issue) : message2;
if (isSchema) dataset.typed = false;
if (dataset.issues) dataset.issues.push(issue);
else dataset.issues = [issue];
}
/* @__NO_SIDE_EFFECTS__ */
function _getStandardProps(context) {
return {
version: 1,
vendor: "valibot",
validate(value2) {
return context["~run"]({ value: value2 }, /* @__PURE__ */ getGlobalConfig());
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function _isValidObjectKey(object2, key) {
return Object.hasOwn(object2, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
}
/* @__NO_SIDE_EFFECTS__ */
function _joinExpects(values2, separator) {
const list = [...new Set(values2)];
if (list.length > 1) return `(${list.join(` ${separator} `)})`;
return list[0] ?? "never";
}
var ValiError = class extends Error {
/**
* Creates a Valibot error with useful information.
*
* @param issues The error issues.
*/
constructor(issues) {
super(issues[0].message);
this.name = "ValiError";
this.issues = issues;
}
};
/* @__NO_SIDE_EFFECTS__ */
function args(schema) {
return {
kind: "transformation",
type: "args",
reference: args,
async: false,
schema,
"~run"(dataset, config2) {
const func = dataset.value;
dataset.value = (...args_) => {
const argsDataset = this.schema["~run"]({ value: args_ }, config2);
if (argsDataset.issues) throw new ValiError(argsDataset.issues);
return func(...argsDataset.value);
};
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function awaitAsync() {
return {
kind: "transformation",
type: "await",
reference: awaitAsync,
async: true,
async "~run"(dataset) {
dataset.value = await dataset.value;
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function description(description_) {
return {
kind: "metadata",
type: "description",
reference: description,
description: description_
};
}
/* @__NO_SIDE_EFFECTS__ */
function returns(schema) {
return {
kind: "transformation",
type: "returns",
reference: returns,
async: false,
schema,
"~run"(dataset, config2) {
const func = dataset.value;
dataset.value = (...args_) => {
const returnsDataset = this.schema["~run"]({ value: func(...args_) }, config2);
if (returnsDataset.issues) throw new ValiError(returnsDataset.issues);
return returnsDataset.value;
};
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function returnsAsync(schema) {
return {
kind: "transformation",
type: "returns",
reference: returnsAsync,
async: false,
schema,
"~run"(dataset, config2) {
const func = dataset.value;
dataset.value = async (...args_) => {
const returnsDataset = await this.schema["~run"]({ value: await func(...args_) }, config2);
if (returnsDataset.issues) throw new ValiError(returnsDataset.issues);
return returnsDataset.value;
};
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function getFallback(schema, dataset, config2) {
return typeof schema.fallback === "function" ? schema.fallback(dataset, config2) : schema.fallback;
}
/* @__NO_SIDE_EFFECTS__ */
function getDefault(schema, dataset, config2) {
return typeof schema.default === "function" ? schema.default(dataset, config2) : schema.default;
}
/* @__NO_SIDE_EFFECTS__ */
function any() {
return {
kind: "schema",
type: "any",
reference: any,
expects: "any",
async: false,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset) {
dataset.typed = true;
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function array(item, message2) {
return {
kind: "schema",
type: "array",
reference: array,
expects: "Array",
async: false,
item,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
const input = dataset.value;
if (Array.isArray(input)) {
dataset.typed = true;
dataset.value = [];
for (let key = 0; key < input.length; key++) {
const value2 = input[key];
const itemDataset = this.item["~run"]({ value: value2 }, config2);
if (itemDataset.issues) {
const pathItem = {
type: "array",
origin: "value",
input,
key,
value: value2
};
for (const issue of itemDataset.issues) {
if (issue.path) issue.path.unshift(pathItem);
else issue.path = [pathItem];
dataset.issues?.push(issue);
}
if (!dataset.issues) dataset.issues = itemDataset.issues;
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!itemDataset.typed) dataset.typed = false;
dataset.value.push(itemDataset.value);
}
} else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function boolean(message2) {
return {
kind: "schema",
type: "boolean",
reference: boolean,
expects: "boolean",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (typeof dataset.value === "boolean") dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function custom(check2, message2) {
return {
kind: "schema",
type: "custom",
reference: custom,
expects: "unknown",
async: false,
check: check2,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (this.check(dataset.value)) dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function function_(message2) {
return {
kind: "schema",
type: "function",
reference: function_,
expects: "Function",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (typeof dataset.value === "function") dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function instance(class_, message2) {
return {
kind: "schema",
type: "instance",
reference: instance,
expects: class_.name,
async: false,
class: class_,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (dataset.value instanceof this.class) dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function literal(literal_, message2) {
return {
kind: "schema",
type: "literal",
reference: literal,
expects: /* @__PURE__ */ _stringify(literal_),
async: false,
literal: literal_,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (dataset.value === this.literal) dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function looseObject(entries2, message2) {
return {
kind: "schema",
type: "loose_object",
reference: looseObject,
expects: "Object",
async: false,
entries: entries2,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
const input = dataset.value;
if (input && typeof input === "object") {
dataset.typed = true;
dataset.value = {};
for (const key in this.entries) {
const valueSchema = this.entries[key];
if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
if (valueDataset.issues) {
const pathItem = {
type: "object",
origin: "value",
input,
key,
value: value2
};
for (const issue of valueDataset.issues) {
if (issue.path) issue.path.unshift(pathItem);
else issue.path = [pathItem];
dataset.issues?.push(issue);
}
if (!dataset.issues) dataset.issues = valueDataset.issues;
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!valueDataset.typed) dataset.typed = false;
dataset.value[key] = valueDataset.value;
} else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
_addIssue(this, "key", dataset, config2, {
input: void 0,
expected: `"${key}"`,
path: [{
type: "object",
origin: "key",
input,
key,
value: input[key]
}]
});
if (config2.abortEarly) break;
}
}
if (!dataset.issues || !config2.abortEarly) {
for (const key in input) if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)) dataset.value[key] = input[key];
}
} else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function never(message2) {
return {
kind: "schema",
type: "never",
reference: never,
expects: "never",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
_addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function nullish(wrapped, default_) {
return {
kind: "schema",
type: "nullish",
reference: nullish,
expects: `(${wrapped.expects} | null | undefined)`,
async: false,
wrapped,
default: default_,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (dataset.value === null || dataset.value === void 0) {
if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2);
if (dataset.value === null || dataset.value === void 0) {
dataset.typed = true;
return dataset;
}
}
return this.wrapped["~run"](dataset, config2);
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function number(message2) {
return {
kind: "schema",
type: "number",
reference: number,
expects: "number",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function object(entries2, message2) {
return {
kind: "schema",
type: "object",
reference: object,
expects: "Object",
async: false,
entries: entries2,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
const input = dataset.value;
if (input && typeof input === "object") {
dataset.typed = true;
dataset.value = {};
for (const key in this.entries) {
const valueSchema = this.entries[key];
if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
if (valueDataset.issues) {
const pathItem = {
type: "object",
origin: "value",
input,
key,
value: value2
};
for (const issue of valueDataset.issues) {
if (issue.path) issue.path.unshift(pathItem);
else issue.path = [pathItem];
dataset.issues?.push(issue);
}
if (!dataset.issues) dataset.issues = valueDataset.issues;
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!valueDataset.typed) dataset.typed = false;
dataset.value[key] = valueDataset.value;
} else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
_addIssue(this, "key", dataset, config2, {
input: void 0,
expected: `"${key}"`,
path: [{
type: "object",
origin: "key",
input,
key,
value: input[key]
}]
});
if (config2.abortEarly) break;
}
}
} else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function optional(wrapped, default_) {
return {
kind: "schema",
type: "optional",
reference: optional,
expects: `(${wrapped.expects} | undefined)`,
async: false,
wrapped,
default: default_,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (dataset.value === void 0) {
if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2);
if (dataset.value === void 0) {
dataset.typed = true;
return dataset;
}
}
return this.wrapped["~run"](dataset, config2);
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function picklist(options, message2) {
return {
kind: "schema",
type: "picklist",
reference: picklist,
expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), "|"),
async: false,
options,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (this.options.includes(dataset.value)) dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function promise(message2) {
return {
kind: "schema",
type: "promise",
reference: promise,
expects: "Promise",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (dataset.value instanceof Promise) dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function record(key, value2, message2) {
return {
kind: "schema",
type: "record",
reference: record,
expects: "Object",
async: false,
key,
value: value2,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
const input = dataset.value;
if (input && typeof input === "object") {
dataset.typed = true;
dataset.value = {};
for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
const entryValue = input[entryKey];
const keyDataset = this.key["~run"]({ value: entryKey }, config2);
if (keyDataset.issues) {
const pathItem = {
type: "object",
origin: "key",
input,
key: entryKey,
value: entryValue
};
for (const issue of keyDataset.issues) {
issue.path = [pathItem];
dataset.issues?.push(issue);
}
if (!dataset.issues) dataset.issues = keyDataset.issues;
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
const valueDataset = this.value["~run"]({ value: entryValue }, config2);
if (valueDataset.issues) {
const pathItem = {
type: "object",
origin: "value",
input,
key: entryKey,
value: entryValue
};
for (const issue of valueDataset.issues) {
if (issue.path) issue.path.unshift(pathItem);
else issue.path = [pathItem];
dataset.issues?.push(issue);
}
if (!dataset.issues) dataset.issues = valueDataset.issues;
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;
}
} else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function strictObject(entries2, message2) {
return {
kind: "schema",
type: "strict_object",
reference: strictObject,
expects: "Object",
async: false,
entries: entries2,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
const input = dataset.value;
if (input && typeof input === "object") {
dataset.typed = true;
dataset.value = {};
for (const key in this.entries) {
const valueSchema = this.entries[key];
if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
if (valueDataset.issues) {
const pathItem = {
type: "object",
origin: "value",
input,
key,
value: value2
};
for (const issue of valueDataset.issues) {
if (issue.path) issue.path.unshift(pathItem);
else issue.path = [pathItem];
dataset.issues?.push(issue);
}
if (!dataset.issues) dataset.issues = valueDataset.issues;
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!valueDataset.typed) dataset.typed = false;
dataset.value[key] = valueDataset.value;
} else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
_addIssue(this, "key", dataset, config2, {
input: void 0,
expected: `"${key}"`,
path: [{
type: "object",
origin: "key",
input,
key,
value: input[key]
}]
});
if (config2.abortEarly) break;
}
}
if (!dataset.issues || !config2.abortEarly) {
for (const key in input) if (!(key in this.entries)) {
_addIssue(this, "key", dataset, config2, {
input: key,
expected: "never",
path: [{
type: "object",
origin: "key",
input,
key,
value: input[key]
}]
});
break;
}
}
} else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function string(message2) {
return {
kind: "schema",
type: "string",
reference: string,
expects: "string",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (typeof dataset.value === "string") dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function tuple(items, message2) {
return {
kind: "schema",
type: "tuple",
reference: tuple,
expects: "Array",
async: false,
items,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
const input = dataset.value;
if (Array.isArray(input)) {
dataset.typed = true;
dataset.value = [];
for (let key = 0; key < this.items.length; key++) {
const value2 = input[key];
const itemDataset = this.items[key]["~run"]({ value: value2 }, config2);
if (itemDataset.issues) {
const pathItem = {
type: "array",
origin: "value",
input,
key,
value: value2
};
for (const issue of itemDataset.issues) {
if (issue.path) issue.path.unshift(pathItem);
else issue.path = [pathItem];
dataset.issues?.push(issue);
}
if (!dataset.issues) dataset.issues = itemDataset.issues;
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!itemDataset.typed) dataset.typed = false;
dataset.value.push(itemDataset.value);
}
} else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function _subIssues(datasets) {
let issues;
if (datasets) for (const dataset of datasets) if (issues) issues.push(...dataset.issues);
else issues = dataset.issues;
return issues;
}
/* @__NO_SIDE_EFFECTS__ */
function union(options, message2) {
return {
kind: "schema",
type: "union",
reference: union,
expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
async: false,
options,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
let validDataset;
let typedDatasets;
let untypedDatasets;
for (const schema of this.options) {
const optionDataset = schema["~run"]({ value: dataset.value }, config2);
if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);
else typedDatasets = [optionDataset];
else {
validDataset = optionDataset;
break;
}
else if (untypedDatasets) untypedDatasets.push(optionDataset);
else untypedDatasets = [optionDataset];
}
if (validDataset) return validDataset;
if (typedDatasets) {
if (typedDatasets.length === 1) return typedDatasets[0];
_addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
dataset.typed = true;
} else if (untypedDatasets?.length === 1) return untypedDatasets[0];
else _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function unionAsync(options, message2) {
return {
kind: "schema",
type: "union",
reference: unionAsync,
expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
async: true,
options,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
async "~run"(dataset, config2) {
let validDataset;
let typedDatasets;
let untypedDatasets;
for (const schema of this.options) {
const optionDataset = await schema["~run"]({ value: dataset.value }, config2);
if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);
else typedDatasets = [optionDataset];
else {
validDataset = optionDataset;
break;
}
else if (untypedDatasets) untypedDatasets.push(optionDataset);
else untypedDatasets = [optionDataset];
}
if (validDataset) return validDataset;
if (typedDatasets) {
if (typedDatasets.length === 1) return typedDatasets[0];
_addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
dataset.typed = true;
} else if (untypedDatasets?.length === 1) return untypedDatasets[0];
else _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function void_(message2) {
return {
kind: "schema",
type: "void",
reference: void_,
expects: "void",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (dataset.value === void 0) dataset.typed = true;
else _addIssue(this, "type", dataset, config2);
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function keyof(schema, message2) {
return /* @__PURE__ */ picklist(Object.keys(schema.entries), message2);
}
/* @__NO_SIDE_EFFECTS__ */
function omit(schema, keys) {
const entries2 = { ...schema.entries };
for (const key of keys) delete entries2[key];
return {
...schema,
entries: entries2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function pipe(...pipe2) {
return {
...pipe2[0],
pipe: pipe2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
for (const item of pipe2) if (item.kind !== "metadata") {
if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
dataset.typed = false;
break;
}
if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) dataset = item["~run"](dataset, config2);
}
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function pipeAsync(...pipe2) {
return {
...pipe2[0],
pipe: pipe2,
async: true,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
async "~run"(dataset, config2) {
for (const item of pipe2) if (item.kind !== "metadata") {
if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
dataset.typed = false;
break;
}
if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) dataset = await item["~run"](dataset, config2);
}
return dataset;
}
};
}
/* @__NO_SIDE_EFFECTS__ */
function safeParse(schema, input, config2) {
const dataset = schema["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config2));
return {
typed: dataset.typed,
success: !dataset.issues,
output: dataset.value,
issues: dataset.issues
};
}
//#endregion
//#region ../../node_modules/.pnpm/@valibot+to-json-schema@1.3.0_valibot@1.1.0_typescript@5.9.2_/node_modules/@valibot/to-json-schema/dist/index.js
/**
* Adds an error message to the errors array.
*
* @param errors The array of error messages.
* @param message The error message to add.
*
* @returns The new errors.
*/
function addError(errors, message) {
if (errors) {
errors.push(message);
return errors;
}
return [message];
}
/**
* Throws an error or logs a warning based on the configuration.
*
* @param message The message to throw or log.
* @param config The conversion configuration.
*/
function handleError(message, config) {
switch (config?.errorMode) {
case "ignore": break;
case "warn":
console.warn(message);
break;
default: throw new Error(message);
}
}
/**
* Converts any supported Valibot action to the JSON Schema format.
*
* @param jsonSchema The JSON Schema object.
* @param valibotAction The Valibot action object.
* @param config The conversion configuration.
*
* @returns The converted JSON Schema.
*/
function convertAction(jsonSchema, valibotAction, config) {
if (config?.ignoreActions?.includes(valibotAction.type)) return jsonSchema;
let errors;
switch (valibotAction.type) {
case "base64":
jsonSchema.contentEncoding = "base64";
break;
case "bic":
case "cuid2":
case "decimal":
case "digits":
case "emoji":
case "hexadecimal":
case "hex_color":
case "nanoid":
case "octal":
case "ulid":
jsonSchema.pattern = valibotAction.requirement.source;
break;
case "description":
jsonSchema.description = valibotAction.description;
break;
case "email":
jsonSchema.format = "email";
break;
case "empty":
if (jsonSchema.type === "array") jsonSchema.maxItems = 0;
else {
if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
jsonSchema.maxLength = 0;
}
break;
case "entries":
jsonSchema.minProperties = valibotAction.requirement;
jsonSchema.maxProperties = valibotAction.requirement;
break;
case "integer":
jsonSchema.type = "integer";
break;
case "ipv4":
jsonSchema.format = "ipv4";
break;
case "ipv6":
jsonSchema.format = "ipv6";
break;
case "iso_date":
jsonSchema.format = "date";
break;
case "iso_date_time":
case "iso_timestamp":
jsonSchema.format = "date-time";
break;
case "iso_time":
jsonSchema.format = "time";
break;
case "length":
if (jsonSchema.type === "array") {
jsonSchema.minItems = valibotAction.requirement;
jsonSchema.maxItems = valibotAction.requirement;
} else {
if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
jsonSchema.minLength = valibotAction.requirement;
jsonSchema.maxLength = valibotAction.requirement;
}
break;
case "max_entries":
jsonSchema.maxProperties = valibotAction.requirement;
break;
case "max_length":
if (jsonSchema.type === "array") jsonSchema.maxItems = valibotAction.requirement;
else {
if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
jsonSchema.maxLength = valibotAction.requirement;
}
break;
case "max_value":
if (jsonSchema.type !== "number") errors = addError(errors, `The "max_value" action is not supported on type "${jsonSchema.type}".`);
jsonSchema.maximum = valibotAction.requirement;
break;
case "metadata":
if (typeof valibotAction.metadata.title === "string") jsonSchema.title = valibotAction.metadata.title;
if (typeof valibotAction.metadata.description === "string") jsonSchema.description = valibotAction.metadata.description;
if (Array.isArray(valibotAction.metadata.examples)) jsonSchema.examples = valibotAction.metadata.examples;
break;
case "min_entries":
jsonSchema.minProperties = valibotAction.requirement;
break;
case "min_length":
if (jsonSchema.type === "array") jsonSchema.minItems = valibotAction.requirement;
else {
if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
jsonSchema.minLength = valibotAction.requirement;
}
break;
case "min_value":
if (jsonSchema.type !== "number") errors = addError(errors, `The "min_value" action is not supported on type "${jsonSchema.type}".`);
jsonSchema.minimum = valibotAction.requirement;
break;
case "multiple_of":
jsonSchema.multipleOf = valibotAction.requirement;
break;
case "non_empty":
if (jsonSchema.type === "array") jsonSchema.minItems = 1;
else {
if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
jsonSchema.minLength = 1;
}
break;
case "regex":
if (valibotAction.requirement.flags) errors = addError(errors, "RegExp flags are not supported by JSON Schema.");
jsonSchema.pattern = valibotAction.requirement.source;
break;
case "title":
jsonSchema.title = valibotAction.title;
break;
case "url":
jsonSchema.format = "uri";
break;
case "uuid":
jsonSchema.format = "uuid";
break;
case "value":
jsonSchema.const = valibotAction.requirement;
break;
default: errors = addError(errors, `The "${valibotAction.type}" action cannot be converted to JSON Schema.`);
}
if (config?.overrideAction) {
const actionOverride = config.overrideAction({
valibotAction,
jsonSchema,
errors
});
if (actionOverride) return { ...actionOverride };
}
if (errors) for (const message of errors) handleError(message, config);
return jsonSchema;
}
/**
* Flattens a Valibot pipe by recursively expanding nested pipes.
*
* @param pipe The pipeline to flatten.
*
* @returns A flat pipeline.
*/
function flattenPipe(pipe$1) {
return pipe$1.flatMap((item) => "pipe" in item ? flattenPipe(item.pipe) : item);
}
let refCount = 0;
/**
* Converts any supported Valibot schema to the JSON Schema format.
*
* @param jsonSchema The JSON Schema object.
* @param valibotSchema The Valibot schema object.
* @param config The conversion configuration.
* @param context The conversion context.
* @param skipRef Whether to skip using a reference.
*
* @returns The converted JSON Schema.
*/
function convertSchema(jsonSchema, valibotSchema, config, context, skipRef = false) {
if (!skipRef) {
const referenceId = context.referenceMap.get(valibotSchema);
if (referenceId) {
jsonSchema.$ref = `#/$defs/${referenceId}`;
if (config?.overrideRef) {
const refOverride = config.overrideRef({
...context,
referenceId,
valibotSchema,
jsonSchema
});
if (refOverride) jsonSchema.$ref = refOverride;
}
return jsonSchema;
}
}
if ("pipe" in valibotSchema) {
const flatPipe = flattenPipe(valibotSchema.pipe);
let startIndex = 0;
let stopIndex = flatPipe.length - 1;
if (config?.typeMode === "input") {
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 === "transform"));
if (inputStopIndex !== -1) stopIndex = inputStopIndex;
} else if (config?.typeMode === "output") {
const outputStartIndex = flatPipe.findLastIndex((item) => item.kind === "schema");
if (outputStartIndex !== -1) startIndex = outputStartIndex;
}
for (let index = startIndex; index <= stopIndex; index++) {
const valibotPipeItem = flatPipe[index];
if (valibotPipeItem.kind === "schema") {
if (index > startIndex) hand