UNPKG

2.65 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.hasRef = void 0;
4const compile_1 = require("../../compile");
5const codegen_1 = require("../../compile/codegen");
6const ref_error_1 = require("../../compile/ref_error");
7const names_1 = require("../../compile/names");
8const ref_1 = require("../core/ref");
9const metadata_1 = require("./metadata");
10const def = {
11 keyword: "ref",
12 schemaType: "string",
13 code(cxt) {
14 (0, metadata_1.checkMetadata)(cxt);
15 const { gen, data, schema: ref, parentSchema, it } = cxt;
16 const { schemaEnv: { root }, } = it;
17 const valid = gen.name("valid");
18 if (parentSchema.nullable) {
19 gen.var(valid, (0, codegen_1._) `${data} === null`);
20 gen.if((0, codegen_1.not)(valid), validateJtdRef);
21 }
22 else {
23 gen.var(valid, false);
24 validateJtdRef();
25 }
26 cxt.ok(valid);
27 function validateJtdRef() {
28 var _a;
29 const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref];
30 if (!refSchema) {
31 throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`);
32 }
33 if (hasRef(refSchema) || !it.opts.inlineRefs)
34 callValidate(refSchema);
35 else
36 inlineRefSchema(refSchema);
37 }
38 function callValidate(schema) {
39 const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` }));
40 const v = (0, ref_1.getValidate)(cxt, sch);
41 const errsCount = gen.const("_errs", names_1.default.errors);
42 (0, ref_1.callRef)(cxt, v, sch, sch.$async);
43 gen.assign(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
44 }
45 function inlineRefSchema(schema) {
46 const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema });
47 cxt.subschema({
48 schema,
49 dataTypes: [],
50 schemaPath: codegen_1.nil,
51 topSchemaRef: schName,
52 errSchemaPath: `/definitions/${ref}`,
53 }, valid);
54 }
55 },
56};
57function hasRef(schema) {
58 for (const key in schema) {
59 let sch;
60 if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch)))
61 return true;
62 }
63 return false;
64}
65exports.hasRef = hasRef;
66exports.default = def;
67//# sourceMappingURL=ref.js.map
\No newline at end of file