schemaorg-jsd
Version:
JSON Schema validation for JSON-LD files using Schema.org vocabulary.
74 lines (73 loc) • 3.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.sdoValidate = exports.SCHEMATA = exports.JSONLD_SCHEMA = exports.META_SCHEMATA = void 0;
const fs = require("fs");
const https = require("https");
const path = require("path");
const ajv_1 = require("ajv");
const requirejson_1 = require("@chharvey/requirejson");
exports.META_SCHEMATA = fs.promises.readdir(path.resolve(__dirname, '../meta/')).then((filenames) => Promise.all(filenames.map((filename) => requirejson_1.requireJSON(path.join(__dirname, '../meta/', filename)))));
exports.JSONLD_SCHEMA = new Promise((resolve, reject) => {
https.get('https://cdn.jsdelivr.net/gh/json-ld/json-ld.org@1.0/schemas/jsonld-schema.json', (res) => {
if (!res.statusCode || res.statusCode < 200 || 300 <= res.statusCode) {
reject(new Error(`
Failed to load.
Status Code: ${res.statusCode || 'no status code found'}
`.replace(/\n\t\t\t\t/g, '\n')));
res.resume();
return;
}
res.setEncoding('utf8');
const body = [];
res.on('data', (chunk) => { body.push(chunk); });
res.on('end', () => {
let data;
try {
data = JSON.parse(body.join(''));
}
catch (err) {
reject(err);
return;
}
data.$schema = 'http://json-schema.org/draft-07/schema#';
data.$id = 'https://json-ld.org/schemas/jsonld-schema.json';
resolve(data);
});
}).on('error', (err) => { reject(err); });
});
exports.SCHEMATA = fs.promises.readdir(path.resolve(__dirname, '../schema/')).then((filenames) => Promise.all(filenames.map((filename) => requirejson_1.requireJSON(path.join(__dirname, '../schema/', filename)))));
async function sdoValidate(obj, type = null, opts = {}) {
let filename = '';
if (typeof obj === 'string') {
filename = obj;
obj = await requirejson_1.requireJSON(obj);
}
if (type === null) {
const objtype = obj['@type'] || null;
if (objtype instanceof Array && objtype.length) {
return (await Promise.all(objtype.map((tp) => sdoValidate(obj, tp)))).every((a) => !!a);
}
else if (typeof objtype === 'string') {
type = ((await exports.SCHEMATA).find((jsd) => jsd.title === `http://schema.org/${objtype}`)) ? objtype :
(console.warn(`Class \`${objtype}\` is not yet supported. Validating against \`Thing.jsd\` instead…`), 'Thing');
}
else {
console.warn(`JSON-LD \`@type\` property was not found. Validating against \`Thing.jsd\`…`);
type = 'Thing';
}
}
const ajv = new ajv_1.default(opts)
.addMetaSchema(await exports.META_SCHEMATA)
.addSchema(await exports.JSONLD_SCHEMA)
.addSchema(await exports.SCHEMATA);
const is_data_valid = await ajv.validate(`https://chharvey.github.io/schemaorg-jsd/schema/${type}.jsd`, obj);
if (!is_data_valid) {
const err = new TypeError(`Object ${obj['@id'] || obj.identifier || obj.name || JSON.stringify(obj)} does not valiate against schema ${type}.jsd!`);
if (filename.length)
err.filename = filename;
err.details = ajv.errors;
throw err;
}
return true;
}
exports.sdoValidate = sdoValidate;