Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

3293 řádky
95 KiB

  1. /**
  2. * swagger-client - swagger.js is a javascript client for use with swaggering APIs.
  3. * @version v2.1.9-M1
  4. * @link http://swagger.io
  5. * @license apache 2.0
  6. */
  7. (function(){
  8. var ArrayModel = function(definition) {
  9. this.name = "arrayModel";
  10. this.definition = definition || {};
  11. this.properties = [];
  12. var requiredFields = definition.enum || [];
  13. var innerType = definition.items;
  14. if(innerType) {
  15. if(innerType.type) {
  16. this.type = typeFromJsonSchema(innerType.type, innerType.format);
  17. }
  18. else {
  19. this.ref = innerType.$ref;
  20. }
  21. }
  22. return this;
  23. };
  24. ArrayModel.prototype.createJSONSample = function(modelsToIgnore) {
  25. var result;
  26. modelsToIgnore = (modelsToIgnore||{});
  27. if(this.type) {
  28. result = this.type;
  29. }
  30. else if (this.ref) {
  31. var name = simpleRef(this.ref);
  32. if(typeof modelsToIgnore[name] === 'undefined') {
  33. modelsToIgnore[name] = this;
  34. result = models[name].createJSONSample(modelsToIgnore);
  35. }
  36. else {
  37. return name;
  38. }
  39. }
  40. return [ result ];
  41. };
  42. ArrayModel.prototype.getSampleValue = function(modelsToIgnore) {
  43. var result;
  44. modelsToIgnore = (modelsToIgnore || {});
  45. if(this.type) {
  46. result = type;
  47. }
  48. else if (this.ref) {
  49. var name = simpleRef(this.ref);
  50. result = models[name].getSampleValue(modelsToIgnore);
  51. }
  52. return [ result ];
  53. };
  54. ArrayModel.prototype.getMockSignature = function(modelsToIgnore) {
  55. var propertiesStr = [];
  56. var i, prop;
  57. for (i = 0; i < this.properties.length; i++) {
  58. prop = this.properties[i];
  59. propertiesStr.push(prop.toString());
  60. }
  61. var strong = '<span class="strong">';
  62. var stronger = '<span class="stronger">';
  63. var strongClose = '</span>';
  64. var classOpen = strong + 'array' + ' {' + strongClose;
  65. var classClose = strong + '}' + strongClose;
  66. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  67. if (!modelsToIgnore)
  68. modelsToIgnore = {};
  69. modelsToIgnore[this.name] = this;
  70. for (i = 0; i < this.properties.length; i++) {
  71. prop = this.properties[i];
  72. var ref = prop.$ref;
  73. var model = models[ref];
  74. if (model && typeof modelsToIgnore[ref] === 'undefined') {
  75. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  76. }
  77. }
  78. return returnVal;
  79. };
  80. /**
  81. * SwaggerAuthorizations applys the correct authorization to an operation being executed
  82. */
  83. var SwaggerAuthorizations = function() {
  84. this.authz = {};
  85. };
  86. SwaggerAuthorizations.prototype.add = function(name, auth) {
  87. this.authz[name] = auth;
  88. return auth;
  89. };
  90. SwaggerAuthorizations.prototype.remove = function(name) {
  91. return delete this.authz[name];
  92. };
  93. SwaggerAuthorizations.prototype.apply = function (obj, authorizations) {
  94. var status = null;
  95. var key, name, value, result;
  96. // if the "authorizations" key is undefined, or has an empty array, add all keys
  97. if (typeof authorizations === 'undefined' || Object.keys(authorizations).length === 0) {
  98. for (key in this.authz) {
  99. value = this.authz[key];
  100. result = value.apply(obj, authorizations);
  101. if (result === true)
  102. status = true;
  103. }
  104. }
  105. else {
  106. // 2.0 support
  107. if (Array.isArray(authorizations)) {
  108. for (var i = 0; i < authorizations.length; i++) {
  109. var auth = authorizations[i];
  110. for (name in auth) {
  111. for (key in this.authz) {
  112. if (key == name) {
  113. value = this.authz[key];
  114. result = value.apply(obj, authorizations);
  115. if (result === true)
  116. status = true;
  117. }
  118. }
  119. }
  120. }
  121. }
  122. else {
  123. // 1.2 support
  124. for (name in authorizations) {
  125. for (key in this.authz) {
  126. if (key == name) {
  127. value = this.authz[key];
  128. result = value.apply(obj, authorizations);
  129. if (result === true)
  130. status = true;
  131. }
  132. }
  133. }
  134. }
  135. }
  136. return status;
  137. };
  138. /**
  139. * ApiKeyAuthorization allows a query param or header to be injected
  140. */
  141. var ApiKeyAuthorization = function(name, value, type) {
  142. this.name = name;
  143. this.value = value;
  144. this.type = type;
  145. };
  146. ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
  147. if (this.type === "query") {
  148. if (obj.url.indexOf('?') > 0)
  149. obj.url = obj.url + "&" + this.name + "=" + this.value;
  150. else
  151. obj.url = obj.url + "?" + this.name + "=" + this.value;
  152. return true;
  153. } else if (this.type === "header") {
  154. obj.headers[this.name] = this.value;
  155. return true;
  156. }
  157. };
  158. var CookieAuthorization = function(cookie) {
  159. this.cookie = cookie;
  160. };
  161. CookieAuthorization.prototype.apply = function(obj, authorizations) {
  162. obj.cookieJar = obj.cookieJar || CookieJar();
  163. obj.cookieJar.setCookie(this.cookie);
  164. return true;
  165. };
  166. /**
  167. * Password Authorization is a basic auth implementation
  168. */
  169. var PasswordAuthorization = function(name, username, password) {
  170. this.name = name;
  171. this.username = username;
  172. this.password = password;
  173. this._btoa = null;
  174. if (typeof window !== 'undefined')
  175. this._btoa = btoa;
  176. else
  177. this._btoa = require("btoa");
  178. };
  179. PasswordAuthorization.prototype.apply = function(obj, authorizations) {
  180. var base64encoder = this._btoa;
  181. obj.headers.Authorization = "Basic " + base64encoder(this.username + ":" + this.password);
  182. return true;
  183. };
  184. var __bind = function(fn, me){
  185. return function(){
  186. return fn.apply(me, arguments);
  187. };
  188. };
  189. fail = function(message) {
  190. log(message);
  191. };
  192. log = function(){
  193. log.history = log.history || [];
  194. log.history.push(arguments);
  195. if(this.console){
  196. console.log( Array.prototype.slice.call(arguments)[0] );
  197. }
  198. };
  199. if (!Array.prototype.indexOf) {
  200. Array.prototype.indexOf = function(obj, start) {
  201. for (var i = (start || 0), j = this.length; i < j; i++) {
  202. if (this[i] === obj) { return i; }
  203. }
  204. return -1;
  205. };
  206. }
  207. /**
  208. * allows override of the default value based on the parameter being
  209. * supplied
  210. **/
  211. var applyParameterMacro = function (operation, parameter) {
  212. var e = (typeof window !== 'undefined' ? window : exports);
  213. if(e.parameterMacro)
  214. return e.parameterMacro(operation, parameter);
  215. else
  216. return parameter.defaultValue;
  217. };
  218. /**
  219. * allows overriding the default value of an model property
  220. **/
  221. var applyModelPropertyMacro = function (model, property) {
  222. var e = (typeof window !== 'undefined' ? window : exports);
  223. if(e.modelPropertyMacro)
  224. return e.modelPropertyMacro(model, property);
  225. else
  226. return property.defaultValue;
  227. };
  228. /**
  229. * PrimitiveModel
  230. **/
  231. var PrimitiveModel = function(definition) {
  232. this.name = "name";
  233. this.definition = definition || {};
  234. this.properties = [];
  235. var requiredFields = definition.enum || [];
  236. this.type = typeFromJsonSchema(definition.type, definition.format);
  237. };
  238. PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) {
  239. var result = this.type;
  240. return result;
  241. };
  242. PrimitiveModel.prototype.getSampleValue = function() {
  243. var result = this.type;
  244. return null;
  245. };
  246. PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) {
  247. var propertiesStr = [];
  248. var i, prop;
  249. for (i = 0; i < this.properties.length; i++) {
  250. prop = this.properties[i];
  251. propertiesStr.push(prop.toString());
  252. }
  253. var strong = '<span class="strong">';
  254. var stronger = '<span class="stronger">';
  255. var strongClose = '</span>';
  256. var classOpen = strong + this.name + ' {' + strongClose;
  257. var classClose = strong + '}' + strongClose;
  258. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  259. if (!modelsToIgnore)
  260. modelsToIgnore = {};
  261. modelsToIgnore[this.name] = this;
  262. for (i = 0; i < this.properties.length; i++) {
  263. prop = this.properties[i];
  264. var ref = prop.$ref;
  265. var model = models[ref];
  266. if (model && typeof modelsToIgnore[ref] === 'undefined') {
  267. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  268. }
  269. }
  270. return returnVal;
  271. };
  272. /**
  273. * Resolves a spec's remote references
  274. */
  275. var Resolver = function (){};
  276. Resolver.prototype.resolve = function(spec, callback, scope) {
  277. this.scope = (scope || this);
  278. var host, name, path, property, propertyName, type;
  279. var processedCalls = 0, resolvedRefs = {}, unresolvedRefs = {};
  280. // store objects for dereferencing
  281. var resolutionTable = {};
  282. // models
  283. for(name in spec.definitions) {
  284. var model = spec.definitions[name];
  285. for(propertyName in model.properties) {
  286. property = model.properties[propertyName];
  287. this.resolveTo(property, resolutionTable);
  288. }
  289. }
  290. // operations
  291. for(name in spec.paths) {
  292. var method, operation, responseCode;
  293. path = spec.paths[name];
  294. for(method in path) {
  295. operation = path[method];
  296. var i, parameters = operation.parameters;
  297. for(i in parameters) {
  298. var parameter = parameters[i];
  299. if(parameter.in === 'body' && parameter.schema) {
  300. this.resolveTo(parameter.schema, resolutionTable);
  301. }
  302. if(parameter.$ref) {
  303. this.resolveInline(spec, parameter, resolutionTable, unresolvedRefs);
  304. }
  305. }
  306. for(responseCode in operation.responses) {
  307. var response = operation.responses[responseCode];
  308. if(response.schema) {
  309. this.resolveTo(response.schema, resolutionTable);
  310. }
  311. }
  312. }
  313. }
  314. // get hosts
  315. var opts = {}, expectedCalls = 0;
  316. for(name in resolutionTable) {
  317. var parts = name.split('#');
  318. if(parts.length == 2) {
  319. host = parts[0]; path = parts[1];
  320. if(!Array.isArray(opts[host])) {
  321. opts[host] = [];
  322. expectedCalls += 1;
  323. }
  324. opts[host].push(path);
  325. }
  326. }
  327. for(name in opts) {
  328. var self = this, opt = opts[name];
  329. host = name;
  330. var obj = {
  331. useJQuery: false, // TODO
  332. url: host,
  333. method: "get",
  334. headers: {
  335. accept: this.scope.swaggerRequestHeaders || 'application/json'
  336. },
  337. on: {
  338. error: function(response) {
  339. processedCalls += 1;
  340. var i;
  341. for(i = 0; i < opt.length; i++) {
  342. // fail all of these
  343. var resolved = host + '#' + opt[i];
  344. unresolvedRefs[resolved] = null;
  345. }
  346. if(processedCalls === expectedCalls)
  347. self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback);
  348. },
  349. response: function(response) {
  350. var i, j, swagger = response.obj;
  351. processedCalls += 1;
  352. for(i = 0; i < opt.length; i++) {
  353. var location = swagger, path = opt[i], parts = path.split('/');
  354. for(j = 0; j < parts.length; j++) {
  355. var segment = parts[j];
  356. if(typeof location === 'undefined')
  357. break;
  358. if(segment.length > 0)
  359. location = location[segment];
  360. }
  361. var resolved = host + '#' + path, resolvedName = parts[j-1];
  362. if(typeof location !== 'undefined') {
  363. resolvedRefs[resolved] = {
  364. name: resolvedName,
  365. obj: location
  366. };
  367. }
  368. else unresolvedRefs[resolved] = null;
  369. }
  370. if(processedCalls === expectedCalls)
  371. self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback);
  372. }
  373. }
  374. };
  375. authorizations.apply(obj);
  376. new SwaggerHttp().execute(obj);
  377. }
  378. if(Object.keys(opts).length === 0)
  379. callback.call(this.scope, spec, unresolvedRefs);
  380. };
  381. Resolver.prototype.finish = function(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback) {
  382. // walk resolution table and replace with resolved refs
  383. var ref;
  384. for(ref in resolutionTable) {
  385. var i, locations = resolutionTable[ref];
  386. for(i = 0; i < locations.length; i++) {
  387. var resolvedTo = resolvedRefs[locations[i].obj.$ref];
  388. if(resolvedTo) {
  389. if(!spec.definitions)
  390. spec.definitions = {};
  391. if(locations[i].resolveAs === '$ref') {
  392. spec.definitions[resolvedTo.name] = resolvedTo.obj;
  393. locations[i].obj.$ref = '#/definitions/' + resolvedTo.name;
  394. }
  395. else if (locations[i].resolveAs === 'inline') {
  396. var key;
  397. var targetObj = locations[i].obj;
  398. delete targetObj.$ref;
  399. for(key in resolvedTo.obj) {
  400. targetObj[key] = resolvedTo.obj[key];
  401. }
  402. }
  403. }
  404. }
  405. }
  406. callback.call(this.scope, spec, unresolvedRefs);
  407. };
  408. /**
  409. * immediately in-lines local refs, queues remote refs
  410. * for inline resolution
  411. */
  412. Resolver.prototype.resolveInline = function (spec, property, objs, unresolvedRefs) {
  413. var ref = property.$ref;
  414. if(ref) {
  415. if(ref.indexOf('http') === 0) {
  416. if(Array.isArray(objs[ref])) {
  417. objs[ref].push({obj: property, resolveAs: 'inline'});
  418. }
  419. else {
  420. objs[ref] = [{obj: property, resolveAs: 'inline'}];
  421. }
  422. }
  423. else if (ref.indexOf('#') === 0) {
  424. // local resolve
  425. var shortenedRef = ref.substring(1);
  426. var i, parts = shortenedRef.split('/'), location = spec;
  427. for(i = 0; i < parts.length; i++) {
  428. var part = parts[i];
  429. if(part.length > 0) {
  430. location = location[part];
  431. }
  432. }
  433. if(location) {
  434. delete property.$ref;
  435. var key;
  436. for(key in location) {
  437. property[key] = location[key];
  438. }
  439. }
  440. else unresolvedRefs[ref] = null;
  441. }
  442. }
  443. else if(property.type === 'array') {
  444. this.resolveTo(property.items, objs);
  445. }
  446. };
  447. Resolver.prototype.resolveTo = function (property, objs) {
  448. var ref = property.$ref;
  449. if(ref) {
  450. if(ref.indexOf('http') === 0) {
  451. if(Array.isArray(objs[ref])) {
  452. objs[ref].push({obj: property, resolveAs: '$ref'});
  453. }
  454. else {
  455. objs[ref] = [{obj: property, resolveAs: '$ref'}];
  456. }
  457. }
  458. }
  459. else if(property.type === 'array') {
  460. var items = property.items;
  461. this.resolveTo(items, objs);
  462. }
  463. };
  464. var addModel = function(name, model) {
  465. models[name] = model;
  466. };
  467. var SwaggerClient = function(url, options) {
  468. this.isBuilt = false;
  469. this.url = null;
  470. this.debug = false;
  471. this.basePath = null;
  472. this.modelsArray = [];
  473. this.authorizations = null;
  474. this.authorizationScheme = null;
  475. this.isValid = false;
  476. this.info = null;
  477. this.useJQuery = false;
  478. this.resourceCount = 0;
  479. if(typeof url !== 'undefined')
  480. return this.initialize(url, options);
  481. };
  482. SwaggerClient.prototype.initialize = function (url, options) {
  483. this.models = models = {};
  484. options = (options||{});
  485. if(typeof url === 'string')
  486. this.url = url;
  487. else if(typeof url === 'object') {
  488. options = url;
  489. this.url = options.url;
  490. }
  491. this.swaggerRequstHeaders = options.swaggerRequstHeaders || 'application/json;charset=utf-8,*/*';
  492. this.defaultSuccessCallback = options.defaultSuccessCallback || null;
  493. this.defaultErrorCallback = options.defaultErrorCallback || null;
  494. if (typeof options.success === 'function')
  495. this.success = options.success;
  496. if (options.useJQuery)
  497. this.useJQuery = options.useJQuery;
  498. if (options.authorizations) {
  499. this.clientAuthorizations = options.authorizations;
  500. } else {
  501. this.clientAuthorizations = authorizations;
  502. }
  503. this.supportedSubmitMethods = options.supportedSubmitMethods || [];
  504. this.failure = options.failure || function() {};
  505. this.progress = options.progress || function() {};
  506. this.spec = options.spec;
  507. this.options = options;
  508. if (typeof options.success === 'function') {
  509. this.ready = true;
  510. this.build();
  511. }
  512. };
  513. SwaggerClient.prototype.build = function(mock) {
  514. if (this.isBuilt) return this;
  515. var self = this;
  516. this.progress('fetching resource list: ' + this.url);
  517. var obj = {
  518. useJQuery: this.useJQuery,
  519. url: this.url,
  520. method: "get",
  521. headers: {
  522. accept: this.swaggerRequstHeaders
  523. },
  524. on: {
  525. error: function(response) {
  526. if (self.url.substring(0, 4) !== 'http')
  527. return self.fail('Please specify the protocol for ' + self.url);
  528. else if (response.status === 0)
  529. return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
  530. else if (response.status === 404)
  531. return self.fail('Can\'t read swagger JSON from ' + self.url);
  532. else
  533. return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
  534. },
  535. response: function(resp) {
  536. var responseObj = resp.obj || JSON.parse(resp.data);
  537. self.swaggerVersion = responseObj.swaggerVersion;
  538. if(responseObj.swagger && parseInt(responseObj.swagger) === 2) {
  539. self.swaggerVersion = responseObj.swagger;
  540. new Resolver().resolve(responseObj, self.buildFromSpec, self);
  541. self.isValid = true;
  542. }
  543. else {
  544. if (self.swaggerVersion === '1.2') {
  545. return self.buildFrom1_2Spec(responseObj);
  546. } else {
  547. return self.buildFrom1_1Spec(responseObj);
  548. }
  549. }
  550. }
  551. }
  552. };
  553. if(this.spec) {
  554. setTimeout(function() {
  555. new Resolver().resolve(self.spec, self.buildFromSpec, self);
  556. }, 10);
  557. }
  558. else {
  559. authorizations.apply(obj);
  560. if(mock)
  561. return obj;
  562. new SwaggerHttp().execute(obj);
  563. }
  564. return this;
  565. };
  566. SwaggerClient.prototype.buildFromSpec = function(response) {
  567. if(this.isBuilt) return this;
  568. this.info = response.info || {};
  569. this.title = response.title || '';
  570. this.host = response.host || '';
  571. this.schemes = response.schemes || [];
  572. this.basePath = response.basePath || '';
  573. this.apis = {};
  574. this.apisArray = [];
  575. this.consumes = response.consumes;
  576. this.produces = response.produces;
  577. this.securityDefinitions = response.securityDefinitions;
  578. // legacy support
  579. this.authSchemes = response.securityDefinitions;
  580. var definedTags = {};
  581. if(Array.isArray(response.tags)) {
  582. definedTags = {};
  583. for(k = 0; k < response.tags.length; k++) {
  584. var t = response.tags[k];
  585. definedTags[t.name] = t;
  586. }
  587. }
  588. var location;
  589. if(typeof this.url === 'string') {
  590. location = this.parseUri(this.url);
  591. }
  592. if(typeof this.schemes === 'undefined' || this.schemes.length === 0) {
  593. this.scheme = location.scheme || 'http';
  594. }
  595. else {
  596. this.scheme = this.schemes[0];
  597. }
  598. if(typeof this.host === 'undefined' || this.host === '') {
  599. this.host = location.host;
  600. if (location.port) {
  601. this.host = this.host + ':' + location.port;
  602. }
  603. }
  604. this.definitions = response.definitions;
  605. var key;
  606. for(key in this.definitions) {
  607. var model = new Model(key, this.definitions[key]);
  608. if(model) {
  609. models[key] = model;
  610. }
  611. }
  612. // get paths, create functions for each operationId
  613. var path;
  614. var operations = [];
  615. for(path in response.paths) {
  616. if(typeof response.paths[path] === 'object') {
  617. var httpMethod;
  618. for(httpMethod in response.paths[path]) {
  619. if(['delete', 'get', 'head', 'options', 'patch', 'post', 'put'].indexOf(httpMethod) === -1) {
  620. continue;
  621. }
  622. var operation = response.paths[path][httpMethod];
  623. var tags = operation.tags;
  624. if(typeof tags === 'undefined') {
  625. operation.tags = [ 'default' ];
  626. tags = operation.tags;
  627. }
  628. var operationId = this.idFromOp(path, httpMethod, operation);
  629. var operationObject = new Operation (
  630. this,
  631. operation.scheme,
  632. operationId,
  633. httpMethod,
  634. path,
  635. operation,
  636. this.definitions
  637. );
  638. // bind this operation's execute command to the api
  639. if(tags.length > 0) {
  640. var i;
  641. for(i = 0; i < tags.length; i++) {
  642. var tag = this.tagFromLabel(tags[i]);
  643. var operationGroup = this[tag];
  644. if(typeof this.apis[tag] === 'undefined')
  645. this.apis[tag] = {};
  646. if(typeof operationGroup === 'undefined') {
  647. this[tag] = [];
  648. operationGroup = this[tag];
  649. operationGroup.operations = {};
  650. operationGroup.label = tag;
  651. operationGroup.apis = [];
  652. var tagObject = definedTags[tag];
  653. if(typeof tagObject === 'object') {
  654. operationGroup.description = tagObject.description;
  655. operationGroup.externalDocs = tagObject.externalDocs;
  656. }
  657. this[tag].help = this.help.bind(operationGroup);
  658. this.apisArray.push(new OperationGroup(tag, operationGroup.description, operationGroup.externalDocs, operationObject));
  659. }
  660. if(typeof this.apis[tag].help !== 'function')
  661. this.apis[tag].help = this.help.bind(operationGroup);
  662. // bind to the apis object
  663. this.apis[tag][operationId] = operationObject.execute.bind(operationObject);
  664. this.apis[tag][operationId].help = operationObject.help.bind(operationObject);
  665. this.apis[tag][operationId].asCurl = operationObject.asCurl.bind(operationObject);
  666. operationGroup[operationId] = operationObject.execute.bind(operationObject);
  667. operationGroup[operationId].help = operationObject.help.bind(operationObject);
  668. operationGroup[operationId].asCurl = operationObject.asCurl.bind(operationObject);
  669. operationGroup.apis.push(operationObject);
  670. operationGroup.operations[operationId] = operationObject;
  671. // legacy UI feature
  672. var j;
  673. var api;
  674. for(j = 0; j < this.apisArray.length; j++) {
  675. if(this.apisArray[j].tag === tag) {
  676. api = this.apisArray[j];
  677. }
  678. }
  679. if(api) {
  680. api.operationsArray.push(operationObject);
  681. }
  682. }
  683. }
  684. else {
  685. log('no group to bind to');
  686. }
  687. }
  688. }
  689. }
  690. this.isBuilt = true;
  691. if (this.success) {
  692. this.isValid = true;
  693. this.isBuilt = true;
  694. this.success();
  695. }
  696. return this;
  697. };
  698. SwaggerClient.prototype.parseUri = function(uri) {
  699. var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
  700. var parts = urlParseRE.exec(uri);
  701. return {
  702. scheme: parts[4].replace(':',''),
  703. host: parts[11],
  704. port: parts[12],
  705. path: parts[15]
  706. };
  707. };
  708. SwaggerClient.prototype.help = function(dontPrint) {
  709. var i;
  710. var output = 'operations for the "' + this.label + '" tag';
  711. for(i = 0; i < this.apis.length; i++) {
  712. var api = this.apis[i];
  713. output += '\n * ' + api.nickname + ': ' + api.operation.summary;
  714. }
  715. if(dontPrint)
  716. return output;
  717. else {
  718. log(output);
  719. return output;
  720. }
  721. };
  722. SwaggerClient.prototype.tagFromLabel = function(label) {
  723. return label;
  724. };
  725. SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) {
  726. var opId = op.operationId || (path.substring(1) + '_' + httpMethod);
  727. return opId.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()\+\s]/g,'_');
  728. };
  729. SwaggerClient.prototype.fail = function(message) {
  730. this.failure(message);
  731. throw message;
  732. };
  733. var OperationGroup = function(tag, description, externalDocs, operation) {
  734. this.tag = tag;
  735. this.path = tag;
  736. this.description = description;
  737. this.externalDocs = externalDocs;
  738. this.name = tag;
  739. this.operation = operation;
  740. this.operationsArray = [];
  741. };
  742. var Operation = function(parent, scheme, operationId, httpMethod, path, args, definitions) {
  743. var errors = [];
  744. parent = parent||{};
  745. args = args||{};
  746. this.operations = {};
  747. this.operation = args;
  748. this.deprecated = args.deprecated;
  749. this.consumes = args.consumes;
  750. this.produces = args.produces;
  751. this.parent = parent;
  752. this.host = parent.host || 'localhost';
  753. this.schemes = parent.schemes;
  754. this.scheme = scheme || parent.scheme || 'http';
  755. this.basePath = parent.basePath || '/';
  756. this.nickname = (operationId||errors.push('Operations must have a nickname.'));
  757. this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.'));
  758. this.path = (path||errors.push('Operation ' + this.nickname + ' is missing path.'));
  759. this.parameters = args !== null ? (args.parameters||[]) : {};
  760. this.summary = args.summary || '';
  761. this.responses = (args.responses||{});
  762. this.type = null;
  763. this.security = args.security;
  764. this.authorizations = args.security;
  765. this.description = args.description;
  766. this.useJQuery = parent.useJQuery;
  767. if(typeof this.deprecated === 'string') {
  768. switch(this.deprecated.toLowerCase()) {
  769. case 'true': case 'yes': case '1': {
  770. this.deprecated = true;
  771. break;
  772. }
  773. case 'false': case 'no': case '0': case null: {
  774. this.deprecated = false;
  775. break;
  776. }
  777. default: this.deprecated = Boolean(this.deprecated);
  778. }
  779. }
  780. var i, model;
  781. if(definitions) {
  782. // add to global models
  783. var key;
  784. for(key in this.definitions) {
  785. model = new Model(key, definitions[key]);
  786. if(model) {
  787. models[key] = model;
  788. }
  789. }
  790. }
  791. for(i = 0; i < this.parameters.length; i++) {
  792. var param = this.parameters[i];
  793. if(param.type === 'array') {
  794. param.isList = true;
  795. param.allowMultiple = true;
  796. }
  797. var innerType = this.getType(param);
  798. if(innerType && innerType.toString().toLowerCase() === 'boolean') {
  799. param.allowableValues = {};
  800. param.isList = true;
  801. param['enum'] = ["true", "false"];
  802. }
  803. if(typeof param['enum'] !== 'undefined') {
  804. var id;
  805. param.allowableValues = {};
  806. param.allowableValues.values = [];
  807. param.allowableValues.descriptiveValues = [];
  808. for(id = 0; id < param['enum'].length; id++) {
  809. var value = param['enum'][id];
  810. var isDefault = (value === param.default) ? true : false;
  811. param.allowableValues.values.push(value);
  812. param.allowableValues.descriptiveValues.push({value : value, isDefault: isDefault});
  813. }
  814. }
  815. if(param.type === 'array') {
  816. innerType = [innerType];
  817. if(typeof param.allowableValues === 'undefined') {
  818. // can't show as a list if no values to select from
  819. delete param.isList;
  820. delete param.allowMultiple;
  821. }
  822. }
  823. param.signature = this.getModelSignature(innerType, models).toString();
  824. param.sampleJSON = this.getModelSampleJSON(innerType, models);
  825. param.responseClassSignature = param.signature;
  826. }
  827. var defaultResponseCode, response, responses = this.responses;
  828. if(responses['200']) {
  829. response = responses['200'];
  830. defaultResponseCode = '200';
  831. }
  832. else if(responses['201']) {
  833. response = responses['201'];
  834. defaultResponseCode = '201';
  835. }
  836. else if(responses['202']) {
  837. response = responses['202'];
  838. defaultResponseCode = '202';
  839. }
  840. else if(responses['203']) {
  841. response = responses['203'];
  842. defaultResponseCode = '203';
  843. }
  844. else if(responses['204']) {
  845. response = responses['204'];
  846. defaultResponseCode = '204';
  847. }
  848. else if(responses['205']) {
  849. response = responses['205'];
  850. defaultResponseCode = '205';
  851. }
  852. else if(responses['206']) {
  853. response = responses['206'];
  854. defaultResponseCode = '206';
  855. }
  856. else if(responses['default']) {
  857. response = responses['default'];
  858. defaultResponseCode = 'default';
  859. }
  860. if(response && response.schema) {
  861. var resolvedModel = this.resolveModel(response.schema, definitions);
  862. delete responses[defaultResponseCode];
  863. if(resolvedModel) {
  864. this.successResponse = {};
  865. this.successResponse[defaultResponseCode] = resolvedModel;
  866. }
  867. else {
  868. this.successResponse = {};
  869. this.successResponse[defaultResponseCode] = response.schema.type;
  870. }
  871. this.type = response;
  872. }
  873. if (errors.length > 0) {
  874. if(this.resource && this.resource.api && this.resource.api.fail)
  875. this.resource.api.fail(errors);
  876. }
  877. return this;
  878. };
  879. OperationGroup.prototype.sort = function(sorter) {
  880. };
  881. Operation.prototype.getType = function (param) {
  882. var type = param.type;
  883. var format = param.format;
  884. var isArray = false;
  885. var str;
  886. if(type === 'integer' && format === 'int32')
  887. str = 'integer';
  888. else if(type === 'integer' && format === 'int64')
  889. str = 'long';
  890. else if(type === 'integer')
  891. str = 'integer';
  892. else if(type === 'string') {
  893. if(format === 'date-time')
  894. str = 'date-time';
  895. else if(format === 'date')
  896. str = 'date';
  897. else
  898. str = 'string';
  899. }
  900. else if(type === 'number' && format === 'float')
  901. str = 'float';
  902. else if(type === 'number' && format === 'double')
  903. str = 'double';
  904. else if(type === 'number')
  905. str = 'double';
  906. else if(type === 'boolean')
  907. str = 'boolean';
  908. else if(type === 'array') {
  909. isArray = true;
  910. if(param.items)
  911. str = this.getType(param.items);
  912. }
  913. if(param.$ref)
  914. str = param.$ref;
  915. var schema = param.schema;
  916. if(schema) {
  917. var ref = schema.$ref;
  918. if(ref) {
  919. ref = simpleRef(ref);
  920. if(isArray)
  921. return [ ref ];
  922. else
  923. return ref;
  924. }
  925. else
  926. return this.getType(schema);
  927. }
  928. if(isArray)
  929. return [ str ];
  930. else
  931. return str;
  932. };
  933. Operation.prototype.resolveModel = function (schema, definitions) {
  934. if(typeof schema.$ref !== 'undefined') {
  935. var ref = schema.$ref;
  936. if(ref.indexOf('#/definitions/') === 0)
  937. ref = ref.substring('#/definitions/'.length);
  938. if(definitions[ref]) {
  939. return new Model(ref, definitions[ref]);
  940. }
  941. }
  942. if(schema.type === 'array')
  943. return new ArrayModel(schema);
  944. else
  945. return null;
  946. };
  947. Operation.prototype.help = function(dontPrint) {
  948. var out = this.nickname + ': ' + this.summary + '\n';
  949. for(var i = 0; i < this.parameters.length; i++) {
  950. var param = this.parameters[i];
  951. var typeInfo = param.signature;
  952. out += '\n * ' + param.name + ' (' + typeInfo + '): ' + param.description;
  953. }
  954. if(typeof dontPrint === 'undefined')
  955. log(out);
  956. return out;
  957. };
  958. Operation.prototype.getModelSignature = function(type, definitions) {
  959. var isPrimitive, listType;
  960. if(type instanceof Array) {
  961. listType = true;
  962. type = type[0];
  963. }
  964. else if(typeof type === 'undefined')
  965. type = 'undefined';
  966. if(type === 'string')
  967. isPrimitive = true;
  968. else
  969. isPrimitive = (listType && definitions[listType]) || (definitions[type]) ? false : true;
  970. if (isPrimitive) {
  971. if(listType)
  972. return 'Array[' + type + ']';
  973. else
  974. return type.toString();
  975. } else {
  976. if (listType)
  977. return 'Array[' + definitions[type].getMockSignature() + ']';
  978. else
  979. return definitions[type].getMockSignature();
  980. }
  981. };
  982. Operation.prototype.supportHeaderParams = function () {
  983. return true;
  984. };
  985. Operation.prototype.supportedSubmitMethods = function () {
  986. return this.parent.supportedSubmitMethods;
  987. };
  988. Operation.prototype.getHeaderParams = function (args) {
  989. var headers = this.setContentTypes(args, {});
  990. for(var i = 0; i < this.parameters.length; i++) {
  991. var param = this.parameters[i];
  992. if(typeof args[param.name] !== 'undefined') {
  993. if (param.in === 'header') {
  994. var value = args[param.name];
  995. if(Array.isArray(value))
  996. value = value.toString();
  997. headers[param.name] = value;
  998. }
  999. }
  1000. }
  1001. return headers;
  1002. };
  1003. Operation.prototype.urlify = function (args) {
  1004. var formParams = {};
  1005. var requestUrl = this.path;
  1006. // grab params from the args, build the querystring along the way
  1007. var querystring = '';
  1008. for(var i = 0; i < this.parameters.length; i++) {
  1009. var param = this.parameters[i];
  1010. if(typeof args[param.name] !== 'undefined') {
  1011. if(param.in === 'path') {
  1012. var reg = new RegExp('\{' + param.name + '\}', 'gi');
  1013. var value = args[param.name];
  1014. if(Array.isArray(value))
  1015. value = this.encodePathCollection(param.collectionFormat, param.name, value);
  1016. else
  1017. value = this.encodePathParam(value);
  1018. requestUrl = requestUrl.replace(reg, value);
  1019. }
  1020. else if (param.in === 'query' && typeof args[param.name] !== 'undefined') {
  1021. if(querystring === '')
  1022. querystring += '?';
  1023. else
  1024. querystring += '&';
  1025. if(typeof param.collectionFormat !== 'undefined') {
  1026. var qp = args[param.name];
  1027. if(Array.isArray(qp))
  1028. querystring += this.encodeQueryCollection(param.collectionFormat, param.name, qp);
  1029. else
  1030. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  1031. }
  1032. else
  1033. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  1034. }
  1035. else if (param.in === 'formData')
  1036. formParams[param.name] = args[param.name];
  1037. }
  1038. }
  1039. var url = this.scheme + '://' + this.host;
  1040. if(this.basePath !== '/')
  1041. url += this.basePath;
  1042. return url + requestUrl + querystring;
  1043. };
  1044. Operation.prototype.getMissingParams = function(args) {
  1045. var missingParams = [];
  1046. // check required params, track the ones that are missing
  1047. var i;
  1048. for(i = 0; i < this.parameters.length; i++) {
  1049. var param = this.parameters[i];
  1050. if(param.required === true) {
  1051. if(typeof args[param.name] === 'undefined')
  1052. missingParams = param.name;
  1053. }
  1054. }
  1055. return missingParams;
  1056. };
  1057. Operation.prototype.getBody = function(headers, args, opts) {
  1058. var formParams = {}, body, key;
  1059. for(var i = 0; i < this.parameters.length; i++) {
  1060. var param = this.parameters[i];
  1061. if(typeof args[param.name] !== 'undefined') {
  1062. if (param.in === 'body') {
  1063. body = args[param.name];
  1064. } else if(param.in === 'formData') {
  1065. formParams[param.name] = args[param.name];
  1066. }
  1067. }
  1068. }
  1069. // handle form params
  1070. if(headers['Content-Type'] === 'application/x-www-form-urlencoded') {
  1071. var encoded = "";
  1072. for(key in formParams) {
  1073. value = formParams[key];
  1074. if(typeof value !== 'undefined'){
  1075. if(encoded !== "")
  1076. encoded += "&";
  1077. encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  1078. }
  1079. }
  1080. body = encoded;
  1081. }
  1082. else if (headers['Content-Type'] && headers['Content-Type'].indexOf('multipart/form-data') >= 0) {
  1083. if(opts.useJQuery) {
  1084. var bodyParam = new FormData();
  1085. bodyParam.type = 'formData';
  1086. for (key in formParams) {
  1087. value = args[key];
  1088. if (typeof value !== 'undefined') {
  1089. // required for jquery file upload
  1090. if(value.type === 'file' && value.value) {
  1091. delete headers['Content-Type'];
  1092. bodyParam.append(key, value.value);
  1093. }
  1094. else
  1095. bodyParam.append(key, value);
  1096. }
  1097. }
  1098. body = bodyParam;
  1099. }
  1100. }
  1101. return body;
  1102. };
  1103. /**
  1104. * gets sample response for a single operation
  1105. **/
  1106. Operation.prototype.getModelSampleJSON = function(type, models) {
  1107. var isPrimitive, listType, sampleJson;
  1108. listType = (type instanceof Array);
  1109. isPrimitive = models[type] ? false : true;
  1110. sampleJson = isPrimitive ? void 0 : models[type].createJSONSample();
  1111. if (sampleJson) {
  1112. sampleJson = listType ? [sampleJson] : sampleJson;
  1113. if(typeof sampleJson == 'string')
  1114. return sampleJson;
  1115. else if(typeof sampleJson === 'object') {
  1116. var t = sampleJson;
  1117. if(sampleJson instanceof Array && sampleJson.length > 0) {
  1118. t = sampleJson[0];
  1119. }
  1120. if(t.nodeName) {
  1121. var xmlString = new XMLSerializer().serializeToString(t);
  1122. return this.formatXml(xmlString);
  1123. }
  1124. else
  1125. return JSON.stringify(sampleJson, null, 2);
  1126. }
  1127. else
  1128. return sampleJson;
  1129. }
  1130. };
  1131. /**
  1132. * legacy binding
  1133. **/
  1134. Operation.prototype["do"] = function(args, opts, callback, error, parent) {
  1135. return this.execute(args, opts, callback, error, parent);
  1136. };
  1137. /**
  1138. * executes an operation
  1139. **/
  1140. Operation.prototype.execute = function(arg1, arg2, arg3, arg4, parent) {
  1141. var args = arg1 || {};
  1142. var opts = {}, success, error;
  1143. if(typeof arg2 === 'object') {
  1144. opts = arg2;
  1145. success = arg3;
  1146. error = arg4;
  1147. }
  1148. if(typeof arg2 === 'function') {
  1149. success = arg2;
  1150. error = arg3;
  1151. }
  1152. success = (success||log);
  1153. error = (error||log);
  1154. if(opts.useJQuery)
  1155. this.useJQuery = opts.useJQuery;
  1156. var missingParams = this.getMissingParams(args);
  1157. if(missingParams.length > 0) {
  1158. var message = 'missing required params: ' + missingParams;
  1159. fail(message);
  1160. return;
  1161. }
  1162. var allHeaders = this.getHeaderParams(args);
  1163. var contentTypeHeaders = this.setContentTypes(args, opts);
  1164. var headers = {}, attrname;
  1165. for (attrname in allHeaders) { headers[attrname] = allHeaders[attrname]; }
  1166. for (attrname in contentTypeHeaders) { headers[attrname] = contentTypeHeaders[attrname]; }
  1167. var body = this.getBody(headers, args, opts);
  1168. var url = this.urlify(args);
  1169. var obj = {
  1170. url: url,
  1171. method: this.method.toUpperCase(),
  1172. body: body,
  1173. useJQuery: this.useJQuery,
  1174. headers: headers,
  1175. on: {
  1176. response: function(response) {
  1177. return success(response, parent);
  1178. },
  1179. error: function(response) {
  1180. return error(response, parent);
  1181. }
  1182. }
  1183. };
  1184. var status = authorizations.apply(obj, this.operation.security);
  1185. if(opts.mock === true)
  1186. return obj;
  1187. else
  1188. new SwaggerHttp().execute(obj, opts);
  1189. };
  1190. Operation.prototype.setContentTypes = function(args, opts) {
  1191. // default type
  1192. var accepts = 'application/json';
  1193. var consumes = args.parameterContentType || 'application/json';
  1194. var allDefinedParams = this.parameters;
  1195. var definedFormParams = [];
  1196. var definedFileParams = [];
  1197. var body;
  1198. var headers = {};
  1199. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  1200. var i;
  1201. for(i = 0; i < allDefinedParams.length; i++) {
  1202. var param = allDefinedParams[i];
  1203. if(param.in === 'formData') {
  1204. if(param.type === 'file')
  1205. definedFileParams.push(param);
  1206. else
  1207. definedFormParams.push(param);
  1208. }
  1209. else if(param.in === 'header' && opts) {
  1210. var key = param.name;
  1211. var headerValue = opts[param.name];
  1212. if(typeof opts[param.name] !== 'undefined')
  1213. headers[key] = headerValue;
  1214. }
  1215. else if(param.in === 'body' && typeof args[param.name] !== 'undefined') {
  1216. body = args[param.name];
  1217. }
  1218. }
  1219. // if there's a body, need to set the consumes header via requestContentType
  1220. if (body && (this.method === 'post' || this.method === 'put' || this.method === 'patch' || this.method === 'delete')) {
  1221. if (opts.requestContentType)
  1222. consumes = opts.requestContentType;
  1223. } else {
  1224. // if any form params, content type must be set
  1225. if(definedFormParams.length > 0) {
  1226. if(opts.requestContentType) // override if set
  1227. consumes = opts.requestContentType;
  1228. else if(definedFileParams.length > 0) // if a file, must be multipart/form-data
  1229. consumes = 'multipart/form-data';
  1230. else // default to x-www-from-urlencoded
  1231. consumes = 'application/x-www-form-urlencoded';
  1232. }
  1233. else if (this.type == 'DELETE')
  1234. body = '{}';
  1235. else if (this.type != 'DELETE')
  1236. consumes = null;
  1237. }
  1238. if (consumes && this.consumes) {
  1239. if (this.consumes.indexOf(consumes) === -1) {
  1240. log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
  1241. }
  1242. }
  1243. if (opts.responseContentType) {
  1244. accepts = opts.responseContentType;
  1245. } else {
  1246. accepts = 'application/json';
  1247. }
  1248. if (accepts && this.produces) {
  1249. if (this.produces.indexOf(accepts) === -1) {
  1250. log('server can\'t produce ' + accepts);
  1251. }
  1252. }
  1253. if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
  1254. headers['Content-Type'] = consumes;
  1255. if (accepts)
  1256. headers.Accept = accepts;
  1257. return headers;
  1258. };
  1259. Operation.prototype.asCurl = function (args) {
  1260. var obj = this.execute(args, {mock: true});
  1261. authorizations.apply(obj);
  1262. var results = [];
  1263. results.push('-X ' + this.method.toUpperCase());
  1264. if (obj.headers) {
  1265. var key;
  1266. for (key in obj.headers)
  1267. results.push('--header "' + key + ': ' + obj.headers[key] + '"');
  1268. }
  1269. if(obj.body) {
  1270. var body;
  1271. if(typeof obj.body === 'object')
  1272. body = JSON.stringify(obj.body);
  1273. else
  1274. body = obj.body;
  1275. results.push('-d "' + body.replace(/"/g, '\\"') + '"');
  1276. }
  1277. return 'curl ' + (results.join(' ')) + ' "' + obj.url + '"';
  1278. };
  1279. Operation.prototype.encodePathCollection = function(type, name, value) {
  1280. var encoded = '';
  1281. var i;
  1282. var separator = '';
  1283. if(type === 'ssv')
  1284. separator = '%20';
  1285. else if(type === 'tsv')
  1286. separator = '\\t';
  1287. else if(type === 'pipes')
  1288. separator = '|';
  1289. else
  1290. separator = ',';
  1291. for(i = 0; i < value.length; i++) {
  1292. if(i === 0)
  1293. encoded = this.encodeQueryParam(value[i]);
  1294. else
  1295. encoded += separator + this.encodeQueryParam(value[i]);
  1296. }
  1297. return encoded;
  1298. };
  1299. Operation.prototype.encodeQueryCollection = function(type, name, value) {
  1300. var encoded = '';
  1301. var i;
  1302. if(type === 'default' || type === 'multi') {
  1303. for(i = 0; i < value.length; i++) {
  1304. if(i > 0) encoded += '&';
  1305. encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
  1306. }
  1307. }
  1308. else {
  1309. var separator = '';
  1310. if(type === 'csv')
  1311. separator = ',';
  1312. else if(type === 'ssv')
  1313. separator = '%20';
  1314. else if(type === 'tsv')
  1315. separator = '\\t';
  1316. else if(type === 'pipes')
  1317. separator = '|';
  1318. else if(type === 'brackets') {
  1319. for(i = 0; i < value.length; i++) {
  1320. if(i !== 0)
  1321. encoded += '&';
  1322. encoded += this.encodeQueryParam(name) + '[]=' + this.encodeQueryParam(value[i]);
  1323. }
  1324. }
  1325. if(separator !== '') {
  1326. for(i = 0; i < value.length; i++) {
  1327. if(i === 0)
  1328. encoded = this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
  1329. else
  1330. encoded += separator + this.encodeQueryParam(value[i]);
  1331. }
  1332. }
  1333. }
  1334. return encoded;
  1335. };
  1336. Operation.prototype.encodeQueryParam = function(arg) {
  1337. return encodeURIComponent(arg);
  1338. };
  1339. /**
  1340. * TODO revisit, might not want to leave '/'
  1341. **/
  1342. Operation.prototype.encodePathParam = function(pathParam) {
  1343. var encParts, part, parts, i, len;
  1344. pathParam = pathParam.toString();
  1345. if (pathParam.indexOf('/') === -1) {
  1346. return encodeURIComponent(pathParam);
  1347. } else {
  1348. parts = pathParam.split('/');
  1349. encParts = [];
  1350. for (i = 0, len = parts.length; i < len; i++) {
  1351. encParts.push(encodeURIComponent(parts[i]));
  1352. }
  1353. return encParts.join('/');
  1354. }
  1355. };
  1356. var Model = function(name, definition) {
  1357. this.name = name;
  1358. this.definition = definition || {};
  1359. this.properties = [];
  1360. var requiredFields = definition.required || [];
  1361. if(definition.type === 'array') {
  1362. var out = new ArrayModel(definition);
  1363. return out;
  1364. }
  1365. var key;
  1366. var props = definition.properties;
  1367. if(props) {
  1368. for(key in props) {
  1369. var required = false;
  1370. var property = props[key];
  1371. if(requiredFields.indexOf(key) >= 0)
  1372. required = true;
  1373. this.properties.push(new Property(key, property, required));
  1374. }
  1375. }
  1376. };
  1377. Model.prototype.createJSONSample = function(modelsToIgnore) {
  1378. var i, result = {}, representations = {};
  1379. modelsToIgnore = (modelsToIgnore||{});
  1380. modelsToIgnore[this.name] = this;
  1381. for (i = 0; i < this.properties.length; i++) {
  1382. prop = this.properties[i];
  1383. var sample = prop.getSampleValue(modelsToIgnore, representations);
  1384. result[prop.name] = sample;
  1385. }
  1386. delete modelsToIgnore[this.name];
  1387. return result;
  1388. };
  1389. Model.prototype.getSampleValue = function(modelsToIgnore) {
  1390. var i, obj = {}, representations = {};
  1391. for(i = 0; i < this.properties.length; i++ ) {
  1392. var property = this.properties[i];
  1393. obj[property.name] = property.sampleValue(false, modelsToIgnore, representations);
  1394. }
  1395. return obj;
  1396. };
  1397. Model.prototype.getMockSignature = function(modelsToIgnore) {
  1398. var i, prop, propertiesStr = [];
  1399. for (i = 0; i < this.properties.length; i++) {
  1400. prop = this.properties[i];
  1401. propertiesStr.push(prop.toString());
  1402. }
  1403. var strong = '<span class="strong">';
  1404. var stronger = '<span class="stronger">';
  1405. var strongClose = '</span>';
  1406. var classOpen = strong + this.name + ' {' + strongClose;
  1407. var classClose = strong + '}' + strongClose;
  1408. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  1409. if (!modelsToIgnore)
  1410. modelsToIgnore = {};
  1411. modelsToIgnore[this.name] = this;
  1412. for (i = 0; i < this.properties.length; i++) {
  1413. prop = this.properties[i];
  1414. var ref = prop.$ref;
  1415. var model = models[ref];
  1416. if (model && typeof modelsToIgnore[model.name] === 'undefined') {
  1417. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  1418. }
  1419. }
  1420. return returnVal;
  1421. };
  1422. var Property = function(name, obj, required) {
  1423. this.schema = obj;
  1424. this.required = required;
  1425. if(obj.$ref)
  1426. this.$ref = simpleRef(obj.$ref);
  1427. else if (obj.type === 'array' && obj.items) {
  1428. if(obj.items.$ref)
  1429. this.$ref = simpleRef(obj.items.$ref);
  1430. else
  1431. obj = obj.items;
  1432. }
  1433. this.name = name;
  1434. this.description = obj.description;
  1435. this.obj = obj;
  1436. this.optional = true;
  1437. this.optional = !required;
  1438. this.default = obj.default || null;
  1439. this.example = obj.example !== undefined ? obj.example : null;
  1440. this.collectionFormat = obj.collectionFormat || null;
  1441. this.maximum = obj.maximum || null;
  1442. this.exclusiveMaximum = obj.exclusiveMaximum || null;
  1443. this.minimum = obj.minimum || null;
  1444. this.exclusiveMinimum = obj.exclusiveMinimum || null;
  1445. this.maxLength = obj.maxLength || null;
  1446. this.minLength = obj.minLength || null;
  1447. this.pattern = obj.pattern || null;
  1448. this.maxItems = obj.maxItems || null;
  1449. this.minItems = obj.minItems || null;
  1450. this.uniqueItems = obj.uniqueItems || null;
  1451. this['enum'] = obj['enum'] || null;
  1452. this.multipleOf = obj.multipleOf || null;
  1453. };
  1454. Property.prototype.getSampleValue = function (modelsToIgnore, representations) {
  1455. return this.sampleValue(false, modelsToIgnore, representations);
  1456. };
  1457. Property.prototype.isArray = function () {
  1458. var schema = this.schema;
  1459. if(schema.type === 'array')
  1460. return true;
  1461. else
  1462. return false;
  1463. };
  1464. Property.prototype.sampleValue = function(isArray, ignoredModels, representations) {
  1465. isArray = (isArray || this.isArray());
  1466. ignoredModels = (ignoredModels || {});
  1467. // representations = (representations || {});
  1468. var type = getStringSignature(this.obj, true);
  1469. var output;
  1470. if(this.$ref) {
  1471. var refModelName = simpleRef(this.$ref);
  1472. var refModel = models[refModelName];
  1473. if(typeof representations[type] !== 'undefined') {
  1474. return representations[type];
  1475. }
  1476. else
  1477. if(refModel && typeof ignoredModels[type] === 'undefined') {
  1478. ignoredModels[type] = this;
  1479. output = refModel.getSampleValue(ignoredModels, representations);
  1480. representations[type] = output;
  1481. }
  1482. else {
  1483. output = (representations[type] || refModelName);
  1484. }
  1485. }
  1486. else if(this.example)
  1487. output = this.example;
  1488. else if(this.default)
  1489. output = this.default;
  1490. else if(type === 'date-time')
  1491. output = new Date().toISOString();
  1492. else if(type === 'date')
  1493. output = new Date().toISOString().split("T")[0];
  1494. else if(type === 'string')
  1495. output = 'string';
  1496. else if(type === 'integer')
  1497. output = 0;
  1498. else if(type === 'long')
  1499. output = 0;
  1500. else if(type === 'float')
  1501. output = 0.0;
  1502. else if(type === 'double')
  1503. output = 0.0;
  1504. else if(type === 'boolean')
  1505. output = true;
  1506. else
  1507. output = {};
  1508. ignoredModels[type] = output;
  1509. if(isArray)
  1510. return [output];
  1511. else
  1512. return output;
  1513. };
  1514. getStringSignature = function(obj, baseComponent) {
  1515. var str = '';
  1516. if(typeof obj.$ref !== 'undefined')
  1517. str += simpleRef(obj.$ref);
  1518. else if(typeof obj.type === 'undefined')
  1519. str += 'object';
  1520. else if(obj.type === 'array') {
  1521. if(baseComponent)
  1522. str += getStringSignature((obj.items || obj.$ref || {}));
  1523. else {
  1524. str += 'Array[';
  1525. str += getStringSignature((obj.items || obj.$ref || {}));
  1526. str += ']';
  1527. }
  1528. }
  1529. else if(obj.type === 'integer' && obj.format === 'int32')
  1530. str += 'integer';
  1531. else if(obj.type === 'integer' && obj.format === 'int64')
  1532. str += 'long';
  1533. else if(obj.type === 'integer' && typeof obj.format === 'undefined')
  1534. str += 'long';
  1535. else if(obj.type === 'string' && obj.format === 'date-time')
  1536. str += 'date-time';
  1537. else if(obj.type === 'string' && obj.format === 'date')
  1538. str += 'date';
  1539. else if(obj.type === 'string' && typeof obj.format === 'undefined')
  1540. str += 'string';
  1541. else if(obj.type === 'number' && obj.format === 'float')
  1542. str += 'float';
  1543. else if(obj.type === 'number' && obj.format === 'double')
  1544. str += 'double';
  1545. else if(obj.type === 'number' && typeof obj.format === 'undefined')
  1546. str += 'double';
  1547. else if(obj.type === 'boolean')
  1548. str += 'boolean';
  1549. else if(obj.$ref)
  1550. str += simpleRef(obj.$ref);
  1551. else
  1552. str += obj.type;
  1553. return str;
  1554. };
  1555. simpleRef = function(name) {
  1556. if(typeof name === 'undefined')
  1557. return null;
  1558. if(name.indexOf("#/definitions/") === 0)
  1559. return name.substring('#/definitions/'.length);
  1560. else
  1561. return name;
  1562. };
  1563. Property.prototype.toString = function() {
  1564. var str = getStringSignature(this.obj);
  1565. if(str !== '') {
  1566. str = '<span class="propName ' + this.required + '">' + this.name + '</span> (<span class="propType">' + str + '</span>';
  1567. if(!this.required)
  1568. str += ', <span class="propOptKey">optional</span>';
  1569. str += ')';
  1570. }
  1571. else
  1572. str = this.name + ' (' + JSON.stringify(this.obj) + ')';
  1573. if(typeof this.description !== 'undefined')
  1574. str += ': ' + this.description;
  1575. if (this['enum']) {
  1576. str += ' = <span class="propVals">[\'' + this['enum'].join('\' or \'') + '\']</span>';
  1577. }
  1578. if (this.descr) {
  1579. str += ': <span class="propDesc">' + this.descr + '</span>';
  1580. }
  1581. var options = '';
  1582. var isArray = this.schema.type === 'array';
  1583. var type;
  1584. if(isArray) {
  1585. if(this.schema.items)
  1586. type = this.schema.items.type;
  1587. else
  1588. type = '';
  1589. }
  1590. else {
  1591. type = this.schema.type;
  1592. }
  1593. if (this.default)
  1594. options += optionHtml('Default', this.default);
  1595. switch (type) {
  1596. case 'string':
  1597. if (this.minLength)
  1598. options += optionHtml('Min. Length', this.minLength);
  1599. if (this.maxLength)
  1600. options += optionHtml('Max. Length', this.maxLength);
  1601. if (this.pattern)
  1602. options += optionHtml('Reg. Exp.', this.pattern);
  1603. break;
  1604. case 'integer':
  1605. case 'number':
  1606. if (this.minimum)
  1607. options += optionHtml('Min. Value', this.minimum);
  1608. if (this.exclusiveMinimum)
  1609. options += optionHtml('Exclusive Min.', "true");
  1610. if (this.maximum)
  1611. options += optionHtml('Max. Value', this.maximum);
  1612. if (this.exclusiveMaximum)
  1613. options += optionHtml('Exclusive Max.', "true");
  1614. if (this.multipleOf)
  1615. options += optionHtml('Multiple Of', this.multipleOf);
  1616. break;
  1617. }
  1618. if (isArray) {
  1619. if (this.minItems)
  1620. options += optionHtml('Min. Items', this.minItems);
  1621. if (this.maxItems)
  1622. options += optionHtml('Max. Items', this.maxItems);
  1623. if (this.uniqueItems)
  1624. options += optionHtml('Unique Items', "true");
  1625. if (this.collectionFormat)
  1626. options += optionHtml('Coll. Format', this.collectionFormat);
  1627. }
  1628. if (this['enum']) {
  1629. var enumString;
  1630. if (type === 'number' || type === 'integer')
  1631. enumString = this['enum'].join(', ');
  1632. else {
  1633. enumString = '"' + this['enum'].join('", "') + '"';
  1634. }
  1635. options += optionHtml('Enum', enumString);
  1636. }
  1637. if (options.length > 0)
  1638. str = '<span class="propWrap">' + str + '<table class="optionsWrapper"><tr><th colspan="2">' + this.name + '</th></tr>' + options + '</table></span>';
  1639. return str;
  1640. };
  1641. optionHtml = function(label, value) {
  1642. return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
  1643. };
  1644. typeFromJsonSchema = function(type, format) {
  1645. var str;
  1646. if(type === 'integer' && format === 'int32')
  1647. str = 'integer';
  1648. else if(type === 'integer' && format === 'int64')
  1649. str = 'long';
  1650. else if(type === 'integer' && typeof format === 'undefined')
  1651. str = 'long';
  1652. else if(type === 'string' && format === 'date-time')
  1653. str = 'date-time';
  1654. else if(type === 'string' && format === 'date')
  1655. str = 'date';
  1656. else if(type === 'number' && format === 'float')
  1657. str = 'float';
  1658. else if(type === 'number' && format === 'double')
  1659. str = 'double';
  1660. else if(type === 'number' && typeof format === 'undefined')
  1661. str = 'double';
  1662. else if(type === 'boolean')
  1663. str = 'boolean';
  1664. else if(type === 'string')
  1665. str = 'string';
  1666. return str;
  1667. };
  1668. var sampleModels = {};
  1669. var cookies = {};
  1670. var models = {};
  1671. SwaggerClient.prototype.buildFrom1_2Spec = function (response) {
  1672. if (response.apiVersion !== null) {
  1673. this.apiVersion = response.apiVersion;
  1674. }
  1675. this.apis = {};
  1676. this.apisArray = [];
  1677. this.consumes = response.consumes;
  1678. this.produces = response.produces;
  1679. this.authSchemes = response.authorizations;
  1680. this.info = this.convertInfo(response.info);
  1681. var isApi = false, i, res;
  1682. for (i = 0; i < response.apis.length; i++) {
  1683. var api = response.apis[i];
  1684. if (api.operations) {
  1685. var j;
  1686. for (j = 0; j < api.operations.length; j++) {
  1687. operation = api.operations[j];
  1688. isApi = true;
  1689. }
  1690. }
  1691. }
  1692. if (response.basePath)
  1693. this.basePath = response.basePath;
  1694. else if (this.url.indexOf('?') > 0)
  1695. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  1696. else
  1697. this.basePath = this.url;
  1698. if (isApi) {
  1699. var newName = response.resourcePath.replace(/\//g, '');
  1700. this.resourcePath = response.resourcePath;
  1701. res = new SwaggerResource(response, this);
  1702. this.apis[newName] = res;
  1703. this.apisArray.push(res);
  1704. this.finish();
  1705. } else {
  1706. var k;
  1707. this.expectedResourceCount = response.apis.length;
  1708. for (k = 0; k < response.apis.length; k++) {
  1709. var resource = response.apis[k];
  1710. res = new SwaggerResource(resource, this);
  1711. this.apis[res.name] = res;
  1712. this.apisArray.push(res);
  1713. }
  1714. }
  1715. this.isValid = true;
  1716. return this;
  1717. };
  1718. SwaggerClient.prototype.finish = function() {
  1719. if (typeof this.success === 'function') {
  1720. this.isValid = true;
  1721. this.ready = true;
  1722. this.isBuilt = true;
  1723. this.selfReflect();
  1724. this.success();
  1725. }
  1726. };
  1727. SwaggerClient.prototype.buildFrom1_1Spec = function (response) {
  1728. log('This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info');
  1729. if (response.apiVersion !== null)
  1730. this.apiVersion = response.apiVersion;
  1731. this.apis = {};
  1732. this.apisArray = [];
  1733. this.produces = response.produces;
  1734. this.info = this.convertInfo(response.info);
  1735. var isApi = false, res;
  1736. for (var i = 0; i < response.apis.length; i++) {
  1737. var api = response.apis[i];
  1738. if (api.operations) {
  1739. for (var j = 0; j < api.operations.length; j++) {
  1740. operation = api.operations[j];
  1741. isApi = true;
  1742. }
  1743. }
  1744. }
  1745. if (response.basePath) {
  1746. this.basePath = response.basePath;
  1747. } else if (this.url.indexOf('?') > 0) {
  1748. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  1749. } else {
  1750. this.basePath = this.url;
  1751. }
  1752. if (isApi) {
  1753. var newName = response.resourcePath.replace(/\//g, '');
  1754. this.resourcePath = response.resourcePath;
  1755. res = new SwaggerResource(response, this);
  1756. this.apis[newName] = res;
  1757. this.apisArray.push(res);
  1758. this.finish();
  1759. } else {
  1760. this.expectedResourceCount = response.apis.length;
  1761. for (k = 0; k < response.apis.length; k++) {
  1762. resource = response.apis[k];
  1763. res = new SwaggerResource(resource, this);
  1764. this.apis[res.name] = res;
  1765. this.apisArray.push(res);
  1766. }
  1767. }
  1768. this.isValid = true;
  1769. return this;
  1770. };
  1771. SwaggerClient.prototype.convertInfo = function (resp) {
  1772. if(typeof resp == 'object') {
  1773. var info = {};
  1774. info.title = resp.title;
  1775. info.description = resp.description;
  1776. info.termsOfService = resp.termsOfServiceUrl;
  1777. info.contact = {};
  1778. info.contact.name = resp.contact;
  1779. info.license = {};
  1780. info.license.name = resp.license;
  1781. info.license.url = resp.licenseUrl;
  1782. return info;
  1783. }
  1784. };
  1785. SwaggerClient.prototype.selfReflect = function () {
  1786. var resource, tag, ref;
  1787. if (this.apis === null) {
  1788. return false;
  1789. }
  1790. ref = this.apis;
  1791. for (tag in ref) {
  1792. api = ref[tag];
  1793. if (api.ready === null) {
  1794. return false;
  1795. }
  1796. this[tag] = api;
  1797. this[tag].help = __bind(api.help, api);
  1798. }
  1799. this.setConsolidatedModels();
  1800. this.ready = true;
  1801. };
  1802. SwaggerClient.prototype.setConsolidatedModels = function () {
  1803. var model, modelName, resource, resource_name, i, apis, models, results;
  1804. this.models = {};
  1805. apis = this.apis;
  1806. for (resource_name in apis) {
  1807. resource = apis[resource_name];
  1808. for (modelName in resource.models) {
  1809. if (typeof this.models[modelName] === 'undefined') {
  1810. this.models[modelName] = resource.models[modelName];
  1811. this.modelsArray.push(resource.models[modelName]);
  1812. }
  1813. }
  1814. }
  1815. models = this.modelsArray;
  1816. results = [];
  1817. for (i = 0; i < models.length; i++) {
  1818. model = models[i];
  1819. results.push(model.setReferencedModels(this.models));
  1820. }
  1821. return results;
  1822. };
  1823. var SwaggerResource = function (resourceObj, api) {
  1824. var _this = this;
  1825. this.api = api;
  1826. this.swaggerRequstHeaders = api.swaggerRequstHeaders;
  1827. this.path = (typeof this.api.resourcePath === 'string') ? this.api.resourcePath : resourceObj.path;
  1828. this.description = resourceObj.description;
  1829. this.authorizations = (resourceObj.authorizations || {});
  1830. var parts = this.path.split('/');
  1831. this.name = parts[parts.length - 1].replace('.{format}', '');
  1832. this.basePath = this.api.basePath;
  1833. this.operations = {};
  1834. this.operationsArray = [];
  1835. this.modelsArray = [];
  1836. this.models = api.models || {};
  1837. this.rawModels = {};
  1838. this.useJQuery = (typeof api.useJQuery !== 'undefined') ? api.useJQuery : null;
  1839. if ((resourceObj.apis) && this.api.resourcePath) {
  1840. this.addApiDeclaration(resourceObj);
  1841. } else {
  1842. if (typeof this.path === 'undefined') {
  1843. this.api.fail('SwaggerResources must have a path.');
  1844. }
  1845. if (this.path.substring(0, 4) === 'http') {
  1846. this.url = this.path.replace('{format}', 'json');
  1847. } else {
  1848. this.url = this.api.basePath + this.path.replace('{format}', 'json');
  1849. }
  1850. this.api.progress('fetching resource ' + this.name + ': ' + this.url);
  1851. var obj = {
  1852. url: this.url,
  1853. method: 'GET',
  1854. useJQuery: this.useJQuery,
  1855. headers: {
  1856. accept: this.swaggerRequstHeaders
  1857. },
  1858. on: {
  1859. response: function (resp) {
  1860. var responseObj = resp.obj || JSON.parse(resp.data);
  1861. _this.api.resourceCount += 1;
  1862. return _this.addApiDeclaration(responseObj);
  1863. },
  1864. error: function (response) {
  1865. _this.api.resourceCount += 1;
  1866. return _this.api.fail('Unable to read api \'' +
  1867. _this.name + '\' from path ' + _this.url + ' (server returned ' + response.statusText + ')');
  1868. }
  1869. }
  1870. };
  1871. var e = typeof window !== 'undefined' ? window : exports;
  1872. e.authorizations.apply(obj);
  1873. new SwaggerHttp().execute(obj);
  1874. }
  1875. };
  1876. SwaggerResource.prototype.help = function (dontPrint) {
  1877. var i;
  1878. var output = 'operations for the "' + this.name + '" tag';
  1879. for(i = 0; i < this.operationsArray.length; i++) {
  1880. var api = this.operationsArray[i];
  1881. output += '\n * ' + api.nickname + ': ' + api.description;
  1882. }
  1883. if(dontPrint)
  1884. return output;
  1885. else {
  1886. log(output);
  1887. return output;
  1888. }
  1889. };
  1890. SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
  1891. var pos, url;
  1892. url = this.api.basePath;
  1893. pos = url.lastIndexOf(relativeBasePath);
  1894. var parts = url.split('/');
  1895. var rootUrl = parts[0] + '//' + parts[2];
  1896. if (relativeBasePath.indexOf('http') === 0)
  1897. return relativeBasePath;
  1898. if (relativeBasePath === '/')
  1899. return rootUrl;
  1900. if (relativeBasePath.substring(0, 1) == '/') {
  1901. // use root + relative
  1902. return rootUrl + relativeBasePath;
  1903. }
  1904. else {
  1905. pos = this.basePath.lastIndexOf('/');
  1906. var base = this.basePath.substring(0, pos);
  1907. if (base.substring(base.length - 1) == '/')
  1908. return base + relativeBasePath;
  1909. else
  1910. return base + '/' + relativeBasePath;
  1911. }
  1912. };
  1913. SwaggerResource.prototype.addApiDeclaration = function (response) {
  1914. if (typeof response.produces === 'string')
  1915. this.produces = response.produces;
  1916. if (typeof response.consumes === 'string')
  1917. this.consumes = response.consumes;
  1918. if ((typeof response.basePath === 'string') && response.basePath.replace(/\s/g, '').length > 0)
  1919. this.basePath = response.basePath.indexOf('http') !== 0 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
  1920. this.resourcePath = response.resourcePath;
  1921. this.addModels(response.models);
  1922. if (response.apis) {
  1923. for (var i = 0 ; i < response.apis.length; i++) {
  1924. var endpoint = response.apis[i];
  1925. this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
  1926. }
  1927. }
  1928. this.api[this.name] = this;
  1929. this.ready = true;
  1930. if(this.api.resourceCount === this.api.expectedResourceCount)
  1931. this.api.finish();
  1932. return this;
  1933. };
  1934. SwaggerResource.prototype.addModels = function (models) {
  1935. if (typeof models === 'object') {
  1936. var modelName;
  1937. for (modelName in models) {
  1938. if (typeof this.models[modelName] === 'undefined') {
  1939. var swaggerModel = new SwaggerModel(modelName, models[modelName]);
  1940. this.modelsArray.push(swaggerModel);
  1941. this.models[modelName] = swaggerModel;
  1942. this.rawModels[modelName] = models[modelName];
  1943. }
  1944. }
  1945. var output = [];
  1946. for (var i = 0; i < this.modelsArray.length; i++) {
  1947. var model = this.modelsArray[i];
  1948. output.push(model.setReferencedModels(this.models));
  1949. }
  1950. return output;
  1951. }
  1952. };
  1953. SwaggerResource.prototype.addOperations = function (resource_path, ops, consumes, produces) {
  1954. if (ops) {
  1955. var output = [];
  1956. for (var i = 0; i < ops.length; i++) {
  1957. var o = ops[i];
  1958. consumes = this.consumes;
  1959. produces = this.produces;
  1960. if (typeof o.consumes !== 'undefined')
  1961. consumes = o.consumes;
  1962. else
  1963. consumes = this.consumes;
  1964. if (typeof o.produces !== 'undefined')
  1965. produces = o.produces;
  1966. else
  1967. produces = this.produces;
  1968. var type = (o.type || o.responseClass);
  1969. if (type === 'array') {
  1970. ref = null;
  1971. if (o.items)
  1972. ref = o.items.type || o.items.$ref;
  1973. type = 'array[' + ref + ']';
  1974. }
  1975. var responseMessages = o.responseMessages;
  1976. var method = o.method;
  1977. if (o.httpMethod) {
  1978. method = o.httpMethod;
  1979. }
  1980. if (o.supportedContentTypes) {
  1981. consumes = o.supportedContentTypes;
  1982. }
  1983. if (o.errorResponses) {
  1984. responseMessages = o.errorResponses;
  1985. for (var j = 0; j < responseMessages.length; j++) {
  1986. r = responseMessages[j];
  1987. r.message = r.reason;
  1988. r.reason = null;
  1989. }
  1990. }
  1991. o.nickname = this.sanitize(o.nickname);
  1992. var op = new SwaggerOperation(o.nickname,
  1993. resource_path,
  1994. method,
  1995. o.parameters,
  1996. o.summary,
  1997. o.notes,
  1998. type,
  1999. responseMessages,
  2000. this,
  2001. consumes,
  2002. produces,
  2003. o.authorizations,
  2004. o.deprecated);
  2005. this.operations[op.nickname] = op;
  2006. output.push(this.operationsArray.push(op));
  2007. }
  2008. return output;
  2009. }
  2010. };
  2011. SwaggerResource.prototype.sanitize = function (nickname) {
  2012. var op;
  2013. op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
  2014. op = op.replace(/((_){2,})/g, '_');
  2015. op = op.replace(/^(_)*/g, '');
  2016. op = op.replace(/([_])*$/g, '');
  2017. return op;
  2018. };
  2019. var SwaggerModel = function (modelName, obj) {
  2020. this.name = typeof obj.id !== 'undefined' ? obj.id : modelName;
  2021. this.properties = [];
  2022. var propertyName;
  2023. for (propertyName in obj.properties) {
  2024. if (obj.required) {
  2025. var value;
  2026. for (value in obj.required) {
  2027. if (propertyName === obj.required[value]) {
  2028. obj.properties[propertyName].required = true;
  2029. }
  2030. }
  2031. }
  2032. var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName], this);
  2033. this.properties.push(prop);
  2034. }
  2035. };
  2036. SwaggerModel.prototype.setReferencedModels = function (allModels) {
  2037. var results = [];
  2038. for (var i = 0; i < this.properties.length; i++) {
  2039. var property = this.properties[i];
  2040. var type = property.type || property.dataType;
  2041. if (allModels[type])
  2042. results.push(property.refModel = allModels[type]);
  2043. else if ((property.refDataType) && (allModels[property.refDataType]))
  2044. results.push(property.refModel = allModels[property.refDataType]);
  2045. else
  2046. results.push(void 0);
  2047. }
  2048. return results;
  2049. };
  2050. SwaggerModel.prototype.getMockSignature = function (modelsToIgnore) {
  2051. var i, prop, propertiesStr = [];
  2052. for (i = 0; i < this.properties.length; i++) {
  2053. prop = this.properties[i];
  2054. propertiesStr.push(prop.toString());
  2055. }
  2056. var strong = '<span class="strong">';
  2057. var strongClose = '</span>';
  2058. var classOpen = strong + this.name + ' {' + strongClose;
  2059. var classClose = strong + '}' + strongClose;
  2060. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  2061. if (!modelsToIgnore)
  2062. modelsToIgnore = [];
  2063. modelsToIgnore.push(this.name);
  2064. for (i = 0; i < this.properties.length; i++) {
  2065. prop = this.properties[i];
  2066. if ((prop.refModel) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
  2067. returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
  2068. }
  2069. }
  2070. return returnVal;
  2071. };
  2072. SwaggerModel.prototype.createJSONSample = function (modelsToIgnore) {
  2073. if (sampleModels[this.name]) {
  2074. return sampleModels[this.name];
  2075. }
  2076. else {
  2077. var result = {};
  2078. modelsToIgnore = (modelsToIgnore || []);
  2079. modelsToIgnore.push(this.name);
  2080. for (var i = 0; i < this.properties.length; i++) {
  2081. var prop = this.properties[i];
  2082. result[prop.name] = prop.getSampleValue(modelsToIgnore);
  2083. }
  2084. modelsToIgnore.pop(this.name);
  2085. return result;
  2086. }
  2087. };
  2088. var SwaggerModelProperty = function (name, obj, model) {
  2089. this.name = name;
  2090. this.dataType = obj.type || obj.dataType || obj.$ref;
  2091. this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
  2092. this.descr = obj.description;
  2093. this.required = obj.required;
  2094. this.defaultValue = applyModelPropertyMacro(obj, model);
  2095. if (obj.items) {
  2096. if (obj.items.type) {
  2097. this.refDataType = obj.items.type;
  2098. }
  2099. if (obj.items.$ref) {
  2100. this.refDataType = obj.items.$ref;
  2101. }
  2102. }
  2103. this.dataTypeWithRef = this.refDataType ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
  2104. if (obj.allowableValues) {
  2105. this.valueType = obj.allowableValues.valueType;
  2106. this.values = obj.allowableValues.values;
  2107. if (this.values) {
  2108. this.valuesString = '\'' + this.values.join('\' or \'') + '\'';
  2109. }
  2110. }
  2111. if (obj['enum']) {
  2112. this.valueType = 'string';
  2113. this.values = obj['enum'];
  2114. if (this.values) {
  2115. this.valueString = '\'' + this.values.join('\' or \'') + '\'';
  2116. }
  2117. }
  2118. };
  2119. SwaggerModelProperty.prototype.getSampleValue = function (modelsToIgnore) {
  2120. var result;
  2121. if ((this.refModel) && (modelsToIgnore.indexOf(this.refModel.name) === -1)) {
  2122. result = this.refModel.createJSONSample(modelsToIgnore);
  2123. } else {
  2124. if (this.isCollection) {
  2125. result = this.toSampleValue(this.refDataType);
  2126. } else {
  2127. result = this.toSampleValue(this.dataType);
  2128. }
  2129. }
  2130. if (this.isCollection) {
  2131. return [result];
  2132. } else {
  2133. return result;
  2134. }
  2135. };
  2136. SwaggerModelProperty.prototype.toSampleValue = function (value) {
  2137. var result;
  2138. if ((typeof this.defaultValue !== 'undefined') && this.defaultValue) {
  2139. result = this.defaultValue;
  2140. } else if (value === 'integer') {
  2141. result = 0;
  2142. } else if (value === 'boolean') {
  2143. result = false;
  2144. } else if (value === 'double' || value === 'number') {
  2145. result = 0.0;
  2146. } else if (value === 'string') {
  2147. result = '';
  2148. } else {
  2149. result = value;
  2150. }
  2151. return result;
  2152. };
  2153. SwaggerModelProperty.prototype.toString = function () {
  2154. var req = this.required ? 'propReq' : 'propOpt';
  2155. var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
  2156. if (!this.required) {
  2157. str += ', <span class="propOptKey">optional</span>';
  2158. }
  2159. str += ')';
  2160. if (this.values) {
  2161. str += ' = <span class="propVals">[\'' + this.values.join('\' or \'') + '\']</span>';
  2162. }
  2163. if (this.descr) {
  2164. str += ': <span class="propDesc">' + this.descr + '</span>';
  2165. }
  2166. return str;
  2167. };
  2168. var SwaggerOperation = function (nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations, deprecated) {
  2169. var _this = this;
  2170. var errors = [];
  2171. this.nickname = (nickname || errors.push('SwaggerOperations must have a nickname.'));
  2172. this.path = (path || errors.push('SwaggerOperation ' + nickname + ' is missing path.'));
  2173. this.method = (method || errors.push('SwaggerOperation ' + nickname + ' is missing method.'));
  2174. this.parameters = parameters ? parameters : [];
  2175. this.summary = summary;
  2176. this.notes = notes;
  2177. this.type = type;
  2178. this.responseMessages = (responseMessages || []);
  2179. this.resource = (resource || errors.push('Resource is required'));
  2180. this.consumes = consumes;
  2181. this.produces = produces;
  2182. this.authorizations = typeof authorizations !== 'undefined' ? authorizations : resource.authorizations;
  2183. this.deprecated = deprecated;
  2184. this['do'] = __bind(this['do'], this);
  2185. if(typeof this.deprecated === 'string') {
  2186. switch(this.deprecated.toLowerCase()) {
  2187. case 'true': case 'yes': case '1': {
  2188. this.deprecated = true;
  2189. break;
  2190. }
  2191. case 'false': case 'no': case '0': case null: {
  2192. this.deprecated = false;
  2193. break;
  2194. }
  2195. default: this.deprecated = Boolean(this.deprecated);
  2196. }
  2197. }
  2198. if (errors.length > 0) {
  2199. console.error('SwaggerOperation errors', errors, arguments);
  2200. this.resource.api.fail(errors);
  2201. }
  2202. this.path = this.path.replace('{format}', 'json');
  2203. this.method = this.method.toLowerCase();
  2204. this.isGetMethod = this.method === 'get';
  2205. var i, j, v;
  2206. this.resourceName = this.resource.name;
  2207. if (typeof this.type !== 'undefined' && this.type === 'void')
  2208. this.type = null;
  2209. else {
  2210. this.responseClassSignature = this.getSignature(this.type, this.resource.models);
  2211. this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
  2212. }
  2213. for (i = 0; i < this.parameters.length; i++) {
  2214. var param = this.parameters[i];
  2215. // might take this away
  2216. param.name = param.name || param.type || param.dataType;
  2217. // for 1.1 compatibility
  2218. type = param.type || param.dataType;
  2219. if (type === 'array') {
  2220. type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
  2221. }
  2222. param.type = type;
  2223. if (type && type.toLowerCase() === 'boolean') {
  2224. param.allowableValues = {};
  2225. param.allowableValues.values = ['true', 'false'];
  2226. }
  2227. param.signature = this.getSignature(type, this.resource.models);
  2228. param.sampleJSON = this.getSampleJSON(type, this.resource.models);
  2229. var enumValue = param['enum'];
  2230. if (typeof enumValue !== 'undefined') {
  2231. param.isList = true;
  2232. param.allowableValues = {};
  2233. param.allowableValues.descriptiveValues = [];
  2234. for (j = 0; j < enumValue.length; j++) {
  2235. v = enumValue[j];
  2236. if (param.defaultValue) {
  2237. param.allowableValues.descriptiveValues.push({
  2238. value: String(v),
  2239. isDefault: (v === param.defaultValue)
  2240. });
  2241. }
  2242. else {
  2243. param.allowableValues.descriptiveValues.push({
  2244. value: String(v),
  2245. isDefault: false
  2246. });
  2247. }
  2248. }
  2249. }
  2250. else if (param.allowableValues) {
  2251. if (param.allowableValues.valueType === 'RANGE')
  2252. param.isRange = true;
  2253. else
  2254. param.isList = true;
  2255. if (param.allowableValues) {
  2256. param.allowableValues.descriptiveValues = [];
  2257. if (param.allowableValues.values) {
  2258. for (j = 0; j < param.allowableValues.values.length; j++) {
  2259. v = param.allowableValues.values[j];
  2260. if (param.defaultValue !== null) {
  2261. param.allowableValues.descriptiveValues.push({
  2262. value: String(v),
  2263. isDefault: (v === param.defaultValue)
  2264. });
  2265. }
  2266. else {
  2267. param.allowableValues.descriptiveValues.push({
  2268. value: String(v),
  2269. isDefault: false
  2270. });
  2271. }
  2272. }
  2273. }
  2274. }
  2275. }
  2276. param.defaultValue = applyParameterMacro(this, param);
  2277. }
  2278. var defaultSuccessCallback = this.resource.api.defaultSuccessCallback || null;
  2279. var defaultErrorCallback = this.resource.api.defaultErrorCallback || null;
  2280. this.resource[this.nickname] = function (args, opts, callback, error) {
  2281. var arg1, arg2, arg3, arg4;
  2282. if(typeof args === 'function') { // right shift 3
  2283. arg1 = {}; arg2 = {}; arg3 = args; arg4 = opts;
  2284. }
  2285. else if(typeof args === 'object' && typeof opts === 'function') { // right shift 2
  2286. arg1 = args; arg2 = {}; arg3 = opts; arg4 = callback;
  2287. }
  2288. else {
  2289. arg1 = args; arg2 = opts; arg3 = callback; arg4 = error;
  2290. }
  2291. return _this['do'](arg1 || {}, arg2 || {}, arg3 || defaultSuccessCallback, arg4 || defaultErrorCallback);
  2292. };
  2293. this.resource[this.nickname].help = function (dontPrint) {
  2294. return _this.help(dontPrint);
  2295. };
  2296. this.resource[this.nickname].asCurl = function (args) {
  2297. return _this.asCurl(args);
  2298. };
  2299. };
  2300. SwaggerOperation.prototype.isListType = function (type) {
  2301. if (type && type.indexOf('[') >= 0) {
  2302. return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
  2303. } else {
  2304. return void 0;
  2305. }
  2306. };
  2307. SwaggerOperation.prototype.getSignature = function (type, models) {
  2308. var isPrimitive, listType;
  2309. listType = this.isListType(type);
  2310. isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
  2311. if (isPrimitive) {
  2312. return type;
  2313. } else {
  2314. if (typeof listType !== 'undefined') {
  2315. return models[listType].getMockSignature();
  2316. } else {
  2317. return models[type].getMockSignature();
  2318. }
  2319. }
  2320. };
  2321. SwaggerOperation.prototype.getSampleJSON = function (type, models) {
  2322. var isPrimitive, listType, val;
  2323. listType = this.isListType(type);
  2324. isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
  2325. val = isPrimitive ? void 0 : (listType ? models[listType].createJSONSample() : models[type].createJSONSample());
  2326. if (val) {
  2327. val = listType ? [val] : val;
  2328. if (typeof val == 'string')
  2329. return val;
  2330. else if (typeof val === 'object') {
  2331. var t = val;
  2332. if (val instanceof Array && val.length > 0) {
  2333. t = val[0];
  2334. }
  2335. if (t.nodeName) {
  2336. var xmlString = new XMLSerializer().serializeToString(t);
  2337. return this.formatXml(xmlString);
  2338. }
  2339. else
  2340. return JSON.stringify(val, null, 2);
  2341. }
  2342. else
  2343. return val;
  2344. }
  2345. };
  2346. SwaggerOperation.prototype['do'] = function (args, opts, callback, error) {
  2347. var key, param, params, possibleParams = [], req, value;
  2348. if (typeof error !== 'function') {
  2349. error = function (xhr, textStatus, error) {
  2350. return log(xhr, textStatus, error);
  2351. };
  2352. }
  2353. if (typeof callback !== 'function') {
  2354. callback = function (response) {
  2355. var content;
  2356. content = null;
  2357. if (response !== null) {
  2358. content = response.data;
  2359. } else {
  2360. content = 'no data';
  2361. }
  2362. return log('default callback: ' + content);
  2363. };
  2364. }
  2365. params = {};
  2366. params.headers = [];
  2367. if (args.headers) {
  2368. params.headers = args.headers;
  2369. delete args.headers;
  2370. }
  2371. // allow override from the opts
  2372. if(opts && opts.responseContentType) {
  2373. params.headers['Content-Type'] = opts.responseContentType;
  2374. }
  2375. if(opts && opts.requestContentType) {
  2376. params.headers.Accept = opts.requestContentType;
  2377. }
  2378. for (var i = 0; i < this.parameters.length; i++) {
  2379. param = this.parameters[i];
  2380. if (param.paramType === 'header') {
  2381. if (typeof args[param.name] !== 'undefined')
  2382. params.headers[param.name] = args[param.name];
  2383. }
  2384. else if (param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
  2385. possibleParams.push(param);
  2386. else if (param.paramType === 'body' && param.name !== 'body' && typeof args[param.name] !== 'undefined') {
  2387. if (args.body) {
  2388. throw new Error('Saw two body params in an API listing; expecting a max of one.');
  2389. }
  2390. args.body = args[param.name];
  2391. }
  2392. }
  2393. if (typeof args.body !== 'undefined') {
  2394. params.body = args.body;
  2395. delete args.body;
  2396. }
  2397. if (possibleParams) {
  2398. for (key in possibleParams) {
  2399. value = possibleParams[key];
  2400. if (args[value.name]) {
  2401. params[value.name] = args[value.name];
  2402. }
  2403. }
  2404. }
  2405. req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
  2406. if (opts.mock) {
  2407. return req;
  2408. } else {
  2409. return true;
  2410. }
  2411. };
  2412. SwaggerOperation.prototype.pathJson = function () {
  2413. return this.path.replace('{format}', 'json');
  2414. };
  2415. SwaggerOperation.prototype.pathXml = function () {
  2416. return this.path.replace('{format}', 'xml');
  2417. };
  2418. SwaggerOperation.prototype.encodePathParam = function (pathParam) {
  2419. var encParts, part, parts, _i, _len;
  2420. pathParam = pathParam.toString();
  2421. if (pathParam.indexOf('/') === -1) {
  2422. return encodeURIComponent(pathParam);
  2423. } else {
  2424. parts = pathParam.split('/');
  2425. encParts = [];
  2426. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  2427. part = parts[_i];
  2428. encParts.push(encodeURIComponent(part));
  2429. }
  2430. return encParts.join('/');
  2431. }
  2432. };
  2433. SwaggerOperation.prototype.urlify = function (args) {
  2434. var i, j, param, url;
  2435. // ensure no double slashing...
  2436. if(this.resource.basePath.length > 1 && this.resource.basePath.slice(-1) === '/' && this.pathJson().charAt(0) === '/')
  2437. url = this.resource.basePath + this.pathJson().substring(1);
  2438. else
  2439. url = this.resource.basePath + this.pathJson();
  2440. var params = this.parameters;
  2441. for (i = 0; i < params.length; i++) {
  2442. param = params[i];
  2443. if (param.paramType === 'path') {
  2444. if (typeof args[param.name] !== 'undefined') {
  2445. // apply path params and remove from args
  2446. var reg = new RegExp('\\{\\s*?' + param.name + '[^\\{\\}\\/]*(?:\\{.*?\\}[^\\{\\}\\/]*)*\\}(?=(\\/?|$))', 'gi');
  2447. url = url.replace(reg, this.encodePathParam(args[param.name]));
  2448. delete args[param.name];
  2449. }
  2450. else
  2451. throw '' + param.name + ' is a required path param.';
  2452. }
  2453. }
  2454. var queryParams = '';
  2455. for (i = 0; i < params.length; i++) {
  2456. param = params[i];
  2457. if(param.paramType === 'query') {
  2458. if (queryParams !== '')
  2459. queryParams += '&';
  2460. if (Array.isArray(param)) {
  2461. var output = '';
  2462. for(j = 0; j < param.length; j++) {
  2463. if(j > 0)
  2464. output += ',';
  2465. output += encodeURIComponent(param[j]);
  2466. }
  2467. queryParams += encodeURIComponent(param.name) + '=' + output;
  2468. }
  2469. else {
  2470. if (typeof args[param.name] !== 'undefined') {
  2471. queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
  2472. } else {
  2473. if (param.required)
  2474. throw '' + param.name + ' is a required query param.';
  2475. }
  2476. }
  2477. }
  2478. }
  2479. if ((queryParams) && queryParams.length > 0)
  2480. url += '?' + queryParams;
  2481. return url;
  2482. };
  2483. SwaggerOperation.prototype.supportHeaderParams = function () {
  2484. return this.resource.api.supportHeaderParams;
  2485. };
  2486. SwaggerOperation.prototype.supportedSubmitMethods = function () {
  2487. return this.resource.api.supportedSubmitMethods;
  2488. };
  2489. SwaggerOperation.prototype.getQueryParams = function (args) {
  2490. return this.getMatchingParams(['query'], args);
  2491. };
  2492. SwaggerOperation.prototype.getHeaderParams = function (args) {
  2493. return this.getMatchingParams(['header'], args);
  2494. };
  2495. SwaggerOperation.prototype.getMatchingParams = function (paramTypes, args) {
  2496. var matchingParams = {};
  2497. var params = this.parameters;
  2498. for (var i = 0; i < params.length; i++) {
  2499. param = params[i];
  2500. if (args && args[param.name])
  2501. matchingParams[param.name] = args[param.name];
  2502. }
  2503. var headers = this.resource.api.headers;
  2504. var name;
  2505. for (name in headers) {
  2506. var value = headers[name];
  2507. matchingParams[name] = value;
  2508. }
  2509. return matchingParams;
  2510. };
  2511. SwaggerOperation.prototype.help = function (dontPrint) {
  2512. var msg = this.nickname + ': ' + this.summary;
  2513. var params = this.parameters;
  2514. for (var i = 0; i < params.length; i++) {
  2515. var param = params[i];
  2516. msg += '\n* ' + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
  2517. }
  2518. if(dontPrint)
  2519. return msg;
  2520. else {
  2521. console.log(msg);
  2522. return msg;
  2523. }
  2524. };
  2525. SwaggerOperation.prototype.asCurl = function (args) {
  2526. var results = [];
  2527. var i;
  2528. var headers = SwaggerRequest.prototype.setHeaders(args, {}, this);
  2529. for(i = 0; i < this.parameters.length; i++) {
  2530. var param = this.parameters[i];
  2531. if(param.paramType && param.paramType === 'header' && args[param.name]) {
  2532. headers[param.name] = args[param.name];
  2533. }
  2534. }
  2535. var key;
  2536. for (key in headers) {
  2537. results.push('--header "' + key + ': ' + headers[key] + '"');
  2538. }
  2539. return 'curl ' + (results.join(' ')) + ' ' + this.urlify(args);
  2540. };
  2541. SwaggerOperation.prototype.formatXml = function (xml) {
  2542. var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
  2543. reg = /(>)(<)(\/*)/g;
  2544. wsexp = /[ ]*(.*)[ ]+\n/g;
  2545. contexp = /(<.+>)(.+\n)/g;
  2546. xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
  2547. pad = 0;
  2548. formatted = '';
  2549. lines = xml.split('\n');
  2550. indent = 0;
  2551. lastType = 'other';
  2552. transitions = {
  2553. 'single->single': 0,
  2554. 'single->closing': -1,
  2555. 'single->opening': 0,
  2556. 'single->other': 0,
  2557. 'closing->single': 0,
  2558. 'closing->closing': -1,
  2559. 'closing->opening': 0,
  2560. 'closing->other': 0,
  2561. 'opening->single': 1,
  2562. 'opening->closing': 0,
  2563. 'opening->opening': 1,
  2564. 'opening->other': 1,
  2565. 'other->single': 0,
  2566. 'other->closing': -1,
  2567. 'other->opening': 0,
  2568. 'other->other': 0
  2569. };
  2570. _fn = function (ln) {
  2571. var fromTo, j, key, padding, type, types, value;
  2572. types = {
  2573. single: Boolean(ln.match(/<.+\/>/)),
  2574. closing: Boolean(ln.match(/<\/.+>/)),
  2575. opening: Boolean(ln.match(/<[^!?].*>/))
  2576. };
  2577. type = ((function () {
  2578. var _results;
  2579. _results = [];
  2580. for (key in types) {
  2581. value = types[key];
  2582. if (value) {
  2583. _results.push(key);
  2584. }
  2585. }
  2586. return _results;
  2587. })())[0];
  2588. type = type === void 0 ? 'other' : type;
  2589. fromTo = lastType + '->' + type;
  2590. lastType = type;
  2591. padding = '';
  2592. indent += transitions[fromTo];
  2593. padding = ((function () {
  2594. var _j, _ref5, _results;
  2595. _results = [];
  2596. for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
  2597. _results.push(' ');
  2598. }
  2599. return _results;
  2600. })()).join('');
  2601. if (fromTo === 'opening->closing') {
  2602. formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
  2603. } else {
  2604. formatted += padding + ln + '\n';
  2605. }
  2606. };
  2607. for (_i = 0, _len = lines.length; _i < _len; _i++) {
  2608. ln = lines[_i];
  2609. _fn(ln);
  2610. }
  2611. return formatted;
  2612. };
  2613. var SwaggerRequest = function (type, url, params, opts, successCallback, errorCallback, operation, execution) {
  2614. var _this = this;
  2615. var errors = [];
  2616. this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
  2617. this.type = (type || errors.push('SwaggerRequest type is required (get/post/put/delete/patch/options).'));
  2618. this.url = (url || errors.push('SwaggerRequest url is required.'));
  2619. this.params = params;
  2620. this.opts = opts;
  2621. this.successCallback = (successCallback || errors.push('SwaggerRequest successCallback is required.'));
  2622. this.errorCallback = (errorCallback || errors.push('SwaggerRequest error callback is required.'));
  2623. this.operation = (operation || errors.push('SwaggerRequest operation is required.'));
  2624. this.execution = execution;
  2625. this.headers = (params.headers || {});
  2626. if (errors.length > 0) {
  2627. throw errors;
  2628. }
  2629. this.type = this.type.toUpperCase();
  2630. // set request, response content type headers
  2631. var headers = this.setHeaders(params, opts, this.operation);
  2632. var body = params.body;
  2633. // encode the body for form submits
  2634. if (headers['Content-Type']) {
  2635. var key, value, values = {}, i;
  2636. var operationParams = this.operation.parameters;
  2637. for (i = 0; i < operationParams.length; i++) {
  2638. var param = operationParams[i];
  2639. if (param.paramType === 'form')
  2640. values[param.name] = param;
  2641. }
  2642. if (headers['Content-Type'].indexOf('application/x-www-form-urlencoded') === 0) {
  2643. var encoded = '';
  2644. for (key in values) {
  2645. value = this.params[key];
  2646. if (typeof value !== 'undefined') {
  2647. if (encoded !== '')
  2648. encoded += '&';
  2649. encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  2650. }
  2651. }
  2652. body = encoded;
  2653. }
  2654. else if (headers['Content-Type'].indexOf('multipart/form-data') === 0) {
  2655. // encode the body for form submits
  2656. var data = '';
  2657. var boundary = '----SwaggerFormBoundary' + Date.now();
  2658. for (key in values) {
  2659. value = this.params[key];
  2660. if (typeof value !== 'undefined') {
  2661. data += '--' + boundary + '\n';
  2662. data += 'Content-Disposition: form-data; name="' + key + '"';
  2663. data += '\n\n';
  2664. data += value + '\n';
  2665. }
  2666. }
  2667. data += '--' + boundary + '--\n';
  2668. headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
  2669. body = data;
  2670. }
  2671. }
  2672. var obj;
  2673. if (!((this.headers) && (this.headers.mock))) {
  2674. obj = {
  2675. url: this.url,
  2676. method: this.type,
  2677. headers: headers,
  2678. body: body,
  2679. useJQuery: this.useJQuery,
  2680. on: {
  2681. error: function (response) {
  2682. return _this.errorCallback(response, _this.opts.parent);
  2683. },
  2684. redirect: function (response) {
  2685. return _this.successCallback(response, _this.opts.parent);
  2686. },
  2687. 307: function (response) {
  2688. return _this.successCallback(response, _this.opts.parent);
  2689. },
  2690. response: function (response) {
  2691. return _this.successCallback(response, _this.opts.parent);
  2692. }
  2693. }
  2694. };
  2695. var status = false;
  2696. if (this.operation.resource && this.operation.resource.api && this.operation.resource.api.clientAuthorizations) {
  2697. // Get the client authorizations from the resource declaration
  2698. status = this.operation.resource.api.clientAuthorizations.apply(obj, this.operation.authorizations);
  2699. } else {
  2700. // Get the client authorization from the default authorization declaration
  2701. var e;
  2702. if (typeof window !== 'undefined') {
  2703. e = window;
  2704. } else {
  2705. e = exports;
  2706. }
  2707. status = e.authorizations.apply(obj, this.operation.authorizations);
  2708. }
  2709. if (!opts.mock) {
  2710. if (status !== false) {
  2711. new SwaggerHttp().execute(obj);
  2712. } else {
  2713. obj.canceled = true;
  2714. }
  2715. } else {
  2716. return obj;
  2717. }
  2718. }
  2719. return obj;
  2720. };
  2721. SwaggerRequest.prototype.setHeaders = function (params, opts, operation) {
  2722. // default type
  2723. var accepts = opts.responseContentType || 'application/json';
  2724. var consumes = opts.requestContentType || 'application/json';
  2725. var allDefinedParams = operation.parameters;
  2726. var definedFormParams = [];
  2727. var definedFileParams = [];
  2728. var body = params.body;
  2729. var headers = {};
  2730. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  2731. var i;
  2732. for (i = 0; i < allDefinedParams.length; i++) {
  2733. var param = allDefinedParams[i];
  2734. if (param.paramType === 'form')
  2735. definedFormParams.push(param);
  2736. else if (param.paramType === 'file')
  2737. definedFileParams.push(param);
  2738. else if (param.paramType === 'header' && this.params.headers) {
  2739. var key = param.name;
  2740. var headerValue = this.params.headers[param.name];
  2741. if (typeof this.params.headers[param.name] !== 'undefined')
  2742. headers[key] = headerValue;
  2743. }
  2744. }
  2745. // if there's a body, need to set the accepts header via requestContentType
  2746. if (body && (this.type === 'POST' || this.type === 'PUT' || this.type === 'PATCH' || this.type === 'DELETE')) {
  2747. if (this.opts.requestContentType)
  2748. consumes = this.opts.requestContentType;
  2749. } else {
  2750. // if any form params, content type must be set
  2751. if (definedFormParams.length > 0) {
  2752. if (definedFileParams.length > 0)
  2753. consumes = 'multipart/form-data';
  2754. else
  2755. consumes = 'application/x-www-form-urlencoded';
  2756. }
  2757. else if (this.type === 'DELETE')
  2758. body = '{}';
  2759. else if (this.type != 'DELETE')
  2760. consumes = null;
  2761. }
  2762. if (consumes && this.operation.consumes) {
  2763. if (this.operation.consumes.indexOf(consumes) === -1) {
  2764. log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.operation.consumes));
  2765. }
  2766. }
  2767. if (this.opts && this.opts.responseContentType) {
  2768. accepts = this.opts.responseContentType;
  2769. } else {
  2770. accepts = 'application/json';
  2771. }
  2772. if (accepts && operation.produces) {
  2773. if (operation.produces.indexOf(accepts) === -1) {
  2774. log('server can\'t produce ' + accepts);
  2775. }
  2776. }
  2777. if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
  2778. headers['Content-Type'] = consumes;
  2779. if (accepts)
  2780. headers.Accept = accepts;
  2781. return headers;
  2782. };
  2783. /**
  2784. * SwaggerHttp is a wrapper for executing requests
  2785. */
  2786. var SwaggerHttp = function() {};
  2787. SwaggerHttp.prototype.execute = function(obj, opts) {
  2788. if(obj && (typeof obj.useJQuery === 'boolean'))
  2789. this.useJQuery = obj.useJQuery;
  2790. else
  2791. this.useJQuery = this.isIE8();
  2792. if(obj && typeof obj.body === 'object') {
  2793. if(obj.body.type && obj.body.type !== 'formData')
  2794. obj.body = JSON.stringify(obj.body);
  2795. else {
  2796. obj.contentType = false;
  2797. obj.processData = false;
  2798. delete obj.headers['Content-Type'];
  2799. }
  2800. }
  2801. if(this.useJQuery)
  2802. return new JQueryHttpClient(opts).execute(obj);
  2803. else
  2804. return new ShredHttpClient(opts).execute(obj);
  2805. };
  2806. SwaggerHttp.prototype.isIE8 = function() {
  2807. var detectedIE = false;
  2808. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  2809. nav = navigator.userAgent.toLowerCase();
  2810. if (nav.indexOf('msie') !== -1) {
  2811. var version = parseInt(nav.split('msie')[1]);
  2812. if (version <= 8) {
  2813. detectedIE = true;
  2814. }
  2815. }
  2816. }
  2817. return detectedIE;
  2818. };
  2819. /*
  2820. * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
  2821. * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
  2822. * Since we are using closures here we need to alias it for internal use.
  2823. */
  2824. var JQueryHttpClient = function(options) {
  2825. "use strict";
  2826. if(!jQuery){
  2827. var jQuery = window.jQuery;
  2828. }
  2829. };
  2830. JQueryHttpClient.prototype.execute = function(obj) {
  2831. var cb = obj.on;
  2832. var request = obj;
  2833. obj.type = obj.method;
  2834. obj.cache = false;
  2835. delete obj.useJQuery;
  2836. /*
  2837. obj.beforeSend = function(xhr) {
  2838. var key, results;
  2839. if (obj.headers) {
  2840. results = [];
  2841. for (key in obj.headers) {
  2842. if (key.toLowerCase() === "content-type") {
  2843. results.push(obj.contentType = obj.headers[key]);
  2844. } else if (key.toLowerCase() === "accept") {
  2845. results.push(obj.accepts = obj.headers[key]);
  2846. } else {
  2847. results.push(xhr.setRequestHeader(key, obj.headers[key]));
  2848. }
  2849. }
  2850. return results;
  2851. }
  2852. };*/
  2853. obj.data = obj.body;
  2854. delete obj.body;
  2855. obj.complete = function(response, textStatus, opts) {
  2856. var headers = {},
  2857. headerArray = response.getAllResponseHeaders().split("\n");
  2858. for(var i = 0; i < headerArray.length; i++) {
  2859. var toSplit = headerArray[i].trim();
  2860. if(toSplit.length === 0)
  2861. continue;
  2862. var separator = toSplit.indexOf(":");
  2863. if(separator === -1) {
  2864. // Name but no value in the header
  2865. headers[toSplit] = null;
  2866. continue;
  2867. }
  2868. var name = toSplit.substring(0, separator).trim(),
  2869. value = toSplit.substring(separator + 1).trim();
  2870. headers[name] = value;
  2871. }
  2872. var out = {
  2873. url: request.url,
  2874. method: request.method,
  2875. status: response.status,
  2876. statusText: response.statusText,
  2877. data: response.responseText,
  2878. headers: headers
  2879. };
  2880. var contentType = (headers["content-type"]||headers["Content-Type"]||null);
  2881. if(contentType) {
  2882. if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
  2883. try {
  2884. out.obj = response.responseJSON || JSON.parse(out.data) || {};
  2885. } catch (ex) {
  2886. // do not set out.obj
  2887. log("unable to parse JSON content");
  2888. }
  2889. }
  2890. }
  2891. if(response.status >= 200 && response.status < 300)
  2892. cb.response(out);
  2893. else if(response.status === 0 || (response.status >= 400 && response.status < 599))
  2894. cb.error(out);
  2895. else
  2896. return cb.response(out);
  2897. };
  2898. jQuery.support.cors = true;
  2899. return jQuery.ajax(obj);
  2900. };
  2901. /*
  2902. * ShredHttpClient is a light-weight, node or browser HTTP client
  2903. */
  2904. var ShredHttpClient = function(opts) {
  2905. this.opts = (opts||{});
  2906. this.isInitialized = false;
  2907. var identity, toString;
  2908. if (typeof window !== 'undefined') {
  2909. this.Shred = require("./shred");
  2910. this.content = require("./shred/content");
  2911. }
  2912. else
  2913. this.Shred = require("shred");
  2914. this.shred = new this.Shred(opts);
  2915. };
  2916. ShredHttpClient.prototype.initShred = function () {
  2917. this.isInitialized = true;
  2918. this.registerProcessors(this.shred);
  2919. };
  2920. ShredHttpClient.prototype.registerProcessors = function(shred) {
  2921. var identity = function(x) {
  2922. return x;
  2923. };
  2924. var toString = function(x) {
  2925. return x.toString();
  2926. };
  2927. if (typeof window !== 'undefined') {
  2928. this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  2929. parser: identity,
  2930. stringify: toString
  2931. });
  2932. } else {
  2933. this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  2934. parser: identity,
  2935. stringify: toString
  2936. });
  2937. }
  2938. };
  2939. ShredHttpClient.prototype.execute = function(obj) {
  2940. if(!this.isInitialized)
  2941. this.initShred();
  2942. var cb = obj.on, res;
  2943. var transform = function(response) {
  2944. var out = {
  2945. headers: response._headers,
  2946. url: response.request.url,
  2947. method: response.request.method,
  2948. status: response.status,
  2949. data: response.content.data
  2950. };
  2951. var headers = response._headers.normalized || response._headers;
  2952. var contentType = (headers["content-type"]||headers["Content-Type"]||null);
  2953. if(contentType) {
  2954. if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
  2955. if(response.content.data && response.content.data !== "")
  2956. try{
  2957. out.obj = JSON.parse(response.content.data);
  2958. }
  2959. catch (e) {
  2960. // unable to parse
  2961. }
  2962. else
  2963. out.obj = {};
  2964. }
  2965. }
  2966. return out;
  2967. };
  2968. // Transform an error into a usable response-like object
  2969. var transformError = function (error) {
  2970. var out = {
  2971. // Default to a status of 0 - The client will treat this as a generic permissions sort of error
  2972. status: 0,
  2973. data: error.message || error
  2974. };
  2975. if (error.code) {
  2976. out.obj = error;
  2977. if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
  2978. // We can tell the client that this should be treated as a missing resource and not as a permissions thing
  2979. out.status = 404;
  2980. }
  2981. }
  2982. return out;
  2983. };
  2984. res = {
  2985. error: function (response) {
  2986. if (obj)
  2987. return cb.error(transform(response));
  2988. },
  2989. // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming)
  2990. request_error: function (err) {
  2991. if (obj)
  2992. return cb.error(transformError(err));
  2993. },
  2994. response: function (response) {
  2995. if (obj) {
  2996. return cb.response(transform(response));
  2997. }
  2998. }
  2999. };
  3000. if (obj) {
  3001. obj.on = res;
  3002. }
  3003. return this.shred.request(obj);
  3004. };
  3005. var e = (typeof window !== 'undefined' ? window : exports);
  3006. e.authorizations = authorizations = new SwaggerAuthorizations();
  3007. e.ApiKeyAuthorization = ApiKeyAuthorization;
  3008. e.PasswordAuthorization = PasswordAuthorization;
  3009. e.CookieAuthorization = CookieAuthorization;
  3010. e.SwaggerClient = SwaggerClient;
  3011. e.SwaggerApi = SwaggerClient;
  3012. e.Operation = Operation;
  3013. e.Model = Model;
  3014. e.addModel = addModel;
  3015. e.Resolver = Resolver;
  3016. })();