nuxt-safe-runtime-config
Version:
Validate Nuxt runtime config with Standard Schema at build time
39 lines (38 loc) • 1.72 kB
JavaScript
function reportError(msg, onError, logger, throwMsg) {
if (onError === "throw") {
logger.error(msg);
throw new Error(throwMsg ?? msg);
}
if (onError === "warn")
logger.warn(msg);
}
function resolveResult(result, onError, logger) {
const issues = "issues" in result ? result.issues : void 0;
if ("value" in result && !issues?.length)
return { success: true, value: result.value };
const errorLines = (issues ?? []).map((issue, index) => ` ${index + 1}. ${formatIssue(issue)}`);
reportError(`Validation failed!
${errorLines.join("\n")}`, onError, logger, "Runtime config validation failed");
return { success: false };
}
export function isPromiseLike(value) {
return Boolean(value && typeof value.then === "function");
}
export function validateRuntimeConfig(config, schema, onError, logger) {
if (!isStandardSchema(schema)) {
reportError("Schema is not Standard Schema compatible", onError, logger, "Invalid schema format");
return { success: false };
}
const result = schema["~standard"].validate(config);
return isPromiseLike(result) ? result.then((value) => resolveResult(value, onError, logger)) : resolveResult(result, onError, logger);
}
export function isStandardSchema(schema) {
const candidate = schema;
return Boolean(
candidate && (typeof schema === "object" || typeof schema === "function") && candidate["~standard"] && typeof candidate["~standard"] === "object" && typeof candidate["~standard"].validate === "function"
);
}
function formatIssue(issue) {
const path = issue.path ? issue.path.map((p) => typeof p === "object" && p !== null && "key" in p ? p.key : p).join(".") : "root";
return `${path}: ${issue.message || "Validation error"}`;
}