You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1342 lines
36 KiB

  1. // swagger-client.js
  2. // version 2.1.0
  3. /**
  4. * SwaggerAuthorizations applys the correct authorization to an operation being executed
  5. */
  6. var SwaggerAuthorizations = function() {
  7. this.authz = {};
  8. };
  9. SwaggerAuthorizations.prototype.add = function(name, auth) {
  10. this.authz[name] = auth;
  11. return auth;
  12. };
  13. SwaggerAuthorizations.prototype.remove = function(name) {
  14. return delete this.authz[name];
  15. };
  16. SwaggerAuthorizations.prototype.apply = function(obj, authorizations) {
  17. var status = null;
  18. var key;
  19. // if the "authorizations" key is undefined, or has an empty array, add all keys
  20. if(typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) {
  21. for (key in this.authz) {
  22. value = this.authz[key];
  23. result = value.apply(obj, authorizations);
  24. if (result === true)
  25. status = true;
  26. }
  27. }
  28. else {
  29. for(name in authorizations) {
  30. for (key in this.authz) {
  31. if(key == name) {
  32. value = this.authz[key];
  33. result = value.apply(obj, authorizations);
  34. if (result === true)
  35. status = true;
  36. }
  37. }
  38. }
  39. }
  40. return status;
  41. };
  42. /**
  43. * ApiKeyAuthorization allows a query param or header to be injected
  44. */
  45. var ApiKeyAuthorization = function(name, value, type) {
  46. this.name = name;
  47. this.value = value;
  48. this.type = type;
  49. };
  50. ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
  51. if (this.type === "query") {
  52. if (obj.url.indexOf('?') > 0)
  53. obj.url = obj.url + "&" + this.name + "=" + this.value;
  54. else
  55. obj.url = obj.url + "?" + this.name + "=" + this.value;
  56. return true;
  57. } else if (this.type === "header") {
  58. obj.headers[this.name] = this.value;
  59. return true;
  60. }
  61. };
  62. var CookieAuthorization = function(cookie) {
  63. this.cookie = cookie;
  64. }
  65. CookieAuthorization.prototype.apply = function(obj, authorizations) {
  66. obj.cookieJar = obj.cookieJar || CookieJar();
  67. obj.cookieJar.setCookie(this.cookie);
  68. return true;
  69. }
  70. /**
  71. * Password Authorization is a basic auth implementation
  72. */
  73. var PasswordAuthorization = function(name, username, password) {
  74. this.name = name;
  75. this.username = username;
  76. this.password = password;
  77. this._btoa = null;
  78. if (typeof window !== 'undefined')
  79. this._btoa = btoa;
  80. else
  81. this._btoa = require("btoa");
  82. };
  83. PasswordAuthorization.prototype.apply = function(obj, authorizations) {
  84. var base64encoder = this._btoa;
  85. obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
  86. return true;
  87. };var __bind = function(fn, me){
  88. return function(){
  89. return fn.apply(me, arguments);
  90. };
  91. };
  92. fail = function(message) {
  93. log(message);
  94. }
  95. log = function(){
  96. log.history = log.history || [];
  97. log.history.push(arguments);
  98. if(this.console){
  99. console.log( Array.prototype.slice.call(arguments)[0] );
  100. }
  101. };
  102. if (!Array.prototype.indexOf) {
  103. Array.prototype.indexOf = function(obj, start) {
  104. for (var i = (start || 0), j = this.length; i < j; i++) {
  105. if (this[i] === obj) { return i; }
  106. }
  107. return -1;
  108. }
  109. }
  110. if (!('filter' in Array.prototype)) {
  111. Array.prototype.filter= function(filter, that /*opt*/) {
  112. var other= [], v;
  113. for (var i=0, n= this.length; i<n; i++)
  114. if (i in this && filter.call(that, v= this[i], i, this))
  115. other.push(v);
  116. return other;
  117. };
  118. }
  119. if (!('map' in Array.prototype)) {
  120. Array.prototype.map= function(mapper, that /*opt*/) {
  121. var other= new Array(this.length);
  122. for (var i= 0, n= this.length; i<n; i++)
  123. if (i in this)
  124. other[i]= mapper.call(that, this[i], i, this);
  125. return other;
  126. };
  127. }
  128. Object.keys = Object.keys || (function () {
  129. var hasOwnProperty = Object.prototype.hasOwnProperty,
  130. hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
  131. DontEnums = [
  132. 'toString',
  133. 'toLocaleString',
  134. 'valueOf',
  135. 'hasOwnProperty',
  136. 'isPrototypeOf',
  137. 'propertyIsEnumerable',
  138. 'constructor'
  139. ],
  140. DontEnumsLength = DontEnums.length;
  141. return function (o) {
  142. if (typeof o != "object" && typeof o != "function" || o === null)
  143. throw new TypeError("Object.keys called on a non-object");
  144. var result = [];
  145. for (var name in o) {
  146. if (hasOwnProperty.call(o, name))
  147. result.push(name);
  148. }
  149. if (hasDontEnumBug) {
  150. for (var i = 0; i < DontEnumsLength; i++) {
  151. if (hasOwnProperty.call(o, DontEnums[i]))
  152. result.push(DontEnums[i]);
  153. }
  154. }
  155. return result;
  156. };
  157. })();
  158. var SwaggerClient = function(url, options) {
  159. this.isBuilt = false;
  160. this.url = null;
  161. this.debug = false;
  162. this.basePath = null;
  163. this.authorizations = null;
  164. this.authorizationScheme = null;
  165. this.isValid = false;
  166. this.info = null;
  167. this.useJQuery = false;
  168. options = (options||{});
  169. if (url)
  170. if (url.url) options = url;
  171. else this.url = url;
  172. else options = url;
  173. if (options.url != null)
  174. this.url = options.url;
  175. if (options.success != null)
  176. this.success = options.success;
  177. if (typeof options.useJQuery === 'boolean')
  178. this.useJQuery = options.useJQuery;
  179. this.failure = options.failure != null ? options.failure : function() {};
  180. this.progress = options.progress != null ? options.progress : function() {};
  181. if (options.success != null)
  182. this.build();
  183. }
  184. SwaggerClient.prototype.build = function() {
  185. var self = this;
  186. this.progress('fetching resource list: ' + this.url);
  187. var obj = {
  188. useJQuery: this.useJQuery,
  189. url: this.url,
  190. method: "get",
  191. headers: {
  192. accept: "application/json, */*"
  193. },
  194. on: {
  195. error: function(response) {
  196. if (self.url.substring(0, 4) !== 'http')
  197. return self.fail('Please specify the protocol for ' + self.url);
  198. else if (response.status === 0)
  199. return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
  200. else if (response.status === 404)
  201. return self.fail('Can\'t read swagger JSON from ' + self.url);
  202. else
  203. return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
  204. },
  205. response: function(resp) {
  206. var responseObj = resp.obj || JSON.parse(resp.data);
  207. self.swaggerVersion = responseObj.swaggerVersion;
  208. if(responseObj.swagger && responseObj.swagger === 2.0) {
  209. self.swaggerVersion = responseObj.swagger;
  210. self.buildFromSpec(responseObj);
  211. self.isValid = true;
  212. }
  213. else {
  214. self.isValid = false;
  215. self.failure()
  216. }
  217. }
  218. }
  219. };
  220. var e = (typeof window !== 'undefined' ? window : exports);
  221. e.authorizations.apply(obj);
  222. new SwaggerHttp().execute(obj);
  223. return this;
  224. };
  225. SwaggerClient.prototype.buildFromSpec = function(response) {
  226. if(this.isBuilt)
  227. return this;
  228. this.info = response.info || {};
  229. this.title = response.title || '';
  230. this.host = response.host || '';
  231. this.schemes = response.schemes || [ 'http' ];
  232. this.basePath = response.basePath || '';
  233. this.apis = {};
  234. this.apisArray = [];
  235. this.consumes = response.consumes;
  236. this.produces = response.produces;
  237. this.authSchemes = response.authorizations;
  238. if(typeof this.host === 'undefined' || this.host === '') {
  239. var location = this.parseUri(this.url);
  240. this.host = location.host;
  241. }
  242. this.definitions = response.definitions;
  243. var key;
  244. for(key in this.definitions) {
  245. var model = new Model(key, this.definitions[key]);
  246. if(model) {
  247. models[key] = model;
  248. }
  249. }
  250. // get paths, create functions for each operationId
  251. var path;
  252. var operations = [];
  253. for(path in response.paths) {
  254. var httpMethod;
  255. for(httpMethod in response.paths[path]) {
  256. var operation = response.paths[path][httpMethod];
  257. var tags = operation.tags;
  258. if(typeof tags === undefined)
  259. tags = [];
  260. var operationId = this.idFromOp(path, httpMethod, operation);
  261. var operation = new Operation (
  262. this,
  263. operationId,
  264. httpMethod,
  265. path,
  266. operation,
  267. this.definitions
  268. );
  269. // bind this operation's execute command to the api
  270. if(tags.length > 0) {
  271. var i;
  272. for(i = 0; i < tags.length; i++) {
  273. var tag = this.tagFromLabel(tags[i]);
  274. var operationGroup = this[tag];
  275. if(typeof operationGroup === 'undefined') {
  276. this[tag] = [];
  277. operationGroup = this[tag];
  278. operationGroup.label = tag;
  279. operationGroup.apis = [];
  280. this[tag].help = this.help.bind(operationGroup);
  281. this.apisArray.push(new OperationGroup(tag, operation));
  282. }
  283. operationGroup[operationId] = operation.execute.bind(operation);
  284. operationGroup[operationId].help = operation.help.bind(operation);
  285. operationGroup.apis.push(operation);
  286. // legacy UI feature
  287. var j;
  288. var api = null;
  289. for(j = 0; j < this.apisArray.length; j++) {
  290. if(this.apisArray[j].tag === tag) {
  291. api = this.apisArray[j];
  292. }
  293. }
  294. if(api) {
  295. api.operationsArray.push(operation);
  296. }
  297. }
  298. }
  299. else {
  300. log('no group to bind to');
  301. }
  302. }
  303. }
  304. this.isBuilt = true;
  305. if (this.success)
  306. this.success();
  307. return this;
  308. }
  309. SwaggerClient.prototype.parseUri = function(uri) {
  310. var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
  311. var parts = urlParseRE.exec(uri);
  312. return {
  313. scheme: parts[4].replace(':',''),
  314. host: parts[11],
  315. path: parts[15]
  316. };
  317. }
  318. SwaggerClient.prototype.help = function() {
  319. var i;
  320. log('operations for the "' + this.label + '" tag');
  321. for(i = 0; i < this.apis.length; i++) {
  322. var api = this.apis[i];
  323. log(' * ' + api.nickname + ': ' + api.operation.summary);
  324. }
  325. }
  326. SwaggerClient.prototype.tagFromLabel = function(label) {
  327. return label;
  328. }
  329. SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) {
  330. if(typeof op.operationId !== 'undefined') {
  331. return (op.operationId);
  332. }
  333. else {
  334. return path.substring(1).replace(/\//g, "_").replace(/\{/g, "").replace(/\}/g, "") + "_" + httpMethod;
  335. }
  336. }
  337. SwaggerClient.prototype.fail = function(message) {
  338. this.failure(message);
  339. throw message;
  340. };
  341. var OperationGroup = function(tag, operation) {
  342. this.tag = tag;
  343. this.path = tag;
  344. this.name = tag;
  345. this.operation = operation;
  346. this.operationsArray = [];
  347. this.description = operation.description || "";
  348. }
  349. var Operation = function(parent, operationId, httpMethod, path, args, definitions) {
  350. var errors = [];
  351. this.operation = args;
  352. this.consumes = args.consumes;
  353. this.produces = args.produces;
  354. this.parent = parent;
  355. this.host = parent.host;
  356. this.schemes = parent.schemes;
  357. this.basePath = parent.basePath;
  358. this.nickname = (operationId||errors.push('Operations must have a nickname.'));
  359. this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.'));
  360. this.path = (path||errors.push('Operation ' + nickname + ' is missing path.'));
  361. this.parameters = args != null ? (args.parameters||[]) : {};
  362. this.summary = args.summary || '';
  363. this.responses = (args.responses||{});
  364. this.type = null;
  365. // this.authorizations = authorizations;
  366. var i;
  367. for(i = 0; i < this.parameters.length; i++) {
  368. var param = this.parameters[i];
  369. type = this.getType(param);
  370. param.signature = this.getSignature(type, models);
  371. param.sampleJSON = this.getSampleJSON(type, models);
  372. param.responseClassSignature = param.signature;
  373. }
  374. var response;
  375. var model;
  376. var responses = this.responses;
  377. if(responses['200'])
  378. response = responses['200'];
  379. else if(responses['default'])
  380. response = responses['default'];
  381. if(response && response.schema) {
  382. var resolvedModel = this.resolveModel(response.schema, definitions);
  383. if(resolvedModel) {
  384. this.type = resolvedModel.name;
  385. this.responseSampleJSON = JSON.stringify(resolvedModel.getSampleValue(), null, 2);
  386. this.responseClassSignature = resolvedModel.getMockSignature();
  387. }
  388. else {
  389. this.type = response.schema.type;
  390. }
  391. }
  392. // else
  393. // this.responseClassSignature = '';
  394. if (errors.length > 0)
  395. this.resource.api.fail(errors);
  396. return this;
  397. }
  398. OperationGroup.prototype.sort = function(sorter) {
  399. }
  400. Operation.prototype.getType = function (param) {
  401. var type = param.type;
  402. var format = param.format;
  403. var isArray = false;
  404. var str;
  405. if(type === 'integer' && format === 'int32')
  406. str = 'integer';
  407. else if(type === 'integer' && format === 'int64')
  408. str = 'long';
  409. else if(type === 'string' && format === 'date-time')
  410. str = 'date-time';
  411. else if(type === 'string' && format === 'date')
  412. str = 'date';
  413. else if(type === 'number' && format === 'float')
  414. str = 'float';
  415. else if(type === 'number' && format === 'double')
  416. str = 'double';
  417. else if(type === 'boolean')
  418. str = 'boolean';
  419. else if(type === 'string')
  420. str = 'string';
  421. else if(type === 'array') {
  422. isArray = true;
  423. if(param.items) {
  424. str = this.getType(param.items);
  425. }
  426. }
  427. if(param['$ref'])
  428. str = param['$ref'];
  429. var schema = param.schema;
  430. if(schema) {
  431. var ref = schema['$ref'];
  432. if(ref) {
  433. ref = simpleRef(ref);
  434. if(isArray)
  435. return [ref];
  436. else
  437. return ref;
  438. }
  439. else
  440. return this.getType(schema);
  441. }
  442. if(isArray)
  443. return [str];
  444. else
  445. return str;
  446. }
  447. Operation.prototype.resolveModel = function (schema, definitions) {
  448. if(typeof schema['$ref'] !== 'undefined') {
  449. var ref = schema['$ref'];
  450. if(ref.indexOf('#/definitions/') == 0)
  451. ref = ref.substring('#/definitions/'.length);
  452. if(definitions[ref])
  453. return new Model(ref, definitions[ref]);
  454. }
  455. if(schema.type === 'array')
  456. return new ArrayModel(schema);
  457. else
  458. return null;
  459. // return new PrimitiveModel(schema);
  460. // else
  461. // var ref = schema.items['$ref'];
  462. // if(ref.indexOf('#/definitions/') === 0)
  463. // ref = ref.substring('#/definitions/'.length);
  464. // return new Model('name', models[ref]);
  465. // }
  466. // else
  467. // return new Model('name', schema);
  468. }
  469. Operation.prototype.help = function() {
  470. log(this.nickname + ': ' + this.operation.summary);
  471. for(var i = 0; i < this.parameters.length; i++) {
  472. var param = this.parameters[i];
  473. log(' * ' + param.name + ': ' + param.description);
  474. }
  475. }
  476. Operation.prototype.getSignature = function(type, models) {
  477. var isPrimitive, listType;
  478. if(type instanceof Array) {
  479. listType = true;
  480. type = type[0];
  481. }
  482. // listType = this.isListType(type);
  483. if(type === 'string')
  484. isPrimitive = true
  485. else
  486. isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
  487. if (isPrimitive) {
  488. return type;
  489. } else {
  490. if (listType != null) {
  491. return models[type].getMockSignature();
  492. } else {
  493. return models[type].getMockSignature();
  494. }
  495. }
  496. };
  497. Operation.prototype.getSampleJSON = function(type, models) {
  498. var isPrimitive, listType, sampleJson;
  499. listType = (type instanceof Array);
  500. isPrimitive = (models[type] != null) ? false : true;
  501. sampleJson = isPrimitive ? void 0 : models[type].createJSONSample();
  502. if (sampleJson) {
  503. sampleJson = listType ? [sampleJson] : sampleJson;
  504. if(typeof sampleJson == 'string')
  505. return sampleJson;
  506. else if(typeof sampleJson === 'object') {
  507. var t = sampleJson;
  508. if(sampleJson instanceof Array && sampleJson.length > 0) {
  509. t = sampleJson[0];
  510. }
  511. if(t.nodeName) {
  512. var xmlString = new XMLSerializer().serializeToString(t);
  513. return this.formatXml(xmlString);
  514. }
  515. else
  516. return JSON.stringify(sampleJson, null, 2);
  517. }
  518. else
  519. return sampleJson;
  520. }
  521. };
  522. // legacy support
  523. Operation.prototype["do"] = function(args, opts, callback, error, parent) {
  524. return this.execute(args, opts, callback, error, parent);
  525. }
  526. Operation.prototype.execute = function(arg1, arg2, arg3, arg4, parent) {
  527. var args = (arg1||{});
  528. var opts = {}, success, error;
  529. if(typeof arg2 === 'object') {
  530. opts = arg2;
  531. success = arg3;
  532. error = arg4;
  533. }
  534. if(typeof arg2 === 'function') {
  535. success = arg2;
  536. error = arg3;
  537. }
  538. var formParams = {};
  539. var headers = {};
  540. var requestUrl = this.path;
  541. success = (success||log)
  542. error = (error||log)
  543. var requiredParams = [];
  544. var missingParams = [];
  545. // check required params
  546. for(var i = 0; i < this.parameters.length; i++) {
  547. var param = this.parameters[i];
  548. if(param.required === true) {
  549. requiredParams.push(param.name);
  550. if(typeof args[param.name] === 'undefined')
  551. missingParams = param.name;
  552. }
  553. }
  554. if(missingParams.length > 0) {
  555. var message = 'missing required params: ' + missingParams;
  556. fail(message);
  557. return;
  558. }
  559. // set content type negotiation
  560. var consumes = this.consumes || this.parent.consumes || [ 'application/json' ];
  561. var produces = this.produces || this.parent.produces || [ 'application/json' ];
  562. headers = this.setContentTypes(args, opts);
  563. // grab params from the args, build the querystring along the way
  564. var querystring = "";
  565. for(var i = 0; i < this.parameters.length; i++) {
  566. var param = this.parameters[i];
  567. if(typeof args[param.name] !== 'undefined') {
  568. if(param.in === 'path') {
  569. var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
  570. requestUrl = requestUrl.replace(reg, this.encodePathParam(args[param.name]));
  571. }
  572. else if (param.in === 'query') {
  573. if(querystring === '')
  574. querystring += '?';
  575. if(typeof param.collectionFormat !== 'undefined') {
  576. var qp = args[param.name];
  577. if(Array.isArray(qp))
  578. querystring += this.encodeCollection(param.collectionFormat, param.name, qp);
  579. else
  580. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  581. }
  582. else
  583. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  584. }
  585. else if (param.in === 'header')
  586. headers[param.name] = args[param.name];
  587. else if (param.in === 'form')
  588. formParams[param.name] = args[param.name];
  589. }
  590. }
  591. var scheme = this.schemes[0];
  592. var url = scheme + '://' + this.host + this.basePath + requestUrl + querystring;
  593. var obj = {
  594. url: url,
  595. method: args.method,
  596. useJQuery: this.useJQuery,
  597. headers: headers,
  598. on: {
  599. response: function(response) {
  600. return success(response, parent);
  601. },
  602. error: function(response) {
  603. return error(response, parent);
  604. }
  605. }
  606. };
  607. new SwaggerHttp().execute(obj);
  608. }
  609. Operation.prototype.setContentTypes = function(args, opts) {
  610. // default type
  611. var accepts = 'application/json';
  612. var consumes = 'application/json';
  613. var allDefinedParams = this.parameters;
  614. var definedFormParams = [];
  615. var definedFileParams = [];
  616. var body = args.body;
  617. var headers = {};
  618. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  619. var i;
  620. for(i = 0; i < allDefinedParams.length; i++) {
  621. var param = allDefinedParams[i];
  622. if(param.in === 'form')
  623. definedFormParams.push(param);
  624. else if(param.in === 'file')
  625. definedFileParams.push(param);
  626. else if(param.in === 'header' && this.params.headers) {
  627. var key = param.name;
  628. var headerValue = this.params.headers[param.name];
  629. if(typeof this.params.headers[param.name] !== 'undefined')
  630. headers[key] = headerValue;
  631. }
  632. }
  633. // if there's a body, need to set the accepts header via requestContentType
  634. if (body && (this.type === 'post' || this.type === 'put' || this.type === 'patch' || this.type === 'delete')) {
  635. if (opts.requestContentType)
  636. consumes = opts.requestContentType;
  637. } else {
  638. // if any form params, content type must be set
  639. if(definedFormParams.length > 0) {
  640. if(definedFileParams.length > 0)
  641. consumes = 'multipart/form-data';
  642. else
  643. consumes = 'application/x-www-form-urlencoded';
  644. }
  645. else if (this.type == 'DELETE')
  646. body = '{}';
  647. else if (this.type != 'DELETE')
  648. accepts = null;
  649. }
  650. if (consumes && this.consumes) {
  651. if (this.consumes.indexOf(consumes) === -1) {
  652. log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
  653. consumes = this.operation.consumes[0];
  654. }
  655. }
  656. if (opts.responseContentType) {
  657. accepts = opts.responseContentType;
  658. } else {
  659. accepts = 'application/json';
  660. }
  661. if (accepts && this.produces) {
  662. if (this.produces.indexOf(accepts) === -1) {
  663. log('server can\'t produce ' + accepts);
  664. accepts = this.produces[0];
  665. }
  666. }
  667. if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
  668. headers['Content-Type'] = consumes;
  669. if (accepts)
  670. headers['Accept'] = accepts;
  671. return headers;
  672. }
  673. Operation.prototype.encodeCollection = function(type, name, value) {
  674. var encoded = '';
  675. var i;
  676. if(type === 'jaxrs') {
  677. for(i = 0; i < value.length; i++) {
  678. if(i > 0) encoded += '&'
  679. encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
  680. }
  681. }
  682. return encoded;
  683. }
  684. Operation.prototype.encodeQueryParam = function(arg) {
  685. return escape(arg);
  686. }
  687. Operation.prototype.encodePathParam = function(pathParam) {
  688. var encParts, part, parts, _i, _len;
  689. pathParam = pathParam.toString();
  690. if (pathParam.indexOf('/') === -1) {
  691. return encodeURIComponent(pathParam);
  692. } else {
  693. parts = pathParam.split('/');
  694. encParts = [];
  695. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  696. part = parts[_i];
  697. encParts.push(encodeURIComponent(part));
  698. }
  699. return encParts.join('/');
  700. }
  701. };
  702. Operation.prototype.encodePathParam = function(pathParam) {
  703. var encParts, part, parts, _i, _len;
  704. pathParam = pathParam.toString();
  705. if (pathParam.indexOf('/') === -1) {
  706. return encodeURIComponent(pathParam);
  707. } else {
  708. parts = pathParam.split('/');
  709. encParts = [];
  710. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  711. part = parts[_i];
  712. encParts.push(encodeURIComponent(part));
  713. }
  714. return encParts.join('/');
  715. }
  716. };
  717. var ArrayModel = function(definition) {
  718. this.name = "name";
  719. this.definition = definition || {};
  720. this.properties = [];
  721. this.type;
  722. this.ref;
  723. var requiredFields = definition.enum || [];
  724. var items = definition.items;
  725. if(items) {
  726. var type = items.type;
  727. if(items.type) {
  728. this.type = typeFromJsonSchema(type.type, type.format);
  729. }
  730. else {
  731. this.ref = items['$ref'];
  732. }
  733. }
  734. }
  735. ArrayModel.prototype.createJSONSample = function(modelsToIgnore) {
  736. var result;
  737. var modelsToIgnore = (modelsToIgnore||[])
  738. if(this.type) {
  739. result = type;
  740. }
  741. else if (this.ref) {
  742. var name = simpleRef(this.ref);
  743. result = models[name].createJSONSample();
  744. }
  745. return [ result ];
  746. };
  747. ArrayModel.prototype.getSampleValue = function() {
  748. var result;
  749. var modelsToIgnore = (modelsToIgnore||[])
  750. if(this.type) {
  751. result = type;
  752. }
  753. else if (this.ref) {
  754. var name = simpleRef(this.ref);
  755. result = models[name].getSampleValue();
  756. }
  757. return [ result ];
  758. }
  759. ArrayModel.prototype.getMockSignature = function(modelsToIgnore) {
  760. var propertiesStr = [];
  761. if(this.ref) {
  762. return models[simpleRef(this.ref)].getMockSignature();
  763. }
  764. };
  765. var PrimitiveModel = function(definition) {
  766. this.name = "name";
  767. this.definition = definition || {};
  768. this.properties = [];
  769. this.type;
  770. var requiredFields = definition.enum || [];
  771. this.type = typeFromJsonSchema(definition.type, definition.format);
  772. }
  773. PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) {
  774. var result = this.type;
  775. return result;
  776. };
  777. PrimitiveModel.prototype.getSampleValue = function() {
  778. var result = this.type;
  779. return null;
  780. }
  781. PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) {
  782. var propertiesStr = [];
  783. var i;
  784. for (i = 0; i < this.properties.length; i++) {
  785. var prop = this.properties[i];
  786. propertiesStr.push(prop.toString());
  787. }
  788. var strong = '<span class="strong">';
  789. var stronger = '<span class="stronger">';
  790. var strongClose = '</span>';
  791. var classOpen = strong + this.name + ' {' + strongClose;
  792. var classClose = strong + '}' + strongClose;
  793. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  794. if (!modelsToIgnore)
  795. modelsToIgnore = [];
  796. modelsToIgnore.push(this.name);
  797. var i;
  798. for (i = 0; i < this.properties.length; i++) {
  799. var prop = this.properties[i];
  800. var ref = prop['$ref'];
  801. var model = models[ref];
  802. if (model && modelsToIgnore.indexOf(ref) === -1) {
  803. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  804. }
  805. }
  806. return returnVal;
  807. };
  808. var Model = function(name, definition) {
  809. this.name = name;
  810. this.definition = definition || {};
  811. this.properties = [];
  812. var requiredFields = definition.enum || [];
  813. var key;
  814. var props = definition.properties;
  815. if(props) {
  816. for(key in props) {
  817. var required = false;
  818. var property = props[key];
  819. if(requiredFields.indexOf(key) >= 0)
  820. required = true;
  821. this.properties.push(new Property(key, property, required));
  822. }
  823. }
  824. }
  825. Model.prototype.createJSONSample = function(modelsToIgnore) {
  826. var result = {};
  827. var modelsToIgnore = (modelsToIgnore||[])
  828. modelsToIgnore.push(this.name);
  829. for (var i = 0; i < this.properties.length; i++) {
  830. prop = this.properties[i];
  831. result[prop.name] = prop.getSampleValue(modelsToIgnore);
  832. }
  833. modelsToIgnore.pop(this.name);
  834. return result;
  835. };
  836. Model.prototype.getSampleValue = function() {
  837. var i;
  838. var obj = {};
  839. for(i = 0; i < this.properties.length; i++ ) {
  840. var property = this.properties[i];
  841. obj[property.name] = property.sampleValue();
  842. }
  843. return obj;
  844. }
  845. Model.prototype.getMockSignature = function(modelsToIgnore) {
  846. var propertiesStr = [];
  847. var i;
  848. for (i = 0; i < this.properties.length; i++) {
  849. var prop = this.properties[i];
  850. propertiesStr.push(prop.toString());
  851. }
  852. var strong = '<span class="strong">';
  853. var stronger = '<span class="stronger">';
  854. var strongClose = '</span>';
  855. var classOpen = strong + this.name + ' {' + strongClose;
  856. var classClose = strong + '}' + strongClose;
  857. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  858. if (!modelsToIgnore)
  859. modelsToIgnore = [];
  860. modelsToIgnore.push(this.name);
  861. var i;
  862. for (i = 0; i < this.properties.length; i++) {
  863. var prop = this.properties[i];
  864. var ref = prop['$ref'];
  865. var model = models[ref];
  866. if (model && modelsToIgnore.indexOf(ref) === -1) {
  867. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  868. }
  869. }
  870. return returnVal;
  871. };
  872. var Property = function(name, obj, required) {
  873. this.schema = obj;
  874. this.required = required;
  875. if(obj['$ref']) {
  876. var refType = obj['$ref'];
  877. refType = refType.indexOf('#/definitions') === -1 ? refType : refType.substring('#/definitions').length;
  878. this['$ref'] = refType;
  879. }
  880. else if (obj.type === 'array') {
  881. if(obj.items['$ref'])
  882. this['$ref'] = obj.items['$ref'];
  883. else
  884. obj = obj.items;
  885. }
  886. this.name = name;
  887. this.obj = obj;
  888. this.optional = true;
  889. this.example = obj.example || null;
  890. }
  891. Property.prototype.getSampleValue = function () {
  892. return this.sampleValue(false);
  893. }
  894. Property.prototype.isArray = function () {
  895. var schema = this.schema;
  896. if(schema.type === 'array')
  897. return true;
  898. else
  899. return false;
  900. }
  901. Property.prototype.sampleValue = function(isArray, ignoredModels) {
  902. isArray = (isArray || this.isArray());
  903. ignoredModels = (ignoredModels || {})
  904. var type = getStringSignature(this.obj);
  905. var output;
  906. if(this['$ref']) {
  907. var refModel = models[this['$ref']];
  908. if(refModel && typeof ignoredModels[refModel] === 'undefined') {
  909. output = refModel.getSampleValue(ignoredModels);
  910. }
  911. else
  912. type = refModel;
  913. }
  914. else if(this.example)
  915. output = this.example;
  916. else if(type === 'date-time') {
  917. output = new Date().toISOString();
  918. }
  919. else if(type === 'string') {
  920. output = 'string';
  921. }
  922. else if(type === 'integer') {
  923. output = 0;
  924. }
  925. else if(type === 'long') {
  926. output = 0;
  927. }
  928. else if(type === 'float') {
  929. output = 0.0;
  930. }
  931. else if(type === 'double') {
  932. output = 0.0;
  933. }
  934. else if(type === 'boolean') {
  935. output = true;
  936. }
  937. else
  938. output = {};
  939. if(isArray) return [output];
  940. else return output;
  941. }
  942. getStringSignature = function(obj) {
  943. var str = '';
  944. if(obj.type === 'array') {
  945. obj = (obj.items || obj['$ref'] || {});
  946. str += 'Array[';
  947. }
  948. if(obj.type === 'integer' && obj.format === 'int32')
  949. str += 'integer';
  950. else if(obj.type === 'integer' && obj.format === 'int64')
  951. str += 'long';
  952. else if(obj.type === 'string' && obj.format === 'date-time')
  953. str += 'date-time';
  954. else if(obj.type === 'string' && obj.format === 'date')
  955. str += 'date';
  956. else if(obj.type === 'number' && obj.format === 'float')
  957. str += 'float';
  958. else if(obj.type === 'number' && obj.format === 'double')
  959. str += 'double';
  960. else if(obj.type === 'boolean')
  961. str += 'boolean';
  962. else
  963. str += obj.type || obj['$ref'];
  964. if(obj.type === 'array')
  965. str += ']';
  966. return str;
  967. }
  968. simpleRef = function(name) {
  969. if(name.indexOf("#/definitions/") === 0)
  970. return name.substring('#/definitions/'.length)
  971. else
  972. return name;
  973. }
  974. Property.prototype.toString = function() {
  975. var str = getStringSignature(this.obj);
  976. if(str !== '')
  977. str = this.name + ' : ' + str;
  978. else
  979. str = this.name + ' : ' + JSON.stringify(this.obj);
  980. if(!this.required)
  981. str += ' (optional)';
  982. return str;
  983. }
  984. typeFromJsonSchema = function(type, format) {
  985. var str;
  986. if(type === 'integer' && format === 'int32')
  987. str = 'integer';
  988. else if(type === 'integer' && format === 'int64')
  989. str = 'long';
  990. else if(type === 'string' && format === 'date-time')
  991. str = 'date-time';
  992. else if(type === 'string' && format === 'date')
  993. str = 'date';
  994. else if(type === 'number' && format === 'float')
  995. str = 'float';
  996. else if(type === 'number' && format === 'double')
  997. str = 'double';
  998. else if(type === 'boolean')
  999. str = 'boolean';
  1000. else if(type === 'string')
  1001. str = 'string';
  1002. return str;
  1003. }
  1004. var e = (typeof window !== 'undefined' ? window : exports);
  1005. var sampleModels = {};
  1006. var cookies = {};
  1007. var models = {};
  1008. e.authorizations = new SwaggerAuthorizations();
  1009. e.ApiKeyAuthorization = ApiKeyAuthorization;
  1010. e.PasswordAuthorization = PasswordAuthorization;
  1011. e.CookieAuthorization = CookieAuthorization;
  1012. e.SwaggerClient = SwaggerClient;/**
  1013. * SwaggerHttp is a wrapper for executing requests
  1014. */
  1015. var SwaggerHttp = function() {};
  1016. SwaggerHttp.prototype.execute = function(obj) {
  1017. if(obj && (typeof obj.useJQuery === 'boolean'))
  1018. this.useJQuery = obj.useJQuery;
  1019. else
  1020. this.useJQuery = this.isIE8();
  1021. if(this.useJQuery)
  1022. return new JQueryHttpClient().execute(obj);
  1023. else
  1024. return new ShredHttpClient().execute(obj);
  1025. }
  1026. SwaggerHttp.prototype.isIE8 = function() {
  1027. var detectedIE = false;
  1028. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1029. nav = navigator.userAgent.toLowerCase();
  1030. if (nav.indexOf('msie') !== -1) {
  1031. var version = parseInt(nav.split('msie')[1]);
  1032. if (version <= 8) {
  1033. detectedIE = true;
  1034. }
  1035. }
  1036. }
  1037. return detectedIE;
  1038. };
  1039. /*
  1040. * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
  1041. * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
  1042. * Since we are using closures here we need to alias it for internal use.
  1043. */
  1044. var JQueryHttpClient = function(options) {
  1045. "use strict";
  1046. if(!jQuery){
  1047. var jQuery = window.jQuery;
  1048. }
  1049. }
  1050. JQueryHttpClient.prototype.execute = function(obj) {
  1051. var cb = obj.on;
  1052. var request = obj;
  1053. obj.type = obj.method;
  1054. obj.cache = false;
  1055. obj.beforeSend = function(xhr) {
  1056. var key, results;
  1057. if (obj.headers) {
  1058. results = [];
  1059. var key;
  1060. for (key in obj.headers) {
  1061. if (key.toLowerCase() === "content-type") {
  1062. results.push(obj.contentType = obj.headers[key]);
  1063. } else if (key.toLowerCase() === "accept") {
  1064. results.push(obj.accepts = obj.headers[key]);
  1065. } else {
  1066. results.push(xhr.setRequestHeader(key, obj.headers[key]));
  1067. }
  1068. }
  1069. return results;
  1070. }
  1071. };
  1072. obj.data = obj.body;
  1073. obj.complete = function(response, textStatus, opts) {
  1074. var headers = {},
  1075. headerArray = response.getAllResponseHeaders().split("\n");
  1076. for(var i = 0; i < headerArray.length; i++) {
  1077. var toSplit = headerArray[i].trim();
  1078. if(toSplit.length === 0)
  1079. continue;
  1080. var separator = toSplit.indexOf(":");
  1081. if(separator === -1) {
  1082. // Name but no value in the header
  1083. headers[toSplit] = null;
  1084. continue;
  1085. }
  1086. var name = toSplit.substring(0, separator).trim(),
  1087. value = toSplit.substring(separator + 1).trim();
  1088. headers[name] = value;
  1089. }
  1090. var out = {
  1091. url: request.url,
  1092. method: request.method,
  1093. status: response.status,
  1094. data: response.responseText,
  1095. headers: headers
  1096. };
  1097. var contentType = (headers["content-type"]||headers["Content-Type"]||null)
  1098. if(contentType != null) {
  1099. if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
  1100. if(response.responseText && response.responseText !== "")
  1101. out.obj = JSON.parse(response.responseText);
  1102. else
  1103. out.obj = {}
  1104. }
  1105. }
  1106. if(response.status >= 200 && response.status < 300)
  1107. cb.response(out);
  1108. else if(response.status === 0 || (response.status >= 400 && response.status < 599))
  1109. cb.error(out);
  1110. else
  1111. return cb.response(out);
  1112. };
  1113. jQuery.support.cors = true;
  1114. return jQuery.ajax(obj);
  1115. }
  1116. /*
  1117. * ShredHttpClient is a light-weight, node or browser HTTP client
  1118. */
  1119. var ShredHttpClient = function(options) {
  1120. this.options = (options||{});
  1121. this.isInitialized = false;
  1122. var identity, toString;
  1123. if (typeof window !== 'undefined') {
  1124. this.Shred = require("./shred");
  1125. this.content = require("./shred/content");
  1126. }
  1127. else
  1128. this.Shred = require("shred");
  1129. this.shred = new this.Shred();
  1130. }
  1131. ShredHttpClient.prototype.initShred = function () {
  1132. this.isInitialized = true;
  1133. this.registerProcessors(this.shred);
  1134. }
  1135. ShredHttpClient.prototype.registerProcessors = function(shred) {
  1136. var identity = function(x) {
  1137. return x;
  1138. };
  1139. var toString = function(x) {
  1140. return x.toString();
  1141. };
  1142. if (typeof window !== 'undefined') {
  1143. this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  1144. parser: identity,
  1145. stringify: toString
  1146. });
  1147. } else {
  1148. this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  1149. parser: identity,
  1150. stringify: toString
  1151. });
  1152. }
  1153. }
  1154. ShredHttpClient.prototype.execute = function(obj) {
  1155. if(!this.isInitialized)
  1156. this.initShred();
  1157. var cb = obj.on, res;
  1158. var transform = function(response) {
  1159. var out = {
  1160. headers: response._headers,
  1161. url: response.request.url,
  1162. method: response.request.method,
  1163. status: response.status,
  1164. data: response.content.data
  1165. };
  1166. var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null)
  1167. if(contentType != null) {
  1168. if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
  1169. if(response.content.data && response.content.data !== "")
  1170. out.obj = JSON.parse(response.content.data);
  1171. else
  1172. out.obj = {}
  1173. }
  1174. }
  1175. return out;
  1176. };
  1177. res = {
  1178. error: function(response) {
  1179. if (obj)
  1180. return cb.error(transform(response));
  1181. },
  1182. redirect: function(response) {
  1183. if (obj)
  1184. return cb.redirect(transform(response));
  1185. },
  1186. 307: function(response) {
  1187. if (obj)
  1188. return cb.redirect(transform(response));
  1189. },
  1190. response: function(response) {
  1191. if (obj)
  1192. return cb.response(transform(response));
  1193. }
  1194. };
  1195. if (obj) {
  1196. obj.on = res;
  1197. }
  1198. return this.shred.request(obj);
  1199. };