UNPKG

aiwrapper

Version:

A Universal AI Wrapper for JavaScript & TypeScript

60 lines (59 loc) 1.94 kB
import { zodToJsonSchema as zodToJsonSchemaPkg } from "zod-to-json-schema"; import Ajv from "ajv"; let ajvInstance = null; function getAjv() { if (!ajvInstance) { ajvInstance = new Ajv({ allErrors: true, strict: false }); } return ajvInstance; } function isZodSchema(schema) { return schema !== null && typeof schema === "object" && "parse" in schema && "safeParse" in schema && typeof schema.parse === "function" && typeof schema.safeParse === "function"; } function isJsonSchema(schema) { return schema !== null && typeof schema === "object" && !isZodSchema(schema); } function validateAgainstSchema(value, schema) { if (isZodSchema(schema)) { const result = schema.safeParse(value); if (result.success) { return { valid: true, errors: [] }; } else { return { valid: false, errors: result.error.errors.map((err) => `${err.path.join(".")}: ${err.message}`) }; } } else if (isJsonSchema(schema)) { try { const ajv = getAjv(); const validate = ajv.compile(schema); const ok = validate(value); if (ok) { return { valid: true, errors: [] }; } const errors = validate.errors; const messages = (errors || []).map((e) => { const instancePath = e.instancePath || ""; const path = instancePath.startsWith("/") ? instancePath.slice(1).replace(/\//g, ".") : instancePath; const msg = e.message || "validation error"; return path ? `${path}: ${msg}` : msg; }); return { valid: false, errors: messages }; } catch (_error) { return { valid: false, errors: ["Invalid JSON Schema or value"] }; } } else { return { valid: false, errors: ["Invalid schema"] }; } } function zodToJsonSchema(schema) { return zodToJsonSchemaPkg(schema); } export { isJsonSchema, isZodSchema, validateAgainstSchema, zodToJsonSchema }; //# sourceMappingURL=schema-utils.js.map