nucleus 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (224) hide show
  1. checksums.yaml +7 -0
  2. data/.gitattributes +1 -0
  3. data/.gitignore +19 -0
  4. data/.rspec +3 -0
  5. data/.rubocop.yml +44 -0
  6. data/.travis.yml +21 -0
  7. data/CHANGELOG.md +19 -0
  8. data/CONTRIBUTING.md +13 -0
  9. data/Gemfile +16 -0
  10. data/Guardfile +22 -0
  11. data/LICENSE +21 -0
  12. data/README.md +675 -0
  13. data/Rakefile +137 -0
  14. data/bin/nucleus +91 -0
  15. data/bin/nucleus.bat +1 -0
  16. data/config.ru +18 -0
  17. data/config/adapters/cloud_control.yml +32 -0
  18. data/config/adapters/cloud_foundry_v2.yml +61 -0
  19. data/config/adapters/heroku.yml +13 -0
  20. data/config/adapters/openshift_v2.yml +20 -0
  21. data/config/nucleus_config.rb +47 -0
  22. data/lib/nucleus.rb +13 -0
  23. data/lib/nucleus/adapter_resolver.rb +115 -0
  24. data/lib/nucleus/adapters/base_adapter.rb +109 -0
  25. data/lib/nucleus/adapters/buildpack_translator.rb +79 -0
  26. data/lib/nucleus/adapters/v1/cloud_control/application.rb +108 -0
  27. data/lib/nucleus/adapters/v1/cloud_control/authentication.rb +27 -0
  28. data/lib/nucleus/adapters/v1/cloud_control/buildpacks.rb +23 -0
  29. data/lib/nucleus/adapters/v1/cloud_control/cloud_control.rb +153 -0
  30. data/lib/nucleus/adapters/v1/cloud_control/data.rb +76 -0
  31. data/lib/nucleus/adapters/v1/cloud_control/domains.rb +68 -0
  32. data/lib/nucleus/adapters/v1/cloud_control/lifecycle.rb +27 -0
  33. data/lib/nucleus/adapters/v1/cloud_control/log_poller.rb +71 -0
  34. data/lib/nucleus/adapters/v1/cloud_control/logs.rb +103 -0
  35. data/lib/nucleus/adapters/v1/cloud_control/regions.rb +32 -0
  36. data/lib/nucleus/adapters/v1/cloud_control/scaling.rb +17 -0
  37. data/lib/nucleus/adapters/v1/cloud_control/semantic_errors.rb +31 -0
  38. data/lib/nucleus/adapters/v1/cloud_control/services.rb +162 -0
  39. data/lib/nucleus/adapters/v1/cloud_control/token.rb +17 -0
  40. data/lib/nucleus/adapters/v1/cloud_control/vars.rb +88 -0
  41. data/lib/nucleus/adapters/v1/cloud_foundry_v2/app_states.rb +28 -0
  42. data/lib/nucleus/adapters/v1/cloud_foundry_v2/application.rb +111 -0
  43. data/lib/nucleus/adapters/v1/cloud_foundry_v2/authentication.rb +17 -0
  44. data/lib/nucleus/adapters/v1/cloud_foundry_v2/buildpacks.rb +23 -0
  45. data/lib/nucleus/adapters/v1/cloud_foundry_v2/cloud_foundry_v2.rb +141 -0
  46. data/lib/nucleus/adapters/v1/cloud_foundry_v2/data.rb +97 -0
  47. data/lib/nucleus/adapters/v1/cloud_foundry_v2/domains.rb +149 -0
  48. data/lib/nucleus/adapters/v1/cloud_foundry_v2/lifecycle.rb +41 -0
  49. data/lib/nucleus/adapters/v1/cloud_foundry_v2/logs.rb +303 -0
  50. data/lib/nucleus/adapters/v1/cloud_foundry_v2/regions.rb +33 -0
  51. data/lib/nucleus/adapters/v1/cloud_foundry_v2/scaling.rb +15 -0
  52. data/lib/nucleus/adapters/v1/cloud_foundry_v2/semantic_errors.rb +27 -0
  53. data/lib/nucleus/adapters/v1/cloud_foundry_v2/services.rb +286 -0
  54. data/lib/nucleus/adapters/v1/cloud_foundry_v2/vars.rb +80 -0
  55. data/lib/nucleus/adapters/v1/heroku/app_states.rb +57 -0
  56. data/lib/nucleus/adapters/v1/heroku/application.rb +93 -0
  57. data/lib/nucleus/adapters/v1/heroku/authentication.rb +27 -0
  58. data/lib/nucleus/adapters/v1/heroku/buildpacks.rb +27 -0
  59. data/lib/nucleus/adapters/v1/heroku/data.rb +78 -0
  60. data/lib/nucleus/adapters/v1/heroku/domains.rb +43 -0
  61. data/lib/nucleus/adapters/v1/heroku/heroku.rb +146 -0
  62. data/lib/nucleus/adapters/v1/heroku/lifecycle.rb +51 -0
  63. data/lib/nucleus/adapters/v1/heroku/logs.rb +108 -0
  64. data/lib/nucleus/adapters/v1/heroku/regions.rb +42 -0
  65. data/lib/nucleus/adapters/v1/heroku/scaling.rb +28 -0
  66. data/lib/nucleus/adapters/v1/heroku/semantic_errors.rb +23 -0
  67. data/lib/nucleus/adapters/v1/heroku/services.rb +168 -0
  68. data/lib/nucleus/adapters/v1/heroku/vars.rb +65 -0
  69. data/lib/nucleus/adapters/v1/openshift_v2/app_states.rb +68 -0
  70. data/lib/nucleus/adapters/v1/openshift_v2/application.rb +108 -0
  71. data/lib/nucleus/adapters/v1/openshift_v2/authentication.rb +21 -0
  72. data/lib/nucleus/adapters/v1/openshift_v2/data.rb +96 -0
  73. data/lib/nucleus/adapters/v1/openshift_v2/domains.rb +37 -0
  74. data/lib/nucleus/adapters/v1/openshift_v2/lifecycle.rb +60 -0
  75. data/lib/nucleus/adapters/v1/openshift_v2/logs.rb +106 -0
  76. data/lib/nucleus/adapters/v1/openshift_v2/openshift_v2.rb +125 -0
  77. data/lib/nucleus/adapters/v1/openshift_v2/regions.rb +58 -0
  78. data/lib/nucleus/adapters/v1/openshift_v2/scaling.rb +39 -0
  79. data/lib/nucleus/adapters/v1/openshift_v2/semantic_errors.rb +40 -0
  80. data/lib/nucleus/adapters/v1/openshift_v2/services.rb +173 -0
  81. data/lib/nucleus/adapters/v1/openshift_v2/vars.rb +49 -0
  82. data/lib/nucleus/adapters/v1/stub_adapter.rb +464 -0
  83. data/lib/nucleus/core/adapter_authentication_inductor.rb +62 -0
  84. data/lib/nucleus/core/adapter_extensions/auth/auth_client.rb +44 -0
  85. data/lib/nucleus/core/adapter_extensions/auth/authentication_retry_wrapper.rb +79 -0
  86. data/lib/nucleus/core/adapter_extensions/auth/expiring_token_auth_client.rb +53 -0
  87. data/lib/nucleus/core/adapter_extensions/auth/http_basic_auth_client.rb +37 -0
  88. data/lib/nucleus/core/adapter_extensions/auth/o_auth2_auth_client.rb +95 -0
  89. data/lib/nucleus/core/adapter_extensions/auth/token_auth_client.rb +36 -0
  90. data/lib/nucleus/core/adapter_extensions/http_client.rb +177 -0
  91. data/lib/nucleus/core/adapter_extensions/http_tail_client.rb +26 -0
  92. data/lib/nucleus/core/adapter_extensions/tail_stopper.rb +25 -0
  93. data/lib/nucleus/core/common/errors/ambiguous_adapter_error.rb +7 -0
  94. data/lib/nucleus/core/common/errors/file_existence_error.rb +7 -0
  95. data/lib/nucleus/core/common/errors/startup_error.rb +12 -0
  96. data/lib/nucleus/core/common/exit_codes.rb +25 -0
  97. data/lib/nucleus/core/common/files/application_repo_sanitizer.rb +52 -0
  98. data/lib/nucleus/core/common/files/archive_extractor.rb +112 -0
  99. data/lib/nucleus/core/common/files/archiver.rb +91 -0
  100. data/lib/nucleus/core/common/link_generator.rb +46 -0
  101. data/lib/nucleus/core/common/logging/logging.rb +52 -0
  102. data/lib/nucleus/core/common/logging/multi_logger.rb +59 -0
  103. data/lib/nucleus/core/common/logging/request_log_formatter.rb +48 -0
  104. data/lib/nucleus/core/common/ssh_handler.rb +108 -0
  105. data/lib/nucleus/core/common/stream_callback.rb +27 -0
  106. data/lib/nucleus/core/common/thread_config_accessor.rb +85 -0
  107. data/lib/nucleus/core/common/url_converter.rb +28 -0
  108. data/lib/nucleus/core/enums/application_states.rb +26 -0
  109. data/lib/nucleus/core/enums/logfile_types.rb +28 -0
  110. data/lib/nucleus/core/error_messages.rb +127 -0
  111. data/lib/nucleus/core/errors/adapter_error.rb +13 -0
  112. data/lib/nucleus/core/errors/adapter_missing_implementation_error.rb +12 -0
  113. data/lib/nucleus/core/errors/adapter_request_error.rb +10 -0
  114. data/lib/nucleus/core/errors/adapter_resource_not_found_error.rb +10 -0
  115. data/lib/nucleus/core/errors/endpoint_authentication_error.rb +10 -0
  116. data/lib/nucleus/core/errors/platform_specific_semantic_error.rb +12 -0
  117. data/lib/nucleus/core/errors/platform_timeout_error.rb +10 -0
  118. data/lib/nucleus/core/errors/platform_unavailable_error.rb +10 -0
  119. data/lib/nucleus/core/errors/semantic_adapter_request_error.rb +19 -0
  120. data/lib/nucleus/core/errors/unknown_adapter_call_error.rb +10 -0
  121. data/lib/nucleus/core/file_handling/archive_converter.rb +29 -0
  122. data/lib/nucleus/core/file_handling/file_manager.rb +64 -0
  123. data/lib/nucleus/core/file_handling/git_deployer.rb +133 -0
  124. data/lib/nucleus/core/file_handling/git_repo_analyzer.rb +23 -0
  125. data/lib/nucleus/core/import/adapter_configuration.rb +53 -0
  126. data/lib/nucleus/core/import/vendor_parser.rb +28 -0
  127. data/lib/nucleus/core/import/version_detector.rb +18 -0
  128. data/lib/nucleus/core/models/abstract_model.rb +29 -0
  129. data/lib/nucleus/core/models/endpoint.rb +30 -0
  130. data/lib/nucleus/core/models/provider.rb +26 -0
  131. data/lib/nucleus/core/models/vendor.rb +22 -0
  132. data/lib/nucleus/ext/kernel.rb +5 -0
  133. data/lib/nucleus/ext/regexp.rb +49 -0
  134. data/lib/nucleus/os.rb +15 -0
  135. data/lib/nucleus/root_dir.rb +13 -0
  136. data/lib/nucleus/scripts/finalize.rb +8 -0
  137. data/lib/nucleus/scripts/initialize.rb +9 -0
  138. data/lib/nucleus/scripts/initialize_config_defaults.rb +26 -0
  139. data/lib/nucleus/scripts/load.rb +17 -0
  140. data/lib/nucleus/scripts/load_dependencies.rb +43 -0
  141. data/lib/nucleus/scripts/setup_config.rb +28 -0
  142. data/lib/nucleus/scripts/shutdown.rb +11 -0
  143. data/lib/nucleus/version.rb +3 -0
  144. data/nucleus.gemspec +88 -0
  145. data/public/robots.txt +2 -0
  146. data/public/swagger-ui/css/reset.css +125 -0
  147. data/public/swagger-ui/css/screen.css +1224 -0
  148. data/public/swagger-ui/images/apple-touch-icon-114x114.png +0 -0
  149. data/public/swagger-ui/images/apple-touch-icon-120x120.png +0 -0
  150. data/public/swagger-ui/images/apple-touch-icon-144x144.png +0 -0
  151. data/public/swagger-ui/images/apple-touch-icon-152x152.png +0 -0
  152. data/public/swagger-ui/images/apple-touch-icon-57x57.png +0 -0
  153. data/public/swagger-ui/images/apple-touch-icon-60x60.png +0 -0
  154. data/public/swagger-ui/images/apple-touch-icon-72x72.png +0 -0
  155. data/public/swagger-ui/images/apple-touch-icon-76x76.png +0 -0
  156. data/public/swagger-ui/images/explorer_icons.png +0 -0
  157. data/public/swagger-ui/images/favicon-128.png +0 -0
  158. data/public/swagger-ui/images/favicon-16x16.png +0 -0
  159. data/public/swagger-ui/images/favicon-196x196.png +0 -0
  160. data/public/swagger-ui/images/favicon-32x32.png +0 -0
  161. data/public/swagger-ui/images/favicon-96x96.png +0 -0
  162. data/public/swagger-ui/images/favicon.ico +0 -0
  163. data/public/swagger-ui/images/logo_small.png +0 -0
  164. data/public/swagger-ui/images/mstile-144x144.png +0 -0
  165. data/public/swagger-ui/images/mstile-150x150.png +0 -0
  166. data/public/swagger-ui/images/mstile-310x150.png +0 -0
  167. data/public/swagger-ui/images/mstile-310x310.png +0 -0
  168. data/public/swagger-ui/images/mstile-70x70.png +0 -0
  169. data/public/swagger-ui/images/pet_store_api.png +0 -0
  170. data/public/swagger-ui/images/throbber.gif +0 -0
  171. data/public/swagger-ui/images/wordnik_api.png +0 -0
  172. data/public/swagger-ui/index.html +107 -0
  173. data/public/swagger-ui/lib/backbone-min.js +38 -0
  174. data/public/swagger-ui/lib/handlebars-1.0.0.js +2278 -0
  175. data/public/swagger-ui/lib/highlight.7.3.pack.js +1 -0
  176. data/public/swagger-ui/lib/jquery-1.8.0.min.js +2 -0
  177. data/public/swagger-ui/lib/jquery.ba-bbq.min.js +18 -0
  178. data/public/swagger-ui/lib/jquery.slideto.min.js +1 -0
  179. data/public/swagger-ui/lib/jquery.wiggle.min.js +8 -0
  180. data/public/swagger-ui/lib/shred.bundle.js +2765 -0
  181. data/public/swagger-ui/lib/shred/content.js +193 -0
  182. data/public/swagger-ui/lib/swagger-oauth.js +211 -0
  183. data/public/swagger-ui/lib/swagger.js +1653 -0
  184. data/public/swagger-ui/lib/underscore-min.js +32 -0
  185. data/public/swagger-ui/o2c.html +15 -0
  186. data/public/swagger-ui/redirect.html +14 -0
  187. data/public/swagger-ui/swagger-ui.js +2324 -0
  188. data/public/swagger-ui/swagger-ui.min.js +1 -0
  189. data/schemas/api.adapter.schema.yml +31 -0
  190. data/schemas/api.requirements.schema.yml +17 -0
  191. data/spec/factories/models.rb +61 -0
  192. data/spec/integration/api/auth_spec.rb +58 -0
  193. data/spec/integration/api/endpoints_spec.rb +167 -0
  194. data/spec/integration/api/errors_spec.rb +47 -0
  195. data/spec/integration/api/providers_spec.rb +157 -0
  196. data/spec/integration/api/swagger_schema_spec.rb +64 -0
  197. data/spec/integration/api/vendors_spec.rb +45 -0
  198. data/spec/integration/integration_spec_helper.rb +27 -0
  199. data/spec/integration/test_data_generator.rb +55 -0
  200. data/spec/nucleus_git_key.pem +51 -0
  201. data/spec/spec_helper.rb +98 -0
  202. data/spec/support/shared_example_request_types.rb +99 -0
  203. data/spec/test_suites.rake +31 -0
  204. data/spec/unit/adapters/archive_converter_spec.rb +25 -0
  205. data/spec/unit/adapters/file_manager_spec.rb +93 -0
  206. data/spec/unit/adapters/git_deployer_spec.rb +262 -0
  207. data/spec/unit/adapters/v1/stub_spec.rb +14 -0
  208. data/spec/unit/common/helpers/auth_helper_spec.rb +73 -0
  209. data/spec/unit/common/oauth2_auth_client_spec.rb +108 -0
  210. data/spec/unit/common/regexp_spec.rb +33 -0
  211. data/spec/unit/common/request_log_formatter_spec.rb +108 -0
  212. data/spec/unit/common/thread_config_accessor_spec.rb +97 -0
  213. data/spec/unit/models/endpoint_spec.rb +83 -0
  214. data/spec/unit/models/provider_spec.rb +102 -0
  215. data/spec/unit/models/vendor_spec.rb +100 -0
  216. data/spec/unit/schemas/adapter_schema_spec.rb +16 -0
  217. data/spec/unit/schemas/adapter_validation_spec.rb +56 -0
  218. data/spec/unit/schemas/requirements_schema_spec.rb +16 -0
  219. data/spec/unit/unit_spec_helper.rb +11 -0
  220. data/tasks/compatibility.rake +113 -0
  221. data/tasks/evaluation.rake +162 -0
  222. data/wiki/adapter_tests.md +99 -0
  223. data/wiki/implement_new_adapter.md +155 -0
  224. metadata +836 -0
@@ -0,0 +1,193 @@
1
+
2
+ // The purpose of the `Content` object is to abstract away the data conversions
3
+ // to and from raw content entities as strings. For example, you want to be able
4
+ // to pass in a Javascript object and have it be automatically converted into a
5
+ // JSON string if the `content-type` is set to a JSON-based media type.
6
+ // Conversely, you want to be able to transparently get back a Javascript object
7
+ // in the response if the `content-type` is a JSON-based media-type.
8
+
9
+ // One limitation of the current implementation is that it [assumes the `charset` is UTF-8](https://github.com/spire-io/shred/issues/5).
10
+
11
+ // The `Content` constructor takes an options object, which *must* have either a
12
+ // `body` or `data` property and *may* have a `type` property indicating the
13
+ // media type. If there is no `type` attribute, a default will be inferred.
14
+ var Content = function(options) {
15
+ this.body = options.body;
16
+ this.data = options.data;
17
+ this.type = options.type;
18
+ };
19
+
20
+ Content.prototype = {
21
+ // Treat `toString()` as asking for the `content.body`. That is, the raw content entity.
22
+ //
23
+ // toString: function() { return this.body; }
24
+ //
25
+ // Commented out, but I've forgotten why. :/
26
+ };
27
+
28
+
29
+ // `Content` objects have the following attributes:
30
+ Object.defineProperties(Content.prototype,{
31
+
32
+ // - **type**. Typically accessed as `content.type`, reflects the `content-type`
33
+ // header associated with the request or response. If not passed as an options
34
+ // to the constructor or set explicitly, it will infer the type the `data`
35
+ // attribute, if possible, and, failing that, will default to `text/plain`.
36
+ type: {
37
+ get: function() {
38
+ if (this._type) {
39
+ return this._type;
40
+ } else {
41
+ if (this._data) {
42
+ switch(typeof this._data) {
43
+ case "string": return "text/plain";
44
+ case "object": return "application/json";
45
+ }
46
+ }
47
+ }
48
+ return "text/plain";
49
+ },
50
+ set: function(value) {
51
+ this._type = value;
52
+ return this;
53
+ },
54
+ enumerable: true
55
+ },
56
+
57
+ // - **data**. Typically accessed as `content.data`, reflects the content entity
58
+ // converted into Javascript data. This can be a string, if the `type` is, say,
59
+ // `text/plain`, but can also be a Javascript object. The conversion applied is
60
+ // based on the `processor` attribute. The `data` attribute can also be set
61
+ // directly, in which case the conversion will be done the other way, to infer
62
+ // the `body` attribute.
63
+ data: {
64
+ get: function() {
65
+ if (this._body) {
66
+ return this.processor.parser(this._body);
67
+ } else {
68
+ return this._data;
69
+ }
70
+ },
71
+ set: function(data) {
72
+ if (this._body&&data) Errors.setDataWithBody(this);
73
+ this._data = data;
74
+ return this;
75
+ },
76
+ enumerable: true
77
+ },
78
+
79
+ // - **body**. Typically accessed as `content.body`, reflects the content entity
80
+ // as a UTF-8 string. It is the mirror of the `data` attribute. If you set the
81
+ // `data` attribute, the `body` attribute will be inferred and vice-versa. If
82
+ // you attempt to set both, an exception is raised.
83
+ body: {
84
+ get: function() {
85
+ if (this._data) {
86
+ return this.processor.stringify(this._data);
87
+ } else {
88
+ return this._body.toString();
89
+ }
90
+ },
91
+ set: function(body) {
92
+ if (this._data&&body) Errors.setBodyWithData(this);
93
+ this._body = body;
94
+ return this;
95
+ },
96
+ enumerable: true
97
+ },
98
+
99
+ // - **processor**. The functions that will be used to convert to/from `data` and
100
+ // `body` attributes. You can add processors. The two that are built-in are for
101
+ // `text/plain`, which is basically an identity transformation and
102
+ // `application/json` and other JSON-based media types (including custom media
103
+ // types with `+json`). You can add your own processors. See below.
104
+ processor: {
105
+ get: function() {
106
+ var processor = Content.processors[this.type];
107
+ if (processor) {
108
+ return processor;
109
+ } else {
110
+ // Return the first processor that matches any part of the
111
+ // content type. ex: application/vnd.foobar.baz+json will match json.
112
+ var main = this.type.split(";")[0];
113
+ var parts = main.split(/\+|\//);
114
+ for (var i=0, l=parts.length; i < l; i++) {
115
+ processor = Content.processors[parts[i]]
116
+ }
117
+ return processor || {parser:identity,stringify:toString};
118
+ }
119
+ },
120
+ enumerable: true
121
+ },
122
+
123
+ // - **length**. Typically accessed as `content.length`, returns the length in
124
+ // bytes of the raw content entity.
125
+ length: {
126
+ get: function() {
127
+ if (typeof Buffer !== 'undefined') {
128
+ return Buffer.byteLength(this.body);
129
+ }
130
+ return this.body.length;
131
+ }
132
+ }
133
+ });
134
+
135
+ Content.processors = {};
136
+
137
+ // The `registerProcessor` function allows you to add your own processors to
138
+ // convert content entities. Each processor consists of a Javascript object with
139
+ // two properties:
140
+ // - **parser**. The function used to parse a raw content entity and convert it
141
+ // into a Javascript data type.
142
+ // - **stringify**. The function used to convert a Javascript data type into a
143
+ // raw content entity.
144
+ Content.registerProcessor = function(types,processor) {
145
+
146
+ // You can pass an array of types that will trigger this processor, or just one.
147
+ // We determine the array via duck-typing here.
148
+ if (types.forEach) {
149
+ types.forEach(function(type) {
150
+ Content.processors[type] = processor;
151
+ });
152
+ } else {
153
+ // If you didn't pass an array, we just use what you pass in.
154
+ Content.processors[types] = processor;
155
+ }
156
+ };
157
+
158
+ // Register the identity processor, which is used for text-based media types.
159
+ var identity = function(x) { return x; }
160
+ , toString = function(x) { return x.toString(); }
161
+ Content.registerProcessor(
162
+ ["text/html","text/plain","text"],
163
+ { parser: identity, stringify: toString });
164
+
165
+ // Register the JSON processor, which is used for JSON-based media types.
166
+ Content.registerProcessor(
167
+ ["application/json; charset=utf-8","application/json","json"],
168
+ {
169
+ parser: function(string) {
170
+ return JSON.parse(string);
171
+ },
172
+ stringify: function(data) {
173
+ return JSON.stringify(data); }});
174
+
175
+ var qs = require('querystring');
176
+ // Register the post processor, which is used for JSON-based media types.
177
+ Content.registerProcessor(
178
+ ["application/x-www-form-urlencoded"],
179
+ { parser : qs.parse, stringify : qs.stringify });
180
+
181
+ // Error functions are defined separately here in an attempt to make the code
182
+ // easier to read.
183
+ var Errors = {
184
+ setDataWithBody: function(object) {
185
+ throw new Error("Attempt to set data attribute of a content object " +
186
+ "when the body attributes was already set.");
187
+ },
188
+ setBodyWithData: function(object) {
189
+ throw new Error("Attempt to set body attribute of a content object " +
190
+ "when the data attributes was already set.");
191
+ }
192
+ }
193
+ module.exports = Content;
@@ -0,0 +1,211 @@
1
+ var appName;
2
+ var popupMask;
3
+ var popupDialog;
4
+ var clientId;
5
+ var realm;
6
+
7
+ function handleLogin() {
8
+ var scopes = [];
9
+
10
+ if(window.swaggerUi.api.authSchemes
11
+ && window.swaggerUi.api.authSchemes.oauth2
12
+ && window.swaggerUi.api.authSchemes.oauth2.scopes) {
13
+ scopes = window.swaggerUi.api.authSchemes.oauth2.scopes;
14
+ }
15
+
16
+ if(window.swaggerUi.api
17
+ && window.swaggerUi.api.info) {
18
+ appName = window.swaggerUi.api.info.title;
19
+ }
20
+
21
+ if(popupDialog.length > 0)
22
+ popupDialog = popupDialog.last();
23
+ else {
24
+ popupDialog = $(
25
+ [
26
+ '<div class="api-popup-dialog">',
27
+ '<div class="api-popup-title">Select OAuth2.0 Scopes</div>',
28
+ '<div class="api-popup-content">',
29
+ '<p>Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes.',
30
+ '<a href="#">Learn how to use</a>',
31
+ '</p>',
32
+ '<p><strong>' + appName + '</strong> API requires the following scopes. Select which ones you want to grant to Swagger UI.</p>',
33
+ '<ul class="api-popup-scopes">',
34
+ '</ul>',
35
+ '<p class="error-msg"></p>',
36
+ '<div class="api-popup-actions"><button class="api-popup-authbtn api-button green" type="button">Authorize</button><button class="api-popup-cancel api-button gray" type="button">Cancel</button></div>',
37
+ '</div>',
38
+ '</div>'].join(''));
39
+ $(document.body).append(popupDialog);
40
+
41
+ popup = popupDialog.find('ul.api-popup-scopes').empty();
42
+ for (i = 0; i < scopes.length; i ++) {
43
+ scope = scopes[i];
44
+ str = '<li><input type="checkbox" id="scope_' + i + '" scope="' + scope.scope + '"/>' + '<label for="scope_' + i + '">' + scope.scope;
45
+ if (scope.description) {
46
+ str += '<br/><span class="api-scope-desc">' + scope.description + '</span>';
47
+ }
48
+ str += '</label></li>';
49
+ popup.append(str);
50
+ }
51
+ }
52
+
53
+ var $win = $(window),
54
+ dw = $win.width(),
55
+ dh = $win.height(),
56
+ st = $win.scrollTop(),
57
+ dlgWd = popupDialog.outerWidth(),
58
+ dlgHt = popupDialog.outerHeight(),
59
+ top = (dh -dlgHt)/2 + st,
60
+ left = (dw - dlgWd)/2;
61
+
62
+ popupDialog.css({
63
+ top: (top < 0? 0 : top) + 'px',
64
+ left: (left < 0? 0 : left) + 'px'
65
+ });
66
+
67
+ popupDialog.find('button.api-popup-cancel').click(function() {
68
+ popupMask.hide();
69
+ popupDialog.hide();
70
+ });
71
+ popupDialog.find('button.api-popup-authbtn').click(function() {
72
+ popupMask.hide();
73
+ popupDialog.hide();
74
+
75
+ var authSchemes = window.swaggerUi.api.authSchemes;
76
+ var host = window.location;
77
+ var pathname = location.pathname.substring(0, location.pathname.lastIndexOf("/"));
78
+ var redirectUrl = host.protocol + '//' + host.host + pathname + "/o2c.html";
79
+ var url = null;
80
+
81
+ for (var key in authSchemes) {
82
+ if (authSchemes.hasOwnProperty(key)) {
83
+ var o = authSchemes[key].grantTypes;
84
+ for(var t in o) {
85
+ if(o.hasOwnProperty(t) && t === 'implicit') {
86
+ var dets = o[t];
87
+ url = dets.loginEndpoint.url + "?response_type=token";
88
+ window.swaggerUi.tokenName = dets.tokenName;
89
+ }
90
+ }
91
+ }
92
+ }
93
+ var scopes = []
94
+ var o = $('.api-popup-scopes').find('input:checked');
95
+
96
+ for(k =0; k < o.length; k++) {
97
+ scopes.push($(o[k]).attr("scope"));
98
+ }
99
+
100
+ window.enabledScopes=scopes;
101
+
102
+ url += '&redirect_uri=' + encodeURIComponent(redirectUrl);
103
+ url += '&realm=' + encodeURIComponent(realm);
104
+ url += '&client_id=' + encodeURIComponent(clientId);
105
+ url += '&scope=' + encodeURIComponent(scopes);
106
+
107
+ window.open(url);
108
+ });
109
+
110
+ popupMask.show();
111
+ popupDialog.show();
112
+ return;
113
+ }
114
+
115
+
116
+ function handleLogout() {
117
+ for(key in window.authorizations.authz){
118
+ window.authorizations.remove(key)
119
+ }
120
+ window.enabledScopes = null;
121
+ $('.api-ic.ic-on').addClass('ic-off');
122
+ $('.api-ic.ic-on').removeClass('ic-on');
123
+
124
+ // set the info box
125
+ $('.api-ic.ic-warning').addClass('ic-error');
126
+ $('.api-ic.ic-warning').removeClass('ic-warning');
127
+ }
128
+
129
+ function initOAuth(opts) {
130
+ var o = (opts||{});
131
+ var errors = [];
132
+
133
+ appName = (o.appName||errors.push("missing appName"));
134
+ popupMask = (o.popupMask||$('#api-common-mask'));
135
+ popupDialog = (o.popupDialog||$('.api-popup-dialog'));
136
+ clientId = (o.clientId||errors.push("missing client id"));
137
+ realm = (o.realm||errors.push("missing realm"));
138
+
139
+ if(errors.length > 0){
140
+ log("auth unable initialize oauth: " + errors);
141
+ return;
142
+ }
143
+
144
+ $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
145
+ $('.api-ic').click(function(s) {
146
+ if($(s.target).hasClass('ic-off'))
147
+ handleLogin();
148
+ else {
149
+ handleLogout();
150
+ }
151
+ false;
152
+ });
153
+ }
154
+
155
+ function onOAuthComplete(token) {
156
+ if(token) {
157
+ if(token.error) {
158
+ var checkbox = $('input[type=checkbox],.secured')
159
+ checkbox.each(function(pos){
160
+ checkbox[pos].checked = false;
161
+ });
162
+ alert(token.error);
163
+ }
164
+ else {
165
+ var b = token[window.swaggerUi.tokenName];
166
+ if(b){
167
+ // if all roles are satisfied
168
+ var o = null;
169
+ $.each($('.auth #api_information_panel'), function(k, v) {
170
+ var children = v;
171
+ if(children && children.childNodes) {
172
+ var requiredScopes = [];
173
+ $.each((children.childNodes), function (k1, v1){
174
+ var inner = v1.innerHTML;
175
+ if(inner)
176
+ requiredScopes.push(inner);
177
+ });
178
+ var diff = [];
179
+ for(var i=0; i < requiredScopes.length; i++) {
180
+ var s = requiredScopes[i];
181
+ if(window.enabledScopes && window.enabledScopes.indexOf(s) == -1) {
182
+ diff.push(s);
183
+ }
184
+ }
185
+ if(diff.length > 0){
186
+ o = v.parentNode;
187
+ $(o.parentNode).find('.api-ic.ic-on').addClass('ic-off');
188
+ $(o.parentNode).find('.api-ic.ic-on').removeClass('ic-on');
189
+
190
+ // sorry, not all scopes are satisfied
191
+ $(o).find('.api-ic').addClass('ic-warning');
192
+ $(o).find('.api-ic').removeClass('ic-error');
193
+ }
194
+ else {
195
+ o = v.parentNode;
196
+ $(o.parentNode).find('.api-ic.ic-off').addClass('ic-on');
197
+ $(o.parentNode).find('.api-ic.ic-off').removeClass('ic-off');
198
+
199
+ // all scopes are satisfied
200
+ $(o).find('.api-ic').addClass('ic-info');
201
+ $(o).find('.api-ic').removeClass('ic-warning');
202
+ $(o).find('.api-ic').removeClass('ic-error');
203
+ }
204
+ }
205
+ });
206
+
207
+ window.authorizations.add("oauth2", new ApiKeyAuthorization("Authorization", "Bearer " + b, "header"));
208
+ }
209
+ }
210
+ }
211
+ }
@@ -0,0 +1,1653 @@
1
+ // swagger.js
2
+ // version 2.0.39
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)[0] );
15
+ }
16
+ };
17
+
18
+ // if you want to apply conditional formatting of parameter values
19
+ parameterMacro = function(value) {
20
+ return value;
21
+ }
22
+
23
+ // if you want to apply conditional formatting of model property values
24
+ modelPropertyMacro = function(value) {
25
+ return value;
26
+ }
27
+
28
+ if (!Array.prototype.indexOf) {
29
+ Array.prototype.indexOf = function(obj, start) {
30
+ for (var i = (start || 0), j = this.length; i < j; i++) {
31
+ if (this[i] === obj) { return i; }
32
+ }
33
+ return -1;
34
+ }
35
+ }
36
+
37
+ if (!('filter' in Array.prototype)) {
38
+ Array.prototype.filter= function(filter, that /*opt*/) {
39
+ var other= [], v;
40
+ for (var i=0, n= this.length; i<n; i++)
41
+ if (i in this && filter.call(that, v= this[i], i, this))
42
+ other.push(v);
43
+ return other;
44
+ };
45
+ }
46
+
47
+ if (!('map' in Array.prototype)) {
48
+ Array.prototype.map= function(mapper, that /*opt*/) {
49
+ var other= new Array(this.length);
50
+ for (var i= 0, n= this.length; i<n; i++)
51
+ if (i in this)
52
+ other[i]= mapper.call(that, this[i], i, this);
53
+ return other;
54
+ };
55
+ }
56
+
57
+ Object.keys = Object.keys || (function () {
58
+ var hasOwnProperty = Object.prototype.hasOwnProperty,
59
+ hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
60
+ DontEnums = [
61
+ 'toString',
62
+ 'toLocaleString',
63
+ 'valueOf',
64
+ 'hasOwnProperty',
65
+ 'isPrototypeOf',
66
+ 'propertyIsEnumerable',
67
+ 'constructor'
68
+ ],
69
+ DontEnumsLength = DontEnums.length;
70
+
71
+ return function (o) {
72
+ if (typeof o != "object" && typeof o != "function" || o === null)
73
+ throw new TypeError("Object.keys called on a non-object");
74
+
75
+ var result = [];
76
+ for (var name in o) {
77
+ if (hasOwnProperty.call(o, name))
78
+ result.push(name);
79
+ }
80
+
81
+ if (hasDontEnumBug) {
82
+ for (var i = 0; i < DontEnumsLength; i++) {
83
+ if (hasOwnProperty.call(o, DontEnums[i]))
84
+ result.push(DontEnums[i]);
85
+ }
86
+ }
87
+
88
+ return result;
89
+ };
90
+ })();
91
+
92
+ var SwaggerApi = function(url, options) {
93
+ this.isBuilt = false;
94
+ this.url = null;
95
+ this.debug = false;
96
+ this.basePath = null;
97
+ this.authorizations = null;
98
+ this.authorizationScheme = null;
99
+ this.info = null;
100
+ this.useJQuery = false;
101
+ this.modelsArray = [];
102
+
103
+ options = (options||{});
104
+ if (url)
105
+ if (url.url)
106
+ options = url;
107
+ else
108
+ this.url = url;
109
+ else
110
+ options = url;
111
+
112
+ if (options.url != null)
113
+ this.url = options.url;
114
+
115
+ if (options.success != null)
116
+ this.success = options.success;
117
+
118
+ if (typeof options.useJQuery === 'boolean')
119
+ this.useJQuery = options.useJQuery;
120
+
121
+ this.failure = options.failure != null ? options.failure : function() {};
122
+ this.progress = options.progress != null ? options.progress : function() {};
123
+ if (options.success != null) {
124
+ this.build();
125
+ this.isBuilt = true;
126
+ }
127
+ }
128
+
129
+ SwaggerApi.prototype.build = function() {
130
+ if(this.isBuilt)
131
+ return this;
132
+ var _this = this;
133
+ this.progress('fetching resource list: ' + this.url);
134
+ var obj = {
135
+ useJQuery: this.useJQuery,
136
+ url: this.url,
137
+ method: "get",
138
+ headers: {
139
+ accept: "application/json,application/json;charset=\"utf-8\",*/*"
140
+ },
141
+ on: {
142
+ error: function(response) {
143
+ if (_this.url.substring(0, 4) !== 'http') {
144
+ return _this.fail('Please specify the protocol for ' + _this.url);
145
+ } else if (response.status === 0) {
146
+ return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
147
+ } else if (response.status === 404) {
148
+ return _this.fail('Can\'t read swagger JSON from ' + _this.url);
149
+ } else {
150
+ return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url);
151
+ }
152
+ },
153
+ response: function(resp) {
154
+ var responseObj = resp.obj || JSON.parse(resp.data);
155
+ _this.swaggerVersion = responseObj.swaggerVersion;
156
+ if (_this.swaggerVersion === "1.2") {
157
+ return _this.buildFromSpec(responseObj);
158
+ } else {
159
+ return _this.buildFrom1_1Spec(responseObj);
160
+ }
161
+ }
162
+ }
163
+ };
164
+ var e = (typeof window !== 'undefined' ? window : exports);
165
+ e.authorizations.apply(obj);
166
+ new SwaggerHttp().execute(obj);
167
+ return this;
168
+ };
169
+
170
+ SwaggerApi.prototype.buildFromSpec = function(response) {
171
+ if (response.apiVersion != null) {
172
+ this.apiVersion = response.apiVersion;
173
+ }
174
+ this.apis = {};
175
+ this.apisArray = [];
176
+ this.consumes = response.consumes;
177
+ this.produces = response.produces;
178
+ this.authSchemes = response.authorizations;
179
+ if (response.info != null) {
180
+ this.info = response.info;
181
+ }
182
+ var isApi = false;
183
+ var i;
184
+ for (i = 0; i < response.apis.length; i++) {
185
+ var api = response.apis[i];
186
+ if (api.operations) {
187
+ var j;
188
+ for (j = 0; j < api.operations.length; j++) {
189
+ operation = api.operations[j];
190
+ isApi = true;
191
+ }
192
+ }
193
+ }
194
+ if (response.basePath)
195
+ this.basePath = response.basePath;
196
+ else if (this.url.indexOf('?') > 0)
197
+ this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
198
+ else
199
+ this.basePath = this.url;
200
+
201
+ if (isApi) {
202
+ var newName = response.resourcePath.replace(/\//g, '');
203
+ this.resourcePath = response.resourcePath;
204
+ res = new SwaggerResource(response, this);
205
+ this.apis[newName] = res;
206
+ this.apisArray.push(res);
207
+ } else {
208
+ var k;
209
+ for (k = 0; k < response.apis.length; k++) {
210
+ var resource = response.apis[k];
211
+ res = new SwaggerResource(resource, this);
212
+ this.apis[res.name] = res;
213
+ this.apisArray.push(res);
214
+ }
215
+ }
216
+ if (this.success) {
217
+ this.success();
218
+ }
219
+ return this;
220
+ };
221
+
222
+ SwaggerApi.prototype.buildFrom1_1Spec = function(response) {
223
+ log("This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info");
224
+ if (response.apiVersion != null)
225
+ this.apiVersion = response.apiVersion;
226
+ this.apis = {};
227
+ this.apisArray = [];
228
+ this.produces = response.produces;
229
+ if (response.info != null) {
230
+ this.info = response.info;
231
+ }
232
+ var isApi = false;
233
+ for (var i = 0; i < response.apis.length; i++) {
234
+ var api = response.apis[i];
235
+ if (api.operations) {
236
+ for (var j = 0; j < api.operations.length; j++) {
237
+ operation = api.operations[j];
238
+ isApi = true;
239
+ }
240
+ }
241
+ }
242
+ if (response.basePath) {
243
+ this.basePath = response.basePath;
244
+ } else if (this.url.indexOf('?') > 0) {
245
+ this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
246
+ } else {
247
+ this.basePath = this.url;
248
+ }
249
+ if (isApi) {
250
+ var newName = response.resourcePath.replace(/\//g, '');
251
+ this.resourcePath = response.resourcePath;
252
+ var res = new SwaggerResource(response, this);
253
+ this.apis[newName] = res;
254
+ this.apisArray.push(res);
255
+ } else {
256
+ for (k = 0; k < response.apis.length; k++) {
257
+ resource = response.apis[k];
258
+ res = new SwaggerResource(resource, this);
259
+ this.apis[res.name] = res;
260
+ this.apisArray.push(res);
261
+ }
262
+ }
263
+ if (this.success) {
264
+ this.success();
265
+ }
266
+ return this;
267
+ };
268
+
269
+ SwaggerApi.prototype.selfReflect = function() {
270
+ var resource, resource_name, _ref;
271
+ if (this.apis == null) {
272
+ return false;
273
+ }
274
+ _ref = this.apis;
275
+ for (resource_name in _ref) {
276
+ resource = _ref[resource_name];
277
+ if (resource.ready == null) {
278
+ return false;
279
+ }
280
+ }
281
+ this.setConsolidatedModels();
282
+ this.ready = true;
283
+ if (this.success != null) {
284
+ return this.success();
285
+ }
286
+ };
287
+
288
+ SwaggerApi.prototype.fail = function(message) {
289
+ this.failure(message);
290
+ throw message;
291
+ };
292
+
293
+ SwaggerApi.prototype.setConsolidatedModels = function() {
294
+ var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results;
295
+ this.models = {};
296
+ _ref = this.apis;
297
+ for (resource_name in _ref) {
298
+ resource = _ref[resource_name];
299
+ for (modelName in resource.models) {
300
+ if (this.models[modelName] == null) {
301
+ this.models[modelName] = resource.models[modelName];
302
+ this.modelsArray.push(resource.models[modelName]);
303
+ }
304
+ }
305
+ }
306
+ _ref1 = this.modelsArray;
307
+ _results = [];
308
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
309
+ model = _ref1[_i];
310
+ _results.push(model.setReferencedModels(this.models));
311
+ }
312
+ return _results;
313
+ };
314
+
315
+ SwaggerApi.prototype.help = function() {
316
+ var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2;
317
+ _ref = this.apis;
318
+ for (resource_name in _ref) {
319
+ resource = _ref[resource_name];
320
+ log(resource_name);
321
+ _ref1 = resource.operations;
322
+ for (operation_name in _ref1) {
323
+ operation = _ref1[operation_name];
324
+ log(" " + operation.nickname);
325
+ _ref2 = operation.parameters;
326
+ for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
327
+ parameter = _ref2[_i];
328
+ log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
329
+ }
330
+ }
331
+ }
332
+ return this;
333
+ };
334
+
335
+ var SwaggerResource = function(resourceObj, api) {
336
+ var _this = this;
337
+ this.api = api;
338
+ this.api = this.api;
339
+ consumes = (this.consumes | []);
340
+ produces = (this.produces | []);
341
+ this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path;
342
+ this.description = resourceObj.description;
343
+
344
+ var parts = this.path.split("/");
345
+ this.name = parts[parts.length - 1].replace('.{format}', '');
346
+ this.basePath = this.api.basePath;
347
+ this.operations = {};
348
+ this.operationsArray = [];
349
+ this.modelsArray = [];
350
+ this.models = {};
351
+ this.rawModels = {};
352
+ this.useJQuery = (typeof api.useJQuery !== 'undefined' ? api.useJQuery : null);
353
+
354
+ if ((resourceObj.apis != null) && (this.api.resourcePath != null)) {
355
+ this.addApiDeclaration(resourceObj);
356
+ } else {
357
+ if (this.path == null) {
358
+ this.api.fail("SwaggerResources must have a path.");
359
+ }
360
+ if (this.path.substring(0, 4) === 'http') {
361
+ this.url = this.path.replace('{format}', 'json');
362
+ } else {
363
+ this.url = this.api.basePath + this.path.replace('{format}', 'json');
364
+ }
365
+ this.api.progress('fetching resource ' + this.name + ': ' + this.url);
366
+ obj = {
367
+ url: this.url,
368
+ method: "get",
369
+ useJQuery: this.useJQuery,
370
+ headers: {
371
+ accept: "application/json,application/json;charset=\"utf-8\",*/*"
372
+ },
373
+ on: {
374
+ response: function(resp) {
375
+ var responseObj = resp.obj || JSON.parse(resp.data);
376
+ return _this.addApiDeclaration(responseObj);
377
+ },
378
+ error: function(response) {
379
+ return _this.api.fail("Unable to read api '" +
380
+ _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")");
381
+ }
382
+ }
383
+ };
384
+ var e = typeof window !== 'undefined' ? window : exports;
385
+ e.authorizations.apply(obj);
386
+ new SwaggerHttp().execute(obj);
387
+ }
388
+ }
389
+
390
+ SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
391
+ var pos, url;
392
+ url = this.api.basePath;
393
+ pos = url.lastIndexOf(relativeBasePath);
394
+ var parts = url.split("/");
395
+ var rootUrl = parts[0] + "//" + parts[2];
396
+
397
+ if(relativeBasePath.indexOf("http") === 0)
398
+ return relativeBasePath;
399
+ if(relativeBasePath === "/")
400
+ return rootUrl;
401
+ if(relativeBasePath.substring(0, 1) == "/") {
402
+ // use root + relative
403
+ return rootUrl + relativeBasePath;
404
+ }
405
+ else {
406
+ var pos = this.basePath.lastIndexOf("/");
407
+ var base = this.basePath.substring(0, pos);
408
+ if(base.substring(base.length - 1) == "/")
409
+ return base + relativeBasePath;
410
+ else
411
+ return base + "/" + relativeBasePath;
412
+ }
413
+ };
414
+
415
+ SwaggerResource.prototype.addApiDeclaration = function(response) {
416
+ if (response.produces != null)
417
+ this.produces = response.produces;
418
+ if (response.consumes != null)
419
+ this.consumes = response.consumes;
420
+ if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0)
421
+ this.basePath = response.basePath.indexOf("http") === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
422
+
423
+ this.addModels(response.models);
424
+ if (response.apis) {
425
+ for (var i = 0 ; i < response.apis.length; i++) {
426
+ var endpoint = response.apis[i];
427
+ this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
428
+ }
429
+ }
430
+ this.api[this.name] = this;
431
+ this.ready = true;
432
+ return this.api.selfReflect();
433
+ };
434
+
435
+ SwaggerResource.prototype.addModels = function(models) {
436
+ if (models != null) {
437
+ var modelName;
438
+ for (modelName in models) {
439
+ if (this.models[modelName] == null) {
440
+ var swaggerModel = new SwaggerModel(modelName, models[modelName]);
441
+ this.modelsArray.push(swaggerModel);
442
+ this.models[modelName] = swaggerModel;
443
+ this.rawModels[modelName] = models[modelName];
444
+ }
445
+ }
446
+ var output = [];
447
+ for (var i = 0; i < this.modelsArray.length; i++) {
448
+ model = this.modelsArray[i];
449
+ output.push(model.setReferencedModels(this.models));
450
+ }
451
+ return output;
452
+ }
453
+ };
454
+
455
+ SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, produces) {
456
+ if (ops) {
457
+ output = [];
458
+ for (var i = 0; i < ops.length; i++) {
459
+ o = ops[i];
460
+ consumes = this.consumes;
461
+ produces = this.produces;
462
+ if (o.consumes != null)
463
+ consumes = o.consumes;
464
+ else
465
+ consumes = this.consumes;
466
+
467
+ if (o.produces != null)
468
+ produces = o.produces;
469
+ else
470
+ produces = this.produces;
471
+ type = (o.type||o.responseClass);
472
+
473
+ if (type === "array") {
474
+ ref = null;
475
+ if (o.items)
476
+ ref = o.items["type"] || o.items["$ref"];
477
+ type = "array[" + ref + "]";
478
+ }
479
+ responseMessages = o.responseMessages;
480
+ method = o.method;
481
+ if (o.httpMethod) {
482
+ method = o.httpMethod;
483
+ }
484
+ if (o.supportedContentTypes) {
485
+ consumes = o.supportedContentTypes;
486
+ }
487
+ if (o.errorResponses) {
488
+ responseMessages = o.errorResponses;
489
+ for (var j = 0; j < responseMessages.length; j++) {
490
+ r = responseMessages[j];
491
+ r.message = r.reason;
492
+ r.reason = null;
493
+ }
494
+ }
495
+ o.nickname = this.sanitize(o.nickname);
496
+ op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations);
497
+ this.operations[op.nickname] = op;
498
+ output.push(this.operationsArray.push(op));
499
+ }
500
+ return output;
501
+ }
502
+ };
503
+
504
+ SwaggerResource.prototype.sanitize = function(nickname) {
505
+ var op;
506
+ op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
507
+ op = op.replace(/((_){2,})/g, '_');
508
+ op = op.replace(/^(_)*/g, '');
509
+ op = op.replace(/([_])*$/g, '');
510
+ return op;
511
+ };
512
+
513
+ SwaggerResource.prototype.help = function() {
514
+ var op = this.operations;
515
+ var output = [];
516
+ var operation_name;
517
+ for (operation_name in op) {
518
+ operation = op[operation_name];
519
+ var msg = " " + operation.nickname;
520
+ for (var i = 0; i < operation.parameters; i++) {
521
+ parameter = operation.parameters[i];
522
+ msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
523
+ }
524
+ output.push(msg);
525
+ }
526
+ return output;
527
+ };
528
+
529
+ var SwaggerModel = function(modelName, obj) {
530
+ this.name = obj.id != null ? obj.id : modelName;
531
+ this.properties = [];
532
+ var propertyName;
533
+ for (propertyName in obj.properties) {
534
+ if (obj.required != null) {
535
+ var value;
536
+ for (value in obj.required) {
537
+ if (propertyName === obj.required[value]) {
538
+ obj.properties[propertyName].required = true;
539
+ }
540
+ }
541
+ }
542
+ prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]);
543
+ this.properties.push(prop);
544
+ }
545
+ }
546
+
547
+ SwaggerModel.prototype.setReferencedModels = function(allModels) {
548
+ var results = [];
549
+ for (var i = 0; i < this.properties.length; i++) {
550
+ var property = this.properties[i];
551
+ var type = property.type || property.dataType;
552
+ if (allModels[type] != null)
553
+ results.push(property.refModel = allModels[type]);
554
+ else if ((property.refDataType != null) && (allModels[property.refDataType] != null))
555
+ results.push(property.refModel = allModels[property.refDataType]);
556
+ else
557
+ results.push(void 0);
558
+ }
559
+ return results;
560
+ };
561
+
562
+ SwaggerModel.prototype.getMockSignature = function(modelsToIgnore) {
563
+ var propertiesStr = [];
564
+ for (var i = 0; i < this.properties.length; i++) {
565
+ prop = this.properties[i];
566
+ propertiesStr.push(prop.toString());
567
+ }
568
+
569
+ var strong = '<span class="strong">';
570
+ var stronger = '<span class="stronger">';
571
+ var strongClose = '</span>';
572
+ var classOpen = strong + this.name + ' {' + strongClose;
573
+ var classClose = strong + '}' + strongClose;
574
+ var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
575
+ if (!modelsToIgnore)
576
+ modelsToIgnore = [];
577
+ modelsToIgnore.push(this.name);
578
+
579
+ for (var i = 0; i < this.properties.length; i++) {
580
+ prop = this.properties[i];
581
+ if ((prop.refModel != null) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
582
+ returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
583
+ }
584
+ }
585
+ return returnVal;
586
+ };
587
+
588
+ SwaggerModel.prototype.createJSONSample = function(modelsToIgnore) {
589
+ if(sampleModels[this.name]) {
590
+ return sampleModels[this.name];
591
+ }
592
+ else {
593
+ var result = {};
594
+ var modelsToIgnore = (modelsToIgnore||[])
595
+ modelsToIgnore.push(this.name);
596
+ for (var i = 0; i < this.properties.length; i++) {
597
+ prop = this.properties[i];
598
+ result[prop.name] = prop.getSampleValue(modelsToIgnore);
599
+ }
600
+ modelsToIgnore.pop(this.name);
601
+ return result;
602
+ }
603
+ };
604
+
605
+ var SwaggerModelProperty = function(name, obj) {
606
+ this.name = name;
607
+ this.dataType = obj.type || obj.dataType || obj["$ref"];
608
+ this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
609
+ this.descr = obj.description;
610
+ this.required = obj.required;
611
+ this.defaultValue = modelPropertyMacro(obj.defaultValue);
612
+ if (obj.items != null) {
613
+ if (obj.items.type != null) {
614
+ this.refDataType = obj.items.type;
615
+ }
616
+ if (obj.items.$ref != null) {
617
+ this.refDataType = obj.items.$ref;
618
+ }
619
+ }
620
+ this.dataTypeWithRef = this.refDataType != null ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
621
+ if (obj.allowableValues != null) {
622
+ this.valueType = obj.allowableValues.valueType;
623
+ this.values = obj.allowableValues.values;
624
+ if (this.values != null) {
625
+ this.valuesString = "'" + this.values.join("' or '") + "'";
626
+ }
627
+ }
628
+ if (obj["enum"] != null) {
629
+ this.valueType = "string";
630
+ this.values = obj["enum"];
631
+ if (this.values != null) {
632
+ this.valueString = "'" + this.values.join("' or '") + "'";
633
+ }
634
+ }
635
+ }
636
+
637
+ SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) {
638
+ var result;
639
+ if ((this.refModel != null) && (modelsToIgnore.indexOf(prop.refModel.name) === -1)) {
640
+ result = this.refModel.createJSONSample(modelsToIgnore);
641
+ } else {
642
+ if (this.isCollection) {
643
+ result = this.toSampleValue(this.refDataType);
644
+ } else {
645
+ result = this.toSampleValue(this.dataType);
646
+ }
647
+ }
648
+ if (this.isCollection) {
649
+ return [result];
650
+ } else {
651
+ return result;
652
+ }
653
+ };
654
+
655
+ SwaggerModelProperty.prototype.toSampleValue = function(value) {
656
+ var result;
657
+ if ((typeof this.defaultValue !== 'undefined') && this.defaultValue !== null) {
658
+ result = this.defaultValue;
659
+ } else if (value === "integer") {
660
+ result = 0;
661
+ } else if (value === "boolean") {
662
+ result = false;
663
+ } else if (value === "double" || value === "number") {
664
+ result = 0.0;
665
+ } else if (value === "string") {
666
+ result = "";
667
+ } else {
668
+ result = value;
669
+ }
670
+ return result;
671
+ };
672
+
673
+ SwaggerModelProperty.prototype.toString = function() {
674
+ var req = this.required ? 'propReq' : 'propOpt';
675
+ var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
676
+ if (!this.required) {
677
+ str += ', <span class="propOptKey">optional</span>';
678
+ }
679
+ str += ')';
680
+ if (this.values != null) {
681
+ str += " = <span class='propVals'>['" + this.values.join("' or '") + "']</span>";
682
+ }
683
+ if (this.descr != null) {
684
+ str += ': <span class="propDesc">' + this.descr + '</span>';
685
+ }
686
+ return str;
687
+ };
688
+
689
+ var SwaggerOperation = function(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) {
690
+ var _this = this;
691
+
692
+ var errors = [];
693
+ this.nickname = (nickname||errors.push("SwaggerOperations must have a nickname."));
694
+ this.path = (path||errors.push("SwaggerOperation " + nickname + " is missing path."));
695
+ this.method = (method||errors.push("SwaggerOperation " + nickname + " is missing method."));
696
+ this.parameters = parameters != null ? parameters : [];
697
+ this.summary = summary;
698
+ this.notes = notes;
699
+ this.type = type;
700
+ this.responseMessages = (responseMessages||[]);
701
+ this.resource = (resource||errors.push("Resource is required"));
702
+ this.consumes = consumes;
703
+ this.produces = produces;
704
+ this.authorizations = authorizations;
705
+ this["do"] = __bind(this["do"], this);
706
+
707
+ if (errors.length > 0)
708
+ this.resource.api.fail(errors);
709
+
710
+ this.path = this.path.replace('{format}', 'json');
711
+ this.method = this.method.toLowerCase();
712
+ this.isGetMethod = this.method === "get";
713
+
714
+ this.resourceName = this.resource.name;
715
+ if(typeof this.type !== 'undefined' && this.type === 'void')
716
+ this.type = null;
717
+ else {
718
+ this.responseClassSignature = this.getSignature(this.type, this.resource.models);
719
+ this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
720
+ }
721
+
722
+ for(var i = 0; i < this.parameters.length; i ++) {
723
+ var param = this.parameters[i];
724
+ // might take this away
725
+ param.name = param.name || param.type || param.dataType;
726
+
727
+ // for 1.1 compatibility
728
+ var type = param.type || param.dataType;
729
+ if(type === 'array') {
730
+ type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
731
+ }
732
+ param.type = type;
733
+
734
+ if(type.toLowerCase() === 'boolean') {
735
+ param.allowableValues = {};
736
+ param.allowableValues.values = ["true", "false"];
737
+ }
738
+ param.signature = this.getSignature(type, this.resource.models);
739
+ param.sampleJSON = this.getSampleJSON(type, this.resource.models);
740
+
741
+ var enumValue = param["enum"];
742
+ if(enumValue != null) {
743
+ param.isList = true;
744
+ param.allowableValues = {};
745
+ param.allowableValues.descriptiveValues = [];
746
+
747
+ for(var j = 0; j < enumValue.length; j++) {
748
+ var v = enumValue[j];
749
+ if(param.defaultValue != null) {
750
+ param.allowableValues.descriptiveValues.push ({
751
+ value: String(v),
752
+ isDefault: (v === param.defaultValue)
753
+ });
754
+ }
755
+ else {
756
+ param.allowableValues.descriptiveValues.push ({
757
+ value: String(v),
758
+ isDefault: false
759
+ });
760
+ }
761
+ }
762
+ }
763
+ else if(param.allowableValues != null) {
764
+ if(param.allowableValues.valueType === "RANGE")
765
+ param.isRange = true;
766
+ else
767
+ param.isList = true;
768
+ if(param.allowableValues != null) {
769
+ param.allowableValues.descriptiveValues = [];
770
+ if(param.allowableValues.values) {
771
+ for(var j = 0; j < param.allowableValues.values.length; j++){
772
+ var v = param.allowableValues.values[j];
773
+ if(param.defaultValue != null) {
774
+ param.allowableValues.descriptiveValues.push ({
775
+ value: String(v),
776
+ isDefault: (v === param.defaultValue)
777
+ });
778
+ }
779
+ else {
780
+ param.allowableValues.descriptiveValues.push ({
781
+ value: String(v),
782
+ isDefault: false
783
+ });
784
+ }
785
+ }
786
+ }
787
+ }
788
+ }
789
+ param.defaultValue = parameterMacro(param.defaultValue);
790
+ }
791
+ this.resource[this.nickname] = function(args, callback, error) {
792
+ return _this["do"](args, callback, error);
793
+ };
794
+ this.resource[this.nickname].help = function() {
795
+ return _this.help();
796
+ };
797
+ }
798
+
799
+ SwaggerOperation.prototype.isListType = function(type) {
800
+ if (type && type.indexOf('[') >= 0) {
801
+ return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
802
+ } else {
803
+ return void 0;
804
+ }
805
+ };
806
+
807
+ SwaggerOperation.prototype.getSignature = function(type, models) {
808
+ var isPrimitive, listType;
809
+ listType = this.isListType(type);
810
+ isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
811
+ if (isPrimitive) {
812
+ return type;
813
+ } else {
814
+ if (listType != null) {
815
+ return models[listType].getMockSignature();
816
+ } else {
817
+ return models[type].getMockSignature();
818
+ }
819
+ }
820
+ };
821
+
822
+ SwaggerOperation.prototype.getSampleJSON = function(type, models) {
823
+ var isPrimitive, listType, val;
824
+ listType = this.isListType(type);
825
+ isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
826
+ val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample());
827
+ if (val) {
828
+ val = listType ? [val] : val;
829
+ if(typeof val == "string")
830
+ return val;
831
+ else if(typeof val === "object") {
832
+ var t = val;
833
+ if(val instanceof Array && val.length > 0) {
834
+ t = val[0];
835
+ }
836
+ if(t.nodeName) {
837
+ var xmlString = new XMLSerializer().serializeToString(t);
838
+ return this.formatXml(xmlString);
839
+ }
840
+ else
841
+ return JSON.stringify(val, null, 2);
842
+ }
843
+ else
844
+ return val;
845
+ }
846
+ };
847
+
848
+ SwaggerOperation.prototype["do"] = function(args, opts, callback, error) {
849
+ var key, param, params, possibleParams, req, requestContentType, responseContentType, value, _i, _len, _ref;
850
+ if (args == null) {
851
+ args = {};
852
+ }
853
+ if (opts == null) {
854
+ opts = {};
855
+ }
856
+ requestContentType = null;
857
+ responseContentType = null;
858
+ if ((typeof args) === "function") {
859
+ error = opts;
860
+ callback = args;
861
+ args = {};
862
+ }
863
+ if ((typeof opts) === "function") {
864
+ error = callback;
865
+ callback = opts;
866
+ }
867
+ if (error == null) {
868
+ error = function(xhr, textStatus, error) {
869
+ return log(xhr, textStatus, error);
870
+ };
871
+ }
872
+ if (callback == null) {
873
+ callback = function(response) {
874
+ var content;
875
+ content = null;
876
+ if (response != null) {
877
+ content = response.data;
878
+ } else {
879
+ content = "no data";
880
+ }
881
+ return log("default callback: " + content);
882
+ };
883
+ }
884
+ params = {};
885
+ params.headers = [];
886
+ if (args.headers != null) {
887
+ params.headers = args.headers;
888
+ delete args.headers;
889
+ }
890
+
891
+ var possibleParams = [];
892
+ for(var i = 0; i < this.parameters.length; i++) {
893
+ var param = this.parameters[i];
894
+ if(param.paramType === 'header') {
895
+ if(args[param.name])
896
+ params.headers[param.name] = args[param.name];
897
+ }
898
+ else if(param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
899
+ possibleParams.push(param);
900
+ }
901
+
902
+ if (args.body != null) {
903
+ params.body = args.body;
904
+ delete args.body;
905
+ }
906
+
907
+ if (possibleParams) {
908
+ var key;
909
+ for (key in possibleParams) {
910
+ value = possibleParams[key];
911
+ if (args[value.name]) {
912
+ params[value.name] = args[value.name];
913
+ }
914
+ }
915
+ }
916
+
917
+ req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
918
+ if (opts.mock != null) {
919
+ return req;
920
+ } else {
921
+ return true;
922
+ }
923
+ };
924
+
925
+ SwaggerOperation.prototype.pathJson = function() {
926
+ return this.path.replace("{format}", "json");
927
+ };
928
+
929
+ SwaggerOperation.prototype.pathXml = function() {
930
+ return this.path.replace("{format}", "xml");
931
+ };
932
+
933
+ SwaggerOperation.prototype.encodePathParam = function(pathParam) {
934
+ var encParts, part, parts, _i, _len;
935
+ pathParam = pathParam.toString();
936
+ if (pathParam.indexOf("/") === -1) {
937
+ return encodeURIComponent(pathParam);
938
+ } else {
939
+ parts = pathParam.split("/");
940
+ encParts = [];
941
+ for (_i = 0, _len = parts.length; _i < _len; _i++) {
942
+ part = parts[_i];
943
+ encParts.push(encodeURIComponent(part));
944
+ }
945
+ return encParts.join("/");
946
+ }
947
+ };
948
+
949
+ SwaggerOperation.prototype.urlify = function(args) {
950
+ var url = this.resource.basePath + this.pathJson();
951
+ var params = this.parameters;
952
+ for(var i = 0; i < params.length; i ++){
953
+ var param = params[i];
954
+ if (param.paramType === 'path') {
955
+ if(args[param.name]) {
956
+ // apply path params and remove from args
957
+ var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
958
+ url = url.replace(reg, this.encodePathParam(args[param.name]));
959
+ delete args[param.name];
960
+ }
961
+ else
962
+ throw "" + param.name + " is a required path param.";
963
+ }
964
+ }
965
+
966
+ var queryParams = "";
967
+ for(var i = 0; i < params.length; i ++){
968
+ var param = params[i];
969
+ if(param.paramType === 'query') {
970
+ if (args[param.name] !== undefined) {
971
+ if (queryParams !== '')
972
+ queryParams += "&";
973
+ queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
974
+ }
975
+ }
976
+ }
977
+ if ((queryParams != null) && queryParams.length > 0)
978
+ url += '?' + queryParams;
979
+ return url;
980
+ };
981
+
982
+ SwaggerOperation.prototype.supportHeaderParams = function() {
983
+ return this.resource.api.supportHeaderParams;
984
+ };
985
+
986
+ SwaggerOperation.prototype.supportedSubmitMethods = function() {
987
+ return this.resource.api.supportedSubmitMethods;
988
+ };
989
+
990
+ SwaggerOperation.prototype.getQueryParams = function(args) {
991
+ return this.getMatchingParams(['query'], args);
992
+ };
993
+
994
+ SwaggerOperation.prototype.getHeaderParams = function(args) {
995
+ return this.getMatchingParams(['header'], args);
996
+ };
997
+
998
+ SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) {
999
+ var matchingParams = {};
1000
+ var params = this.parameters;
1001
+ for (var i = 0; i < params.length; i++) {
1002
+ param = params[i];
1003
+ if (args && args[param.name])
1004
+ matchingParams[param.name] = args[param.name];
1005
+ }
1006
+ var headers = this.resource.api.headers;
1007
+ var name;
1008
+ for (name in headers) {
1009
+ var value = headers[name];
1010
+ matchingParams[name] = value;
1011
+ }
1012
+ return matchingParams;
1013
+ };
1014
+
1015
+ SwaggerOperation.prototype.help = function() {
1016
+ var msg = "";
1017
+ var params = this.parameters;
1018
+ for (var i = 0; i < params.length; i++) {
1019
+ var param = params[i];
1020
+ if (msg !== "")
1021
+ msg += "\n";
1022
+ msg += "* " + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
1023
+ }
1024
+ return msg;
1025
+ };
1026
+
1027
+
1028
+ SwaggerOperation.prototype.formatXml = function(xml) {
1029
+ var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
1030
+ reg = /(>)(<)(\/*)/g;
1031
+ wsexp = /[ ]*(.*)[ ]+\n/g;
1032
+ contexp = /(<.+>)(.+\n)/g;
1033
+ xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
1034
+ pad = 0;
1035
+ formatted = '';
1036
+ lines = xml.split('\n');
1037
+ indent = 0;
1038
+ lastType = 'other';
1039
+ transitions = {
1040
+ 'single->single': 0,
1041
+ 'single->closing': -1,
1042
+ 'single->opening': 0,
1043
+ 'single->other': 0,
1044
+ 'closing->single': 0,
1045
+ 'closing->closing': -1,
1046
+ 'closing->opening': 0,
1047
+ 'closing->other': 0,
1048
+ 'opening->single': 1,
1049
+ 'opening->closing': 0,
1050
+ 'opening->opening': 1,
1051
+ 'opening->other': 1,
1052
+ 'other->single': 0,
1053
+ 'other->closing': -1,
1054
+ 'other->opening': 0,
1055
+ 'other->other': 0
1056
+ };
1057
+ _fn = function(ln) {
1058
+ var fromTo, j, key, padding, type, types, value;
1059
+ types = {
1060
+ single: Boolean(ln.match(/<.+\/>/)),
1061
+ closing: Boolean(ln.match(/<\/.+>/)),
1062
+ opening: Boolean(ln.match(/<[^!?].*>/))
1063
+ };
1064
+ type = ((function() {
1065
+ var _results;
1066
+ _results = [];
1067
+ for (key in types) {
1068
+ value = types[key];
1069
+ if (value) {
1070
+ _results.push(key);
1071
+ }
1072
+ }
1073
+ return _results;
1074
+ })())[0];
1075
+ type = type === void 0 ? 'other' : type;
1076
+ fromTo = lastType + '->' + type;
1077
+ lastType = type;
1078
+ padding = '';
1079
+ indent += transitions[fromTo];
1080
+ padding = ((function() {
1081
+ var _j, _ref5, _results;
1082
+ _results = [];
1083
+ for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
1084
+ _results.push(' ');
1085
+ }
1086
+ return _results;
1087
+ })()).join('');
1088
+ if (fromTo === 'opening->closing') {
1089
+ return formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
1090
+ } else {
1091
+ return formatted += padding + ln + '\n';
1092
+ }
1093
+ };
1094
+ for (_i = 0, _len = lines.length; _i < _len; _i++) {
1095
+ ln = lines[_i];
1096
+ _fn(ln);
1097
+ }
1098
+ return formatted;
1099
+ };
1100
+
1101
+ var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) {
1102
+ var _this = this;
1103
+ var errors = [];
1104
+ this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
1105
+ this.type = (type||errors.push("SwaggerRequest type is required (get/post/put/delete/patch/options)."));
1106
+ this.url = (url||errors.push("SwaggerRequest url is required."));
1107
+ this.params = params;
1108
+ this.opts = opts;
1109
+ this.successCallback = (successCallback||errors.push("SwaggerRequest successCallback is required."));
1110
+ this.errorCallback = (errorCallback||errors.push("SwaggerRequest error callback is required."));
1111
+ this.operation = (operation||errors.push("SwaggerRequest operation is required."));
1112
+ this.execution = execution;
1113
+ this.headers = (params.headers||{});
1114
+
1115
+ if(errors.length > 0) {
1116
+ throw errors;
1117
+ }
1118
+
1119
+ this.type = this.type.toUpperCase();
1120
+
1121
+ // set request, response content type headers
1122
+ var headers = this.setHeaders(params, this.operation);
1123
+ var body = params.body;
1124
+
1125
+ // encode the body for form submits
1126
+ if (headers["Content-Type"]) {
1127
+ var values = {};
1128
+ var i;
1129
+ var operationParams = this.operation.parameters;
1130
+ for(i = 0; i < operationParams.length; i++) {
1131
+ var param = operationParams[i];
1132
+ if(param.paramType === "form")
1133
+ values[param.name] = param;
1134
+ }
1135
+
1136
+ if(headers["Content-Type"].indexOf("application/x-www-form-urlencoded") === 0) {
1137
+ var encoded = "";
1138
+ var key;
1139
+ for(key in values) {
1140
+ value = this.params[key];
1141
+ if(typeof value !== 'undefined'){
1142
+ if(encoded !== "")
1143
+ encoded += "&";
1144
+ encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
1145
+ }
1146
+ }
1147
+ body = encoded;
1148
+ }
1149
+ else if (headers["Content-Type"].indexOf("multipart/form-data") === 0) {
1150
+ // encode the body for form submits
1151
+ var data = "";
1152
+ var boundary = "----SwaggerFormBoundary" + Date.now();
1153
+ var key;
1154
+ for(key in values) {
1155
+ value = this.params[key];
1156
+ if(typeof value !== 'undefined') {
1157
+ data += '--' + boundary + '\n';
1158
+ data += 'Content-Disposition: form-data; name="' + key + '"';
1159
+ data += '\n\n';
1160
+ data += value + "\n";
1161
+ }
1162
+ }
1163
+ data += "--" + boundary + "--\n";
1164
+ headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
1165
+ body = data;
1166
+ }
1167
+ }
1168
+
1169
+ if (!((this.headers != null) && (this.headers.mock != null))) {
1170
+ obj = {
1171
+ url: this.url,
1172
+ method: this.type,
1173
+ headers: headers,
1174
+ body: body,
1175
+ useJQuery: this.useJQuery,
1176
+ on: {
1177
+ error: function(response) {
1178
+ return _this.errorCallback(response, _this.opts.parent);
1179
+ },
1180
+ redirect: function(response) {
1181
+ return _this.successCallback(response, _this.opts.parent);
1182
+ },
1183
+ 307: function(response) {
1184
+ return _this.successCallback(response, _this.opts.parent);
1185
+ },
1186
+ response: function(response) {
1187
+ return _this.successCallback(response, _this.opts.parent);
1188
+ }
1189
+ }
1190
+ };
1191
+ var e;
1192
+ if (typeof window !== 'undefined') {
1193
+ e = window;
1194
+ } else {
1195
+ e = exports;
1196
+ }
1197
+ status = e.authorizations.apply(obj, this.operation.authorizations);
1198
+ if (opts.mock == null) {
1199
+ if (status !== false) {
1200
+ new SwaggerHttp().execute(obj);
1201
+ } else {
1202
+ obj.canceled = true;
1203
+ }
1204
+ } else {
1205
+ return obj;
1206
+ }
1207
+ }
1208
+ };
1209
+
1210
+ SwaggerRequest.prototype.setHeaders = function(params, operation) {
1211
+ // default type
1212
+ var accepts = "application/json";
1213
+ var consumes = "application/json";
1214
+
1215
+ var allDefinedParams = this.operation.parameters;
1216
+ var definedFormParams = [];
1217
+ var definedFileParams = [];
1218
+ var body = params.body;
1219
+ var headers = {};
1220
+
1221
+ // get params from the operation and set them in definedFileParams, definedFormParams, headers
1222
+ var i;
1223
+ for(i = 0; i < allDefinedParams.length; i++) {
1224
+ var param = allDefinedParams[i];
1225
+ if(param.paramType === "form")
1226
+ definedFormParams.push(param);
1227
+ else if(param.paramType === "file")
1228
+ definedFileParams.push(param);
1229
+ else if(param.paramType === "header" && this.params.headers) {
1230
+ var key = param.name;
1231
+ var headerValue = this.params.headers[param.name];
1232
+ if(typeof this.params.headers[param.name] !== 'undefined')
1233
+ headers[key] = headerValue;
1234
+ }
1235
+ }
1236
+
1237
+ // if there's a body, need to set the accepts header via requestContentType
1238
+ if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH" || this.type === "DELETE")) {
1239
+ if (this.opts.requestContentType)
1240
+ consumes = this.opts.requestContentType;
1241
+ } else {
1242
+ // if any form params, content type must be set
1243
+ if(definedFormParams.length > 0) {
1244
+ if(definedFileParams.length > 0)
1245
+ consumes = "multipart/form-data";
1246
+ else
1247
+ consumes = "application/x-www-form-urlencoded";
1248
+ }
1249
+ else if (this.type === "DELETE")
1250
+ body = "{}";
1251
+ else if (this.type != "DELETE")
1252
+ accepts = null;
1253
+ }
1254
+
1255
+ if (consumes && this.operation.consumes) {
1256
+ if (this.operation.consumes.indexOf(consumes) === -1) {
1257
+ log("server doesn't consume " + consumes + ", try " + JSON.stringify(this.operation.consumes));
1258
+ consumes = this.operation.consumes[0];
1259
+ }
1260
+ }
1261
+
1262
+ if (this.opts.responseContentType) {
1263
+ accepts = this.opts.responseContentType;
1264
+ } else {
1265
+ accepts = "application/json";
1266
+ }
1267
+ if (accepts && this.operation.produces) {
1268
+ if (this.operation.produces.indexOf(accepts) === -1) {
1269
+ log("server can't produce " + accepts);
1270
+ accepts = this.operation.produces[0];
1271
+ }
1272
+ }
1273
+
1274
+ if ((consumes && body !== "") || (consumes === "application/x-www-form-urlencoded"))
1275
+ headers["Content-Type"] = consumes;
1276
+ if (accepts)
1277
+ headers["Accept"] = accepts;
1278
+ return headers;
1279
+ }
1280
+
1281
+ SwaggerRequest.prototype.asCurl = function() {
1282
+ var results = [];
1283
+ if(this.headers) {
1284
+ var key;
1285
+ for(key in this.headers) {
1286
+ results.push("--header \"" + key + ": " + this.headers[v] + "\"");
1287
+ }
1288
+ }
1289
+ return "curl " + (results.join(" ")) + " " + this.url;
1290
+ };
1291
+
1292
+ /**
1293
+ * SwaggerHttp is a wrapper for executing requests
1294
+ */
1295
+ var SwaggerHttp = function() {};
1296
+
1297
+ SwaggerHttp.prototype.execute = function(obj) {
1298
+ if(obj && (typeof obj.useJQuery === 'boolean'))
1299
+ this.useJQuery = obj.useJQuery;
1300
+ else
1301
+ this.useJQuery = this.isIE8();
1302
+
1303
+ if(this.useJQuery)
1304
+ return new JQueryHttpClient().execute(obj);
1305
+ else
1306
+ return new ShredHttpClient().execute(obj);
1307
+ }
1308
+
1309
+ SwaggerHttp.prototype.isIE8 = function() {
1310
+ var detectedIE = false;
1311
+ if (typeof navigator !== 'undefined' && navigator.userAgent) {
1312
+ nav = navigator.userAgent.toLowerCase();
1313
+ if (nav.indexOf('msie') !== -1) {
1314
+ var version = parseInt(nav.split('msie')[1]);
1315
+ if (version <= 8) {
1316
+ detectedIE = true;
1317
+ }
1318
+ }
1319
+ }
1320
+ return detectedIE;
1321
+ };
1322
+
1323
+ /*
1324
+ * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
1325
+ * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
1326
+ * Since we are using closures here we need to alias it for internal use.
1327
+ */
1328
+ var JQueryHttpClient = function(options) {
1329
+ "use strict";
1330
+ if(!jQuery){
1331
+ var jQuery = window.jQuery;
1332
+ }
1333
+ }
1334
+
1335
+ JQueryHttpClient.prototype.execute = function(obj) {
1336
+ var cb = obj.on;
1337
+ var request = obj;
1338
+
1339
+ obj.type = obj.method;
1340
+ obj.cache = false;
1341
+
1342
+ obj.beforeSend = function(xhr) {
1343
+ var key, results;
1344
+ if (obj.headers) {
1345
+ results = [];
1346
+ var key;
1347
+ for (key in obj.headers) {
1348
+ if (key.toLowerCase() === "content-type") {
1349
+ results.push(obj.contentType = obj.headers[key]);
1350
+ } else if (key.toLowerCase() === "accept") {
1351
+ results.push(obj.accepts = obj.headers[key]);
1352
+ } else {
1353
+ results.push(xhr.setRequestHeader(key, obj.headers[key]));
1354
+ }
1355
+ }
1356
+ return results;
1357
+ }
1358
+ };
1359
+
1360
+ obj.data = obj.body;
1361
+ obj.complete = function(response, textStatus, opts) {
1362
+ var headers = {},
1363
+ headerArray = response.getAllResponseHeaders().split("\n");
1364
+
1365
+ for(var i = 0; i < headerArray.length; i++) {
1366
+ var toSplit = headerArray[i].trim();
1367
+ if(toSplit.length === 0)
1368
+ continue;
1369
+ var separator = toSplit.indexOf(":");
1370
+ if(separator === -1) {
1371
+ // Name but no value in the header
1372
+ headers[toSplit] = null;
1373
+ continue;
1374
+ }
1375
+ var name = toSplit.substring(0, separator).trim(),
1376
+ value = toSplit.substring(separator + 1).trim();
1377
+ headers[name] = value;
1378
+ }
1379
+
1380
+ var out = {
1381
+ url: request.url,
1382
+ method: request.method,
1383
+ status: response.status,
1384
+ data: response.responseText,
1385
+ headers: headers
1386
+ };
1387
+
1388
+ var contentType = (headers["content-type"]||headers["Content-Type"]||null)
1389
+
1390
+ if(contentType != null) {
1391
+ if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1392
+ if(response.responseText && response.responseText !== "")
1393
+ out.obj = JSON.parse(response.responseText);
1394
+ else
1395
+ out.obj = {}
1396
+ }
1397
+ }
1398
+
1399
+ if(response.status >= 200 && response.status < 300)
1400
+ cb.response(out);
1401
+ else if(response.status === 0 || (response.status >= 400 && response.status < 599))
1402
+ cb.error(out);
1403
+ else
1404
+ return cb.response(out);
1405
+ };
1406
+
1407
+ jQuery.support.cors = true;
1408
+ return jQuery.ajax(obj);
1409
+ }
1410
+
1411
+ /*
1412
+ * ShredHttpClient is a light-weight, node or browser HTTP client
1413
+ */
1414
+ var ShredHttpClient = function(options) {
1415
+ this.options = (options||{});
1416
+ this.isInitialized = false;
1417
+
1418
+ var identity, toString;
1419
+
1420
+ if (typeof window !== 'undefined') {
1421
+ this.Shred = require("./shred");
1422
+ this.content = require("./shred/content");
1423
+ }
1424
+ else
1425
+ this.Shred = require("shred");
1426
+ this.shred = new this.Shred();
1427
+ }
1428
+
1429
+ ShredHttpClient.prototype.initShred = function () {
1430
+ this.isInitialized = true;
1431
+ this.registerProcessors(this.shred);
1432
+ }
1433
+
1434
+ ShredHttpClient.prototype.registerProcessors = function(shred) {
1435
+ var identity = function(x) {
1436
+ return x;
1437
+ };
1438
+ var toString = function(x) {
1439
+ return x.toString();
1440
+ };
1441
+
1442
+ if (typeof window !== 'undefined') {
1443
+ this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1444
+ parser: identity,
1445
+ stringify: toString
1446
+ });
1447
+ } else {
1448
+ this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1449
+ parser: identity,
1450
+ stringify: toString
1451
+ });
1452
+ }
1453
+ }
1454
+
1455
+ ShredHttpClient.prototype.execute = function(obj) {
1456
+ if(!this.isInitialized)
1457
+ this.initShred();
1458
+
1459
+ var cb = obj.on, res;
1460
+
1461
+ var transform = function(response) {
1462
+ var out = {
1463
+ headers: response._headers,
1464
+ url: response.request.url,
1465
+ method: response.request.method,
1466
+ status: response.status,
1467
+ data: response.content.data
1468
+ };
1469
+
1470
+ var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null)
1471
+
1472
+ if(contentType != null) {
1473
+ if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1474
+ if(response.content.data && response.content.data !== "")
1475
+ out.obj = JSON.parse(response.content.data);
1476
+ else
1477
+ out.obj = {}
1478
+ }
1479
+ }
1480
+ return out;
1481
+ };
1482
+
1483
+ // Transform an error into a usable response-like object
1484
+ var transformError = function(error) {
1485
+ var out = {
1486
+ // Default to a status of 0 - The client will treat this as a generic permissions sort of error
1487
+ status: 0,
1488
+ data: error.message || error
1489
+ };
1490
+
1491
+ if(error.code) {
1492
+ out.obj = error;
1493
+
1494
+ if(error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED' ) {
1495
+ // We can tell the client that this should be treated as a missing resource and not as a permissions thing
1496
+ out.status = 404;
1497
+ }
1498
+ }
1499
+
1500
+ return out;
1501
+ };
1502
+
1503
+ res = {
1504
+ error: function(response) {
1505
+ if (obj)
1506
+ return cb.error(transform(response));
1507
+ },
1508
+ // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming)
1509
+ request_error: function(err) {
1510
+ if(obj)
1511
+ return cb.error(transformError(err));
1512
+ },
1513
+ redirect: function(response) {
1514
+ if (obj)
1515
+ return cb.redirect(transform(response));
1516
+ },
1517
+ 307: function(response) {
1518
+ if (obj)
1519
+ return cb.redirect(transform(response));
1520
+ },
1521
+ response: function(response) {
1522
+ if (obj)
1523
+ return cb.response(transform(response));
1524
+ }
1525
+ };
1526
+ if (obj) {
1527
+ obj.on = res;
1528
+ }
1529
+ return this.shred.request(obj);
1530
+ };
1531
+
1532
+ /**
1533
+ * SwaggerAuthorizations applys the correct authorization to an operation being executed
1534
+ */
1535
+ var SwaggerAuthorizations = function() {
1536
+ this.authz = {};
1537
+ };
1538
+
1539
+ SwaggerAuthorizations.prototype.add = function(name, auth) {
1540
+ this.authz[name] = auth;
1541
+ return auth;
1542
+ };
1543
+
1544
+ SwaggerAuthorizations.prototype.remove = function(name) {
1545
+ return delete this.authz[name];
1546
+ };
1547
+
1548
+ SwaggerAuthorizations.prototype.apply = function(obj, authorizations) {
1549
+ var status = null;
1550
+ var key;
1551
+
1552
+ // if the "authorizations" key is undefined, or has an empty array, add all keys
1553
+ if(typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) {
1554
+ for (key in this.authz) {
1555
+ value = this.authz[key];
1556
+ result = value.apply(obj, authorizations);
1557
+ if (result === true)
1558
+ status = true;
1559
+ }
1560
+ }
1561
+ else {
1562
+ for(name in authorizations) {
1563
+ for (key in this.authz) {
1564
+ if(key == name) {
1565
+ value = this.authz[key];
1566
+ result = value.apply(obj, authorizations);
1567
+ if (result === true)
1568
+ status = true;
1569
+ }
1570
+ }
1571
+ }
1572
+ }
1573
+
1574
+ return status;
1575
+ };
1576
+
1577
+ /**
1578
+ * ApiKeyAuthorization allows a query param or header to be injected
1579
+ */
1580
+ var ApiKeyAuthorization = function(name, value, type, delimiter) {
1581
+ this.name = name;
1582
+ this.value = value;
1583
+ this.type = type;
1584
+ this.delimiter = delimiter;
1585
+ };
1586
+
1587
+ ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
1588
+ if (this.type === "query") {
1589
+ if (obj.url.indexOf('?') > 0)
1590
+ obj.url = obj.url + "&" + this.name + "=" + this.value;
1591
+ else
1592
+ obj.url = obj.url + "?" + this.name + "=" + this.value;
1593
+ return true;
1594
+ } else if (this.type === "header") {
1595
+ if(typeof obj.headers[this.name] !== 'undefined') {
1596
+ if(typeof this.delimiter !== 'undefined')
1597
+ obj.headers[this.name] = obj.headers[this.name] + this.delimiter + this.value;
1598
+ }
1599
+ else
1600
+ obj.headers[this.name] = this.value;
1601
+ return true;
1602
+ }
1603
+ };
1604
+
1605
+ var CookieAuthorization = function(cookie) {
1606
+ this.cookie = cookie;
1607
+ }
1608
+
1609
+ CookieAuthorization.prototype.apply = function(obj, authorizations) {
1610
+ obj.cookieJar = obj.cookieJar || CookieJar();
1611
+ obj.cookieJar.setCookie(this.cookie);
1612
+ return true;
1613
+ }
1614
+
1615
+ /**
1616
+ * Password Authorization is a basic auth implementation
1617
+ */
1618
+ var PasswordAuthorization = function(name, username, password) {
1619
+ this.name = name;
1620
+ this.username = username;
1621
+ this.password = password;
1622
+ this._btoa = null;
1623
+ if (typeof window !== 'undefined')
1624
+ this._btoa = btoa;
1625
+ else
1626
+ this._btoa = require("btoa");
1627
+ };
1628
+
1629
+ PasswordAuthorization.prototype.apply = function(obj, authorizations) {
1630
+ var base64encoder = this._btoa;
1631
+ obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
1632
+ return true;
1633
+ };
1634
+
1635
+ var e = (typeof window !== 'undefined' ? window : exports);
1636
+
1637
+ var sampleModels = {};
1638
+ var cookies = {};
1639
+
1640
+ e.SampleModels = sampleModels;
1641
+ e.SwaggerHttp = SwaggerHttp;
1642
+ e.SwaggerRequest = SwaggerRequest;
1643
+ e.authorizations = new SwaggerAuthorizations();
1644
+ e.ApiKeyAuthorization = ApiKeyAuthorization;
1645
+ e.PasswordAuthorization = PasswordAuthorization;
1646
+ e.CookieAuthorization = CookieAuthorization;
1647
+ e.JQueryHttpClient = JQueryHttpClient;
1648
+ e.ShredHttpClient = ShredHttpClient;
1649
+ e.SwaggerOperation = SwaggerOperation;
1650
+ e.SwaggerModel = SwaggerModel;
1651
+ e.SwaggerModelProperty = SwaggerModelProperty;
1652
+ e.SwaggerResource = SwaggerResource;
1653
+ e.SwaggerApi = SwaggerApi;