UNPKG

6.64 kBPlain TextView Raw
1import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
2import type {SchemaCxt, SchemaObjCxt} from "."
3import {_, getProperty, Code, Name, CodeGen} from "./codegen"
4import {_Code} from "./codegen/code"
5import type {Rule, ValidationRules} from "./rules"
6
7// TODO refactor to use Set
8export function toHash<T extends string = string>(arr: T[]): {[K in T]?: true} {
9 const hash: {[K in T]?: true} = {}
10 for (const item of arr) hash[item] = true
11 return hash
12}
13
14export function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {
15 if (typeof schema == "boolean") return schema
16 if (Object.keys(schema).length === 0) return true
17 checkUnknownRules(it, schema)
18 return !schemaHasRules(schema, it.self.RULES.all)
19}
20
21export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {
22 const {opts, self} = it
23 if (!opts.strictSchema) return
24 if (typeof schema === "boolean") return
25 const rules = self.RULES.keywords
26 for (const key in schema) {
27 if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`)
28 }
29}
30
31export function schemaHasRules(
32 schema: AnySchema,
33 rules: {[Key in string]?: boolean | Rule}
34): boolean {
35 if (typeof schema == "boolean") return !schema
36 for (const key in schema) if (rules[key]) return true
37 return false
38}
39
40export function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {
41 if (typeof schema == "boolean") return !schema
42 for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true
43 return false
44}
45
46export function schemaRefOrVal(
47 {topSchemaRef, schemaPath}: SchemaObjCxt,
48 schema: unknown,
49 keyword: string,
50 $data?: string | false
51): Code | number | boolean {
52 if (!$data) {
53 if (typeof schema == "number" || typeof schema == "boolean") return schema
54 if (typeof schema == "string") return _`${schema}`
55 }
56 return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`
57}
58
59export function unescapeFragment(str: string): string {
60 return unescapeJsonPointer(decodeURIComponent(str))
61}
62
63export function escapeFragment(str: string | number): string {
64 return encodeURIComponent(escapeJsonPointer(str))
65}
66
67export function escapeJsonPointer(str: string | number): string {
68 if (typeof str == "number") return `${str}`
69 return str.replace(/~/g, "~0").replace(/\//g, "~1")
70}
71
72export function unescapeJsonPointer(str: string): string {
73 return str.replace(/~1/g, "/").replace(/~0/g, "~")
74}
75
76export function eachItem<T>(xs: T | T[], f: (x: T) => void): void {
77 if (Array.isArray(xs)) {
78 for (const x of xs) f(x)
79 } else {
80 f(xs)
81 }
82}
83
84type SomeEvaluated = EvaluatedProperties | EvaluatedItems
85
86type MergeEvaluatedFunc<T extends SomeEvaluated> = (
87 gen: CodeGen,
88 from: Name | T,
89 to: Name | Exclude<T, true> | undefined,
90 toName?: typeof Name
91) => Name | T
92
93interface MakeMergeFuncArgs<T extends SomeEvaluated> {
94 mergeNames: (gen: CodeGen, from: Name, to: Name) => void
95 mergeToName: (gen: CodeGen, from: T, to: Name) => void
96 mergeValues: (from: T, to: Exclude<T, true>) => T
97 resultToName: (gen: CodeGen, res?: T) => Name
98}
99
100function makeMergeEvaluated<T extends SomeEvaluated>({
101 mergeNames,
102 mergeToName,
103 mergeValues,
104 resultToName,
105}: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {
106 return (gen, from, to, toName) => {
107 const res =
108 to === undefined
109 ? from
110 : to instanceof Name
111 ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
112 : from instanceof Name
113 ? (mergeToName(gen, to, from), from)
114 : mergeValues(from, to)
115 return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res
116 }
117}
118
119interface MergeEvaluated {
120 props: MergeEvaluatedFunc<EvaluatedProperties>
121 items: MergeEvaluatedFunc<EvaluatedItems>
122}
123
124export const mergeEvaluated: MergeEvaluated = {
125 props: makeMergeEvaluated({
126 mergeNames: (gen, from, to) =>
127 gen.if(_`${to} !== true && ${from} !== undefined`, () => {
128 gen.if(
129 _`${from} === true`,
130 () => gen.assign(to, true),
131 () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)
132 )
133 }),
134 mergeToName: (gen, from, to) =>
135 gen.if(_`${to} !== true`, () => {
136 if (from === true) {
137 gen.assign(to, true)
138 } else {
139 gen.assign(to, _`${to} || {}`)
140 setEvaluated(gen, to, from)
141 }
142 }),
143 mergeValues: (from, to) => (from === true ? true : {...from, ...to}),
144 resultToName: evaluatedPropsToName,
145 }),
146 items: makeMergeEvaluated({
147 mergeNames: (gen, from, to) =>
148 gen.if(_`${to} !== true && ${from} !== undefined`, () =>
149 gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)
150 ),
151 mergeToName: (gen, from, to) =>
152 gen.if(_`${to} !== true`, () =>
153 gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)
154 ),
155 mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
156 resultToName: (gen, items) => gen.var("items", items),
157 }),
158}
159
160export function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {
161 if (ps === true) return gen.var("props", true)
162 const props = gen.var("props", _`{}`)
163 if (ps !== undefined) setEvaluated(gen, props, ps)
164 return props
165}
166
167export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {
168 Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))
169}
170
171const snippets: {[S in string]?: _Code} = {}
172
173export function useFunc(gen: CodeGen, f: {code: string}): Name {
174 return gen.scopeValue("func", {
175 ref: f,
176 code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),
177 })
178}
179
180export enum Type {
181 Num,
182 Str,
183}
184
185export function getErrorPath(
186 dataProp: Name | string | number,
187 dataPropType?: Type,
188 jsPropertySyntax?: boolean
189): Code | string {
190 // let path
191 if (dataProp instanceof Name) {
192 const isNumber = dataPropType === Type.Num
193 return jsPropertySyntax
194 ? isNumber
195 ? _`"[" + ${dataProp} + "]"`
196 : _`"['" + ${dataProp} + "']"`
197 : isNumber
198 ? _`"/" + ${dataProp}`
199 : _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer
200 }
201 return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp)
202}
203
204export function checkStrictMode(
205 it: SchemaCxt,
206 msg: string,
207 mode: boolean | "log" = it.opts.strictSchema
208): void {
209 if (!mode) return
210 msg = `strict mode: ${msg}`
211 if (mode === true) throw new Error(msg)
212 it.self.logger.warn(msg)
213}