ined); if (draft && this.#draft != draft) { console.error( `Adding a draft "${draft}" schema to a draft "${ this.#draft }" validator.` ); } try { this.#inner.addSchema(Cu.cloneInto(schema, sandbox), id); } catch (ex) { throw new Error(ex.message, { cause: ex }); } } } /** * A wrapper around validate that provides some options as an object * instead of positional arguments. * * @param {object} instance The instance to validate. * @param {object} schema The JSON schema to validate against. * @param {object} options Options for the validator. * @param {string} options.draft The draft to validate against. Should * be one of "4", "6", "7", "2019-09", or "2020-12". * * If the |$schema| key is present in the |schema|, it * will be used to auto-detect the correct version. * Otherwise, 2019-09 will be used. * @param {boolean} options.shortCircuit Whether or not the validator should * return after a single error occurs. * * @returns {object} An object with |valid| and |errors| keys that indicates the * success of validation. */ function validate( instance, schema, { draft = detectSchemaDraft(schema), shortCircuit = true } = {} ) { const clonedSchema = Cu.cloneInto(schema, sandbox); try { return sandbox.validate( Cu.cloneInto(instance, sandbox), clonedSchema, draft, sandbox.dereference(clonedSchema), shortCircuit ); } catch (ex) { throw new Error(ex.message, { cause: ex }); } } function detectSchemaDraft(schema, defaultDraft = "2019-09") { const { $schema } = schema; if (typeof $schema === "undefined") { return defaultDraft; } switch ($schema) { case "http://json-schema.org/draft-04/schema#": return "4"; case "http://json-schema.org/draft-06/schema#": return "6"; case "http://json-schema.org/draft-07/schema#": return "7"; case "https://json-schema.org/draft/2019-09/schema": return "2019-09"; case "https://json-schema.org/draft/2020-12/schema": return "2020-12"; default: console.error( `Unexpected $schema "${$schema}", defaulting to ${defaultDraft}.` ); return defaultDraft; } } export const JsonSchema = { Validator, validate, detectSchemaDraft, }; PK