'use strict';


const RefParser = require('json-schema-ref-parser');

const { getYaml } = require('./yaml');


/**
 * Dereference JSON references. RFC: https://tools.ietf.org/id/draft-pbryan-zyp-json-ref-03.html
 * I.e. { $ref: "path|url" } will be replaced by the target, which can be accessed locally (local path) or remotely (HTTP[S])
 * Targets can be JSON or YAML files.
 * Circular references are supported.
 * Siblings attributes to `$ref` will be merged (with higher priority), although this is not standard|spec behavior.
 * This function might throw for several reasons, e.g. YAML|JSON parsing error, cannot access remote|local file, etc.
 */
const dereferenceRefs = async function (obj) {
  return await RefParser.dereference(obj, {
    parse: {
      json: {
        allowEmpty: false,
      },
      yaml: {
        allowEmpty: false,
        // We need to override YAML parsing, as we use stricter YAML parsing (CORE_SCHEMA only)
        async parse({ data }) {
          if (Buffer.isBuffer(data)) {
            data = data.toString();
          }
          if (typeof data !== 'string') { return data; }
          // `content` cannot be `null` because of a bug with `json-schema-ref-parser`
          const content = await getYaml({ content: data }) || undefined;
          return content;
        },
      },
      text: false,
      binary: false,
    },
  });
};


module.exports = {
  dereferenceRefs,
};

@@ -9,16 +9,54 @@
 ict';%0A%0A%0A
+const %7B basename %7D = require('path');%0A
 const Re
@@ -775,16 +775,110 @@
 (obj, %7B%0A
+    resolve: %7B%0A      nodeModule: nodeModuleRefs.resolve,%0A      node: nodeRefs.resolve,%0A    %7D,%0A
     pars
@@ -1499,16 +1499,673 @@
     
-%7D,%0A  %7D);
+  nodeModule: nodeModuleRefs.parse,%0A      node: nodeRefs.parse,%0A    %7D,%0A  %7D);%0A%7D;%0A%0A// Allow referencing Node.js modules, e.g. %7B %22$ref%22: %22lodash%22 %7D%0Aconst nodeModuleRefs = %7B%0A  resolve: %7B%0A    order: 50,%0A    canRead: true,%0A    read: (%7B url %7D) =%3E require(basename(url)),%0A  %7D,%0A  parse: %7B%0A    allowEmpty: false,%0A    order: 500,%0A    canParse: true,%0A    parse: (%7B data %7D) =%3E data,%0A  %7D,%0A%7D;%0A%0A// Allow referencing JavaScript files, e.g. %7B %22$ref%22: %22./my_file.js%22 %7D%0Aconst nodeRefs = %7B%0A  resolve: %7B%0A    order: 60,%0A    canRead: '.js',%0A    read: (%7B url %7D) =%3E require(url),%0A  %7D,%0A  parse: %7B%0A    allowEmpty: false,%0A    order: 600,%0A    canParse: '.js',%0A    parse: (%7B data %7D) =%3E data,%0A  %7D,
 %0A%7D;%0A

Allow $ref to reference Node.js modules or files