UNPKG

@minecraft/creator-tools

Version:

Minecraft Creator Tools command line and libraries.

42 lines (40 loc) 1.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateJsonAndAssert = validateJsonAndAssert; const json_schema_1 = require("json-schema"); const zod_1 = require("zod"); /* uses schema to validate a json object and if valid, returns it with the type asserted returns a tuple of [value, errors]. If errors is null, then value will be a valid value with type T otherwise errors will be an array and value will be null */ function validateJsonAndAssert(json, schema, transforms = []) { const [result, errors] = schema instanceof zod_1.ZodType ? zodValidateSchema(json, schema) : jsonschemaValidateSchema(json, schema); if (errors) { return [null, errors]; } let obj = result; for (const transform of transforms) { obj = transform(obj); } return [obj, null]; } function jsonschemaValidateSchema(json, schema, transforms = []) { if (!json || typeof json !== "object") { return [null, [{ message: "Could not parse json" }]]; } const validation = (0, json_schema_1.validate)(json, schema); return validation.valid ? [json, null] : [null, validation.errors]; } function zodValidateSchema(json, schema) { const parseResult = schema.safeParse(json); if (!parseResult.success) { const errors = parseResult.error.errors.map((error) => ({ message: error.message, propertyName: error.path.join("/"), })); return [null, errors]; } return [parseResult.data, null]; }