-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
48 lines (44 loc) · 1.38 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Copyright 2021 - Frederik Ring <[email protected]>
* SPDX-License-Identifier: MIT
*/
const Ajv = require('ajv')
const standaloneCode = require('ajv/dist/standalone').default
const fs = require('fs')
const addAjvFormats = require('ajv-formats')
const ajvSecure = new Ajv({ strictTypes: false })
const isSchemaSecure = ajvSecure.compile(require('ajv/lib/refs/json-schema-secure.json'))
module.exports = ({
filter = /\.schema$|\.schema\.json$/,
secure = true,
addFormats = true,
ajvOptions = {}
} = {}) => {
const ajv = new Ajv({ code: { source: true }, ...ajvOptions })
if (addFormats) addAjvFormats(ajv)
return {
name: 'jsonschema',
setup (build) {
build.onLoad({ filter }, async (args) => {
const contents = await fs.promises.readFile(args.path, 'utf8')
let moduleCode
try {
const schema = JSON.parse(contents)
if (secure && !isSchemaSecure(schema)) {
return {
errors: isSchemaSecure.errors.map(err => {
return { text: `Schema ${args.path} is not secure`, detail: err }
})
}
}
moduleCode = standaloneCode(ajv, ajv.compile(schema))
} catch (err) {
return {
errors: [{ text: 'Error compiling and packing schema', detail: err }]
}
}
return { contents: moduleCode }
})
}
}
}