| 1 | import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" |
| 2 | import type {KeywordCxt} from "../../compile/validate" |
| 3 | import {usePattern} from "../code" |
| 4 | import {useFunc} from "../../compile/util" |
| 5 | import {_, str} from "../../compile/codegen" |
| 6 | |
| 7 | export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}> |
| 8 | |
| 9 | const error: KeywordErrorDefinition = { |
| 10 | message: ({schemaCode}) => str`must match pattern "${schemaCode}"`, |
| 11 | params: ({schemaCode}) => _`{pattern: ${schemaCode}}`, |
| 12 | } |
| 13 | |
| 14 | const def: CodeKeywordDefinition = { |
| 15 | keyword: "pattern", |
| 16 | type: "string", |
| 17 | schemaType: "string", |
| 18 | $data: true, |
| 19 | error, |
| 20 | code(cxt: KeywordCxt) { |
| 21 | const {gen, data, $data, schema, schemaCode, it} = cxt |
| 22 | const u = it.opts.unicodeRegExp ? "u" : "" |
| 23 | if ($data) { |
| 24 | const {regExp} = it.opts.code |
| 25 | const regExpCode = regExp.code === "new RegExp" ? _`new RegExp` : useFunc(gen, regExp) |
| 26 | const valid = gen.let("valid") |
| 27 | gen.try( |
| 28 | () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`), |
| 29 | () => gen.assign(valid, false) |
| 30 | ) |
| 31 | cxt.fail$data(_`!${valid}`) |
| 32 | } else { |
| 33 | const regExp = usePattern(cxt, schema) |
| 34 | cxt.fail$data(_`!${regExp}.test(${data})`) |
| 35 | } |
| 36 | }, |
| 37 | } |
| 38 | |
| 39 | export default def |