1 import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
2 import type {SchemaCxt, SchemaObjCxt} from "."
3 import {_, getProperty, Code, Name, CodeGen} from "./codegen"
4 import {_Code} from "./codegen/code"
5 import type {Rule, ValidationRules} from "./rules"
7 // TODO refactor to use Set
8 export 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
14 export 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)
21 export 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}"`)
31 export function schemaHasRules(
33 rules: {[Key in string]?: boolean | Rule}
35 if (typeof schema == "boolean") return !schema
36 for (const key in schema) if (rules[key]) return true
40 export 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
46 export function schemaRefOrVal(
47 {topSchemaRef, schemaPath}: SchemaObjCxt,
50 $data?: string | false
51 ): Code | number | boolean {
53 if (typeof schema == "number" || typeof schema == "boolean") return schema
54 if (typeof schema == "string") return _`${schema}`
56 return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`
59 export function unescapeFragment(str: string): string {
60 return unescapeJsonPointer(decodeURIComponent(str))
63 export function escapeFragment(str: string | number): string {
64 return encodeURIComponent(escapeJsonPointer(str))
67 export function escapeJsonPointer(str: string | number): string {
68 if (typeof str == "number") return `${str}`
69 return str.replace(/~/g, "~0").replace(/\//g, "~1")
72 export function unescapeJsonPointer(str: string): string {
73 return str.replace(/~1/g, "/").replace(/~0/g, "~")
76 export function eachItem<T>(xs: T | T[], f: (x: T) => void): void {
77 if (Array.isArray(xs)) {
78 for (const x of xs) f(x)
84 type SomeEvaluated = EvaluatedProperties | EvaluatedItems
86 type MergeEvaluatedFunc<T extends SomeEvaluated> = (
89 to: Name | Exclude<T, true> | undefined,
93 interface 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
100 function makeMergeEvaluated<T extends SomeEvaluated>({
105 }: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {
106 return (gen, from, to, toName) => {
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
119 interface MergeEvaluated {
120 props: MergeEvaluatedFunc<EvaluatedProperties>
121 items: MergeEvaluatedFunc<EvaluatedItems>
124 export const mergeEvaluated: MergeEvaluated = {
125 props: makeMergeEvaluated({
126 mergeNames: (gen, from, to) =>
127 gen.if(_`${to} !== true && ${from} !== undefined`, () => {
130 () => gen.assign(to, true),
131 () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)
134 mergeToName: (gen, from, to) =>
135 gen.if(_`${to} !== true`, () => {
139 gen.assign(to, _`${to} || {}`)
140 setEvaluated(gen, to, from)
143 mergeValues: (from, to) => (from === true ? true : {...from, ...to}),
144 resultToName: evaluatedPropsToName,
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}`)
151 mergeToName: (gen, from, to) =>
152 gen.if(_`${to} !== true`, () =>
153 gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)
155 mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
156 resultToName: (gen, items) => gen.var("items", items),
160 export 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)
167 export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {
168 Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))
171 const snippets: {[S in string]?: _Code} = {}
173 export function useFunc(gen: CodeGen, f: {code: string}): Name {
174 return gen.scopeValue("func", {
176 code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),
185 export function getErrorPath(
186 dataProp: Name | string | number,
188 jsPropertySyntax?: boolean
191 if (dataProp instanceof Name) {
192 const isNumber = dataPropType === Type.Num
193 return jsPropertySyntax
195 ? _`"[" + ${dataProp} + "]"`
196 : _`"['" + ${dataProp} + "']"`
198 ? _`"/" + ${dataProp}`
199 : _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer
201 return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp)
204 export function checkStrictMode(
207 mode: boolean | "log" = it.opts.strictSchema
210 msg = `strict mode: ${msg}`
211 if (mode === true) throw new Error(msg)
212 it.self.logger.warn(msg)