.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / table / node_modules / ajv / lib / vocabularies / jtd / type.ts
1 import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
2 import type {KeywordCxt} from "../../compile/validate"
3 import {_, or, Code} from "../../compile/codegen"
4 import validTimestamp from "../../runtime/timestamp"
5 import {useFunc} from "../../compile/util"
6 import {checkMetadata} from "./metadata"
7 import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"
8
9 export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType>
10
11 export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"
12
13 export const intRange: {[T in IntType]: [number, number, number]} = {
14   int8: [-128, 127, 3],
15   uint8: [0, 255, 3],
16   int16: [-32768, 32767, 5],
17   uint16: [0, 65535, 5],
18   int32: [-2147483648, 2147483647, 10],
19   uint32: [0, 4294967295, 10],
20 }
21
22 export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType
23
24 const error: KeywordErrorDefinition = {
25   message: (cxt) => typeErrorMessage(cxt, cxt.schema),
26   params: (cxt) => typeErrorParams(cxt, cxt.schema),
27 }
28
29 const def: CodeKeywordDefinition = {
30   keyword: "type",
31   schemaType: "string",
32   error,
33   code(cxt: KeywordCxt) {
34     checkMetadata(cxt)
35     const {gen, data, schema, parentSchema} = cxt
36     let cond: Code
37     switch (schema) {
38       case "boolean":
39       case "string":
40         cond = _`typeof ${data} == ${schema}`
41         break
42       case "timestamp": {
43         const vts = useFunc(gen, validTimestamp)
44         cond = _`${data} instanceof Date || (typeof ${data} == "string" && ${vts}(${data}))`
45         break
46       }
47       case "float32":
48       case "float64":
49         cond = _`typeof ${data} == "number"`
50         break
51       default: {
52         const [min, max] = intRange[schema as IntType]
53         cond = _`typeof ${data} == "number" && isFinite(${data}) && ${data} >= ${min} && ${data} <= ${max} && !(${data} % 1)`
54       }
55     }
56     cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond)
57   },
58 }
59
60 export default def