module.exports = function(source) {
    
    var callback = this.async();
    var jsonObj = typeof source === "string" ? JSON.parse(source) : source;
    var query = loaderUtils.parseQuery(this.query);
    var parser = new $RefParser();
    
    this.cacheable && this.cacheable();
    
    parser.dereference(this.resourcePath)
        .then(handleResolveSuccess.bind(this))
        .catch(callback);
    
    function handleResolveSuccess(schema) {
        var json;
        
        if(query.mergeAllOf) {
            schema = mergeAllOf(schema);
        }
        
        json = JSON.stringify(schema, undefined, 2);
        
        this.value = [`module.exports = ${json};`]
        _.map(parser.$refs.paths(), (file) => this.addDependency(file));
        
        callback(null, this.value[0])
    }
}
Esempio n. 2
0
const getSwagger = function(settings, request, callback){
    if(settings.swagger && settings.swagger.swagger){
        let schema = Hoek.clone(settings.swagger);
        JSONDeRef.dereference(schema, callback);
    }else{
        var swagger = request.server.plugins['hapi-swagger'];
        swagger.getJSON({}, request, callback);
    }
}
Esempio n. 3
0
/**
 * Dereference a jsonschema
 */
function dereference(file, opts, cb) {
	parser.dereference(file.path, opts, (err, schema) => {
		if (err) {
			this.emit('error', new gutil.PluginError('gulp-jsonschema-deref', err, {fileName: file.path}));
		} else {
			file.contents = Buffer.from(JSON.stringify(schema));
			this.push(file);
		}
		cb();
	});
}
Esempio n. 4
0
builder.dereference = function (schema, callback) {

    JSONDeRef.dereference(schema, function (err, json) {

        if (!err) {
            delete json.definitions;
        } else {
            err = { 'error': 'fail to dereference schema' };
        }
        callback(err, json);
    });
};
Esempio n. 5
0
 this.whenReady = new Promise(function(resolve, reject) {
   console.log('Reading :', path.resolve(self.wd, self.config));
   $RefParser.dereference(path.resolve(self.wd, self.config), function(
     err,
     parsed
   ) {
     if (err) return reject(err);
     self.config = parsed;
     console.log('Parsed:', parsed);
     resolve(parsed);
   });
 });
Esempio n. 6
0
async function buildSchemas() {

  // Dereference and save every schema
  for (const file of glob.sync('schemas/*.json')) {
    const basename = nodePath.basename(file)
    if (excludeOnOutput.includes(basename)) continue
    const rawSchema = JSON.parse(fs.readFileSync(file))
    const schema = await $RefParser.dereference(rawSchema)
    const contents = JSON.stringify(schema, null, 2)
    fs.writeFileSync(`build/schemas/${basename}`, contents)
    console.log(`[+] build/schemas/${basename}.json`)
  }

}
Esempio n. 7
0
    it("should validate " + file, function() {
      var swagger = readFile(file);

      expect(swagger).to.be.an('object');
      if (_.isUndefined(swagger.swagger))
        return;

      validate(swagger);

      return RefParser.dereference(file, {
        $refs: {
          internal: false // Don't dereference internal $refs, only external
        }
      })
      .then(function(resolveSwagger) {
        validate(resolveSwagger);
      });
    })
Esempio n. 8
0
gulp.task('configdefaults', done => {
    jsRefParser.dereference(config.schema).then(schema => {
        const defs = [
            'basicLayerOptionsNode',
            'featureLayerOptionsNode',
            'compoundLayerOptionsNode',
            'dynamicLayerOptionsNode',

            'wmsLayerEntryNode',
            'dynamicLayerEntryNode'
        ];

        pkg.schemaDefaults = {};
        defs.forEach(def => {
            pkg.schemaDefaults[def] = jsDefaults(schema.definitions[def]);
        });

        done();
    });
});
jsf.resolve = (schema, refs, cwd) => {
  if (typeof refs === 'string') {
    cwd = refs;
    refs = {};
  }

  // normalize basedir (browser aware)
  cwd = cwd || (typeof process !== 'undefined' ? process.cwd() : '');
  cwd = `${cwd.replace(/\/+$/, '')}/`;

  const $refs = getRefs(refs);

  // identical setup as json-schema-sequelizer
  const fixedRefs = {
    order: 300,
    canRead: true,
    read(file, callback) {
      try {
        callback(null, $refs[file.url] || $refs[file.url.split('/').pop()]);
      } catch (e) {
        callback(e);
      }
    },
  };

  return $RefParser
    .dereference(cwd, schema, {
      resolve: {
        file: { order: 100 },
        http: { order: 200 },
        fixedRefs,
      },
      dereference: {
        circular: 'ignore',
      },
    }).then(sub => run($refs, sub, container));
};
Esempio n. 10
0
function parseV2(obj, dst, config, callback) {

    var $RefParser = require('json-schema-ref-parser');
    $RefParser.dereference(obj, function (err, input) {

        if (err) {
            return callback(err);
        }

        try {
            var marked_opt = {
                renderer: new marked.Renderer(),
                gfm: true,
                tables: true,
                breaks: false,
                pedantic: false,
                sanitize: true,
                smartLists: true,
                smartypants: false
            };

            var hasCodeSection = false;
            marked_opt.renderer.code = function (code, language) {
                hasCodeSection = true;
                if (language) {
                    return '<pre class="hljs"><code class="' + language + '">' + require('highlight.js').highlight(language, code, true).value + '</code></pre>';
                }
                else {
                    return '<pre class="hljs"><code>' + require('highlight.js').highlightAuto(code).value + '</code></pre>';
                }
            };
            marked.setOptions(marked_opt);
            indent_num = config.indent_num || indent_num;

            var result = livedoc.initContainer();
            result.name = input.info.title;
            result.summary = config.markdown ? marked(input.info.description || "") : input.info.description || "";
            if (input.info.version) {
                result.metadata["Version"] = input.info.version;
            }
            if (input.info.contact) {
                if (input.info.contact.email && input.info.contact.url) {
                    result.metadata["Contact"] = '<a href="mailto:' + input.info.contact.email + '">' + input.info.contact.email + '</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="' + input.info.contact.url + '" target="_blank">' + input.info.contact.url + '</a>';
                }
                else if (input.info.contact.email) {
                    result.metadata["Contact"] = '<a href="mailto:' + input.info.contact.email + '">' + input.info.contact.name ? input.info.contact.name : input.info.contact.email + '</a>';
                }
                else if (input.info.contact.url) {
                    if (isEmail(input.info.contact.name)) {
                        result.metadata["Contact"] = '<a href="mailto:' + input.info.contact.name + '">' + input.info.contact.name + '</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="' + input.info.contact.url + '" target="_blank">' + input.info.contact.url + '</a>';
                    }
                    else {
                        result.metadata["Contact"] = '<a href="' + input.info.contact.url + '" target="_blank">' + input.info.contact.name ? input.info.contact.name : input.info.contact.url + '</a>';
                    }
                }
                else if (input.info.contact.name) {

                    if (input.info.contact.name.toLowerCase().startsWith("http")) {
                        result.metadata["Contact"] = '<a href="' + input.info.contact.name + '" target="_blank">' + input.info.contact.name + '</a>';
                    }
                    else if (isEmail(input.info.contact.name)) {
                        result.metadata["Contact"] = '<a href="mailto:' + input.info.contact.name + '">' + input.info.contact.name + '</a>';
                    }
                    else {
                        result.metadata["Contact"] = input.info.contact.name;
                    }
                }
            }
            if (input.info.license) {

                if (input.info.license.url) {
                    result.metadata["License"] = '<a href="' + input.info.license.url + '" target="_blank">' + input.info.license.name + '</a>';
                }
                else {
                    result.metadata["License"] = input.info.license.name;
                }
            }
            if (input.info.termsOfService) {
                if (input.info.termsOfService.toUpperCase().startsWith("HTTP")) {
                    result.metadata["Terms of service"] = '<a href="' + input.info.termsOfService + '" target="_blank">' + input.info.termsOfService + '</a>';
                }
                else {
                    result.metadata["Terms of service"] = input.info.termsOfService;
                }
            }
            result.host = input.host || "";
            result.basePath = (input.basePath || "").replace(/\/$/, "");
            result.appConfig.showNav = !config.noNav;
            if (config.theme) {
                if (config.theme === "default") {
                    result.bgColor = {
                        default: "blue"
                        , GET: "blue"
                        , HEAD: "cyan"
                        , POST: "teal"
                        , PUT: "deep-purple"
                        , DELETE: "red"
                        , CONNECT: "purple"
                        , OPTIONS: "light-blue"
                        , TRACE: "blue-grey"
                        , PATCH: "deep-purple"
                    };
                }
                else if (typeof config.theme === "string") {
                    result.appConfig.bgColor = { default: config.theme };
                }
                else {
                    //custom
                    result.appConfig.bgColor = config.theme;
                }
            }
            result.appConfig.fixedNav = config.fixedNav;
            result.appConfig.showDevPlayground = !config.noRequest;

            if (!config.collapse) {
                config.collapse = {};
            }
            for (var path in input.paths) {

                var api = livedoc.initApi();
                result.apis.push(api);
                api.path = path;
                api.showMe = !config.collapse.path;
                var path_params = [];
                if ("parameters" in input.paths[path]) {
                    var path_scope_params = input.paths[path]["parameters"]; //array
                    for (var i = 0; i < path_scope_params.length; i++) {
                        var path_param = livedoc.initParam();
                        var input_path_param = path_scope_params[i];
                        if ("$ref" in input_path_param) {
                            input_path_param = input.parameters[input_path_param["$ref"].substr(13)]; //remove "#/parameters/" portion
                        }
                        path_param.name = input_path_param.name;
                        path_param.location = input_path_param.in;
                        path_param.desc = input_path_param.description;
                        path_param.required = input_path_param.required;
                        if (input_path_param.schema) {
                            path_param.schema = computeSchema(input_path_param.schema, input.definitions);
                        }
                        else if (input_path_param.type) {
                            path_param.schema = computeSchema(input_path_param.type, input.definitions, input_path_param);
                        }
                        if (path_param.name && path_param.location) {
                            path_params.push(path_param);
                        }
                    }
                }
                for (var method_name in input.paths[path]) {

                    if (method_name === "parameters") {
                        continue;
                    }
                    var method = livedoc.initMethod();
                    api.methods.push(method);
                    var input_method = input.paths[path][method_name];
                    method.name = method_name.toUpperCase();
                    method.tags = input_method.tags || [];
                    method.showMe = !config.collapse.method;
                    if (config.collapse.tool) {
                        method.showTool = !config.collapse.tool;
                    }
                    else {
                        method.showTool = false;
                    }
                    if (config.autoTags == undefined) {
                        config.autoTags = true;
                    }
                    if (config.autoTags) {
                        //tmp_tags is a place holder for token that will not be added to tags
                        var tmp_tags = method.tags.map(function (x) { return pluralize.singular(x.replace(/[ -_]/g, '').toLowerCase()); });

                        method.tags.push(method.name);
                        var segments = path.split("/");
                        segmentLoop:
                        for (var i = 0; i < segments.length; i++) {
                            var seg = segments[i].trim();
                            if (!seg || (seg.startsWith("{") && seg.endsWith("}"))) {
                                continue;
                            }

                            var normed_seg = seg.trim();
                            var singular = pluralize.singular(normed_seg);
                            normed_seg = pluralize.singular(normed_seg.toLowerCase().replace(/[ -_]/g, ''))
                            //don't add placeholder and plural when already have a singular in
                            //var singular = pluralize.singular(normed_seg);
                            if (tmp_tags.indexOf(normed_seg) > -1) {
                                continue;
                            }

                            for (var j = 0; j < method.tags.length; j++) {
                                var longerTag = method.tags[j].toLowerCase();

                                if (longerTag.startsWith(singular) || longerTag.startsWith(normed_seg)) {
                                    continue segmentLoop;
                                }

                            }
                            method.tags.push(singular);
                            tmp_tags.push(normed_seg);
                        }
                    }
                    method.tags = replace(' ', '-', method.tags);
                    method.tags.sort(sortTags);
                    input_method.summary = input_method.summary || "";
                    input_method.description = input_method.description || "";
                    method.summary = config.markdown ? marked(input_method.summary) : input_method.summary;
                    method.desc = config.markdown ? marked(input_method.description) : input_method.description;

                    if (path_params.length > 0) {
                        method.params = method.params.concat(path_params);
                    }
                    if (input_method.parameters) {
                        for (i = 0; i < input_method.parameters.length; i++) {
                            var param = livedoc.initParam();
                            method.params.push(param);
                            var parameter = input_method.parameters[i];
                            param.name = parameter.name;
                            param.location = parameter.in;
                            param.desc = parameter.description ? (config.markdown ? marked(parameter.description) : parameter.description) : "";
                            param.required = parameter.required;
                            param.value = parameter.default || "";
                            param.type = parameter.type || "text";
                            if (parameter.schema) {
                                param.schema = computeSchema(parameter.schema, input.definitions);
                            }
                            else if (parameter.type) {
                                param.schema = computeSchema(parameter.type, input.definitions, parameter);
                            }
                        }
                    }

                    for (var code in input_method.responses) {
                        var res = livedoc.initResponse();
                        method.responses.push(res);
                        var response = input_method.responses[code];
                        res.code = code;
                        if (response.examples && Object.keys(response.examples).length > 0) {
                            hasCodeSection = true;
                            // add example section
                            var allExamples = "";
                            for (var res_type in response.examples) {
                                var isJson = false;
                                allExamples += "*" + res_type + "*\n```";
                                lowered = res_type.toLowerCase();
                                if (lowered.includes("html")) {
                                    allExamples += 'html\n';
                                }
                                else if (lowered.includes("xml")) {
                                    allExamples += 'xml\n';
                                }
                                else if (lowered.includes("json")) {
                                    allExamples += 'json\n';
                                    isJson = true;
                                }
                                else {
                                    allExamples += "\n";
                                }
                                if (isJson && typeof response.examples[res_type] === 'string') {
                                    allExamples += response.examples[res_type];
                                }
                                else {
                                    allExamples += JSON.stringify(response.examples[res_type], null, indent_num);
                                }
                                allExamples += "\n```\n";
                            }
                            method.examples[code] = marked(allExamples.trim());
                        }

                        res.desc = response.description ? (config.markdown ? marked(response.description) : response.description) : "";
                        if (response.schema) {
                            res.schema = computeSchema(response.schema, input.definitions);
                        }
                    }
                }
            }
            var conf = {
                mode: config.format
                , pathParamLeftToken: "{"
                , pathParamRightToken: "}"
                , formDataToken: "formData"
                , allowHtml: config.markdown
                , syntaxHighlight: hasCodeSection
                , customCSS: config.customCSS
            };

            var footer = "";
            if (!config.noDate) {
                footer = ' __GENERATED_DATE__';
            }
            if (!config.noCredit) {
                footer = footer + ' by <a href="https://github.com/twskj/pretty-swag">pretty-swag</a>'
            }
            if (footer) {
                conf.footer = "Generated" + footer;
            }
            else {
                conf.noFooter = true;
            }
            if (config.format === "offline") {
                conf.outputFilename = dst;
            }
            try {
                if (typeof result.bgColor === "object") {
                    conf.mainColor = result.bgColor.default
                }
                else {
                    conf.mainColor = result.bgColor;
                }
            }
            catch (err) {
                conf.mainColor = 'blue';
            }

            if (config.home) {
                conf.home = config.home;
            }

            livedoc.generateHTML(JSON.stringify(result, null, indent_num), conf, function (err, data) {
                if (dst === null) {
                    return callback(err, data);
                }
                else if (conf.mode === "offline") {
                    return callback(err);
                }
                else {
                    const fs = require('fs');
                    return fs.writeFile(dst, data, 'utf8', function (err) {
                        if (err) {
                            return callback(err);
                        }
                        return callback(null);
                    });
                }
            });
        }
        catch (err) {
            callback(err);
        }
    });

}
Esempio n. 11
0
var fileContents = function (file, cb) {
  $RefParser.dereference(file, cb)
}