Commit 5569a942 authored by David Sveningsson's avatar David Sveningsson
Browse files

fix: allow loading elements from js-file again

parent 7ff9325c
Pipeline #132854396 passed with stages
in 9 minutes and 14 seconds
import path from "path";
/* mock ajv for easier testing of errors and to allow invalid values though the
* validation to ensure the code works anyway */
interface Validate {
......@@ -94,6 +96,49 @@ describe("MetaTable", () => {
expect(table.getMetaFor("$schema")).toBeNull();
});
describe("should load metadata from", () => {
const fileDir = path.resolve(__dirname, "../../test-files/meta");
it("json file", () => {
expect.assertions(1);
const table = new MetaTable();
const filename = path.join(fileDir, "elements-json.json");
table.loadFromFile(filename);
expect(table.getMetaFor("foo")).toMatchInlineSnapshot(`
Object {
"flow": true,
"tagName": "foo",
}
`);
});
it("js file", () => {
expect.assertions(1);
const table = new MetaTable();
const filename = path.join(fileDir, "elements-js.js");
table.loadFromFile(filename);
expect(table.getMetaFor("foo")).toMatchInlineSnapshot(`
Object {
"flow": true,
"tagName": "foo",
}
`);
});
it("js without extension", () => {
expect.assertions(1);
const table = new MetaTable();
const filename = path.join(fileDir, "elements-js");
table.loadFromFile(filename);
expect(table.getMetaFor("foo")).toMatchInlineSnapshot(`
Object {
"flow": true,
"tagName": "foo",
}
`);
});
});
describe("getMetaFor", () => {
let table: MetaTable;
......
import fs from "fs";
import Ajv from "ajv";
import deepmerge from "deepmerge";
import jsonMergePatch from "json-merge-patch";
......@@ -137,17 +136,21 @@ export class MetaTable {
* Load metadata table from filename
*/
public loadFromFile(filename: string): void {
let json;
try {
const data = fs.readFileSync(filename, "utf-8");
json = JSON.parse(data);
/* remove cached copy so we always load a fresh copy, important for
* editors which keep a long-running instance of [[HtmlValidate]]
* around. */
delete require.cache[require.resolve(filename)];
/* load using require as it can process both js and json */
const data = require(filename); // eslint-disable-line import/no-dynamic-require
this.loadFromObject(data, filename);
} catch (err) {
throw new UserError(
`Failed to load element metadata from "${filename}"`,
err
);
}
this.loadFromObject(clone(json), filename);
}
/**
......
module.exports = {
foo: {
flow: true,
},
};
{
"foo": {
"flow": true
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment