fuel: Enable concurrency for fuel-deploy job
[releng.git] / utils / test / result_collection_api / opnfv_testapi / tornado_swagger_ui / tornado_swagger / static / lib / swagger.js
1 // swagger.js
2 // version 2.0.27
3
4 var __bind = function(fn, me){
5   return function(){
6     return fn.apply(me, arguments);
7   };
8 };
9
10 log = function(){
11   log.history = log.history || [];
12   log.history.push(arguments);
13   if(this.console){
14     console.log( Array.prototype.slice.call(arguments) );
15   }
16 };
17
18 if (!Array.prototype.indexOf) {
19   Array.prototype.indexOf = function(obj, start) {
20     for (var i = (start || 0), j = this.length; i < j; i++) {
21       if (this[i] === obj) { return i; }
22     }
23     return -1;
24   }
25 }
26
27 if (!('filter' in Array.prototype)) {
28     Array.prototype.filter= function(filter, that /*opt*/) {
29         var other= [], v;
30         for (var i=0, n= this.length; i<n; i++)
31             if (i in this && filter.call(that, v= this[i], i, this))
32                 other.push(v);
33         return other;
34     };
35 }
36
37 if (!('map' in Array.prototype)) {
38   Array.prototype.map= function(mapper, that /*opt*/) {
39     var other= new Array(this.length);
40     for (var i= 0, n= this.length; i<n; i++)
41       if (i in this)
42         other[i]= mapper.call(that, this[i], i, this);
43     return other;
44   };
45 }
46
47 Object.keys = Object.keys || (function () {
48     var hasOwnProperty = Object.prototype.hasOwnProperty,
49         hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
50         DontEnums = [
51             'toString',
52             'toLocaleString',
53             'valueOf',
54             'hasOwnProperty',
55             'isPrototypeOf',
56             'propertyIsEnumerable',
57             'constructor'
58         ],
59         DontEnumsLength = DontEnums.length;
60   
61     return function (o) {
62         if (typeof o != "object" && typeof o != "function" || o === null)
63             throw new TypeError("Object.keys called on a non-object");
64      
65         var result = [];
66         for (var name in o) {
67             if (hasOwnProperty.call(o, name))
68                 result.push(name);
69         }
70      
71         if (hasDontEnumBug) {
72             for (var i = 0; i < DontEnumsLength; i++) {
73                 if (hasOwnProperty.call(o, DontEnums[i]))
74                     result.push(DontEnums[i]);
75             }   
76         }
77      
78         return result;
79     };
80 })();
81
82
83 var SwaggerApi = function(url, options) {
84   this.url = null;
85   this.debug = false;
86   this.basePath = null;
87   this.authorizations = null;
88   this.authorizationScheme = null;
89   this.info = null;
90
91   options = (options||{});
92   if (url)
93     if (url.url)
94       options = url;
95     else
96       this.url = url;
97   else
98     options = url;
99
100   if (options.url != null)
101     this.url = options.url;
102
103   if (options.success != null)
104     this.success = options.success;
105
106   this.failure = options.failure != null ? options.failure : function() {};
107   this.progress = options.progress != null ? options.progress : function() {};
108   if (options.success != null)
109     this.build();
110 }
111
112 SwaggerApi.prototype.build = function() {
113   var _this = this;
114   this.progress('fetching resource list: ' + this.url);
115   var obj = {
116     useJQuery: this.useJQuery,
117     url: this.url,
118     method: "get",
119     headers: {
120       accept: "application/json"
121     },
122     on: {
123       error: function(response) {
124         if (_this.url.substring(0, 4) !== 'http') {
125           return _this.fail('Please specify the protocol for ' + _this.url);
126         } else if (response.status === 0) {
127           return _this.fail('Can\'t read from server.  It may not have the appropriate access-control-origin settings.');
128         } else if (response.status === 404) {
129           return _this.fail('Can\'t read swagger JSON from ' + _this.url);
130         } else {
131           return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url);
132         }
133       },
134       response: function(resp) {
135         var responseObj = resp.obj || JSON.parse(resp.data);
136         _this.swaggerVersion = responseObj.swaggerVersion;
137         if (_this.swaggerVersion === "1.2") {
138           return _this.buildFromSpec(responseObj);
139         } else {
140           return _this.buildFrom1_1Spec(responseObj);
141         }
142       }
143     }
144   };
145   var e = (typeof window !== 'undefined' ? window : exports);
146   e.authorizations.apply(obj);
147   new SwaggerHttp().execute(obj);
148   return this;
149 };
150
151 SwaggerApi.prototype.buildFromSpec = function(response) {
152   if (response.apiVersion != null) {
153     this.apiVersion = response.apiVersion;
154   }
155   this.apis = {};
156   this.apisArray = [];
157   this.produces = response.produces;
158   this.authSchemes = response.authorizations;
159   if (response.info != null) {
160     this.info = response.info;
161   }
162   var isApi = false;
163   var i;
164   for (i = 0; i < response.apis.length; i++) {
165     var api = response.apis[i];
166     if (api.operations) {
167       var j;
168       for (j = 0; j < api.operations.length; j++) {
169         operation = api.operations[j];
170         isApi = true;
171       }
172     }
173   }
174   if (response.basePath) {
175     this.basePath = response.basePath;
176   } else if (this.url.indexOf('?') > 0) {
177     this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
178   } else {
179     this.basePath = this.url;
180   }
181   if (isApi) {
182     var newName = response.resourcePath.replace(/\//g, '');
183     this.resourcePath = response.resourcePath;
184     res = new SwaggerResource(response, this);
185     this.apis[newName] = res;
186     this.apisArray.push(res);
187   } else {
188     var k;
189     for (k = 0; k < response.apis.length; k++) {
190       var resource = response.apis[k];
191       res = new SwaggerResource(resource, this);
192       this.apis[res.name] = res;
193       this.apisArray.push(res);
194     }
195   }
196   if (this.success) {
197     this.success();
198   }
199   return this;
200 };
201
202 SwaggerApi.prototype.buildFrom1_1Spec = function(response) {
203   log("This API is using a deprecated version of Swagger!  Please see http://github.com/wordnik/swagger-core/wiki for more info");
204   if (response.apiVersion != null)
205     this.apiVersion = response.apiVersion;
206   this.apis = {};
207   this.apisArray = [];
208   this.produces = response.produces;
209   if (response.info != null) {
210     this.info = response.info;
211   }
212   var isApi = false;
213   for (var i = 0; i < response.apis.length; i++) {
214     var api = response.apis[i];
215     if (api.operations) {
216       for (var j = 0; j < api.operations.length; j++) {
217         operation = api.operations[j];
218         isApi = true;
219       }
220     }
221   }
222   if (response.basePath) {
223     this.basePath = response.basePath;
224   } else if (this.url.indexOf('?') > 0) {
225     this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
226   } else {
227     this.basePath = this.url;
228   }
229   if (isApi) {
230     var newName = response.resourcePath.replace(/\//g, '');
231     this.resourcePath = response.resourcePath;
232     var res = new SwaggerResource(response, this);
233     this.apis[newName] = res;
234     this.apisArray.push(res);
235   } else {
236     for (k = 0; k < response.apis.length; k++) {
237       resource = response.apis[k];
238       res = new SwaggerResource(resource, this);
239       this.apis[res.name] = res;
240       this.apisArray.push(res);
241     }
242   }
243   if (this.success) {
244     this.success();
245   }
246   return this;
247 };
248
249 SwaggerApi.prototype.selfReflect = function() {
250   var resource, resource_name, _ref;
251   if (this.apis == null) {
252     return false;
253   }
254   _ref = this.apis;
255   for (resource_name in _ref) {
256     resource = _ref[resource_name];
257     if (resource.ready == null) {
258       return false;
259     }
260   }
261   this.setConsolidatedModels();
262   this.ready = true;
263   if (this.success != null) {
264     return this.success();
265   }
266 };
267
268 SwaggerApi.prototype.fail = function(message) {
269   this.failure(message);
270   throw message;
271 };
272
273 SwaggerApi.prototype.setConsolidatedModels = function() {
274   var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results;
275   this.modelsArray = [];
276   this.models = {};
277   _ref = this.apis;
278   for (resource_name in _ref) {
279     resource = _ref[resource_name];
280     for (modelName in resource.models) {
281       if (this.models[modelName] == null) {
282         this.models[modelName] = resource.models[modelName];
283         this.modelsArray.push(resource.models[modelName]);
284       }
285     }
286   }
287   _ref1 = this.modelsArray;
288   _results = [];
289   for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
290     model = _ref1[_i];
291     _results.push(model.setReferencedModels(this.models));
292   }
293   return _results;
294 };
295
296 SwaggerApi.prototype.help = function() {
297   var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2;
298   _ref = this.apis;
299   for (resource_name in _ref) {
300     resource = _ref[resource_name];
301     log(resource_name);
302     _ref1 = resource.operations;
303     for (operation_name in _ref1) {
304       operation = _ref1[operation_name];
305       log("  " + operation.nickname);
306       _ref2 = operation.parameters;
307       for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
308         parameter = _ref2[_i];
309         log("    " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
310       }
311     }
312   }
313   return this;
314 };
315
316 var SwaggerResource = function(resourceObj, api) {
317   var _this = this;
318   this.api = api;
319   this.api = this.api;
320   produces = [];
321   consumes = [];
322   this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path;
323   this.description = resourceObj.description;
324
325   var parts = this.path.split("/");
326   this.name = parts[parts.length - 1].replace('.{format}', '');
327   this.basePath = this.api.basePath;
328   this.operations = {};
329   this.operationsArray = [];
330   this.modelsArray = [];
331   this.models = {};
332   this.rawModels = {};
333   this.useJQuery = (typeof api.useJQuery !== 'undefined' ? api.useJQuery : null);
334
335   if ((resourceObj.apis != null) && (this.api.resourcePath != null)) {
336     this.addApiDeclaration(resourceObj);
337   } else {
338     if (this.path == null) {
339       this.api.fail("SwaggerResources must have a path.");
340     }
341     if (this.path.substring(0, 4) === 'http') {
342       this.url = this.path.replace('{format}', 'json');
343     } else {
344       this.url = this.api.basePath + this.path.replace('{format}', 'json');
345     }
346     this.api.progress('fetching resource ' + this.name + ': ' + this.url);
347     obj = {
348       url: this.url,
349       method: "get",
350       useJQuery: this.useJQuery,
351       headers: {
352         accept: "application/json"
353       },
354       on: {
355         response: function(resp) {
356           var responseObj = resp.obj || JSON.parse(resp.data);
357           return _this.addApiDeclaration(responseObj);
358         },
359         error: function(response) {
360           return _this.api.fail("Unable to read api '" +
361             _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")");
362         }
363       }
364     };
365     var e = typeof window !== 'undefined' ? window : exports;
366     e.authorizations.apply(obj);
367     new SwaggerHttp().execute(obj);
368   }
369 }
370
371 SwaggerResource.prototype.getAbsoluteBasePath = function(relativeBasePath) {
372   var parts, pos, url;
373   url = this.api.basePath;
374   pos = url.lastIndexOf(relativeBasePath);
375   if (pos === -1) {
376     parts = url.split("/");
377     url = parts[0] + "//" + parts[2];
378     if (relativeBasePath.indexOf("/") === 0) {
379       return url + relativeBasePath;
380     } else {
381       return url + "/" + relativeBasePath;
382     }
383   } else if (relativeBasePath === "/") {
384     return url.substring(0, pos);
385   } else {
386     return url.substring(0, pos) + relativeBasePath;
387   }
388 };
389
390 SwaggerResource.prototype.addApiDeclaration = function(response) {
391   if (response.produces != null)
392     this.produces = response.produces;
393   if (response.consumes != null)
394     this.consumes = response.consumes;
395   if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0)
396     this.basePath = response.basePath.indexOf("http") === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
397
398   this.addModels(response.models);
399   if (response.apis) {
400     for (var i = 0 ; i < response.apis.length; i++) {
401       var endpoint = response.apis[i];
402       this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
403     }
404   }
405   this.api[this.name] = this;
406   this.ready = true;
407   return this.api.selfReflect();
408 };
409
410 SwaggerResource.prototype.addModels = function(models) {
411   if (models != null) {
412     var modelName;
413     for (modelName in models) {
414       if (this.models[modelName] == null) {
415         var swaggerModel = new SwaggerModel(modelName, models[modelName]);
416         this.modelsArray.push(swaggerModel);
417         this.models[modelName] = swaggerModel;
418         this.rawModels[modelName] = models[modelName];
419       }
420     }
421     var output = [];
422     for (var i = 0; i < this.modelsArray.length; i++) {
423       model = this.modelsArray[i];
424       output.push(model.setReferencedModels(this.models));
425     }
426     return output;
427   }
428 };
429
430 SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, produces) {
431   if (ops) {
432     output = [];
433     for (var i = 0; i < ops.length; i++) {
434       o = ops[i];
435       consumes = this.consumes;
436       produces = this.produces;
437       if (o.consumes != null)
438         consumes = o.consumes;
439       else
440         consumes = this.consumes;
441
442       if (o.produces != null)
443         produces = o.produces;
444       else
445         produces = this.produces;
446       type = (o.type||o.responseClass);
447
448       if (type === "array") {
449         ref = null;
450         if (o.items)
451           ref = o.items["type"] || o.items["$ref"];
452         type = "array[" + ref + "]";
453       }
454       responseMessages = o.responseMessages;
455       method = o.method;
456       if (o.httpMethod) {
457         method = o.httpMethod;
458       }
459       if (o.supportedContentTypes) {
460         consumes = o.supportedContentTypes;
461       }
462       if (o.errorResponses) {
463         responseMessages = o.errorResponses;
464         for (var j = 0; j < responseMessages.length; j++) {
465           r = responseMessages[j];
466           r.message = r.reason;
467           r.reason = null;
468         }
469       }
470       o.nickname = this.sanitize(o.nickname);
471       op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations);
472       this.operations[op.nickname] = op;
473       output.push(this.operationsArray.push(op));
474     }
475     return output;
476   }
477 };
478
479 SwaggerResource.prototype.sanitize = function(nickname) {
480   var op;
481   op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]/g, '_');
482   //'
483   op = op.replace(/((_){2,})/g, '_');
484   op = op.replace(/^(_)*/g, '');
485   op = op.replace(/([_])*$/g, '');
486   return op;
487 };
488
489 SwaggerResource.prototype.help = function() {
490   var op = this.operations;
491   var output = [];
492   var operation_name;
493   for (operation_name in op) {
494     operation = op[operation_name];
495     var msg = "  " + operation.nickname;
496     for (var i = 0; i < operation.parameters; i++) {
497       parameter = operation.parameters[i];
498       msg.concat("    " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
499     }
500     output.push(msg);
501   }
502   return output;
503 };
504
505 var SwaggerModel = function(modelName, obj) {
506   this.name = obj.id != null ? obj.id : modelName;
507   this.properties = [];
508   var propertyName;
509   for (propertyName in obj.properties) {
510     if (obj.required != null) {
511       var value;
512       for (value in obj.required) {
513         if (propertyName === obj.required[value]) {
514           obj.properties[propertyName].required = true;
515         }
516       }
517     }
518     prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]);
519     this.properties.push(prop);
520   }
521 }
522
523 SwaggerModel.prototype.setReferencedModels = function(allModels) {
524   var results = [];
525   for (var i = 0; i < this.properties.length; i++) {
526     var property = this.properties[i];
527     var type = property.type || property.dataType;
528     if (allModels[type] != null)
529       results.push(property.refModel = allModels[type]);
530     else if ((property.refDataType != null) && (allModels[property.refDataType] != null))
531       results.push(property.refModel = allModels[property.refDataType]);
532     else
533       results.push(void 0);
534   }
535   return results;
536 };
537
538 SwaggerModel.prototype.getMockSignature = function(modelsToIgnore) {
539   var propertiesStr = [];
540   for (var i = 0; i < this.properties.length; i++) {
541     prop = this.properties[i];
542     propertiesStr.push(prop.toString());
543   }
544
545   var strong = '<span class="strong">';
546   var stronger = '<span class="stronger">';
547   var strongClose = '</span>';
548   var classOpen = strong + this.name + ' {' + strongClose;
549   var classClose = strong + '}' + strongClose;
550   var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
551   if (!modelsToIgnore)
552     modelsToIgnore = [];
553   modelsToIgnore.push(this.name);
554
555   for (var i = 0; i < this.properties.length; i++) {
556     prop = this.properties[i];
557     if ((prop.refModel != null) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
558       returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
559     }
560   }
561   return returnVal;
562 };
563
564 SwaggerModel.prototype.createJSONSample = function(modelsToIgnore) {
565   var result = {};
566   var modelsToIgnore = (modelsToIgnore||[])
567   modelsToIgnore.push(this.name);
568   for (var i = 0; i < this.properties.length; i++) {
569     prop = this.properties[i];
570     result[prop.name] = prop.getSampleValue(modelsToIgnore);
571   }
572   modelsToIgnore.pop(this.name);
573   return result;
574 };
575
576 var SwaggerModelProperty = function(name, obj) {
577   this.name = name;
578   this.dataType = obj.type || obj.dataType || obj["$ref"];
579   this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
580   this.descr = obj.description;
581   this.required = obj.required;
582   if (obj.items != null) {
583     if (obj.items.type != null) {
584       this.refDataType = obj.items.type;
585     }
586     if (obj.items.$ref != null) {
587       this.refDataType = obj.items.$ref;
588     }
589   }
590   this.dataTypeWithRef = this.refDataType != null ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
591   if (obj.allowableValues != null) {
592     this.valueType = obj.allowableValues.valueType;
593     this.values = obj.allowableValues.values;
594     if (this.values != null) {
595       this.valuesString = "'" + this.values.join("' or '") + "'";
596     }
597   }
598   if (obj["enum"] != null) {
599     this.valueType = "string";
600     this.values = obj["enum"];
601     if (this.values != null) {
602       this.valueString = "'" + this.values.join("' or '") + "'";
603     }
604   }
605 }
606
607 SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) {
608   var result;
609   if ((this.refModel != null) && (modelsToIgnore.indexOf(prop.refModel.name) === -1)) {
610     result = this.refModel.createJSONSample(modelsToIgnore);
611   } else {
612     if (this.isCollection) {
613       result = this.toSampleValue(this.refDataType);
614     } else {
615       result = this.toSampleValue(this.dataType);
616     }
617   }
618   if (this.isCollection) {
619     return [result];
620   } else {
621     return result;
622   }
623 };
624
625 SwaggerModelProperty.prototype.toSampleValue = function(value) {
626   var result;
627   if (value === "integer") {
628     result = 0;
629   } else if (value === "boolean") {
630     result = false;
631   } else if (value === "double" || value === "number") {
632     result = 0.0;
633   } else if (value === "string") {
634     result = "";
635   } else {
636     result = value;
637   }
638   return result;
639 };
640
641 SwaggerModelProperty.prototype.toString = function() {
642   var req = this.required ? 'propReq' : 'propOpt';
643   var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
644   if (!this.required) {
645     str += ', <span class="propOptKey">optional</span>';
646   }
647   str += ')';
648   if (this.values != null) {
649     str += " = <span class='propVals'>['" + this.values.join("' or '") + "']</span>";
650   }
651   if (this.descr != null) {
652     str += ': <span class="propDesc">' + this.descr + '</span>';
653   }
654   return str;
655 };
656
657 var SwaggerOperation = function(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) {
658   var _this = this;
659
660   var errors = [];
661   this.nickname = (nickname||errors.push("SwaggerOperations must have a nickname."));
662   this.path = (path||errors.push("SwaggerOperation " + nickname + " is missing path."));
663   this.method = (method||errors.push("SwaggerOperation " + nickname + " is missing method."));
664   this.parameters = parameters != null ? parameters : [];
665   this.summary = summary;
666   this.notes = notes;
667   this.type = type;
668   this.responseMessages = (responseMessages||[]);
669   this.resource = (resource||errors.push("Resource is required"));
670   this.consumes = consumes;
671   this.produces = produces;
672   this.authorizations = authorizations;
673   this["do"] = __bind(this["do"], this);
674
675   if (errors.length > 0)
676     this.resource.api.fail(errors);
677
678   this.path = this.path.replace('{format}', 'json');
679   this.method = this.method.toLowerCase();
680   this.isGetMethod = this.method === "get";
681
682   this.resourceName = this.resource.name;
683   if(typeof this.type !== 'undefined' && this.type === 'void')
684     this.type = null;
685   else {
686     this.responseClassSignature = this.getSignature(this.type, this.resource.models);
687     this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
688   }
689
690   for(var i = 0; i < this.parameters.length; i ++) {
691     var param = this.parameters[i];
692     // might take this away
693     param.name = param.name || param.type || param.dataType;
694
695     // for 1.1 compatibility
696     var type = param.type || param.dataType;
697     if(type === 'array') {
698       type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
699     }
700     param.type = type;
701
702     if(type.toLowerCase() === 'boolean') {
703       param.allowableValues = {};
704       param.allowableValues.values = ["true", "false"];
705     }
706     param.signature = this.getSignature(type, this.resource.models);
707     param.sampleJSON = this.getSampleJSON(type, this.resource.models);
708
709     var enumValue = param["enum"];
710     if(enumValue != null) {
711       param.isList = true;
712       param.allowableValues = {};
713       param.allowableValues.descriptiveValues = [];
714
715       for(var j = 0; j < enumValue.length; j++) {
716         var v = enumValue[j];
717         if(param.defaultValue != null) {
718           param.allowableValues.descriptiveValues.push ({
719             value: String(v),
720             isDefault: (v === param.defaultValue)
721           });
722         }
723         else {
724           param.allowableValues.descriptiveValues.push ({
725             value: String(v),
726             isDefault: false
727           });
728         }
729       }
730     }
731     else if(param.allowableValues != null) {
732       if(param.allowableValues.valueType === "RANGE")
733         param.isRange = true;
734       else
735         param.isList = true;
736       if(param.allowableValues != null) {
737         param.allowableValues.descriptiveValues = [];
738         if(param.allowableValues.values) {
739           for(var j = 0; j < param.allowableValues.values.length; j++){
740             var v = param.allowableValues.values[j];
741             if(param.defaultValue != null) {
742               param.allowableValues.descriptiveValues.push ({
743                 value: String(v),
744                 isDefault: (v === param.defaultValue)
745               });
746             }
747             else {
748               param.allowableValues.descriptiveValues.push ({
749                 value: String(v),
750                 isDefault: false
751               });
752             }
753           }
754         }
755       }
756     }
757   }
758   this.resource[this.nickname] = function(args, callback, error) {
759     return _this["do"](args, callback, error);
760   };
761   this.resource[this.nickname].help = function() {
762     return _this.help();
763   };
764 }
765
766 SwaggerOperation.prototype.isListType = function(type) {
767   if (type && type.indexOf('[') >= 0) {
768     return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
769   } else {
770     return void 0;
771   }
772 };
773
774 SwaggerOperation.prototype.getSignature = function(type, models) {
775   var isPrimitive, listType;
776   listType = this.isListType(type);
777   isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
778   if (isPrimitive) {
779     return type;
780   } else {
781     if (listType != null) {
782       return models[listType].getMockSignature();
783     } else {
784       return models[type].getMockSignature();
785     }
786   }
787 };
788
789 SwaggerOperation.prototype.getSampleJSON = function(type, models) {
790   var isPrimitive, listType, val;
791   listType = this.isListType(type);
792   isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
793   val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample());
794   if (val) {
795     val = listType ? [val] : val;
796     return JSON.stringify(val, null, 2);
797   }
798 };
799
800 SwaggerOperation.prototype["do"] = function(args, opts, callback, error) {
801   var key, param, params, possibleParams, req, requestContentType, responseContentType, value, _i, _len, _ref;
802   if (args == null) {
803     args = {};
804   }
805   if (opts == null) {
806     opts = {};
807   }
808   requestContentType = null;
809   responseContentType = null;
810   if ((typeof args) === "function") {
811     error = opts;
812     callback = args;
813     args = {};
814   }
815   if ((typeof opts) === "function") {
816     error = callback;
817     callback = opts;
818   }
819   if (error == null) {
820     error = function(xhr, textStatus, error) {
821       return log(xhr, textStatus, error);
822     };
823   }
824   if (callback == null) {
825     callback = function(response) {
826       var content;
827       content = null;
828       if (response != null) {
829         content = response.data;
830       } else {
831         content = "no data";
832       }
833       return log("default callback: " + content);
834     };
835   }
836   params = {};
837   params.headers = [];
838   if (args.headers != null) {
839     params.headers = args.headers;
840     delete args.headers;
841   }
842
843   var possibleParams = [];
844   for(var i = 0; i < this.parameters.length; i++) {
845     var param = this.parameters[i];
846     if(param.paramType === 'header') {
847       if(args[param.name])
848         params.headers[param.name] = args[param.name];
849     }
850     else if(param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
851       possibleParams.push(param);
852   }
853
854   if (args.body != null) {
855     params.body = args.body;
856     delete args.body;
857   }
858
859   if (possibleParams) {
860     var key;
861     for (key in possibleParams) {
862       value = possibleParams[key];
863       if (args[value.name]) {
864         params[value.name] = args[value.name];
865       }
866     }
867   }
868
869   req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
870   if (opts.mock != null) {
871     return req;
872   } else {
873     return true;
874   }
875 };
876
877 SwaggerOperation.prototype.pathJson = function() {
878   return this.path.replace("{format}", "json");
879 };
880
881 SwaggerOperation.prototype.pathXml = function() {
882   return this.path.replace("{format}", "xml");
883 };
884
885 SwaggerOperation.prototype.encodePathParam = function(pathParam) {
886   var encParts, part, parts, _i, _len;
887   if (pathParam.indexOf("/") === -1) {
888     return encodeURIComponent(pathParam);
889   } else {
890     parts = pathParam.split("/");
891     encParts = [];
892     for (_i = 0, _len = parts.length; _i < _len; _i++) {
893       part = parts[_i];
894       encParts.push(encodeURIComponent(part));
895     }
896     return encParts.join("/");
897   }
898 };
899
900 SwaggerOperation.prototype.urlify = function(args) {
901   var url = this.resource.basePath + this.pathJson();
902   var params = this.parameters;
903   for(var i = 0; i < params.length; i ++){
904     var param = params[i];
905     if (param.paramType === 'path') {
906       if(args[param.name]) {
907         // apply path params and remove from args
908         var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
909         url = url.replace(reg, this.encodePathParam(args[param.name]));
910         delete args[param.name];
911       }
912       else
913         throw "" + param.name + " is a required path param.";
914     }
915   }
916
917   var queryParams = "";
918   for(var i = 0; i < params.length; i ++){
919     var param = params[i];
920     if(param.paramType === 'query') {
921       if (args[param.name] !== undefined) {
922         if (queryParams !== '')
923           queryParams += "&";
924         queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
925       }
926     }
927   }
928   if ((queryParams != null) && queryParams.length > 0)
929     url += '?' + queryParams;
930   return url;
931 };
932
933 SwaggerOperation.prototype.supportHeaderParams = function() {
934   return this.resource.api.supportHeaderParams;
935 };
936
937 SwaggerOperation.prototype.supportedSubmitMethods = function() {
938   return this.resource.api.supportedSubmitMethods;
939 };
940
941 SwaggerOperation.prototype.getQueryParams = function(args) {
942   return this.getMatchingParams(['query'], args);
943 };
944
945 SwaggerOperation.prototype.getHeaderParams = function(args) {
946   return this.getMatchingParams(['header'], args);
947 };
948
949 SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) {
950   var matchingParams = {};
951   var params = this.parameters;
952   for (var i = 0; i < params.length; i++) {
953     param = params[i];
954     if (args && args[param.name])
955       matchingParams[param.name] = args[param.name];
956   }
957   var headers = this.resource.api.headers;
958   var name;
959   for (name in headers) {
960     var value = headers[name];
961     matchingParams[name] = value;
962   }
963   return matchingParams;
964 };
965
966 SwaggerOperation.prototype.help = function() {
967   var msg = "";
968   var params = this.parameters;
969   for (var i = 0; i < params.length; i++) {
970     var param = params[i];
971     if (msg !== "")
972       msg += "\n";
973     msg += "* " + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
974   }
975   return msg;
976 };
977
978 var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) {
979   var _this = this;
980   var errors = [];
981   this.useJQuery = (typeof operation.useJQuery !== 'undefined' ? operation.useJQuery : null);
982   this.type = (type||errors.push("SwaggerRequest type is required (get/post/put/delete/patch/options)."));
983   this.url = (url||errors.push("SwaggerRequest url is required."));
984   this.params = params;
985   this.opts = opts;
986   this.successCallback = (successCallback||errors.push("SwaggerRequest successCallback is required."));
987   this.errorCallback = (errorCallback||errors.push("SwaggerRequest error callback is required."));
988   this.operation = (operation||errors.push("SwaggerRequest operation is required."));
989   this.execution = execution;
990   this.headers = (params.headers||{});
991
992   if(errors.length > 0) {
993     throw errors;
994   }
995
996   this.type = this.type.toUpperCase();
997
998   var myHeaders = {};
999   var body = params.body;
1000   var parent = params["parent"];
1001   var requestContentType = "application/json";
1002
1003   var formParams = [];
1004   var fileParams = [];
1005   var params = this.operation.parameters;
1006
1007
1008   for(var i = 0; i < params.length; i++) {
1009     var param = params[i];
1010     if(param.paramType === "form")
1011       formParams.push(param);
1012     else if(param.paramType === "file")
1013       fileParams.push(param);
1014   }
1015
1016
1017   if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH")) {
1018     if (this.opts.requestContentType) {
1019       requestContentType = this.opts.requestContentType;
1020     }
1021   } else {
1022     // if any form params, content type must be set
1023     if(formParams.length > 0) {
1024       if(fileParams.length > 0)
1025         requestContentType = "multipart/form-data";
1026       else
1027         requestContentType = "application/x-www-form-urlencoded";
1028     }
1029     else if (this.type != "DELETE")
1030       requestContentType = null;
1031   }
1032
1033   if (requestContentType && this.operation.consumes) {
1034     if (this.operation.consumes[requestContentType] === 'undefined') {
1035       log("server doesn't consume " + requestContentType + ", try " + JSON.stringify(this.operation.consumes));
1036       if (this.requestContentType === null) {
1037         requestContentType = this.operation.consumes[0];
1038       }
1039     }
1040   }
1041
1042   var responseContentType = null;
1043   if (this.opts.responseContentType) {
1044     responseContentType = this.opts.responseContentType;
1045   } else {
1046     responseContentType = "application/json";
1047   }
1048   if (responseContentType && this.operation.produces) {
1049     if (this.operation.produces[responseContentType] === 'undefined') {
1050       log("server can't produce " + responseContentType);
1051     }
1052   }
1053   if (requestContentType && requestContentType.indexOf("application/x-www-form-urlencoded") === 0) {
1054     var fields = {};
1055     var possibleParams = {};
1056     var values = {};
1057     var key;
1058     for(key in formParams){
1059       var param = formParams[key];
1060       values[param.name] = param;
1061     }
1062
1063     var encoded = "";
1064     var key;
1065     for(key in values) {
1066       value = this.params[key];
1067       if(typeof value !== 'undefined'){
1068         if(encoded !== "")
1069           encoded += "&";
1070         encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
1071       }
1072     }
1073     body = encoded;
1074   }
1075   var name;
1076   for (name in this.headers)
1077     myHeaders[name] = this.headers[name];
1078   if ((requestContentType && body !== "") || (requestContentType === "application/x-www-form-urlencoded"))
1079     myHeaders["Content-Type"] = requestContentType;
1080   if (responseContentType)
1081     myHeaders["Accept"] = responseContentType;
1082
1083   if (!((this.headers != null) && (this.headers.mock != null))) {
1084     obj = {
1085       url: this.url,
1086       method: this.type,
1087       headers: myHeaders,
1088       body: body,
1089       useJQuery: this.useJQuery,
1090       on: {
1091         error: function(response) {
1092           return _this.errorCallback(response, _this.opts.parent);
1093         },
1094         redirect: function(response) {
1095           return _this.successCallback(response, _this.opts.parent);
1096         },
1097         307: function(response) {
1098           return _this.successCallback(response, _this.opts.parent);
1099         },
1100         response: function(response) {
1101           return _this.successCallback(response, _this.opts.parent);
1102         }
1103       }
1104     };
1105     var e;
1106     if (typeof window !== 'undefined') {
1107       e = window;
1108     } else {
1109       e = exports;
1110     }
1111     status = e.authorizations.apply(obj, this.operation.authorizations);
1112     if (opts.mock == null) {
1113       if (status !== false) {
1114         new SwaggerHttp().execute(obj);
1115       } else {
1116         obj.canceled = true;
1117       }
1118     } else {
1119       return obj;
1120     }
1121   }
1122 };
1123
1124 SwaggerRequest.prototype.asCurl = function() {
1125   var results = [];
1126   if(this.headers) {
1127     var key;
1128     for(key in this.headers) {
1129       results.push("--header \"" + key + ": " + this.headers[v] + "\"");
1130     }
1131   }
1132   return "curl " + (results.join(" ")) + " " + this.url;
1133 };
1134
1135 /**
1136  * SwaggerHttp is a wrapper for executing requests
1137  */
1138 var SwaggerHttp = function() {};
1139
1140 SwaggerHttp.prototype.execute = function(obj) {
1141   if(obj && (typeof obj.useJQuery === 'boolean'))
1142     this.useJQuery = obj.useJQuery;
1143   else
1144     this.useJQuery = this.isIE8();
1145
1146   if(this.useJQuery)
1147     return new JQueryHttpClient().execute(obj);
1148   else
1149     return new ShredHttpClient().execute(obj);
1150 }
1151
1152 SwaggerHttp.prototype.isIE8 = function() {
1153   var detectedIE = false;
1154   if (typeof navigator !== 'undefined' && navigator.userAgent) {
1155     nav = navigator.userAgent.toLowerCase();
1156     if (nav.indexOf('msie') !== -1) {
1157       var version = parseInt(nav.split('msie')[1]);
1158       if (version <= 8) {
1159         detectedIE = true;
1160       }
1161     }
1162   }
1163   return detectedIE;
1164 };
1165
1166 /*
1167  * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic
1168  */
1169 var JQueryHttpClient = function(options) {}
1170
1171 JQueryHttpClient.prototype.execute = function(obj) {
1172   var cb = obj.on;
1173   var request = obj;
1174
1175   obj.type = obj.method;
1176   obj.cache = false;
1177
1178   obj.beforeSend = function(xhr) {
1179     var key, results;
1180     if (obj.headers) {
1181       results = [];
1182       var key;
1183       for (key in obj.headers) {
1184         if (key.toLowerCase() === "content-type") {
1185           results.push(obj.contentType = obj.headers[key]);
1186         } else if (key.toLowerCase() === "accept") {
1187           results.push(obj.accepts = obj.headers[key]);
1188         } else {
1189           results.push(xhr.setRequestHeader(key, obj.headers[key]));
1190         }
1191       }
1192       return results;
1193     }
1194   };
1195
1196   obj.data = obj.body;
1197   obj.complete = function(response, textStatus, opts) {
1198     headers = {};
1199     headerArray = response.getAllResponseHeaders().split(":");
1200
1201     for(var i = 0; i < headerArray.length / 2; i++)
1202       headers[headerArray[i] = headerArray[i+1]];
1203
1204     out = {
1205       headers: headers,
1206       url: request.url,
1207       method: request.method,
1208       status: response.status,
1209       data: response.responseText,
1210       headers: headers
1211     };
1212
1213     var contentType = (headers["content-type"]||headers["Content-Type"]||null)
1214
1215     if(contentType != null) {
1216       if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1217         if(response.responseText && response.responseText !== "")
1218           out.obj = JSON.parse(response.responseText);
1219         else
1220           out.obj = {}
1221       }
1222     }
1223
1224     if(response.status >= 200 && response.status < 300)
1225       cb.response(out);
1226     else if(response.status === 0 || (response.status >= 400 && response.status < 599))
1227       cb.error(out);
1228     else
1229       return cb.response(out);
1230   };
1231
1232   $.support.cors = true;
1233   return $.ajax(obj);
1234 }
1235
1236 /*
1237  * ShredHttpClient is a light-weight, node or browser HTTP client
1238  */
1239 var ShredHttpClient = function(options) {
1240   this.options = (options||{});
1241   this.isInitialized = false;
1242
1243   var identity, toString;
1244
1245   if (typeof window !== 'undefined') {
1246     this.Shred = require("./shred");
1247     this.content = require("./shred/content");
1248   }
1249   else
1250     this.Shred = require("shred");
1251   this.shred = new this.Shred();
1252 }
1253
1254 ShredHttpClient.prototype.initShred = function () {
1255   this.isInitialized = true;
1256   this.registerProcessors(this.shred);
1257 }
1258
1259 ShredHttpClient.prototype.registerProcessors = function(shred) {
1260   var identity = function(x) {
1261     return x;
1262   };
1263   var toString = function(x) {
1264     return x.toString();
1265   };
1266
1267   if (typeof window !== 'undefined') {
1268     this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1269       parser: identity,
1270       stringify: toString
1271     });
1272   } else {
1273     this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1274       parser: identity,
1275       stringify: toString
1276     });
1277   }
1278 }
1279
1280 ShredHttpClient.prototype.execute = function(obj) {
1281   if(!this.isInitialized)
1282     this.initShred();
1283
1284   var cb = obj.on, res;
1285
1286   var transform = function(response) {
1287     var out = {
1288       headers: response._headers,
1289       url: response.request.url,
1290       method: response.request.method,
1291       status: response.status,
1292       data: response.content.data
1293     };
1294
1295     var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null)
1296
1297     if(contentType != null) {
1298       if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1299         if(response.content.data && response.content.data !== "")
1300           out.obj = JSON.parse(response.content.data);
1301         else
1302           out.obj = {}
1303       }
1304     }
1305     return out;
1306   };
1307
1308   res = {
1309     error: function(response) {
1310       if (obj)
1311         return cb.error(transform(response));
1312     },
1313     redirect: function(response) {
1314       if (obj)
1315         return cb.redirect(transform(response));
1316     },
1317     307: function(response) {
1318       if (obj)
1319         return cb.redirect(transform(response));
1320     },
1321     response: function(response) {
1322       if (obj)
1323         return cb.response(transform(response));
1324     }
1325   };
1326   if (obj) {
1327     obj.on = res;
1328   }
1329   return this.shred.request(obj);
1330 };
1331
1332 /**
1333  * SwaggerAuthorizations applys the correct authorization to an operation being executed
1334  */
1335 var SwaggerAuthorizations = function() {
1336   this.authz = {};
1337 };
1338
1339 SwaggerAuthorizations.prototype.add = function(name, auth) {
1340   this.authz[name] = auth;
1341   return auth;
1342 };
1343
1344 SwaggerAuthorizations.prototype.remove = function(name) {
1345   return delete this.authz[name];
1346 };
1347
1348 SwaggerAuthorizations.prototype.apply = function(obj, authorizations) {
1349   status = null;
1350   var key;
1351   for (key in this.authz) {
1352     value = this.authz[key];
1353     result = value.apply(obj, authorizations);
1354     if (result === false)
1355       status = false;
1356     if (result === true)
1357       status = true;
1358   }
1359   return status;
1360 };
1361
1362 /**
1363  * ApiKeyAuthorization allows a query param or header to be injected
1364  */
1365 var ApiKeyAuthorization = function(name, value, type) {
1366   this.name = name;
1367   this.value = value;
1368   this.type = type;
1369 };
1370
1371 ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
1372   if (this.type === "query") {
1373     if (obj.url.indexOf('?') > 0)
1374       obj.url = obj.url + "&" + this.name + "=" + this.value;
1375     else
1376       obj.url = obj.url + "?" + this.name + "=" + this.value;
1377     return true;
1378   } else if (this.type === "header") {
1379     obj.headers[this.name] = this.value;
1380     return true;
1381   }
1382 };
1383
1384 /**
1385  * Password Authorization is a basic auth implementation
1386  */
1387 var PasswordAuthorization = function(name, username, password) {
1388   this.name = name;
1389   this.username = username;
1390   this.password = password;
1391   this._btoa = null;
1392   if (typeof window !== 'undefined')
1393     this._btoa = btoa;
1394   else
1395     this._btoa = require("btoa");
1396 };
1397
1398 PasswordAuthorization.prototype.apply = function(obj, authorizations) {
1399   var base64encoder = this._btoa;
1400   obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
1401   return true;
1402 };
1403
1404 var e = (typeof window !== 'undefined' ? window : exports);
1405
1406 e.SwaggerHttp = SwaggerHttp;
1407 e.SwaggerRequest = SwaggerRequest;
1408 e.authorizations = new SwaggerAuthorizations();
1409 e.ApiKeyAuthorization = ApiKeyAuthorization;
1410 e.PasswordAuthorization = PasswordAuthorization;
1411 e.JQueryHttpClient = JQueryHttpClient;
1412 e.ShredHttpClient = ShredHttpClient;
1413 e.SwaggerOperation = SwaggerOperation;
1414 e.SwaggerModel = SwaggerModel;
1415 e.SwaggerModelProperty = SwaggerModelProperty;
1416 e.SwaggerResource = SwaggerResource;
1417 e.SwaggerApi = SwaggerApi;