UNPKG

ajv-cli

Version:

Command line interface for Ajv JSON schema validator

89 lines 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const util_1 = require("./util"); const ajv_1 = require("./ajv"); const standalone_1 = require("ajv/dist/standalone"); const fs = require("fs"); const cmd = { execute, schema: { type: "object", required: ["s"], properties: { s: { $ref: "#/$defs/stringOrArray" }, r: { $ref: "#/$defs/stringOrArray" }, m: { $ref: "#/$defs/stringOrArray" }, c: { $ref: "#/$defs/stringOrArray" }, o: { anyOf: [{ type: "string", format: "notGlob" }, { type: "boolean" }] }, spec: { enum: ["draft7", "draft2019", "draft2020", "jtd"] }, }, ajvOptions: true, }, }; exports.default = cmd; function execute(argv) { const ajv = ajv_1.default(argv); const schemaFiles = util_1.getFiles(argv.s); if ("o" in argv && schemaFiles.length > 1) return compileMultiExportModule(schemaFiles); return schemaFiles.map(compileSchemaAndSave).every((x) => x); function compileMultiExportModule(files) { const validators = files.map(compileSchema); if (validators.every((v) => v)) { return saveStandaloneCode(getRefs(validators, files)); } console.error("module not saved"); return false; } function compileSchemaAndSave(file) { const validate = compileSchema(file); if (validate) return "o" in argv ? saveStandaloneCode(validate) : true; return false; } function compileSchema(file) { const sch = util_1.openFile(file, `schema ${file}`); try { const id = sch === null || sch === void 0 ? void 0 : sch.$id; ajv.addSchema(sch, id ? undefined : file); const validate = ajv.getSchema(id || file); if (argv.o !== true) console.log(`schema ${file} is valid`); return validate; } catch (err) { console.error(`schema ${file} is invalid`); console.error(`error: ${err.message}`); return undefined; } } function getRefs(validators, files) { const refs = {}; validators.forEach((v, i) => { const ref = typeof v.schema == "object" ? v.schema.$id || files[i] : files[i]; refs[ref] = ref; }); return refs; } function saveStandaloneCode(refsOrFunc) { try { const moduleCode = standalone_1.default(ajv, refsOrFunc); try { if (argv.o === true) console.log(moduleCode); else fs.writeFileSync(argv.o, moduleCode); return true; } catch (e) { console.error("error saving file:", e); return false; } } catch (e) { console.error("error preparing module:", e); return false; } } } //# sourceMappingURL=compile.js.map