ref.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.hasRef = void 0;
  4. const compile_1 = require("../../compile");
  5. const codegen_1 = require("../../compile/codegen");
  6. const ref_error_1 = require("../../compile/ref_error");
  7. const names_1 = require("../../compile/names");
  8. const ref_1 = require("../core/ref");
  9. const metadata_1 = require("./metadata");
  10. const 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. };
  57. function 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. }
  65. exports.hasRef = hasRef;
  66. exports.default = def;
  67. //# sourceMappingURL=ref.js.map