Validate on top-level settings and use pre-compiled ajv

jh-changes
Shin'ya Ueoka 5 years ago
parent 2318e3a555
commit 776977e0dc
  1. 33
      src/shared/settings/Blacklist.ts
  2. 31
      src/shared/settings/Keymaps.ts
  3. 21
      src/shared/settings/Properties.ts
  4. 34
      src/shared/settings/Search.ts
  5. 50
      src/shared/settings/Settings.ts
  6. 20
      src/shared/settings/Validator.ts
  7. 3
      src/shared/settings/schema.json
  8. 22
      src/shared/settings/validate.js
  9. 18
      test/shared/settings/Blacklist.test.ts
  10. 1
      test/shared/settings/Keymaps.test.ts
  11. 13
      test/shared/settings/Search.test.ts

@ -1,23 +1,4 @@
import Key from './Key';
import Validator from './Validator';
const ItemSchema = {
anyOf: [
{ type: 'string' },
{
type: 'object',
properties: {
url: { type: 'string' },
keys: {
type: 'array',
items: { type: 'string', minLength: 1 },
minItems: 1,
}
},
required: ['url', 'keys'],
}
],
};
export type BlacklistItemJSON = string | {
url: string,
@ -54,11 +35,10 @@ export class BlacklistItem {
this.keyEntities = this.keys.map(Key.fromMapKey);
}
static fromJSON(json: unknown): BlacklistItem {
let obj = new Validator<BlacklistItemJSON>(ItemSchema).validate(json);
return typeof obj === 'string'
? new BlacklistItem(obj, false, [])
: new BlacklistItem(obj.url, true, obj.keys);
static fromJSON(json: BlacklistItemJSON): BlacklistItem {
return typeof json === 'string'
? new BlacklistItem(json, false, [])
: new BlacklistItem(json.url, true, json.keys);
}
toJSON(): BlacklistItemJSON {
@ -91,10 +71,7 @@ export default class Blacklist {
) {
}
static fromJSON(json: unknown): Blacklist {
if (!Array.isArray(json)) {
throw new TypeError('blacklist is not an array');
}
static fromJSON(json: BlacklistJSON): Blacklist {
let items = json.map(o => BlacklistItem.fromJSON(o));
return new Blacklist(items);
}

@ -1,32 +1,23 @@
import * as operations from '../operations';
import Validator from './Validator';
const Schema = {
type: 'object',
patternProperties: {
'.*': {
type: 'object',
properties: {
type: { type: 'string' },
},
required: ['type'],
},
}
type OperationJson = {
type: string
} | {
type: string;
[prop: string]: string | number | boolean;
};
export type KeymapsJSON = { [key: string]: operations.Operation };
export type KeymapsJSON = { [key: string]: OperationJson };
export default class Keymaps {
constructor(
private readonly data: KeymapsJSON,
private readonly data: { [key: string]: operations.Operation },
) {
}
static fromJSON(json: unknown): Keymaps {
let obj = new Validator<KeymapsJSON>(Schema).validate(json);
let entries: KeymapsJSON = {};
for (let key of Object.keys(obj)) {
entries[key] = operations.valueOf(obj[key]);
static fromJSON(json: KeymapsJSON): Keymaps {
let entries: { [key: string]: operations.Operation } = {};
for (let key of Object.keys(json)) {
entries[key] = operations.valueOf(json[key]);
}
return new Keymaps(entries);
}

@ -1,19 +1,3 @@
import Validator from './Validator';
const Schema = {
type: 'object',
properties: {
hintchars: {
type: 'string',
},
smoothscroll: {
type: 'boolean',
},
complete: {
type: 'string',
},
},
};
export type PropertiesJSON = {
hintchars?: string;
@ -82,9 +66,8 @@ export default class Properties {
this.complete = complete || defaultValues.complete;
}
static fromJSON(json: unknown): Properties {
let obj = new Validator<PropertiesJSON>(Schema).validate(json);
return new Properties(obj);
static fromJSON(json: PropertiesJSON): Properties {
return new Properties(json);
}
static types(): PropertyTypes {

@ -1,22 +1,3 @@
import Validator from './Validator';
const Schema = {
type: 'object',
properties: {
default: { type: 'string' },
engines: {
type: 'object',
propertyNames: {
pattern: '^[A-Za-z_][A-Za-z0-9_]+$',
},
patternProperties: {
'.*': { type: 'string' },
},
},
},
required: ['default'],
};
type Entries = { [name: string]: string };
export type SearchJSON = {
@ -31,10 +12,11 @@ export default class Search {
) {
}
static fromJSON(json: unknown): Search {
let obj = new Validator<SearchJSON>(Schema).validate(json);
for (let [name, url] of Object.entries(obj.engines)) {
static fromJSON(json: SearchJSON): Search {
for (let [name, url] of Object.entries(json.engines)) {
if (!(/^[a-zA-Z0-9]+$/).test(name)) {
throw new TypeError('Search engine\'s name must be [a-zA-Z0-9]+');
}
let matches = url.match(/{}/g);
if (matches === null) {
throw new TypeError(`No {}-placeholders in URL of "${name}"`);
@ -42,11 +24,11 @@ export default class Search {
throw new TypeError(`Multiple {}-placeholders in URL of "${name}"`);
}
}
if (!Object.keys(obj.engines).includes(obj.default)) {
throw new TypeError(`Default engine "${obj.default}" not found`);
if (!Object.keys(json.engines).includes(json.default)) {
throw new TypeError(`Default engine "${json.default}" not found`);
}
return new Search(obj.default, obj.engines);
return new Search(json.default, json.engines);
}
toJSON(): SearchJSON {

@ -1,13 +1,16 @@
import Ajv from 'ajv';
import Keymaps, { KeymapsJSON } from './Keymaps';
import Search, { SearchJSON } from './Search';
import Properties, { PropertiesJSON } from './Properties';
import Blacklist, { BlacklistJSON } from './Blacklist';
import validate from './validate';
export type SettingsJSON = {
keymaps: KeymapsJSON,
search: SearchJSON,
properties: PropertiesJSON,
blacklist: BlacklistJSON,
keymaps?: KeymapsJSON,
search?: SearchJSON,
properties?: PropertiesJSON,
blacklist?: BlacklistJSON,
};
export default class Settings {
@ -36,25 +39,30 @@ export default class Settings {
this.blacklist = blacklist;
}
static fromJSON(json: any): Settings {
static fromJSON(json: unknown): Settings {
let valid = validate(json);
if (!valid) {
let message = (validate as any).errors!!
.map((err: Ajv.ErrorObject) => {
return `'${err.dataPath}' of ${err.keyword} ${err.message}`;
})
.join('; ');
throw new TypeError(message);
}
let obj = json as SettingsJSON;
let settings = { ...DefaultSetting };
for (let key of Object.keys(json)) {
switch (key) {
case 'keymaps':
settings.keymaps = Keymaps.fromJSON(json.keymaps);
break;
case 'search':
settings.search = Search.fromJSON(json.search);
break;
case 'properties':
settings.properties = Properties.fromJSON(json.properties);
break;
case 'blacklist':
settings.blacklist = Blacklist.fromJSON(json.blacklist);
break;
default:
throw new TypeError('unknown setting: ' + key);
if (obj.keymaps) {
settings.keymaps = Keymaps.fromJSON(obj.keymaps);
}
if (obj.search) {
settings.search = Search.fromJSON(obj.search);
}
if (obj.properties) {
settings.properties = Properties.fromJSON(obj.properties);
}
if (obj.blacklist) {
settings.blacklist = Blacklist.fromJSON(obj.blacklist);
}
return new Settings(settings);
}

@ -1,20 +0,0 @@
import Ajv from 'ajv';
export default class Validator<T> {
constructor(
private schema: object | boolean,
) {
}
validate(data: any): T {
let ajv = new Ajv();
let valid = ajv.validate(this.schema, data);
if (!valid) {
let message = ajv.errors!!
.map(err => `'${err.dataPath}' of ${err.keyword} ${err.message}`)
.join('; ');
throw new TypeError(message);
}
return data as T;
}
}

@ -78,5 +78,6 @@
]
}
}
}
},
"additionalProperties": false
}

@ -9,6 +9,24 @@ var validate = (function() {
if ((data && typeof data === "object" && !Array.isArray(data))) {
var errs__0 = errors;
var valid1 = true;
for (var key0 in data) {
var isAdditional0 = !(false || key0 == 'keymaps' || key0 == 'search' || key0 == 'properties' || key0 == 'blacklist');
if (isAdditional0) {
valid1 = false;
validate.errors = [{
keyword: 'additionalProperties',
dataPath: (dataPath || '') + "",
schemaPath: '#/additionalProperties',
params: {
additionalProperty: '' + key0 + ''
},
message: 'should NOT have additional properties'
}];
return false;
break;
}
}
if (valid1) {
var data1 = data.keymaps;
if (data1 === undefined) {
valid1 = true;
@ -445,6 +463,7 @@ var validate = (function() {
}
}
}
}
} else {
validate.errors = [{
keyword: 'type',
@ -531,7 +550,8 @@ validate.schema = {
}]
}
}
}
},
"additionalProperties": false
};
validate.errors = null;
module.exports = validate;

@ -16,16 +16,6 @@ describe('BlacklistItem', () => {
expect(item.partial).to.be.true;
expect(item.keys).to.deep.equal(['j', 'k']);
});
it('throws a TypeError', () => {
expect(() => BlacklistItem.fromJSON(null)).to.throw(TypeError);
expect(() => BlacklistItem.fromJSON(100)).to.throw(TypeError);
expect(() => BlacklistItem.fromJSON({})).to.throw(TypeError);
expect(() => BlacklistItem.fromJSON({url: 'google.com'})).to.throw(TypeError);
expect(() => BlacklistItem.fromJSON({keys: ['a']})).to.throw(TypeError);
expect(() => BlacklistItem.fromJSON({url: 'google.com', keys: 10})).to.throw(TypeError);
expect(() => BlacklistItem.fromJSON({url: 'google.com', keys: ['a', 'b', 3]})).to.throw(TypeError);
});
});
describe('#matches', () => {
@ -118,14 +108,6 @@ describe('Blacklist', () => {
let blacklist = Blacklist.fromJSON([]);
expect(blacklist.toJSON()).to.deep.equals([]);
});
it('throws a TypeError', () => {
expect(() => Blacklist.fromJSON(null)).to.throw(TypeError);
expect(() => Blacklist.fromJSON(100)).to.throw(TypeError);
expect(() => Blacklist.fromJSON({})).to.throw(TypeError);
expect(() => Blacklist.fromJSON([100])).to.throw(TypeError);
expect(() => Blacklist.fromJSON([{}])).to.throw(TypeError);
})
});
describe('#includesEntireBlacklist', () => {

@ -19,7 +19,6 @@ describe('Keymaps', () => {
});
it('throws a TypeError by invalid settings', () => {
expect(() => Keymaps.fromJSON(null)).to.throw(TypeError);
expect(() => Keymaps.fromJSON({
k: { type: "invalid.operation" },
})).to.throw(TypeError);

@ -26,19 +26,6 @@ describe('Search', () => {
});
it('throws a TypeError by invalid settings', () => {
expect(() => Search.fromJSON(null)).to.throw(TypeError);
expect(() => Search.fromJSON({})).to.throw(TypeError);
expect(() => Search.fromJSON([])).to.throw(TypeError);
expect(() => Search.fromJSON({
default: 123,
engines: {}
})).to.throw(TypeError);
expect(() => Search.fromJSON({
default: 'google',
engines: {
'google': 123456,
}
})).to.throw(TypeError);
expect(() => Search.fromJSON({
default: 'wikipedia',
engines: {