1 | import type {FuncKeywordDefinition} from "ajv"
|
2 |
|
3 | type Constructor = new (...args: any[]) => any
|
4 |
|
5 | const CONSTRUCTORS: Record<string, Constructor | undefined> = {
|
6 | Object,
|
7 | Array,
|
8 | Function,
|
9 | Number,
|
10 | String,
|
11 | Date,
|
12 | RegExp,
|
13 | }
|
14 |
|
15 |
|
16 | if (typeof Buffer != "undefined") CONSTRUCTORS.Buffer = Buffer
|
17 |
|
18 |
|
19 | if (typeof Promise != "undefined") CONSTRUCTORS.Promise = Promise
|
20 |
|
21 | const getDef: (() => FuncKeywordDefinition) & {
|
22 | CONSTRUCTORS: typeof CONSTRUCTORS
|
23 | } = Object.assign(_getDef, {CONSTRUCTORS})
|
24 |
|
25 | function _getDef(): FuncKeywordDefinition {
|
26 | return {
|
27 | keyword: "instanceof",
|
28 | schemaType: ["string", "array"],
|
29 | compile(schema: string | string[]) {
|
30 | if (typeof schema == "string") {
|
31 | const C = getConstructor(schema)
|
32 | return (data) => data instanceof C
|
33 | }
|
34 |
|
35 | if (Array.isArray(schema)) {
|
36 | const constructors = schema.map(getConstructor)
|
37 | return (data) => {
|
38 | for (const C of constructors) {
|
39 | if (data instanceof C) return true
|
40 | }
|
41 | return false
|
42 | }
|
43 | }
|
44 |
|
45 |
|
46 | throw new Error("ajv implementation error")
|
47 | },
|
48 | metaSchema: {
|
49 | anyOf: [{type: "string"}, {type: "array", items: {type: "string"}}],
|
50 | },
|
51 | }
|
52 | }
|
53 |
|
54 | function getConstructor(c: string): Constructor {
|
55 | const C = CONSTRUCTORS[c]
|
56 | if (C) return C
|
57 | throw new Error(`invalid "instanceof" keyword value ${c}`)
|
58 | }
|
59 |
|
60 | export default getDef
|
61 | module.exports = getDef
|