swagger-client
Version:
swagger-client is a javascript client for use with swaggering APIs.
1,613 lines (1,384 loc) • 1.65 MB
JavaScript
/**
* swagger-client - swagger-client is a javascript client for use with swaggering APIs.
* @version v2.1.19
* @link http://swagger.io
* @license Apache-2.0
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.SwaggerClient = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var auth = require('./lib/auth');
var helpers = require('./lib/helpers');
var SwaggerClient = require('./lib/client');
var deprecationWrapper = function (url, options) {
helpers.log('This is deprecated, use "new SwaggerClient" instead.');
return new SwaggerClient(url, options);
};
/* Here for IE8 Support */
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
};
}
/* Here for IE8 Support */
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
/* Here for node 10.x support */
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
module.exports = SwaggerClient;
SwaggerClient.ApiKeyAuthorization = auth.ApiKeyAuthorization;
SwaggerClient.PasswordAuthorization = auth.PasswordAuthorization;
SwaggerClient.CookieAuthorization = auth.CookieAuthorization;
SwaggerClient.SwaggerApi = deprecationWrapper;
SwaggerClient.SwaggerClient = deprecationWrapper;
SwaggerClient.SchemaMarkup = require('./lib/schema-markup');
},{"./lib/auth":2,"./lib/client":3,"./lib/helpers":4,"./lib/schema-markup":7}],2:[function(require,module,exports){
'use strict';
var helpers = require('./helpers');
var btoa = require('btoa'); // jshint ignore:line
var CookieJar = require('cookiejar').CookieJar;
var _ = {
each: require('lodash-compat/collection/each'),
includes: require('lodash-compat/collection/includes'),
isObject: require('lodash-compat/lang/isObject'),
isArray: require('lodash-compat/lang/isArray')
};
/**
* SwaggerAuthorizations applys the correct authorization to an operation being executed
*/
var SwaggerAuthorizations = module.exports.SwaggerAuthorizations = function (authz) {
this.authz = authz || {};
};
/**
* Add auths to the hash
* Will overwrite any existing
*
*/
SwaggerAuthorizations.prototype.add = function (name, auth) {
if(_.isObject(name)) {
for (var key in name) {
this.authz[key] = name[key];
}
} else if(typeof name === 'string' ){
this.authz[name] = auth;
}
return auth;
};
SwaggerAuthorizations.prototype.remove = function (name) {
return delete this.authz[name];
};
SwaggerAuthorizations.prototype.apply = function (obj, securities) {
var status = true;
var applyAll = !securities;
var flattenedSecurities = [];
// favor the object-level authorizations over global
var authz = obj.clientAuthorizations || this.authz;
// Securities could be [ {} ]
_.each(securities, function (obj, key) {
// Make sure we account for securities being [ str ]
if(typeof key === 'string') {
flattenedSecurities.push(key);
}
// Flatten keys in to our array
_.each(obj, function (val, key) {
flattenedSecurities.push(key);
});
});
_.each(authz, function (auth, authName) {
if(applyAll || _.includes(flattenedSecurities, authName)) {
var newStatus = auth.apply(obj);
status = status && !!newStatus; // logical ORs regarding status
}
});
return status;
};
/**
* ApiKeyAuthorization allows a query param or header to be injected
*/
var ApiKeyAuthorization = module.exports.ApiKeyAuthorization = function (name, value, type) {
this.name = name;
this.value = value;
this.type = type;
};
ApiKeyAuthorization.prototype.apply = function (obj) {
if (this.type === 'query') {
// see if already applied. If so, don't do it again
var qp;
if (obj.url.indexOf('?') > 0) {
qp = obj.url.substring(obj.url.indexOf('?') + 1);
var parts = qp.split('&');
if(parts && parts.length > 0) {
for(var i = 0; i < parts.length; i++) {
var kv = parts[i].split('=');
if(kv && kv.length > 0) {
if (kv[0] === this.name) {
// skip it
return false;
}
}
}
}
}
if (obj.url.indexOf('?') > 0) {
obj.url = obj.url + '&' + this.name + '=' + this.value;
} else {
obj.url = obj.url + '?' + this.name + '=' + this.value;
}
return true;
} else if (this.type === 'header') {
if(typeof obj.headers[this.name] === 'undefined') {
obj.headers[this.name] = this.value;
}
return true;
}
};
var CookieAuthorization = module.exports.CookieAuthorization = function (cookie) {
this.cookie = cookie;
};
CookieAuthorization.prototype.apply = function (obj) {
obj.cookieJar = obj.cookieJar || new CookieJar();
obj.cookieJar.setCookie(this.cookie);
return true;
};
/**
* Password Authorization is a basic auth implementation
*/
var PasswordAuthorization = module.exports.PasswordAuthorization = function (username, password) {
if (arguments.length === 3) {
helpers.log('PasswordAuthorization: the \'name\' argument has been removed, pass only username and password');
username = arguments[1];
password = arguments[2];
}
this.username = username;
this.password = password;
};
PasswordAuthorization.prototype.apply = function (obj) {
if(typeof obj.headers.Authorization === 'undefined') {
obj.headers.Authorization = 'Basic ' + btoa(this.username + ':' + this.password);
}
return true;
};
},{"./helpers":4,"btoa":13,"cookiejar":18,"lodash-compat/collection/each":52,"lodash-compat/collection/includes":55,"lodash-compat/lang/isArray":140,"lodash-compat/lang/isObject":144}],3:[function(require,module,exports){
'use strict';
var _ = {
bind: require('lodash-compat/function/bind'),
cloneDeep: require('lodash-compat/lang/cloneDeep'),
find: require('lodash-compat/collection/find'),
forEach: require('lodash-compat/collection/forEach'),
indexOf: require('lodash-compat/array/indexOf'),
isArray: require('lodash-compat/lang/isArray'),
isObject: require('lodash-compat/lang/isObject'),
isFunction: require('lodash-compat/lang/isFunction'),
isPlainObject: require('lodash-compat/lang/isPlainObject'),
isUndefined: require('lodash-compat/lang/isUndefined')
};
var auth = require('./auth');
var helpers = require('./helpers');
var Model = require('./types/model');
var Operation = require('./types/operation');
var OperationGroup = require('./types/operationGroup');
var Resolver = require('./resolver');
var SwaggerHttp = require('./http');
var SwaggerSpecConverter = require('./spec-converter');
var Q = require('q');
// We have to keep track of the function/property names to avoid collisions for tag names which are used to allow the
// following usage: 'client.{tagName}'
var reservedClientTags = [
'apis',
'authorizationScheme',
'authorizations',
'basePath',
'build',
'buildFrom1_1Spec',
'buildFrom1_2Spec',
'buildFromSpec',
'clientAuthorizations',
'convertInfo',
'debug',
'defaultErrorCallback',
'defaultSuccessCallback',
'enableCookies',
'fail',
'failure',
'finish',
'help',
'host',
'idFromOp',
'info',
'initialize',
'isBuilt',
'isValid',
'modelPropertyMacro',
'models',
'modelsArray',
'options',
'parameterMacro',
'parseUri',
'progress',
'resourceCount',
'sampleModels',
'selfReflect',
'setConsolidatedModels',
'spec',
'supportedSubmitMethods',
'swaggerRequestHeaders',
'tagFromLabel',
'title',
'url',
'useJQuery',
'jqueryAjaxCache'
];
// We have to keep track of the function/property names to avoid collisions for tag names which are used to allow the
// following usage: 'client.apis.{tagName}'
var reservedApiTags = [
'apis',
'asCurl',
'description',
'externalDocs',
'help',
'label',
'name',
'operation',
'operations',
'operationsArray',
'path',
'tag'
];
var supportedOperationMethods = ['delete', 'get', 'head', 'options', 'patch', 'post', 'put'];
var SwaggerClient = module.exports = function (url, options) {
this.authorizations = null;
this.authorizationScheme = null;
this.basePath = null;
this.debug = false;
this.enableCookies = false;
this.info = null;
this.isBuilt = false;
this.isValid = false;
this.modelsArray = [];
this.resourceCount = 0;
this.url = null;
this.useJQuery = false;
this.jqueryAjaxCache = false;
this.swaggerObject = {};
this.deferredClient = undefined;
this.clientAuthorizations = new auth.SwaggerAuthorizations();
if (typeof url !== 'undefined') {
return this.initialize(url, options);
} else {
return this;
}
};
SwaggerClient.prototype.initialize = function (url, options) {
this.models = {};
this.sampleModels = {};
if (typeof url === 'string') {
this.url = url;
} else if (_.isObject(url)) {
options = url;
this.url = options.url;
}
if(this.url && this.url.indexOf('http:') === -1 && this.url.indexOf('https:') === -1) {
// no protocol, so we can only use window if it exists
if(typeof(window) !== 'undefined' && window && window.location) {
this.url = window.location.origin + this.url;
}
}
options = options || {};
this.clientAuthorizations.add(options.authorizations);
this.swaggerRequestHeaders = options.swaggerRequestHeaders || 'application/json;charset=utf-8,*/*';
this.defaultSuccessCallback = options.defaultSuccessCallback || null;
this.defaultErrorCallback = options.defaultErrorCallback || null;
this.modelPropertyMacro = options.modelPropertyMacro || null;
this.parameterMacro = options.parameterMacro || null;
this.usePromise = options.usePromise || null;
// operation request timeout default
this.timeout = options.timeout || null;
// default to request timeout when not specified
this.fetchSpecTimeout = typeof options.fetchSpecTimeout !== 'undefined'
? options.fetchSpecTimeout
: options.timeout || null;
if(this.usePromise) {
this.deferredClient = Q.defer();
}
if (typeof options.success === 'function') {
this.success = options.success;
}
if (options.useJQuery) {
this.useJQuery = options.useJQuery;
}
if (options.jqueryAjaxCache) {
this.jqueryAjaxCache = options.jqueryAjaxCache;
}
if (options.enableCookies) {
this.enableCookies = options.enableCookies;
}
this.options = options || {};
// maybe don't need this?
this.options.timeout = this.timeout;
this.options.fetchSpecTimeout = this.fetchSpecTimeout;
this.supportedSubmitMethods = options.supportedSubmitMethods || [];
this.failure = options.failure || function (err) { throw err; };
this.progress = options.progress || function () {};
this.spec = _.cloneDeep(options.spec); // Clone so we do not alter the provided document
if (options.scheme) {
this.scheme = options.scheme;
}
if (this.usePromise || typeof options.success === 'function') {
this.ready = true;
return this.build();
}
};
SwaggerClient.prototype.build = function (mock) {
if (this.isBuilt) {
return this;
}
var self = this;
if (this.spec) {
this.progress('fetching resource list; Please wait.');
} else {
this.progress('fetching resource list: ' + this.url + '; Please wait.');
}
var obj = {
useJQuery: this.useJQuery,
jqueryAjaxCache: this.jqueryAjaxCache,
url: this.url,
method: 'get',
headers: {
accept: this.swaggerRequestHeaders
},
on: {
error: function (response) {
if (self.url.substring(0, 4) !== 'http') {
return self.fail('Please specify the protocol for ' + self.url);
} else if (response.errObj && (response.errObj.code === 'ECONNABORTED' || response.errObj.message.indexOf('timeout') != -1)) {
return self.fail('Request timed out after ' + self.fetchSpecTimeout + 'ms');
} else if (response.status === 0) {
return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
} else if (response.status === 404) {
return self.fail('Can\'t read swagger JSON from ' + self.url);
} else {
return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
}
},
response: function (resp) {
var responseObj = resp.obj;
if(!responseObj) {
return self.fail('failed to parse JSON/YAML response');
}
self.swaggerVersion = responseObj.swaggerVersion;
self.swaggerObject = responseObj;
if (responseObj.swagger && parseInt(responseObj.swagger) === 2) {
self.swaggerVersion = responseObj.swagger;
new Resolver().resolve(responseObj, self.url, self.buildFromSpec, self);
self.isValid = true;
} else {
var converter = new SwaggerSpecConverter();
self.oldSwaggerObject = self.swaggerObject;
converter.setDocumentationLocation(self.url);
converter.convert(responseObj, self.clientAuthorizations, self.options, function(spec) {
self.swaggerObject = spec;
new Resolver().resolve(spec, self.url, self.buildFromSpec, self);
self.isValid = true;
});
}
}
}
};
// only set timeout when specified
if (this.fetchSpecTimeout) {
obj.timeout = this.fetchSpecTimeout;
}
if (this.spec) {
self.swaggerObject = this.spec;
setTimeout(function () {
new Resolver().resolve(self.spec, self.url, self.buildFromSpec, self);
}, 10);
} else {
this.clientAuthorizations.apply(obj);
if (mock) {
return obj;
}
new SwaggerHttp().execute(obj, this.options);
}
return (this.usePromise) ? this.deferredClient.promise : this;
};
SwaggerClient.prototype.buildFromSpec = function (response) {
if (this.isBuilt) {
return this;
}
this.apis = {};
this.apisArray = [];
this.basePath = response.basePath || '';
this.consumes = response.consumes;
this.host = response.host || '';
this.info = response.info || {};
this.produces = response.produces;
this.schemes = response.schemes || [];
this.securityDefinitions = response.securityDefinitions;
this.security = response.security;
this.title = response.title || '';
if (response.externalDocs) {
this.externalDocs = response.externalDocs;
}
// legacy support
this.authSchemes = response.securityDefinitions;
var definedTags = {};
var k;
if (Array.isArray(response.tags)) {
definedTags = {};
for (k = 0; k < response.tags.length; k++) {
var t = response.tags[k];
definedTags[t.name] = t;
}
}
var location;
if (typeof this.url === 'string') {
location = this.parseUri(this.url);
if (typeof this.scheme === 'undefined' && typeof this.schemes === 'undefined' || this.schemes.length === 0) {
if(typeof window !== 'undefined') {
// use the window scheme
this.scheme = window.location.scheme;
}
else {
this.scheme = location.scheme || 'http';
}
} else if (typeof this.scheme === 'undefined') {
if(typeof window !== 'undefined') {
var scheme = window.location.protocol.replace(':','');
if(this.schemes.indexOf(scheme) !== -1) {
this.scheme = scheme;
}
else {
this.scheme = 'http';
}
}
else {
this.scheme = this.schemes[0] || location.scheme;
}
}
if (typeof this.host === 'undefined' || this.host === '') {
this.host = location.host;
if (location.port) {
this.host = this.host + ':' + location.port;
}
}
}
else {
if (typeof this.schemes === 'undefined' || this.schemes.length === 0) {
this.scheme = 'http';
}
else if (typeof this.scheme === 'undefined') {
this.scheme = this.schemes[0];
}
}
this.definitions = response.definitions;
var key;
for (key in this.definitions) {
var model = new Model(key, this.definitions[key], this.models, this.modelPropertyMacro);
if (model) {
this.models[key] = model;
}
}
// get paths, create functions for each operationId
var self = this;
// Bind help to 'client.apis'
self.apis.help = _.bind(self.help, self);
_.forEach(response.paths, function (pathObj, path) {
// Only process a path if it's an object
if (!_.isPlainObject(pathObj)) {
return;
}
_.forEach(supportedOperationMethods, function (method) {
var operation = pathObj[method];
if (_.isUndefined(operation)) {
// Operation does not exist
return;
} else if (!_.isPlainObject(operation)) {
// Operation exists but it is not an Operation Object. Since this is invalid, log it.
helpers.log('The \'' + method + '\' operation for \'' + path + '\' path is not an Operation Object');
return;
}
var tags = operation.tags;
if (_.isUndefined(tags) || !_.isArray(tags) || tags.length === 0) {
tags = operation.tags = [ 'default' ];
}
var operationId = self.idFromOp(path, method, operation);
var operationObject = new Operation(self,
operation.scheme,
operationId,
method,
path,
operation,
self.definitions,
self.models,
self.clientAuthorizations);
// bind self operation's execute command to the api
_.forEach(tags, function (tag) {
var clientProperty = _.indexOf(reservedClientTags, tag) > -1 ? '_' + tag : tag;
var apiProperty = _.indexOf(reservedApiTags, tag) > -1 ? '_' + tag : tag;
var operationGroup = self[clientProperty];
if (clientProperty !== tag) {
helpers.log('The \'' + tag + '\' tag conflicts with a SwaggerClient function/property name. Use \'client.' +
clientProperty + '\' or \'client.apis.' + tag + '\' instead of \'client.' + tag + '\'.');
}
if (apiProperty !== tag) {
helpers.log('The \'' + tag + '\' tag conflicts with a SwaggerClient operation function/property name. Use ' +
'\'client.apis.' + apiProperty + '\' instead of \'client.apis.' + tag + '\'.');
}
if (_.indexOf(reservedApiTags, operationId) > -1) {
helpers.log('The \'' + operationId + '\' operationId conflicts with a SwaggerClient operation ' +
'function/property name. Use \'client.apis.' + apiProperty + '._' + operationId +
'\' instead of \'client.apis.' + apiProperty + '.' + operationId + '\'.');
operationId = '_' + operationId;
operationObject.nickname = operationId; // So 'client.apis.[tag].operationId.help() works properly
}
if (_.isUndefined(operationGroup)) {
operationGroup = self[clientProperty] = self.apis[apiProperty] = {};
operationGroup.operations = {};
operationGroup.label = apiProperty;
operationGroup.apis = {};
var tagDef = definedTags[tag];
if (!_.isUndefined(tagDef)) {
operationGroup.description = tagDef.description;
operationGroup.externalDocs = tagDef.externalDocs;
}
self[clientProperty].help = _.bind(self.help, operationGroup);
self.apisArray.push(new OperationGroup(tag, operationGroup.description, operationGroup.externalDocs, operationObject));
}
operationId = self.makeUniqueOperationId(operationId, self.apis[apiProperty]);
// Bind tag help
if (!_.isFunction(operationGroup.help)) {
operationGroup.help = _.bind(self.help, operationGroup);
}
// bind to the apis object
self.apis[apiProperty][operationId] = operationGroup[operationId] = _.bind(operationObject.execute,
operationObject);
self.apis[apiProperty][operationId].help = operationGroup[operationId].help = _.bind(operationObject.help,
operationObject);
self.apis[apiProperty][operationId].asCurl = operationGroup[operationId].asCurl = _.bind(operationObject.asCurl,
operationObject);
operationGroup.apis[operationId] = operationGroup.operations[operationId] = operationObject;
// legacy UI feature
var api = _.find(self.apisArray, function (api) {
return api.tag === tag;
});
if (api) {
api.operationsArray.push(operationObject);
}
});
});
});
// sort the apisArray according to the tags
var sortedApis = [];
_.forEach(Object.keys(definedTags), function (tag) {
var _apiToAdd;
var pos;
for(pos in self.apisArray) {
var _api = self.apisArray[pos];
if(_api && tag === _api.name) {
sortedApis.push(_api);
self.apisArray[pos] = null;
}
}
});
// add anything left
_.forEach(self.apisArray, function (api) {
if(api) {
sortedApis.push(api);
}
});
self.apisArray = sortedApis;
_.forEach(response.definitions, function (definitionObj, definition) {
definitionObj['id'] = definition.toLowerCase();
definitionObj['name'] = definition;
self.modelsArray.push(definitionObj);
});
this.isBuilt = true;
if (this.usePromise) {
this.isValid = true;
this.isBuilt = true;
this.deferredClient.resolve(this);
return this.deferredClient.promise;
}
if (this.success) {
this.success();
}
return this;
};
SwaggerClient.prototype.makeUniqueOperationId = function(operationId, api) {
var count = 0;
var name = operationId;
// make unique across this operation group
while(true) {
var matched = false;
_.forEach(api.operations, function (operation) {
if(operation.nickname === name) {
matched = true;
}
});
if(!matched) {
return name;
}
name = operationId + '_' + count;
count ++;
}
return operationId;
};
SwaggerClient.prototype.parseUri = function (uri) {
var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
var parts = urlParseRE.exec(uri);
return {
scheme: parts[4] ? parts[4].replace(':','') : undefined,
host: parts[11],
port: parts[12],
path: parts[15]
};
};
SwaggerClient.prototype.help = function (dontPrint) {
var output = '';
if (this instanceof SwaggerClient) {
_.forEach(this.apis, function (api, name) {
if (_.isPlainObject(api)) {
output += 'operations for the \'' + name + '\' tag\n';
_.forEach(api.operations, function (operation, name) {
output += ' * ' + name + ': ' + operation.summary + '\n';
});
}
});
} else if (this instanceof OperationGroup || _.isPlainObject(this)) {
output += 'operations for the \'' + this.label + '\' tag\n';
_.forEach(this.apis, function (operation, name) {
output += ' * ' + name + ': ' + operation.summary + '\n';
});
}
if (dontPrint) {
return output;
} else {
helpers.log(output);
return output;
}
};
SwaggerClient.prototype.tagFromLabel = function (label) {
return label;
};
SwaggerClient.prototype.idFromOp = function (path, httpMethod, op) {
if(!op || !op.operationId) {
op = op || {};
op.operationId = httpMethod + '_' + path;
}
var opId = op.operationId.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_') || (path.substring(1) + '_' + httpMethod);
opId = opId.replace(/((_){2,})/g, '_');
opId = opId.replace(/^(_)*/g, '');
opId = opId.replace(/([_])*$/g, '');
return opId;
};
SwaggerClient.prototype.setHost = function (host) {
this.host = host;
if(this.apis) {
_.forEach(this.apis, function(api) {
if(api.operations) {
_.forEach(api.operations, function(operation) {
operation.host = host;
});
}
});
}
};
SwaggerClient.prototype.setBasePath = function (basePath) {
this.basePath = basePath;
if(this.apis) {
_.forEach(this.apis, function(api) {
if(api.operations) {
_.forEach(api.operations, function(operation) {
operation.basePath = basePath;
});
}
});
}
};
SwaggerClient.prototype.setSchemes = function (schemes) {
this.schemes = schemes;
if(schemes && schemes.length > 0) {
if(this.apis) {
_.forEach(this.apis, function (api) {
if (api.operations) {
_.forEach(api.operations, function (operation) {
operation.scheme = schemes[0];
});
}
});
}
}
};
SwaggerClient.prototype.fail = function (message) {
if (this.usePromise) {
this.deferredClient.reject(message);
return this.deferredClient.promise;
} else {
if (this.failure) {
this.failure(message);
}
else {
this.failure(message);
}
}
};
},{"./auth":2,"./helpers":4,"./http":5,"./resolver":6,"./spec-converter":8,"./types/model":9,"./types/operation":10,"./types/operationGroup":11,"lodash-compat/array/indexOf":49,"lodash-compat/collection/find":53,"lodash-compat/collection/forEach":54,"lodash-compat/function/bind":58,"lodash-compat/lang/cloneDeep":138,"lodash-compat/lang/isArray":140,"lodash-compat/lang/isFunction":142,"lodash-compat/lang/isObject":144,"lodash-compat/lang/isPlainObject":145,"lodash-compat/lang/isUndefined":148,"q":157}],4:[function(require,module,exports){
(function (process){
'use strict';
var _ = {
isPlainObject: require('lodash-compat/lang/isPlainObject'),
indexOf: require('lodash-compat/array/indexOf')
};
module.exports.__bind = function (fn, me) {
return function(){
return fn.apply(me, arguments);
};
};
var log = module.exports.log = function() {
// Only log if available and we're not testing
if (console && process.env.NODE_ENV !== 'test') {
console.log(Array.prototype.slice.call(arguments)[0]);
}
};
module.exports.fail = function (message) {
log(message);
};
var optionHtml = module.exports.optionHtml = function (label, value) {
return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
};
var resolveSchema = module.exports.resolveSchema = function (schema) {
if (_.isPlainObject(schema.schema)) {
schema = resolveSchema(schema.schema);
}
return schema;
};
var simpleRef = module.exports.simpleRef = function (name) {
if (typeof name === 'undefined') {
return null;
}
if (name.indexOf('#/definitions/') === 0) {
return name.substring('#/definitions/'.length);
} else {
return name;
}
};
}).call(this,require('_process'))
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImxpYi9oZWxwZXJzLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiJ3VzZSBzdHJpY3QnO1xuXG52YXIgXyA9IHtcbiAgaXNQbGFpbk9iamVjdDogcmVxdWlyZSgnbG9kYXNoLWNvbXBhdC9sYW5nL2lzUGxhaW5PYmplY3QnKSxcbiAgaW5kZXhPZjogcmVxdWlyZSgnbG9kYXNoLWNvbXBhdC9hcnJheS9pbmRleE9mJylcbn07XG5cbm1vZHVsZS5leHBvcnRzLl9fYmluZCA9IGZ1bmN0aW9uIChmbiwgbWUpIHtcbiAgcmV0dXJuIGZ1bmN0aW9uKCl7XG4gICAgcmV0dXJuIGZuLmFwcGx5KG1lLCBhcmd1bWVudHMpO1xuICB9O1xufTtcblxudmFyIGxvZyA9IG1vZHVsZS5leHBvcnRzLmxvZyA9IGZ1bmN0aW9uKCkge1xuICAvLyBPbmx5IGxvZyBpZiBhdmFpbGFibGUgYW5kIHdlJ3JlIG5vdCB0ZXN0aW5nXG4gIGlmIChjb25zb2xlICYmIHByb2Nlc3MuZW52Lk5PREVfRU5WICE9PSAndGVzdCcpIHtcbiAgICBjb25zb2xlLmxvZyhBcnJheS5wcm90b3R5cGUuc2xpY2UuY2FsbChhcmd1bWVudHMpWzBdKTtcbiAgfVxufTtcblxubW9kdWxlLmV4cG9ydHMuZmFpbCA9IGZ1bmN0aW9uIChtZXNzYWdlKSB7XG4gIGxvZyhtZXNzYWdlKTtcbn07XG5cbnZhciBvcHRpb25IdG1sID0gbW9kdWxlLmV4cG9ydHMub3B0aW9uSHRtbCA9IGZ1bmN0aW9uIChsYWJlbCwgdmFsdWUpIHtcbiAgcmV0dXJuICc8dHI+PHRkIGNsYXNzPVwib3B0aW9uTmFtZVwiPicgKyBsYWJlbCArICc6PC90ZD48dGQ+JyArIHZhbHVlICsgJzwvdGQ+PC90cj4nO1xufTtcblxudmFyIHJlc29sdmVTY2hlbWEgPSBtb2R1bGUuZXhwb3J0cy5yZXNvbHZlU2NoZW1hID0gZnVuY3Rpb24gKHNjaGVtYSkge1xuICBpZiAoXy5pc1BsYWluT2JqZWN0KHNjaGVtYS5zY2hlbWEpKSB7XG4gICAgc2NoZW1hID0gcmVzb2x2ZVNjaGVtYShzY2hlbWEuc2NoZW1hKTtcbiAgfVxuXG4gIHJldHVybiBzY2hlbWE7XG59O1xuXG52YXIgc2ltcGxlUmVmID0gbW9kdWxlLmV4cG9ydHMuc2ltcGxlUmVmID0gZnVuY3Rpb24gKG5hbWUpIHtcbiAgaWYgKHR5cGVvZiBuYW1lID09PSAndW5kZWZpbmVkJykge1xuICAgIHJldHVybiBudWxsO1xuICB9XG5cbiAgaWYgKG5hbWUuaW5kZXhPZignIy9kZWZpbml0aW9ucy8nKSA9PT0gMCkge1xuICAgIHJldHVybiBuYW1lLnN1YnN0cmluZygnIy9kZWZpbml0aW9ucy8nLmxlbmd0aCk7XG4gIH0gZWxzZSB7XG4gICAgcmV0dXJuIG5hbWU7XG4gIH1cbn07XG5cbiJdfQ==
},{"_process":12,"lodash-compat/array/indexOf":49,"lodash-compat/lang/isPlainObject":145}],5:[function(require,module,exports){
'use strict';
var helpers = require('./helpers');
var request = require('superagent');
var jsyaml = require('js-yaml');
var _ = {
isObject: require('lodash-compat/lang/isObject'),
keys: require('lodash-compat/object/keys')
};
/*
* JQueryHttpClient is a light-weight, node or browser HTTP client
*/
var JQueryHttpClient = function () {
this.type = 'JQueryHttpClient';
};
/*
* SuperagentHttpClient is a light-weight, node or browser HTTP client
*/
var SuperagentHttpClient = function () {
this.type = 'SuperagentHttpClient';
};
/**
* SwaggerHttp is a wrapper for executing requests
*/
var SwaggerHttp = module.exports = function () {};
SwaggerHttp.prototype.execute = function (obj, opts) {
var client;
if(opts && opts.client) {
client = opts.client;
}
else {
client = new SuperagentHttpClient(opts);
}
client.opts = opts || {};
// legacy support
var hasJQuery = false;
if(typeof window !== 'undefined') {
if(typeof window.jQuery !== 'undefined') {
hasJQuery = true;
}
}
// OPTIONS support
if(obj.method.toLowerCase() === 'options' && client.type === 'SuperagentHttpClient') {
log('forcing jQuery as OPTIONS are not supported by SuperAgent');
obj.useJQuery = true;
}
if(this.isInternetExplorer() && (obj.useJQuery === false || !hasJQuery )) {
throw new Error('Unsupported configuration! JQuery is required but not available');
}
if ((obj && obj.useJQuery === true) || this.isInternetExplorer() && hasJQuery) {
client = new JQueryHttpClient(opts);
}
var success = obj.on.response;
var error = obj.on.error;
var requestInterceptor = function(data) {
if(opts && opts.requestInterceptor) {
data = opts.requestInterceptor.apply(data);
}
return data;
};
var responseInterceptor = function(data) {
if(opts && opts.responseInterceptor) {
data = opts.responseInterceptor.apply(data);
}
return success(data);
};
var errorInterceptor = function(data) {
if(opts && opts.responseInterceptor) {
data = opts.responseInterceptor.apply(data);
}
error(data);
};
obj.on.error = function(data) {
errorInterceptor(data);
};
obj.on.response = function(data) {
responseInterceptor(data);
};
if (_.isObject(obj) && _.isObject(obj.body)) {
// special processing for file uploads via jquery
if (obj.body.type && obj.body.type === 'formData'){
if(opts.useJQuery) {
obj.contentType = false;
obj.processData = false;
delete obj.headers['Content-Type'];
}
}
}
obj = requestInterceptor(obj) || obj;
if (obj.beforeSend) {
obj.beforeSend(function(_obj) {
client.execute(_obj || obj);
});
} else {
client.execute(obj);
}
return (obj.deferred) ? obj.deferred.promise : obj;
};
SwaggerHttp.prototype.isInternetExplorer = function () {
var detectedIE = false;
if (typeof navigator !== 'undefined' && navigator.userAgent) {
var nav = navigator.userAgent.toLowerCase();
if (nav.indexOf('msie') !== -1) {
var version = parseInt(nav.split('msie')[1]);
if (version <= 8) {
detectedIE = true;
}
}
}
return detectedIE;
};
JQueryHttpClient.prototype.execute = function (obj) {
var jq = this.jQuery || (typeof window !== 'undefined' && window.jQuery);
var cb = obj.on;
var request = obj;
if(typeof jq === 'undefined' || jq === false) {
throw new Error('Unsupported configuration! JQuery is required but not available');
}
obj.type = obj.method;
obj.cache = obj.jqueryAjaxCache;
obj.data = obj.body;
delete obj.jqueryAjaxCache;
delete obj.useJQuery;
delete obj.body;
obj.complete = function (response) {
var headers = {};
var headerArray = response.getAllResponseHeaders().split('\n');
for (var i = 0; i < headerArray.length; i++) {
var toSplit = headerArray[i].trim();
if (toSplit.length === 0) {
continue;
}
var separator = toSplit.indexOf(':');
if (separator === -1) {
// Name but no value in the header
headers[toSplit] = null;
continue;
}
var name = toSplit.substring(0, separator).trim();
var value = toSplit.substring(separator + 1).trim();
headers[name] = value;
}
var out = {
url: request.url,
method: request.method,
status: response.status,
statusText: response.statusText,
data: response.responseText,
headers: headers
};
try {
var possibleObj = response.responseJSON || jsyaml.safeLoad(response.responseText);
out.obj = (typeof possibleObj === 'string') ? {} : possibleObj;
} catch (ex) {
// do not set out.obj
helpers.log('unable to parse JSON/YAML content');
}
// I can throw, or parse null?
out.obj = out.obj || null;
if (response.status >= 200 && response.status < 300) {
cb.response(out);
} else if (response.status === 0 || (response.status >= 400 && response.status < 599)) {
cb.error(out);
} else {
return cb.response(out);
}
};
jq.support.cors = true;
return jq.ajax(obj);
};
SuperagentHttpClient.prototype.execute = function (obj) {
var method = obj.method.toLowerCase();
var timeout = obj.timeout;
if (method === 'delete') {
method = 'del';
}
var headers = obj.headers || {};
var r = request[method](obj.url);
if (timeout) {
r.timeout(timeout);
}
if (obj.enableCookies) {
r.withCredentials();
}
if(obj.body) {
if(_.isObject(obj.body)) {
var contentType = obj.headers['Content-Type'] || '';
if (contentType.indexOf('multipart/form-data') === 0) {
delete headers['Content-Type'];
if({}.toString.apply(obj.body) === '[object FormData]') {
var itr = obj.body.keys();
var p = [];
while(true) {
var v = itr.next();
if(v.done) {
break;
}
var key = v.value;
// only once
if(p.indexOf(key) === -1) {
p.push(key);
var value = obj.body.getAll(key);
if({}.toString.apply(value) === '[object File]') {
r.attach(key, value);
}
else {
if (Array.isArray(value)) {
for (var v in value) {
r.field(key, value[v]);
}
}
else {
r.field(key, value);
}
}
}
}
}
else {
var keyname;
for (var keyname in obj.body) {
var value = obj.body[keyname];
if(Array.isArray(value)) {
for(var v in value) {
r.field(keyname, v);
}
}
else {
r.field(keyname, value);
}
}
}
}
else if (_.isObject(obj.body)) {
obj.body = JSON.stringify(obj.body);
r.send(obj.body);
}
}
else {
r.send(obj.body);
}
}
var name;
for (name in headers) {
r.set(name, headers[name]);
}
if(typeof r.buffer === 'function') {
r.buffer(); // force superagent to populate res.text with the raw response data
}
r.end(function (err, res) {
res = res || {
status: 0,
headers: {error: 'no response from server'}
};
var response = {
url: obj.url,
method: obj.method,
headers: res.headers
};
var cb;
if (!err && res.error) {
err = res.error;
}
if (err && obj.on && obj.on.error) {
response.errObj = err;
response.status = res ? res.status : 500;
response.statusText = res ? res.text : err.message;
if(res.headers && res.headers['content-type']) {
if(res.headers['content-type'].indexOf('application/json') >= 0) {
try {
response.obj = JSON.parse(response.statusText);
}
catch (e) {
response.obj = null;
}
}
}
cb = obj.on.error;
} else if (res && obj.on && obj.on.response) {
var possibleObj;
// Already parsed by by superagent?
if(res.body && _.keys(res.body).length > 0) {
possibleObj = res.body;
} else {
try {
possibleObj = jsyaml.safeLoad(res.text);
// can parse into a string... which we don't need running around in the system
possibleObj = (typeof possibleObj === 'string') ? null : possibleObj;
} catch(e) {
helpers.log('cannot parse JSON/YAML content');
}
}
// null means we can't parse into object
response.obj = (typeof possibleObj === 'object') ? possibleObj : null;
response.status = res.status;
response.statusText = res.text;
cb = obj.on.response;
}
response.data = response.statusText;
if (cb) {
cb(response);
}
});
};
},{"./helpers":4,"js-yaml":19,"lodash-compat/lang/isObject":144,"lodash-compat/object/keys":149,"superagent":158}],6:[function(require,module,exports){
'use strict';
var SwaggerHttp = require('./http');
var _ = {
isObject: require('lodash-compat/lang/isObject'),
cloneDeep: require('lodash-compat/lang/cloneDeep'),
isArray: require('lodash-compat/lang/isArray'),
isString: require('lodash-compat/lang/isString')
};
/**
* Resolves a spec's remote references
*/
var Resolver = module.exports = function () {
this.failedUrls = [];
this.resolverCache = {};
this.pendingUrls = {};
};
Resolver.prototype.processAllOf = function(root, name, definition, resolutionTable, unresolvedRefs, spec) {
var i, location, property;
definition['x-resolved-from'] = [ '#/definitions/' + name ];
var allOf = definition.allOf;
// the refs go first
allOf.sort(function(a, b) {
if(a.$ref && b.$ref) { return 0; }
else if(a.$ref) { return -1; }
else { return 1; }
});
for (i = 0; i < allOf.length; i++) {
property = allOf[i];
location = '/definitions/' + name + '/allOf';
this.resolveInline(root, spec, property, resolutionTable, unresolvedRefs, location);
}
};
Resolver.prototype.resolve = function (spec, arg1, arg2, arg3) {
this.spec = spec;
var root = arg1, callback = arg2, scope = arg3, opts = {}, location, i;
if(typeof arg1 === 'function') {
root = null;
callback = arg1;
scope = arg2;
}
var _root = root;
this.scope = (scope || this);
this.iteration = this.iteration || 0;
if(this.scope.options && this.scope.options.requestInterceptor){
opts.requestInterceptor = this.scope.options.requestInterceptor;
}
if(this.scope.options && this.scope.options.responseInterceptor){
opts.responseInterceptor = this.scope.options.responseInterceptor;
}
var name, path, property, propertyName;
var processedCalls = 0, resolvedRefs = {}, unresolvedRefs = {};
var resolutionTable = []; // store objects for dereferencing
spec.definitions = spec.definitions || {};
// definitions
for (name in spec.definitions) {
var definition = spec.definitions[name];
if(definition['$ref']) {
this.resolveInline(root, spec, definition, resolutionTable, unresolvedRefs, definition);
}
else {
for (propertyName in definition.properties) {
property = definition.properties[propertyName];
if (_.isArray(property.allOf)) {
this.processAllOf(root, name, property, resolutionTable, unresolvedRefs, spec);
}
else {
this.resolveTo(root, property, resolutionTable, '/definitions');
}
}
if (definition.allOf) {
this.processAllOf(root, name, definition, resolutionTable, unresolvedRefs, spec);
}
}
}
// shared parameters
spec.parameters = spec.parameters || {};
for(name in spec.parameters) {
var parameter = spec.parameters[name];
if (parameter.in === 'body' && parameter.schema) {
if(_.isArray(parameter.schema.allOf)) {
// move to a definition
var modelName = 'inline_model';
var name = modelName;
var done = false; var counter = 0;
while(!done) {
if(typeof spec.definitions[name] === 'undefined') {
done = true;
break;
}
name = modelName + '_' + counter;
counter ++;
}
spec.definitions[name] = { allOf: parameter.schema.allOf };
delete parameter.schema.allOf;
parameter.schema.$ref = '#/definitions/' + name;
this.processAllOf(root, name, spec.definitions[name], resolutionTable, unresolvedRefs, spec);
}
else {
this.resolveTo(root, parameter.schema, resolutionTable, location);
}
}
if (parameter.$ref) {
// parameter reference
this.resolveInline(root, spec, parameter, resolutionTable, unresolvedRefs, parameter.$ref);
}
}
// operations
for (name in spec.paths) {
var method, operation, responseCode;
path = spec.paths[name];
for (method in path) {
// operation reference
if(method === '$ref') {
// location = path[method];
location = '/paths' + name;
this.resolveInline(root, spec, path, resolutionTable, unresolvedRefs, location);
}
else {
operation = path[method];
var sharedParameters = path.parameters || [];
var parameters = operation.parameters || [];
for (i in sharedParameters) {
var parameter = sharedParameters[i];
parameters.unshift(parameter);
}
if(method !== 'parameters' && _.isObject(operation)) {
operation.parameters = operation.parameters || parameters;
}
for (i in parameters) {
var parameter = parameters[i];
location = '/paths' + name + '/' + method + '/parameters';
if (parameter.in === 'body' && parameter.schema) {
if(_.isArray(parameter.schema.allOf)) {
// move to a definition
var modelName = 'inline_model';
var name = modelName;
var done = false; var counter = 0;
while(!done) {
if(typeof spec.definitions[name] === 'undefined') {
done = true;
break;
}
name = modelName + '_' + counter;
counter ++;
}
spec.definitions[name] = { allOf: parameter.schema.allOf };
delete parameter.schema.allOf;
parameter.schema.$ref = '#/definitions/' + name;
this.processAllOf(root, name, spec.definitions[name], resolutionTable, unresolvedRefs, spec);
}
else {
this.resolveTo(root, parameter.schema, resolutionTable, location);
}
}
if (parameter.$ref) {
// parameter reference
this.resolveInline(root, spec, parameter, resolutionTable, unresolvedRefs, parameter.$ref);
}
}
for (responseCode in operation.responses) {
var response = operation.responses[responseCode];
location = '/paths' + name + '/' + method + '/responses/' + responseCode;
if(_.isObject(response)) {
if(response.$ref) {
// response reference
this.resolveInline(root, spec, response, resolutionTable, unresolvedRefs, location);
}
if (response.schema) {
var responseObj = response;
if(_.isArray(responseObj.schema.allOf)) {
// move to a definition
var modelName = 'inline_model';
var name = modelName;
var done = false; var counter = 0;
while(!done) {
if(typeof spec.definitions[name] === 'undefined') {
done = true;
break;
}
name = modelName + '_' + counter;
counter ++;
}
spec.definitions[name] = { allOf: responseObj.schema.allOf };
delete responseObj.schema.allOf;
delete responseObj.schema.type;
responseObj.schema.$ref = '#/definitions/' + name;
this.processAllOf(root, name, spec.definitions[name], resolutionTable, unresolvedRefs, spec);
}
else if('array' === responseObj.schema.type) {
if(responseObj.schema.items && responseObj.schema.items.$ref) {
// response reference
this.resolveInline(root, spec, responseObj.schema.items, resolutionTable, unresolvedRefs, location);
}
}
else {
this.resolveTo(root, response.schema, resolutionTable, location);
}
}
}
}
}
}
// clear them out to avoid multiple resolutions
path.parameters = [];
}
var expectedCalls = 0, toResolve = [];
// if the root is same as obj[i].root we can resolve locally
var all = resolutionTable;
var parts;
for(i = 0; i < all.length; i++) {
var a = all[i];
if(root === a.root) {
if(a.resolveAs === 'ref') {
// resolve any path walking
var joined = ((a.root || '') + '/' + a.key).split('/');
var normalized = [];
var url = '';
var k;
if(a.key.indexOf('../') >= 0) {
for(var j = 0; j < joined.length; j++) {
if(joined[j] === '..') {
normalized = normalized.slice(0, normalized.length-1);
}
else {
normalized.push(joined[j]);
}
}
for(k = 0; k < normalized.length; k ++) {
if(k > 0) {
url += '/';
}
url += normalized[k];
}
// we now have to remote resolve this because the path has changed
a.root = url;
toResolve.push(a);
}
else {
parts = a.key.split('#');
if(parts.length === 2) {
if(parts[0].indexOf('http:') === 0 || parts[0].indexOf('https:') === 0) {
a.root = parts[0];
}
location = parts[1].split('/');
var r;
var s = spec;
for(k = 0; k < location.length; k++) {
var part = location[k];
if(part !== '') {
s = s[part];
if(typeof s !== 'undefined') {
r = s;
}
else {
r = null;
break;
}
}
}
if(r === null) {
// must resolve this too
toResolve.push(a);
}
}
}
}
else {
if (a.resolveAs === 'inline') {
if(a.key && a.key.indexOf('#') === -1 && a.key.charAt(0) !== '/') {
// handle relative schema
parts = a.root.split('/');
location = '';
for(i = 0; i < parts.length - 1; i++) {
location += parts[i] + '/';
}
location += a.key;
a.root = location;
a.location = '';
}
toResolve.push(a);
}
}
}
else {
toResolve.push(a);
}
}
expectedCalls = toResolve.length;
// resolve anything that is local
var lock = {};
for(var ii = 0; ii < toResolve.length; ii++) {
(function(item, spec, self, lock, ii) {
if(!item.root || item.root === root) {
// local resolve
self.resolveItem(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, item);
processedCalls += 1;
if(processedCalls === expectedCalls) {
self.finish(spec, root, resolutionTable, resolvedRefs, unresolvedRefs, callback, true);
}
}
else if(self.failedUrls.indexOf(item.root) === -1) {
var obj = {
useJQuery: false