UNPKG

1.12 kBPlain TextView Raw
1import type {CodeKeywordDefinition} from "../../types"
2import type {KeywordCxt} from "../../compile/validate"
3import {_, getProperty, Code} from "../../compile/codegen"
4import N from "../../compile/names"
5import {SchemaEnv, compileSchema} from "../../compile"
6import {getValidate} from "../core/ref"
7
8const def: CodeKeywordDefinition = {
9 keyword: "$dynamicAnchor",
10 schemaType: "string",
11 code: (cxt) => dynamicAnchor(cxt, cxt.schema),
12}
13
14export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void {
15 const {gen, it} = cxt
16 it.schemaEnv.root.dynamicAnchors[anchor] = true
17 const v = _`${N.dynamicAnchors}${getProperty(anchor)}`
18 const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt)
19 gen.if(_`!${v}`, () => gen.assign(v, validate))
20}
21
22function _getValidate(cxt: KeywordCxt): Code {
23 const {schemaEnv, schema, self} = cxt.it
24 const {root, baseId, localRefs, meta} = schemaEnv.root
25 const {schemaId} = self.opts
26 const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta})
27 compileSchema.call(self, sch)
28 return getValidate(cxt, sch)
29}
30
31export default def