UNPKG

401 kBJavaScriptView Raw
1(function webpackUniversalModuleDefinition(root, factory) {
2 if(typeof exports === 'object' && typeof module === 'object')
3 module.exports = factory();
4 else if(typeof define === 'function' && define.amd)
5 define([], factory);
6 else if(typeof exports === 'object')
7 exports["AWS"] = factory();
8 else
9 root["AWS"] = factory();
10})(this, function() {
11return /******/ (function(modules) { // webpackBootstrap
12/******/ // The module cache
13/******/ var installedModules = {};
14
15/******/ // The require function
16/******/ function __webpack_require__(moduleId) {
17
18/******/ // Check if module is in cache
19/******/ if(installedModules[moduleId])
20/******/ return installedModules[moduleId].exports;
21
22/******/ // Create a new module (and put it into the cache)
23/******/ var module = installedModules[moduleId] = {
24/******/ exports: {},
25/******/ id: moduleId,
26/******/ loaded: false
27/******/ };
28
29/******/ // Execute the module function
30/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31
32/******/ // Flag the module as loaded
33/******/ module.loaded = true;
34
35/******/ // Return the exports of the module
36/******/ return module.exports;
37/******/ }
38
39
40/******/ // expose the modules object (__webpack_modules__)
41/******/ __webpack_require__.m = modules;
42
43/******/ // expose the module cache
44/******/ __webpack_require__.c = installedModules;
45
46/******/ // __webpack_public_path__
47/******/ __webpack_require__.p = "";
48
49/******/ // Load entry module and return exports
50/******/ return __webpack_require__(0);
51/******/ })
52/************************************************************************/
53/******/ ([
54/* 0 */
55/***/ (function(module, exports, __webpack_require__) {
56
57 module.exports = __webpack_require__(1);
58
59
60/***/ }),
61/* 1 */
62/***/ (function(module, exports, __webpack_require__) {
63
64 /**
65 * The main AWS namespace
66 */
67 var AWS = { util: __webpack_require__(2) };
68
69 /**
70 * @api private
71 * @!macro [new] nobrowser
72 * @note This feature is not supported in the browser environment of the SDK.
73 */
74 var _hidden = {}; _hidden.toString(); // hack to parse macro
75
76 /**
77 * @api private
78 */
79 module.exports = AWS;
80
81 AWS.util.update(AWS, {
82
83 /**
84 * @constant
85 */
86 VERSION: '2.426.0',
87
88 /**
89 * @api private
90 */
91 Signers: {},
92
93 /**
94 * @api private
95 */
96 Protocol: {
97 Json: __webpack_require__(13),
98 Query: __webpack_require__(17),
99 Rest: __webpack_require__(21),
100 RestJson: __webpack_require__(22),
101 RestXml: __webpack_require__(23)
102 },
103
104 /**
105 * @api private
106 */
107 XML: {
108 Builder: __webpack_require__(24),
109 Parser: null // conditionally set based on environment
110 },
111
112 /**
113 * @api private
114 */
115 JSON: {
116 Builder: __webpack_require__(14),
117 Parser: __webpack_require__(15)
118 },
119
120 /**
121 * @api private
122 */
123 Model: {
124 Api: __webpack_require__(29),
125 Operation: __webpack_require__(30),
126 Shape: __webpack_require__(19),
127 Paginator: __webpack_require__(31),
128 ResourceWaiter: __webpack_require__(32)
129 },
130
131 /**
132 * @api private
133 */
134 apiLoader: __webpack_require__(33),
135
136 /**
137 * @api private
138 */
139 EndpointCache: __webpack_require__(34).EndpointCache
140 });
141 __webpack_require__(36);
142 __webpack_require__(37);
143 __webpack_require__(40);
144 __webpack_require__(43);
145 __webpack_require__(44);
146 __webpack_require__(49);
147 __webpack_require__(52);
148 __webpack_require__(53);
149 __webpack_require__(54);
150 __webpack_require__(62);
151
152 /**
153 * @readonly
154 * @return [AWS.SequentialExecutor] a collection of global event listeners that
155 * are attached to every sent request.
156 * @see AWS.Request AWS.Request for a list of events to listen for
157 * @example Logging the time taken to send a request
158 * AWS.events.on('send', function startSend(resp) {
159 * resp.startTime = new Date().getTime();
160 * }).on('complete', function calculateTime(resp) {
161 * var time = (new Date().getTime() - resp.startTime) / 1000;
162 * console.log('Request took ' + time + ' seconds');
163 * });
164 *
165 * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds'
166 */
167 AWS.events = new AWS.SequentialExecutor();
168
169 //create endpoint cache lazily
170 AWS.util.memoizedProperty(AWS, 'endpointCache', function() {
171 return new AWS.EndpointCache(AWS.config.endpointCacheSize);
172 }, true);
173
174
175/***/ }),
176/* 2 */
177/***/ (function(module, exports, __webpack_require__) {
178
179 /* WEBPACK VAR INJECTION */(function(process, setImmediate) {/* eslint guard-for-in:0 */
180 var AWS;
181
182 /**
183 * A set of utility methods for use with the AWS SDK.
184 *
185 * @!attribute abort
186 * Return this value from an iterator function {each} or {arrayEach}
187 * to break out of the iteration.
188 * @example Breaking out of an iterator function
189 * AWS.util.each({a: 1, b: 2, c: 3}, function(key, value) {
190 * if (key == 'b') return AWS.util.abort;
191 * });
192 * @see each
193 * @see arrayEach
194 * @api private
195 */
196 var util = {
197 environment: 'nodejs',
198 engine: function engine() {
199 if (util.isBrowser() && typeof navigator !== 'undefined') {
200 return navigator.userAgent;
201 } else {
202 var engine = process.platform + '/' + process.version;
203 if (process.env.AWS_EXECUTION_ENV) {
204 engine += ' exec-env/' + process.env.AWS_EXECUTION_ENV;
205 }
206 return engine;
207 }
208 },
209
210 userAgent: function userAgent() {
211 var name = util.environment;
212 var agent = 'aws-sdk-' + name + '/' + __webpack_require__(1).VERSION;
213 if (name === 'nodejs') agent += ' ' + util.engine();
214 return agent;
215 },
216
217 uriEscape: function uriEscape(string) {
218 var output = encodeURIComponent(string);
219 output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape);
220
221 // AWS percent-encodes some extra non-standard characters in a URI
222 output = output.replace(/[*]/g, function(ch) {
223 return '%' + ch.charCodeAt(0).toString(16).toUpperCase();
224 });
225
226 return output;
227 },
228
229 uriEscapePath: function uriEscapePath(string) {
230 var parts = [];
231 util.arrayEach(string.split('/'), function (part) {
232 parts.push(util.uriEscape(part));
233 });
234 return parts.join('/');
235 },
236
237 urlParse: function urlParse(url) {
238 return util.url.parse(url);
239 },
240
241 urlFormat: function urlFormat(url) {
242 return util.url.format(url);
243 },
244
245 queryStringParse: function queryStringParse(qs) {
246 return util.querystring.parse(qs);
247 },
248
249 queryParamsToString: function queryParamsToString(params) {
250 var items = [];
251 var escape = util.uriEscape;
252 var sortedKeys = Object.keys(params).sort();
253
254 util.arrayEach(sortedKeys, function(name) {
255 var value = params[name];
256 var ename = escape(name);
257 var result = ename + '=';
258 if (Array.isArray(value)) {
259 var vals = [];
260 util.arrayEach(value, function(item) { vals.push(escape(item)); });
261 result = ename + '=' + vals.sort().join('&' + ename + '=');
262 } else if (value !== undefined && value !== null) {
263 result = ename + '=' + escape(value);
264 }
265 items.push(result);
266 });
267
268 return items.join('&');
269 },
270
271 readFileSync: function readFileSync(path) {
272 if (util.isBrowser()) return null;
273 return __webpack_require__(6).readFileSync(path, 'utf-8');
274 },
275
276 base64: {
277 encode: function encode64(string) {
278 if (typeof string === 'number') {
279 throw util.error(new Error('Cannot base64 encode number ' + string));
280 }
281 if (string === null || typeof string === 'undefined') {
282 return string;
283 }
284 var buf = (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(string) : new util.Buffer(string);
285 return buf.toString('base64');
286 },
287
288 decode: function decode64(string) {
289 if (typeof string === 'number') {
290 throw util.error(new Error('Cannot base64 decode number ' + string));
291 }
292 if (string === null || typeof string === 'undefined') {
293 return string;
294 }
295 return (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(string, 'base64') : new util.Buffer(string, 'base64');
296 }
297
298 },
299
300 buffer: {
301 toStream: function toStream(buffer) {
302 if (!util.Buffer.isBuffer(buffer)) buffer = new util.Buffer(buffer);
303
304 var readable = new (util.stream.Readable)();
305 var pos = 0;
306 readable._read = function(size) {
307 if (pos >= buffer.length) return readable.push(null);
308
309 var end = pos + size;
310 if (end > buffer.length) end = buffer.length;
311 readable.push(buffer.slice(pos, end));
312 pos = end;
313 };
314
315 return readable;
316 },
317
318 /**
319 * Concatenates a list of Buffer objects.
320 */
321 concat: function(buffers) {
322 var length = 0,
323 offset = 0,
324 buffer = null, i;
325
326 for (i = 0; i < buffers.length; i++) {
327 length += buffers[i].length;
328 }
329
330 buffer = new util.Buffer(length);
331
332 for (i = 0; i < buffers.length; i++) {
333 buffers[i].copy(buffer, offset);
334 offset += buffers[i].length;
335 }
336
337 return buffer;
338 }
339 },
340
341 string: {
342 byteLength: function byteLength(string) {
343 if (string === null || string === undefined) return 0;
344 if (typeof string === 'string') string = new util.Buffer(string);
345
346 if (typeof string.byteLength === 'number') {
347 return string.byteLength;
348 } else if (typeof string.length === 'number') {
349 return string.length;
350 } else if (typeof string.size === 'number') {
351 return string.size;
352 } else if (typeof string.path === 'string') {
353 return __webpack_require__(6).lstatSync(string.path).size;
354 } else {
355 throw util.error(new Error('Cannot determine length of ' + string),
356 { object: string });
357 }
358 },
359
360 upperFirst: function upperFirst(string) {
361 return string[0].toUpperCase() + string.substr(1);
362 },
363
364 lowerFirst: function lowerFirst(string) {
365 return string[0].toLowerCase() + string.substr(1);
366 }
367 },
368
369 ini: {
370 parse: function string(ini) {
371 var currentSection, map = {};
372 util.arrayEach(ini.split(/\r?\n/), function(line) {
373 line = line.split(/(^|\s)[;#]/)[0]; // remove comments
374 var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/);
375 if (section) {
376 currentSection = section[1];
377 } else if (currentSection) {
378 var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/);
379 if (item) {
380 map[currentSection] = map[currentSection] || {};
381 map[currentSection][item[1]] = item[2];
382 }
383 }
384 });
385
386 return map;
387 }
388 },
389
390 fn: {
391 noop: function() {},
392 callback: function (err) { if (err) throw err; },
393
394 /**
395 * Turn a synchronous function into as "async" function by making it call
396 * a callback. The underlying function is called with all but the last argument,
397 * which is treated as the callback. The callback is passed passed a first argument
398 * of null on success to mimick standard node callbacks.
399 */
400 makeAsync: function makeAsync(fn, expectedArgs) {
401 if (expectedArgs && expectedArgs <= fn.length) {
402 return fn;
403 }
404
405 return function() {
406 var args = Array.prototype.slice.call(arguments, 0);
407 var callback = args.pop();
408 var result = fn.apply(null, args);
409 callback(result);
410 };
411 }
412 },
413
414 /**
415 * Date and time utility functions.
416 */
417 date: {
418
419 /**
420 * @return [Date] the current JavaScript date object. Since all
421 * AWS services rely on this date object, you can override
422 * this function to provide a special time value to AWS service
423 * requests.
424 */
425 getDate: function getDate() {
426 if (!AWS) AWS = __webpack_require__(1);
427 if (AWS.config.systemClockOffset) { // use offset when non-zero
428 return new Date(new Date().getTime() + AWS.config.systemClockOffset);
429 } else {
430 return new Date();
431 }
432 },
433
434 /**
435 * @return [String] the date in ISO-8601 format
436 */
437 iso8601: function iso8601(date) {
438 if (date === undefined) { date = util.date.getDate(); }
439 return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
440 },
441
442 /**
443 * @return [String] the date in RFC 822 format
444 */
445 rfc822: function rfc822(date) {
446 if (date === undefined) { date = util.date.getDate(); }
447 return date.toUTCString();
448 },
449
450 /**
451 * @return [Integer] the UNIX timestamp value for the current time
452 */
453 unixTimestamp: function unixTimestamp(date) {
454 if (date === undefined) { date = util.date.getDate(); }
455 return date.getTime() / 1000;
456 },
457
458 /**
459 * @param [String,number,Date] date
460 * @return [Date]
461 */
462 from: function format(date) {
463 if (typeof date === 'number') {
464 return new Date(date * 1000); // unix timestamp
465 } else {
466 return new Date(date);
467 }
468 },
469
470 /**
471 * Given a Date or date-like value, this function formats the
472 * date into a string of the requested value.
473 * @param [String,number,Date] date
474 * @param [String] formatter Valid formats are:
475 # * 'iso8601'
476 # * 'rfc822'
477 # * 'unixTimestamp'
478 * @return [String]
479 */
480 format: function format(date, formatter) {
481 if (!formatter) formatter = 'iso8601';
482 return util.date[formatter](util.date.from(date));
483 },
484
485 parseTimestamp: function parseTimestamp(value) {
486 if (typeof value === 'number') { // unix timestamp (number)
487 return new Date(value * 1000);
488 } else if (value.match(/^\d+$/)) { // unix timestamp
489 return new Date(value * 1000);
490 } else if (value.match(/^\d{4}/)) { // iso8601
491 return new Date(value);
492 } else if (value.match(/^\w{3},/)) { // rfc822
493 return new Date(value);
494 } else {
495 throw util.error(
496 new Error('unhandled timestamp format: ' + value),
497 {code: 'TimestampParserError'});
498 }
499 }
500
501 },
502
503 crypto: {
504 crc32Table: [
505 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
506 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
507 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
508 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
509 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
510 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
511 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
512 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
513 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
514 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
515 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
516 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
517 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
518 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
519 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
520 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
521 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
522 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
523 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
524 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
525 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
526 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
527 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
528 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
529 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
530 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
531 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
532 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
533 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
534 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
535 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
536 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
537 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
538 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
539 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
540 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
541 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
542 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
543 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
544 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
545 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
546 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
547 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
548 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
549 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
550 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
551 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
552 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
553 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
554 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
555 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
556 0x2D02EF8D],
557
558 crc32: function crc32(data) {
559 var tbl = util.crypto.crc32Table;
560 var crc = 0 ^ -1;
561
562 if (typeof data === 'string') {
563 data = new util.Buffer(data);
564 }
565
566 for (var i = 0; i < data.length; i++) {
567 var code = data.readUInt8(i);
568 crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF];
569 }
570 return (crc ^ -1) >>> 0;
571 },
572
573 hmac: function hmac(key, string, digest, fn) {
574 if (!digest) digest = 'binary';
575 if (digest === 'buffer') { digest = undefined; }
576 if (!fn) fn = 'sha256';
577 if (typeof string === 'string') string = new util.Buffer(string);
578 return util.crypto.lib.createHmac(fn, key).update(string).digest(digest);
579 },
580
581 md5: function md5(data, digest, callback) {
582 return util.crypto.hash('md5', data, digest, callback);
583 },
584
585 sha256: function sha256(data, digest, callback) {
586 return util.crypto.hash('sha256', data, digest, callback);
587 },
588
589 hash: function(algorithm, data, digest, callback) {
590 var hash = util.crypto.createHash(algorithm);
591 if (!digest) { digest = 'binary'; }
592 if (digest === 'buffer') { digest = undefined; }
593 if (typeof data === 'string') data = new util.Buffer(data);
594 var sliceFn = util.arraySliceFn(data);
595 var isBuffer = util.Buffer.isBuffer(data);
596 //Identifying objects with an ArrayBuffer as buffers
597 if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true;
598
599 if (callback && typeof data === 'object' &&
600 typeof data.on === 'function' && !isBuffer) {
601 data.on('data', function(chunk) { hash.update(chunk); });
602 data.on('error', function(err) { callback(err); });
603 data.on('end', function() { callback(null, hash.digest(digest)); });
604 } else if (callback && sliceFn && !isBuffer &&
605 typeof FileReader !== 'undefined') {
606 // this might be a File/Blob
607 var index = 0, size = 1024 * 512;
608 var reader = new FileReader();
609 reader.onerror = function() {
610 callback(new Error('Failed to read data.'));
611 };
612 reader.onload = function() {
613 var buf = new util.Buffer(new Uint8Array(reader.result));
614 hash.update(buf);
615 index += buf.length;
616 reader._continueReading();
617 };
618 reader._continueReading = function() {
619 if (index >= data.size) {
620 callback(null, hash.digest(digest));
621 return;
622 }
623
624 var back = index + size;
625 if (back > data.size) back = data.size;
626 reader.readAsArrayBuffer(sliceFn.call(data, index, back));
627 };
628
629 reader._continueReading();
630 } else {
631 if (util.isBrowser() && typeof data === 'object' && !isBuffer) {
632 data = new util.Buffer(new Uint8Array(data));
633 }
634 var out = hash.update(data).digest(digest);
635 if (callback) callback(null, out);
636 return out;
637 }
638 },
639
640 toHex: function toHex(data) {
641 var out = [];
642 for (var i = 0; i < data.length; i++) {
643 out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2));
644 }
645 return out.join('');
646 },
647
648 createHash: function createHash(algorithm) {
649 return util.crypto.lib.createHash(algorithm);
650 }
651
652 },
653
654 /** @!ignore */
655
656 /* Abort constant */
657 abort: {},
658
659 each: function each(object, iterFunction) {
660 for (var key in object) {
661 if (Object.prototype.hasOwnProperty.call(object, key)) {
662 var ret = iterFunction.call(this, key, object[key]);
663 if (ret === util.abort) break;
664 }
665 }
666 },
667
668 arrayEach: function arrayEach(array, iterFunction) {
669 for (var idx in array) {
670 if (Object.prototype.hasOwnProperty.call(array, idx)) {
671 var ret = iterFunction.call(this, array[idx], parseInt(idx, 10));
672 if (ret === util.abort) break;
673 }
674 }
675 },
676
677 update: function update(obj1, obj2) {
678 util.each(obj2, function iterator(key, item) {
679 obj1[key] = item;
680 });
681 return obj1;
682 },
683
684 merge: function merge(obj1, obj2) {
685 return util.update(util.copy(obj1), obj2);
686 },
687
688 copy: function copy(object) {
689 if (object === null || object === undefined) return object;
690 var dupe = {};
691 // jshint forin:false
692 for (var key in object) {
693 dupe[key] = object[key];
694 }
695 return dupe;
696 },
697
698 isEmpty: function isEmpty(obj) {
699 for (var prop in obj) {
700 if (Object.prototype.hasOwnProperty.call(obj, prop)) {
701 return false;
702 }
703 }
704 return true;
705 },
706
707 arraySliceFn: function arraySliceFn(obj) {
708 var fn = obj.slice || obj.webkitSlice || obj.mozSlice;
709 return typeof fn === 'function' ? fn : null;
710 },
711
712 isType: function isType(obj, type) {
713 // handle cross-"frame" objects
714 if (typeof type === 'function') type = util.typeName(type);
715 return Object.prototype.toString.call(obj) === '[object ' + type + ']';
716 },
717
718 typeName: function typeName(type) {
719 if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name;
720 var str = type.toString();
721 var match = str.match(/^\s*function (.+)\(/);
722 return match ? match[1] : str;
723 },
724
725 error: function error(err, options) {
726 var originalError = null;
727 if (typeof err.message === 'string' && err.message !== '') {
728 if (typeof options === 'string' || (options && options.message)) {
729 originalError = util.copy(err);
730 originalError.message = err.message;
731 }
732 }
733 err.message = err.message || null;
734
735 if (typeof options === 'string') {
736 err.message = options;
737 } else if (typeof options === 'object' && options !== null) {
738 util.update(err, options);
739 if (options.message)
740 err.message = options.message;
741 if (options.code || options.name)
742 err.code = options.code || options.name;
743 if (options.stack)
744 err.stack = options.stack;
745 }
746
747 if (typeof Object.defineProperty === 'function') {
748 Object.defineProperty(err, 'name', {writable: true, enumerable: false});
749 Object.defineProperty(err, 'message', {enumerable: true});
750 }
751
752 err.name = options && options.name || err.name || err.code || 'Error';
753 err.time = new Date();
754
755 if (originalError) err.originalError = originalError;
756
757 return err;
758 },
759
760 /**
761 * @api private
762 */
763 inherit: function inherit(klass, features) {
764 var newObject = null;
765 if (features === undefined) {
766 features = klass;
767 klass = Object;
768 newObject = {};
769 } else {
770 var ctor = function ConstructorWrapper() {};
771 ctor.prototype = klass.prototype;
772 newObject = new ctor();
773 }
774
775 // constructor not supplied, create pass-through ctor
776 if (features.constructor === Object) {
777 features.constructor = function() {
778 if (klass !== Object) {
779 return klass.apply(this, arguments);
780 }
781 };
782 }
783
784 features.constructor.prototype = newObject;
785 util.update(features.constructor.prototype, features);
786 features.constructor.__super__ = klass;
787 return features.constructor;
788 },
789
790 /**
791 * @api private
792 */
793 mixin: function mixin() {
794 var klass = arguments[0];
795 for (var i = 1; i < arguments.length; i++) {
796 // jshint forin:false
797 for (var prop in arguments[i].prototype) {
798 var fn = arguments[i].prototype[prop];
799 if (prop !== 'constructor') {
800 klass.prototype[prop] = fn;
801 }
802 }
803 }
804 return klass;
805 },
806
807 /**
808 * @api private
809 */
810 hideProperties: function hideProperties(obj, props) {
811 if (typeof Object.defineProperty !== 'function') return;
812
813 util.arrayEach(props, function (key) {
814 Object.defineProperty(obj, key, {
815 enumerable: false, writable: true, configurable: true });
816 });
817 },
818
819 /**
820 * @api private
821 */
822 property: function property(obj, name, value, enumerable, isValue) {
823 var opts = {
824 configurable: true,
825 enumerable: enumerable !== undefined ? enumerable : true
826 };
827 if (typeof value === 'function' && !isValue) {
828 opts.get = value;
829 }
830 else {
831 opts.value = value; opts.writable = true;
832 }
833
834 Object.defineProperty(obj, name, opts);
835 },
836
837 /**
838 * @api private
839 */
840 memoizedProperty: function memoizedProperty(obj, name, get, enumerable) {
841 var cachedValue = null;
842
843 // build enumerable attribute for each value with lazy accessor.
844 util.property(obj, name, function() {
845 if (cachedValue === null) {
846 cachedValue = get();
847 }
848 return cachedValue;
849 }, enumerable);
850 },
851
852 /**
853 * TODO Remove in major version revision
854 * This backfill populates response data without the
855 * top-level payload name.
856 *
857 * @api private
858 */
859 hoistPayloadMember: function hoistPayloadMember(resp) {
860 var req = resp.request;
861 var operationName = req.operation;
862 var operation = req.service.api.operations[operationName];
863 var output = operation.output;
864 if (output.payload && !operation.hasEventOutput) {
865 var payloadMember = output.members[output.payload];
866 var responsePayload = resp.data[output.payload];
867 if (payloadMember.type === 'structure') {
868 util.each(responsePayload, function(key, value) {
869 util.property(resp.data, key, value, false);
870 });
871 }
872 }
873 },
874
875 /**
876 * Compute SHA-256 checksums of streams
877 *
878 * @api private
879 */
880 computeSha256: function computeSha256(body, done) {
881 if (util.isNode()) {
882 var Stream = util.stream.Stream;
883 var fs = __webpack_require__(6);
884 if (body instanceof Stream) {
885 if (typeof body.path === 'string') { // assume file object
886 var settings = {};
887 if (typeof body.start === 'number') {
888 settings.start = body.start;
889 }
890 if (typeof body.end === 'number') {
891 settings.end = body.end;
892 }
893 body = fs.createReadStream(body.path, settings);
894 } else { // TODO support other stream types
895 return done(new Error('Non-file stream objects are ' +
896 'not supported with SigV4'));
897 }
898 }
899 }
900
901 util.crypto.sha256(body, 'hex', function(err, sha) {
902 if (err) done(err);
903 else done(null, sha);
904 });
905 },
906
907 /**
908 * @api private
909 */
910 isClockSkewed: function isClockSkewed(serverTime) {
911 if (serverTime) {
912 util.property(AWS.config, 'isClockSkewed',
913 Math.abs(new Date().getTime() - serverTime) >= 300000, false);
914 return AWS.config.isClockSkewed;
915 }
916 },
917
918 applyClockOffset: function applyClockOffset(serverTime) {
919 if (serverTime)
920 AWS.config.systemClockOffset = serverTime - new Date().getTime();
921 },
922
923 /**
924 * @api private
925 */
926 extractRequestId: function extractRequestId(resp) {
927 var requestId = resp.httpResponse.headers['x-amz-request-id'] ||
928 resp.httpResponse.headers['x-amzn-requestid'];
929
930 if (!requestId && resp.data && resp.data.ResponseMetadata) {
931 requestId = resp.data.ResponseMetadata.RequestId;
932 }
933
934 if (requestId) {
935 resp.requestId = requestId;
936 }
937
938 if (resp.error) {
939 resp.error.requestId = requestId;
940 }
941 },
942
943 /**
944 * @api private
945 */
946 addPromises: function addPromises(constructors, PromiseDependency) {
947 var deletePromises = false;
948 if (PromiseDependency === undefined && AWS && AWS.config) {
949 PromiseDependency = AWS.config.getPromisesDependency();
950 }
951 if (PromiseDependency === undefined && typeof Promise !== 'undefined') {
952 PromiseDependency = Promise;
953 }
954 if (typeof PromiseDependency !== 'function') deletePromises = true;
955 if (!Array.isArray(constructors)) constructors = [constructors];
956
957 for (var ind = 0; ind < constructors.length; ind++) {
958 var constructor = constructors[ind];
959 if (deletePromises) {
960 if (constructor.deletePromisesFromClass) {
961 constructor.deletePromisesFromClass();
962 }
963 } else if (constructor.addPromisesToClass) {
964 constructor.addPromisesToClass(PromiseDependency);
965 }
966 }
967 },
968
969 /**
970 * @api private
971 */
972 promisifyMethod: function promisifyMethod(methodName, PromiseDependency) {
973 return function promise() {
974 var self = this;
975 return new PromiseDependency(function(resolve, reject) {
976 self[methodName](function(err, data) {
977 if (err) {
978 reject(err);
979 } else {
980 resolve(data);
981 }
982 });
983 });
984 };
985 },
986
987 /**
988 * @api private
989 */
990 isDualstackAvailable: function isDualstackAvailable(service) {
991 if (!service) return false;
992 var metadata = __webpack_require__(7);
993 if (typeof service !== 'string') service = service.serviceIdentifier;
994 if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false;
995 return !!metadata[service].dualstackAvailable;
996 },
997
998 /**
999 * @api private
1000 */
1001 calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) {
1002 if (!retryDelayOptions) retryDelayOptions = {};
1003 var customBackoff = retryDelayOptions.customBackoff || null;
1004 if (typeof customBackoff === 'function') {
1005 return customBackoff(retryCount);
1006 }
1007 var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100;
1008 var delay = Math.random() * (Math.pow(2, retryCount) * base);
1009 return delay;
1010 },
1011
1012 /**
1013 * @api private
1014 */
1015 handleRequestWithRetries: function handleRequestWithRetries(httpRequest, options, cb) {
1016 if (!options) options = {};
1017 var http = AWS.HttpClient.getInstance();
1018 var httpOptions = options.httpOptions || {};
1019 var retryCount = 0;
1020
1021 var errCallback = function(err) {
1022 var maxRetries = options.maxRetries || 0;
1023 if (err && err.code === 'TimeoutError') err.retryable = true;
1024 if (err && err.retryable && retryCount < maxRetries) {
1025 retryCount++;
1026 var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions);
1027 setTimeout(sendRequest, delay + (err.retryAfter || 0));
1028 } else {
1029 cb(err);
1030 }
1031 };
1032
1033 var sendRequest = function() {
1034 var data = '';
1035 http.handleRequest(httpRequest, httpOptions, function(httpResponse) {
1036 httpResponse.on('data', function(chunk) { data += chunk.toString(); });
1037 httpResponse.on('end', function() {
1038 var statusCode = httpResponse.statusCode;
1039 if (statusCode < 300) {
1040 cb(null, data);
1041 } else {
1042 var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0;
1043 var err = util.error(new Error(),
1044 { retryable: statusCode >= 500 || statusCode === 429 }
1045 );
1046 if (retryAfter && err.retryable) err.retryAfter = retryAfter;
1047 errCallback(err);
1048 }
1049 });
1050 }, errCallback);
1051 };
1052
1053 AWS.util.defer(sendRequest);
1054 },
1055
1056 /**
1057 * @api private
1058 */
1059 uuid: {
1060 v4: function uuidV4() {
1061 return __webpack_require__(8).v4();
1062 }
1063 },
1064
1065 /**
1066 * @api private
1067 */
1068 convertPayloadToString: function convertPayloadToString(resp) {
1069 var req = resp.request;
1070 var operation = req.operation;
1071 var rules = req.service.api.operations[operation].output || {};
1072 if (rules.payload && resp.data[rules.payload]) {
1073 resp.data[rules.payload] = resp.data[rules.payload].toString();
1074 }
1075 },
1076
1077 /**
1078 * @api private
1079 */
1080 defer: function defer(callback) {
1081 if (typeof process === 'object' && typeof process.nextTick === 'function') {
1082 process.nextTick(callback);
1083 } else if (typeof setImmediate === 'function') {
1084 setImmediate(callback);
1085 } else {
1086 setTimeout(callback, 0);
1087 }
1088 },
1089
1090 /**
1091 * @api private
1092 */
1093 defaultProfile: 'default',
1094
1095 /**
1096 * @api private
1097 */
1098 configOptInEnv: 'AWS_SDK_LOAD_CONFIG',
1099
1100 /**
1101 * @api private
1102 */
1103 sharedCredentialsFileEnv: 'AWS_SHARED_CREDENTIALS_FILE',
1104
1105 /**
1106 * @api private
1107 */
1108 sharedConfigFileEnv: 'AWS_CONFIG_FILE',
1109
1110 /**
1111 * @api private
1112 */
1113 imdsDisabledEnv: 'AWS_EC2_METADATA_DISABLED'
1114 };
1115
1116 /**
1117 * @api private
1118 */
1119 module.exports = util;
1120
1121 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(4).setImmediate))
1122
1123/***/ }),
1124/* 3 */
1125/***/ (function(module, exports) {
1126
1127 // shim for using process in browser
1128 var process = module.exports = {};
1129
1130 // cached from whatever global is present so that test runners that stub it
1131 // don't break things. But we need to wrap it in a try catch in case it is
1132 // wrapped in strict mode code which doesn't define any globals. It's inside a
1133 // function because try/catches deoptimize in certain engines.
1134
1135 var cachedSetTimeout;
1136 var cachedClearTimeout;
1137
1138 function defaultSetTimout() {
1139 throw new Error('setTimeout has not been defined');
1140 }
1141 function defaultClearTimeout () {
1142 throw new Error('clearTimeout has not been defined');
1143 }
1144 (function () {
1145 try {
1146 if (typeof setTimeout === 'function') {
1147 cachedSetTimeout = setTimeout;
1148 } else {
1149 cachedSetTimeout = defaultSetTimout;
1150 }
1151 } catch (e) {
1152 cachedSetTimeout = defaultSetTimout;
1153 }
1154 try {
1155 if (typeof clearTimeout === 'function') {
1156 cachedClearTimeout = clearTimeout;
1157 } else {
1158 cachedClearTimeout = defaultClearTimeout;
1159 }
1160 } catch (e) {
1161 cachedClearTimeout = defaultClearTimeout;
1162 }
1163 } ())
1164 function runTimeout(fun) {
1165 if (cachedSetTimeout === setTimeout) {
1166 //normal enviroments in sane situations
1167 return setTimeout(fun, 0);
1168 }
1169 // if setTimeout wasn't available but was latter defined
1170 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
1171 cachedSetTimeout = setTimeout;
1172 return setTimeout(fun, 0);
1173 }
1174 try {
1175 // when when somebody has screwed with setTimeout but no I.E. maddness
1176 return cachedSetTimeout(fun, 0);
1177 } catch(e){
1178 try {
1179 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1180 return cachedSetTimeout.call(null, fun, 0);
1181 } catch(e){
1182 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
1183 return cachedSetTimeout.call(this, fun, 0);
1184 }
1185 }
1186
1187
1188 }
1189 function runClearTimeout(marker) {
1190 if (cachedClearTimeout === clearTimeout) {
1191 //normal enviroments in sane situations
1192 return clearTimeout(marker);
1193 }
1194 // if clearTimeout wasn't available but was latter defined
1195 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
1196 cachedClearTimeout = clearTimeout;
1197 return clearTimeout(marker);
1198 }
1199 try {
1200 // when when somebody has screwed with setTimeout but no I.E. maddness
1201 return cachedClearTimeout(marker);
1202 } catch (e){
1203 try {
1204 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1205 return cachedClearTimeout.call(null, marker);
1206 } catch (e){
1207 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
1208 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
1209 return cachedClearTimeout.call(this, marker);
1210 }
1211 }
1212
1213
1214
1215 }
1216 var queue = [];
1217 var draining = false;
1218 var currentQueue;
1219 var queueIndex = -1;
1220
1221 function cleanUpNextTick() {
1222 if (!draining || !currentQueue) {
1223 return;
1224 }
1225 draining = false;
1226 if (currentQueue.length) {
1227 queue = currentQueue.concat(queue);
1228 } else {
1229 queueIndex = -1;
1230 }
1231 if (queue.length) {
1232 drainQueue();
1233 }
1234 }
1235
1236 function drainQueue() {
1237 if (draining) {
1238 return;
1239 }
1240 var timeout = runTimeout(cleanUpNextTick);
1241 draining = true;
1242
1243 var len = queue.length;
1244 while(len) {
1245 currentQueue = queue;
1246 queue = [];
1247 while (++queueIndex < len) {
1248 if (currentQueue) {
1249 currentQueue[queueIndex].run();
1250 }
1251 }
1252 queueIndex = -1;
1253 len = queue.length;
1254 }
1255 currentQueue = null;
1256 draining = false;
1257 runClearTimeout(timeout);
1258 }
1259
1260 process.nextTick = function (fun) {
1261 var args = new Array(arguments.length - 1);
1262 if (arguments.length > 1) {
1263 for (var i = 1; i < arguments.length; i++) {
1264 args[i - 1] = arguments[i];
1265 }
1266 }
1267 queue.push(new Item(fun, args));
1268 if (queue.length === 1 && !draining) {
1269 runTimeout(drainQueue);
1270 }
1271 };
1272
1273 // v8 likes predictible objects
1274 function Item(fun, array) {
1275 this.fun = fun;
1276 this.array = array;
1277 }
1278 Item.prototype.run = function () {
1279 this.fun.apply(null, this.array);
1280 };
1281 process.title = 'browser';
1282 process.browser = true;
1283 process.env = {};
1284 process.argv = [];
1285 process.version = ''; // empty string to avoid regexp issues
1286 process.versions = {};
1287
1288 function noop() {}
1289
1290 process.on = noop;
1291 process.addListener = noop;
1292 process.once = noop;
1293 process.off = noop;
1294 process.removeListener = noop;
1295 process.removeAllListeners = noop;
1296 process.emit = noop;
1297 process.prependListener = noop;
1298 process.prependOnceListener = noop;
1299
1300 process.listeners = function (name) { return [] }
1301
1302 process.binding = function (name) {
1303 throw new Error('process.binding is not supported');
1304 };
1305
1306 process.cwd = function () { return '/' };
1307 process.chdir = function (dir) {
1308 throw new Error('process.chdir is not supported');
1309 };
1310 process.umask = function() { return 0; };
1311
1312
1313/***/ }),
1314/* 4 */
1315/***/ (function(module, exports, __webpack_require__) {
1316
1317 /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
1318 (typeof self !== "undefined" && self) ||
1319 window;
1320 var apply = Function.prototype.apply;
1321
1322 // DOM APIs, for completeness
1323
1324 exports.setTimeout = function() {
1325 return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
1326 };
1327 exports.setInterval = function() {
1328 return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
1329 };
1330 exports.clearTimeout =
1331 exports.clearInterval = function(timeout) {
1332 if (timeout) {
1333 timeout.close();
1334 }
1335 };
1336
1337 function Timeout(id, clearFn) {
1338 this._id = id;
1339 this._clearFn = clearFn;
1340 }
1341 Timeout.prototype.unref = Timeout.prototype.ref = function() {};
1342 Timeout.prototype.close = function() {
1343 this._clearFn.call(scope, this._id);
1344 };
1345
1346 // Does not start the time, just sets up the members needed.
1347 exports.enroll = function(item, msecs) {
1348 clearTimeout(item._idleTimeoutId);
1349 item._idleTimeout = msecs;
1350 };
1351
1352 exports.unenroll = function(item) {
1353 clearTimeout(item._idleTimeoutId);
1354 item._idleTimeout = -1;
1355 };
1356
1357 exports._unrefActive = exports.active = function(item) {
1358 clearTimeout(item._idleTimeoutId);
1359
1360 var msecs = item._idleTimeout;
1361 if (msecs >= 0) {
1362 item._idleTimeoutId = setTimeout(function onTimeout() {
1363 if (item._onTimeout)
1364 item._onTimeout();
1365 }, msecs);
1366 }
1367 };
1368
1369 // setimmediate attaches itself to the global object
1370 __webpack_require__(5);
1371 // On some exotic environments, it's not clear which object `setimmediate` was
1372 // able to install onto. Search each possibility in the same order as the
1373 // `setimmediate` library.
1374 exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
1375 (typeof global !== "undefined" && global.setImmediate) ||
1376 (this && this.setImmediate);
1377 exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
1378 (typeof global !== "undefined" && global.clearImmediate) ||
1379 (this && this.clearImmediate);
1380
1381 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
1382
1383/***/ }),
1384/* 5 */
1385/***/ (function(module, exports, __webpack_require__) {
1386
1387 /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
1388 "use strict";
1389
1390 if (global.setImmediate) {
1391 return;
1392 }
1393
1394 var nextHandle = 1; // Spec says greater than zero
1395 var tasksByHandle = {};
1396 var currentlyRunningATask = false;
1397 var doc = global.document;
1398 var registerImmediate;
1399
1400 function setImmediate(callback) {
1401 // Callback can either be a function or a string
1402 if (typeof callback !== "function") {
1403 callback = new Function("" + callback);
1404 }
1405 // Copy function arguments
1406 var args = new Array(arguments.length - 1);
1407 for (var i = 0; i < args.length; i++) {
1408 args[i] = arguments[i + 1];
1409 }
1410 // Store and register the task
1411 var task = { callback: callback, args: args };
1412 tasksByHandle[nextHandle] = task;
1413 registerImmediate(nextHandle);
1414 return nextHandle++;
1415 }
1416
1417 function clearImmediate(handle) {
1418 delete tasksByHandle[handle];
1419 }
1420
1421 function run(task) {
1422 var callback = task.callback;
1423 var args = task.args;
1424 switch (args.length) {
1425 case 0:
1426 callback();
1427 break;
1428 case 1:
1429 callback(args[0]);
1430 break;
1431 case 2:
1432 callback(args[0], args[1]);
1433 break;
1434 case 3:
1435 callback(args[0], args[1], args[2]);
1436 break;
1437 default:
1438 callback.apply(undefined, args);
1439 break;
1440 }
1441 }
1442
1443 function runIfPresent(handle) {
1444 // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
1445 // So if we're currently running a task, we'll need to delay this invocation.
1446 if (currentlyRunningATask) {
1447 // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
1448 // "too much recursion" error.
1449 setTimeout(runIfPresent, 0, handle);
1450 } else {
1451 var task = tasksByHandle[handle];
1452 if (task) {
1453 currentlyRunningATask = true;
1454 try {
1455 run(task);
1456 } finally {
1457 clearImmediate(handle);
1458 currentlyRunningATask = false;
1459 }
1460 }
1461 }
1462 }
1463
1464 function installNextTickImplementation() {
1465 registerImmediate = function(handle) {
1466 process.nextTick(function () { runIfPresent(handle); });
1467 };
1468 }
1469
1470 function canUsePostMessage() {
1471 // The test against `importScripts` prevents this implementation from being installed inside a web worker,
1472 // where `global.postMessage` means something completely different and can't be used for this purpose.
1473 if (global.postMessage && !global.importScripts) {
1474 var postMessageIsAsynchronous = true;
1475 var oldOnMessage = global.onmessage;
1476 global.onmessage = function() {
1477 postMessageIsAsynchronous = false;
1478 };
1479 global.postMessage("", "*");
1480 global.onmessage = oldOnMessage;
1481 return postMessageIsAsynchronous;
1482 }
1483 }
1484
1485 function installPostMessageImplementation() {
1486 // Installs an event handler on `global` for the `message` event: see
1487 // * https://developer.mozilla.org/en/DOM/window.postMessage
1488 // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
1489
1490 var messagePrefix = "setImmediate$" + Math.random() + "$";
1491 var onGlobalMessage = function(event) {
1492 if (event.source === global &&
1493 typeof event.data === "string" &&
1494 event.data.indexOf(messagePrefix) === 0) {
1495 runIfPresent(+event.data.slice(messagePrefix.length));
1496 }
1497 };
1498
1499 if (global.addEventListener) {
1500 global.addEventListener("message", onGlobalMessage, false);
1501 } else {
1502 global.attachEvent("onmessage", onGlobalMessage);
1503 }
1504
1505 registerImmediate = function(handle) {
1506 global.postMessage(messagePrefix + handle, "*");
1507 };
1508 }
1509
1510 function installMessageChannelImplementation() {
1511 var channel = new MessageChannel();
1512 channel.port1.onmessage = function(event) {
1513 var handle = event.data;
1514 runIfPresent(handle);
1515 };
1516
1517 registerImmediate = function(handle) {
1518 channel.port2.postMessage(handle);
1519 };
1520 }
1521
1522 function installReadyStateChangeImplementation() {
1523 var html = doc.documentElement;
1524 registerImmediate = function(handle) {
1525 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
1526 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
1527 var script = doc.createElement("script");
1528 script.onreadystatechange = function () {
1529 runIfPresent(handle);
1530 script.onreadystatechange = null;
1531 html.removeChild(script);
1532 script = null;
1533 };
1534 html.appendChild(script);
1535 };
1536 }
1537
1538 function installSetTimeoutImplementation() {
1539 registerImmediate = function(handle) {
1540 setTimeout(runIfPresent, 0, handle);
1541 };
1542 }
1543
1544 // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
1545 var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
1546 attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
1547
1548 // Don't get fooled by e.g. browserify environments.
1549 if ({}.toString.call(global.process) === "[object process]") {
1550 // For Node.js before 0.9
1551 installNextTickImplementation();
1552
1553 } else if (canUsePostMessage()) {
1554 // For non-IE10 modern browsers
1555 installPostMessageImplementation();
1556
1557 } else if (global.MessageChannel) {
1558 // For web workers, where supported
1559 installMessageChannelImplementation();
1560
1561 } else if (doc && "onreadystatechange" in doc.createElement("script")) {
1562 // For IE 6–8
1563 installReadyStateChangeImplementation();
1564
1565 } else {
1566 // For older browsers
1567 installSetTimeoutImplementation();
1568 }
1569
1570 attachTo.setImmediate = setImmediate;
1571 attachTo.clearImmediate = clearImmediate;
1572 }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
1573
1574 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
1575
1576/***/ }),
1577/* 6 */
1578/***/ (function(module, exports) {
1579
1580 /* (ignored) */
1581
1582/***/ }),
1583/* 7 */
1584/***/ (function(module, exports) {
1585
1586 module.exports = {"acm":{"name":"ACM","cors":true},"apigateway":{"name":"APIGateway","cors":true},"applicationautoscaling":{"prefix":"application-autoscaling","name":"ApplicationAutoScaling","cors":true},"appstream":{"name":"AppStream"},"autoscaling":{"name":"AutoScaling","cors":true},"batch":{"name":"Batch"},"budgets":{"name":"Budgets"},"clouddirectory":{"name":"CloudDirectory","versions":["2016-05-10*"]},"cloudformation":{"name":"CloudFormation","cors":true},"cloudfront":{"name":"CloudFront","versions":["2013-05-12*","2013-11-11*","2014-05-31*","2014-10-21*","2014-11-06*","2015-04-17*","2015-07-27*","2015-09-17*","2016-01-13*","2016-01-28*","2016-08-01*","2016-08-20*","2016-09-07*","2016-09-29*","2016-11-25*","2017-03-25*","2017-10-30*","2018-06-18*"],"cors":true},"cloudhsm":{"name":"CloudHSM","cors":true},"cloudsearch":{"name":"CloudSearch"},"cloudsearchdomain":{"name":"CloudSearchDomain"},"cloudtrail":{"name":"CloudTrail","cors":true},"cloudwatch":{"prefix":"monitoring","name":"CloudWatch","cors":true},"cloudwatchevents":{"prefix":"events","name":"CloudWatchEvents","versions":["2014-02-03*"],"cors":true},"cloudwatchlogs":{"prefix":"logs","name":"CloudWatchLogs","cors":true},"codebuild":{"name":"CodeBuild","cors":true},"codecommit":{"name":"CodeCommit","cors":true},"codedeploy":{"name":"CodeDeploy","cors":true},"codepipeline":{"name":"CodePipeline","cors":true},"cognitoidentity":{"prefix":"cognito-identity","name":"CognitoIdentity","cors":true},"cognitoidentityserviceprovider":{"prefix":"cognito-idp","name":"CognitoIdentityServiceProvider","cors":true},"cognitosync":{"prefix":"cognito-sync","name":"CognitoSync","cors":true},"configservice":{"prefix":"config","name":"ConfigService","cors":true},"cur":{"name":"CUR","cors":true},"datapipeline":{"name":"DataPipeline"},"devicefarm":{"name":"DeviceFarm","cors":true},"directconnect":{"name":"DirectConnect","cors":true},"directoryservice":{"prefix":"ds","name":"DirectoryService"},"discovery":{"name":"Discovery"},"dms":{"name":"DMS"},"dynamodb":{"name":"DynamoDB","cors":true},"dynamodbstreams":{"prefix":"streams.dynamodb","name":"DynamoDBStreams","cors":true},"ec2":{"name":"EC2","versions":["2013-06-15*","2013-10-15*","2014-02-01*","2014-05-01*","2014-06-15*","2014-09-01*","2014-10-01*","2015-03-01*","2015-04-15*","2015-10-01*","2016-04-01*","2016-09-15*"],"cors":true},"ecr":{"name":"ECR","cors":true},"ecs":{"name":"ECS","cors":true},"efs":{"prefix":"elasticfilesystem","name":"EFS","cors":true},"elasticache":{"name":"ElastiCache","versions":["2012-11-15*","2014-03-24*","2014-07-15*","2014-09-30*"],"cors":true},"elasticbeanstalk":{"name":"ElasticBeanstalk","cors":true},"elb":{"prefix":"elasticloadbalancing","name":"ELB","cors":true},"elbv2":{"prefix":"elasticloadbalancingv2","name":"ELBv2","cors":true},"emr":{"prefix":"elasticmapreduce","name":"EMR","cors":true},"es":{"name":"ES"},"elastictranscoder":{"name":"ElasticTranscoder","cors":true},"firehose":{"name":"Firehose","cors":true},"gamelift":{"name":"GameLift","cors":true},"glacier":{"name":"Glacier"},"health":{"name":"Health"},"iam":{"name":"IAM","cors":true},"importexport":{"name":"ImportExport"},"inspector":{"name":"Inspector","versions":["2015-08-18*"],"cors":true},"iot":{"name":"Iot","cors":true},"iotdata":{"prefix":"iot-data","name":"IotData","cors":true},"kinesis":{"name":"Kinesis","cors":true},"kinesisanalytics":{"name":"KinesisAnalytics"},"kms":{"name":"KMS","cors":true},"lambda":{"name":"Lambda","cors":true},"lexruntime":{"prefix":"runtime.lex","name":"LexRuntime","cors":true},"lightsail":{"name":"Lightsail"},"machinelearning":{"name":"MachineLearning","cors":true},"marketplacecommerceanalytics":{"name":"MarketplaceCommerceAnalytics","cors":true},"marketplacemetering":{"prefix":"meteringmarketplace","name":"MarketplaceMetering"},"mturk":{"prefix":"mturk-requester","name":"MTurk","cors":true},"mobileanalytics":{"name":"MobileAnalytics","cors":true},"opsworks":{"name":"OpsWorks","cors":true},"opsworkscm":{"name":"OpsWorksCM"},"organizations":{"name":"Organizations"},"pinpoint":{"name":"Pinpoint"},"polly":{"name":"Polly","cors":true},"rds":{"name":"RDS","versions":["2014-09-01*"],"cors":true},"redshift":{"name":"Redshift","cors":true},"rekognition":{"name":"Rekognition","cors":true},"resourcegroupstaggingapi":{"name":"ResourceGroupsTaggingAPI"},"route53":{"name":"Route53","cors":true},"route53domains":{"name":"Route53Domains","cors":true},"s3":{"name":"S3","dualstackAvailable":true,"cors":true},"s3control":{"name":"S3Control","dualstackAvailable":true},"servicecatalog":{"name":"ServiceCatalog","cors":true},"ses":{"prefix":"email","name":"SES","cors":true},"shield":{"name":"Shield"},"simpledb":{"prefix":"sdb","name":"SimpleDB"},"sms":{"name":"SMS"},"snowball":{"name":"Snowball"},"sns":{"name":"SNS","cors":true},"sqs":{"name":"SQS","cors":true},"ssm":{"name":"SSM","cors":true},"storagegateway":{"name":"StorageGateway","cors":true},"stepfunctions":{"prefix":"states","name":"StepFunctions"},"sts":{"name":"STS","cors":true},"support":{"name":"Support"},"swf":{"name":"SWF"},"xray":{"name":"XRay"},"waf":{"name":"WAF","cors":true},"wafregional":{"prefix":"waf-regional","name":"WAFRegional"},"workdocs":{"name":"WorkDocs","cors":true},"workspaces":{"name":"WorkSpaces"},"codestar":{"name":"CodeStar"},"lexmodelbuildingservice":{"prefix":"lex-models","name":"LexModelBuildingService","cors":true},"marketplaceentitlementservice":{"prefix":"entitlement.marketplace","name":"MarketplaceEntitlementService"},"athena":{"name":"Athena"},"greengrass":{"name":"Greengrass"},"dax":{"name":"DAX"},"migrationhub":{"prefix":"AWSMigrationHub","name":"MigrationHub"},"cloudhsmv2":{"name":"CloudHSMV2"},"glue":{"name":"Glue"},"mobile":{"name":"Mobile"},"pricing":{"name":"Pricing","cors":true},"costexplorer":{"prefix":"ce","name":"CostExplorer"},"mediaconvert":{"name":"MediaConvert"},"medialive":{"name":"MediaLive"},"mediapackage":{"name":"MediaPackage"},"mediastore":{"name":"MediaStore"},"mediastoredata":{"prefix":"mediastore-data","name":"MediaStoreData","cors":true},"appsync":{"name":"AppSync"},"guardduty":{"name":"GuardDuty"},"mq":{"name":"MQ"},"comprehend":{"name":"Comprehend","cors":true},"iotjobsdataplane":{"prefix":"iot-jobs-data","name":"IoTJobsDataPlane"},"kinesisvideoarchivedmedia":{"prefix":"kinesis-video-archived-media","name":"KinesisVideoArchivedMedia","cors":true},"kinesisvideomedia":{"prefix":"kinesis-video-media","name":"KinesisVideoMedia","cors":true},"kinesisvideo":{"name":"KinesisVideo","cors":true},"sagemakerruntime":{"prefix":"runtime.sagemaker","name":"SageMakerRuntime"},"sagemaker":{"name":"SageMaker"},"translate":{"name":"Translate","cors":true},"resourcegroups":{"prefix":"resource-groups","name":"ResourceGroups","cors":true},"alexaforbusiness":{"name":"AlexaForBusiness"},"cloud9":{"name":"Cloud9"},"serverlessapplicationrepository":{"prefix":"serverlessrepo","name":"ServerlessApplicationRepository"},"servicediscovery":{"name":"ServiceDiscovery"},"workmail":{"name":"WorkMail"},"autoscalingplans":{"prefix":"autoscaling-plans","name":"AutoScalingPlans"},"transcribeservice":{"prefix":"transcribe","name":"TranscribeService"},"connect":{"name":"Connect"},"acmpca":{"prefix":"acm-pca","name":"ACMPCA"},"fms":{"name":"FMS"},"secretsmanager":{"name":"SecretsManager","cors":true},"iotanalytics":{"name":"IoTAnalytics"},"iot1clickdevicesservice":{"prefix":"iot1click-devices","name":"IoT1ClickDevicesService"},"iot1clickprojects":{"prefix":"iot1click-projects","name":"IoT1ClickProjects"},"pi":{"name":"PI"},"neptune":{"name":"Neptune"},"mediatailor":{"name":"MediaTailor"},"eks":{"name":"EKS"},"macie":{"name":"Macie"},"dlm":{"name":"DLM"},"signer":{"name":"Signer"},"chime":{"name":"Chime"},"pinpointemail":{"prefix":"pinpoint-email","name":"PinpointEmail"},"ram":{"name":"RAM"},"route53resolver":{"name":"Route53Resolver"},"pinpointsmsvoice":{"prefix":"sms-voice","name":"PinpointSMSVoice"},"quicksight":{"name":"QuickSight"},"rdsdataservice":{"prefix":"rds-data","name":"RDSDataService"},"amplify":{"name":"Amplify"},"datasync":{"name":"DataSync"},"robomaker":{"name":"RoboMaker"},"transfer":{"name":"Transfer"},"globalaccelerator":{"name":"GlobalAccelerator"},"comprehendmedical":{"name":"ComprehendMedical","cors":true},"kinesisanalyticsv2":{"name":"KinesisAnalyticsV2"},"mediaconnect":{"name":"MediaConnect"},"fsx":{"name":"FSx"},"securityhub":{"name":"SecurityHub"},"appmesh":{"name":"AppMesh","versions":["2018-10-01*"]},"licensemanager":{"prefix":"license-manager","name":"LicenseManager"},"kafka":{"name":"Kafka"},"apigatewaymanagementapi":{"name":"ApiGatewayManagementApi"},"apigatewayv2":{"name":"ApiGatewayV2"},"docdb":{"name":"DocDB"},"backup":{"name":"Backup"},"worklink":{"name":"WorkLink"},"textract":{"name":"Textract"}}
1587
1588/***/ }),
1589/* 8 */
1590/***/ (function(module, exports, __webpack_require__) {
1591
1592 var v1 = __webpack_require__(9);
1593 var v4 = __webpack_require__(12);
1594
1595 var uuid = v4;
1596 uuid.v1 = v1;
1597 uuid.v4 = v4;
1598
1599 module.exports = uuid;
1600
1601
1602/***/ }),
1603/* 9 */
1604/***/ (function(module, exports, __webpack_require__) {
1605
1606 var rng = __webpack_require__(10);
1607 var bytesToUuid = __webpack_require__(11);
1608
1609 // **`v1()` - Generate time-based UUID**
1610 //
1611 // Inspired by https://github.com/LiosK/UUID.js
1612 // and http://docs.python.org/library/uuid.html
1613
1614 var _nodeId;
1615 var _clockseq;
1616
1617 // Previous uuid creation time
1618 var _lastMSecs = 0;
1619 var _lastNSecs = 0;
1620
1621 // See https://github.com/broofa/node-uuid for API details
1622 function v1(options, buf, offset) {
1623 var i = buf && offset || 0;
1624 var b = buf || [];
1625
1626 options = options || {};
1627 var node = options.node || _nodeId;
1628 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
1629
1630 // node and clockseq need to be initialized to random values if they're not
1631 // specified. We do this lazily to minimize issues related to insufficient
1632 // system entropy. See #189
1633 if (node == null || clockseq == null) {
1634 var seedBytes = rng();
1635 if (node == null) {
1636 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
1637 node = _nodeId = [
1638 seedBytes[0] | 0x01,
1639 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
1640 ];
1641 }
1642 if (clockseq == null) {
1643 // Per 4.2.2, randomize (14 bit) clockseq
1644 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
1645 }
1646 }
1647
1648 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
1649 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
1650 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
1651 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
1652 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
1653
1654 // Per 4.2.1.2, use count of uuid's generated during the current clock
1655 // cycle to simulate higher resolution clock
1656 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
1657
1658 // Time since last uuid creation (in msecs)
1659 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
1660
1661 // Per 4.2.1.2, Bump clockseq on clock regression
1662 if (dt < 0 && options.clockseq === undefined) {
1663 clockseq = clockseq + 1 & 0x3fff;
1664 }
1665
1666 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
1667 // time interval
1668 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
1669 nsecs = 0;
1670 }
1671
1672 // Per 4.2.1.2 Throw error if too many uuids are requested
1673 if (nsecs >= 10000) {
1674 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
1675 }
1676
1677 _lastMSecs = msecs;
1678 _lastNSecs = nsecs;
1679 _clockseq = clockseq;
1680
1681 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
1682 msecs += 12219292800000;
1683
1684 // `time_low`
1685 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
1686 b[i++] = tl >>> 24 & 0xff;
1687 b[i++] = tl >>> 16 & 0xff;
1688 b[i++] = tl >>> 8 & 0xff;
1689 b[i++] = tl & 0xff;
1690
1691 // `time_mid`
1692 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
1693 b[i++] = tmh >>> 8 & 0xff;
1694 b[i++] = tmh & 0xff;
1695
1696 // `time_high_and_version`
1697 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
1698 b[i++] = tmh >>> 16 & 0xff;
1699
1700 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
1701 b[i++] = clockseq >>> 8 | 0x80;
1702
1703 // `clock_seq_low`
1704 b[i++] = clockseq & 0xff;
1705
1706 // `node`
1707 for (var n = 0; n < 6; ++n) {
1708 b[i + n] = node[n];
1709 }
1710
1711 return buf ? buf : bytesToUuid(b);
1712 }
1713
1714 module.exports = v1;
1715
1716
1717/***/ }),
1718/* 10 */
1719/***/ (function(module, exports) {
1720
1721 // Unique ID creation requires a high quality random # generator. In the
1722 // browser this is a little complicated due to unknown quality of Math.random()
1723 // and inconsistent support for the `crypto` API. We do the best we can via
1724 // feature-detection
1725
1726 // getRandomValues needs to be invoked in a context where "this" is a Crypto
1727 // implementation. Also, find the complete implementation of crypto on IE11.
1728 var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
1729 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
1730
1731 if (getRandomValues) {
1732 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
1733 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
1734
1735 module.exports = function whatwgRNG() {
1736 getRandomValues(rnds8);
1737 return rnds8;
1738 };
1739 } else {
1740 // Math.random()-based (RNG)
1741 //
1742 // If all else fails, use Math.random(). It's fast, but is of unspecified
1743 // quality.
1744 var rnds = new Array(16);
1745
1746 module.exports = function mathRNG() {
1747 for (var i = 0, r; i < 16; i++) {
1748 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
1749 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
1750 }
1751
1752 return rnds;
1753 };
1754 }
1755
1756
1757/***/ }),
1758/* 11 */
1759/***/ (function(module, exports) {
1760
1761 /**
1762 * Convert array of 16 byte values to UUID string format of the form:
1763 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1764 */
1765 var byteToHex = [];
1766 for (var i = 0; i < 256; ++i) {
1767 byteToHex[i] = (i + 0x100).toString(16).substr(1);
1768 }
1769
1770 function bytesToUuid(buf, offset) {
1771 var i = offset || 0;
1772 var bth = byteToHex;
1773 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
1774 return ([bth[buf[i++]], bth[buf[i++]],
1775 bth[buf[i++]], bth[buf[i++]], '-',
1776 bth[buf[i++]], bth[buf[i++]], '-',
1777 bth[buf[i++]], bth[buf[i++]], '-',
1778 bth[buf[i++]], bth[buf[i++]], '-',
1779 bth[buf[i++]], bth[buf[i++]],
1780 bth[buf[i++]], bth[buf[i++]],
1781 bth[buf[i++]], bth[buf[i++]]]).join('');
1782 }
1783
1784 module.exports = bytesToUuid;
1785
1786
1787/***/ }),
1788/* 12 */
1789/***/ (function(module, exports, __webpack_require__) {
1790
1791 var rng = __webpack_require__(10);
1792 var bytesToUuid = __webpack_require__(11);
1793
1794 function v4(options, buf, offset) {
1795 var i = buf && offset || 0;
1796
1797 if (typeof(options) == 'string') {
1798 buf = options === 'binary' ? new Array(16) : null;
1799 options = null;
1800 }
1801 options = options || {};
1802
1803 var rnds = options.random || (options.rng || rng)();
1804
1805 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1806 rnds[6] = (rnds[6] & 0x0f) | 0x40;
1807 rnds[8] = (rnds[8] & 0x3f) | 0x80;
1808
1809 // Copy bytes to buffer, if provided
1810 if (buf) {
1811 for (var ii = 0; ii < 16; ++ii) {
1812 buf[i + ii] = rnds[ii];
1813 }
1814 }
1815
1816 return buf || bytesToUuid(rnds);
1817 }
1818
1819 module.exports = v4;
1820
1821
1822/***/ }),
1823/* 13 */
1824/***/ (function(module, exports, __webpack_require__) {
1825
1826 var util = __webpack_require__(2);
1827 var JsonBuilder = __webpack_require__(14);
1828 var JsonParser = __webpack_require__(15);
1829 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
1830
1831 function buildRequest(req) {
1832 var httpRequest = req.httpRequest;
1833 var api = req.service.api;
1834 var target = api.targetPrefix + '.' + api.operations[req.operation].name;
1835 var version = api.jsonVersion || '1.0';
1836 var input = api.operations[req.operation].input;
1837 var builder = new JsonBuilder();
1838
1839 if (version === 1) version = '1.0';
1840 httpRequest.body = builder.build(req.params || {}, input);
1841 httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version;
1842 httpRequest.headers['X-Amz-Target'] = target;
1843
1844 populateHostPrefix(req);
1845 }
1846
1847 function extractError(resp) {
1848 var error = {};
1849 var httpResponse = resp.httpResponse;
1850
1851 error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError';
1852 if (typeof error.code === 'string') {
1853 error.code = error.code.split(':')[0];
1854 }
1855
1856 if (httpResponse.body.length > 0) {
1857 try {
1858 var e = JSON.parse(httpResponse.body.toString());
1859 if (e.__type || e.code) {
1860 error.code = (e.__type || e.code).split('#').pop();
1861 }
1862 if (error.code === 'RequestEntityTooLarge') {
1863 error.message = 'Request body must be less than 1 MB';
1864 } else {
1865 error.message = (e.message || e.Message || null);
1866 }
1867 } catch (e) {
1868 error.statusCode = httpResponse.statusCode;
1869 error.message = httpResponse.statusMessage;
1870 }
1871 } else {
1872 error.statusCode = httpResponse.statusCode;
1873 error.message = httpResponse.statusCode.toString();
1874 }
1875
1876 resp.error = util.error(new Error(), error);
1877 }
1878
1879 function extractData(resp) {
1880 var body = resp.httpResponse.body.toString() || '{}';
1881 if (resp.request.service.config.convertResponseTypes === false) {
1882 resp.data = JSON.parse(body);
1883 } else {
1884 var operation = resp.request.service.api.operations[resp.request.operation];
1885 var shape = operation.output || {};
1886 var parser = new JsonParser();
1887 resp.data = parser.parse(body, shape);
1888 }
1889 }
1890
1891 /**
1892 * @api private
1893 */
1894 module.exports = {
1895 buildRequest: buildRequest,
1896 extractError: extractError,
1897 extractData: extractData
1898 };
1899
1900
1901/***/ }),
1902/* 14 */
1903/***/ (function(module, exports, __webpack_require__) {
1904
1905 var util = __webpack_require__(2);
1906
1907 function JsonBuilder() { }
1908
1909 JsonBuilder.prototype.build = function(value, shape) {
1910 return JSON.stringify(translate(value, shape));
1911 };
1912
1913 function translate(value, shape) {
1914 if (!shape || value === undefined || value === null) return undefined;
1915
1916 switch (shape.type) {
1917 case 'structure': return translateStructure(value, shape);
1918 case 'map': return translateMap(value, shape);
1919 case 'list': return translateList(value, shape);
1920 default: return translateScalar(value, shape);
1921 }
1922 }
1923
1924 function translateStructure(structure, shape) {
1925 var struct = {};
1926 util.each(structure, function(name, value) {
1927 var memberShape = shape.members[name];
1928 if (memberShape) {
1929 if (memberShape.location !== 'body') return;
1930 var locationName = memberShape.isLocationName ? memberShape.name : name;
1931 var result = translate(value, memberShape);
1932 if (result !== undefined) struct[locationName] = result;
1933 }
1934 });
1935 return struct;
1936 }
1937
1938 function translateList(list, shape) {
1939 var out = [];
1940 util.arrayEach(list, function(value) {
1941 var result = translate(value, shape.member);
1942 if (result !== undefined) out.push(result);
1943 });
1944 return out;
1945 }
1946
1947 function translateMap(map, shape) {
1948 var out = {};
1949 util.each(map, function(key, value) {
1950 var result = translate(value, shape.value);
1951 if (result !== undefined) out[key] = result;
1952 });
1953 return out;
1954 }
1955
1956 function translateScalar(value, shape) {
1957 return shape.toWireFormat(value);
1958 }
1959
1960 /**
1961 * @api private
1962 */
1963 module.exports = JsonBuilder;
1964
1965
1966/***/ }),
1967/* 15 */
1968/***/ (function(module, exports, __webpack_require__) {
1969
1970 var util = __webpack_require__(2);
1971
1972 function JsonParser() { }
1973
1974 JsonParser.prototype.parse = function(value, shape) {
1975 return translate(JSON.parse(value), shape);
1976 };
1977
1978 function translate(value, shape) {
1979 if (!shape || value === undefined) return undefined;
1980
1981 switch (shape.type) {
1982 case 'structure': return translateStructure(value, shape);
1983 case 'map': return translateMap(value, shape);
1984 case 'list': return translateList(value, shape);
1985 default: return translateScalar(value, shape);
1986 }
1987 }
1988
1989 function translateStructure(structure, shape) {
1990 if (structure == null) return undefined;
1991
1992 var struct = {};
1993 var shapeMembers = shape.members;
1994 util.each(shapeMembers, function(name, memberShape) {
1995 var locationName = memberShape.isLocationName ? memberShape.name : name;
1996 if (Object.prototype.hasOwnProperty.call(structure, locationName)) {
1997 var value = structure[locationName];
1998 var result = translate(value, memberShape);
1999 if (result !== undefined) struct[name] = result;
2000 }
2001 });
2002 return struct;
2003 }
2004
2005 function translateList(list, shape) {
2006 if (list == null) return undefined;
2007
2008 var out = [];
2009 util.arrayEach(list, function(value) {
2010 var result = translate(value, shape.member);
2011 if (result === undefined) out.push(null);
2012 else out.push(result);
2013 });
2014 return out;
2015 }
2016
2017 function translateMap(map, shape) {
2018 if (map == null) return undefined;
2019
2020 var out = {};
2021 util.each(map, function(key, value) {
2022 var result = translate(value, shape.value);
2023 if (result === undefined) out[key] = null;
2024 else out[key] = result;
2025 });
2026 return out;
2027 }
2028
2029 function translateScalar(value, shape) {
2030 return shape.toType(value);
2031 }
2032
2033 /**
2034 * @api private
2035 */
2036 module.exports = JsonParser;
2037
2038
2039/***/ }),
2040/* 16 */
2041/***/ (function(module, exports, __webpack_require__) {
2042
2043 var util = __webpack_require__(2);
2044 var AWS = __webpack_require__(1);
2045
2046 /**
2047 * Prepend prefix defined by API model to endpoint that's already
2048 * constructed. This feature does not apply to operations using
2049 * endpoint discovery and can be disabled.
2050 * @api private
2051 */
2052 function populateHostPrefix(request) {
2053 var enabled = request.service.config.hostPrefixEnabled;
2054 if (!enabled) return request;
2055 var operationModel = request.service.api.operations[request.operation];
2056 //don't marshal host prefix when operation has endpoint discovery traits
2057 if (hasEndpointDiscover(request)) return request;
2058 if (operationModel.endpoint && operationModel.endpoint.hostPrefix) {
2059 var hostPrefixNotation = operationModel.endpoint.hostPrefix;
2060 var hostPrefix = expandHostPrefix(hostPrefixNotation, request.params, operationModel.input);
2061 prependEndpointPrefix(request.httpRequest.endpoint, hostPrefix);
2062 validateHostname(request.httpRequest.endpoint.hostname);
2063 }
2064 return request;
2065 }
2066
2067 /**
2068 * @api private
2069 */
2070 function hasEndpointDiscover(request) {
2071 var api = request.service.api;
2072 var operationModel = api.operations[request.operation];
2073 var isEndpointOperation = api.endpointOperation && (api.endpointOperation === util.string.lowerFirst(operationModel.name));
2074 return (operationModel.endpointDiscoveryRequired !== 'NULL' || isEndpointOperation === true);
2075 }
2076
2077 /**
2078 * @api private
2079 */
2080 function expandHostPrefix(hostPrefixNotation, params, shape) {
2081 util.each(shape.members, function(name, member) {
2082 if (member.hostLabel === true) {
2083 if (typeof params[name] !== 'string' || params[name] === '') {
2084 throw util.error(new Error(), {
2085 message: 'Parameter ' + name + ' should be a non-empty string.',
2086 code: 'InvalidParameter'
2087 });
2088 }
2089 var regex = new RegExp('\\{' + name + '\\}', 'g');
2090 hostPrefixNotation = hostPrefixNotation.replace(regex, params[name]);
2091 }
2092 });
2093 return hostPrefixNotation;
2094 }
2095
2096 /**
2097 * @api private
2098 */
2099 function prependEndpointPrefix(endpoint, prefix) {
2100 if (endpoint.host) {
2101 endpoint.host = prefix + endpoint.host;
2102 }
2103 if (endpoint.hostname) {
2104 endpoint.hostname = prefix + endpoint.hostname;
2105 }
2106 }
2107
2108 /**
2109 * @api private
2110 */
2111 function validateHostname(hostname) {
2112 var labels = hostname.split('.');
2113 //Reference: https://tools.ietf.org/html/rfc1123#section-2
2114 var hostPattern = /^[a-zA-Z0-9]{1}$|^[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]$/;
2115 util.arrayEach(labels, function(label) {
2116 if (!label.length || label.length < 1 || label.length > 63) {
2117 throw util.error(new Error(), {
2118 code: 'ValidationError',
2119 message: 'Hostname label length should be between 1 to 63 characters, inclusive.'
2120 });
2121 }
2122 if (!hostPattern.test(label)) {
2123 throw AWS.util.error(new Error(),
2124 {code: 'ValidationError', message: label + ' is not hostname compatible.'});
2125 }
2126 });
2127 }
2128
2129 module.exports = {
2130 populateHostPrefix: populateHostPrefix
2131 };
2132
2133
2134/***/ }),
2135/* 17 */
2136/***/ (function(module, exports, __webpack_require__) {
2137
2138 var AWS = __webpack_require__(1);
2139 var util = __webpack_require__(2);
2140 var QueryParamSerializer = __webpack_require__(18);
2141 var Shape = __webpack_require__(19);
2142 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2143
2144 function buildRequest(req) {
2145 var operation = req.service.api.operations[req.operation];
2146 var httpRequest = req.httpRequest;
2147 httpRequest.headers['Content-Type'] =
2148 'application/x-www-form-urlencoded; charset=utf-8';
2149 httpRequest.params = {
2150 Version: req.service.api.apiVersion,
2151 Action: operation.name
2152 };
2153
2154 // convert the request parameters into a list of query params,
2155 // e.g. Deeply.NestedParam.0.Name=value
2156 var builder = new QueryParamSerializer();
2157 builder.serialize(req.params, operation.input, function(name, value) {
2158 httpRequest.params[name] = value;
2159 });
2160 httpRequest.body = util.queryParamsToString(httpRequest.params);
2161
2162 populateHostPrefix(req);
2163 }
2164
2165 function extractError(resp) {
2166 var data, body = resp.httpResponse.body.toString();
2167 if (body.match('<UnknownOperationException')) {
2168 data = {
2169 Code: 'UnknownOperation',
2170 Message: 'Unknown operation ' + resp.request.operation
2171 };
2172 } else {
2173 try {
2174 data = new AWS.XML.Parser().parse(body);
2175 } catch (e) {
2176 data = {
2177 Code: resp.httpResponse.statusCode,
2178 Message: resp.httpResponse.statusMessage
2179 };
2180 }
2181 }
2182
2183 if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
2184 if (data.Errors) data = data.Errors;
2185 if (data.Error) data = data.Error;
2186 if (data.Code) {
2187 resp.error = util.error(new Error(), {
2188 code: data.Code,
2189 message: data.Message
2190 });
2191 } else {
2192 resp.error = util.error(new Error(), {
2193 code: resp.httpResponse.statusCode,
2194 message: null
2195 });
2196 }
2197 }
2198
2199 function extractData(resp) {
2200 var req = resp.request;
2201 var operation = req.service.api.operations[req.operation];
2202 var shape = operation.output || {};
2203 var origRules = shape;
2204
2205 if (origRules.resultWrapper) {
2206 var tmp = Shape.create({type: 'structure'});
2207 tmp.members[origRules.resultWrapper] = shape;
2208 tmp.memberNames = [origRules.resultWrapper];
2209 util.property(shape, 'name', shape.resultWrapper);
2210 shape = tmp;
2211 }
2212
2213 var parser = new AWS.XML.Parser();
2214
2215 // TODO: Refactor XML Parser to parse RequestId from response.
2216 if (shape && shape.members && !shape.members._XAMZRequestId) {
2217 var requestIdShape = Shape.create(
2218 { type: 'string' },
2219 { api: { protocol: 'query' } },
2220 'requestId'
2221 );
2222 shape.members._XAMZRequestId = requestIdShape;
2223 }
2224
2225 var data = parser.parse(resp.httpResponse.body.toString(), shape);
2226 resp.requestId = data._XAMZRequestId || data.requestId;
2227
2228 if (data._XAMZRequestId) delete data._XAMZRequestId;
2229
2230 if (origRules.resultWrapper) {
2231 if (data[origRules.resultWrapper]) {
2232 util.update(data, data[origRules.resultWrapper]);
2233 delete data[origRules.resultWrapper];
2234 }
2235 }
2236
2237 resp.data = data;
2238 }
2239
2240 /**
2241 * @api private
2242 */
2243 module.exports = {
2244 buildRequest: buildRequest,
2245 extractError: extractError,
2246 extractData: extractData
2247 };
2248
2249
2250/***/ }),
2251/* 18 */
2252/***/ (function(module, exports, __webpack_require__) {
2253
2254 var util = __webpack_require__(2);
2255
2256 function QueryParamSerializer() {
2257 }
2258
2259 QueryParamSerializer.prototype.serialize = function(params, shape, fn) {
2260 serializeStructure('', params, shape, fn);
2261 };
2262
2263 function ucfirst(shape) {
2264 if (shape.isQueryName || shape.api.protocol !== 'ec2') {
2265 return shape.name;
2266 } else {
2267 return shape.name[0].toUpperCase() + shape.name.substr(1);
2268 }
2269 }
2270
2271 function serializeStructure(prefix, struct, rules, fn) {
2272 util.each(rules.members, function(name, member) {
2273 var value = struct[name];
2274 if (value === null || value === undefined) return;
2275
2276 var memberName = ucfirst(member);
2277 memberName = prefix ? prefix + '.' + memberName : memberName;
2278 serializeMember(memberName, value, member, fn);
2279 });
2280 }
2281
2282 function serializeMap(name, map, rules, fn) {
2283 var i = 1;
2284 util.each(map, function (key, value) {
2285 var prefix = rules.flattened ? '.' : '.entry.';
2286 var position = prefix + (i++) + '.';
2287 var keyName = position + (rules.key.name || 'key');
2288 var valueName = position + (rules.value.name || 'value');
2289 serializeMember(name + keyName, key, rules.key, fn);
2290 serializeMember(name + valueName, value, rules.value, fn);
2291 });
2292 }
2293
2294 function serializeList(name, list, rules, fn) {
2295 var memberRules = rules.member || {};
2296
2297 if (list.length === 0) {
2298 fn.call(this, name, null);
2299 return;
2300 }
2301
2302 util.arrayEach(list, function (v, n) {
2303 var suffix = '.' + (n + 1);
2304 if (rules.api.protocol === 'ec2') {
2305 // Do nothing for EC2
2306 suffix = suffix + ''; // make linter happy
2307 } else if (rules.flattened) {
2308 if (memberRules.name) {
2309 var parts = name.split('.');
2310 parts.pop();
2311 parts.push(ucfirst(memberRules));
2312 name = parts.join('.');
2313 }
2314 } else {
2315 suffix = '.' + (memberRules.name ? memberRules.name : 'member') + suffix;
2316 }
2317 serializeMember(name + suffix, v, memberRules, fn);
2318 });
2319 }
2320
2321 function serializeMember(name, value, rules, fn) {
2322 if (value === null || value === undefined) return;
2323 if (rules.type === 'structure') {
2324 serializeStructure(name, value, rules, fn);
2325 } else if (rules.type === 'list') {
2326 serializeList(name, value, rules, fn);
2327 } else if (rules.type === 'map') {
2328 serializeMap(name, value, rules, fn);
2329 } else {
2330 fn(name, rules.toWireFormat(value).toString());
2331 }
2332 }
2333
2334 /**
2335 * @api private
2336 */
2337 module.exports = QueryParamSerializer;
2338
2339
2340/***/ }),
2341/* 19 */
2342/***/ (function(module, exports, __webpack_require__) {
2343
2344 var Collection = __webpack_require__(20);
2345
2346 var util = __webpack_require__(2);
2347
2348 function property(obj, name, value) {
2349 if (value !== null && value !== undefined) {
2350 util.property.apply(this, arguments);
2351 }
2352 }
2353
2354 function memoizedProperty(obj, name) {
2355 if (!obj.constructor.prototype[name]) {
2356 util.memoizedProperty.apply(this, arguments);
2357 }
2358 }
2359
2360 function Shape(shape, options, memberName) {
2361 options = options || {};
2362
2363 property(this, 'shape', shape.shape);
2364 property(this, 'api', options.api, false);
2365 property(this, 'type', shape.type);
2366 property(this, 'enum', shape.enum);
2367 property(this, 'min', shape.min);
2368 property(this, 'max', shape.max);
2369 property(this, 'pattern', shape.pattern);
2370 property(this, 'location', shape.location || this.location || 'body');
2371 property(this, 'name', this.name || shape.xmlName || shape.queryName ||
2372 shape.locationName || memberName);
2373 property(this, 'isStreaming', shape.streaming || this.isStreaming || false);
2374 property(this, 'isComposite', shape.isComposite || false);
2375 property(this, 'isShape', true, false);
2376 property(this, 'isQueryName', Boolean(shape.queryName), false);
2377 property(this, 'isLocationName', Boolean(shape.locationName), false);
2378 property(this, 'isIdempotent', shape.idempotencyToken === true);
2379 property(this, 'isJsonValue', shape.jsonvalue === true);
2380 property(this, 'isSensitive', shape.sensitive === true || shape.prototype && shape.prototype.sensitive === true);
2381 property(this, 'isEventStream', Boolean(shape.eventstream), false);
2382 property(this, 'isEvent', Boolean(shape.event), false);
2383 property(this, 'isEventPayload', Boolean(shape.eventpayload), false);
2384 property(this, 'isEventHeader', Boolean(shape.eventheader), false);
2385 property(this, 'isTimestampFormatSet', Boolean(shape.timestampFormat) || shape.prototype && shape.prototype.isTimestampFormatSet === true, false);
2386 property(this, 'endpointDiscoveryId', Boolean(shape.endpointdiscoveryid), false);
2387 property(this, 'hostLabel', Boolean(shape.hostLabel), false);
2388
2389 if (options.documentation) {
2390 property(this, 'documentation', shape.documentation);
2391 property(this, 'documentationUrl', shape.documentationUrl);
2392 }
2393
2394 if (shape.xmlAttribute) {
2395 property(this, 'isXmlAttribute', shape.xmlAttribute || false);
2396 }
2397
2398 // type conversion and parsing
2399 property(this, 'defaultValue', null);
2400 this.toWireFormat = function(value) {
2401 if (value === null || value === undefined) return '';
2402 return value;
2403 };
2404 this.toType = function(value) { return value; };
2405 }
2406
2407 /**
2408 * @api private
2409 */
2410 Shape.normalizedTypes = {
2411 character: 'string',
2412 double: 'float',
2413 long: 'integer',
2414 short: 'integer',
2415 biginteger: 'integer',
2416 bigdecimal: 'float',
2417 blob: 'binary'
2418 };
2419
2420 /**
2421 * @api private
2422 */
2423 Shape.types = {
2424 'structure': StructureShape,
2425 'list': ListShape,
2426 'map': MapShape,
2427 'boolean': BooleanShape,
2428 'timestamp': TimestampShape,
2429 'float': FloatShape,
2430 'integer': IntegerShape,
2431 'string': StringShape,
2432 'base64': Base64Shape,
2433 'binary': BinaryShape
2434 };
2435
2436 Shape.resolve = function resolve(shape, options) {
2437 if (shape.shape) {
2438 var refShape = options.api.shapes[shape.shape];
2439 if (!refShape) {
2440 throw new Error('Cannot find shape reference: ' + shape.shape);
2441 }
2442
2443 return refShape;
2444 } else {
2445 return null;
2446 }
2447 };
2448
2449 Shape.create = function create(shape, options, memberName) {
2450 if (shape.isShape) return shape;
2451
2452 var refShape = Shape.resolve(shape, options);
2453 if (refShape) {
2454 var filteredKeys = Object.keys(shape);
2455 if (!options.documentation) {
2456 filteredKeys = filteredKeys.filter(function(name) {
2457 return !name.match(/documentation/);
2458 });
2459 }
2460
2461 // create an inline shape with extra members
2462 var InlineShape = function() {
2463 refShape.constructor.call(this, shape, options, memberName);
2464 };
2465 InlineShape.prototype = refShape;
2466 return new InlineShape();
2467 } else {
2468 // set type if not set
2469 if (!shape.type) {
2470 if (shape.members) shape.type = 'structure';
2471 else if (shape.member) shape.type = 'list';
2472 else if (shape.key) shape.type = 'map';
2473 else shape.type = 'string';
2474 }
2475
2476 // normalize types
2477 var origType = shape.type;
2478 if (Shape.normalizedTypes[shape.type]) {
2479 shape.type = Shape.normalizedTypes[shape.type];
2480 }
2481
2482 if (Shape.types[shape.type]) {
2483 return new Shape.types[shape.type](shape, options, memberName);
2484 } else {
2485 throw new Error('Unrecognized shape type: ' + origType);
2486 }
2487 }
2488 };
2489
2490 function CompositeShape(shape) {
2491 Shape.apply(this, arguments);
2492 property(this, 'isComposite', true);
2493
2494 if (shape.flattened) {
2495 property(this, 'flattened', shape.flattened || false);
2496 }
2497 }
2498
2499 function StructureShape(shape, options) {
2500 var self = this;
2501 var requiredMap = null, firstInit = !this.isShape;
2502
2503 CompositeShape.apply(this, arguments);
2504
2505 if (firstInit) {
2506 property(this, 'defaultValue', function() { return {}; });
2507 property(this, 'members', {});
2508 property(this, 'memberNames', []);
2509 property(this, 'required', []);
2510 property(this, 'isRequired', function() { return false; });
2511 }
2512
2513 if (shape.members) {
2514 property(this, 'members', new Collection(shape.members, options, function(name, member) {
2515 return Shape.create(member, options, name);
2516 }));
2517 memoizedProperty(this, 'memberNames', function() {
2518 return shape.xmlOrder || Object.keys(shape.members);
2519 });
2520
2521 if (shape.event) {
2522 memoizedProperty(this, 'eventPayloadMemberName', function() {
2523 var members = self.members;
2524 var memberNames = self.memberNames;
2525 // iterate over members to find ones that are event payloads
2526 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2527 if (members[memberNames[i]].isEventPayload) {
2528 return memberNames[i];
2529 }
2530 }
2531 });
2532
2533 memoizedProperty(this, 'eventHeaderMemberNames', function() {
2534 var members = self.members;
2535 var memberNames = self.memberNames;
2536 var eventHeaderMemberNames = [];
2537 // iterate over members to find ones that are event headers
2538 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2539 if (members[memberNames[i]].isEventHeader) {
2540 eventHeaderMemberNames.push(memberNames[i]);
2541 }
2542 }
2543 return eventHeaderMemberNames;
2544 });
2545 }
2546 }
2547
2548 if (shape.required) {
2549 property(this, 'required', shape.required);
2550 property(this, 'isRequired', function(name) {
2551 if (!requiredMap) {
2552 requiredMap = {};
2553 for (var i = 0; i < shape.required.length; i++) {
2554 requiredMap[shape.required[i]] = true;
2555 }
2556 }
2557
2558 return requiredMap[name];
2559 }, false, true);
2560 }
2561
2562 property(this, 'resultWrapper', shape.resultWrapper || null);
2563
2564 if (shape.payload) {
2565 property(this, 'payload', shape.payload);
2566 }
2567
2568 if (typeof shape.xmlNamespace === 'string') {
2569 property(this, 'xmlNamespaceUri', shape.xmlNamespace);
2570 } else if (typeof shape.xmlNamespace === 'object') {
2571 property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix);
2572 property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri);
2573 }
2574 }
2575
2576 function ListShape(shape, options) {
2577 var self = this, firstInit = !this.isShape;
2578 CompositeShape.apply(this, arguments);
2579
2580 if (firstInit) {
2581 property(this, 'defaultValue', function() { return []; });
2582 }
2583
2584 if (shape.member) {
2585 memoizedProperty(this, 'member', function() {
2586 return Shape.create(shape.member, options);
2587 });
2588 }
2589
2590 if (this.flattened) {
2591 var oldName = this.name;
2592 memoizedProperty(this, 'name', function() {
2593 return self.member.name || oldName;
2594 });
2595 }
2596 }
2597
2598 function MapShape(shape, options) {
2599 var firstInit = !this.isShape;
2600 CompositeShape.apply(this, arguments);
2601
2602 if (firstInit) {
2603 property(this, 'defaultValue', function() { return {}; });
2604 property(this, 'key', Shape.create({type: 'string'}, options));
2605 property(this, 'value', Shape.create({type: 'string'}, options));
2606 }
2607
2608 if (shape.key) {
2609 memoizedProperty(this, 'key', function() {
2610 return Shape.create(shape.key, options);
2611 });
2612 }
2613 if (shape.value) {
2614 memoizedProperty(this, 'value', function() {
2615 return Shape.create(shape.value, options);
2616 });
2617 }
2618 }
2619
2620 function TimestampShape(shape) {
2621 var self = this;
2622 Shape.apply(this, arguments);
2623
2624 if (shape.timestampFormat) {
2625 property(this, 'timestampFormat', shape.timestampFormat);
2626 } else if (self.isTimestampFormatSet && this.timestampFormat) {
2627 property(this, 'timestampFormat', this.timestampFormat);
2628 } else if (this.location === 'header') {
2629 property(this, 'timestampFormat', 'rfc822');
2630 } else if (this.location === 'querystring') {
2631 property(this, 'timestampFormat', 'iso8601');
2632 } else if (this.api) {
2633 switch (this.api.protocol) {
2634 case 'json':
2635 case 'rest-json':
2636 property(this, 'timestampFormat', 'unixTimestamp');
2637 break;
2638 case 'rest-xml':
2639 case 'query':
2640 case 'ec2':
2641 property(this, 'timestampFormat', 'iso8601');
2642 break;
2643 }
2644 }
2645
2646 this.toType = function(value) {
2647 if (value === null || value === undefined) return null;
2648 if (typeof value.toUTCString === 'function') return value;
2649 return typeof value === 'string' || typeof value === 'number' ?
2650 util.date.parseTimestamp(value) : null;
2651 };
2652
2653 this.toWireFormat = function(value) {
2654 return util.date.format(value, self.timestampFormat);
2655 };
2656 }
2657
2658 function StringShape() {
2659 Shape.apply(this, arguments);
2660
2661 var nullLessProtocols = ['rest-xml', 'query', 'ec2'];
2662 this.toType = function(value) {
2663 value = this.api && nullLessProtocols.indexOf(this.api.protocol) > -1 ?
2664 value || '' : value;
2665 if (this.isJsonValue) {
2666 return JSON.parse(value);
2667 }
2668
2669 return value && typeof value.toString === 'function' ?
2670 value.toString() : value;
2671 };
2672
2673 this.toWireFormat = function(value) {
2674 return this.isJsonValue ? JSON.stringify(value) : value;
2675 };
2676 }
2677
2678 function FloatShape() {
2679 Shape.apply(this, arguments);
2680
2681 this.toType = function(value) {
2682 if (value === null || value === undefined) return null;
2683 return parseFloat(value);
2684 };
2685 this.toWireFormat = this.toType;
2686 }
2687
2688 function IntegerShape() {
2689 Shape.apply(this, arguments);
2690
2691 this.toType = function(value) {
2692 if (value === null || value === undefined) return null;
2693 return parseInt(value, 10);
2694 };
2695 this.toWireFormat = this.toType;
2696 }
2697
2698 function BinaryShape() {
2699 Shape.apply(this, arguments);
2700 this.toType = util.base64.decode;
2701 this.toWireFormat = util.base64.encode;
2702 }
2703
2704 function Base64Shape() {
2705 BinaryShape.apply(this, arguments);
2706 }
2707
2708 function BooleanShape() {
2709 Shape.apply(this, arguments);
2710
2711 this.toType = function(value) {
2712 if (typeof value === 'boolean') return value;
2713 if (value === null || value === undefined) return null;
2714 return value === 'true';
2715 };
2716 }
2717
2718 /**
2719 * @api private
2720 */
2721 Shape.shapes = {
2722 StructureShape: StructureShape,
2723 ListShape: ListShape,
2724 MapShape: MapShape,
2725 StringShape: StringShape,
2726 BooleanShape: BooleanShape,
2727 Base64Shape: Base64Shape
2728 };
2729
2730 /**
2731 * @api private
2732 */
2733 module.exports = Shape;
2734
2735
2736/***/ }),
2737/* 20 */
2738/***/ (function(module, exports, __webpack_require__) {
2739
2740 var memoizedProperty = __webpack_require__(2).memoizedProperty;
2741
2742 function memoize(name, value, factory, nameTr) {
2743 memoizedProperty(this, nameTr(name), function() {
2744 return factory(name, value);
2745 });
2746 }
2747
2748 function Collection(iterable, options, factory, nameTr, callback) {
2749 nameTr = nameTr || String;
2750 var self = this;
2751
2752 for (var id in iterable) {
2753 if (Object.prototype.hasOwnProperty.call(iterable, id)) {
2754 memoize.call(self, id, iterable[id], factory, nameTr);
2755 if (callback) callback(id, iterable[id]);
2756 }
2757 }
2758 }
2759
2760 /**
2761 * @api private
2762 */
2763 module.exports = Collection;
2764
2765
2766/***/ }),
2767/* 21 */
2768/***/ (function(module, exports, __webpack_require__) {
2769
2770 var util = __webpack_require__(2);
2771 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2772
2773 function populateMethod(req) {
2774 req.httpRequest.method = req.service.api.operations[req.operation].httpMethod;
2775 }
2776
2777 function generateURI(endpointPath, operationPath, input, params) {
2778 var uri = [endpointPath, operationPath].join('/');
2779 uri = uri.replace(/\/+/g, '/');
2780
2781 var queryString = {}, queryStringSet = false;
2782 util.each(input.members, function (name, member) {
2783 var paramValue = params[name];
2784 if (paramValue === null || paramValue === undefined) return;
2785 if (member.location === 'uri') {
2786 var regex = new RegExp('\\{' + member.name + '(\\+)?\\}');
2787 uri = uri.replace(regex, function(_, plus) {
2788 var fn = plus ? util.uriEscapePath : util.uriEscape;
2789 return fn(String(paramValue));
2790 });
2791 } else if (member.location === 'querystring') {
2792 queryStringSet = true;
2793
2794 if (member.type === 'list') {
2795 queryString[member.name] = paramValue.map(function(val) {
2796 return util.uriEscape(member.member.toWireFormat(val).toString());
2797 });
2798 } else if (member.type === 'map') {
2799 util.each(paramValue, function(key, value) {
2800 if (Array.isArray(value)) {
2801 queryString[key] = value.map(function(val) {
2802 return util.uriEscape(String(val));
2803 });
2804 } else {
2805 queryString[key] = util.uriEscape(String(value));
2806 }
2807 });
2808 } else {
2809 queryString[member.name] = util.uriEscape(member.toWireFormat(paramValue).toString());
2810 }
2811 }
2812 });
2813
2814 if (queryStringSet) {
2815 uri += (uri.indexOf('?') >= 0 ? '&' : '?');
2816 var parts = [];
2817 util.arrayEach(Object.keys(queryString).sort(), function(key) {
2818 if (!Array.isArray(queryString[key])) {
2819 queryString[key] = [queryString[key]];
2820 }
2821 for (var i = 0; i < queryString[key].length; i++) {
2822 parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]);
2823 }
2824 });
2825 uri += parts.join('&');
2826 }
2827
2828 return uri;
2829 }
2830
2831 function populateURI(req) {
2832 var operation = req.service.api.operations[req.operation];
2833 var input = operation.input;
2834
2835 var uri = generateURI(req.httpRequest.endpoint.path, operation.httpPath, input, req.params);
2836 req.httpRequest.path = uri;
2837 }
2838
2839 function populateHeaders(req) {
2840 var operation = req.service.api.operations[req.operation];
2841 util.each(operation.input.members, function (name, member) {
2842 var value = req.params[name];
2843 if (value === null || value === undefined) return;
2844
2845 if (member.location === 'headers' && member.type === 'map') {
2846 util.each(value, function(key, memberValue) {
2847 req.httpRequest.headers[member.name + key] = memberValue;
2848 });
2849 } else if (member.location === 'header') {
2850 value = member.toWireFormat(value).toString();
2851 if (member.isJsonValue) {
2852 value = util.base64.encode(value);
2853 }
2854 req.httpRequest.headers[member.name] = value;
2855 }
2856 });
2857 }
2858
2859 function buildRequest(req) {
2860 populateMethod(req);
2861 populateURI(req);
2862 populateHeaders(req);
2863 populateHostPrefix(req);
2864 }
2865
2866 function extractError() {
2867 }
2868
2869 function extractData(resp) {
2870 var req = resp.request;
2871 var data = {};
2872 var r = resp.httpResponse;
2873 var operation = req.service.api.operations[req.operation];
2874 var output = operation.output;
2875
2876 // normalize headers names to lower-cased keys for matching
2877 var headers = {};
2878 util.each(r.headers, function (k, v) {
2879 headers[k.toLowerCase()] = v;
2880 });
2881
2882 util.each(output.members, function(name, member) {
2883 var header = (member.name || name).toLowerCase();
2884 if (member.location === 'headers' && member.type === 'map') {
2885 data[name] = {};
2886 var location = member.isLocationName ? member.name : '';
2887 var pattern = new RegExp('^' + location + '(.+)', 'i');
2888 util.each(r.headers, function (k, v) {
2889 var result = k.match(pattern);
2890 if (result !== null) {
2891 data[name][result[1]] = v;
2892 }
2893 });
2894 } else if (member.location === 'header') {
2895 if (headers[header] !== undefined) {
2896 var value = member.isJsonValue ?
2897 util.base64.decode(headers[header]) :
2898 headers[header];
2899 data[name] = member.toType(value);
2900 }
2901 } else if (member.location === 'statusCode') {
2902 data[name] = parseInt(r.statusCode, 10);
2903 }
2904 });
2905
2906 resp.data = data;
2907 }
2908
2909 /**
2910 * @api private
2911 */
2912 module.exports = {
2913 buildRequest: buildRequest,
2914 extractError: extractError,
2915 extractData: extractData,
2916 generateURI: generateURI
2917 };
2918
2919
2920/***/ }),
2921/* 22 */
2922/***/ (function(module, exports, __webpack_require__) {
2923
2924 var util = __webpack_require__(2);
2925 var Rest = __webpack_require__(21);
2926 var Json = __webpack_require__(13);
2927 var JsonBuilder = __webpack_require__(14);
2928 var JsonParser = __webpack_require__(15);
2929
2930 function populateBody(req) {
2931 var builder = new JsonBuilder();
2932 var input = req.service.api.operations[req.operation].input;
2933
2934 if (input.payload) {
2935 var params = {};
2936 var payloadShape = input.members[input.payload];
2937 params = req.params[input.payload];
2938 if (params === undefined) return;
2939
2940 if (payloadShape.type === 'structure') {
2941 req.httpRequest.body = builder.build(params, payloadShape);
2942 applyContentTypeHeader(req);
2943 } else { // non-JSON payload
2944 req.httpRequest.body = params;
2945 if (payloadShape.type === 'binary' || payloadShape.isStreaming) {
2946 applyContentTypeHeader(req, true);
2947 }
2948 }
2949 } else {
2950 var body = builder.build(req.params, input);
2951 if (body !== '{}' || req.httpRequest.method !== 'GET') { //don't send empty body for GET method
2952 req.httpRequest.body = body;
2953 }
2954 applyContentTypeHeader(req);
2955 }
2956 }
2957
2958 function applyContentTypeHeader(req, isBinary) {
2959 var operation = req.service.api.operations[req.operation];
2960 var input = operation.input;
2961
2962 if (!req.httpRequest.headers['Content-Type']) {
2963 var type = isBinary ? 'binary/octet-stream' : 'application/json';
2964 req.httpRequest.headers['Content-Type'] = type;
2965 }
2966 }
2967
2968 function buildRequest(req) {
2969 Rest.buildRequest(req);
2970
2971 // never send body payload on HEAD/DELETE
2972 if (['HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) {
2973 populateBody(req);
2974 }
2975 }
2976
2977 function extractError(resp) {
2978 Json.extractError(resp);
2979 }
2980
2981 function extractData(resp) {
2982 Rest.extractData(resp);
2983
2984 var req = resp.request;
2985 var operation = req.service.api.operations[req.operation];
2986 var rules = req.service.api.operations[req.operation].output || {};
2987 var parser;
2988 var hasEventOutput = operation.hasEventOutput;
2989
2990 if (rules.payload) {
2991 var payloadMember = rules.members[rules.payload];
2992 var body = resp.httpResponse.body;
2993 if (payloadMember.isEventStream) {
2994 parser = new JsonParser();
2995 resp.data[payload] = util.createEventStream(
2996 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : body,
2997 parser,
2998 payloadMember
2999 );
3000 } else if (payloadMember.type === 'structure' || payloadMember.type === 'list') {
3001 var parser = new JsonParser();
3002 resp.data[rules.payload] = parser.parse(body, payloadMember);
3003 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3004 resp.data[rules.payload] = body;
3005 } else {
3006 resp.data[rules.payload] = payloadMember.toType(body);
3007 }
3008 } else {
3009 var data = resp.data;
3010 Json.extractData(resp);
3011 resp.data = util.merge(data, resp.data);
3012 }
3013 }
3014
3015 /**
3016 * @api private
3017 */
3018 module.exports = {
3019 buildRequest: buildRequest,
3020 extractError: extractError,
3021 extractData: extractData
3022 };
3023
3024
3025/***/ }),
3026/* 23 */
3027/***/ (function(module, exports, __webpack_require__) {
3028
3029 var AWS = __webpack_require__(1);
3030 var util = __webpack_require__(2);
3031 var Rest = __webpack_require__(21);
3032
3033 function populateBody(req) {
3034 var input = req.service.api.operations[req.operation].input;
3035 var builder = new AWS.XML.Builder();
3036 var params = req.params;
3037
3038 var payload = input.payload;
3039 if (payload) {
3040 var payloadMember = input.members[payload];
3041 params = params[payload];
3042 if (params === undefined) return;
3043
3044 if (payloadMember.type === 'structure') {
3045 var rootElement = payloadMember.name;
3046 req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true);
3047 } else { // non-xml payload
3048 req.httpRequest.body = params;
3049 }
3050 } else {
3051 req.httpRequest.body = builder.toXML(params, input, input.name ||
3052 input.shape || util.string.upperFirst(req.operation) + 'Request');
3053 }
3054 }
3055
3056 function buildRequest(req) {
3057 Rest.buildRequest(req);
3058
3059 // never send body payload on GET/HEAD
3060 if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) {
3061 populateBody(req);
3062 }
3063 }
3064
3065 function extractError(resp) {
3066 Rest.extractError(resp);
3067
3068 var data;
3069 try {
3070 data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString());
3071 } catch (e) {
3072 data = {
3073 Code: resp.httpResponse.statusCode,
3074 Message: resp.httpResponse.statusMessage
3075 };
3076 }
3077
3078 if (data.Errors) data = data.Errors;
3079 if (data.Error) data = data.Error;
3080 if (data.Code) {
3081 resp.error = util.error(new Error(), {
3082 code: data.Code,
3083 message: data.Message
3084 });
3085 } else {
3086 resp.error = util.error(new Error(), {
3087 code: resp.httpResponse.statusCode,
3088 message: null
3089 });
3090 }
3091 }
3092
3093 function extractData(resp) {
3094 Rest.extractData(resp);
3095
3096 var parser;
3097 var req = resp.request;
3098 var body = resp.httpResponse.body;
3099 var operation = req.service.api.operations[req.operation];
3100 var output = operation.output;
3101
3102 var hasEventOutput = operation.hasEventOutput;
3103
3104 var payload = output.payload;
3105 if (payload) {
3106 var payloadMember = output.members[payload];
3107 if (payloadMember.isEventStream) {
3108 parser = new AWS.XML.Parser();
3109 resp.data[payload] = util.createEventStream(
3110 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : resp.httpResponse.body,
3111 parser,
3112 payloadMember
3113 );
3114 } else if (payloadMember.type === 'structure') {
3115 parser = new AWS.XML.Parser();
3116 resp.data[payload] = parser.parse(body.toString(), payloadMember);
3117 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3118 resp.data[payload] = body;
3119 } else {
3120 resp.data[payload] = payloadMember.toType(body);
3121 }
3122 } else if (body.length > 0) {
3123 parser = new AWS.XML.Parser();
3124 var data = parser.parse(body.toString(), output);
3125 util.update(resp.data, data);
3126 }
3127 }
3128
3129 /**
3130 * @api private
3131 */
3132 module.exports = {
3133 buildRequest: buildRequest,
3134 extractError: extractError,
3135 extractData: extractData
3136 };
3137
3138
3139/***/ }),
3140/* 24 */
3141/***/ (function(module, exports, __webpack_require__) {
3142
3143 var util = __webpack_require__(2);
3144 var XmlNode = __webpack_require__(25).XmlNode;
3145 var XmlText = __webpack_require__(27).XmlText;
3146
3147 function XmlBuilder() { }
3148
3149 XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) {
3150 var xml = new XmlNode(rootElement);
3151 applyNamespaces(xml, shape, true);
3152 serialize(xml, params, shape);
3153 return xml.children.length > 0 || noEmpty ? xml.toString() : '';
3154 };
3155
3156 function serialize(xml, value, shape) {
3157 switch (shape.type) {
3158 case 'structure': return serializeStructure(xml, value, shape);
3159 case 'map': return serializeMap(xml, value, shape);
3160 case 'list': return serializeList(xml, value, shape);
3161 default: return serializeScalar(xml, value, shape);
3162 }
3163 }
3164
3165 function serializeStructure(xml, params, shape) {
3166 util.arrayEach(shape.memberNames, function(memberName) {
3167 var memberShape = shape.members[memberName];
3168 if (memberShape.location !== 'body') return;
3169
3170 var value = params[memberName];
3171 var name = memberShape.name;
3172 if (value !== undefined && value !== null) {
3173 if (memberShape.isXmlAttribute) {
3174 xml.addAttribute(name, value);
3175 } else if (memberShape.flattened) {
3176 serialize(xml, value, memberShape);
3177 } else {
3178 var element = new XmlNode(name);
3179 xml.addChildNode(element);
3180 applyNamespaces(element, memberShape);
3181 serialize(element, value, memberShape);
3182 }
3183 }
3184 });
3185 }
3186
3187 function serializeMap(xml, map, shape) {
3188 var xmlKey = shape.key.name || 'key';
3189 var xmlValue = shape.value.name || 'value';
3190
3191 util.each(map, function(key, value) {
3192 var entry = new XmlNode(shape.flattened ? shape.name : 'entry');
3193 xml.addChildNode(entry);
3194
3195 var entryKey = new XmlNode(xmlKey);
3196 var entryValue = new XmlNode(xmlValue);
3197 entry.addChildNode(entryKey);
3198 entry.addChildNode(entryValue);
3199
3200 serialize(entryKey, key, shape.key);
3201 serialize(entryValue, value, shape.value);
3202 });
3203 }
3204
3205 function serializeList(xml, list, shape) {
3206 if (shape.flattened) {
3207 util.arrayEach(list, function(value) {
3208 var name = shape.member.name || shape.name;
3209 var element = new XmlNode(name);
3210 xml.addChildNode(element);
3211 serialize(element, value, shape.member);
3212 });
3213 } else {
3214 util.arrayEach(list, function(value) {
3215 var name = shape.member.name || 'member';
3216 var element = new XmlNode(name);
3217 xml.addChildNode(element);
3218 serialize(element, value, shape.member);
3219 });
3220 }
3221 }
3222
3223 function serializeScalar(xml, value, shape) {
3224 xml.addChildNode(
3225 new XmlText(shape.toWireFormat(value))
3226 );
3227 }
3228
3229 function applyNamespaces(xml, shape, isRoot) {
3230 var uri, prefix = 'xmlns';
3231 if (shape.xmlNamespaceUri) {
3232 uri = shape.xmlNamespaceUri;
3233 if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix;
3234 } else if (isRoot && shape.api.xmlNamespaceUri) {
3235 uri = shape.api.xmlNamespaceUri;
3236 }
3237
3238 if (uri) xml.addAttribute(prefix, uri);
3239 }
3240
3241 /**
3242 * @api private
3243 */
3244 module.exports = XmlBuilder;
3245
3246
3247/***/ }),
3248/* 25 */
3249/***/ (function(module, exports, __webpack_require__) {
3250
3251 var escapeAttribute = __webpack_require__(26).escapeAttribute;
3252
3253 /**
3254 * Represents an XML node.
3255 * @api private
3256 */
3257 function XmlNode(name, children) {
3258 if (children === void 0) { children = []; }
3259 this.name = name;
3260 this.children = children;
3261 this.attributes = {};
3262 }
3263 XmlNode.prototype.addAttribute = function (name, value) {
3264 this.attributes[name] = value;
3265 return this;
3266 };
3267 XmlNode.prototype.addChildNode = function (child) {
3268 this.children.push(child);
3269 return this;
3270 };
3271 XmlNode.prototype.removeAttribute = function (name) {
3272 delete this.attributes[name];
3273 return this;
3274 };
3275 XmlNode.prototype.toString = function () {
3276 var hasChildren = Boolean(this.children.length);
3277 var xmlText = '<' + this.name;
3278 // add attributes
3279 var attributes = this.attributes;
3280 for (var i = 0, attributeNames = Object.keys(attributes); i < attributeNames.length; i++) {
3281 var attributeName = attributeNames[i];
3282 var attribute = attributes[attributeName];
3283 if (typeof attribute !== 'undefined' && attribute !== null) {
3284 xmlText += ' ' + attributeName + '=\"' + escapeAttribute('' + attribute) + '\"';
3285 }
3286 }
3287 return xmlText += !hasChildren ? '/>' : '>' + this.children.map(function (c) { return c.toString(); }).join('') + '</' + this.name + '>';
3288 };
3289
3290 /**
3291 * @api private
3292 */
3293 module.exports = {
3294 XmlNode: XmlNode
3295 };
3296
3297
3298/***/ }),
3299/* 26 */
3300/***/ (function(module, exports) {
3301
3302 /**
3303 * Escapes characters that can not be in an XML attribute.
3304 */
3305 function escapeAttribute(value) {
3306 return value.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
3307 }
3308
3309 /**
3310 * @api private
3311 */
3312 module.exports = {
3313 escapeAttribute: escapeAttribute
3314 };
3315
3316
3317/***/ }),
3318/* 27 */
3319/***/ (function(module, exports, __webpack_require__) {
3320
3321 var escapeElement = __webpack_require__(28).escapeElement;
3322
3323 /**
3324 * Represents an XML text value.
3325 * @api private
3326 */
3327 function XmlText(value) {
3328 this.value = value;
3329 }
3330
3331 XmlText.prototype.toString = function () {
3332 return escapeElement('' + this.value);
3333 };
3334
3335 /**
3336 * @api private
3337 */
3338 module.exports = {
3339 XmlText: XmlText
3340 };
3341
3342
3343/***/ }),
3344/* 28 */
3345/***/ (function(module, exports) {
3346
3347 /**
3348 * Escapes characters that can not be in an XML element.
3349 */
3350 function escapeElement(value) {
3351 return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3352 }
3353
3354 /**
3355 * @api private
3356 */
3357 module.exports = {
3358 escapeElement: escapeElement
3359 };
3360
3361
3362/***/ }),
3363/* 29 */
3364/***/ (function(module, exports, __webpack_require__) {
3365
3366 var Collection = __webpack_require__(20);
3367 var Operation = __webpack_require__(30);
3368 var Shape = __webpack_require__(19);
3369 var Paginator = __webpack_require__(31);
3370 var ResourceWaiter = __webpack_require__(32);
3371
3372 var util = __webpack_require__(2);
3373 var property = util.property;
3374 var memoizedProperty = util.memoizedProperty;
3375
3376 function Api(api, options) {
3377 var self = this;
3378 api = api || {};
3379 options = options || {};
3380 options.api = this;
3381
3382 api.metadata = api.metadata || {};
3383
3384 property(this, 'isApi', true, false);
3385 property(this, 'apiVersion', api.metadata.apiVersion);
3386 property(this, 'endpointPrefix', api.metadata.endpointPrefix);
3387 property(this, 'signingName', api.metadata.signingName);
3388 property(this, 'globalEndpoint', api.metadata.globalEndpoint);
3389 property(this, 'signatureVersion', api.metadata.signatureVersion);
3390 property(this, 'jsonVersion', api.metadata.jsonVersion);
3391 property(this, 'targetPrefix', api.metadata.targetPrefix);
3392 property(this, 'protocol', api.metadata.protocol);
3393 property(this, 'timestampFormat', api.metadata.timestampFormat);
3394 property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace);
3395 property(this, 'abbreviation', api.metadata.serviceAbbreviation);
3396 property(this, 'fullName', api.metadata.serviceFullName);
3397 property(this, 'serviceId', api.metadata.serviceId);
3398
3399 memoizedProperty(this, 'className', function() {
3400 var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName;
3401 if (!name) return null;
3402
3403 name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, '');
3404 if (name === 'ElasticLoadBalancing') name = 'ELB';
3405 return name;
3406 });
3407
3408 function addEndpointOperation(name, operation) {
3409 if (operation.endpointoperation === true) {
3410 property(self, 'endpointOperation', util.string.lowerFirst(name));
3411 }
3412 }
3413
3414 property(this, 'operations', new Collection(api.operations, options, function(name, operation) {
3415 return new Operation(name, operation, options);
3416 }, util.string.lowerFirst, addEndpointOperation));
3417
3418 property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) {
3419 return Shape.create(shape, options);
3420 }));
3421
3422 property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) {
3423 return new Paginator(name, paginator, options);
3424 }));
3425
3426 property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) {
3427 return new ResourceWaiter(name, waiter, options);
3428 }, util.string.lowerFirst));
3429
3430 if (options.documentation) {
3431 property(this, 'documentation', api.documentation);
3432 property(this, 'documentationUrl', api.documentationUrl);
3433 }
3434 }
3435
3436 /**
3437 * @api private
3438 */
3439 module.exports = Api;
3440
3441
3442/***/ }),
3443/* 30 */
3444/***/ (function(module, exports, __webpack_require__) {
3445
3446 var Shape = __webpack_require__(19);
3447
3448 var util = __webpack_require__(2);
3449 var property = util.property;
3450 var memoizedProperty = util.memoizedProperty;
3451
3452 function Operation(name, operation, options) {
3453 var self = this;
3454 options = options || {};
3455
3456 property(this, 'name', operation.name || name);
3457 property(this, 'api', options.api, false);
3458
3459 operation.http = operation.http || {};
3460 property(this, 'endpoint', operation.endpoint);
3461 property(this, 'httpMethod', operation.http.method || 'POST');
3462 property(this, 'httpPath', operation.http.requestUri || '/');
3463 property(this, 'authtype', operation.authtype || '');
3464 property(
3465 this,
3466 'endpointDiscoveryRequired',
3467 operation.endpointdiscovery ?
3468 (operation.endpointdiscovery.required ? 'REQUIRED' : 'OPTIONAL') :
3469 'NULL'
3470 );
3471
3472 memoizedProperty(this, 'input', function() {
3473 if (!operation.input) {
3474 return new Shape.create({type: 'structure'}, options);
3475 }
3476 return Shape.create(operation.input, options);
3477 });
3478
3479 memoizedProperty(this, 'output', function() {
3480 if (!operation.output) {
3481 return new Shape.create({type: 'structure'}, options);
3482 }
3483 return Shape.create(operation.output, options);
3484 });
3485
3486 memoizedProperty(this, 'errors', function() {
3487 var list = [];
3488 if (!operation.errors) return null;
3489
3490 for (var i = 0; i < operation.errors.length; i++) {
3491 list.push(Shape.create(operation.errors[i], options));
3492 }
3493
3494 return list;
3495 });
3496
3497 memoizedProperty(this, 'paginator', function() {
3498 return options.api.paginators[name];
3499 });
3500
3501 if (options.documentation) {
3502 property(this, 'documentation', operation.documentation);
3503 property(this, 'documentationUrl', operation.documentationUrl);
3504 }
3505
3506 // idempotentMembers only tracks top-level input shapes
3507 memoizedProperty(this, 'idempotentMembers', function() {
3508 var idempotentMembers = [];
3509 var input = self.input;
3510 var members = input.members;
3511 if (!input.members) {
3512 return idempotentMembers;
3513 }
3514 for (var name in members) {
3515 if (!members.hasOwnProperty(name)) {
3516 continue;
3517 }
3518 if (members[name].isIdempotent === true) {
3519 idempotentMembers.push(name);
3520 }
3521 }
3522 return idempotentMembers;
3523 });
3524
3525 memoizedProperty(this, 'hasEventOutput', function() {
3526 var output = self.output;
3527 return hasEventStream(output);
3528 });
3529 }
3530
3531 function hasEventStream(topLevelShape) {
3532 var members = topLevelShape.members;
3533 var payload = topLevelShape.payload;
3534
3535 if (!topLevelShape.members) {
3536 return false;
3537 }
3538
3539 if (payload) {
3540 var payloadMember = members[payload];
3541 return payloadMember.isEventStream;
3542 }
3543
3544 // check if any member is an event stream
3545 for (var name in members) {
3546 if (!members.hasOwnProperty(name)) {
3547 if (members[name].isEventStream === true) {
3548 return true;
3549 }
3550 }
3551 }
3552 return false;
3553 }
3554
3555 /**
3556 * @api private
3557 */
3558 module.exports = Operation;
3559
3560
3561/***/ }),
3562/* 31 */
3563/***/ (function(module, exports, __webpack_require__) {
3564
3565 var property = __webpack_require__(2).property;
3566
3567 function Paginator(name, paginator) {
3568 property(this, 'inputToken', paginator.input_token);
3569 property(this, 'limitKey', paginator.limit_key);
3570 property(this, 'moreResults', paginator.more_results);
3571 property(this, 'outputToken', paginator.output_token);
3572 property(this, 'resultKey', paginator.result_key);
3573 }
3574
3575 /**
3576 * @api private
3577 */
3578 module.exports = Paginator;
3579
3580
3581/***/ }),
3582/* 32 */
3583/***/ (function(module, exports, __webpack_require__) {
3584
3585 var util = __webpack_require__(2);
3586 var property = util.property;
3587
3588 function ResourceWaiter(name, waiter, options) {
3589 options = options || {};
3590 property(this, 'name', name);
3591 property(this, 'api', options.api, false);
3592
3593 if (waiter.operation) {
3594 property(this, 'operation', util.string.lowerFirst(waiter.operation));
3595 }
3596
3597 var self = this;
3598 var keys = [
3599 'type',
3600 'description',
3601 'delay',
3602 'maxAttempts',
3603 'acceptors'
3604 ];
3605
3606 keys.forEach(function(key) {
3607 var value = waiter[key];
3608 if (value) {
3609 property(self, key, value);
3610 }
3611 });
3612 }
3613
3614 /**
3615 * @api private
3616 */
3617 module.exports = ResourceWaiter;
3618
3619
3620/***/ }),
3621/* 33 */
3622/***/ (function(module, exports) {
3623
3624 function apiLoader(svc, version) {
3625 if (!apiLoader.services.hasOwnProperty(svc)) {
3626 throw new Error('InvalidService: Failed to load api for ' + svc);
3627 }
3628 return apiLoader.services[svc][version];
3629 }
3630
3631 /**
3632 * @api private
3633 *
3634 * This member of AWS.apiLoader is private, but changing it will necessitate a
3635 * change to ../scripts/services-table-generator.ts
3636 */
3637 apiLoader.services = {};
3638
3639 /**
3640 * @api private
3641 */
3642 module.exports = apiLoader;
3643
3644
3645/***/ }),
3646/* 34 */
3647/***/ (function(module, exports, __webpack_require__) {
3648
3649 "use strict";
3650 Object.defineProperty(exports, "__esModule", { value: true });
3651 var LRU_1 = __webpack_require__(35);
3652 var CACHE_SIZE = 1000;
3653 /**
3654 * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache]
3655 */
3656 var EndpointCache = /** @class */ (function () {
3657 function EndpointCache(maxSize) {
3658 if (maxSize === void 0) { maxSize = CACHE_SIZE; }
3659 this.maxSize = maxSize;
3660 this.cache = new LRU_1.LRUCache(maxSize);
3661 }
3662 ;
3663 Object.defineProperty(EndpointCache.prototype, "size", {
3664 get: function () {
3665 return this.cache.length;
3666 },
3667 enumerable: true,
3668 configurable: true
3669 });
3670 EndpointCache.prototype.put = function (key, value) {
3671 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3672 var endpointRecord = this.populateValue(value);
3673 this.cache.put(keyString, endpointRecord);
3674 };
3675 EndpointCache.prototype.get = function (key) {
3676 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3677 var now = Date.now();
3678 var records = this.cache.get(keyString);
3679 if (records) {
3680 for (var i = 0; i < records.length; i++) {
3681 var record = records[i];
3682 if (record.Expire < now) {
3683 this.cache.remove(keyString);
3684 return undefined;
3685 }
3686 }
3687 }
3688 return records;
3689 };
3690 EndpointCache.getKeyString = function (key) {
3691 var identifiers = [];
3692 var identifierNames = Object.keys(key).sort();
3693 for (var i = 0; i < identifierNames.length; i++) {
3694 var identifierName = identifierNames[i];
3695 if (key[identifierName] === undefined)
3696 continue;
3697 identifiers.push(key[identifierName]);
3698 }
3699 return identifiers.join(' ');
3700 };
3701 EndpointCache.prototype.populateValue = function (endpoints) {
3702 var now = Date.now();
3703 return endpoints.map(function (endpoint) { return ({
3704 Address: endpoint.Address || '',
3705 Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000
3706 }); });
3707 };
3708 EndpointCache.prototype.empty = function () {
3709 this.cache.empty();
3710 };
3711 EndpointCache.prototype.remove = function (key) {
3712 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3713 this.cache.remove(keyString);
3714 };
3715 return EndpointCache;
3716 }());
3717 exports.EndpointCache = EndpointCache;
3718
3719/***/ }),
3720/* 35 */
3721/***/ (function(module, exports) {
3722
3723 "use strict";
3724 Object.defineProperty(exports, "__esModule", { value: true });
3725 var LinkedListNode = /** @class */ (function () {
3726 function LinkedListNode(key, value) {
3727 this.key = key;
3728 this.value = value;
3729 }
3730 return LinkedListNode;
3731 }());
3732 var LRUCache = /** @class */ (function () {
3733 function LRUCache(size) {
3734 this.nodeMap = {};
3735 this.size = 0;
3736 if (typeof size !== 'number' || size < 1) {
3737 throw new Error('Cache size can only be positive number');
3738 }
3739 this.sizeLimit = size;
3740 }
3741 Object.defineProperty(LRUCache.prototype, "length", {
3742 get: function () {
3743 return this.size;
3744 },
3745 enumerable: true,
3746 configurable: true
3747 });
3748 LRUCache.prototype.prependToList = function (node) {
3749 if (!this.headerNode) {
3750 this.tailNode = node;
3751 }
3752 else {
3753 this.headerNode.prev = node;
3754 node.next = this.headerNode;
3755 }
3756 this.headerNode = node;
3757 this.size++;
3758 };
3759 LRUCache.prototype.removeFromTail = function () {
3760 if (!this.tailNode) {
3761 return undefined;
3762 }
3763 var node = this.tailNode;
3764 var prevNode = node.prev;
3765 if (prevNode) {
3766 prevNode.next = undefined;
3767 }
3768 node.prev = undefined;
3769 this.tailNode = prevNode;
3770 this.size--;
3771 return node;
3772 };
3773 LRUCache.prototype.detachFromList = function (node) {
3774 if (this.headerNode === node) {
3775 this.headerNode = node.next;
3776 }
3777 if (this.tailNode === node) {
3778 this.tailNode = node.prev;
3779 }
3780 if (node.prev) {
3781 node.prev.next = node.next;
3782 }
3783 if (node.next) {
3784 node.next.prev = node.prev;
3785 }
3786 node.next = undefined;
3787 node.prev = undefined;
3788 this.size--;
3789 };
3790 LRUCache.prototype.get = function (key) {
3791 if (this.nodeMap[key]) {
3792 var node = this.nodeMap[key];
3793 this.detachFromList(node);
3794 this.prependToList(node);
3795 return node.value;
3796 }
3797 };
3798 LRUCache.prototype.remove = function (key) {
3799 if (this.nodeMap[key]) {
3800 var node = this.nodeMap[key];
3801 this.detachFromList(node);
3802 delete this.nodeMap[key];
3803 }
3804 };
3805 LRUCache.prototype.put = function (key, value) {
3806 if (this.nodeMap[key]) {
3807 this.remove(key);
3808 }
3809 else if (this.size === this.sizeLimit) {
3810 var tailNode = this.removeFromTail();
3811 var key_1 = tailNode.key;
3812 delete this.nodeMap[key_1];
3813 }
3814 var newNode = new LinkedListNode(key, value);
3815 this.nodeMap[key] = newNode;
3816 this.prependToList(newNode);
3817 };
3818 LRUCache.prototype.empty = function () {
3819 var keys = Object.keys(this.nodeMap);
3820 for (var i = 0; i < keys.length; i++) {
3821 var key = keys[i];
3822 var node = this.nodeMap[key];
3823 this.detachFromList(node);
3824 delete this.nodeMap[key];
3825 }
3826 };
3827 return LRUCache;
3828 }());
3829 exports.LRUCache = LRUCache;
3830
3831/***/ }),
3832/* 36 */
3833/***/ (function(module, exports, __webpack_require__) {
3834
3835 var AWS = __webpack_require__(1);
3836
3837 /**
3838 * @api private
3839 * @!method on(eventName, callback)
3840 * Registers an event listener callback for the event given by `eventName`.
3841 * Parameters passed to the callback function depend on the individual event
3842 * being triggered. See the event documentation for those parameters.
3843 *
3844 * @param eventName [String] the event name to register the listener for
3845 * @param callback [Function] the listener callback function
3846 * @param toHead [Boolean] attach the listener callback to the head of callback array if set to true.
3847 * Default to be false.
3848 * @return [AWS.SequentialExecutor] the same object for chaining
3849 */
3850 AWS.SequentialExecutor = AWS.util.inherit({
3851
3852 constructor: function SequentialExecutor() {
3853 this._events = {};
3854 },
3855
3856 /**
3857 * @api private
3858 */
3859 listeners: function listeners(eventName) {
3860 return this._events[eventName] ? this._events[eventName].slice(0) : [];
3861 },
3862
3863 on: function on(eventName, listener, toHead) {
3864 if (this._events[eventName]) {
3865 toHead ?
3866 this._events[eventName].unshift(listener) :
3867 this._events[eventName].push(listener);
3868 } else {
3869 this._events[eventName] = [listener];
3870 }
3871 return this;
3872 },
3873
3874 onAsync: function onAsync(eventName, listener, toHead) {
3875 listener._isAsync = true;
3876 return this.on(eventName, listener, toHead);
3877 },
3878
3879 removeListener: function removeListener(eventName, listener) {
3880 var listeners = this._events[eventName];
3881 if (listeners) {
3882 var length = listeners.length;
3883 var position = -1;
3884 for (var i = 0; i < length; ++i) {
3885 if (listeners[i] === listener) {
3886 position = i;
3887 }
3888 }
3889 if (position > -1) {
3890 listeners.splice(position, 1);
3891 }
3892 }
3893 return this;
3894 },
3895
3896 removeAllListeners: function removeAllListeners(eventName) {
3897 if (eventName) {
3898 delete this._events[eventName];
3899 } else {
3900 this._events = {};
3901 }
3902 return this;
3903 },
3904
3905 /**
3906 * @api private
3907 */
3908 emit: function emit(eventName, eventArgs, doneCallback) {
3909 if (!doneCallback) doneCallback = function() { };
3910 var listeners = this.listeners(eventName);
3911 var count = listeners.length;
3912 this.callListeners(listeners, eventArgs, doneCallback);
3913 return count > 0;
3914 },
3915
3916 /**
3917 * @api private
3918 */
3919 callListeners: function callListeners(listeners, args, doneCallback, prevError) {
3920 var self = this;
3921 var error = prevError || null;
3922
3923 function callNextListener(err) {
3924 if (err) {
3925 error = AWS.util.error(error || new Error(), err);
3926 if (self._haltHandlersOnError) {
3927 return doneCallback.call(self, error);
3928 }
3929 }
3930 self.callListeners(listeners, args, doneCallback, error);
3931 }
3932
3933 while (listeners.length > 0) {
3934 var listener = listeners.shift();
3935 if (listener._isAsync) { // asynchronous listener
3936 listener.apply(self, args.concat([callNextListener]));
3937 return; // stop here, callNextListener will continue
3938 } else { // synchronous listener
3939 try {
3940 listener.apply(self, args);
3941 } catch (err) {
3942 error = AWS.util.error(error || new Error(), err);
3943 }
3944 if (error && self._haltHandlersOnError) {
3945 doneCallback.call(self, error);
3946 return;
3947 }
3948 }
3949 }
3950 doneCallback.call(self, error);
3951 },
3952
3953 /**
3954 * Adds or copies a set of listeners from another list of
3955 * listeners or SequentialExecutor object.
3956 *
3957 * @param listeners [map<String,Array<Function>>, AWS.SequentialExecutor]
3958 * a list of events and callbacks, or an event emitter object
3959 * containing listeners to add to this emitter object.
3960 * @return [AWS.SequentialExecutor] the emitter object, for chaining.
3961 * @example Adding listeners from a map of listeners
3962 * emitter.addListeners({
3963 * event1: [function() { ... }, function() { ... }],
3964 * event2: [function() { ... }]
3965 * });
3966 * emitter.emit('event1'); // emitter has event1
3967 * emitter.emit('event2'); // emitter has event2
3968 * @example Adding listeners from another emitter object
3969 * var emitter1 = new AWS.SequentialExecutor();
3970 * emitter1.on('event1', function() { ... });
3971 * emitter1.on('event2', function() { ... });
3972 * var emitter2 = new AWS.SequentialExecutor();
3973 * emitter2.addListeners(emitter1);
3974 * emitter2.emit('event1'); // emitter2 has event1
3975 * emitter2.emit('event2'); // emitter2 has event2
3976 */
3977 addListeners: function addListeners(listeners) {
3978 var self = this;
3979
3980 // extract listeners if parameter is an SequentialExecutor object
3981 if (listeners._events) listeners = listeners._events;
3982
3983 AWS.util.each(listeners, function(event, callbacks) {
3984 if (typeof callbacks === 'function') callbacks = [callbacks];
3985 AWS.util.arrayEach(callbacks, function(callback) {
3986 self.on(event, callback);
3987 });
3988 });
3989
3990 return self;
3991 },
3992
3993 /**
3994 * Registers an event with {on} and saves the callback handle function
3995 * as a property on the emitter object using a given `name`.
3996 *
3997 * @param name [String] the property name to set on this object containing
3998 * the callback function handle so that the listener can be removed in
3999 * the future.
4000 * @param (see on)
4001 * @return (see on)
4002 * @example Adding a named listener DATA_CALLBACK
4003 * var listener = function() { doSomething(); };
4004 * emitter.addNamedListener('DATA_CALLBACK', 'data', listener);
4005 *
4006 * // the following prints: true
4007 * console.log(emitter.DATA_CALLBACK == listener);
4008 */
4009 addNamedListener: function addNamedListener(name, eventName, callback, toHead) {
4010 this[name] = callback;
4011 this.addListener(eventName, callback, toHead);
4012 return this;
4013 },
4014
4015 /**
4016 * @api private
4017 */
4018 addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback, toHead) {
4019 callback._isAsync = true;
4020 return this.addNamedListener(name, eventName, callback, toHead);
4021 },
4022
4023 /**
4024 * Helper method to add a set of named listeners using
4025 * {addNamedListener}. The callback contains a parameter
4026 * with a handle to the `addNamedListener` method.
4027 *
4028 * @callback callback function(add)
4029 * The callback function is called immediately in order to provide
4030 * the `add` function to the block. This simplifies the addition of
4031 * a large group of named listeners.
4032 * @param add [Function] the {addNamedListener} function to call
4033 * when registering listeners.
4034 * @example Adding a set of named listeners
4035 * emitter.addNamedListeners(function(add) {
4036 * add('DATA_CALLBACK', 'data', function() { ... });
4037 * add('OTHER', 'otherEvent', function() { ... });
4038 * add('LAST', 'lastEvent', function() { ... });
4039 * });
4040 *
4041 * // these properties are now set:
4042 * emitter.DATA_CALLBACK;
4043 * emitter.OTHER;
4044 * emitter.LAST;
4045 */
4046 addNamedListeners: function addNamedListeners(callback) {
4047 var self = this;
4048 callback(
4049 function() {
4050 self.addNamedListener.apply(self, arguments);
4051 },
4052 function() {
4053 self.addNamedAsyncListener.apply(self, arguments);
4054 }
4055 );
4056 return this;
4057 }
4058 });
4059
4060 /**
4061 * {on} is the prefered method.
4062 * @api private
4063 */
4064 AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on;
4065
4066 /**
4067 * @api private
4068 */
4069 module.exports = AWS.SequentialExecutor;
4070
4071
4072/***/ }),
4073/* 37 */
4074/***/ (function(module, exports, __webpack_require__) {
4075
4076 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
4077 var Api = __webpack_require__(29);
4078 var regionConfig = __webpack_require__(38);
4079
4080 var inherit = AWS.util.inherit;
4081 var clientCount = 0;
4082
4083 /**
4084 * The service class representing an AWS service.
4085 *
4086 * @class_abstract This class is an abstract class.
4087 *
4088 * @!attribute apiVersions
4089 * @return [Array<String>] the list of API versions supported by this service.
4090 * @readonly
4091 */
4092 AWS.Service = inherit({
4093 /**
4094 * Create a new service object with a configuration object
4095 *
4096 * @param config [map] a map of configuration options
4097 */
4098 constructor: function Service(config) {
4099 if (!this.loadServiceClass) {
4100 throw AWS.util.error(new Error(),
4101 'Service must be constructed with `new\' operator');
4102 }
4103 var ServiceClass = this.loadServiceClass(config || {});
4104 if (ServiceClass) {
4105 var originalConfig = AWS.util.copy(config);
4106 var svc = new ServiceClass(config);
4107 Object.defineProperty(svc, '_originalConfig', {
4108 get: function() { return originalConfig; },
4109 enumerable: false,
4110 configurable: true
4111 });
4112 svc._clientId = ++clientCount;
4113 return svc;
4114 }
4115 this.initialize(config);
4116 },
4117
4118 /**
4119 * @api private
4120 */
4121 initialize: function initialize(config) {
4122 var svcConfig = AWS.config[this.serviceIdentifier];
4123 this.config = new AWS.Config(AWS.config);
4124 if (svcConfig) this.config.update(svcConfig, true);
4125 if (config) this.config.update(config, true);
4126
4127 this.validateService();
4128 if (!this.config.endpoint) regionConfig(this);
4129
4130 this.config.endpoint = this.endpointFromTemplate(this.config.endpoint);
4131 this.setEndpoint(this.config.endpoint);
4132 //enable attaching listeners to service client
4133 AWS.SequentialExecutor.call(this);
4134 AWS.Service.addDefaultMonitoringListeners(this);
4135 if ((this.config.clientSideMonitoring || AWS.Service._clientSideMonitoring) && this.publisher) {
4136 var publisher = this.publisher;
4137 this.addNamedListener('PUBLISH_API_CALL', 'apiCall', function PUBLISH_API_CALL(event) {
4138 process.nextTick(function() {publisher.eventHandler(event);});
4139 });
4140 this.addNamedListener('PUBLISH_API_ATTEMPT', 'apiCallAttempt', function PUBLISH_API_ATTEMPT(event) {
4141 process.nextTick(function() {publisher.eventHandler(event);});
4142 });
4143 }
4144 },
4145
4146 /**
4147 * @api private
4148 */
4149 validateService: function validateService() {
4150 },
4151
4152 /**
4153 * @api private
4154 */
4155 loadServiceClass: function loadServiceClass(serviceConfig) {
4156 var config = serviceConfig;
4157 if (!AWS.util.isEmpty(this.api)) {
4158 return null;
4159 } else if (config.apiConfig) {
4160 return AWS.Service.defineServiceApi(this.constructor, config.apiConfig);
4161 } else if (!this.constructor.services) {
4162 return null;
4163 } else {
4164 config = new AWS.Config(AWS.config);
4165 config.update(serviceConfig, true);
4166 var version = config.apiVersions[this.constructor.serviceIdentifier];
4167 version = version || config.apiVersion;
4168 return this.getLatestServiceClass(version);
4169 }
4170 },
4171
4172 /**
4173 * @api private
4174 */
4175 getLatestServiceClass: function getLatestServiceClass(version) {
4176 version = this.getLatestServiceVersion(version);
4177 if (this.constructor.services[version] === null) {
4178 AWS.Service.defineServiceApi(this.constructor, version);
4179 }
4180
4181 return this.constructor.services[version];
4182 },
4183
4184 /**
4185 * @api private
4186 */
4187 getLatestServiceVersion: function getLatestServiceVersion(version) {
4188 if (!this.constructor.services || this.constructor.services.length === 0) {
4189 throw new Error('No services defined on ' +
4190 this.constructor.serviceIdentifier);
4191 }
4192
4193 if (!version) {
4194 version = 'latest';
4195 } else if (AWS.util.isType(version, Date)) {
4196 version = AWS.util.date.iso8601(version).split('T')[0];
4197 }
4198
4199 if (Object.hasOwnProperty(this.constructor.services, version)) {
4200 return version;
4201 }
4202
4203 var keys = Object.keys(this.constructor.services).sort();
4204 var selectedVersion = null;
4205 for (var i = keys.length - 1; i >= 0; i--) {
4206 // versions that end in "*" are not available on disk and can be
4207 // skipped, so do not choose these as selectedVersions
4208 if (keys[i][keys[i].length - 1] !== '*') {
4209 selectedVersion = keys[i];
4210 }
4211 if (keys[i].substr(0, 10) <= version) {
4212 return selectedVersion;
4213 }
4214 }
4215
4216 throw new Error('Could not find ' + this.constructor.serviceIdentifier +
4217 ' API to satisfy version constraint `' + version + '\'');
4218 },
4219
4220 /**
4221 * @api private
4222 */
4223 api: {},
4224
4225 /**
4226 * @api private
4227 */
4228 defaultRetryCount: 3,
4229
4230 /**
4231 * @api private
4232 */
4233 customizeRequests: function customizeRequests(callback) {
4234 if (!callback) {
4235 this.customRequestHandler = null;
4236 } else if (typeof callback === 'function') {
4237 this.customRequestHandler = callback;
4238 } else {
4239 throw new Error('Invalid callback type \'' + typeof callback + '\' provided in customizeRequests');
4240 }
4241 },
4242
4243 /**
4244 * Calls an operation on a service with the given input parameters.
4245 *
4246 * @param operation [String] the name of the operation to call on the service.
4247 * @param params [map] a map of input options for the operation
4248 * @callback callback function(err, data)
4249 * If a callback is supplied, it is called when a response is returned
4250 * from the service.
4251 * @param err [Error] the error object returned from the request.
4252 * Set to `null` if the request is successful.
4253 * @param data [Object] the de-serialized data returned from
4254 * the request. Set to `null` if a request error occurs.
4255 */
4256 makeRequest: function makeRequest(operation, params, callback) {
4257 if (typeof params === 'function') {
4258 callback = params;
4259 params = null;
4260 }
4261
4262 params = params || {};
4263 if (this.config.params) { // copy only toplevel bound params
4264 var rules = this.api.operations[operation];
4265 if (rules) {
4266 params = AWS.util.copy(params);
4267 AWS.util.each(this.config.params, function(key, value) {
4268 if (rules.input.members[key]) {
4269 if (params[key] === undefined || params[key] === null) {
4270 params[key] = value;
4271 }
4272 }
4273 });
4274 }
4275 }
4276
4277 var request = new AWS.Request(this, operation, params);
4278 this.addAllRequestListeners(request);
4279 this.attachMonitoringEmitter(request);
4280 if (callback) request.send(callback);
4281 return request;
4282 },
4283
4284 /**
4285 * Calls an operation on a service with the given input parameters, without
4286 * any authentication data. This method is useful for "public" API operations.
4287 *
4288 * @param operation [String] the name of the operation to call on the service.
4289 * @param params [map] a map of input options for the operation
4290 * @callback callback function(err, data)
4291 * If a callback is supplied, it is called when a response is returned
4292 * from the service.
4293 * @param err [Error] the error object returned from the request.
4294 * Set to `null` if the request is successful.
4295 * @param data [Object] the de-serialized data returned from
4296 * the request. Set to `null` if a request error occurs.
4297 */
4298 makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) {
4299 if (typeof params === 'function') {
4300 callback = params;
4301 params = {};
4302 }
4303
4304 var request = this.makeRequest(operation, params).toUnauthenticated();
4305 return callback ? request.send(callback) : request;
4306 },
4307
4308 /**
4309 * Waits for a given state
4310 *
4311 * @param state [String] the state on the service to wait for
4312 * @param params [map] a map of parameters to pass with each request
4313 * @option params $waiter [map] a map of configuration options for the waiter
4314 * @option params $waiter.delay [Number] The number of seconds to wait between
4315 * requests
4316 * @option params $waiter.maxAttempts [Number] The maximum number of requests
4317 * to send while waiting
4318 * @callback callback function(err, data)
4319 * If a callback is supplied, it is called when a response is returned
4320 * from the service.
4321 * @param err [Error] the error object returned from the request.
4322 * Set to `null` if the request is successful.
4323 * @param data [Object] the de-serialized data returned from
4324 * the request. Set to `null` if a request error occurs.
4325 */
4326 waitFor: function waitFor(state, params, callback) {
4327 var waiter = new AWS.ResourceWaiter(this, state);
4328 return waiter.wait(params, callback);
4329 },
4330
4331 /**
4332 * @api private
4333 */
4334 addAllRequestListeners: function addAllRequestListeners(request) {
4335 var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(),
4336 AWS.EventListeners.CorePost];
4337 for (var i = 0; i < list.length; i++) {
4338 if (list[i]) request.addListeners(list[i]);
4339 }
4340
4341 // disable parameter validation
4342 if (!this.config.paramValidation) {
4343 request.removeListener('validate',
4344 AWS.EventListeners.Core.VALIDATE_PARAMETERS);
4345 }
4346
4347 if (this.config.logger) { // add logging events
4348 request.addListeners(AWS.EventListeners.Logger);
4349 }
4350
4351 this.setupRequestListeners(request);
4352 // call prototype's customRequestHandler
4353 if (typeof this.constructor.prototype.customRequestHandler === 'function') {
4354 this.constructor.prototype.customRequestHandler(request);
4355 }
4356 // call instance's customRequestHandler
4357 if (Object.prototype.hasOwnProperty.call(this, 'customRequestHandler') && typeof this.customRequestHandler === 'function') {
4358 this.customRequestHandler(request);
4359 }
4360 },
4361
4362 /**
4363 * Event recording metrics for a whole API call.
4364 * @returns {object} a subset of api call metrics
4365 * @api private
4366 */
4367 apiCallEvent: function apiCallEvent(request) {
4368 var api = request.service.api.operations[request.operation];
4369 var monitoringEvent = {
4370 Type: 'ApiCall',
4371 Api: api ? api.name : request.operation,
4372 Version: 1,
4373 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4374 Region: request.httpRequest.region,
4375 MaxRetriesExceeded: 0,
4376 UserAgent: request.httpRequest.getUserAgent(),
4377 };
4378 var response = request.response;
4379 if (response.httpResponse.statusCode) {
4380 monitoringEvent.FinalHttpStatusCode = response.httpResponse.statusCode;
4381 }
4382 if (response.error) {
4383 var error = response.error;
4384 var statusCode = response.httpResponse.statusCode;
4385 if (statusCode > 299) {
4386 if (error.code) monitoringEvent.FinalAwsException = error.code;
4387 if (error.message) monitoringEvent.FinalAwsExceptionMessage = error.message;
4388 } else {
4389 if (error.code || error.name) monitoringEvent.FinalSdkException = error.code || error.name;
4390 if (error.message) monitoringEvent.FinalSdkExceptionMessage = error.message;
4391 }
4392 }
4393 return monitoringEvent;
4394 },
4395
4396 /**
4397 * Event recording metrics for an API call attempt.
4398 * @returns {object} a subset of api call attempt metrics
4399 * @api private
4400 */
4401 apiAttemptEvent: function apiAttemptEvent(request) {
4402 var api = request.service.api.operations[request.operation];
4403 var monitoringEvent = {
4404 Type: 'ApiCallAttempt',
4405 Api: api ? api.name : request.operation,
4406 Version: 1,
4407 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4408 Fqdn: request.httpRequest.endpoint.hostname,
4409 UserAgent: request.httpRequest.getUserAgent(),
4410 };
4411 var response = request.response;
4412 if (response.httpResponse.statusCode) {
4413 monitoringEvent.HttpStatusCode = response.httpResponse.statusCode;
4414 }
4415 if (
4416 !request._unAuthenticated &&
4417 request.service.config.credentials &&
4418 request.service.config.credentials.accessKeyId
4419 ) {
4420 monitoringEvent.AccessKey = request.service.config.credentials.accessKeyId;
4421 }
4422 if (!response.httpResponse.headers) return monitoringEvent;
4423 if (request.httpRequest.headers['x-amz-security-token']) {
4424 monitoringEvent.SessionToken = request.httpRequest.headers['x-amz-security-token'];
4425 }
4426 if (response.httpResponse.headers['x-amzn-requestid']) {
4427 monitoringEvent.XAmznRequestId = response.httpResponse.headers['x-amzn-requestid'];
4428 }
4429 if (response.httpResponse.headers['x-amz-request-id']) {
4430 monitoringEvent.XAmzRequestId = response.httpResponse.headers['x-amz-request-id'];
4431 }
4432 if (response.httpResponse.headers['x-amz-id-2']) {
4433 monitoringEvent.XAmzId2 = response.httpResponse.headers['x-amz-id-2'];
4434 }
4435 return monitoringEvent;
4436 },
4437
4438 /**
4439 * Add metrics of failed request.
4440 * @api private
4441 */
4442 attemptFailEvent: function attemptFailEvent(request) {
4443 var monitoringEvent = this.apiAttemptEvent(request);
4444 var response = request.response;
4445 var error = response.error;
4446 if (response.httpResponse.statusCode > 299 ) {
4447 if (error.code) monitoringEvent.AwsException = error.code;
4448 if (error.message) monitoringEvent.AwsExceptionMessage = error.message;
4449 } else {
4450 if (error.code || error.name) monitoringEvent.SdkException = error.code || error.name;
4451 if (error.message) monitoringEvent.SdkExceptionMessage = error.message;
4452 }
4453 return monitoringEvent;
4454 },
4455
4456 /**
4457 * Attach listeners to request object to fetch metrics of each request
4458 * and emit data object through \'ApiCall\' and \'ApiCallAttempt\' events.
4459 * @api private
4460 */
4461 attachMonitoringEmitter: function attachMonitoringEmitter(request) {
4462 var attemptTimestamp; //timestamp marking the beginning of a request attempt
4463 var attemptStartRealTime; //Start time of request attempt. Used to calculating attemptLatency
4464 var attemptLatency; //latency from request sent out to http response reaching SDK
4465 var callStartRealTime; //Start time of API call. Used to calculating API call latency
4466 var attemptCount = 0; //request.retryCount is not reliable here
4467 var region; //region cache region for each attempt since it can be updated in plase (e.g. s3)
4468 var callTimestamp; //timestamp when the request is created
4469 var self = this;
4470 var addToHead = true;
4471
4472 request.on('validate', function () {
4473 callStartRealTime = AWS.util.realClock.now();
4474 callTimestamp = Date.now();
4475 }, addToHead);
4476 request.on('sign', function () {
4477 attemptStartRealTime = AWS.util.realClock.now();
4478 attemptTimestamp = Date.now();
4479 region = request.httpRequest.region;
4480 attemptCount++;
4481 }, addToHead);
4482 request.on('validateResponse', function() {
4483 attemptLatency = Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4484 });
4485 request.addNamedListener('API_CALL_ATTEMPT', 'success', function API_CALL_ATTEMPT() {
4486 var apiAttemptEvent = self.apiAttemptEvent(request);
4487 apiAttemptEvent.Timestamp = attemptTimestamp;
4488 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4489 apiAttemptEvent.Region = region;
4490 self.emit('apiCallAttempt', [apiAttemptEvent]);
4491 });
4492 request.addNamedListener('API_CALL_ATTEMPT_RETRY', 'retry', function API_CALL_ATTEMPT_RETRY() {
4493 var apiAttemptEvent = self.attemptFailEvent(request);
4494 apiAttemptEvent.Timestamp = attemptTimestamp;
4495 //attemptLatency may not be available if fail before response
4496 attemptLatency = attemptLatency ||
4497 Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4498 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4499 apiAttemptEvent.Region = region;
4500 self.emit('apiCallAttempt', [apiAttemptEvent]);
4501 });
4502 request.addNamedListener('API_CALL', 'complete', function API_CALL() {
4503 var apiCallEvent = self.apiCallEvent(request);
4504 apiCallEvent.AttemptCount = attemptCount;
4505 if (apiCallEvent.AttemptCount <= 0) return;
4506 apiCallEvent.Timestamp = callTimestamp;
4507 var latency = Math.round(AWS.util.realClock.now() - callStartRealTime);
4508 apiCallEvent.Latency = latency >= 0 ? latency : 0;
4509 var response = request.response;
4510 if (
4511 typeof response.retryCount === 'number' &&
4512 typeof response.maxRetries === 'number' &&
4513 (response.retryCount >= response.maxRetries)
4514 ) {
4515 apiCallEvent.MaxRetriesExceeded = 1;
4516 }
4517 self.emit('apiCall', [apiCallEvent]);
4518 });
4519 },
4520
4521 /**
4522 * Override this method to setup any custom request listeners for each
4523 * new request to the service.
4524 *
4525 * @method_abstract This is an abstract method.
4526 */
4527 setupRequestListeners: function setupRequestListeners(request) {
4528 },
4529
4530 /**
4531 * Gets the signer class for a given request
4532 * @api private
4533 */
4534 getSignerClass: function getSignerClass(request) {
4535 var version;
4536 // get operation authtype if present
4537 var operation = null;
4538 var authtype = '';
4539 if (request) {
4540 var operations = request.service.api.operations || {};
4541 operation = operations[request.operation] || null;
4542 authtype = operation ? operation.authtype : '';
4543 }
4544 if (this.config.signatureVersion) {
4545 version = this.config.signatureVersion;
4546 } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') {
4547 version = 'v4';
4548 } else {
4549 version = this.api.signatureVersion;
4550 }
4551 return AWS.Signers.RequestSigner.getVersion(version);
4552 },
4553
4554 /**
4555 * @api private
4556 */
4557 serviceInterface: function serviceInterface() {
4558 switch (this.api.protocol) {
4559 case 'ec2': return AWS.EventListeners.Query;
4560 case 'query': return AWS.EventListeners.Query;
4561 case 'json': return AWS.EventListeners.Json;
4562 case 'rest-json': return AWS.EventListeners.RestJson;
4563 case 'rest-xml': return AWS.EventListeners.RestXml;
4564 }
4565 if (this.api.protocol) {
4566 throw new Error('Invalid service `protocol\' ' +
4567 this.api.protocol + ' in API config');
4568 }
4569 },
4570
4571 /**
4572 * @api private
4573 */
4574 successfulResponse: function successfulResponse(resp) {
4575 return resp.httpResponse.statusCode < 300;
4576 },
4577
4578 /**
4579 * How many times a failed request should be retried before giving up.
4580 * the defaultRetryCount can be overriden by service classes.
4581 *
4582 * @api private
4583 */
4584 numRetries: function numRetries() {
4585 if (this.config.maxRetries !== undefined) {
4586 return this.config.maxRetries;
4587 } else {
4588 return this.defaultRetryCount;
4589 }
4590 },
4591
4592 /**
4593 * @api private
4594 */
4595 retryDelays: function retryDelays(retryCount) {
4596 return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions);
4597 },
4598
4599 /**
4600 * @api private
4601 */
4602 retryableError: function retryableError(error) {
4603 if (this.timeoutError(error)) return true;
4604 if (this.networkingError(error)) return true;
4605 if (this.expiredCredentialsError(error)) return true;
4606 if (this.throttledError(error)) return true;
4607 if (error.statusCode >= 500) return true;
4608 return false;
4609 },
4610
4611 /**
4612 * @api private
4613 */
4614 networkingError: function networkingError(error) {
4615 return error.code === 'NetworkingError';
4616 },
4617
4618 /**
4619 * @api private
4620 */
4621 timeoutError: function timeoutError(error) {
4622 return error.code === 'TimeoutError';
4623 },
4624
4625 /**
4626 * @api private
4627 */
4628 expiredCredentialsError: function expiredCredentialsError(error) {
4629 // TODO : this only handles *one* of the expired credential codes
4630 return (error.code === 'ExpiredTokenException');
4631 },
4632
4633 /**
4634 * @api private
4635 */
4636 clockSkewError: function clockSkewError(error) {
4637 switch (error.code) {
4638 case 'RequestTimeTooSkewed':
4639 case 'RequestExpired':
4640 case 'InvalidSignatureException':
4641 case 'SignatureDoesNotMatch':
4642 case 'AuthFailure':
4643 case 'RequestInTheFuture':
4644 return true;
4645 default: return false;
4646 }
4647 },
4648
4649 /**
4650 * @api private
4651 */
4652 getSkewCorrectedDate: function getSkewCorrectedDate() {
4653 return new Date(Date.now() + this.config.systemClockOffset);
4654 },
4655
4656 /**
4657 * @api private
4658 */
4659 applyClockOffset: function applyClockOffset(newServerTime) {
4660 if (newServerTime) {
4661 this.config.systemClockOffset = newServerTime - Date.now();
4662 }
4663 },
4664
4665 /**
4666 * @api private
4667 */
4668 isClockSkewed: function isClockSkewed(newServerTime) {
4669 if (newServerTime) {
4670 return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 30000;
4671 }
4672 },
4673
4674 /**
4675 * @api private
4676 */
4677 throttledError: function throttledError(error) {
4678 // this logic varies between services
4679 switch (error.code) {
4680 case 'ProvisionedThroughputExceededException':
4681 case 'Throttling':
4682 case 'ThrottlingException':
4683 case 'RequestLimitExceeded':
4684 case 'RequestThrottled':
4685 case 'TooManyRequestsException':
4686 case 'TransactionInProgressException': //dynamodb
4687 return true;
4688 default:
4689 return false;
4690 }
4691 },
4692
4693 /**
4694 * @api private
4695 */
4696 endpointFromTemplate: function endpointFromTemplate(endpoint) {
4697 if (typeof endpoint !== 'string') return endpoint;
4698
4699 var e = endpoint;
4700 e = e.replace(/\{service\}/g, this.api.endpointPrefix);
4701 e = e.replace(/\{region\}/g, this.config.region);
4702 e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http');
4703 return e;
4704 },
4705
4706 /**
4707 * @api private
4708 */
4709 setEndpoint: function setEndpoint(endpoint) {
4710 this.endpoint = new AWS.Endpoint(endpoint, this.config);
4711 },
4712
4713 /**
4714 * @api private
4715 */
4716 paginationConfig: function paginationConfig(operation, throwException) {
4717 var paginator = this.api.operations[operation].paginator;
4718 if (!paginator) {
4719 if (throwException) {
4720 var e = new Error();
4721 throw AWS.util.error(e, 'No pagination configuration for ' + operation);
4722 }
4723 return null;
4724 }
4725
4726 return paginator;
4727 }
4728 });
4729
4730 AWS.util.update(AWS.Service, {
4731
4732 /**
4733 * Adds one method for each operation described in the api configuration
4734 *
4735 * @api private
4736 */
4737 defineMethods: function defineMethods(svc) {
4738 AWS.util.each(svc.prototype.api.operations, function iterator(method) {
4739 if (svc.prototype[method]) return;
4740 var operation = svc.prototype.api.operations[method];
4741 if (operation.authtype === 'none') {
4742 svc.prototype[method] = function (params, callback) {
4743 return this.makeUnauthenticatedRequest(method, params, callback);
4744 };
4745 } else {
4746 svc.prototype[method] = function (params, callback) {
4747 return this.makeRequest(method, params, callback);
4748 };
4749 }
4750 });
4751 },
4752
4753 /**
4754 * Defines a new Service class using a service identifier and list of versions
4755 * including an optional set of features (functions) to apply to the class
4756 * prototype.
4757 *
4758 * @param serviceIdentifier [String] the identifier for the service
4759 * @param versions [Array<String>] a list of versions that work with this
4760 * service
4761 * @param features [Object] an object to attach to the prototype
4762 * @return [Class<Service>] the service class defined by this function.
4763 */
4764 defineService: function defineService(serviceIdentifier, versions, features) {
4765 AWS.Service._serviceMap[serviceIdentifier] = true;
4766 if (!Array.isArray(versions)) {
4767 features = versions;
4768 versions = [];
4769 }
4770
4771 var svc = inherit(AWS.Service, features || {});
4772
4773 if (typeof serviceIdentifier === 'string') {
4774 AWS.Service.addVersions(svc, versions);
4775
4776 var identifier = svc.serviceIdentifier || serviceIdentifier;
4777 svc.serviceIdentifier = identifier;
4778 } else { // defineService called with an API
4779 svc.prototype.api = serviceIdentifier;
4780 AWS.Service.defineMethods(svc);
4781 }
4782 AWS.SequentialExecutor.call(this.prototype);
4783 //util.clientSideMonitoring is only available in node
4784 if (!this.prototype.publisher && AWS.util.clientSideMonitoring) {
4785 var Publisher = AWS.util.clientSideMonitoring.Publisher;
4786 var configProvider = AWS.util.clientSideMonitoring.configProvider;
4787 var publisherConfig = configProvider();
4788 this.prototype.publisher = new Publisher(publisherConfig);
4789 if (publisherConfig.enabled) {
4790 //if csm is enabled in environment, SDK should send all metrics
4791 AWS.Service._clientSideMonitoring = true;
4792 }
4793 }
4794 AWS.SequentialExecutor.call(svc.prototype);
4795 AWS.Service.addDefaultMonitoringListeners(svc.prototype);
4796 return svc;
4797 },
4798
4799 /**
4800 * @api private
4801 */
4802 addVersions: function addVersions(svc, versions) {
4803 if (!Array.isArray(versions)) versions = [versions];
4804
4805 svc.services = svc.services || {};
4806 for (var i = 0; i < versions.length; i++) {
4807 if (svc.services[versions[i]] === undefined) {
4808 svc.services[versions[i]] = null;
4809 }
4810 }
4811
4812 svc.apiVersions = Object.keys(svc.services).sort();
4813 },
4814
4815 /**
4816 * @api private
4817 */
4818 defineServiceApi: function defineServiceApi(superclass, version, apiConfig) {
4819 var svc = inherit(superclass, {
4820 serviceIdentifier: superclass.serviceIdentifier
4821 });
4822
4823 function setApi(api) {
4824 if (api.isApi) {
4825 svc.prototype.api = api;
4826 } else {
4827 svc.prototype.api = new Api(api);
4828 }
4829 }
4830
4831 if (typeof version === 'string') {
4832 if (apiConfig) {
4833 setApi(apiConfig);
4834 } else {
4835 try {
4836 setApi(AWS.apiLoader(superclass.serviceIdentifier, version));
4837 } catch (err) {
4838 throw AWS.util.error(err, {
4839 message: 'Could not find API configuration ' +
4840 superclass.serviceIdentifier + '-' + version
4841 });
4842 }
4843 }
4844 if (!Object.prototype.hasOwnProperty.call(superclass.services, version)) {
4845 superclass.apiVersions = superclass.apiVersions.concat(version).sort();
4846 }
4847 superclass.services[version] = svc;
4848 } else {
4849 setApi(version);
4850 }
4851
4852 AWS.Service.defineMethods(svc);
4853 return svc;
4854 },
4855
4856 /**
4857 * @api private
4858 */
4859 hasService: function(identifier) {
4860 return Object.prototype.hasOwnProperty.call(AWS.Service._serviceMap, identifier);
4861 },
4862
4863 /**
4864 * @param attachOn attach default monitoring listeners to object
4865 *
4866 * Each monitoring event should be emitted from service client to service constructor prototype and then
4867 * to global service prototype like bubbling up. These default monitoring events listener will transfer
4868 * the monitoring events to the upper layer.
4869 * @api private
4870 */
4871 addDefaultMonitoringListeners: function addDefaultMonitoringListeners(attachOn) {
4872 attachOn.addNamedListener('MONITOR_EVENTS_BUBBLE', 'apiCallAttempt', function EVENTS_BUBBLE(event) {
4873 var baseClass = Object.getPrototypeOf(attachOn);
4874 if (baseClass._events) baseClass.emit('apiCallAttempt', [event]);
4875 });
4876 attachOn.addNamedListener('CALL_EVENTS_BUBBLE', 'apiCall', function CALL_EVENTS_BUBBLE(event) {
4877 var baseClass = Object.getPrototypeOf(attachOn);
4878 if (baseClass._events) baseClass.emit('apiCall', [event]);
4879 });
4880 },
4881
4882 /**
4883 * @api private
4884 */
4885 _serviceMap: {}
4886 });
4887
4888 AWS.util.mixin(AWS.Service, AWS.SequentialExecutor);
4889
4890 /**
4891 * @api private
4892 */
4893 module.exports = AWS.Service;
4894
4895 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
4896
4897/***/ }),
4898/* 38 */
4899/***/ (function(module, exports, __webpack_require__) {
4900
4901 var util = __webpack_require__(2);
4902 var regionConfig = __webpack_require__(39);
4903
4904 function generateRegionPrefix(region) {
4905 if (!region) return null;
4906
4907 var parts = region.split('-');
4908 if (parts.length < 3) return null;
4909 return parts.slice(0, parts.length - 2).join('-') + '-*';
4910 }
4911
4912 function derivedKeys(service) {
4913 var region = service.config.region;
4914 var regionPrefix = generateRegionPrefix(region);
4915 var endpointPrefix = service.api.endpointPrefix;
4916
4917 return [
4918 [region, endpointPrefix],
4919 [regionPrefix, endpointPrefix],
4920 [region, '*'],
4921 [regionPrefix, '*'],
4922 ['*', endpointPrefix],
4923 ['*', '*']
4924 ].map(function(item) {
4925 return item[0] && item[1] ? item.join('/') : null;
4926 });
4927 }
4928
4929 function applyConfig(service, config) {
4930 util.each(config, function(key, value) {
4931 if (key === 'globalEndpoint') return;
4932 if (service.config[key] === undefined || service.config[key] === null) {
4933 service.config[key] = value;
4934 }
4935 });
4936 }
4937
4938 function configureEndpoint(service) {
4939 var keys = derivedKeys(service);
4940 for (var i = 0; i < keys.length; i++) {
4941 var key = keys[i];
4942 if (!key) continue;
4943
4944 if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) {
4945 var config = regionConfig.rules[key];
4946 if (typeof config === 'string') {
4947 config = regionConfig.patterns[config];
4948 }
4949
4950 // set dualstack endpoint
4951 if (service.config.useDualstack && util.isDualstackAvailable(service)) {
4952 config = util.copy(config);
4953 config.endpoint = '{service}.dualstack.{region}.amazonaws.com';
4954 }
4955
4956 // set global endpoint
4957 service.isGlobalEndpoint = !!config.globalEndpoint;
4958
4959 // signature version
4960 if (!config.signatureVersion) config.signatureVersion = 'v4';
4961
4962 // merge config
4963 applyConfig(service, config);
4964 return;
4965 }
4966 }
4967 }
4968
4969 /**
4970 * @api private
4971 */
4972 module.exports = configureEndpoint;
4973
4974
4975/***/ }),
4976/* 39 */
4977/***/ (function(module, exports) {
4978
4979 module.exports = {"rules":{"*/*":{"endpoint":"{service}.{region}.amazonaws.com"},"cn-*/*":{"endpoint":"{service}.{region}.amazonaws.com.cn"},"*/budgets":"globalSSL","*/cloudfront":"globalSSL","*/iam":"globalSSL","*/sts":"globalSSL","*/importexport":{"endpoint":"{service}.amazonaws.com","signatureVersion":"v2","globalEndpoint":true},"*/route53":{"endpoint":"https://{service}.amazonaws.com","signatureVersion":"v3https","globalEndpoint":true},"*/waf":"globalSSL","us-gov-*/iam":"globalGovCloud","us-gov-*/sts":{"endpoint":"{service}.{region}.amazonaws.com"},"us-gov-west-1/s3":"s3signature","us-west-1/s3":"s3signature","us-west-2/s3":"s3signature","eu-west-1/s3":"s3signature","ap-southeast-1/s3":"s3signature","ap-southeast-2/s3":"s3signature","ap-northeast-1/s3":"s3signature","sa-east-1/s3":"s3signature","us-east-1/s3":{"endpoint":"{service}.amazonaws.com","signatureVersion":"s3"},"us-east-1/sdb":{"endpoint":"{service}.amazonaws.com","signatureVersion":"v2"},"*/sdb":{"endpoint":"{service}.{region}.amazonaws.com","signatureVersion":"v2"}},"patterns":{"globalSSL":{"endpoint":"https://{service}.amazonaws.com","globalEndpoint":true},"globalGovCloud":{"endpoint":"{service}.us-gov.amazonaws.com"},"s3signature":{"endpoint":"{service}.{region}.amazonaws.com","signatureVersion":"s3"}}}
4980
4981/***/ }),
4982/* 40 */
4983/***/ (function(module, exports, __webpack_require__) {
4984
4985 var AWS = __webpack_require__(1);
4986 __webpack_require__(41);
4987 __webpack_require__(42);
4988 var PromisesDependency;
4989
4990 /**
4991 * The main configuration class used by all service objects to set
4992 * the region, credentials, and other options for requests.
4993 *
4994 * By default, credentials and region settings are left unconfigured.
4995 * This should be configured by the application before using any
4996 * AWS service APIs.
4997 *
4998 * In order to set global configuration options, properties should
4999 * be assigned to the global {AWS.config} object.
5000 *
5001 * @see AWS.config
5002 *
5003 * @!group General Configuration Options
5004 *
5005 * @!attribute credentials
5006 * @return [AWS.Credentials] the AWS credentials to sign requests with.
5007 *
5008 * @!attribute region
5009 * @example Set the global region setting to us-west-2
5010 * AWS.config.update({region: 'us-west-2'});
5011 * @return [AWS.Credentials] The region to send service requests to.
5012 * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
5013 * A list of available endpoints for each AWS service
5014 *
5015 * @!attribute maxRetries
5016 * @return [Integer] the maximum amount of retries to perform for a
5017 * service request. By default this value is calculated by the specific
5018 * service object that the request is being made to.
5019 *
5020 * @!attribute maxRedirects
5021 * @return [Integer] the maximum amount of redirects to follow for a
5022 * service request. Defaults to 10.
5023 *
5024 * @!attribute paramValidation
5025 * @return [Boolean|map] whether input parameters should be validated against
5026 * the operation description before sending the request. Defaults to true.
5027 * Pass a map to enable any of the following specific validation features:
5028 *
5029 * * **min** [Boolean] &mdash; Validates that a value meets the min
5030 * constraint. This is enabled by default when paramValidation is set
5031 * to `true`.
5032 * * **max** [Boolean] &mdash; Validates that a value meets the max
5033 * constraint.
5034 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5035 * regular expression.
5036 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5037 * of the allowable enum values.
5038 *
5039 * @!attribute computeChecksums
5040 * @return [Boolean] whether to compute checksums for payload bodies when
5041 * the service accepts it (currently supported in S3 only).
5042 *
5043 * @!attribute convertResponseTypes
5044 * @return [Boolean] whether types are converted when parsing response data.
5045 * Currently only supported for JSON based services. Turning this off may
5046 * improve performance on large response payloads. Defaults to `true`.
5047 *
5048 * @!attribute correctClockSkew
5049 * @return [Boolean] whether to apply a clock skew correction and retry
5050 * requests that fail because of an skewed client clock. Defaults to
5051 * `false`.
5052 *
5053 * @!attribute sslEnabled
5054 * @return [Boolean] whether SSL is enabled for requests
5055 *
5056 * @!attribute s3ForcePathStyle
5057 * @return [Boolean] whether to force path style URLs for S3 objects
5058 *
5059 * @!attribute s3BucketEndpoint
5060 * @note Setting this configuration option requires an `endpoint` to be
5061 * provided explicitly to the service constructor.
5062 * @return [Boolean] whether the provided endpoint addresses an individual
5063 * bucket (false if it addresses the root API endpoint).
5064 *
5065 * @!attribute s3DisableBodySigning
5066 * @return [Boolean] whether to disable S3 body signing when using signature version `v4`.
5067 * Body signing can only be disabled when using https. Defaults to `true`.
5068 *
5069 * @!attribute useAccelerateEndpoint
5070 * @note This configuration option is only compatible with S3 while accessing
5071 * dns-compatible buckets.
5072 * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service.
5073 * Defaults to `false`.
5074 *
5075 * @!attribute retryDelayOptions
5076 * @example Set the base retry delay for all services to 300 ms
5077 * AWS.config.update({retryDelayOptions: {base: 300}});
5078 * // Delays with maxRetries = 3: 300, 600, 1200
5079 * @example Set a custom backoff function to provide delay values on retries
5080 * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) {
5081 * // returns delay in ms
5082 * }}});
5083 * @return [map] A set of options to configure the retry delay on retryable errors.
5084 * Currently supported options are:
5085 *
5086 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5087 * exponential backoff for operation retries. Defaults to 100 ms for all services except
5088 * DynamoDB, where it defaults to 50ms.
5089 * * **customBackoff ** [function] &mdash; A custom function that accepts a retry count
5090 * and returns the amount of time to delay in milliseconds. The `base` option will be
5091 * ignored if this option is supplied.
5092 *
5093 * @!attribute httpOptions
5094 * @return [map] A set of options to pass to the low-level HTTP request.
5095 * Currently supported options are:
5096 *
5097 * * **proxy** [String] &mdash; the URL to proxy requests through
5098 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5099 * HTTP requests with. Used for connection pooling. Defaults to the global
5100 * agent (`http.globalAgent`) for non-SSL connections. Note that for
5101 * SSL connections, a special Agent object is used in order to enable
5102 * peer certificate verification. This feature is only supported in the
5103 * Node.js environment.
5104 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5105 * failing to establish a connection with the server after
5106 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5107 * connection has been established.
5108 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5109 * milliseconds of inactivity on the socket. Defaults to two minutes
5110 * (120000)
5111 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5112 * HTTP requests. Used in the browser environment only. Set to false to
5113 * send requests synchronously. Defaults to true (async on).
5114 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5115 * property of an XMLHttpRequest object. Used in the browser environment
5116 * only. Defaults to false.
5117 * @!attribute logger
5118 * @return [#write,#log] an object that responds to .write() (like a stream)
5119 * or .log() (like the console object) in order to log information about
5120 * requests
5121 *
5122 * @!attribute systemClockOffset
5123 * @return [Number] an offset value in milliseconds to apply to all signing
5124 * times. Use this to compensate for clock skew when your system may be
5125 * out of sync with the service time. Note that this configuration option
5126 * can only be applied to the global `AWS.config` object and cannot be
5127 * overridden in service-specific configuration. Defaults to 0 milliseconds.
5128 *
5129 * @!attribute signatureVersion
5130 * @return [String] the signature version to sign requests with (overriding
5131 * the API configuration). Possible values are: 'v2', 'v3', 'v4'.
5132 *
5133 * @!attribute signatureCache
5134 * @return [Boolean] whether the signature to sign requests with (overriding
5135 * the API configuration) is cached. Only applies to the signature version 'v4'.
5136 * Defaults to `true`.
5137 *
5138 * @!attribute endpointDiscoveryEnabled
5139 * @return [Boolean] whether to enable endpoint discovery for operations that
5140 * allow optionally using an endpoint returned by the service.
5141 * Defaults to 'false'
5142 *
5143 * @!attribute endpointCacheSize
5144 * @return [Number] the size of the global cache storing endpoints from endpoint
5145 * discovery operations. Once endpoint cache is created, updating this setting
5146 * cannot change existing cache size.
5147 * Defaults to 1000
5148 *
5149 * @!attribute hostPrefixEnabled
5150 * @return [Boolean] whether to marshal request parameters to the prefix of
5151 * hostname. Defaults to `true`.
5152 */
5153 AWS.Config = AWS.util.inherit({
5154 /**
5155 * @!endgroup
5156 */
5157
5158 /**
5159 * Creates a new configuration object. This is the object that passes
5160 * option data along to service requests, including credentials, security,
5161 * region information, and some service specific settings.
5162 *
5163 * @example Creating a new configuration object with credentials and region
5164 * var config = new AWS.Config({
5165 * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
5166 * });
5167 * @option options accessKeyId [String] your AWS access key ID.
5168 * @option options secretAccessKey [String] your AWS secret access key.
5169 * @option options sessionToken [AWS.Credentials] the optional AWS
5170 * session token to sign requests with.
5171 * @option options credentials [AWS.Credentials] the AWS credentials
5172 * to sign requests with. You can either specify this object, or
5173 * specify the accessKeyId and secretAccessKey options directly.
5174 * @option options credentialProvider [AWS.CredentialProviderChain] the
5175 * provider chain used to resolve credentials if no static `credentials`
5176 * property is set.
5177 * @option options region [String] the region to send service requests to.
5178 * See {region} for more information.
5179 * @option options maxRetries [Integer] the maximum amount of retries to
5180 * attempt with a request. See {maxRetries} for more information.
5181 * @option options maxRedirects [Integer] the maximum amount of redirects to
5182 * follow with a request. See {maxRedirects} for more information.
5183 * @option options sslEnabled [Boolean] whether to enable SSL for
5184 * requests.
5185 * @option options paramValidation [Boolean|map] whether input parameters
5186 * should be validated against the operation description before sending
5187 * the request. Defaults to true. Pass a map to enable any of the
5188 * following specific validation features:
5189 *
5190 * * **min** [Boolean] &mdash; Validates that a value meets the min
5191 * constraint. This is enabled by default when paramValidation is set
5192 * to `true`.
5193 * * **max** [Boolean] &mdash; Validates that a value meets the max
5194 * constraint.
5195 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5196 * regular expression.
5197 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5198 * of the allowable enum values.
5199 * @option options computeChecksums [Boolean] whether to compute checksums
5200 * for payload bodies when the service accepts it (currently supported
5201 * in S3 only)
5202 * @option options convertResponseTypes [Boolean] whether types are converted
5203 * when parsing response data. Currently only supported for JSON based
5204 * services. Turning this off may improve performance on large response
5205 * payloads. Defaults to `true`.
5206 * @option options correctClockSkew [Boolean] whether to apply a clock skew
5207 * correction and retry requests that fail because of an skewed client
5208 * clock. Defaults to `false`.
5209 * @option options s3ForcePathStyle [Boolean] whether to force path
5210 * style URLs for S3 objects.
5211 * @option options s3BucketEndpoint [Boolean] whether the provided endpoint
5212 * addresses an individual bucket (false if it addresses the root API
5213 * endpoint). Note that setting this configuration option requires an
5214 * `endpoint` to be provided explicitly to the service constructor.
5215 * @option options s3DisableBodySigning [Boolean] whether S3 body signing
5216 * should be disabled when using signature version `v4`. Body signing
5217 * can only be disabled when using https. Defaults to `true`.
5218 *
5219 * @option options retryDelayOptions [map] A set of options to configure
5220 * the retry delay on retryable errors. Currently supported options are:
5221 *
5222 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5223 * exponential backoff for operation retries. Defaults to 100 ms for all
5224 * services except DynamoDB, where it defaults to 50ms.
5225 * * **customBackoff ** [function] &mdash; A custom function that accepts a retry count
5226 * and returns the amount of time to delay in milliseconds. The `base` option will be
5227 * ignored if this option is supplied.
5228 * @option options httpOptions [map] A set of options to pass to the low-level
5229 * HTTP request. Currently supported options are:
5230 *
5231 * * **proxy** [String] &mdash; the URL to proxy requests through
5232 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5233 * HTTP requests with. Used for connection pooling. Defaults to the global
5234 * agent (`http.globalAgent`) for non-SSL connections. Note that for
5235 * SSL connections, a special Agent object is used in order to enable
5236 * peer certificate verification. This feature is only available in the
5237 * Node.js environment.
5238 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5239 * failing to establish a connection with the server after
5240 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5241 * connection has been established.
5242 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5243 * milliseconds of inactivity on the socket. Defaults to two minutes
5244 * (120000).
5245 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5246 * HTTP requests. Used in the browser environment only. Set to false to
5247 * send requests synchronously. Defaults to true (async on).
5248 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5249 * property of an XMLHttpRequest object. Used in the browser environment
5250 * only. Defaults to false.
5251 * @option options apiVersion [String, Date] a String in YYYY-MM-DD format
5252 * (or a date) that represents the latest possible API version that can be
5253 * used in all services (unless overridden by `apiVersions`). Specify
5254 * 'latest' to use the latest possible version.
5255 * @option options apiVersions [map<String, String|Date>] a map of service
5256 * identifiers (the lowercase service class name) with the API version to
5257 * use when instantiating a service. Specify 'latest' for each individual
5258 * that can use the latest available version.
5259 * @option options logger [#write,#log] an object that responds to .write()
5260 * (like a stream) or .log() (like the console object) in order to log
5261 * information about requests
5262 * @option options systemClockOffset [Number] an offset value in milliseconds
5263 * to apply to all signing times. Use this to compensate for clock skew
5264 * when your system may be out of sync with the service time. Note that
5265 * this configuration option can only be applied to the global `AWS.config`
5266 * object and cannot be overridden in service-specific configuration.
5267 * Defaults to 0 milliseconds.
5268 * @option options signatureVersion [String] the signature version to sign
5269 * requests with (overriding the API configuration). Possible values are:
5270 * 'v2', 'v3', 'v4'.
5271 * @option options signatureCache [Boolean] whether the signature to sign
5272 * requests with (overriding the API configuration) is cached. Only applies
5273 * to the signature version 'v4'. Defaults to `true`.
5274 * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32
5275 * checksum of HTTP response bodies returned by DynamoDB. Default: `true`.
5276 * @option options useAccelerateEndpoint [Boolean] Whether to use the
5277 * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`.
5278 * @option options clientSideMonitoring [Boolean] whether to collect and
5279 * publish this client's performance metrics of all its API requests.
5280 * @option options endpointDiscoveryEnabled [Boolean] whether to enable endpoint
5281 * discovery for operations that allow optionally using an endpoint returned by
5282 * the service.
5283 * Defaults to 'false'
5284 * @option options endpointCacheSize [Number] the size of the global cache storing
5285 * endpoints from endpoint discovery operations. Once endpoint cache is created,
5286 * updating this setting cannot change existing cache size.
5287 * Defaults to 1000
5288 * @option options hostPrefixEnabled [Boolean] whether to marshal request
5289 * parameters to the prefix of hostname.
5290 * Defaults to `true`.
5291 */
5292 constructor: function Config(options) {
5293 if (options === undefined) options = {};
5294 options = this.extractCredentials(options);
5295
5296 AWS.util.each.call(this, this.keys, function (key, value) {
5297 this.set(key, options[key], value);
5298 });
5299 },
5300
5301 /**
5302 * @!group Managing Credentials
5303 */
5304
5305 /**
5306 * Loads credentials from the configuration object. This is used internally
5307 * by the SDK to ensure that refreshable {Credentials} objects are properly
5308 * refreshed and loaded when sending a request. If you want to ensure that
5309 * your credentials are loaded prior to a request, you can use this method
5310 * directly to provide accurate credential data stored in the object.
5311 *
5312 * @note If you configure the SDK with static or environment credentials,
5313 * the credential data should already be present in {credentials} attribute.
5314 * This method is primarily necessary to load credentials from asynchronous
5315 * sources, or sources that can refresh credentials periodically.
5316 * @example Getting your access key
5317 * AWS.config.getCredentials(function(err) {
5318 * if (err) console.log(err.stack); // credentials not loaded
5319 * else console.log("Access Key:", AWS.config.credentials.accessKeyId);
5320 * })
5321 * @callback callback function(err)
5322 * Called when the {credentials} have been properly set on the configuration
5323 * object.
5324 *
5325 * @param err [Error] if this is set, credentials were not successfully
5326 * loaded and this error provides information why.
5327 * @see credentials
5328 * @see Credentials
5329 */
5330 getCredentials: function getCredentials(callback) {
5331 var self = this;
5332
5333 function finish(err) {
5334 callback(err, err ? null : self.credentials);
5335 }
5336
5337 function credError(msg, err) {
5338 return new AWS.util.error(err || new Error(), {
5339 code: 'CredentialsError',
5340 message: msg,
5341 name: 'CredentialsError'
5342 });
5343 }
5344
5345 function getAsyncCredentials() {
5346 self.credentials.get(function(err) {
5347 if (err) {
5348 var msg = 'Could not load credentials from ' +
5349 self.credentials.constructor.name;
5350 err = credError(msg, err);
5351 }
5352 finish(err);
5353 });
5354 }
5355
5356 function getStaticCredentials() {
5357 var err = null;
5358 if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
5359 err = credError('Missing credentials');
5360 }
5361 finish(err);
5362 }
5363
5364 if (self.credentials) {
5365 if (typeof self.credentials.get === 'function') {
5366 getAsyncCredentials();
5367 } else { // static credentials
5368 getStaticCredentials();
5369 }
5370 } else if (self.credentialProvider) {
5371 self.credentialProvider.resolve(function(err, creds) {
5372 if (err) {
5373 err = credError('Could not load credentials from any providers', err);
5374 }
5375 self.credentials = creds;
5376 finish(err);
5377 });
5378 } else {
5379 finish(credError('No credentials to load'));
5380 }
5381 },
5382
5383 /**
5384 * @!group Loading and Setting Configuration Options
5385 */
5386
5387 /**
5388 * @overload update(options, allowUnknownKeys = false)
5389 * Updates the current configuration object with new options.
5390 *
5391 * @example Update maxRetries property of a configuration object
5392 * config.update({maxRetries: 10});
5393 * @param [Object] options a map of option keys and values.
5394 * @param [Boolean] allowUnknownKeys whether unknown keys can be set on
5395 * the configuration object. Defaults to `false`.
5396 * @see constructor
5397 */
5398 update: function update(options, allowUnknownKeys) {
5399 allowUnknownKeys = allowUnknownKeys || false;
5400 options = this.extractCredentials(options);
5401 AWS.util.each.call(this, options, function (key, value) {
5402 if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) ||
5403 AWS.Service.hasService(key)) {
5404 this.set(key, value);
5405 }
5406 });
5407 },
5408
5409 /**
5410 * Loads configuration data from a JSON file into this config object.
5411 * @note Loading configuration will reset all existing configuration
5412 * on the object.
5413 * @!macro nobrowser
5414 * @param path [String] the path relative to your process's current
5415 * working directory to load configuration from.
5416 * @return [AWS.Config] the same configuration object
5417 */
5418 loadFromPath: function loadFromPath(path) {
5419 this.clear();
5420
5421 var options = JSON.parse(AWS.util.readFileSync(path));
5422 var fileSystemCreds = new AWS.FileSystemCredentials(path);
5423 var chain = new AWS.CredentialProviderChain();
5424 chain.providers.unshift(fileSystemCreds);
5425 chain.resolve(function (err, creds) {
5426 if (err) throw err;
5427 else options.credentials = creds;
5428 });
5429
5430 this.constructor(options);
5431
5432 return this;
5433 },
5434
5435 /**
5436 * Clears configuration data on this object
5437 *
5438 * @api private
5439 */
5440 clear: function clear() {
5441 /*jshint forin:false */
5442 AWS.util.each.call(this, this.keys, function (key) {
5443 delete this[key];
5444 });
5445
5446 // reset credential provider
5447 this.set('credentials', undefined);
5448 this.set('credentialProvider', undefined);
5449 },
5450
5451 /**
5452 * Sets a property on the configuration object, allowing for a
5453 * default value
5454 * @api private
5455 */
5456 set: function set(property, value, defaultValue) {
5457 if (value === undefined) {
5458 if (defaultValue === undefined) {
5459 defaultValue = this.keys[property];
5460 }
5461 if (typeof defaultValue === 'function') {
5462 this[property] = defaultValue.call(this);
5463 } else {
5464 this[property] = defaultValue;
5465 }
5466 } else if (property === 'httpOptions' && this[property]) {
5467 // deep merge httpOptions
5468 this[property] = AWS.util.merge(this[property], value);
5469 } else {
5470 this[property] = value;
5471 }
5472 },
5473
5474 /**
5475 * All of the keys with their default values.
5476 *
5477 * @constant
5478 * @api private
5479 */
5480 keys: {
5481 credentials: null,
5482 credentialProvider: null,
5483 region: null,
5484 logger: null,
5485 apiVersions: {},
5486 apiVersion: null,
5487 endpoint: undefined,
5488 httpOptions: {
5489 timeout: 120000
5490 },
5491 maxRetries: undefined,
5492 maxRedirects: 10,
5493 paramValidation: true,
5494 sslEnabled: true,
5495 s3ForcePathStyle: false,
5496 s3BucketEndpoint: false,
5497 s3DisableBodySigning: true,
5498 computeChecksums: true,
5499 convertResponseTypes: true,
5500 correctClockSkew: false,
5501 customUserAgent: null,
5502 dynamoDbCrc32: true,
5503 systemClockOffset: 0,
5504 signatureVersion: null,
5505 signatureCache: true,
5506 retryDelayOptions: {},
5507 useAccelerateEndpoint: false,
5508 clientSideMonitoring: false,
5509 endpointDiscoveryEnabled: false,
5510 endpointCacheSize: 1000,
5511 hostPrefixEnabled: true
5512 },
5513
5514 /**
5515 * Extracts accessKeyId, secretAccessKey and sessionToken
5516 * from a configuration hash.
5517 *
5518 * @api private
5519 */
5520 extractCredentials: function extractCredentials(options) {
5521 if (options.accessKeyId && options.secretAccessKey) {
5522 options = AWS.util.copy(options);
5523 options.credentials = new AWS.Credentials(options);
5524 }
5525 return options;
5526 },
5527
5528 /**
5529 * Sets the promise dependency the SDK will use wherever Promises are returned.
5530 * Passing `null` will force the SDK to use native Promises if they are available.
5531 * If native Promises are not available, passing `null` will have no effect.
5532 * @param [Constructor] dep A reference to a Promise constructor
5533 */
5534 setPromisesDependency: function setPromisesDependency(dep) {
5535 PromisesDependency = dep;
5536 // if null was passed in, we should try to use native promises
5537 if (dep === null && typeof Promise === 'function') {
5538 PromisesDependency = Promise;
5539 }
5540 var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain];
5541 if (AWS.S3 && AWS.S3.ManagedUpload) constructors.push(AWS.S3.ManagedUpload);
5542 AWS.util.addPromises(constructors, PromisesDependency);
5543 },
5544
5545 /**
5546 * Gets the promise dependency set by `AWS.config.setPromisesDependency`.
5547 */
5548 getPromisesDependency: function getPromisesDependency() {
5549 return PromisesDependency;
5550 }
5551 });
5552
5553 /**
5554 * @return [AWS.Config] The global configuration object singleton instance
5555 * @readonly
5556 * @see AWS.Config
5557 */
5558 AWS.config = new AWS.Config();
5559
5560
5561/***/ }),
5562/* 41 */
5563/***/ (function(module, exports, __webpack_require__) {
5564
5565 var AWS = __webpack_require__(1);
5566
5567 /**
5568 * Represents your AWS security credentials, specifically the
5569 * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}.
5570 * Creating a `Credentials` object allows you to pass around your
5571 * security information to configuration and service objects.
5572 *
5573 * Note that this class typically does not need to be constructed manually,
5574 * as the {AWS.Config} and {AWS.Service} classes both accept simple
5575 * options hashes with the three keys. These structures will be converted
5576 * into Credentials objects automatically.
5577 *
5578 * ## Expiring and Refreshing Credentials
5579 *
5580 * Occasionally credentials can expire in the middle of a long-running
5581 * application. In this case, the SDK will automatically attempt to
5582 * refresh the credentials from the storage location if the Credentials
5583 * class implements the {refresh} method.
5584 *
5585 * If you are implementing a credential storage location, you
5586 * will want to create a subclass of the `Credentials` class and
5587 * override the {refresh} method. This method allows credentials to be
5588 * retrieved from the backing store, be it a file system, database, or
5589 * some network storage. The method should reset the credential attributes
5590 * on the object.
5591 *
5592 * @!attribute expired
5593 * @return [Boolean] whether the credentials have been expired and
5594 * require a refresh. Used in conjunction with {expireTime}.
5595 * @!attribute expireTime
5596 * @return [Date] a time when credentials should be considered expired. Used
5597 * in conjunction with {expired}.
5598 * @!attribute accessKeyId
5599 * @return [String] the AWS access key ID
5600 * @!attribute secretAccessKey
5601 * @return [String] the AWS secret access key
5602 * @!attribute sessionToken
5603 * @return [String] an optional AWS session token
5604 */
5605 AWS.Credentials = AWS.util.inherit({
5606 /**
5607 * A credentials object can be created using positional arguments or an options
5608 * hash.
5609 *
5610 * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
5611 * Creates a Credentials object with a given set of credential information
5612 * as positional arguments.
5613 * @param accessKeyId [String] the AWS access key ID
5614 * @param secretAccessKey [String] the AWS secret access key
5615 * @param sessionToken [String] the optional AWS session token
5616 * @example Create a credentials object with AWS credentials
5617 * var creds = new AWS.Credentials('akid', 'secret', 'session');
5618 * @overload AWS.Credentials(options)
5619 * Creates a Credentials object with a given set of credential information
5620 * as an options hash.
5621 * @option options accessKeyId [String] the AWS access key ID
5622 * @option options secretAccessKey [String] the AWS secret access key
5623 * @option options sessionToken [String] the optional AWS session token
5624 * @example Create a credentials object with AWS credentials
5625 * var creds = new AWS.Credentials({
5626 * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
5627 * });
5628 */
5629 constructor: function Credentials() {
5630 // hide secretAccessKey from being displayed with util.inspect
5631 AWS.util.hideProperties(this, ['secretAccessKey']);
5632
5633 this.expired = false;
5634 this.expireTime = null;
5635 this.refreshCallbacks = [];
5636 if (arguments.length === 1 && typeof arguments[0] === 'object') {
5637 var creds = arguments[0].credentials || arguments[0];
5638 this.accessKeyId = creds.accessKeyId;
5639 this.secretAccessKey = creds.secretAccessKey;
5640 this.sessionToken = creds.sessionToken;
5641 } else {
5642 this.accessKeyId = arguments[0];
5643 this.secretAccessKey = arguments[1];
5644 this.sessionToken = arguments[2];
5645 }
5646 },
5647
5648 /**
5649 * @return [Integer] the number of seconds before {expireTime} during which
5650 * the credentials will be considered expired.
5651 */
5652 expiryWindow: 15,
5653
5654 /**
5655 * @return [Boolean] whether the credentials object should call {refresh}
5656 * @note Subclasses should override this method to provide custom refresh
5657 * logic.
5658 */
5659 needsRefresh: function needsRefresh() {
5660 var currentTime = AWS.util.date.getDate().getTime();
5661 var adjustedTime = new Date(currentTime + this.expiryWindow * 1000);
5662
5663 if (this.expireTime && adjustedTime > this.expireTime) {
5664 return true;
5665 } else {
5666 return this.expired || !this.accessKeyId || !this.secretAccessKey;
5667 }
5668 },
5669
5670 /**
5671 * Gets the existing credentials, refreshing them if they are not yet loaded
5672 * or have expired. Users should call this method before using {refresh},
5673 * as this will not attempt to reload credentials when they are already
5674 * loaded into the object.
5675 *
5676 * @callback callback function(err)
5677 * When this callback is called with no error, it means either credentials
5678 * do not need to be refreshed or refreshed credentials information has
5679 * been loaded into the object (as the `accessKeyId`, `secretAccessKey`,
5680 * and `sessionToken` properties).
5681 * @param err [Error] if an error occurred, this value will be filled
5682 */
5683 get: function get(callback) {
5684 var self = this;
5685 if (this.needsRefresh()) {
5686 this.refresh(function(err) {
5687 if (!err) self.expired = false; // reset expired flag
5688 if (callback) callback(err);
5689 });
5690 } else if (callback) {
5691 callback();
5692 }
5693 },
5694
5695 /**
5696 * @!method getPromise()
5697 * Returns a 'thenable' promise.
5698 * Gets the existing credentials, refreshing them if they are not yet loaded
5699 * or have expired. Users should call this method before using {refresh},
5700 * as this will not attempt to reload credentials when they are already
5701 * loaded into the object.
5702 *
5703 * Two callbacks can be provided to the `then` method on the returned promise.
5704 * The first callback will be called if the promise is fulfilled, and the second
5705 * callback will be called if the promise is rejected.
5706 * @callback fulfilledCallback function()
5707 * Called if the promise is fulfilled. When this callback is called, it
5708 * means either credentials do not need to be refreshed or refreshed
5709 * credentials information has been loaded into the object (as the
5710 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5711 * @callback rejectedCallback function(err)
5712 * Called if the promise is rejected.
5713 * @param err [Error] if an error occurred, this value will be filled
5714 * @return [Promise] A promise that represents the state of the `get` call.
5715 * @example Calling the `getPromise` method.
5716 * var promise = credProvider.getPromise();
5717 * promise.then(function() { ... }, function(err) { ... });
5718 */
5719
5720 /**
5721 * @!method refreshPromise()
5722 * Returns a 'thenable' promise.
5723 * Refreshes the credentials. Users should call {get} before attempting
5724 * to forcibly refresh credentials.
5725 *
5726 * Two callbacks can be provided to the `then` method on the returned promise.
5727 * The first callback will be called if the promise is fulfilled, and the second
5728 * callback will be called if the promise is rejected.
5729 * @callback fulfilledCallback function()
5730 * Called if the promise is fulfilled. When this callback is called, it
5731 * means refreshed credentials information has been loaded into the object
5732 * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5733 * @callback rejectedCallback function(err)
5734 * Called if the promise is rejected.
5735 * @param err [Error] if an error occurred, this value will be filled
5736 * @return [Promise] A promise that represents the state of the `refresh` call.
5737 * @example Calling the `refreshPromise` method.
5738 * var promise = credProvider.refreshPromise();
5739 * promise.then(function() { ... }, function(err) { ... });
5740 */
5741
5742 /**
5743 * Refreshes the credentials. Users should call {get} before attempting
5744 * to forcibly refresh credentials.
5745 *
5746 * @callback callback function(err)
5747 * When this callback is called with no error, it means refreshed
5748 * credentials information has been loaded into the object (as the
5749 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5750 * @param err [Error] if an error occurred, this value will be filled
5751 * @note Subclasses should override this class to reset the
5752 * {accessKeyId}, {secretAccessKey} and optional {sessionToken}
5753 * on the credentials object and then call the callback with
5754 * any error information.
5755 * @see get
5756 */
5757 refresh: function refresh(callback) {
5758 this.expired = false;
5759 callback();
5760 },
5761
5762 /**
5763 * @api private
5764 * @param callback
5765 */
5766 coalesceRefresh: function coalesceRefresh(callback, sync) {
5767 var self = this;
5768 if (self.refreshCallbacks.push(callback) === 1) {
5769 self.load(function onLoad(err) {
5770 AWS.util.arrayEach(self.refreshCallbacks, function(callback) {
5771 if (sync) {
5772 callback(err);
5773 } else {
5774 // callback could throw, so defer to ensure all callbacks are notified
5775 AWS.util.defer(function () {
5776 callback(err);
5777 });
5778 }
5779 });
5780 self.refreshCallbacks.length = 0;
5781 });
5782 }
5783 },
5784
5785 /**
5786 * @api private
5787 * @param callback
5788 */
5789 load: function load(callback) {
5790 callback();
5791 }
5792 });
5793
5794 /**
5795 * @api private
5796 */
5797 AWS.Credentials.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
5798 this.prototype.getPromise = AWS.util.promisifyMethod('get', PromiseDependency);
5799 this.prototype.refreshPromise = AWS.util.promisifyMethod('refresh', PromiseDependency);
5800 };
5801
5802 /**
5803 * @api private
5804 */
5805 AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() {
5806 delete this.prototype.getPromise;
5807 delete this.prototype.refreshPromise;
5808 };
5809
5810 AWS.util.addPromises(AWS.Credentials);
5811
5812
5813/***/ }),
5814/* 42 */
5815/***/ (function(module, exports, __webpack_require__) {
5816
5817 var AWS = __webpack_require__(1);
5818
5819 /**
5820 * Creates a credential provider chain that searches for AWS credentials
5821 * in a list of credential providers specified by the {providers} property.
5822 *
5823 * By default, the chain will use the {defaultProviders} to resolve credentials.
5824 * These providers will look in the environment using the
5825 * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes.
5826 *
5827 * ## Setting Providers
5828 *
5829 * Each provider in the {providers} list should be a function that returns
5830 * a {AWS.Credentials} object, or a hardcoded credentials object. The function
5831 * form allows for delayed execution of the credential construction.
5832 *
5833 * ## Resolving Credentials from a Chain
5834 *
5835 * Call {resolve} to return the first valid credential object that can be
5836 * loaded by the provider chain.
5837 *
5838 * For example, to resolve a chain with a custom provider that checks a file
5839 * on disk after the set of {defaultProviders}:
5840 *
5841 * ```javascript
5842 * var diskProvider = new AWS.FileSystemCredentials('./creds.json');
5843 * var chain = new AWS.CredentialProviderChain();
5844 * chain.providers.push(diskProvider);
5845 * chain.resolve();
5846 * ```
5847 *
5848 * The above code will return the `diskProvider` object if the
5849 * file contains credentials and the `defaultProviders` do not contain
5850 * any credential settings.
5851 *
5852 * @!attribute providers
5853 * @return [Array<AWS.Credentials, Function>]
5854 * a list of credentials objects or functions that return credentials
5855 * objects. If the provider is a function, the function will be
5856 * executed lazily when the provider needs to be checked for valid
5857 * credentials. By default, this object will be set to the
5858 * {defaultProviders}.
5859 * @see defaultProviders
5860 */
5861 AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, {
5862
5863 /**
5864 * Creates a new CredentialProviderChain with a default set of providers
5865 * specified by {defaultProviders}.
5866 */
5867 constructor: function CredentialProviderChain(providers) {
5868 if (providers) {
5869 this.providers = providers;
5870 } else {
5871 this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
5872 }
5873 this.resolveCallbacks = [];
5874 },
5875
5876 /**
5877 * @!method resolvePromise()
5878 * Returns a 'thenable' promise.
5879 * Resolves the provider chain by searching for the first set of
5880 * credentials in {providers}.
5881 *
5882 * Two callbacks can be provided to the `then` method on the returned promise.
5883 * The first callback will be called if the promise is fulfilled, and the second
5884 * callback will be called if the promise is rejected.
5885 * @callback fulfilledCallback function(credentials)
5886 * Called if the promise is fulfilled and the provider resolves the chain
5887 * to a credentials object
5888 * @param credentials [AWS.Credentials] the credentials object resolved
5889 * by the provider chain.
5890 * @callback rejectedCallback function(error)
5891 * Called if the promise is rejected.
5892 * @param err [Error] the error object returned if no credentials are found.
5893 * @return [Promise] A promise that represents the state of the `resolve` method call.
5894 * @example Calling the `resolvePromise` method.
5895 * var promise = chain.resolvePromise();
5896 * promise.then(function(credentials) { ... }, function(err) { ... });
5897 */
5898
5899 /**
5900 * Resolves the provider chain by searching for the first set of
5901 * credentials in {providers}.
5902 *
5903 * @callback callback function(err, credentials)
5904 * Called when the provider resolves the chain to a credentials object
5905 * or null if no credentials can be found.
5906 *
5907 * @param err [Error] the error object returned if no credentials are
5908 * found.
5909 * @param credentials [AWS.Credentials] the credentials object resolved
5910 * by the provider chain.
5911 * @return [AWS.CredentialProviderChain] the provider, for chaining.
5912 */
5913 resolve: function resolve(callback) {
5914 var self = this;
5915 if (self.providers.length === 0) {
5916 callback(new Error('No providers'));
5917 return self;
5918 }
5919
5920 if (self.resolveCallbacks.push(callback) === 1) {
5921 var index = 0;
5922 var providers = self.providers.slice(0);
5923
5924 function resolveNext(err, creds) {
5925 if ((!err && creds) || index === providers.length) {
5926 AWS.util.arrayEach(self.resolveCallbacks, function (callback) {
5927 callback(err, creds);
5928 });
5929 self.resolveCallbacks.length = 0;
5930 return;
5931 }
5932
5933 var provider = providers[index++];
5934 if (typeof provider === 'function') {
5935 creds = provider.call();
5936 } else {
5937 creds = provider;
5938 }
5939
5940 if (creds.get) {
5941 creds.get(function (getErr) {
5942 resolveNext(getErr, getErr ? null : creds);
5943 });
5944 } else {
5945 resolveNext(null, creds);
5946 }
5947 }
5948
5949 resolveNext();
5950 }
5951
5952 return self;
5953 }
5954 });
5955
5956 /**
5957 * The default set of providers used by a vanilla CredentialProviderChain.
5958 *
5959 * In the browser:
5960 *
5961 * ```javascript
5962 * AWS.CredentialProviderChain.defaultProviders = []
5963 * ```
5964 *
5965 * In Node.js:
5966 *
5967 * ```javascript
5968 * AWS.CredentialProviderChain.defaultProviders = [
5969 * function () { return new AWS.EnvironmentCredentials('AWS'); },
5970 * function () { return new AWS.EnvironmentCredentials('AMAZON'); },
5971 * function () { return new AWS.SharedIniFileCredentials(); },
5972 * function () {
5973 * // if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set
5974 * return new AWS.ECSCredentials();
5975 * // else
5976 * return new AWS.EC2MetadataCredentials();
5977 * }
5978 * ]
5979 * ```
5980 */
5981 AWS.CredentialProviderChain.defaultProviders = [];
5982
5983 /**
5984 * @api private
5985 */
5986 AWS.CredentialProviderChain.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
5987 this.prototype.resolvePromise = AWS.util.promisifyMethod('resolve', PromiseDependency);
5988 };
5989
5990 /**
5991 * @api private
5992 */
5993 AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFromClass() {
5994 delete this.prototype.resolvePromise;
5995 };
5996
5997 AWS.util.addPromises(AWS.CredentialProviderChain);
5998
5999
6000/***/ }),
6001/* 43 */
6002/***/ (function(module, exports, __webpack_require__) {
6003
6004 var AWS = __webpack_require__(1);
6005 var inherit = AWS.util.inherit;
6006
6007 /**
6008 * The endpoint that a service will talk to, for example,
6009 * `'https://ec2.ap-southeast-1.amazonaws.com'`. If
6010 * you need to override an endpoint for a service, you can
6011 * set the endpoint on a service by passing the endpoint
6012 * object with the `endpoint` option key:
6013 *
6014 * ```javascript
6015 * var ep = new AWS.Endpoint('awsproxy.example.com');
6016 * var s3 = new AWS.S3({endpoint: ep});
6017 * s3.service.endpoint.hostname == 'awsproxy.example.com'
6018 * ```
6019 *
6020 * Note that if you do not specify a protocol, the protocol will
6021 * be selected based on your current {AWS.config} configuration.
6022 *
6023 * @!attribute protocol
6024 * @return [String] the protocol (http or https) of the endpoint
6025 * URL
6026 * @!attribute hostname
6027 * @return [String] the host portion of the endpoint, e.g.,
6028 * example.com
6029 * @!attribute host
6030 * @return [String] the host portion of the endpoint including
6031 * the port, e.g., example.com:80
6032 * @!attribute port
6033 * @return [Integer] the port of the endpoint
6034 * @!attribute href
6035 * @return [String] the full URL of the endpoint
6036 */
6037 AWS.Endpoint = inherit({
6038
6039 /**
6040 * @overload Endpoint(endpoint)
6041 * Constructs a new endpoint given an endpoint URL. If the
6042 * URL omits a protocol (http or https), the default protocol
6043 * set in the global {AWS.config} will be used.
6044 * @param endpoint [String] the URL to construct an endpoint from
6045 */
6046 constructor: function Endpoint(endpoint, config) {
6047 AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']);
6048
6049 if (typeof endpoint === 'undefined' || endpoint === null) {
6050 throw new Error('Invalid endpoint: ' + endpoint);
6051 } else if (typeof endpoint !== 'string') {
6052 return AWS.util.copy(endpoint);
6053 }
6054
6055 if (!endpoint.match(/^http/)) {
6056 var useSSL = config && config.sslEnabled !== undefined ?
6057 config.sslEnabled : AWS.config.sslEnabled;
6058 endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
6059 }
6060
6061 AWS.util.update(this, AWS.util.urlParse(endpoint));
6062
6063 // Ensure the port property is set as an integer
6064 if (this.port) {
6065 this.port = parseInt(this.port, 10);
6066 } else {
6067 this.port = this.protocol === 'https:' ? 443 : 80;
6068 }
6069 }
6070
6071 });
6072
6073 /**
6074 * The low level HTTP request object, encapsulating all HTTP header
6075 * and body data sent by a service request.
6076 *
6077 * @!attribute method
6078 * @return [String] the HTTP method of the request
6079 * @!attribute path
6080 * @return [String] the path portion of the URI, e.g.,
6081 * "/list/?start=5&num=10"
6082 * @!attribute headers
6083 * @return [map<String,String>]
6084 * a map of header keys and their respective values
6085 * @!attribute body
6086 * @return [String] the request body payload
6087 * @!attribute endpoint
6088 * @return [AWS.Endpoint] the endpoint for the request
6089 * @!attribute region
6090 * @api private
6091 * @return [String] the region, for signing purposes only.
6092 */
6093 AWS.HttpRequest = inherit({
6094
6095 /**
6096 * @api private
6097 */
6098 constructor: function HttpRequest(endpoint, region) {
6099 endpoint = new AWS.Endpoint(endpoint);
6100 this.method = 'POST';
6101 this.path = endpoint.path || '/';
6102 this.headers = {};
6103 this.body = '';
6104 this.endpoint = endpoint;
6105 this.region = region;
6106 this._userAgent = '';
6107 this.setUserAgent();
6108 },
6109
6110 /**
6111 * @api private
6112 */
6113 setUserAgent: function setUserAgent() {
6114 this._userAgent = this.headers[this.getUserAgentHeaderName()] = AWS.util.userAgent();
6115 },
6116
6117 getUserAgentHeaderName: function getUserAgentHeaderName() {
6118 var prefix = AWS.util.isBrowser() ? 'X-Amz-' : '';
6119 return prefix + 'User-Agent';
6120 },
6121
6122 /**
6123 * @api private
6124 */
6125 appendToUserAgent: function appendToUserAgent(agentPartial) {
6126 if (typeof agentPartial === 'string' && agentPartial) {
6127 this._userAgent += ' ' + agentPartial;
6128 }
6129 this.headers[this.getUserAgentHeaderName()] = this._userAgent;
6130 },
6131
6132 /**
6133 * @api private
6134 */
6135 getUserAgent: function getUserAgent() {
6136 return this._userAgent;
6137 },
6138
6139 /**
6140 * @return [String] the part of the {path} excluding the
6141 * query string
6142 */
6143 pathname: function pathname() {
6144 return this.path.split('?', 1)[0];
6145 },
6146
6147 /**
6148 * @return [String] the query string portion of the {path}
6149 */
6150 search: function search() {
6151 var query = this.path.split('?', 2)[1];
6152 if (query) {
6153 query = AWS.util.queryStringParse(query);
6154 return AWS.util.queryParamsToString(query);
6155 }
6156 return '';
6157 },
6158
6159 /**
6160 * @api private
6161 * update httpRequest endpoint with endpoint string
6162 */
6163 updateEndpoint: function updateEndpoint(endpointStr) {
6164 var newEndpoint = new AWS.Endpoint(endpointStr);
6165 this.endpoint = newEndpoint;
6166 this.path = newEndpoint.path || '/';
6167 }
6168 });
6169
6170 /**
6171 * The low level HTTP response object, encapsulating all HTTP header
6172 * and body data returned from the request.
6173 *
6174 * @!attribute statusCode
6175 * @return [Integer] the HTTP status code of the response (e.g., 200, 404)
6176 * @!attribute headers
6177 * @return [map<String,String>]
6178 * a map of response header keys and their respective values
6179 * @!attribute body
6180 * @return [String] the response body payload
6181 * @!attribute [r] streaming
6182 * @return [Boolean] whether this response is being streamed at a low-level.
6183 * Defaults to `false` (buffered reads). Do not modify this manually, use
6184 * {createUnbufferedStream} to convert the stream to unbuffered mode
6185 * instead.
6186 */
6187 AWS.HttpResponse = inherit({
6188
6189 /**
6190 * @api private
6191 */
6192 constructor: function HttpResponse() {
6193 this.statusCode = undefined;
6194 this.headers = {};
6195 this.body = undefined;
6196 this.streaming = false;
6197 this.stream = null;
6198 },
6199
6200 /**
6201 * Disables buffering on the HTTP response and returns the stream for reading.
6202 * @return [Stream, XMLHttpRequest, null] the underlying stream object.
6203 * Use this object to directly read data off of the stream.
6204 * @note This object is only available after the {AWS.Request~httpHeaders}
6205 * event has fired. This method must be called prior to
6206 * {AWS.Request~httpData}.
6207 * @example Taking control of a stream
6208 * request.on('httpHeaders', function(statusCode, headers) {
6209 * if (statusCode < 300) {
6210 * if (headers.etag === 'xyz') {
6211 * // pipe the stream, disabling buffering
6212 * var stream = this.response.httpResponse.createUnbufferedStream();
6213 * stream.pipe(process.stdout);
6214 * } else { // abort this request and set a better error message
6215 * this.abort();
6216 * this.response.error = new Error('Invalid ETag');
6217 * }
6218 * }
6219 * }).send(console.log);
6220 */
6221 createUnbufferedStream: function createUnbufferedStream() {
6222 this.streaming = true;
6223 return this.stream;
6224 }
6225 });
6226
6227
6228 AWS.HttpClient = inherit({});
6229
6230 /**
6231 * @api private
6232 */
6233 AWS.HttpClient.getInstance = function getInstance() {
6234 if (this.singleton === undefined) {
6235 this.singleton = new this();
6236 }
6237 return this.singleton;
6238 };
6239
6240
6241/***/ }),
6242/* 44 */
6243/***/ (function(module, exports, __webpack_require__) {
6244
6245 var AWS = __webpack_require__(1);
6246 var SequentialExecutor = __webpack_require__(36);
6247 var DISCOVER_ENDPOINT = __webpack_require__(45).discoverEndpoint;
6248 /**
6249 * The namespace used to register global event listeners for request building
6250 * and sending.
6251 */
6252 AWS.EventListeners = {
6253 /**
6254 * @!attribute VALIDATE_CREDENTIALS
6255 * A request listener that validates whether the request is being
6256 * sent with credentials.
6257 * Handles the {AWS.Request~validate 'validate' Request event}
6258 * @example Sending a request without validating credentials
6259 * var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS;
6260 * request.removeListener('validate', listener);
6261 * @readonly
6262 * @return [Function]
6263 * @!attribute VALIDATE_REGION
6264 * A request listener that validates whether the region is set
6265 * for a request.
6266 * Handles the {AWS.Request~validate 'validate' Request event}
6267 * @example Sending a request without validating region configuration
6268 * var listener = AWS.EventListeners.Core.VALIDATE_REGION;
6269 * request.removeListener('validate', listener);
6270 * @readonly
6271 * @return [Function]
6272 * @!attribute VALIDATE_PARAMETERS
6273 * A request listener that validates input parameters in a request.
6274 * Handles the {AWS.Request~validate 'validate' Request event}
6275 * @example Sending a request without validating parameters
6276 * var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS;
6277 * request.removeListener('validate', listener);
6278 * @example Disable parameter validation globally
6279 * AWS.EventListeners.Core.removeListener('validate',
6280 * AWS.EventListeners.Core.VALIDATE_REGION);
6281 * @readonly
6282 * @return [Function]
6283 * @!attribute SEND
6284 * A request listener that initiates the HTTP connection for a
6285 * request being sent. Handles the {AWS.Request~send 'send' Request event}
6286 * @example Replacing the HTTP handler
6287 * var listener = AWS.EventListeners.Core.SEND;
6288 * request.removeListener('send', listener);
6289 * request.on('send', function(response) {
6290 * customHandler.send(response);
6291 * });
6292 * @return [Function]
6293 * @readonly
6294 * @!attribute HTTP_DATA
6295 * A request listener that reads data from the HTTP connection in order
6296 * to build the response data.
6297 * Handles the {AWS.Request~httpData 'httpData' Request event}.
6298 * Remove this handler if you are overriding the 'httpData' event and
6299 * do not want extra data processing and buffering overhead.
6300 * @example Disabling default data processing
6301 * var listener = AWS.EventListeners.Core.HTTP_DATA;
6302 * request.removeListener('httpData', listener);
6303 * @return [Function]
6304 * @readonly
6305 */
6306 Core: {} /* doc hack */
6307 };
6308
6309 /**
6310 * @api private
6311 */
6312 function getOperationAuthtype(req) {
6313 if (!req.service.api.operations) {
6314 return '';
6315 }
6316 var operation = req.service.api.operations[req.operation];
6317 return operation ? operation.authtype : '';
6318 }
6319
6320 AWS.EventListeners = {
6321 Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) {
6322 addAsync('VALIDATE_CREDENTIALS', 'validate',
6323 function VALIDATE_CREDENTIALS(req, done) {
6324 if (!req.service.api.signatureVersion) return done(); // none
6325 req.service.config.getCredentials(function(err) {
6326 if (err) {
6327 req.response.error = AWS.util.error(err,
6328 {code: 'CredentialsError', message: 'Missing credentials in config'});
6329 }
6330 done();
6331 });
6332 });
6333
6334 add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
6335 if (!req.service.config.region && !req.service.isGlobalEndpoint) {
6336 req.response.error = AWS.util.error(new Error(),
6337 {code: 'ConfigError', message: 'Missing region in config'});
6338 }
6339 });
6340
6341 add('BUILD_IDEMPOTENCY_TOKENS', 'validate', function BUILD_IDEMPOTENCY_TOKENS(req) {
6342 if (!req.service.api.operations) {
6343 return;
6344 }
6345 var operation = req.service.api.operations[req.operation];
6346 if (!operation) {
6347 return;
6348 }
6349 var idempotentMembers = operation.idempotentMembers;
6350 if (!idempotentMembers.length) {
6351 return;
6352 }
6353 // creates a copy of params so user's param object isn't mutated
6354 var params = AWS.util.copy(req.params);
6355 for (var i = 0, iLen = idempotentMembers.length; i < iLen; i++) {
6356 if (!params[idempotentMembers[i]]) {
6357 // add the member
6358 params[idempotentMembers[i]] = AWS.util.uuid.v4();
6359 }
6360 }
6361 req.params = params;
6362 });
6363
6364 add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) {
6365 if (!req.service.api.operations) {
6366 return;
6367 }
6368 var rules = req.service.api.operations[req.operation].input;
6369 var validation = req.service.config.paramValidation;
6370 new AWS.ParamValidator(validation).validate(rules, req.params);
6371 });
6372
6373 addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) {
6374 req.haltHandlersOnError();
6375 if (!req.service.api.operations) {
6376 return;
6377 }
6378 var operation = req.service.api.operations[req.operation];
6379 var authtype = operation ? operation.authtype : '';
6380 if (!req.service.api.signatureVersion && !authtype) return done(); // none
6381 if (req.service.getSignerClass(req) === AWS.Signers.V4) {
6382 var body = req.httpRequest.body || '';
6383 if (authtype.indexOf('unsigned-body') >= 0) {
6384 req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD';
6385 return done();
6386 }
6387 AWS.util.computeSha256(body, function(err, sha) {
6388 if (err) {
6389 done(err);
6390 }
6391 else {
6392 req.httpRequest.headers['X-Amz-Content-Sha256'] = sha;
6393 done();
6394 }
6395 });
6396 } else {
6397 done();
6398 }
6399 });
6400
6401 add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) {
6402 var authtype = getOperationAuthtype(req);
6403 if (req.httpRequest.headers['Content-Length'] === undefined) {
6404 try {
6405 var length = AWS.util.string.byteLength(req.httpRequest.body);
6406 req.httpRequest.headers['Content-Length'] = length;
6407 } catch (err) {
6408 if (authtype.indexOf('unsigned-body') === -1) {
6409 throw err;
6410 } else {
6411 // Body isn't signed and may not need content length (lex)
6412 return;
6413 }
6414 }
6415 }
6416 });
6417
6418 add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) {
6419 req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host;
6420 });
6421
6422 add('RESTART', 'restart', function RESTART() {
6423 var err = this.response.error;
6424 if (!err || !err.retryable) return;
6425
6426 this.httpRequest = new AWS.HttpRequest(
6427 this.service.endpoint,
6428 this.service.region
6429 );
6430
6431 if (this.response.retryCount < this.service.config.maxRetries) {
6432 this.response.retryCount++;
6433 } else {
6434 this.response.error = null;
6435 }
6436 });
6437
6438 var addToHead = true;
6439 addAsync('DISCOVER_ENDPOINT', 'sign', DISCOVER_ENDPOINT, addToHead);
6440
6441 addAsync('SIGN', 'sign', function SIGN(req, done) {
6442 var service = req.service;
6443 var operations = req.service.api.operations || {};
6444 var operation = operations[req.operation];
6445 var authtype = operation ? operation.authtype : '';
6446 if (!service.api.signatureVersion && !authtype) return done(); // none
6447
6448 service.config.getCredentials(function (err, credentials) {
6449 if (err) {
6450 req.response.error = err;
6451 return done();
6452 }
6453
6454 try {
6455 var date = service.getSkewCorrectedDate();
6456 var SignerClass = service.getSignerClass(req);
6457 var signer = new SignerClass(req.httpRequest,
6458 service.api.signingName || service.api.endpointPrefix,
6459 {
6460 signatureCache: service.config.signatureCache,
6461 operation: operation,
6462 signatureVersion: service.api.signatureVersion
6463 });
6464 signer.setServiceClientId(service._clientId);
6465
6466 // clear old authorization headers
6467 delete req.httpRequest.headers['Authorization'];
6468 delete req.httpRequest.headers['Date'];
6469 delete req.httpRequest.headers['X-Amz-Date'];
6470
6471 // add new authorization
6472 signer.addAuthorization(credentials, date);
6473 req.signedAt = date;
6474 } catch (e) {
6475 req.response.error = e;
6476 }
6477 done();
6478 });
6479 });
6480
6481 add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) {
6482 if (this.service.successfulResponse(resp, this)) {
6483 resp.data = {};
6484 resp.error = null;
6485 } else {
6486 resp.data = null;
6487 resp.error = AWS.util.error(new Error(),
6488 {code: 'UnknownError', message: 'An unknown error occurred.'});
6489 }
6490 });
6491
6492 addAsync('SEND', 'send', function SEND(resp, done) {
6493 resp.httpResponse._abortCallback = done;
6494 resp.error = null;
6495 resp.data = null;
6496
6497 function callback(httpResp) {
6498 resp.httpResponse.stream = httpResp;
6499 var stream = resp.request.httpRequest.stream;
6500 var service = resp.request.service;
6501 var api = service.api;
6502 var operationName = resp.request.operation;
6503 var operation = api.operations[operationName] || {};
6504
6505 httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) {
6506 resp.request.emit(
6507 'httpHeaders',
6508 [statusCode, headers, resp, statusMessage]
6509 );
6510
6511 if (!resp.httpResponse.streaming) {
6512 if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check
6513 // if we detect event streams, we're going to have to
6514 // return the stream immediately
6515 if (operation.hasEventOutput && service.successfulResponse(resp)) {
6516 // skip reading the IncomingStream
6517 resp.request.emit('httpDone');
6518 done();
6519 return;
6520 }
6521
6522 httpResp.on('readable', function onReadable() {
6523 var data = httpResp.read();
6524 if (data !== null) {
6525 resp.request.emit('httpData', [data, resp]);
6526 }
6527 });
6528 } else { // legacy streams API
6529 httpResp.on('data', function onData(data) {
6530 resp.request.emit('httpData', [data, resp]);
6531 });
6532 }
6533 }
6534 });
6535
6536 httpResp.on('end', function onEnd() {
6537 if (!stream || !stream.didCallback) {
6538 if (AWS.HttpClient.streamsApiVersion === 2 && (operation.hasEventOutput && service.successfulResponse(resp))) {
6539 // don't concatenate response chunks when streaming event stream data when response is successful
6540 return;
6541 }
6542 resp.request.emit('httpDone');
6543 done();
6544 }
6545 });
6546 }
6547
6548 function progress(httpResp) {
6549 httpResp.on('sendProgress', function onSendProgress(value) {
6550 resp.request.emit('httpUploadProgress', [value, resp]);
6551 });
6552
6553 httpResp.on('receiveProgress', function onReceiveProgress(value) {
6554 resp.request.emit('httpDownloadProgress', [value, resp]);
6555 });
6556 }
6557
6558 function error(err) {
6559 if (err.code !== 'RequestAbortedError') {
6560 var errCode = err.code === 'TimeoutError' ? err.code : 'NetworkingError';
6561 err = AWS.util.error(err, {
6562 code: errCode,
6563 region: resp.request.httpRequest.region,
6564 hostname: resp.request.httpRequest.endpoint.hostname,
6565 retryable: true
6566 });
6567 }
6568 resp.error = err;
6569 resp.request.emit('httpError', [resp.error, resp], function() {
6570 done();
6571 });
6572 }
6573
6574 function executeSend() {
6575 var http = AWS.HttpClient.getInstance();
6576 var httpOptions = resp.request.service.config.httpOptions || {};
6577 try {
6578 var stream = http.handleRequest(resp.request.httpRequest, httpOptions,
6579 callback, error);
6580 progress(stream);
6581 } catch (err) {
6582 error(err);
6583 }
6584 }
6585 var timeDiff = (resp.request.service.getSkewCorrectedDate() - this.signedAt) / 1000;
6586 if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign
6587 this.emit('sign', [this], function(err) {
6588 if (err) done(err);
6589 else executeSend();
6590 });
6591 } else {
6592 executeSend();
6593 }
6594 });
6595
6596 add('HTTP_HEADERS', 'httpHeaders',
6597 function HTTP_HEADERS(statusCode, headers, resp, statusMessage) {
6598 resp.httpResponse.statusCode = statusCode;
6599 resp.httpResponse.statusMessage = statusMessage;
6600 resp.httpResponse.headers = headers;
6601 resp.httpResponse.body = new AWS.util.Buffer('');
6602 resp.httpResponse.buffers = [];
6603 resp.httpResponse.numBytes = 0;
6604 var dateHeader = headers.date || headers.Date;
6605 var service = resp.request.service;
6606 if (dateHeader) {
6607 var serverTime = Date.parse(dateHeader);
6608 if (service.config.correctClockSkew
6609 && service.isClockSkewed(serverTime)) {
6610 service.applyClockOffset(serverTime);
6611 }
6612 }
6613 });
6614
6615 add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) {
6616 if (chunk) {
6617 if (AWS.util.isNode()) {
6618 resp.httpResponse.numBytes += chunk.length;
6619
6620 var total = resp.httpResponse.headers['content-length'];
6621 var progress = { loaded: resp.httpResponse.numBytes, total: total };
6622 resp.request.emit('httpDownloadProgress', [progress, resp]);
6623 }
6624
6625 resp.httpResponse.buffers.push(new AWS.util.Buffer(chunk));
6626 }
6627 });
6628
6629 add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) {
6630 // convert buffers array into single buffer
6631 if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) {
6632 var body = AWS.util.buffer.concat(resp.httpResponse.buffers);
6633 resp.httpResponse.body = body;
6634 }
6635 delete resp.httpResponse.numBytes;
6636 delete resp.httpResponse.buffers;
6637 });
6638
6639 add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) {
6640 if (resp.httpResponse.statusCode) {
6641 resp.error.statusCode = resp.httpResponse.statusCode;
6642 if (resp.error.retryable === undefined) {
6643 resp.error.retryable = this.service.retryableError(resp.error, this);
6644 }
6645 }
6646 });
6647
6648 add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) {
6649 if (!resp.error) return;
6650 switch (resp.error.code) {
6651 case 'RequestExpired': // EC2 only
6652 case 'ExpiredTokenException':
6653 case 'ExpiredToken':
6654 resp.error.retryable = true;
6655 resp.request.service.config.credentials.expired = true;
6656 }
6657 });
6658
6659 add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) {
6660 var err = resp.error;
6661 if (!err) return;
6662 if (typeof err.code === 'string' && typeof err.message === 'string') {
6663 if (err.code.match(/Signature/) && err.message.match(/expired/)) {
6664 resp.error.retryable = true;
6665 }
6666 }
6667 });
6668
6669 add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) {
6670 if (!resp.error) return;
6671 if (this.service.clockSkewError(resp.error)
6672 && this.service.config.correctClockSkew) {
6673 resp.error.retryable = true;
6674 }
6675 });
6676
6677 add('REDIRECT', 'retry', function REDIRECT(resp) {
6678 if (resp.error && resp.error.statusCode >= 300 &&
6679 resp.error.statusCode < 400 && resp.httpResponse.headers['location']) {
6680 this.httpRequest.endpoint =
6681 new AWS.Endpoint(resp.httpResponse.headers['location']);
6682 this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host;
6683 resp.error.redirect = true;
6684 resp.error.retryable = true;
6685 }
6686 });
6687
6688 add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) {
6689 if (resp.error) {
6690 if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6691 resp.error.retryDelay = 0;
6692 } else if (resp.retryCount < resp.maxRetries) {
6693 resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0;
6694 }
6695 }
6696 });
6697
6698 addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) {
6699 var delay, willRetry = false;
6700
6701 if (resp.error) {
6702 delay = resp.error.retryDelay || 0;
6703 if (resp.error.retryable && resp.retryCount < resp.maxRetries) {
6704 resp.retryCount++;
6705 willRetry = true;
6706 } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6707 resp.redirectCount++;
6708 willRetry = true;
6709 }
6710 }
6711
6712 if (willRetry) {
6713 resp.error = null;
6714 setTimeout(done, delay);
6715 } else {
6716 done();
6717 }
6718 });
6719 }),
6720
6721 CorePost: new SequentialExecutor().addNamedListeners(function(add) {
6722 add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId);
6723 add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId);
6724
6725 add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) {
6726 if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') {
6727 var message = 'Inaccessible host: `' + err.hostname +
6728 '\'. This service may not be available in the `' + err.region +
6729 '\' region.';
6730 this.response.error = AWS.util.error(new Error(message), {
6731 code: 'UnknownEndpoint',
6732 region: err.region,
6733 hostname: err.hostname,
6734 retryable: true,
6735 originalError: err
6736 });
6737 }
6738 });
6739 }),
6740
6741 Logger: new SequentialExecutor().addNamedListeners(function(add) {
6742 add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) {
6743 var req = resp.request;
6744 var logger = req.service.config.logger;
6745 if (!logger) return;
6746 function filterSensitiveLog(inputShape, shape) {
6747 if (!shape) {
6748 return shape;
6749 }
6750 switch (inputShape.type) {
6751 case 'structure':
6752 var struct = {};
6753 AWS.util.each(shape, function(subShapeName, subShape) {
6754 if (Object.prototype.hasOwnProperty.call(inputShape.members, subShapeName)) {
6755 struct[subShapeName] = filterSensitiveLog(inputShape.members[subShapeName], subShape);
6756 } else {
6757 struct[subShapeName] = subShape;
6758 }
6759 });
6760 return struct;
6761 case 'list':
6762 var list = [];
6763 AWS.util.arrayEach(shape, function(subShape, index) {
6764 list.push(filterSensitiveLog(inputShape.member, subShape));
6765 });
6766 return list;
6767 case 'map':
6768 var map = {};
6769 AWS.util.each(shape, function(key, value) {
6770 map[key] = filterSensitiveLog(inputShape.value, value);
6771 });
6772 return map;
6773 default:
6774 if (inputShape.isSensitive) {
6775 return '***SensitiveInformation***';
6776 } else {
6777 return shape;
6778 }
6779 }
6780 }
6781
6782 function buildMessage() {
6783 var time = resp.request.service.getSkewCorrectedDate().getTime();
6784 var delta = (time - req.startTime.getTime()) / 1000;
6785 var ansi = logger.isTTY ? true : false;
6786 var status = resp.httpResponse.statusCode;
6787 var censoredParams = req.params;
6788 if (
6789 req.service.api.operations &&
6790 req.service.api.operations[req.operation] &&
6791 req.service.api.operations[req.operation].input
6792 ) {
6793 var inputShape = req.service.api.operations[req.operation].input;
6794 censoredParams = filterSensitiveLog(inputShape, req.params);
6795 }
6796 var params = __webpack_require__(46).inspect(censoredParams, true, null);
6797 var message = '';
6798 if (ansi) message += '\x1B[33m';
6799 message += '[AWS ' + req.service.serviceIdentifier + ' ' + status;
6800 message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]';
6801 if (ansi) message += '\x1B[0;1m';
6802 message += ' ' + AWS.util.string.lowerFirst(req.operation);
6803 message += '(' + params + ')';
6804 if (ansi) message += '\x1B[0m';
6805 return message;
6806 }
6807
6808 var line = buildMessage();
6809 if (typeof logger.log === 'function') {
6810 logger.log(line);
6811 } else if (typeof logger.write === 'function') {
6812 logger.write(line + '\n');
6813 }
6814 });
6815 }),
6816
6817 Json: new SequentialExecutor().addNamedListeners(function(add) {
6818 var svc = __webpack_require__(13);
6819 add('BUILD', 'build', svc.buildRequest);
6820 add('EXTRACT_DATA', 'extractData', svc.extractData);
6821 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6822 }),
6823
6824 Rest: new SequentialExecutor().addNamedListeners(function(add) {
6825 var svc = __webpack_require__(21);
6826 add('BUILD', 'build', svc.buildRequest);
6827 add('EXTRACT_DATA', 'extractData', svc.extractData);
6828 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6829 }),
6830
6831 RestJson: new SequentialExecutor().addNamedListeners(function(add) {
6832 var svc = __webpack_require__(22);
6833 add('BUILD', 'build', svc.buildRequest);
6834 add('EXTRACT_DATA', 'extractData', svc.extractData);
6835 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6836 }),
6837
6838 RestXml: new SequentialExecutor().addNamedListeners(function(add) {
6839 var svc = __webpack_require__(23);
6840 add('BUILD', 'build', svc.buildRequest);
6841 add('EXTRACT_DATA', 'extractData', svc.extractData);
6842 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6843 }),
6844
6845 Query: new SequentialExecutor().addNamedListeners(function(add) {
6846 var svc = __webpack_require__(17);
6847 add('BUILD', 'build', svc.buildRequest);
6848 add('EXTRACT_DATA', 'extractData', svc.extractData);
6849 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6850 })
6851 };
6852
6853
6854/***/ }),
6855/* 45 */
6856/***/ (function(module, exports, __webpack_require__) {
6857
6858 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
6859 var util = __webpack_require__(2);
6860 var endpointDiscoveryEnabledEnvs = ['AWS_ENABLE_ENDPOINT_DISCOVERY', 'AWS_ENDPOINT_DISCOVERY_ENABLED'];
6861
6862 /**
6863 * Generate key (except resources and operation part) to index the endpoints in the cache
6864 * If input shape has endpointdiscoveryid trait then use
6865 * accessKey + operation + resources + region + service as cache key
6866 * If input shape doesn't have endpointdiscoveryid trait then use
6867 * accessKey + region + service as cache key
6868 * @return [map<String,String>] object with keys to index endpoints.
6869 * @api private
6870 */
6871 function getCacheKey(request) {
6872 var service = request.service;
6873 var api = service.api || {};
6874 var operations = api.operations;
6875 var identifiers = {};
6876 if (service.config.region) {
6877 identifiers.region = service.config.region;
6878 }
6879 if (api.serviceId) {
6880 identifiers.serviceId = api.serviceId;
6881 }
6882 if (service.config.credentials.accessKeyId) {
6883 identifiers.accessKeyId = service.config.credentials.accessKeyId;
6884 }
6885 return identifiers;
6886 }
6887
6888 /**
6889 * Recursive helper for marshallCustomIdentifiers().
6890 * Looks for required string input members that have 'endpointdiscoveryid' trait.
6891 * @api private
6892 */
6893 function marshallCustomIdentifiersHelper(result, params, shape) {
6894 if (!shape || params === undefined || params === null) return;
6895 if (shape.type === 'structure' && shape.required && shape.required.length > 0) {
6896 util.arrayEach(shape.required, function(name) {
6897 var memberShape = shape.members[name];
6898 if (memberShape.endpointDiscoveryId === true) {
6899 var locationName = memberShape.isLocationName ? memberShape.name : name;
6900 result[locationName] = String(params[name]);
6901 } else {
6902 marshallCustomIdentifiersHelper(result, params[name], memberShape);
6903 }
6904 });
6905 }
6906 }
6907
6908 /**
6909 * Get custom identifiers for cache key.
6910 * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait.
6911 * @param [object] request object
6912 * @param [object] input shape of the given operation's api
6913 * @api private
6914 */
6915 function marshallCustomIdentifiers(request, shape) {
6916 var identifiers = {};
6917 marshallCustomIdentifiersHelper(identifiers, request.params, shape);
6918 return identifiers;
6919 }
6920
6921 /**
6922 * Call endpoint discovery operation when it's optional.
6923 * When endpoint is available in cache then use the cached endpoints. If endpoints
6924 * are unavailable then use regional endpoints and call endpoint discovery operation
6925 * asynchronously. This is turned off by default.
6926 * @param [object] request object
6927 * @api private
6928 */
6929 function optionalDiscoverEndpoint(request) {
6930 var service = request.service;
6931 var api = service.api;
6932 var operationModel = api.operations ? api.operations[request.operation] : undefined;
6933 var inputShape = operationModel ? operationModel.input : undefined;
6934
6935 var identifiers = marshallCustomIdentifiers(request, inputShape);
6936 var cacheKey = getCacheKey(request);
6937 if (Object.keys(identifiers).length > 0) {
6938 cacheKey = util.update(cacheKey, identifiers);
6939 if (operationModel) cacheKey.operation = operationModel.name;
6940 }
6941 var endpoints = AWS.endpointCache.get(cacheKey);
6942 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
6943 //endpoint operation is being made but response not yet received
6944 //or endpoint operation just failed in 1 minute
6945 return;
6946 } else if (endpoints && endpoints.length > 0) {
6947 //found endpoint record from cache
6948 request.httpRequest.updateEndpoint(endpoints[0].Address);
6949 } else {
6950 //endpoint record not in cache or outdated. make discovery operation
6951 var endpointRequest = service.makeRequest(api.endpointOperation, {
6952 Operation: operationModel.name,
6953 Identifiers: identifiers,
6954 });
6955 addApiVersionHeader(endpointRequest);
6956 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
6957 endpointRequest.removeListener('retry', AWS.EventListeners.Core.RETRY_CHECK);
6958 //put in a placeholder for endpoints already requested, prevent
6959 //too much in-flight calls
6960 AWS.endpointCache.put(cacheKey, [{
6961 Address: '',
6962 CachePeriodInMinutes: 1
6963 }]);
6964 endpointRequest.send(function(err, data) {
6965 if (data && data.Endpoints) {
6966 AWS.endpointCache.put(cacheKey, data.Endpoints);
6967 } else if (err) {
6968 AWS.endpointCache.put(cacheKey, [{
6969 Address: '',
6970 CachePeriodInMinutes: 1 //not to make more endpoint operation in next 1 minute
6971 }]);
6972 }
6973 });
6974 }
6975 }
6976
6977 var requestQueue = {};
6978
6979 /**
6980 * Call endpoint discovery operation when it's required.
6981 * When endpoint is available in cache then use cached ones. If endpoints are
6982 * unavailable then SDK should call endpoint operation then use returned new
6983 * endpoint for the api call. SDK will automatically attempt to do endpoint
6984 * discovery. This is turned off by default
6985 * @param [object] request object
6986 * @api private
6987 */
6988 function requiredDiscoverEndpoint(request, done) {
6989 var service = request.service;
6990 var api = service.api;
6991 var operationModel = api.operations ? api.operations[request.operation] : undefined;
6992 var inputShape = operationModel ? operationModel.input : undefined;
6993
6994 var identifiers = marshallCustomIdentifiers(request, inputShape);
6995 var cacheKey = getCacheKey(request);
6996 if (Object.keys(identifiers).length > 0) {
6997 cacheKey = util.update(cacheKey, identifiers);
6998 if (operationModel) cacheKey.operation = operationModel.name;
6999 }
7000 var cacheKeyStr = AWS.EndpointCache.getKeyString(cacheKey);
7001 var endpoints = AWS.endpointCache.get(cacheKeyStr); //endpoint cache also accepts string keys
7002 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
7003 //endpoint operation is being made but response not yet received
7004 //push request object to a pending queue
7005 if (!requestQueue[cacheKeyStr]) requestQueue[cacheKeyStr] = [];
7006 requestQueue[cacheKeyStr].push({request: request, callback: done});
7007 return;
7008 } else if (endpoints && endpoints.length > 0) {
7009 request.httpRequest.updateEndpoint(endpoints[0].Address);
7010 done();
7011 } else {
7012 var endpointRequest = service.makeRequest(api.endpointOperation, {
7013 Operation: operationModel.name,
7014 Identifiers: identifiers,
7015 });
7016 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
7017 addApiVersionHeader(endpointRequest);
7018
7019 //put in a placeholder for endpoints already requested, prevent
7020 //too much in-flight calls
7021 AWS.endpointCache.put(cacheKeyStr, [{
7022 Address: '',
7023 CachePeriodInMinutes: 60 //long-live cache
7024 }]);
7025 endpointRequest.send(function(err, data) {
7026 if (err) {
7027 var errorParams = {
7028 code: 'EndpointDiscoveryException',
7029 message: 'Request cannot be fulfilled without specifying an endpoint',
7030 retryable: false
7031 };
7032 request.response.error = util.error(err, errorParams);
7033 AWS.endpointCache.remove(cacheKey);
7034
7035 //fail all the pending requests in batch
7036 if (requestQueue[cacheKeyStr]) {
7037 var pendingRequests = requestQueue[cacheKeyStr];
7038 util.arrayEach(pendingRequests, function(requestContext) {
7039 requestContext.request.response.error = util.error(err, errorParams);
7040 requestContext.callback();
7041 });
7042 delete requestQueue[cacheKeyStr];
7043 }
7044 } else if (data) {
7045 AWS.endpointCache.put(cacheKeyStr, data.Endpoints);
7046 request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7047
7048 //update the endpoint for all the pending requests in batch
7049 if (requestQueue[cacheKeyStr]) {
7050 var pendingRequests = requestQueue[cacheKeyStr];
7051 util.arrayEach(pendingRequests, function(requestContext) {
7052 requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7053 requestContext.callback();
7054 });
7055 delete requestQueue[cacheKeyStr];
7056 }
7057 }
7058 done();
7059 });
7060 }
7061 }
7062
7063 /**
7064 * add api version header to endpoint operation
7065 * @api private
7066 */
7067 function addApiVersionHeader(endpointRequest) {
7068 var api = endpointRequest.service.api;
7069 var apiVersion = api.apiVersion;
7070 if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) {
7071 endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion;
7072 }
7073 }
7074
7075 /**
7076 * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid
7077 * endpoint from cache.
7078 * @api private
7079 */
7080 function invalidateCachedEndpoints(response) {
7081 var error = response.error;
7082 var httpResponse = response.httpResponse;
7083 if (error &&
7084 (error.code === 'InvalidEndpointException' || httpResponse.statusCode === 421)
7085 ) {
7086 var request = response.request;
7087 var operations = request.service.api.operations || {};
7088 var inputShape = operations[request.operation] ? operations[request.operation].input : undefined;
7089 var identifiers = marshallCustomIdentifiers(request, inputShape);
7090 var cacheKey = getCacheKey(request);
7091 if (Object.keys(identifiers).length > 0) {
7092 cacheKey = util.update(cacheKey, identifiers);
7093 if (operations[request.operation]) cacheKey.operation = operations[request.operation].name;
7094 }
7095 AWS.endpointCache.remove(cacheKey);
7096 }
7097 }
7098
7099 /**
7100 * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime.
7101 * @param [object] client Service client object.
7102 * @api private
7103 */
7104 function hasCustomEndpoint(client) {
7105 //if set endpoint is set for specific client, enable endpoint discovery will raise an error.
7106 if (client._originalConfig && client._originalConfig.endpoint && client._originalConfig.endpointDiscoveryEnabled === true) {
7107 throw util.error(new Error(), {
7108 code: 'ConfigurationException',
7109 message: 'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.'
7110 });
7111 };
7112 var svcConfig = AWS.config[client.serviceIdentifier] || {};
7113 return Boolean(AWS.config.endpoint || svcConfig.endpoint || (client._originalConfig && client._originalConfig.endpoint));
7114 }
7115
7116 /**
7117 * @api private
7118 */
7119 function isFalsy(value) {
7120 return ['false', '0'].indexOf(value) >= 0;
7121 }
7122
7123 /**
7124 * If endpoint discovery should perform for this request when endpoint discovery is optional.
7125 * SDK performs config resolution in order like below:
7126 * 1. If turned on client configuration(default to off) then turn on endpoint discovery.
7127 * 2. If turned on in env AWS_ENABLE_ENDPOINT_DISCOVERY then turn on endpoint discovery.
7128 * 3. If turned on in shared ini config file with key 'endpoint_discovery_enabled', then
7129 * turn on endpoint discovery.
7130 * @param [object] request request object.
7131 * @api private
7132 */
7133 function isEndpointDiscoveryApplicable(request) {
7134 var service = request.service || {};
7135 if (service.config.endpointDiscoveryEnabled === true) return true;
7136
7137 //shared ini file is only available in Node
7138 //not to check env in browser
7139 if (util.isBrowser()) return false;
7140
7141 for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) {
7142 var env = endpointDiscoveryEnabledEnvs[i];
7143 if (Object.prototype.hasOwnProperty.call(process.env, env)) {
7144 if (process.env[env] === '' || process.env[env] === undefined) {
7145 throw util.error(new Error(), {
7146 code: 'ConfigurationException',
7147 message: 'environmental variable ' + env + ' cannot be set to nothing'
7148 });
7149 }
7150 if (!isFalsy(process.env[env])) return true;
7151 }
7152 }
7153
7154 var configFile = {};
7155 try {
7156 configFile = AWS.util.iniLoader ? AWS.util.iniLoader.loadFrom({
7157 isConfig: true,
7158 filename: process.env[AWS.util.sharedConfigFileEnv]
7159 }) : {};
7160 } catch (e) {}
7161 var sharedFileConfig = configFile[
7162 process.env.AWS_PROFILE || AWS.util.defaultProfile
7163 ] || {};
7164 if (Object.prototype.hasOwnProperty.call(sharedFileConfig, 'endpoint_discovery_enabled')) {
7165 if (sharedFileConfig.endpoint_discovery_enabled === undefined) {
7166 throw util.error(new Error(), {
7167 code: 'ConfigurationException',
7168 message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing'
7169 });
7170 }
7171 if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true;
7172 }
7173 return false;
7174 }
7175
7176 /**
7177 * attach endpoint discovery logic to request object
7178 * @param [object] request
7179 * @api private
7180 */
7181 function discoverEndpoint(request, done) {
7182 var service = request.service || {};
7183 if (hasCustomEndpoint(service) || request.isPresigned()) return done();
7184
7185 if (!isEndpointDiscoveryApplicable(request)) return done();
7186
7187 request.httpRequest.appendToUserAgent('endpoint-discovery');
7188
7189 var operations = service.api.operations || {};
7190 var operationModel = operations[request.operation];
7191 var isEndpointDiscoveryRequired = operationModel ? operationModel.endpointDiscoveryRequired : 'NULL';
7192 switch (isEndpointDiscoveryRequired) {
7193 case 'OPTIONAL':
7194 optionalDiscoverEndpoint(request);
7195 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7196 done();
7197 break;
7198 case 'REQUIRED':
7199 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7200 requiredDiscoverEndpoint(request, done);
7201 break;
7202 case 'NULL':
7203 default:
7204 done();
7205 break;
7206 }
7207 }
7208
7209 module.exports = {
7210 discoverEndpoint: discoverEndpoint,
7211 requiredDiscoverEndpoint: requiredDiscoverEndpoint,
7212 optionalDiscoverEndpoint: optionalDiscoverEndpoint,
7213 marshallCustomIdentifiers: marshallCustomIdentifiers,
7214 getCacheKey: getCacheKey,
7215 invalidateCachedEndpoint: invalidateCachedEndpoints,
7216 };
7217
7218 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
7219
7220/***/ }),
7221/* 46 */
7222/***/ (function(module, exports, __webpack_require__) {
7223
7224 /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
7225 //
7226 // Permission is hereby granted, free of charge, to any person obtaining a
7227 // copy of this software and associated documentation files (the
7228 // "Software"), to deal in the Software without restriction, including
7229 // without limitation the rights to use, copy, modify, merge, publish,
7230 // distribute, sublicense, and/or sell copies of the Software, and to permit
7231 // persons to whom the Software is furnished to do so, subject to the
7232 // following conditions:
7233 //
7234 // The above copyright notice and this permission notice shall be included
7235 // in all copies or substantial portions of the Software.
7236 //
7237 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7238 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7239 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7240 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7241 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7242 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7243 // USE OR OTHER DEALINGS IN THE SOFTWARE.
7244
7245 var formatRegExp = /%[sdj%]/g;
7246 exports.format = function(f) {
7247 if (!isString(f)) {
7248 var objects = [];
7249 for (var i = 0; i < arguments.length; i++) {
7250 objects.push(inspect(arguments[i]));
7251 }
7252 return objects.join(' ');
7253 }
7254
7255 var i = 1;
7256 var args = arguments;
7257 var len = args.length;
7258 var str = String(f).replace(formatRegExp, function(x) {
7259 if (x === '%%') return '%';
7260 if (i >= len) return x;
7261 switch (x) {
7262 case '%s': return String(args[i++]);
7263 case '%d': return Number(args[i++]);
7264 case '%j':
7265 try {
7266 return JSON.stringify(args[i++]);
7267 } catch (_) {
7268 return '[Circular]';
7269 }
7270 default:
7271 return x;
7272 }
7273 });
7274 for (var x = args[i]; i < len; x = args[++i]) {
7275 if (isNull(x) || !isObject(x)) {
7276 str += ' ' + x;
7277 } else {
7278 str += ' ' + inspect(x);
7279 }
7280 }
7281 return str;
7282 };
7283
7284
7285 // Mark that a method should not be used.
7286 // Returns a modified function which warns once by default.
7287 // If --no-deprecation is set, then it is a no-op.
7288 exports.deprecate = function(fn, msg) {
7289 // Allow for deprecating things in the process of starting up.
7290 if (isUndefined(global.process)) {
7291 return function() {
7292 return exports.deprecate(fn, msg).apply(this, arguments);
7293 };
7294 }
7295
7296 if (process.noDeprecation === true) {
7297 return fn;
7298 }
7299
7300 var warned = false;
7301 function deprecated() {
7302 if (!warned) {
7303 if (process.throwDeprecation) {
7304 throw new Error(msg);
7305 } else if (process.traceDeprecation) {
7306 console.trace(msg);
7307 } else {
7308 console.error(msg);
7309 }
7310 warned = true;
7311 }
7312 return fn.apply(this, arguments);
7313 }
7314
7315 return deprecated;
7316 };
7317
7318
7319 var debugs = {};
7320 var debugEnviron;
7321 exports.debuglog = function(set) {
7322 if (isUndefined(debugEnviron))
7323 debugEnviron = process.env.NODE_DEBUG || '';
7324 set = set.toUpperCase();
7325 if (!debugs[set]) {
7326 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
7327 var pid = process.pid;
7328 debugs[set] = function() {
7329 var msg = exports.format.apply(exports, arguments);
7330 console.error('%s %d: %s', set, pid, msg);
7331 };
7332 } else {
7333 debugs[set] = function() {};
7334 }
7335 }
7336 return debugs[set];
7337 };
7338
7339
7340 /**
7341 * Echos the value of a value. Trys to print the value out
7342 * in the best way possible given the different types.
7343 *
7344 * @param {Object} obj The object to print out.
7345 * @param {Object} opts Optional options object that alters the output.
7346 */
7347 /* legacy: obj, showHidden, depth, colors*/
7348 function inspect(obj, opts) {
7349 // default options
7350 var ctx = {
7351 seen: [],
7352 stylize: stylizeNoColor
7353 };
7354 // legacy...
7355 if (arguments.length >= 3) ctx.depth = arguments[2];
7356 if (arguments.length >= 4) ctx.colors = arguments[3];
7357 if (isBoolean(opts)) {
7358 // legacy...
7359 ctx.showHidden = opts;
7360 } else if (opts) {
7361 // got an "options" object
7362 exports._extend(ctx, opts);
7363 }
7364 // set default options
7365 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
7366 if (isUndefined(ctx.depth)) ctx.depth = 2;
7367 if (isUndefined(ctx.colors)) ctx.colors = false;
7368 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
7369 if (ctx.colors) ctx.stylize = stylizeWithColor;
7370 return formatValue(ctx, obj, ctx.depth);
7371 }
7372 exports.inspect = inspect;
7373
7374
7375 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
7376 inspect.colors = {
7377 'bold' : [1, 22],
7378 'italic' : [3, 23],
7379 'underline' : [4, 24],
7380 'inverse' : [7, 27],
7381 'white' : [37, 39],
7382 'grey' : [90, 39],
7383 'black' : [30, 39],
7384 'blue' : [34, 39],
7385 'cyan' : [36, 39],
7386 'green' : [32, 39],
7387 'magenta' : [35, 39],
7388 'red' : [31, 39],
7389 'yellow' : [33, 39]
7390 };
7391
7392 // Don't use 'blue' not visible on cmd.exe
7393 inspect.styles = {
7394 'special': 'cyan',
7395 'number': 'yellow',
7396 'boolean': 'yellow',
7397 'undefined': 'grey',
7398 'null': 'bold',
7399 'string': 'green',
7400 'date': 'magenta',
7401 // "name": intentionally not styling
7402 'regexp': 'red'
7403 };
7404
7405
7406 function stylizeWithColor(str, styleType) {
7407 var style = inspect.styles[styleType];
7408
7409 if (style) {
7410 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
7411 '\u001b[' + inspect.colors[style][1] + 'm';
7412 } else {
7413 return str;
7414 }
7415 }
7416
7417
7418 function stylizeNoColor(str, styleType) {
7419 return str;
7420 }
7421
7422
7423 function arrayToHash(array) {
7424 var hash = {};
7425
7426 array.forEach(function(val, idx) {
7427 hash[val] = true;
7428 });
7429
7430 return hash;
7431 }
7432
7433
7434 function formatValue(ctx, value, recurseTimes) {
7435 // Provide a hook for user-specified inspect functions.
7436 // Check that value is an object with an inspect function on it
7437 if (ctx.customInspect &&
7438 value &&
7439 isFunction(value.inspect) &&
7440 // Filter out the util module, it's inspect function is special
7441 value.inspect !== exports.inspect &&
7442 // Also filter out any prototype objects using the circular check.
7443 !(value.constructor && value.constructor.prototype === value)) {
7444 var ret = value.inspect(recurseTimes, ctx);
7445 if (!isString(ret)) {
7446 ret = formatValue(ctx, ret, recurseTimes);
7447 }
7448 return ret;
7449 }
7450
7451 // Primitive types cannot have properties
7452 var primitive = formatPrimitive(ctx, value);
7453 if (primitive) {
7454 return primitive;
7455 }
7456
7457 // Look up the keys of the object.
7458 var keys = Object.keys(value);
7459 var visibleKeys = arrayToHash(keys);
7460
7461 if (ctx.showHidden) {
7462 keys = Object.getOwnPropertyNames(value);
7463 }
7464
7465 // IE doesn't make error fields non-enumerable
7466 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
7467 if (isError(value)
7468 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
7469 return formatError(value);
7470 }
7471
7472 // Some type of object without properties can be shortcutted.
7473 if (keys.length === 0) {
7474 if (isFunction(value)) {
7475 var name = value.name ? ': ' + value.name : '';
7476 return ctx.stylize('[Function' + name + ']', 'special');
7477 }
7478 if (isRegExp(value)) {
7479 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7480 }
7481 if (isDate(value)) {
7482 return ctx.stylize(Date.prototype.toString.call(value), 'date');
7483 }
7484 if (isError(value)) {
7485 return formatError(value);
7486 }
7487 }
7488
7489 var base = '', array = false, braces = ['{', '}'];
7490
7491 // Make Array say that they are Array
7492 if (isArray(value)) {
7493 array = true;
7494 braces = ['[', ']'];
7495 }
7496
7497 // Make functions say that they are functions
7498 if (isFunction(value)) {
7499 var n = value.name ? ': ' + value.name : '';
7500 base = ' [Function' + n + ']';
7501 }
7502
7503 // Make RegExps say that they are RegExps
7504 if (isRegExp(value)) {
7505 base = ' ' + RegExp.prototype.toString.call(value);
7506 }
7507
7508 // Make dates with properties first say the date
7509 if (isDate(value)) {
7510 base = ' ' + Date.prototype.toUTCString.call(value);
7511 }
7512
7513 // Make error with message first say the error
7514 if (isError(value)) {
7515 base = ' ' + formatError(value);
7516 }
7517
7518 if (keys.length === 0 && (!array || value.length == 0)) {
7519 return braces[0] + base + braces[1];
7520 }
7521
7522 if (recurseTimes < 0) {
7523 if (isRegExp(value)) {
7524 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7525 } else {
7526 return ctx.stylize('[Object]', 'special');
7527 }
7528 }
7529
7530 ctx.seen.push(value);
7531
7532 var output;
7533 if (array) {
7534 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
7535 } else {
7536 output = keys.map(function(key) {
7537 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
7538 });
7539 }
7540
7541 ctx.seen.pop();
7542
7543 return reduceToSingleString(output, base, braces);
7544 }
7545
7546
7547 function formatPrimitive(ctx, value) {
7548 if (isUndefined(value))
7549 return ctx.stylize('undefined', 'undefined');
7550 if (isString(value)) {
7551 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
7552 .replace(/'/g, "\\'")
7553 .replace(/\\"/g, '"') + '\'';
7554 return ctx.stylize(simple, 'string');
7555 }
7556 if (isNumber(value))
7557 return ctx.stylize('' + value, 'number');
7558 if (isBoolean(value))
7559 return ctx.stylize('' + value, 'boolean');
7560 // For some reason typeof null is "object", so special case here.
7561 if (isNull(value))
7562 return ctx.stylize('null', 'null');
7563 }
7564
7565
7566 function formatError(value) {
7567 return '[' + Error.prototype.toString.call(value) + ']';
7568 }
7569
7570
7571 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
7572 var output = [];
7573 for (var i = 0, l = value.length; i < l; ++i) {
7574 if (hasOwnProperty(value, String(i))) {
7575 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7576 String(i), true));
7577 } else {
7578 output.push('');
7579 }
7580 }
7581 keys.forEach(function(key) {
7582 if (!key.match(/^\d+$/)) {
7583 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7584 key, true));
7585 }
7586 });
7587 return output;
7588 }
7589
7590
7591 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
7592 var name, str, desc;
7593 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
7594 if (desc.get) {
7595 if (desc.set) {
7596 str = ctx.stylize('[Getter/Setter]', 'special');
7597 } else {
7598 str = ctx.stylize('[Getter]', 'special');
7599 }
7600 } else {
7601 if (desc.set) {
7602 str = ctx.stylize('[Setter]', 'special');
7603 }
7604 }
7605 if (!hasOwnProperty(visibleKeys, key)) {
7606 name = '[' + key + ']';
7607 }
7608 if (!str) {
7609 if (ctx.seen.indexOf(desc.value) < 0) {
7610 if (isNull(recurseTimes)) {
7611 str = formatValue(ctx, desc.value, null);
7612 } else {
7613 str = formatValue(ctx, desc.value, recurseTimes - 1);
7614 }
7615 if (str.indexOf('\n') > -1) {
7616 if (array) {
7617 str = str.split('\n').map(function(line) {
7618 return ' ' + line;
7619 }).join('\n').substr(2);
7620 } else {
7621 str = '\n' + str.split('\n').map(function(line) {
7622 return ' ' + line;
7623 }).join('\n');
7624 }
7625 }
7626 } else {
7627 str = ctx.stylize('[Circular]', 'special');
7628 }
7629 }
7630 if (isUndefined(name)) {
7631 if (array && key.match(/^\d+$/)) {
7632 return str;
7633 }
7634 name = JSON.stringify('' + key);
7635 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
7636 name = name.substr(1, name.length - 2);
7637 name = ctx.stylize(name, 'name');
7638 } else {
7639 name = name.replace(/'/g, "\\'")
7640 .replace(/\\"/g, '"')
7641 .replace(/(^"|"$)/g, "'");
7642 name = ctx.stylize(name, 'string');
7643 }
7644 }
7645
7646 return name + ': ' + str;
7647 }
7648
7649
7650 function reduceToSingleString(output, base, braces) {
7651 var numLinesEst = 0;
7652 var length = output.reduce(function(prev, cur) {
7653 numLinesEst++;
7654 if (cur.indexOf('\n') >= 0) numLinesEst++;
7655 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
7656 }, 0);
7657
7658 if (length > 60) {
7659 return braces[0] +
7660 (base === '' ? '' : base + '\n ') +
7661 ' ' +
7662 output.join(',\n ') +
7663 ' ' +
7664 braces[1];
7665 }
7666
7667 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
7668 }
7669
7670
7671 // NOTE: These type checking functions intentionally don't use `instanceof`
7672 // because it is fragile and can be easily faked with `Object.create()`.
7673 function isArray(ar) {
7674 return Array.isArray(ar);
7675 }
7676 exports.isArray = isArray;
7677
7678 function isBoolean(arg) {
7679 return typeof arg === 'boolean';
7680 }
7681 exports.isBoolean = isBoolean;
7682
7683 function isNull(arg) {
7684 return arg === null;
7685 }
7686 exports.isNull = isNull;
7687
7688 function isNullOrUndefined(arg) {
7689 return arg == null;
7690 }
7691 exports.isNullOrUndefined = isNullOrUndefined;
7692
7693 function isNumber(arg) {
7694 return typeof arg === 'number';
7695 }
7696 exports.isNumber = isNumber;
7697
7698 function isString(arg) {
7699 return typeof arg === 'string';
7700 }
7701 exports.isString = isString;
7702
7703 function isSymbol(arg) {
7704 return typeof arg === 'symbol';
7705 }
7706 exports.isSymbol = isSymbol;
7707
7708 function isUndefined(arg) {
7709 return arg === void 0;
7710 }
7711 exports.isUndefined = isUndefined;
7712
7713 function isRegExp(re) {
7714 return isObject(re) && objectToString(re) === '[object RegExp]';
7715 }
7716 exports.isRegExp = isRegExp;
7717
7718 function isObject(arg) {
7719 return typeof arg === 'object' && arg !== null;
7720 }
7721 exports.isObject = isObject;
7722
7723 function isDate(d) {
7724 return isObject(d) && objectToString(d) === '[object Date]';
7725 }
7726 exports.isDate = isDate;
7727
7728 function isError(e) {
7729 return isObject(e) &&
7730 (objectToString(e) === '[object Error]' || e instanceof Error);
7731 }
7732 exports.isError = isError;
7733
7734 function isFunction(arg) {
7735 return typeof arg === 'function';
7736 }
7737 exports.isFunction = isFunction;
7738
7739 function isPrimitive(arg) {
7740 return arg === null ||
7741 typeof arg === 'boolean' ||
7742 typeof arg === 'number' ||
7743 typeof arg === 'string' ||
7744 typeof arg === 'symbol' || // ES6 symbol
7745 typeof arg === 'undefined';
7746 }
7747 exports.isPrimitive = isPrimitive;
7748
7749 exports.isBuffer = __webpack_require__(47);
7750
7751 function objectToString(o) {
7752 return Object.prototype.toString.call(o);
7753 }
7754
7755
7756 function pad(n) {
7757 return n < 10 ? '0' + n.toString(10) : n.toString(10);
7758 }
7759
7760
7761 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
7762 'Oct', 'Nov', 'Dec'];
7763
7764 // 26 Feb 16:19:34
7765 function timestamp() {
7766 var d = new Date();
7767 var time = [pad(d.getHours()),
7768 pad(d.getMinutes()),
7769 pad(d.getSeconds())].join(':');
7770 return [d.getDate(), months[d.getMonth()], time].join(' ');
7771 }
7772
7773
7774 // log is just a thin wrapper to console.log that prepends a timestamp
7775 exports.log = function() {
7776 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
7777 };
7778
7779
7780 /**
7781 * Inherit the prototype methods from one constructor into another.
7782 *
7783 * The Function.prototype.inherits from lang.js rewritten as a standalone
7784 * function (not on Function.prototype). NOTE: If this file is to be loaded
7785 * during bootstrapping this function needs to be rewritten using some native
7786 * functions as prototype setup using normal JavaScript does not work as
7787 * expected during bootstrapping (see mirror.js in r114903).
7788 *
7789 * @param {function} ctor Constructor function which needs to inherit the
7790 * prototype.
7791 * @param {function} superCtor Constructor function to inherit prototype from.
7792 */
7793 exports.inherits = __webpack_require__(48);
7794
7795 exports._extend = function(origin, add) {
7796 // Don't do anything if add isn't an object
7797 if (!add || !isObject(add)) return origin;
7798
7799 var keys = Object.keys(add);
7800 var i = keys.length;
7801 while (i--) {
7802 origin[keys[i]] = add[keys[i]];
7803 }
7804 return origin;
7805 };
7806
7807 function hasOwnProperty(obj, prop) {
7808 return Object.prototype.hasOwnProperty.call(obj, prop);
7809 }
7810
7811 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
7812
7813/***/ }),
7814/* 47 */
7815/***/ (function(module, exports) {
7816
7817 module.exports = function isBuffer(arg) {
7818 return arg && typeof arg === 'object'
7819 && typeof arg.copy === 'function'
7820 && typeof arg.fill === 'function'
7821 && typeof arg.readUInt8 === 'function';
7822 }
7823
7824/***/ }),
7825/* 48 */
7826/***/ (function(module, exports) {
7827
7828 if (typeof Object.create === 'function') {
7829 // implementation from standard node.js 'util' module
7830 module.exports = function inherits(ctor, superCtor) {
7831 ctor.super_ = superCtor
7832 ctor.prototype = Object.create(superCtor.prototype, {
7833 constructor: {
7834 value: ctor,
7835 enumerable: false,
7836 writable: true,
7837 configurable: true
7838 }
7839 });
7840 };
7841 } else {
7842 // old school shim for old browsers
7843 module.exports = function inherits(ctor, superCtor) {
7844 ctor.super_ = superCtor
7845 var TempCtor = function () {}
7846 TempCtor.prototype = superCtor.prototype
7847 ctor.prototype = new TempCtor()
7848 ctor.prototype.constructor = ctor
7849 }
7850 }
7851
7852
7853/***/ }),
7854/* 49 */
7855/***/ (function(module, exports, __webpack_require__) {
7856
7857 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
7858 var AcceptorStateMachine = __webpack_require__(50);
7859 var inherit = AWS.util.inherit;
7860 var domain = AWS.util.domain;
7861 var jmespath = __webpack_require__(51);
7862
7863 /**
7864 * @api private
7865 */
7866 var hardErrorStates = {success: 1, error: 1, complete: 1};
7867
7868 function isTerminalState(machine) {
7869 return Object.prototype.hasOwnProperty.call(hardErrorStates, machine._asm.currentState);
7870 }
7871
7872 var fsm = new AcceptorStateMachine();
7873 fsm.setupStates = function() {
7874 var transition = function(_, done) {
7875 var self = this;
7876 self._haltHandlersOnError = false;
7877
7878 self.emit(self._asm.currentState, function(err) {
7879 if (err) {
7880 if (isTerminalState(self)) {
7881 if (domain && self.domain instanceof domain.Domain) {
7882 err.domainEmitter = self;
7883 err.domain = self.domain;
7884 err.domainThrown = false;
7885 self.domain.emit('error', err);
7886 } else {
7887 throw err;
7888 }
7889 } else {
7890 self.response.error = err;
7891 done(err);
7892 }
7893 } else {
7894 done(self.response.error);
7895 }
7896 });
7897
7898 };
7899
7900 this.addState('validate', 'build', 'error', transition);
7901 this.addState('build', 'afterBuild', 'restart', transition);
7902 this.addState('afterBuild', 'sign', 'restart', transition);
7903 this.addState('sign', 'send', 'retry', transition);
7904 this.addState('retry', 'afterRetry', 'afterRetry', transition);
7905 this.addState('afterRetry', 'sign', 'error', transition);
7906 this.addState('send', 'validateResponse', 'retry', transition);
7907 this.addState('validateResponse', 'extractData', 'extractError', transition);
7908 this.addState('extractError', 'extractData', 'retry', transition);
7909 this.addState('extractData', 'success', 'retry', transition);
7910 this.addState('restart', 'build', 'error', transition);
7911 this.addState('success', 'complete', 'complete', transition);
7912 this.addState('error', 'complete', 'complete', transition);
7913 this.addState('complete', null, null, transition);
7914 };
7915 fsm.setupStates();
7916
7917 /**
7918 * ## Asynchronous Requests
7919 *
7920 * All requests made through the SDK are asynchronous and use a
7921 * callback interface. Each service method that kicks off a request
7922 * returns an `AWS.Request` object that you can use to register
7923 * callbacks.
7924 *
7925 * For example, the following service method returns the request
7926 * object as "request", which can be used to register callbacks:
7927 *
7928 * ```javascript
7929 * // request is an AWS.Request object
7930 * var request = ec2.describeInstances();
7931 *
7932 * // register callbacks on request to retrieve response data
7933 * request.on('success', function(response) {
7934 * console.log(response.data);
7935 * });
7936 * ```
7937 *
7938 * When a request is ready to be sent, the {send} method should
7939 * be called:
7940 *
7941 * ```javascript
7942 * request.send();
7943 * ```
7944 *
7945 * Since registered callbacks may or may not be idempotent, requests should only
7946 * be sent once. To perform the same operation multiple times, you will need to
7947 * create multiple request objects, each with its own registered callbacks.
7948 *
7949 * ## Removing Default Listeners for Events
7950 *
7951 * Request objects are built with default listeners for the various events,
7952 * depending on the service type. In some cases, you may want to remove
7953 * some built-in listeners to customize behaviour. Doing this requires
7954 * access to the built-in listener functions, which are exposed through
7955 * the {AWS.EventListeners.Core} namespace. For instance, you may
7956 * want to customize the HTTP handler used when sending a request. In this
7957 * case, you can remove the built-in listener associated with the 'send'
7958 * event, the {AWS.EventListeners.Core.SEND} listener and add your own.
7959 *
7960 * ## Multiple Callbacks and Chaining
7961 *
7962 * You can register multiple callbacks on any request object. The
7963 * callbacks can be registered for different events, or all for the
7964 * same event. In addition, you can chain callback registration, for
7965 * example:
7966 *
7967 * ```javascript
7968 * request.
7969 * on('success', function(response) {
7970 * console.log("Success!");
7971 * }).
7972 * on('error', function(response) {
7973 * console.log("Error!");
7974 * }).
7975 * on('complete', function(response) {
7976 * console.log("Always!");
7977 * }).
7978 * send();
7979 * ```
7980 *
7981 * The above example will print either "Success! Always!", or "Error! Always!",
7982 * depending on whether the request succeeded or not.
7983 *
7984 * @!attribute httpRequest
7985 * @readonly
7986 * @!group HTTP Properties
7987 * @return [AWS.HttpRequest] the raw HTTP request object
7988 * containing request headers and body information
7989 * sent by the service.
7990 *
7991 * @!attribute startTime
7992 * @readonly
7993 * @!group Operation Properties
7994 * @return [Date] the time that the request started
7995 *
7996 * @!group Request Building Events
7997 *
7998 * @!event validate(request)
7999 * Triggered when a request is being validated. Listeners
8000 * should throw an error if the request should not be sent.
8001 * @param request [Request] the request object being sent
8002 * @see AWS.EventListeners.Core.VALIDATE_CREDENTIALS
8003 * @see AWS.EventListeners.Core.VALIDATE_REGION
8004 * @example Ensuring that a certain parameter is set before sending a request
8005 * var req = s3.putObject(params);
8006 * req.on('validate', function() {
8007 * if (!req.params.Body.match(/^Hello\s/)) {
8008 * throw new Error('Body must start with "Hello "');
8009 * }
8010 * });
8011 * req.send(function(err, data) { ... });
8012 *
8013 * @!event build(request)
8014 * Triggered when the request payload is being built. Listeners
8015 * should fill the necessary information to send the request
8016 * over HTTP.
8017 * @param (see AWS.Request~validate)
8018 * @example Add a custom HTTP header to a request
8019 * var req = s3.putObject(params);
8020 * req.on('build', function() {
8021 * req.httpRequest.headers['Custom-Header'] = 'value';
8022 * });
8023 * req.send(function(err, data) { ... });
8024 *
8025 * @!event sign(request)
8026 * Triggered when the request is being signed. Listeners should
8027 * add the correct authentication headers and/or adjust the body,
8028 * depending on the authentication mechanism being used.
8029 * @param (see AWS.Request~validate)
8030 *
8031 * @!group Request Sending Events
8032 *
8033 * @!event send(response)
8034 * Triggered when the request is ready to be sent. Listeners
8035 * should call the underlying transport layer to initiate
8036 * the sending of the request.
8037 * @param response [Response] the response object
8038 * @context [Request] the request object that was sent
8039 * @see AWS.EventListeners.Core.SEND
8040 *
8041 * @!event retry(response)
8042 * Triggered when a request failed and might need to be retried or redirected.
8043 * If the response is retryable, the listener should set the
8044 * `response.error.retryable` property to `true`, and optionally set
8045 * `response.error.retryDelay` to the millisecond delay for the next attempt.
8046 * In the case of a redirect, `response.error.redirect` should be set to
8047 * `true` with `retryDelay` set to an optional delay on the next request.
8048 *
8049 * If a listener decides that a request should not be retried,
8050 * it should set both `retryable` and `redirect` to false.
8051 *
8052 * Note that a retryable error will be retried at most
8053 * {AWS.Config.maxRetries} times (based on the service object's config).
8054 * Similarly, a request that is redirected will only redirect at most
8055 * {AWS.Config.maxRedirects} times.
8056 *
8057 * @param (see AWS.Request~send)
8058 * @context (see AWS.Request~send)
8059 * @example Adding a custom retry for a 404 response
8060 * request.on('retry', function(response) {
8061 * // this resource is not yet available, wait 10 seconds to get it again
8062 * if (response.httpResponse.statusCode === 404 && response.error) {
8063 * response.error.retryable = true; // retry this error
8064 * response.error.retryDelay = 10000; // wait 10 seconds
8065 * }
8066 * });
8067 *
8068 * @!group Data Parsing Events
8069 *
8070 * @!event extractError(response)
8071 * Triggered on all non-2xx requests so that listeners can extract
8072 * error details from the response body. Listeners to this event
8073 * should set the `response.error` property.
8074 * @param (see AWS.Request~send)
8075 * @context (see AWS.Request~send)
8076 *
8077 * @!event extractData(response)
8078 * Triggered in successful requests to allow listeners to
8079 * de-serialize the response body into `response.data`.
8080 * @param (see AWS.Request~send)
8081 * @context (see AWS.Request~send)
8082 *
8083 * @!group Completion Events
8084 *
8085 * @!event success(response)
8086 * Triggered when the request completed successfully.
8087 * `response.data` will contain the response data and
8088 * `response.error` will be null.
8089 * @param (see AWS.Request~send)
8090 * @context (see AWS.Request~send)
8091 *
8092 * @!event error(error, response)
8093 * Triggered when an error occurs at any point during the
8094 * request. `response.error` will contain details about the error
8095 * that occurred. `response.data` will be null.
8096 * @param error [Error] the error object containing details about
8097 * the error that occurred.
8098 * @param (see AWS.Request~send)
8099 * @context (see AWS.Request~send)
8100 *
8101 * @!event complete(response)
8102 * Triggered whenever a request cycle completes. `response.error`
8103 * should be checked, since the request may have failed.
8104 * @param (see AWS.Request~send)
8105 * @context (see AWS.Request~send)
8106 *
8107 * @!group HTTP Events
8108 *
8109 * @!event httpHeaders(statusCode, headers, response, statusMessage)
8110 * Triggered when headers are sent by the remote server
8111 * @param statusCode [Integer] the HTTP response code
8112 * @param headers [map<String,String>] the response headers
8113 * @param (see AWS.Request~send)
8114 * @param statusMessage [String] A status message corresponding to the HTTP
8115 * response code
8116 * @context (see AWS.Request~send)
8117 *
8118 * @!event httpData(chunk, response)
8119 * Triggered when data is sent by the remote server
8120 * @param chunk [Buffer] the buffer data containing the next data chunk
8121 * from the server
8122 * @param (see AWS.Request~send)
8123 * @context (see AWS.Request~send)
8124 * @see AWS.EventListeners.Core.HTTP_DATA
8125 *
8126 * @!event httpUploadProgress(progress, response)
8127 * Triggered when the HTTP request has uploaded more data
8128 * @param progress [map] An object containing the `loaded` and `total` bytes
8129 * of the request.
8130 * @param (see AWS.Request~send)
8131 * @context (see AWS.Request~send)
8132 * @note This event will not be emitted in Node.js 0.8.x.
8133 *
8134 * @!event httpDownloadProgress(progress, response)
8135 * Triggered when the HTTP request has downloaded more data
8136 * @param progress [map] An object containing the `loaded` and `total` bytes
8137 * of the request.
8138 * @param (see AWS.Request~send)
8139 * @context (see AWS.Request~send)
8140 * @note This event will not be emitted in Node.js 0.8.x.
8141 *
8142 * @!event httpError(error, response)
8143 * Triggered when the HTTP request failed
8144 * @param error [Error] the error object that was thrown
8145 * @param (see AWS.Request~send)
8146 * @context (see AWS.Request~send)
8147 *
8148 * @!event httpDone(response)
8149 * Triggered when the server is finished sending data
8150 * @param (see AWS.Request~send)
8151 * @context (see AWS.Request~send)
8152 *
8153 * @see AWS.Response
8154 */
8155 AWS.Request = inherit({
8156
8157 /**
8158 * Creates a request for an operation on a given service with
8159 * a set of input parameters.
8160 *
8161 * @param service [AWS.Service] the service to perform the operation on
8162 * @param operation [String] the operation to perform on the service
8163 * @param params [Object] parameters to send to the operation.
8164 * See the operation's documentation for the format of the
8165 * parameters.
8166 */
8167 constructor: function Request(service, operation, params) {
8168 var endpoint = service.endpoint;
8169 var region = service.config.region;
8170 var customUserAgent = service.config.customUserAgent;
8171
8172 // global endpoints sign as us-east-1
8173 if (service.isGlobalEndpoint) region = 'us-east-1';
8174
8175 this.domain = domain && domain.active;
8176 this.service = service;
8177 this.operation = operation;
8178 this.params = params || {};
8179 this.httpRequest = new AWS.HttpRequest(endpoint, region);
8180 this.httpRequest.appendToUserAgent(customUserAgent);
8181 this.startTime = service.getSkewCorrectedDate();
8182
8183 this.response = new AWS.Response(this);
8184 this._asm = new AcceptorStateMachine(fsm.states, 'validate');
8185 this._haltHandlersOnError = false;
8186
8187 AWS.SequentialExecutor.call(this);
8188 this.emit = this.emitEvent;
8189 },
8190
8191 /**
8192 * @!group Sending a Request
8193 */
8194
8195 /**
8196 * @overload send(callback = null)
8197 * Sends the request object.
8198 *
8199 * @callback callback function(err, data)
8200 * If a callback is supplied, it is called when a response is returned
8201 * from the service.
8202 * @context [AWS.Request] the request object being sent.
8203 * @param err [Error] the error object returned from the request.
8204 * Set to `null` if the request is successful.
8205 * @param data [Object] the de-serialized data returned from
8206 * the request. Set to `null` if a request error occurs.
8207 * @example Sending a request with a callback
8208 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8209 * request.send(function(err, data) { console.log(err, data); });
8210 * @example Sending a request with no callback (using event handlers)
8211 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8212 * request.on('complete', function(response) { ... }); // register a callback
8213 * request.send();
8214 */
8215 send: function send(callback) {
8216 if (callback) {
8217 // append to user agent
8218 this.httpRequest.appendToUserAgent('callback');
8219 this.on('complete', function (resp) {
8220 callback.call(resp, resp.error, resp.data);
8221 });
8222 }
8223 this.runTo();
8224
8225 return this.response;
8226 },
8227
8228 /**
8229 * @!method promise()
8230 * Sends the request and returns a 'thenable' promise.
8231 *
8232 * Two callbacks can be provided to the `then` method on the returned promise.
8233 * The first callback will be called if the promise is fulfilled, and the second
8234 * callback will be called if the promise is rejected.
8235 * @callback fulfilledCallback function(data)
8236 * Called if the promise is fulfilled.
8237 * @param data [Object] the de-serialized data returned from the request.
8238 * @callback rejectedCallback function(error)
8239 * Called if the promise is rejected.
8240 * @param error [Error] the error object returned from the request.
8241 * @return [Promise] A promise that represents the state of the request.
8242 * @example Sending a request using promises.
8243 * var request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8244 * var result = request.promise();
8245 * result.then(function(data) { ... }, function(error) { ... });
8246 */
8247
8248 /**
8249 * @api private
8250 */
8251 build: function build(callback) {
8252 return this.runTo('send', callback);
8253 },
8254
8255 /**
8256 * @api private
8257 */
8258 runTo: function runTo(state, done) {
8259 this._asm.runTo(state, done, this);
8260 return this;
8261 },
8262
8263 /**
8264 * Aborts a request, emitting the error and complete events.
8265 *
8266 * @!macro nobrowser
8267 * @example Aborting a request after sending
8268 * var params = {
8269 * Bucket: 'bucket', Key: 'key',
8270 * Body: new Buffer(1024 * 1024 * 5) // 5MB payload
8271 * };
8272 * var request = s3.putObject(params);
8273 * request.send(function (err, data) {
8274 * if (err) console.log("Error:", err.code, err.message);
8275 * else console.log(data);
8276 * });
8277 *
8278 * // abort request in 1 second
8279 * setTimeout(request.abort.bind(request), 1000);
8280 *
8281 * // prints "Error: RequestAbortedError Request aborted by user"
8282 * @return [AWS.Request] the same request object, for chaining.
8283 * @since v1.4.0
8284 */
8285 abort: function abort() {
8286 this.removeAllListeners('validateResponse');
8287 this.removeAllListeners('extractError');
8288 this.on('validateResponse', function addAbortedError(resp) {
8289 resp.error = AWS.util.error(new Error('Request aborted by user'), {
8290 code: 'RequestAbortedError', retryable: false
8291 });
8292 });
8293
8294 if (this.httpRequest.stream && !this.httpRequest.stream.didCallback) { // abort HTTP stream
8295 this.httpRequest.stream.abort();
8296 if (this.httpRequest._abortCallback) {
8297 this.httpRequest._abortCallback();
8298 } else {
8299 this.removeAllListeners('send'); // haven't sent yet, so let's not
8300 }
8301 }
8302
8303 return this;
8304 },
8305
8306 /**
8307 * Iterates over each page of results given a pageable request, calling
8308 * the provided callback with each page of data. After all pages have been
8309 * retrieved, the callback is called with `null` data.
8310 *
8311 * @note This operation can generate multiple requests to a service.
8312 * @example Iterating over multiple pages of objects in an S3 bucket
8313 * var pages = 1;
8314 * s3.listObjects().eachPage(function(err, data) {
8315 * if (err) return;
8316 * console.log("Page", pages++);
8317 * console.log(data);
8318 * });
8319 * @example Iterating over multiple pages with an asynchronous callback
8320 * s3.listObjects(params).eachPage(function(err, data, done) {
8321 * doSomethingAsyncAndOrExpensive(function() {
8322 * // The next page of results isn't fetched until done is called
8323 * done();
8324 * });
8325 * });
8326 * @callback callback function(err, data, [doneCallback])
8327 * Called with each page of resulting data from the request. If the
8328 * optional `doneCallback` is provided in the function, it must be called
8329 * when the callback is complete.
8330 *
8331 * @param err [Error] an error object, if an error occurred.
8332 * @param data [Object] a single page of response data. If there is no
8333 * more data, this object will be `null`.
8334 * @param doneCallback [Function] an optional done callback. If this
8335 * argument is defined in the function declaration, it should be called
8336 * when the next page is ready to be retrieved. This is useful for
8337 * controlling serial pagination across asynchronous operations.
8338 * @return [Boolean] if the callback returns `false`, pagination will
8339 * stop.
8340 *
8341 * @see AWS.Request.eachItem
8342 * @see AWS.Response.nextPage
8343 * @since v1.4.0
8344 */
8345 eachPage: function eachPage(callback) {
8346 // Make all callbacks async-ish
8347 callback = AWS.util.fn.makeAsync(callback, 3);
8348
8349 function wrappedCallback(response) {
8350 callback.call(response, response.error, response.data, function (result) {
8351 if (result === false) return;
8352
8353 if (response.hasNextPage()) {
8354 response.nextPage().on('complete', wrappedCallback).send();
8355 } else {
8356 callback.call(response, null, null, AWS.util.fn.noop);
8357 }
8358 });
8359 }
8360
8361 this.on('complete', wrappedCallback).send();
8362 },
8363
8364 /**
8365 * Enumerates over individual items of a request, paging the responses if
8366 * necessary.
8367 *
8368 * @api experimental
8369 * @since v1.4.0
8370 */
8371 eachItem: function eachItem(callback) {
8372 var self = this;
8373 function wrappedCallback(err, data) {
8374 if (err) return callback(err, null);
8375 if (data === null) return callback(null, null);
8376
8377 var config = self.service.paginationConfig(self.operation);
8378 var resultKey = config.resultKey;
8379 if (Array.isArray(resultKey)) resultKey = resultKey[0];
8380 var items = jmespath.search(data, resultKey);
8381 var continueIteration = true;
8382 AWS.util.arrayEach(items, function(item) {
8383 continueIteration = callback(null, item);
8384 if (continueIteration === false) {
8385 return AWS.util.abort;
8386 }
8387 });
8388 return continueIteration;
8389 }
8390
8391 this.eachPage(wrappedCallback);
8392 },
8393
8394 /**
8395 * @return [Boolean] whether the operation can return multiple pages of
8396 * response data.
8397 * @see AWS.Response.eachPage
8398 * @since v1.4.0
8399 */
8400 isPageable: function isPageable() {
8401 return this.service.paginationConfig(this.operation) ? true : false;
8402 },
8403
8404 /**
8405 * Sends the request and converts the request object into a readable stream
8406 * that can be read from or piped into a writable stream.
8407 *
8408 * @note The data read from a readable stream contains only
8409 * the raw HTTP body contents.
8410 * @example Manually reading from a stream
8411 * request.createReadStream().on('data', function(data) {
8412 * console.log("Got data:", data.toString());
8413 * });
8414 * @example Piping a request body into a file
8415 * var out = fs.createWriteStream('/path/to/outfile.jpg');
8416 * s3.service.getObject(params).createReadStream().pipe(out);
8417 * @return [Stream] the readable stream object that can be piped
8418 * or read from (by registering 'data' event listeners).
8419 * @!macro nobrowser
8420 */
8421 createReadStream: function createReadStream() {
8422 var streams = AWS.util.stream;
8423 var req = this;
8424 var stream = null;
8425
8426 if (AWS.HttpClient.streamsApiVersion === 2) {
8427 stream = new streams.PassThrough();
8428 process.nextTick(function() { req.send(); });
8429 } else {
8430 stream = new streams.Stream();
8431 stream.readable = true;
8432
8433 stream.sent = false;
8434 stream.on('newListener', function(event) {
8435 if (!stream.sent && event === 'data') {
8436 stream.sent = true;
8437 process.nextTick(function() { req.send(); });
8438 }
8439 });
8440 }
8441
8442 this.on('error', function(err) {
8443 stream.emit('error', err);
8444 });
8445
8446 this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
8447 if (statusCode < 300) {
8448 req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
8449 req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
8450 req.on('httpError', function streamHttpError(error) {
8451 resp.error = error;
8452 resp.error.retryable = false;
8453 });
8454
8455 var shouldCheckContentLength = false;
8456 var expectedLen;
8457 if (req.httpRequest.method !== 'HEAD') {
8458 expectedLen = parseInt(headers['content-length'], 10);
8459 }
8460 if (expectedLen !== undefined && !isNaN(expectedLen) && expectedLen >= 0) {
8461 shouldCheckContentLength = true;
8462 var receivedLen = 0;
8463 }
8464
8465 var checkContentLengthAndEmit = function checkContentLengthAndEmit() {
8466 if (shouldCheckContentLength && receivedLen !== expectedLen) {
8467 stream.emit('error', AWS.util.error(
8468 new Error('Stream content length mismatch. Received ' +
8469 receivedLen + ' of ' + expectedLen + ' bytes.'),
8470 { code: 'StreamContentLengthMismatch' }
8471 ));
8472 } else if (AWS.HttpClient.streamsApiVersion === 2) {
8473 stream.end();
8474 } else {
8475 stream.emit('end');
8476 }
8477 };
8478
8479 var httpStream = resp.httpResponse.createUnbufferedStream();
8480
8481 if (AWS.HttpClient.streamsApiVersion === 2) {
8482 if (shouldCheckContentLength) {
8483 var lengthAccumulator = new streams.PassThrough();
8484 lengthAccumulator._write = function(chunk) {
8485 if (chunk && chunk.length) {
8486 receivedLen += chunk.length;
8487 }
8488 return streams.PassThrough.prototype._write.apply(this, arguments);
8489 };
8490
8491 lengthAccumulator.on('end', checkContentLengthAndEmit);
8492 stream.on('error', function(err) {
8493 shouldCheckContentLength = false;
8494 httpStream.unpipe(lengthAccumulator);
8495 lengthAccumulator.emit('end');
8496 lengthAccumulator.end();
8497 });
8498 httpStream.pipe(lengthAccumulator).pipe(stream, { end: false });
8499 } else {
8500 httpStream.pipe(stream);
8501 }
8502 } else {
8503
8504 if (shouldCheckContentLength) {
8505 httpStream.on('data', function(arg) {
8506 if (arg && arg.length) {
8507 receivedLen += arg.length;
8508 }
8509 });
8510 }
8511
8512 httpStream.on('data', function(arg) {
8513 stream.emit('data', arg);
8514 });
8515 httpStream.on('end', checkContentLengthAndEmit);
8516 }
8517
8518 httpStream.on('error', function(err) {
8519 shouldCheckContentLength = false;
8520 stream.emit('error', err);
8521 });
8522 }
8523 });
8524
8525 return stream;
8526 },
8527
8528 /**
8529 * @param [Array,Response] args This should be the response object,
8530 * or an array of args to send to the event.
8531 * @api private
8532 */
8533 emitEvent: function emit(eventName, args, done) {
8534 if (typeof args === 'function') { done = args; args = null; }
8535 if (!done) done = function() { };
8536 if (!args) args = this.eventParameters(eventName, this.response);
8537
8538 var origEmit = AWS.SequentialExecutor.prototype.emit;
8539 origEmit.call(this, eventName, args, function (err) {
8540 if (err) this.response.error = err;
8541 done.call(this, err);
8542 });
8543 },
8544
8545 /**
8546 * @api private
8547 */
8548 eventParameters: function eventParameters(eventName) {
8549 switch (eventName) {
8550 case 'restart':
8551 case 'validate':
8552 case 'sign':
8553 case 'build':
8554 case 'afterValidate':
8555 case 'afterBuild':
8556 return [this];
8557 case 'error':
8558 return [this.response.error, this.response];
8559 default:
8560 return [this.response];
8561 }
8562 },
8563
8564 /**
8565 * @api private
8566 */
8567 presign: function presign(expires, callback) {
8568 if (!callback && typeof expires === 'function') {
8569 callback = expires;
8570 expires = null;
8571 }
8572 return new AWS.Signers.Presign().sign(this.toGet(), expires, callback);
8573 },
8574
8575 /**
8576 * @api private
8577 */
8578 isPresigned: function isPresigned() {
8579 return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires');
8580 },
8581
8582 /**
8583 * @api private
8584 */
8585 toUnauthenticated: function toUnauthenticated() {
8586 this._unAuthenticated = true;
8587 this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS);
8588 this.removeListener('sign', AWS.EventListeners.Core.SIGN);
8589 return this;
8590 },
8591
8592 /**
8593 * @api private
8594 */
8595 toGet: function toGet() {
8596 if (this.service.api.protocol === 'query' ||
8597 this.service.api.protocol === 'ec2') {
8598 this.removeListener('build', this.buildAsGet);
8599 this.addListener('build', this.buildAsGet);
8600 }
8601 return this;
8602 },
8603
8604 /**
8605 * @api private
8606 */
8607 buildAsGet: function buildAsGet(request) {
8608 request.httpRequest.method = 'GET';
8609 request.httpRequest.path = request.service.endpoint.path +
8610 '?' + request.httpRequest.body;
8611 request.httpRequest.body = '';
8612
8613 // don't need these headers on a GET request
8614 delete request.httpRequest.headers['Content-Length'];
8615 delete request.httpRequest.headers['Content-Type'];
8616 },
8617
8618 /**
8619 * @api private
8620 */
8621 haltHandlersOnError: function haltHandlersOnError() {
8622 this._haltHandlersOnError = true;
8623 }
8624 });
8625
8626 /**
8627 * @api private
8628 */
8629 AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
8630 this.prototype.promise = function promise() {
8631 var self = this;
8632 // append to user agent
8633 this.httpRequest.appendToUserAgent('promise');
8634 return new PromiseDependency(function(resolve, reject) {
8635 self.on('complete', function(resp) {
8636 if (resp.error) {
8637 reject(resp.error);
8638 } else {
8639 // define $response property so that it is not enumberable
8640 // this prevents circular reference errors when stringifying the JSON object
8641 resolve(Object.defineProperty(
8642 resp.data || {},
8643 '$response',
8644 {value: resp}
8645 ));
8646 }
8647 });
8648 self.runTo();
8649 });
8650 };
8651 };
8652
8653 /**
8654 * @api private
8655 */
8656 AWS.Request.deletePromisesFromClass = function deletePromisesFromClass() {
8657 delete this.prototype.promise;
8658 };
8659
8660 AWS.util.addPromises(AWS.Request);
8661
8662 AWS.util.mixin(AWS.Request, AWS.SequentialExecutor);
8663
8664 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
8665
8666/***/ }),
8667/* 50 */
8668/***/ (function(module, exports) {
8669
8670 function AcceptorStateMachine(states, state) {
8671 this.currentState = state || null;
8672 this.states = states || {};
8673 }
8674
8675 AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) {
8676 if (typeof finalState === 'function') {
8677 inputError = bindObject; bindObject = done;
8678 done = finalState; finalState = null;
8679 }
8680
8681 var self = this;
8682 var state = self.states[self.currentState];
8683 state.fn.call(bindObject || self, inputError, function(err) {
8684 if (err) {
8685 if (state.fail) self.currentState = state.fail;
8686 else return done ? done.call(bindObject, err) : null;
8687 } else {
8688 if (state.accept) self.currentState = state.accept;
8689 else return done ? done.call(bindObject) : null;
8690 }
8691 if (self.currentState === finalState) {
8692 return done ? done.call(bindObject, err) : null;
8693 }
8694
8695 self.runTo(finalState, done, bindObject, err);
8696 });
8697 };
8698
8699 AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) {
8700 if (typeof acceptState === 'function') {
8701 fn = acceptState; acceptState = null; failState = null;
8702 } else if (typeof failState === 'function') {
8703 fn = failState; failState = null;
8704 }
8705
8706 if (!this.currentState) this.currentState = name;
8707 this.states[name] = { accept: acceptState, fail: failState, fn: fn };
8708 return this;
8709 };
8710
8711 /**
8712 * @api private
8713 */
8714 module.exports = AcceptorStateMachine;
8715
8716
8717/***/ }),
8718/* 51 */
8719/***/ (function(module, exports, __webpack_require__) {
8720
8721 (function(exports) {
8722 "use strict";
8723
8724 function isArray(obj) {
8725 if (obj !== null) {
8726 return Object.prototype.toString.call(obj) === "[object Array]";
8727 } else {
8728 return false;
8729 }
8730 }
8731
8732 function isObject(obj) {
8733 if (obj !== null) {
8734 return Object.prototype.toString.call(obj) === "[object Object]";
8735 } else {
8736 return false;
8737 }
8738 }
8739
8740 function strictDeepEqual(first, second) {
8741 // Check the scalar case first.
8742 if (first === second) {
8743 return true;
8744 }
8745
8746 // Check if they are the same type.
8747 var firstType = Object.prototype.toString.call(first);
8748 if (firstType !== Object.prototype.toString.call(second)) {
8749 return false;
8750 }
8751 // We know that first and second have the same type so we can just check the
8752 // first type from now on.
8753 if (isArray(first) === true) {
8754 // Short circuit if they're not the same length;
8755 if (first.length !== second.length) {
8756 return false;
8757 }
8758 for (var i = 0; i < first.length; i++) {
8759 if (strictDeepEqual(first[i], second[i]) === false) {
8760 return false;
8761 }
8762 }
8763 return true;
8764 }
8765 if (isObject(first) === true) {
8766 // An object is equal if it has the same key/value pairs.
8767 var keysSeen = {};
8768 for (var key in first) {
8769 if (hasOwnProperty.call(first, key)) {
8770 if (strictDeepEqual(first[key], second[key]) === false) {
8771 return false;
8772 }
8773 keysSeen[key] = true;
8774 }
8775 }
8776 // Now check that there aren't any keys in second that weren't
8777 // in first.
8778 for (var key2 in second) {
8779 if (hasOwnProperty.call(second, key2)) {
8780 if (keysSeen[key2] !== true) {
8781 return false;
8782 }
8783 }
8784 }
8785 return true;
8786 }
8787 return false;
8788 }
8789
8790 function isFalse(obj) {
8791 // From the spec:
8792 // A false value corresponds to the following values:
8793 // Empty list
8794 // Empty object
8795 // Empty string
8796 // False boolean
8797 // null value
8798
8799 // First check the scalar values.
8800 if (obj === "" || obj === false || obj === null) {
8801 return true;
8802 } else if (isArray(obj) && obj.length === 0) {
8803 // Check for an empty array.
8804 return true;
8805 } else if (isObject(obj)) {
8806 // Check for an empty object.
8807 for (var key in obj) {
8808 // If there are any keys, then
8809 // the object is not empty so the object
8810 // is not false.
8811 if (obj.hasOwnProperty(key)) {
8812 return false;
8813 }
8814 }
8815 return true;
8816 } else {
8817 return false;
8818 }
8819 }
8820
8821 function objValues(obj) {
8822 var keys = Object.keys(obj);
8823 var values = [];
8824 for (var i = 0; i < keys.length; i++) {
8825 values.push(obj[keys[i]]);
8826 }
8827 return values;
8828 }
8829
8830 function merge(a, b) {
8831 var merged = {};
8832 for (var key in a) {
8833 merged[key] = a[key];
8834 }
8835 for (var key2 in b) {
8836 merged[key2] = b[key2];
8837 }
8838 return merged;
8839 }
8840
8841 var trimLeft;
8842 if (typeof String.prototype.trimLeft === "function") {
8843 trimLeft = function(str) {
8844 return str.trimLeft();
8845 };
8846 } else {
8847 trimLeft = function(str) {
8848 return str.match(/^\s*(.*)/)[1];
8849 };
8850 }
8851
8852 // Type constants used to define functions.
8853 var TYPE_NUMBER = 0;
8854 var TYPE_ANY = 1;
8855 var TYPE_STRING = 2;
8856 var TYPE_ARRAY = 3;
8857 var TYPE_OBJECT = 4;
8858 var TYPE_BOOLEAN = 5;
8859 var TYPE_EXPREF = 6;
8860 var TYPE_NULL = 7;
8861 var TYPE_ARRAY_NUMBER = 8;
8862 var TYPE_ARRAY_STRING = 9;
8863
8864 var TOK_EOF = "EOF";
8865 var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier";
8866 var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier";
8867 var TOK_RBRACKET = "Rbracket";
8868 var TOK_RPAREN = "Rparen";
8869 var TOK_COMMA = "Comma";
8870 var TOK_COLON = "Colon";
8871 var TOK_RBRACE = "Rbrace";
8872 var TOK_NUMBER = "Number";
8873 var TOK_CURRENT = "Current";
8874 var TOK_EXPREF = "Expref";
8875 var TOK_PIPE = "Pipe";
8876 var TOK_OR = "Or";
8877 var TOK_AND = "And";
8878 var TOK_EQ = "EQ";
8879 var TOK_GT = "GT";
8880 var TOK_LT = "LT";
8881 var TOK_GTE = "GTE";
8882 var TOK_LTE = "LTE";
8883 var TOK_NE = "NE";
8884 var TOK_FLATTEN = "Flatten";
8885 var TOK_STAR = "Star";
8886 var TOK_FILTER = "Filter";
8887 var TOK_DOT = "Dot";
8888 var TOK_NOT = "Not";
8889 var TOK_LBRACE = "Lbrace";
8890 var TOK_LBRACKET = "Lbracket";
8891 var TOK_LPAREN= "Lparen";
8892 var TOK_LITERAL= "Literal";
8893
8894 // The "&", "[", "<", ">" tokens
8895 // are not in basicToken because
8896 // there are two token variants
8897 // ("&&", "[?", "<=", ">="). This is specially handled
8898 // below.
8899
8900 var basicTokens = {
8901 ".": TOK_DOT,
8902 "*": TOK_STAR,
8903 ",": TOK_COMMA,
8904 ":": TOK_COLON,
8905 "{": TOK_LBRACE,
8906 "}": TOK_RBRACE,
8907 "]": TOK_RBRACKET,
8908 "(": TOK_LPAREN,
8909 ")": TOK_RPAREN,
8910 "@": TOK_CURRENT
8911 };
8912
8913 var operatorStartToken = {
8914 "<": true,
8915 ">": true,
8916 "=": true,
8917 "!": true
8918 };
8919
8920 var skipChars = {
8921 " ": true,
8922 "\t": true,
8923 "\n": true
8924 };
8925
8926
8927 function isAlpha(ch) {
8928 return (ch >= "a" && ch <= "z") ||
8929 (ch >= "A" && ch <= "Z") ||
8930 ch === "_";
8931 }
8932
8933 function isNum(ch) {
8934 return (ch >= "0" && ch <= "9") ||
8935 ch === "-";
8936 }
8937 function isAlphaNum(ch) {
8938 return (ch >= "a" && ch <= "z") ||
8939 (ch >= "A" && ch <= "Z") ||
8940 (ch >= "0" && ch <= "9") ||
8941 ch === "_";
8942 }
8943
8944 function Lexer() {
8945 }
8946 Lexer.prototype = {
8947 tokenize: function(stream) {
8948 var tokens = [];
8949 this._current = 0;
8950 var start;
8951 var identifier;
8952 var token;
8953 while (this._current < stream.length) {
8954 if (isAlpha(stream[this._current])) {
8955 start = this._current;
8956 identifier = this._consumeUnquotedIdentifier(stream);
8957 tokens.push({type: TOK_UNQUOTEDIDENTIFIER,
8958 value: identifier,
8959 start: start});
8960 } else if (basicTokens[stream[this._current]] !== undefined) {
8961 tokens.push({type: basicTokens[stream[this._current]],
8962 value: stream[this._current],
8963 start: this._current});
8964 this._current++;
8965 } else if (isNum(stream[this._current])) {
8966 token = this._consumeNumber(stream);
8967 tokens.push(token);
8968 } else if (stream[this._current] === "[") {
8969 // No need to increment this._current. This happens
8970 // in _consumeLBracket
8971 token = this._consumeLBracket(stream);
8972 tokens.push(token);
8973 } else if (stream[this._current] === "\"") {
8974 start = this._current;
8975 identifier = this._consumeQuotedIdentifier(stream);
8976 tokens.push({type: TOK_QUOTEDIDENTIFIER,
8977 value: identifier,
8978 start: start});
8979 } else if (stream[this._current] === "'") {
8980 start = this._current;
8981 identifier = this._consumeRawStringLiteral(stream);
8982 tokens.push({type: TOK_LITERAL,
8983 value: identifier,
8984 start: start});
8985 } else if (stream[this._current] === "`") {
8986 start = this._current;
8987 var literal = this._consumeLiteral(stream);
8988 tokens.push({type: TOK_LITERAL,
8989 value: literal,
8990 start: start});
8991 } else if (operatorStartToken[stream[this._current]] !== undefined) {
8992 tokens.push(this._consumeOperator(stream));
8993 } else if (skipChars[stream[this._current]] !== undefined) {
8994 // Ignore whitespace.
8995 this._current++;
8996 } else if (stream[this._current] === "&") {
8997 start = this._current;
8998 this._current++;
8999 if (stream[this._current] === "&") {
9000 this._current++;
9001 tokens.push({type: TOK_AND, value: "&&", start: start});
9002 } else {
9003 tokens.push({type: TOK_EXPREF, value: "&", start: start});
9004 }
9005 } else if (stream[this._current] === "|") {
9006 start = this._current;
9007 this._current++;
9008 if (stream[this._current] === "|") {
9009 this._current++;
9010 tokens.push({type: TOK_OR, value: "||", start: start});
9011 } else {
9012 tokens.push({type: TOK_PIPE, value: "|", start: start});
9013 }
9014 } else {
9015 var error = new Error("Unknown character:" + stream[this._current]);
9016 error.name = "LexerError";
9017 throw error;
9018 }
9019 }
9020 return tokens;
9021 },
9022
9023 _consumeUnquotedIdentifier: function(stream) {
9024 var start = this._current;
9025 this._current++;
9026 while (this._current < stream.length && isAlphaNum(stream[this._current])) {
9027 this._current++;
9028 }
9029 return stream.slice(start, this._current);
9030 },
9031
9032 _consumeQuotedIdentifier: function(stream) {
9033 var start = this._current;
9034 this._current++;
9035 var maxLength = stream.length;
9036 while (stream[this._current] !== "\"" && this._current < maxLength) {
9037 // You can escape a double quote and you can escape an escape.
9038 var current = this._current;
9039 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9040 stream[current + 1] === "\"")) {
9041 current += 2;
9042 } else {
9043 current++;
9044 }
9045 this._current = current;
9046 }
9047 this._current++;
9048 return JSON.parse(stream.slice(start, this._current));
9049 },
9050
9051 _consumeRawStringLiteral: function(stream) {
9052 var start = this._current;
9053 this._current++;
9054 var maxLength = stream.length;
9055 while (stream[this._current] !== "'" && this._current < maxLength) {
9056 // You can escape a single quote and you can escape an escape.
9057 var current = this._current;
9058 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9059 stream[current + 1] === "'")) {
9060 current += 2;
9061 } else {
9062 current++;
9063 }
9064 this._current = current;
9065 }
9066 this._current++;
9067 var literal = stream.slice(start + 1, this._current - 1);
9068 return literal.replace("\\'", "'");
9069 },
9070
9071 _consumeNumber: function(stream) {
9072 var start = this._current;
9073 this._current++;
9074 var maxLength = stream.length;
9075 while (isNum(stream[this._current]) && this._current < maxLength) {
9076 this._current++;
9077 }
9078 var value = parseInt(stream.slice(start, this._current));
9079 return {type: TOK_NUMBER, value: value, start: start};
9080 },
9081
9082 _consumeLBracket: function(stream) {
9083 var start = this._current;
9084 this._current++;
9085 if (stream[this._current] === "?") {
9086 this._current++;
9087 return {type: TOK_FILTER, value: "[?", start: start};
9088 } else if (stream[this._current] === "]") {
9089 this._current++;
9090 return {type: TOK_FLATTEN, value: "[]", start: start};
9091 } else {
9092 return {type: TOK_LBRACKET, value: "[", start: start};
9093 }
9094 },
9095
9096 _consumeOperator: function(stream) {
9097 var start = this._current;
9098 var startingChar = stream[start];
9099 this._current++;
9100 if (startingChar === "!") {
9101 if (stream[this._current] === "=") {
9102 this._current++;
9103 return {type: TOK_NE, value: "!=", start: start};
9104 } else {
9105 return {type: TOK_NOT, value: "!", start: start};
9106 }
9107 } else if (startingChar === "<") {
9108 if (stream[this._current] === "=") {
9109 this._current++;
9110 return {type: TOK_LTE, value: "<=", start: start};
9111 } else {
9112 return {type: TOK_LT, value: "<", start: start};
9113 }
9114 } else if (startingChar === ">") {
9115 if (stream[this._current] === "=") {
9116 this._current++;
9117 return {type: TOK_GTE, value: ">=", start: start};
9118 } else {
9119 return {type: TOK_GT, value: ">", start: start};
9120 }
9121 } else if (startingChar === "=") {
9122 if (stream[this._current] === "=") {
9123 this._current++;
9124 return {type: TOK_EQ, value: "==", start: start};
9125 }
9126 }
9127 },
9128
9129 _consumeLiteral: function(stream) {
9130 this._current++;
9131 var start = this._current;
9132 var maxLength = stream.length;
9133 var literal;
9134 while(stream[this._current] !== "`" && this._current < maxLength) {
9135 // You can escape a literal char or you can escape the escape.
9136 var current = this._current;
9137 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9138 stream[current + 1] === "`")) {
9139 current += 2;
9140 } else {
9141 current++;
9142 }
9143 this._current = current;
9144 }
9145 var literalString = trimLeft(stream.slice(start, this._current));
9146 literalString = literalString.replace("\\`", "`");
9147 if (this._looksLikeJSON(literalString)) {
9148 literal = JSON.parse(literalString);
9149 } else {
9150 // Try to JSON parse it as "<literal>"
9151 literal = JSON.parse("\"" + literalString + "\"");
9152 }
9153 // +1 gets us to the ending "`", +1 to move on to the next char.
9154 this._current++;
9155 return literal;
9156 },
9157
9158 _looksLikeJSON: function(literalString) {
9159 var startingChars = "[{\"";
9160 var jsonLiterals = ["true", "false", "null"];
9161 var numberLooking = "-0123456789";
9162
9163 if (literalString === "") {
9164 return false;
9165 } else if (startingChars.indexOf(literalString[0]) >= 0) {
9166 return true;
9167 } else if (jsonLiterals.indexOf(literalString) >= 0) {
9168 return true;
9169 } else if (numberLooking.indexOf(literalString[0]) >= 0) {
9170 try {
9171 JSON.parse(literalString);
9172 return true;
9173 } catch (ex) {
9174 return false;
9175 }
9176 } else {
9177 return false;
9178 }
9179 }
9180 };
9181
9182 var bindingPower = {};
9183 bindingPower[TOK_EOF] = 0;
9184 bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0;
9185 bindingPower[TOK_QUOTEDIDENTIFIER] = 0;
9186 bindingPower[TOK_RBRACKET] = 0;
9187 bindingPower[TOK_RPAREN] = 0;
9188 bindingPower[TOK_COMMA] = 0;
9189 bindingPower[TOK_RBRACE] = 0;
9190 bindingPower[TOK_NUMBER] = 0;
9191 bindingPower[TOK_CURRENT] = 0;
9192 bindingPower[TOK_EXPREF] = 0;
9193 bindingPower[TOK_PIPE] = 1;
9194 bindingPower[TOK_OR] = 2;
9195 bindingPower[TOK_AND] = 3;
9196 bindingPower[TOK_EQ] = 5;
9197 bindingPower[TOK_GT] = 5;
9198 bindingPower[TOK_LT] = 5;
9199 bindingPower[TOK_GTE] = 5;
9200 bindingPower[TOK_LTE] = 5;
9201 bindingPower[TOK_NE] = 5;
9202 bindingPower[TOK_FLATTEN] = 9;
9203 bindingPower[TOK_STAR] = 20;
9204 bindingPower[TOK_FILTER] = 21;
9205 bindingPower[TOK_DOT] = 40;
9206 bindingPower[TOK_NOT] = 45;
9207 bindingPower[TOK_LBRACE] = 50;
9208 bindingPower[TOK_LBRACKET] = 55;
9209 bindingPower[TOK_LPAREN] = 60;
9210
9211 function Parser() {
9212 }
9213
9214 Parser.prototype = {
9215 parse: function(expression) {
9216 this._loadTokens(expression);
9217 this.index = 0;
9218 var ast = this.expression(0);
9219 if (this._lookahead(0) !== TOK_EOF) {
9220 var t = this._lookaheadToken(0);
9221 var error = new Error(
9222 "Unexpected token type: " + t.type + ", value: " + t.value);
9223 error.name = "ParserError";
9224 throw error;
9225 }
9226 return ast;
9227 },
9228
9229 _loadTokens: function(expression) {
9230 var lexer = new Lexer();
9231 var tokens = lexer.tokenize(expression);
9232 tokens.push({type: TOK_EOF, value: "", start: expression.length});
9233 this.tokens = tokens;
9234 },
9235
9236 expression: function(rbp) {
9237 var leftToken = this._lookaheadToken(0);
9238 this._advance();
9239 var left = this.nud(leftToken);
9240 var currentToken = this._lookahead(0);
9241 while (rbp < bindingPower[currentToken]) {
9242 this._advance();
9243 left = this.led(currentToken, left);
9244 currentToken = this._lookahead(0);
9245 }
9246 return left;
9247 },
9248
9249 _lookahead: function(number) {
9250 return this.tokens[this.index + number].type;
9251 },
9252
9253 _lookaheadToken: function(number) {
9254 return this.tokens[this.index + number];
9255 },
9256
9257 _advance: function() {
9258 this.index++;
9259 },
9260
9261 nud: function(token) {
9262 var left;
9263 var right;
9264 var expression;
9265 switch (token.type) {
9266 case TOK_LITERAL:
9267 return {type: "Literal", value: token.value};
9268 case TOK_UNQUOTEDIDENTIFIER:
9269 return {type: "Field", name: token.value};
9270 case TOK_QUOTEDIDENTIFIER:
9271 var node = {type: "Field", name: token.value};
9272 if (this._lookahead(0) === TOK_LPAREN) {
9273 throw new Error("Quoted identifier not allowed for function names.");
9274 } else {
9275 return node;
9276 }
9277 break;
9278 case TOK_NOT:
9279 right = this.expression(bindingPower.Not);
9280 return {type: "NotExpression", children: [right]};
9281 case TOK_STAR:
9282 left = {type: "Identity"};
9283 right = null;
9284 if (this._lookahead(0) === TOK_RBRACKET) {
9285 // This can happen in a multiselect,
9286 // [a, b, *]
9287 right = {type: "Identity"};
9288 } else {
9289 right = this._parseProjectionRHS(bindingPower.Star);
9290 }
9291 return {type: "ValueProjection", children: [left, right]};
9292 case TOK_FILTER:
9293 return this.led(token.type, {type: "Identity"});
9294 case TOK_LBRACE:
9295 return this._parseMultiselectHash();
9296 case TOK_FLATTEN:
9297 left = {type: TOK_FLATTEN, children: [{type: "Identity"}]};
9298 right = this._parseProjectionRHS(bindingPower.Flatten);
9299 return {type: "Projection", children: [left, right]};
9300 case TOK_LBRACKET:
9301 if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) {
9302 right = this._parseIndexExpression();
9303 return this._projectIfSlice({type: "Identity"}, right);
9304 } else if (this._lookahead(0) === TOK_STAR &&
9305 this._lookahead(1) === TOK_RBRACKET) {
9306 this._advance();
9307 this._advance();
9308 right = this._parseProjectionRHS(bindingPower.Star);
9309 return {type: "Projection",
9310 children: [{type: "Identity"}, right]};
9311 } else {
9312 return this._parseMultiselectList();
9313 }
9314 break;
9315 case TOK_CURRENT:
9316 return {type: TOK_CURRENT};
9317 case TOK_EXPREF:
9318 expression = this.expression(bindingPower.Expref);
9319 return {type: "ExpressionReference", children: [expression]};
9320 case TOK_LPAREN:
9321 var args = [];
9322 while (this._lookahead(0) !== TOK_RPAREN) {
9323 if (this._lookahead(0) === TOK_CURRENT) {
9324 expression = {type: TOK_CURRENT};
9325 this._advance();
9326 } else {
9327 expression = this.expression(0);
9328 }
9329 args.push(expression);
9330 }
9331 this._match(TOK_RPAREN);
9332 return args[0];
9333 default:
9334 this._errorToken(token);
9335 }
9336 },
9337
9338 led: function(tokenName, left) {
9339 var right;
9340 switch(tokenName) {
9341 case TOK_DOT:
9342 var rbp = bindingPower.Dot;
9343 if (this._lookahead(0) !== TOK_STAR) {
9344 right = this._parseDotRHS(rbp);
9345 return {type: "Subexpression", children: [left, right]};
9346 } else {
9347 // Creating a projection.
9348 this._advance();
9349 right = this._parseProjectionRHS(rbp);
9350 return {type: "ValueProjection", children: [left, right]};
9351 }
9352 break;
9353 case TOK_PIPE:
9354 right = this.expression(bindingPower.Pipe);
9355 return {type: TOK_PIPE, children: [left, right]};
9356 case TOK_OR:
9357 right = this.expression(bindingPower.Or);
9358 return {type: "OrExpression", children: [left, right]};
9359 case TOK_AND:
9360 right = this.expression(bindingPower.And);
9361 return {type: "AndExpression", children: [left, right]};
9362 case TOK_LPAREN:
9363 var name = left.name;
9364 var args = [];
9365 var expression, node;
9366 while (this._lookahead(0) !== TOK_RPAREN) {
9367 if (this._lookahead(0) === TOK_CURRENT) {
9368 expression = {type: TOK_CURRENT};
9369 this._advance();
9370 } else {
9371 expression = this.expression(0);
9372 }
9373 if (this._lookahead(0) === TOK_COMMA) {
9374 this._match(TOK_COMMA);
9375 }
9376 args.push(expression);
9377 }
9378 this._match(TOK_RPAREN);
9379 node = {type: "Function", name: name, children: args};
9380 return node;
9381 case TOK_FILTER:
9382 var condition = this.expression(0);
9383 this._match(TOK_RBRACKET);
9384 if (this._lookahead(0) === TOK_FLATTEN) {
9385 right = {type: "Identity"};
9386 } else {
9387 right = this._parseProjectionRHS(bindingPower.Filter);
9388 }
9389 return {type: "FilterProjection", children: [left, right, condition]};
9390 case TOK_FLATTEN:
9391 var leftNode = {type: TOK_FLATTEN, children: [left]};
9392 var rightNode = this._parseProjectionRHS(bindingPower.Flatten);
9393 return {type: "Projection", children: [leftNode, rightNode]};
9394 case TOK_EQ:
9395 case TOK_NE:
9396 case TOK_GT:
9397 case TOK_GTE:
9398 case TOK_LT:
9399 case TOK_LTE:
9400 return this._parseComparator(left, tokenName);
9401 case TOK_LBRACKET:
9402 var token = this._lookaheadToken(0);
9403 if (token.type === TOK_NUMBER || token.type === TOK_COLON) {
9404 right = this._parseIndexExpression();
9405 return this._projectIfSlice(left, right);
9406 } else {
9407 this._match(TOK_STAR);
9408 this._match(TOK_RBRACKET);
9409 right = this._parseProjectionRHS(bindingPower.Star);
9410 return {type: "Projection", children: [left, right]};
9411 }
9412 break;
9413 default:
9414 this._errorToken(this._lookaheadToken(0));
9415 }
9416 },
9417
9418 _match: function(tokenType) {
9419 if (this._lookahead(0) === tokenType) {
9420 this._advance();
9421 } else {
9422 var t = this._lookaheadToken(0);
9423 var error = new Error("Expected " + tokenType + ", got: " + t.type);
9424 error.name = "ParserError";
9425 throw error;
9426 }
9427 },
9428
9429 _errorToken: function(token) {
9430 var error = new Error("Invalid token (" +
9431 token.type + "): \"" +
9432 token.value + "\"");
9433 error.name = "ParserError";
9434 throw error;
9435 },
9436
9437
9438 _parseIndexExpression: function() {
9439 if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) {
9440 return this._parseSliceExpression();
9441 } else {
9442 var node = {
9443 type: "Index",
9444 value: this._lookaheadToken(0).value};
9445 this._advance();
9446 this._match(TOK_RBRACKET);
9447 return node;
9448 }
9449 },
9450
9451 _projectIfSlice: function(left, right) {
9452 var indexExpr = {type: "IndexExpression", children: [left, right]};
9453 if (right.type === "Slice") {
9454 return {
9455 type: "Projection",
9456 children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)]
9457 };
9458 } else {
9459 return indexExpr;
9460 }
9461 },
9462
9463 _parseSliceExpression: function() {
9464 // [start:end:step] where each part is optional, as well as the last
9465 // colon.
9466 var parts = [null, null, null];
9467 var index = 0;
9468 var currentToken = this._lookahead(0);
9469 while (currentToken !== TOK_RBRACKET && index < 3) {
9470 if (currentToken === TOK_COLON) {
9471 index++;
9472 this._advance();
9473 } else if (currentToken === TOK_NUMBER) {
9474 parts[index] = this._lookaheadToken(0).value;
9475 this._advance();
9476 } else {
9477 var t = this._lookahead(0);
9478 var error = new Error("Syntax error, unexpected token: " +
9479 t.value + "(" + t.type + ")");
9480 error.name = "Parsererror";
9481 throw error;
9482 }
9483 currentToken = this._lookahead(0);
9484 }
9485 this._match(TOK_RBRACKET);
9486 return {
9487 type: "Slice",
9488 children: parts
9489 };
9490 },
9491
9492 _parseComparator: function(left, comparator) {
9493 var right = this.expression(bindingPower[comparator]);
9494 return {type: "Comparator", name: comparator, children: [left, right]};
9495 },
9496
9497 _parseDotRHS: function(rbp) {
9498 var lookahead = this._lookahead(0);
9499 var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];
9500 if (exprTokens.indexOf(lookahead) >= 0) {
9501 return this.expression(rbp);
9502 } else if (lookahead === TOK_LBRACKET) {
9503 this._match(TOK_LBRACKET);
9504 return this._parseMultiselectList();
9505 } else if (lookahead === TOK_LBRACE) {
9506 this._match(TOK_LBRACE);
9507 return this._parseMultiselectHash();
9508 }
9509 },
9510
9511 _parseProjectionRHS: function(rbp) {
9512 var right;
9513 if (bindingPower[this._lookahead(0)] < 10) {
9514 right = {type: "Identity"};
9515 } else if (this._lookahead(0) === TOK_LBRACKET) {
9516 right = this.expression(rbp);
9517 } else if (this._lookahead(0) === TOK_FILTER) {
9518 right = this.expression(rbp);
9519 } else if (this._lookahead(0) === TOK_DOT) {
9520 this._match(TOK_DOT);
9521 right = this._parseDotRHS(rbp);
9522 } else {
9523 var t = this._lookaheadToken(0);
9524 var error = new Error("Sytanx error, unexpected token: " +
9525 t.value + "(" + t.type + ")");
9526 error.name = "ParserError";
9527 throw error;
9528 }
9529 return right;
9530 },
9531
9532 _parseMultiselectList: function() {
9533 var expressions = [];
9534 while (this._lookahead(0) !== TOK_RBRACKET) {
9535 var expression = this.expression(0);
9536 expressions.push(expression);
9537 if (this._lookahead(0) === TOK_COMMA) {
9538 this._match(TOK_COMMA);
9539 if (this._lookahead(0) === TOK_RBRACKET) {
9540 throw new Error("Unexpected token Rbracket");
9541 }
9542 }
9543 }
9544 this._match(TOK_RBRACKET);
9545 return {type: "MultiSelectList", children: expressions};
9546 },
9547
9548 _parseMultiselectHash: function() {
9549 var pairs = [];
9550 var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER];
9551 var keyToken, keyName, value, node;
9552 for (;;) {
9553 keyToken = this._lookaheadToken(0);
9554 if (identifierTypes.indexOf(keyToken.type) < 0) {
9555 throw new Error("Expecting an identifier token, got: " +
9556 keyToken.type);
9557 }
9558 keyName = keyToken.value;
9559 this._advance();
9560 this._match(TOK_COLON);
9561 value = this.expression(0);
9562 node = {type: "KeyValuePair", name: keyName, value: value};
9563 pairs.push(node);
9564 if (this._lookahead(0) === TOK_COMMA) {
9565 this._match(TOK_COMMA);
9566 } else if (this._lookahead(0) === TOK_RBRACE) {
9567 this._match(TOK_RBRACE);
9568 break;
9569 }
9570 }
9571 return {type: "MultiSelectHash", children: pairs};
9572 }
9573 };
9574
9575
9576 function TreeInterpreter(runtime) {
9577 this.runtime = runtime;
9578 }
9579
9580 TreeInterpreter.prototype = {
9581 search: function(node, value) {
9582 return this.visit(node, value);
9583 },
9584
9585 visit: function(node, value) {
9586 var matched, current, result, first, second, field, left, right, collected, i;
9587 switch (node.type) {
9588 case "Field":
9589 if (value === null ) {
9590 return null;
9591 } else if (isObject(value)) {
9592 field = value[node.name];
9593 if (field === undefined) {
9594 return null;
9595 } else {
9596 return field;
9597 }
9598 } else {
9599 return null;
9600 }
9601 break;
9602 case "Subexpression":
9603 result = this.visit(node.children[0], value);
9604 for (i = 1; i < node.children.length; i++) {
9605 result = this.visit(node.children[1], result);
9606 if (result === null) {
9607 return null;
9608 }
9609 }
9610 return result;
9611 case "IndexExpression":
9612 left = this.visit(node.children[0], value);
9613 right = this.visit(node.children[1], left);
9614 return right;
9615 case "Index":
9616 if (!isArray(value)) {
9617 return null;
9618 }
9619 var index = node.value;
9620 if (index < 0) {
9621 index = value.length + index;
9622 }
9623 result = value[index];
9624 if (result === undefined) {
9625 result = null;
9626 }
9627 return result;
9628 case "Slice":
9629 if (!isArray(value)) {
9630 return null;
9631 }
9632 var sliceParams = node.children.slice(0);
9633 var computed = this.computeSliceParams(value.length, sliceParams);
9634 var start = computed[0];
9635 var stop = computed[1];
9636 var step = computed[2];
9637 result = [];
9638 if (step > 0) {
9639 for (i = start; i < stop; i += step) {
9640 result.push(value[i]);
9641 }
9642 } else {
9643 for (i = start; i > stop; i += step) {
9644 result.push(value[i]);
9645 }
9646 }
9647 return result;
9648 case "Projection":
9649 // Evaluate left child.
9650 var base = this.visit(node.children[0], value);
9651 if (!isArray(base)) {
9652 return null;
9653 }
9654 collected = [];
9655 for (i = 0; i < base.length; i++) {
9656 current = this.visit(node.children[1], base[i]);
9657 if (current !== null) {
9658 collected.push(current);
9659 }
9660 }
9661 return collected;
9662 case "ValueProjection":
9663 // Evaluate left child.
9664 base = this.visit(node.children[0], value);
9665 if (!isObject(base)) {
9666 return null;
9667 }
9668 collected = [];
9669 var values = objValues(base);
9670 for (i = 0; i < values.length; i++) {
9671 current = this.visit(node.children[1], values[i]);
9672 if (current !== null) {
9673 collected.push(current);
9674 }
9675 }
9676 return collected;
9677 case "FilterProjection":
9678 base = this.visit(node.children[0], value);
9679 if (!isArray(base)) {
9680 return null;
9681 }
9682 var filtered = [];
9683 var finalResults = [];
9684 for (i = 0; i < base.length; i++) {
9685 matched = this.visit(node.children[2], base[i]);
9686 if (!isFalse(matched)) {
9687 filtered.push(base[i]);
9688 }
9689 }
9690 for (var j = 0; j < filtered.length; j++) {
9691 current = this.visit(node.children[1], filtered[j]);
9692 if (current !== null) {
9693 finalResults.push(current);
9694 }
9695 }
9696 return finalResults;
9697 case "Comparator":
9698 first = this.visit(node.children[0], value);
9699 second = this.visit(node.children[1], value);
9700 switch(node.name) {
9701 case TOK_EQ:
9702 result = strictDeepEqual(first, second);
9703 break;
9704 case TOK_NE:
9705 result = !strictDeepEqual(first, second);
9706 break;
9707 case TOK_GT:
9708 result = first > second;
9709 break;
9710 case TOK_GTE:
9711 result = first >= second;
9712 break;
9713 case TOK_LT:
9714 result = first < second;
9715 break;
9716 case TOK_LTE:
9717 result = first <= second;
9718 break;
9719 default:
9720 throw new Error("Unknown comparator: " + node.name);
9721 }
9722 return result;
9723 case TOK_FLATTEN:
9724 var original = this.visit(node.children[0], value);
9725 if (!isArray(original)) {
9726 return null;
9727 }
9728 var merged = [];
9729 for (i = 0; i < original.length; i++) {
9730 current = original[i];
9731 if (isArray(current)) {
9732 merged.push.apply(merged, current);
9733 } else {
9734 merged.push(current);
9735 }
9736 }
9737 return merged;
9738 case "Identity":
9739 return value;
9740 case "MultiSelectList":
9741 if (value === null) {
9742 return null;
9743 }
9744 collected = [];
9745 for (i = 0; i < node.children.length; i++) {
9746 collected.push(this.visit(node.children[i], value));
9747 }
9748 return collected;
9749 case "MultiSelectHash":
9750 if (value === null) {
9751 return null;
9752 }
9753 collected = {};
9754 var child;
9755 for (i = 0; i < node.children.length; i++) {
9756 child = node.children[i];
9757 collected[child.name] = this.visit(child.value, value);
9758 }
9759 return collected;
9760 case "OrExpression":
9761 matched = this.visit(node.children[0], value);
9762 if (isFalse(matched)) {
9763 matched = this.visit(node.children[1], value);
9764 }
9765 return matched;
9766 case "AndExpression":
9767 first = this.visit(node.children[0], value);
9768
9769 if (isFalse(first) === true) {
9770 return first;
9771 }
9772 return this.visit(node.children[1], value);
9773 case "NotExpression":
9774 first = this.visit(node.children[0], value);
9775 return isFalse(first);
9776 case "Literal":
9777 return node.value;
9778 case TOK_PIPE:
9779 left = this.visit(node.children[0], value);
9780 return this.visit(node.children[1], left);
9781 case TOK_CURRENT:
9782 return value;
9783 case "Function":
9784 var resolvedArgs = [];
9785 for (i = 0; i < node.children.length; i++) {
9786 resolvedArgs.push(this.visit(node.children[i], value));
9787 }
9788 return this.runtime.callFunction(node.name, resolvedArgs);
9789 case "ExpressionReference":
9790 var refNode = node.children[0];
9791 // Tag the node with a specific attribute so the type
9792 // checker verify the type.
9793 refNode.jmespathType = TOK_EXPREF;
9794 return refNode;
9795 default:
9796 throw new Error("Unknown node type: " + node.type);
9797 }
9798 },
9799
9800 computeSliceParams: function(arrayLength, sliceParams) {
9801 var start = sliceParams[0];
9802 var stop = sliceParams[1];
9803 var step = sliceParams[2];
9804 var computed = [null, null, null];
9805 if (step === null) {
9806 step = 1;
9807 } else if (step === 0) {
9808 var error = new Error("Invalid slice, step cannot be 0");
9809 error.name = "RuntimeError";
9810 throw error;
9811 }
9812 var stepValueNegative = step < 0 ? true : false;
9813
9814 if (start === null) {
9815 start = stepValueNegative ? arrayLength - 1 : 0;
9816 } else {
9817 start = this.capSliceRange(arrayLength, start, step);
9818 }
9819
9820 if (stop === null) {
9821 stop = stepValueNegative ? -1 : arrayLength;
9822 } else {
9823 stop = this.capSliceRange(arrayLength, stop, step);
9824 }
9825 computed[0] = start;
9826 computed[1] = stop;
9827 computed[2] = step;
9828 return computed;
9829 },
9830
9831 capSliceRange: function(arrayLength, actualValue, step) {
9832 if (actualValue < 0) {
9833 actualValue += arrayLength;
9834 if (actualValue < 0) {
9835 actualValue = step < 0 ? -1 : 0;
9836 }
9837 } else if (actualValue >= arrayLength) {
9838 actualValue = step < 0 ? arrayLength - 1 : arrayLength;
9839 }
9840 return actualValue;
9841 }
9842
9843 };
9844
9845 function Runtime(interpreter) {
9846 this._interpreter = interpreter;
9847 this.functionTable = {
9848 // name: [function, <signature>]
9849 // The <signature> can be:
9850 //
9851 // {
9852 // args: [[type1, type2], [type1, type2]],
9853 // variadic: true|false
9854 // }
9855 //
9856 // Each arg in the arg list is a list of valid types
9857 // (if the function is overloaded and supports multiple
9858 // types. If the type is "any" then no type checking
9859 // occurs on the argument. Variadic is optional
9860 // and if not provided is assumed to be false.
9861 abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]},
9862 avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
9863 ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]},
9864 contains: {
9865 _func: this._functionContains,
9866 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]},
9867 {types: [TYPE_ANY]}]},
9868 "ends_with": {
9869 _func: this._functionEndsWith,
9870 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
9871 floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]},
9872 length: {
9873 _func: this._functionLength,
9874 _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]},
9875 map: {
9876 _func: this._functionMap,
9877 _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]},
9878 max: {
9879 _func: this._functionMax,
9880 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
9881 "merge": {
9882 _func: this._functionMerge,
9883 _signature: [{types: [TYPE_OBJECT], variadic: true}]
9884 },
9885 "max_by": {
9886 _func: this._functionMaxBy,
9887 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9888 },
9889 sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
9890 "starts_with": {
9891 _func: this._functionStartsWith,
9892 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
9893 min: {
9894 _func: this._functionMin,
9895 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
9896 "min_by": {
9897 _func: this._functionMinBy,
9898 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9899 },
9900 type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]},
9901 keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]},
9902 values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]},
9903 sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]},
9904 "sort_by": {
9905 _func: this._functionSortBy,
9906 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9907 },
9908 join: {
9909 _func: this._functionJoin,
9910 _signature: [
9911 {types: [TYPE_STRING]},
9912 {types: [TYPE_ARRAY_STRING]}
9913 ]
9914 },
9915 reverse: {
9916 _func: this._functionReverse,
9917 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]},
9918 "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]},
9919 "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]},
9920 "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]},
9921 "not_null": {
9922 _func: this._functionNotNull,
9923 _signature: [{types: [TYPE_ANY], variadic: true}]
9924 }
9925 };
9926 }
9927
9928 Runtime.prototype = {
9929 callFunction: function(name, resolvedArgs) {
9930 var functionEntry = this.functionTable[name];
9931 if (functionEntry === undefined) {
9932 throw new Error("Unknown function: " + name + "()");
9933 }
9934 this._validateArgs(name, resolvedArgs, functionEntry._signature);
9935 return functionEntry._func.call(this, resolvedArgs);
9936 },
9937
9938 _validateArgs: function(name, args, signature) {
9939 // Validating the args requires validating
9940 // the correct arity and the correct type of each arg.
9941 // If the last argument is declared as variadic, then we need
9942 // a minimum number of args to be required. Otherwise it has to
9943 // be an exact amount.
9944 var pluralized;
9945 if (signature[signature.length - 1].variadic) {
9946 if (args.length < signature.length) {
9947 pluralized = signature.length === 1 ? " argument" : " arguments";
9948 throw new Error("ArgumentError: " + name + "() " +
9949 "takes at least" + signature.length + pluralized +
9950 " but received " + args.length);
9951 }
9952 } else if (args.length !== signature.length) {
9953 pluralized = signature.length === 1 ? " argument" : " arguments";
9954 throw new Error("ArgumentError: " + name + "() " +
9955 "takes " + signature.length + pluralized +
9956 " but received " + args.length);
9957 }
9958 var currentSpec;
9959 var actualType;
9960 var typeMatched;
9961 for (var i = 0; i < signature.length; i++) {
9962 typeMatched = false;
9963 currentSpec = signature[i].types;
9964 actualType = this._getTypeName(args[i]);
9965 for (var j = 0; j < currentSpec.length; j++) {
9966 if (this._typeMatches(actualType, currentSpec[j], args[i])) {
9967 typeMatched = true;
9968 break;
9969 }
9970 }
9971 if (!typeMatched) {
9972 throw new Error("TypeError: " + name + "() " +
9973 "expected argument " + (i + 1) +
9974 " to be type " + currentSpec +
9975 " but received type " + actualType +
9976 " instead.");
9977 }
9978 }
9979 },
9980
9981 _typeMatches: function(actual, expected, argValue) {
9982 if (expected === TYPE_ANY) {
9983 return true;
9984 }
9985 if (expected === TYPE_ARRAY_STRING ||
9986 expected === TYPE_ARRAY_NUMBER ||
9987 expected === TYPE_ARRAY) {
9988 // The expected type can either just be array,
9989 // or it can require a specific subtype (array of numbers).
9990 //
9991 // The simplest case is if "array" with no subtype is specified.
9992 if (expected === TYPE_ARRAY) {
9993 return actual === TYPE_ARRAY;
9994 } else if (actual === TYPE_ARRAY) {
9995 // Otherwise we need to check subtypes.
9996 // I think this has potential to be improved.
9997 var subtype;
9998 if (expected === TYPE_ARRAY_NUMBER) {
9999 subtype = TYPE_NUMBER;
10000 } else if (expected === TYPE_ARRAY_STRING) {
10001 subtype = TYPE_STRING;
10002 }
10003 for (var i = 0; i < argValue.length; i++) {
10004 if (!this._typeMatches(
10005 this._getTypeName(argValue[i]), subtype,
10006 argValue[i])) {
10007 return false;
10008 }
10009 }
10010 return true;
10011 }
10012 } else {
10013 return actual === expected;
10014 }
10015 },
10016 _getTypeName: function(obj) {
10017 switch (Object.prototype.toString.call(obj)) {
10018 case "[object String]":
10019 return TYPE_STRING;
10020 case "[object Number]":
10021 return TYPE_NUMBER;
10022 case "[object Array]":
10023 return TYPE_ARRAY;
10024 case "[object Boolean]":
10025 return TYPE_BOOLEAN;
10026 case "[object Null]":
10027 return TYPE_NULL;
10028 case "[object Object]":
10029 // Check if it's an expref. If it has, it's been
10030 // tagged with a jmespathType attr of 'Expref';
10031 if (obj.jmespathType === TOK_EXPREF) {
10032 return TYPE_EXPREF;
10033 } else {
10034 return TYPE_OBJECT;
10035 }
10036 }
10037 },
10038
10039 _functionStartsWith: function(resolvedArgs) {
10040 return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0;
10041 },
10042
10043 _functionEndsWith: function(resolvedArgs) {
10044 var searchStr = resolvedArgs[0];
10045 var suffix = resolvedArgs[1];
10046 return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1;
10047 },
10048
10049 _functionReverse: function(resolvedArgs) {
10050 var typeName = this._getTypeName(resolvedArgs[0]);
10051 if (typeName === TYPE_STRING) {
10052 var originalStr = resolvedArgs[0];
10053 var reversedStr = "";
10054 for (var i = originalStr.length - 1; i >= 0; i--) {
10055 reversedStr += originalStr[i];
10056 }
10057 return reversedStr;
10058 } else {
10059 var reversedArray = resolvedArgs[0].slice(0);
10060 reversedArray.reverse();
10061 return reversedArray;
10062 }
10063 },
10064
10065 _functionAbs: function(resolvedArgs) {
10066 return Math.abs(resolvedArgs[0]);
10067 },
10068
10069 _functionCeil: function(resolvedArgs) {
10070 return Math.ceil(resolvedArgs[0]);
10071 },
10072
10073 _functionAvg: function(resolvedArgs) {
10074 var sum = 0;
10075 var inputArray = resolvedArgs[0];
10076 for (var i = 0; i < inputArray.length; i++) {
10077 sum += inputArray[i];
10078 }
10079 return sum / inputArray.length;
10080 },
10081
10082 _functionContains: function(resolvedArgs) {
10083 return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0;
10084 },
10085
10086 _functionFloor: function(resolvedArgs) {
10087 return Math.floor(resolvedArgs[0]);
10088 },
10089
10090 _functionLength: function(resolvedArgs) {
10091 if (!isObject(resolvedArgs[0])) {
10092 return resolvedArgs[0].length;
10093 } else {
10094 // As far as I can tell, there's no way to get the length
10095 // of an object without O(n) iteration through the object.
10096 return Object.keys(resolvedArgs[0]).length;
10097 }
10098 },
10099
10100 _functionMap: function(resolvedArgs) {
10101 var mapped = [];
10102 var interpreter = this._interpreter;
10103 var exprefNode = resolvedArgs[0];
10104 var elements = resolvedArgs[1];
10105 for (var i = 0; i < elements.length; i++) {
10106 mapped.push(interpreter.visit(exprefNode, elements[i]));
10107 }
10108 return mapped;
10109 },
10110
10111 _functionMerge: function(resolvedArgs) {
10112 var merged = {};
10113 for (var i = 0; i < resolvedArgs.length; i++) {
10114 var current = resolvedArgs[i];
10115 for (var key in current) {
10116 merged[key] = current[key];
10117 }
10118 }
10119 return merged;
10120 },
10121
10122 _functionMax: function(resolvedArgs) {
10123 if (resolvedArgs[0].length > 0) {
10124 var typeName = this._getTypeName(resolvedArgs[0][0]);
10125 if (typeName === TYPE_NUMBER) {
10126 return Math.max.apply(Math, resolvedArgs[0]);
10127 } else {
10128 var elements = resolvedArgs[0];
10129 var maxElement = elements[0];
10130 for (var i = 1; i < elements.length; i++) {
10131 if (maxElement.localeCompare(elements[i]) < 0) {
10132 maxElement = elements[i];
10133 }
10134 }
10135 return maxElement;
10136 }
10137 } else {
10138 return null;
10139 }
10140 },
10141
10142 _functionMin: function(resolvedArgs) {
10143 if (resolvedArgs[0].length > 0) {
10144 var typeName = this._getTypeName(resolvedArgs[0][0]);
10145 if (typeName === TYPE_NUMBER) {
10146 return Math.min.apply(Math, resolvedArgs[0]);
10147 } else {
10148 var elements = resolvedArgs[0];
10149 var minElement = elements[0];
10150 for (var i = 1; i < elements.length; i++) {
10151 if (elements[i].localeCompare(minElement) < 0) {
10152 minElement = elements[i];
10153 }
10154 }
10155 return minElement;
10156 }
10157 } else {
10158 return null;
10159 }
10160 },
10161
10162 _functionSum: function(resolvedArgs) {
10163 var sum = 0;
10164 var listToSum = resolvedArgs[0];
10165 for (var i = 0; i < listToSum.length; i++) {
10166 sum += listToSum[i];
10167 }
10168 return sum;
10169 },
10170
10171 _functionType: function(resolvedArgs) {
10172 switch (this._getTypeName(resolvedArgs[0])) {
10173 case TYPE_NUMBER:
10174 return "number";
10175 case TYPE_STRING:
10176 return "string";
10177 case TYPE_ARRAY:
10178 return "array";
10179 case TYPE_OBJECT:
10180 return "object";
10181 case TYPE_BOOLEAN:
10182 return "boolean";
10183 case TYPE_EXPREF:
10184 return "expref";
10185 case TYPE_NULL:
10186 return "null";
10187 }
10188 },
10189
10190 _functionKeys: function(resolvedArgs) {
10191 return Object.keys(resolvedArgs[0]);
10192 },
10193
10194 _functionValues: function(resolvedArgs) {
10195 var obj = resolvedArgs[0];
10196 var keys = Object.keys(obj);
10197 var values = [];
10198 for (var i = 0; i < keys.length; i++) {
10199 values.push(obj[keys[i]]);
10200 }
10201 return values;
10202 },
10203
10204 _functionJoin: function(resolvedArgs) {
10205 var joinChar = resolvedArgs[0];
10206 var listJoin = resolvedArgs[1];
10207 return listJoin.join(joinChar);
10208 },
10209
10210 _functionToArray: function(resolvedArgs) {
10211 if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) {
10212 return resolvedArgs[0];
10213 } else {
10214 return [resolvedArgs[0]];
10215 }
10216 },
10217
10218 _functionToString: function(resolvedArgs) {
10219 if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) {
10220 return resolvedArgs[0];
10221 } else {
10222 return JSON.stringify(resolvedArgs[0]);
10223 }
10224 },
10225
10226 _functionToNumber: function(resolvedArgs) {
10227 var typeName = this._getTypeName(resolvedArgs[0]);
10228 var convertedValue;
10229 if (typeName === TYPE_NUMBER) {
10230 return resolvedArgs[0];
10231 } else if (typeName === TYPE_STRING) {
10232 convertedValue = +resolvedArgs[0];
10233 if (!isNaN(convertedValue)) {
10234 return convertedValue;
10235 }
10236 }
10237 return null;
10238 },
10239
10240 _functionNotNull: function(resolvedArgs) {
10241 for (var i = 0; i < resolvedArgs.length; i++) {
10242 if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) {
10243 return resolvedArgs[i];
10244 }
10245 }
10246 return null;
10247 },
10248
10249 _functionSort: function(resolvedArgs) {
10250 var sortedArray = resolvedArgs[0].slice(0);
10251 sortedArray.sort();
10252 return sortedArray;
10253 },
10254
10255 _functionSortBy: function(resolvedArgs) {
10256 var sortedArray = resolvedArgs[0].slice(0);
10257 if (sortedArray.length === 0) {
10258 return sortedArray;
10259 }
10260 var interpreter = this._interpreter;
10261 var exprefNode = resolvedArgs[1];
10262 var requiredType = this._getTypeName(
10263 interpreter.visit(exprefNode, sortedArray[0]));
10264 if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) {
10265 throw new Error("TypeError");
10266 }
10267 var that = this;
10268 // In order to get a stable sort out of an unstable
10269 // sort algorithm, we decorate/sort/undecorate (DSU)
10270 // by creating a new list of [index, element] pairs.
10271 // In the cmp function, if the evaluated elements are
10272 // equal, then the index will be used as the tiebreaker.
10273 // After the decorated list has been sorted, it will be
10274 // undecorated to extract the original elements.
10275 var decorated = [];
10276 for (var i = 0; i < sortedArray.length; i++) {
10277 decorated.push([i, sortedArray[i]]);
10278 }
10279 decorated.sort(function(a, b) {
10280 var exprA = interpreter.visit(exprefNode, a[1]);
10281 var exprB = interpreter.visit(exprefNode, b[1]);
10282 if (that._getTypeName(exprA) !== requiredType) {
10283 throw new Error(
10284 "TypeError: expected " + requiredType + ", received " +
10285 that._getTypeName(exprA));
10286 } else if (that._getTypeName(exprB) !== requiredType) {
10287 throw new Error(
10288 "TypeError: expected " + requiredType + ", received " +
10289 that._getTypeName(exprB));
10290 }
10291 if (exprA > exprB) {
10292 return 1;
10293 } else if (exprA < exprB) {
10294 return -1;
10295 } else {
10296 // If they're equal compare the items by their
10297 // order to maintain relative order of equal keys
10298 // (i.e. to get a stable sort).
10299 return a[0] - b[0];
10300 }
10301 });
10302 // Undecorate: extract out the original list elements.
10303 for (var j = 0; j < decorated.length; j++) {
10304 sortedArray[j] = decorated[j][1];
10305 }
10306 return sortedArray;
10307 },
10308
10309 _functionMaxBy: function(resolvedArgs) {
10310 var exprefNode = resolvedArgs[1];
10311 var resolvedArray = resolvedArgs[0];
10312 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10313 var maxNumber = -Infinity;
10314 var maxRecord;
10315 var current;
10316 for (var i = 0; i < resolvedArray.length; i++) {
10317 current = keyFunction(resolvedArray[i]);
10318 if (current > maxNumber) {
10319 maxNumber = current;
10320 maxRecord = resolvedArray[i];
10321 }
10322 }
10323 return maxRecord;
10324 },
10325
10326 _functionMinBy: function(resolvedArgs) {
10327 var exprefNode = resolvedArgs[1];
10328 var resolvedArray = resolvedArgs[0];
10329 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10330 var minNumber = Infinity;
10331 var minRecord;
10332 var current;
10333 for (var i = 0; i < resolvedArray.length; i++) {
10334 current = keyFunction(resolvedArray[i]);
10335 if (current < minNumber) {
10336 minNumber = current;
10337 minRecord = resolvedArray[i];
10338 }
10339 }
10340 return minRecord;
10341 },
10342
10343 createKeyFunction: function(exprefNode, allowedTypes) {
10344 var that = this;
10345 var interpreter = this._interpreter;
10346 var keyFunc = function(x) {
10347 var current = interpreter.visit(exprefNode, x);
10348 if (allowedTypes.indexOf(that._getTypeName(current)) < 0) {
10349 var msg = "TypeError: expected one of " + allowedTypes +
10350 ", received " + that._getTypeName(current);
10351 throw new Error(msg);
10352 }
10353 return current;
10354 };
10355 return keyFunc;
10356 }
10357
10358 };
10359
10360 function compile(stream) {
10361 var parser = new Parser();
10362 var ast = parser.parse(stream);
10363 return ast;
10364 }
10365
10366 function tokenize(stream) {
10367 var lexer = new Lexer();
10368 return lexer.tokenize(stream);
10369 }
10370
10371 function search(data, expression) {
10372 var parser = new Parser();
10373 // This needs to be improved. Both the interpreter and runtime depend on
10374 // each other. The runtime needs the interpreter to support exprefs.
10375 // There's likely a clean way to avoid the cyclic dependency.
10376 var runtime = new Runtime();
10377 var interpreter = new TreeInterpreter(runtime);
10378 runtime._interpreter = interpreter;
10379 var node = parser.parse(expression);
10380 return interpreter.search(node, data);
10381 }
10382
10383 exports.tokenize = tokenize;
10384 exports.compile = compile;
10385 exports.search = search;
10386 exports.strictDeepEqual = strictDeepEqual;
10387 })( false ? this.jmespath = {} : exports);
10388
10389
10390/***/ }),
10391/* 52 */
10392/***/ (function(module, exports, __webpack_require__) {
10393
10394 var AWS = __webpack_require__(1);
10395 var inherit = AWS.util.inherit;
10396 var jmespath = __webpack_require__(51);
10397
10398 /**
10399 * This class encapsulates the response information
10400 * from a service request operation sent through {AWS.Request}.
10401 * The response object has two main properties for getting information
10402 * back from a request:
10403 *
10404 * ## The `data` property
10405 *
10406 * The `response.data` property contains the serialized object data
10407 * retrieved from the service request. For instance, for an
10408 * Amazon DynamoDB `listTables` method call, the response data might
10409 * look like:
10410 *
10411 * ```
10412 * > resp.data
10413 * { TableNames:
10414 * [ 'table1', 'table2', ... ] }
10415 * ```
10416 *
10417 * The `data` property can be null if an error occurs (see below).
10418 *
10419 * ## The `error` property
10420 *
10421 * In the event of a service error (or transfer error), the
10422 * `response.error` property will be filled with the given
10423 * error data in the form:
10424 *
10425 * ```
10426 * { code: 'SHORT_UNIQUE_ERROR_CODE',
10427 * message: 'Some human readable error message' }
10428 * ```
10429 *
10430 * In the case of an error, the `data` property will be `null`.
10431 * Note that if you handle events that can be in a failure state,
10432 * you should always check whether `response.error` is set
10433 * before attempting to access the `response.data` property.
10434 *
10435 * @!attribute data
10436 * @readonly
10437 * @!group Data Properties
10438 * @note Inside of a {AWS.Request~httpData} event, this
10439 * property contains a single raw packet instead of the
10440 * full de-serialized service response.
10441 * @return [Object] the de-serialized response data
10442 * from the service.
10443 *
10444 * @!attribute error
10445 * An structure containing information about a service
10446 * or networking error.
10447 * @readonly
10448 * @!group Data Properties
10449 * @note This attribute is only filled if a service or
10450 * networking error occurs.
10451 * @return [Error]
10452 * * code [String] a unique short code representing the
10453 * error that was emitted.
10454 * * message [String] a longer human readable error message
10455 * * retryable [Boolean] whether the error message is
10456 * retryable.
10457 * * statusCode [Numeric] in the case of a request that reached the service,
10458 * this value contains the response status code.
10459 * * time [Date] the date time object when the error occurred.
10460 * * hostname [String] set when a networking error occurs to easily
10461 * identify the endpoint of the request.
10462 * * region [String] set when a networking error occurs to easily
10463 * identify the region of the request.
10464 *
10465 * @!attribute requestId
10466 * @readonly
10467 * @!group Data Properties
10468 * @return [String] the unique request ID associated with the response.
10469 * Log this value when debugging requests for AWS support.
10470 *
10471 * @!attribute retryCount
10472 * @readonly
10473 * @!group Operation Properties
10474 * @return [Integer] the number of retries that were
10475 * attempted before the request was completed.
10476 *
10477 * @!attribute redirectCount
10478 * @readonly
10479 * @!group Operation Properties
10480 * @return [Integer] the number of redirects that were
10481 * followed before the request was completed.
10482 *
10483 * @!attribute httpResponse
10484 * @readonly
10485 * @!group HTTP Properties
10486 * @return [AWS.HttpResponse] the raw HTTP response object
10487 * containing the response headers and body information
10488 * from the server.
10489 *
10490 * @see AWS.Request
10491 */
10492 AWS.Response = inherit({
10493
10494 /**
10495 * @api private
10496 */
10497 constructor: function Response(request) {
10498 this.request = request;
10499 this.data = null;
10500 this.error = null;
10501 this.retryCount = 0;
10502 this.redirectCount = 0;
10503 this.httpResponse = new AWS.HttpResponse();
10504 if (request) {
10505 this.maxRetries = request.service.numRetries();
10506 this.maxRedirects = request.service.config.maxRedirects;
10507 }
10508 },
10509
10510 /**
10511 * Creates a new request for the next page of response data, calling the
10512 * callback with the page data if a callback is provided.
10513 *
10514 * @callback callback function(err, data)
10515 * Called when a page of data is returned from the next request.
10516 *
10517 * @param err [Error] an error object, if an error occurred in the request
10518 * @param data [Object] the next page of data, or null, if there are no
10519 * more pages left.
10520 * @return [AWS.Request] the request object for the next page of data
10521 * @return [null] if no callback is provided and there are no pages left
10522 * to retrieve.
10523 * @since v1.4.0
10524 */
10525 nextPage: function nextPage(callback) {
10526 var config;
10527 var service = this.request.service;
10528 var operation = this.request.operation;
10529 try {
10530 config = service.paginationConfig(operation, true);
10531 } catch (e) { this.error = e; }
10532
10533 if (!this.hasNextPage()) {
10534 if (callback) callback(this.error, null);
10535 else if (this.error) throw this.error;
10536 return null;
10537 }
10538
10539 var params = AWS.util.copy(this.request.params);
10540 if (!this.nextPageTokens) {
10541 return callback ? callback(null, null) : null;
10542 } else {
10543 var inputTokens = config.inputToken;
10544 if (typeof inputTokens === 'string') inputTokens = [inputTokens];
10545 for (var i = 0; i < inputTokens.length; i++) {
10546 params[inputTokens[i]] = this.nextPageTokens[i];
10547 }
10548 return service.makeRequest(this.request.operation, params, callback);
10549 }
10550 },
10551
10552 /**
10553 * @return [Boolean] whether more pages of data can be returned by further
10554 * requests
10555 * @since v1.4.0
10556 */
10557 hasNextPage: function hasNextPage() {
10558 this.cacheNextPageTokens();
10559 if (this.nextPageTokens) return true;
10560 if (this.nextPageTokens === undefined) return undefined;
10561 else return false;
10562 },
10563
10564 /**
10565 * @api private
10566 */
10567 cacheNextPageTokens: function cacheNextPageTokens() {
10568 if (Object.prototype.hasOwnProperty.call(this, 'nextPageTokens')) return this.nextPageTokens;
10569 this.nextPageTokens = undefined;
10570
10571 var config = this.request.service.paginationConfig(this.request.operation);
10572 if (!config) return this.nextPageTokens;
10573
10574 this.nextPageTokens = null;
10575 if (config.moreResults) {
10576 if (!jmespath.search(this.data, config.moreResults)) {
10577 return this.nextPageTokens;
10578 }
10579 }
10580
10581 var exprs = config.outputToken;
10582 if (typeof exprs === 'string') exprs = [exprs];
10583 AWS.util.arrayEach.call(this, exprs, function (expr) {
10584 var output = jmespath.search(this.data, expr);
10585 if (output) {
10586 this.nextPageTokens = this.nextPageTokens || [];
10587 this.nextPageTokens.push(output);
10588 }
10589 });
10590
10591 return this.nextPageTokens;
10592 }
10593
10594 });
10595
10596
10597/***/ }),
10598/* 53 */
10599/***/ (function(module, exports, __webpack_require__) {
10600
10601 /**
10602 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
10603 *
10604 * Licensed under the Apache License, Version 2.0 (the "License"). You
10605 * may not use this file except in compliance with the License. A copy of
10606 * the License is located at
10607 *
10608 * http://aws.amazon.com/apache2.0/
10609 *
10610 * or in the "license" file accompanying this file. This file is
10611 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
10612 * ANY KIND, either express or implied. See the License for the specific
10613 * language governing permissions and limitations under the License.
10614 */
10615
10616 var AWS = __webpack_require__(1);
10617 var inherit = AWS.util.inherit;
10618 var jmespath = __webpack_require__(51);
10619
10620 /**
10621 * @api private
10622 */
10623 function CHECK_ACCEPTORS(resp) {
10624 var waiter = resp.request._waiter;
10625 var acceptors = waiter.config.acceptors;
10626 var acceptorMatched = false;
10627 var state = 'retry';
10628
10629 acceptors.forEach(function(acceptor) {
10630 if (!acceptorMatched) {
10631 var matcher = waiter.matchers[acceptor.matcher];
10632 if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) {
10633 acceptorMatched = true;
10634 state = acceptor.state;
10635 }
10636 }
10637 });
10638
10639 if (!acceptorMatched && resp.error) state = 'failure';
10640
10641 if (state === 'success') {
10642 waiter.setSuccess(resp);
10643 } else {
10644 waiter.setError(resp, state === 'retry');
10645 }
10646 }
10647
10648 /**
10649 * @api private
10650 */
10651 AWS.ResourceWaiter = inherit({
10652 /**
10653 * Waits for a given state on a service object
10654 * @param service [Service] the service object to wait on
10655 * @param state [String] the state (defined in waiter configuration) to wait
10656 * for.
10657 * @example Create a waiter for running EC2 instances
10658 * var ec2 = new AWS.EC2;
10659 * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
10660 */
10661 constructor: function constructor(service, state) {
10662 this.service = service;
10663 this.state = state;
10664 this.loadWaiterConfig(this.state);
10665 },
10666
10667 service: null,
10668
10669 state: null,
10670
10671 config: null,
10672
10673 matchers: {
10674 path: function(resp, expected, argument) {
10675 try {
10676 var result = jmespath.search(resp.data, argument);
10677 } catch (err) {
10678 return false;
10679 }
10680
10681 return jmespath.strictDeepEqual(result,expected);
10682 },
10683
10684 pathAll: function(resp, expected, argument) {
10685 try {
10686 var results = jmespath.search(resp.data, argument);
10687 } catch (err) {
10688 return false;
10689 }
10690
10691 if (!Array.isArray(results)) results = [results];
10692 var numResults = results.length;
10693 if (!numResults) return false;
10694 for (var ind = 0 ; ind < numResults; ind++) {
10695 if (!jmespath.strictDeepEqual(results[ind], expected)) {
10696 return false;
10697 }
10698 }
10699 return true;
10700 },
10701
10702 pathAny: function(resp, expected, argument) {
10703 try {
10704 var results = jmespath.search(resp.data, argument);
10705 } catch (err) {
10706 return false;
10707 }
10708
10709 if (!Array.isArray(results)) results = [results];
10710 var numResults = results.length;
10711 for (var ind = 0 ; ind < numResults; ind++) {
10712 if (jmespath.strictDeepEqual(results[ind], expected)) {
10713 return true;
10714 }
10715 }
10716 return false;
10717 },
10718
10719 status: function(resp, expected) {
10720 var statusCode = resp.httpResponse.statusCode;
10721 return (typeof statusCode === 'number') && (statusCode === expected);
10722 },
10723
10724 error: function(resp, expected) {
10725 if (typeof expected === 'string' && resp.error) {
10726 return expected === resp.error.code;
10727 }
10728 // if expected is not string, can be boolean indicating presence of error
10729 return expected === !!resp.error;
10730 }
10731 },
10732
10733 listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) {
10734 add('RETRY_CHECK', 'retry', function(resp) {
10735 var waiter = resp.request._waiter;
10736 if (resp.error && resp.error.code === 'ResourceNotReady') {
10737 resp.error.retryDelay = (waiter.config.delay || 0) * 1000;
10738 }
10739 });
10740
10741 add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS);
10742
10743 add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS);
10744 }),
10745
10746 /**
10747 * @return [AWS.Request]
10748 */
10749 wait: function wait(params, callback) {
10750 if (typeof params === 'function') {
10751 callback = params; params = undefined;
10752 }
10753
10754 if (params && params.$waiter) {
10755 params = AWS.util.copy(params);
10756 if (typeof params.$waiter.delay === 'number') {
10757 this.config.delay = params.$waiter.delay;
10758 }
10759 if (typeof params.$waiter.maxAttempts === 'number') {
10760 this.config.maxAttempts = params.$waiter.maxAttempts;
10761 }
10762 delete params.$waiter;
10763 }
10764
10765 var request = this.service.makeRequest(this.config.operation, params);
10766 request._waiter = this;
10767 request.response.maxRetries = this.config.maxAttempts;
10768 request.addListeners(this.listeners);
10769
10770 if (callback) request.send(callback);
10771 return request;
10772 },
10773
10774 setSuccess: function setSuccess(resp) {
10775 resp.error = null;
10776 resp.data = resp.data || {};
10777 resp.request.removeAllListeners('extractData');
10778 },
10779
10780 setError: function setError(resp, retryable) {
10781 resp.data = null;
10782 resp.error = AWS.util.error(resp.error || new Error(), {
10783 code: 'ResourceNotReady',
10784 message: 'Resource is not in the state ' + this.state,
10785 retryable: retryable
10786 });
10787 },
10788
10789 /**
10790 * Loads waiter configuration from API configuration
10791 *
10792 * @api private
10793 */
10794 loadWaiterConfig: function loadWaiterConfig(state) {
10795 if (!this.service.api.waiters[state]) {
10796 throw new AWS.util.error(new Error(), {
10797 code: 'StateNotFoundError',
10798 message: 'State ' + state + ' not found.'
10799 });
10800 }
10801
10802 this.config = AWS.util.copy(this.service.api.waiters[state]);
10803 }
10804 });
10805
10806
10807/***/ }),
10808/* 54 */
10809/***/ (function(module, exports, __webpack_require__) {
10810
10811 var AWS = __webpack_require__(1);
10812
10813 var inherit = AWS.util.inherit;
10814
10815 /**
10816 * @api private
10817 */
10818 AWS.Signers.RequestSigner = inherit({
10819 constructor: function RequestSigner(request) {
10820 this.request = request;
10821 },
10822
10823 setServiceClientId: function setServiceClientId(id) {
10824 this.serviceClientId = id;
10825 },
10826
10827 getServiceClientId: function getServiceClientId() {
10828 return this.serviceClientId;
10829 }
10830 });
10831
10832 AWS.Signers.RequestSigner.getVersion = function getVersion(version) {
10833 switch (version) {
10834 case 'v2': return AWS.Signers.V2;
10835 case 'v3': return AWS.Signers.V3;
10836 case 's3v4': return AWS.Signers.V4;
10837 case 'v4': return AWS.Signers.V4;
10838 case 's3': return AWS.Signers.S3;
10839 case 'v3https': return AWS.Signers.V3Https;
10840 }
10841 throw new Error('Unknown signing version ' + version);
10842 };
10843
10844 __webpack_require__(55);
10845 __webpack_require__(56);
10846 __webpack_require__(57);
10847 __webpack_require__(58);
10848 __webpack_require__(60);
10849 __webpack_require__(61);
10850
10851
10852/***/ }),
10853/* 55 */
10854/***/ (function(module, exports, __webpack_require__) {
10855
10856 var AWS = __webpack_require__(1);
10857 var inherit = AWS.util.inherit;
10858
10859 /**
10860 * @api private
10861 */
10862 AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, {
10863 addAuthorization: function addAuthorization(credentials, date) {
10864
10865 if (!date) date = AWS.util.date.getDate();
10866
10867 var r = this.request;
10868
10869 r.params.Timestamp = AWS.util.date.iso8601(date);
10870 r.params.SignatureVersion = '2';
10871 r.params.SignatureMethod = 'HmacSHA256';
10872 r.params.AWSAccessKeyId = credentials.accessKeyId;
10873
10874 if (credentials.sessionToken) {
10875 r.params.SecurityToken = credentials.sessionToken;
10876 }
10877
10878 delete r.params.Signature; // delete old Signature for re-signing
10879 r.params.Signature = this.signature(credentials);
10880
10881 r.body = AWS.util.queryParamsToString(r.params);
10882 r.headers['Content-Length'] = r.body.length;
10883 },
10884
10885 signature: function signature(credentials) {
10886 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
10887 },
10888
10889 stringToSign: function stringToSign() {
10890 var parts = [];
10891 parts.push(this.request.method);
10892 parts.push(this.request.endpoint.host.toLowerCase());
10893 parts.push(this.request.pathname());
10894 parts.push(AWS.util.queryParamsToString(this.request.params));
10895 return parts.join('\n');
10896 }
10897
10898 });
10899
10900 /**
10901 * @api private
10902 */
10903 module.exports = AWS.Signers.V2;
10904
10905
10906/***/ }),
10907/* 56 */
10908/***/ (function(module, exports, __webpack_require__) {
10909
10910 var AWS = __webpack_require__(1);
10911 var inherit = AWS.util.inherit;
10912
10913 /**
10914 * @api private
10915 */
10916 AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, {
10917 addAuthorization: function addAuthorization(credentials, date) {
10918
10919 var datetime = AWS.util.date.rfc822(date);
10920
10921 this.request.headers['X-Amz-Date'] = datetime;
10922
10923 if (credentials.sessionToken) {
10924 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
10925 }
10926
10927 this.request.headers['X-Amzn-Authorization'] =
10928 this.authorization(credentials, datetime);
10929
10930 },
10931
10932 authorization: function authorization(credentials) {
10933 return 'AWS3 ' +
10934 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
10935 'Algorithm=HmacSHA256,' +
10936 'SignedHeaders=' + this.signedHeaders() + ',' +
10937 'Signature=' + this.signature(credentials);
10938 },
10939
10940 signedHeaders: function signedHeaders() {
10941 var headers = [];
10942 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
10943 headers.push(h.toLowerCase());
10944 });
10945 return headers.sort().join(';');
10946 },
10947
10948 canonicalHeaders: function canonicalHeaders() {
10949 var headers = this.request.headers;
10950 var parts = [];
10951 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
10952 parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim());
10953 });
10954 return parts.sort().join('\n') + '\n';
10955 },
10956
10957 headersToSign: function headersToSign() {
10958 var headers = [];
10959 AWS.util.each(this.request.headers, function iterator(k) {
10960 if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) {
10961 headers.push(k);
10962 }
10963 });
10964 return headers;
10965 },
10966
10967 signature: function signature(credentials) {
10968 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
10969 },
10970
10971 stringToSign: function stringToSign() {
10972 var parts = [];
10973 parts.push(this.request.method);
10974 parts.push('/');
10975 parts.push('');
10976 parts.push(this.canonicalHeaders());
10977 parts.push(this.request.body);
10978 return AWS.util.crypto.sha256(parts.join('\n'));
10979 }
10980
10981 });
10982
10983 /**
10984 * @api private
10985 */
10986 module.exports = AWS.Signers.V3;
10987
10988
10989/***/ }),
10990/* 57 */
10991/***/ (function(module, exports, __webpack_require__) {
10992
10993 var AWS = __webpack_require__(1);
10994 var inherit = AWS.util.inherit;
10995
10996 __webpack_require__(56);
10997
10998 /**
10999 * @api private
11000 */
11001 AWS.Signers.V3Https = inherit(AWS.Signers.V3, {
11002 authorization: function authorization(credentials) {
11003 return 'AWS3-HTTPS ' +
11004 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
11005 'Algorithm=HmacSHA256,' +
11006 'Signature=' + this.signature(credentials);
11007 },
11008
11009 stringToSign: function stringToSign() {
11010 return this.request.headers['X-Amz-Date'];
11011 }
11012 });
11013
11014 /**
11015 * @api private
11016 */
11017 module.exports = AWS.Signers.V3Https;
11018
11019
11020/***/ }),
11021/* 58 */
11022/***/ (function(module, exports, __webpack_require__) {
11023
11024 var AWS = __webpack_require__(1);
11025 var v4Credentials = __webpack_require__(59);
11026 var inherit = AWS.util.inherit;
11027
11028 /**
11029 * @api private
11030 */
11031 var expiresHeader = 'presigned-expires';
11032
11033 /**
11034 * @api private
11035 */
11036 AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, {
11037 constructor: function V4(request, serviceName, options) {
11038 AWS.Signers.RequestSigner.call(this, request);
11039 this.serviceName = serviceName;
11040 options = options || {};
11041 this.signatureCache = typeof options.signatureCache === 'boolean' ? options.signatureCache : true;
11042 this.operation = options.operation;
11043 this.signatureVersion = options.signatureVersion;
11044 },
11045
11046 algorithm: 'AWS4-HMAC-SHA256',
11047
11048 addAuthorization: function addAuthorization(credentials, date) {
11049 var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '');
11050
11051 if (this.isPresigned()) {
11052 this.updateForPresigned(credentials, datetime);
11053 } else {
11054 this.addHeaders(credentials, datetime);
11055 }
11056
11057 this.request.headers['Authorization'] =
11058 this.authorization(credentials, datetime);
11059 },
11060
11061 addHeaders: function addHeaders(credentials, datetime) {
11062 this.request.headers['X-Amz-Date'] = datetime;
11063 if (credentials.sessionToken) {
11064 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11065 }
11066 },
11067
11068 updateForPresigned: function updateForPresigned(credentials, datetime) {
11069 var credString = this.credentialString(datetime);
11070 var qs = {
11071 'X-Amz-Date': datetime,
11072 'X-Amz-Algorithm': this.algorithm,
11073 'X-Amz-Credential': credentials.accessKeyId + '/' + credString,
11074 'X-Amz-Expires': this.request.headers[expiresHeader],
11075 'X-Amz-SignedHeaders': this.signedHeaders()
11076 };
11077
11078 if (credentials.sessionToken) {
11079 qs['X-Amz-Security-Token'] = credentials.sessionToken;
11080 }
11081
11082 if (this.request.headers['Content-Type']) {
11083 qs['Content-Type'] = this.request.headers['Content-Type'];
11084 }
11085 if (this.request.headers['Content-MD5']) {
11086 qs['Content-MD5'] = this.request.headers['Content-MD5'];
11087 }
11088 if (this.request.headers['Cache-Control']) {
11089 qs['Cache-Control'] = this.request.headers['Cache-Control'];
11090 }
11091
11092 // need to pull in any other X-Amz-* headers
11093 AWS.util.each.call(this, this.request.headers, function(key, value) {
11094 if (key === expiresHeader) return;
11095 if (this.isSignableHeader(key)) {
11096 var lowerKey = key.toLowerCase();
11097 // Metadata should be normalized
11098 if (lowerKey.indexOf('x-amz-meta-') === 0) {
11099 qs[lowerKey] = value;
11100 } else if (lowerKey.indexOf('x-amz-') === 0) {
11101 qs[key] = value;
11102 }
11103 }
11104 });
11105
11106 var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?';
11107 this.request.path += sep + AWS.util.queryParamsToString(qs);
11108 },
11109
11110 authorization: function authorization(credentials, datetime) {
11111 var parts = [];
11112 var credString = this.credentialString(datetime);
11113 parts.push(this.algorithm + ' Credential=' +
11114 credentials.accessKeyId + '/' + credString);
11115 parts.push('SignedHeaders=' + this.signedHeaders());
11116 parts.push('Signature=' + this.signature(credentials, datetime));
11117 return parts.join(', ');
11118 },
11119
11120 signature: function signature(credentials, datetime) {
11121 var signingKey = v4Credentials.getSigningKey(
11122 credentials,
11123 datetime.substr(0, 8),
11124 this.request.region,
11125 this.serviceName,
11126 this.signatureCache
11127 );
11128 return AWS.util.crypto.hmac(signingKey, this.stringToSign(datetime), 'hex');
11129 },
11130
11131 stringToSign: function stringToSign(datetime) {
11132 var parts = [];
11133 parts.push('AWS4-HMAC-SHA256');
11134 parts.push(datetime);
11135 parts.push(this.credentialString(datetime));
11136 parts.push(this.hexEncodedHash(this.canonicalString()));
11137 return parts.join('\n');
11138 },
11139
11140 canonicalString: function canonicalString() {
11141 var parts = [], pathname = this.request.pathname();
11142 if (this.serviceName !== 's3' && this.signatureVersion !== 's3v4') pathname = AWS.util.uriEscapePath(pathname);
11143
11144 parts.push(this.request.method);
11145 parts.push(pathname);
11146 parts.push(this.request.search());
11147 parts.push(this.canonicalHeaders() + '\n');
11148 parts.push(this.signedHeaders());
11149 parts.push(this.hexEncodedBodyHash());
11150 return parts.join('\n');
11151 },
11152
11153 canonicalHeaders: function canonicalHeaders() {
11154 var headers = [];
11155 AWS.util.each.call(this, this.request.headers, function (key, item) {
11156 headers.push([key, item]);
11157 });
11158 headers.sort(function (a, b) {
11159 return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
11160 });
11161 var parts = [];
11162 AWS.util.arrayEach.call(this, headers, function (item) {
11163 var key = item[0].toLowerCase();
11164 if (this.isSignableHeader(key)) {
11165 var value = item[1];
11166 if (typeof value === 'undefined' || value === null || typeof value.toString !== 'function') {
11167 throw AWS.util.error(new Error('Header ' + key + ' contains invalid value'), {
11168 code: 'InvalidHeader'
11169 });
11170 }
11171 parts.push(key + ':' +
11172 this.canonicalHeaderValues(value.toString()));
11173 }
11174 });
11175 return parts.join('\n');
11176 },
11177
11178 canonicalHeaderValues: function canonicalHeaderValues(values) {
11179 return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
11180 },
11181
11182 signedHeaders: function signedHeaders() {
11183 var keys = [];
11184 AWS.util.each.call(this, this.request.headers, function (key) {
11185 key = key.toLowerCase();
11186 if (this.isSignableHeader(key)) keys.push(key);
11187 });
11188 return keys.sort().join(';');
11189 },
11190
11191 credentialString: function credentialString(datetime) {
11192 return v4Credentials.createScope(
11193 datetime.substr(0, 8),
11194 this.request.region,
11195 this.serviceName
11196 );
11197 },
11198
11199 hexEncodedHash: function hash(string) {
11200 return AWS.util.crypto.sha256(string, 'hex');
11201 },
11202
11203 hexEncodedBodyHash: function hexEncodedBodyHash() {
11204 var request = this.request;
11205 if (this.isPresigned() && this.serviceName === 's3' && !request.body) {
11206 return 'UNSIGNED-PAYLOAD';
11207 } else if (request.headers['X-Amz-Content-Sha256']) {
11208 return request.headers['X-Amz-Content-Sha256'];
11209 } else {
11210 return this.hexEncodedHash(this.request.body || '');
11211 }
11212 },
11213
11214 unsignableHeaders: [
11215 'authorization',
11216 'content-type',
11217 'content-length',
11218 'user-agent',
11219 expiresHeader,
11220 'expect',
11221 'x-amzn-trace-id'
11222 ],
11223
11224 isSignableHeader: function isSignableHeader(key) {
11225 if (key.toLowerCase().indexOf('x-amz-') === 0) return true;
11226 return this.unsignableHeaders.indexOf(key) < 0;
11227 },
11228
11229 isPresigned: function isPresigned() {
11230 return this.request.headers[expiresHeader] ? true : false;
11231 }
11232
11233 });
11234
11235 /**
11236 * @api private
11237 */
11238 module.exports = AWS.Signers.V4;
11239
11240
11241/***/ }),
11242/* 59 */
11243/***/ (function(module, exports, __webpack_require__) {
11244
11245 var AWS = __webpack_require__(1);
11246
11247 /**
11248 * @api private
11249 */
11250 var cachedSecret = {};
11251
11252 /**
11253 * @api private
11254 */
11255 var cacheQueue = [];
11256
11257 /**
11258 * @api private
11259 */
11260 var maxCacheEntries = 50;
11261
11262 /**
11263 * @api private
11264 */
11265 var v4Identifier = 'aws4_request';
11266
11267 /**
11268 * @api private
11269 */
11270 module.exports = {
11271 /**
11272 * @api private
11273 *
11274 * @param date [String]
11275 * @param region [String]
11276 * @param serviceName [String]
11277 * @return [String]
11278 */
11279 createScope: function createScope(date, region, serviceName) {
11280 return [
11281 date.substr(0, 8),
11282 region,
11283 serviceName,
11284 v4Identifier
11285 ].join('/');
11286 },
11287
11288 /**
11289 * @api private
11290 *
11291 * @param credentials [Credentials]
11292 * @param date [String]
11293 * @param region [String]
11294 * @param service [String]
11295 * @param shouldCache [Boolean]
11296 * @return [String]
11297 */
11298 getSigningKey: function getSigningKey(
11299 credentials,
11300 date,
11301 region,
11302 service,
11303 shouldCache
11304 ) {
11305 var credsIdentifier = AWS.util.crypto
11306 .hmac(credentials.secretAccessKey, credentials.accessKeyId, 'base64');
11307 var cacheKey = [credsIdentifier, date, region, service].join('_');
11308 shouldCache = shouldCache !== false;
11309 if (shouldCache && (cacheKey in cachedSecret)) {
11310 return cachedSecret[cacheKey];
11311 }
11312
11313 var kDate = AWS.util.crypto.hmac(
11314 'AWS4' + credentials.secretAccessKey,
11315 date,
11316 'buffer'
11317 );
11318 var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer');
11319 var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer');
11320
11321 var signingKey = AWS.util.crypto.hmac(kService, v4Identifier, 'buffer');
11322 if (shouldCache) {
11323 cachedSecret[cacheKey] = signingKey;
11324 cacheQueue.push(cacheKey);
11325 if (cacheQueue.length > maxCacheEntries) {
11326 // remove the oldest entry (not the least recently used)
11327 delete cachedSecret[cacheQueue.shift()];
11328 }
11329 }
11330
11331 return signingKey;
11332 },
11333
11334 /**
11335 * @api private
11336 *
11337 * Empties the derived signing key cache. Made available for testing purposes
11338 * only.
11339 */
11340 emptyCache: function emptyCache() {
11341 cachedSecret = {};
11342 cacheQueue = [];
11343 }
11344 };
11345
11346
11347/***/ }),
11348/* 60 */
11349/***/ (function(module, exports, __webpack_require__) {
11350
11351 var AWS = __webpack_require__(1);
11352 var inherit = AWS.util.inherit;
11353
11354 /**
11355 * @api private
11356 */
11357 AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, {
11358 /**
11359 * When building the stringToSign, these sub resource params should be
11360 * part of the canonical resource string with their NON-decoded values
11361 */
11362 subResources: {
11363 'acl': 1,
11364 'accelerate': 1,
11365 'analytics': 1,
11366 'cors': 1,
11367 'lifecycle': 1,
11368 'delete': 1,
11369 'inventory': 1,
11370 'location': 1,
11371 'logging': 1,
11372 'metrics': 1,
11373 'notification': 1,
11374 'partNumber': 1,
11375 'policy': 1,
11376 'requestPayment': 1,
11377 'replication': 1,
11378 'restore': 1,
11379 'tagging': 1,
11380 'torrent': 1,
11381 'uploadId': 1,
11382 'uploads': 1,
11383 'versionId': 1,
11384 'versioning': 1,
11385 'versions': 1,
11386 'website': 1
11387 },
11388
11389 // when building the stringToSign, these querystring params should be
11390 // part of the canonical resource string with their NON-encoded values
11391 responseHeaders: {
11392 'response-content-type': 1,
11393 'response-content-language': 1,
11394 'response-expires': 1,
11395 'response-cache-control': 1,
11396 'response-content-disposition': 1,
11397 'response-content-encoding': 1
11398 },
11399
11400 addAuthorization: function addAuthorization(credentials, date) {
11401 if (!this.request.headers['presigned-expires']) {
11402 this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date);
11403 }
11404
11405 if (credentials.sessionToken) {
11406 // presigned URLs require this header to be lowercased
11407 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11408 }
11409
11410 var signature = this.sign(credentials.secretAccessKey, this.stringToSign());
11411 var auth = 'AWS ' + credentials.accessKeyId + ':' + signature;
11412
11413 this.request.headers['Authorization'] = auth;
11414 },
11415
11416 stringToSign: function stringToSign() {
11417 var r = this.request;
11418
11419 var parts = [];
11420 parts.push(r.method);
11421 parts.push(r.headers['Content-MD5'] || '');
11422 parts.push(r.headers['Content-Type'] || '');
11423
11424 // This is the "Date" header, but we use X-Amz-Date.
11425 // The S3 signing mechanism requires us to pass an empty
11426 // string for this Date header regardless.
11427 parts.push(r.headers['presigned-expires'] || '');
11428
11429 var headers = this.canonicalizedAmzHeaders();
11430 if (headers) parts.push(headers);
11431 parts.push(this.canonicalizedResource());
11432
11433 return parts.join('\n');
11434
11435 },
11436
11437 canonicalizedAmzHeaders: function canonicalizedAmzHeaders() {
11438
11439 var amzHeaders = [];
11440
11441 AWS.util.each(this.request.headers, function (name) {
11442 if (name.match(/^x-amz-/i))
11443 amzHeaders.push(name);
11444 });
11445
11446 amzHeaders.sort(function (a, b) {
11447 return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
11448 });
11449
11450 var parts = [];
11451 AWS.util.arrayEach.call(this, amzHeaders, function (name) {
11452 parts.push(name.toLowerCase() + ':' + String(this.request.headers[name]));
11453 });
11454
11455 return parts.join('\n');
11456
11457 },
11458
11459 canonicalizedResource: function canonicalizedResource() {
11460
11461 var r = this.request;
11462
11463 var parts = r.path.split('?');
11464 var path = parts[0];
11465 var querystring = parts[1];
11466
11467 var resource = '';
11468
11469 if (r.virtualHostedBucket)
11470 resource += '/' + r.virtualHostedBucket;
11471
11472 resource += path;
11473
11474 if (querystring) {
11475
11476 // collect a list of sub resources and query params that need to be signed
11477 var resources = [];
11478
11479 AWS.util.arrayEach.call(this, querystring.split('&'), function (param) {
11480 var name = param.split('=')[0];
11481 var value = param.split('=')[1];
11482 if (this.subResources[name] || this.responseHeaders[name]) {
11483 var subresource = { name: name };
11484 if (value !== undefined) {
11485 if (this.subResources[name]) {
11486 subresource.value = value;
11487 } else {
11488 subresource.value = decodeURIComponent(value);
11489 }
11490 }
11491 resources.push(subresource);
11492 }
11493 });
11494
11495 resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; });
11496
11497 if (resources.length) {
11498
11499 querystring = [];
11500 AWS.util.arrayEach(resources, function (res) {
11501 if (res.value === undefined) {
11502 querystring.push(res.name);
11503 } else {
11504 querystring.push(res.name + '=' + res.value);
11505 }
11506 });
11507
11508 resource += '?' + querystring.join('&');
11509 }
11510
11511 }
11512
11513 return resource;
11514
11515 },
11516
11517 sign: function sign(secret, string) {
11518 return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1');
11519 }
11520 });
11521
11522 /**
11523 * @api private
11524 */
11525 module.exports = AWS.Signers.S3;
11526
11527
11528/***/ }),
11529/* 61 */
11530/***/ (function(module, exports, __webpack_require__) {
11531
11532 var AWS = __webpack_require__(1);
11533 var inherit = AWS.util.inherit;
11534
11535 /**
11536 * @api private
11537 */
11538 var expiresHeader = 'presigned-expires';
11539
11540 /**
11541 * @api private
11542 */
11543 function signedUrlBuilder(request) {
11544 var expires = request.httpRequest.headers[expiresHeader];
11545 var signerClass = request.service.getSignerClass(request);
11546
11547 delete request.httpRequest.headers['User-Agent'];
11548 delete request.httpRequest.headers['X-Amz-User-Agent'];
11549
11550 if (signerClass === AWS.Signers.V4) {
11551 if (expires > 604800) { // one week expiry is invalid
11552 var message = 'Presigning does not support expiry time greater ' +
11553 'than a week with SigV4 signing.';
11554 throw AWS.util.error(new Error(), {
11555 code: 'InvalidExpiryTime', message: message, retryable: false
11556 });
11557 }
11558 request.httpRequest.headers[expiresHeader] = expires;
11559 } else if (signerClass === AWS.Signers.S3) {
11560 var now = request.service ? request.service.getSkewCorrectedDate() : AWS.util.date.getDate();
11561 request.httpRequest.headers[expiresHeader] = parseInt(
11562 AWS.util.date.unixTimestamp(now) + expires, 10).toString();
11563 } else {
11564 throw AWS.util.error(new Error(), {
11565 message: 'Presigning only supports S3 or SigV4 signing.',
11566 code: 'UnsupportedSigner', retryable: false
11567 });
11568 }
11569 }
11570
11571 /**
11572 * @api private
11573 */
11574 function signedUrlSigner(request) {
11575 var endpoint = request.httpRequest.endpoint;
11576 var parsedUrl = AWS.util.urlParse(request.httpRequest.path);
11577 var queryParams = {};
11578
11579 if (parsedUrl.search) {
11580 queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1));
11581 }
11582
11583 var auth = request.httpRequest.headers['Authorization'].split(' ');
11584 if (auth[0] === 'AWS') {
11585 auth = auth[1].split(':');
11586 queryParams['AWSAccessKeyId'] = auth[0];
11587 queryParams['Signature'] = auth[1];
11588
11589 AWS.util.each(request.httpRequest.headers, function (key, value) {
11590 if (key === expiresHeader) key = 'Expires';
11591 if (key.indexOf('x-amz-meta-') === 0) {
11592 // Delete existing, potentially not normalized key
11593 delete queryParams[key];
11594 key = key.toLowerCase();
11595 }
11596 queryParams[key] = value;
11597 });
11598 delete request.httpRequest.headers[expiresHeader];
11599 delete queryParams['Authorization'];
11600 delete queryParams['Host'];
11601 } else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing
11602 auth.shift();
11603 var rest = auth.join(' ');
11604 var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];
11605 queryParams['X-Amz-Signature'] = signature;
11606 delete queryParams['Expires'];
11607 }
11608
11609 // build URL
11610 endpoint.pathname = parsedUrl.pathname;
11611 endpoint.search = AWS.util.queryParamsToString(queryParams);
11612 }
11613
11614 /**
11615 * @api private
11616 */
11617 AWS.Signers.Presign = inherit({
11618 /**
11619 * @api private
11620 */
11621 sign: function sign(request, expireTime, callback) {
11622 request.httpRequest.headers[expiresHeader] = expireTime || 3600;
11623 request.on('build', signedUrlBuilder);
11624 request.on('sign', signedUrlSigner);
11625 request.removeListener('afterBuild',
11626 AWS.EventListeners.Core.SET_CONTENT_LENGTH);
11627 request.removeListener('afterBuild',
11628 AWS.EventListeners.Core.COMPUTE_SHA256);
11629
11630 request.emit('beforePresign', [request]);
11631
11632 if (callback) {
11633 request.build(function() {
11634 if (this.response.error) callback(this.response.error);
11635 else {
11636 callback(null, AWS.util.urlFormat(request.httpRequest.endpoint));
11637 }
11638 });
11639 } else {
11640 request.build();
11641 if (request.response.error) throw request.response.error;
11642 return AWS.util.urlFormat(request.httpRequest.endpoint);
11643 }
11644 }
11645 });
11646
11647 /**
11648 * @api private
11649 */
11650 module.exports = AWS.Signers.Presign;
11651
11652
11653/***/ }),
11654/* 62 */
11655/***/ (function(module, exports, __webpack_require__) {
11656
11657 var AWS = __webpack_require__(1);
11658
11659 /**
11660 * @api private
11661 */
11662 AWS.ParamValidator = AWS.util.inherit({
11663 /**
11664 * Create a new validator object.
11665 *
11666 * @param validation [Boolean|map] whether input parameters should be
11667 * validated against the operation description before sending the
11668 * request. Pass a map to enable any of the following specific
11669 * validation features:
11670 *
11671 * * **min** [Boolean] &mdash; Validates that a value meets the min
11672 * constraint. This is enabled by default when paramValidation is set
11673 * to `true`.
11674 * * **max** [Boolean] &mdash; Validates that a value meets the max
11675 * constraint.
11676 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
11677 * regular expression.
11678 * * **enum** [Boolean] &mdash; Validates that a string value matches one
11679 * of the allowable enum values.
11680 */
11681 constructor: function ParamValidator(validation) {
11682 if (validation === true || validation === undefined) {
11683 validation = {'min': true};
11684 }
11685 this.validation = validation;
11686 },
11687
11688 validate: function validate(shape, params, context) {
11689 this.errors = [];
11690 this.validateMember(shape, params || {}, context || 'params');
11691
11692 if (this.errors.length > 1) {
11693 var msg = this.errors.join('\n* ');
11694 msg = 'There were ' + this.errors.length +
11695 ' validation errors:\n* ' + msg;
11696 throw AWS.util.error(new Error(msg),
11697 {code: 'MultipleValidationErrors', errors: this.errors});
11698 } else if (this.errors.length === 1) {
11699 throw this.errors[0];
11700 } else {
11701 return true;
11702 }
11703 },
11704
11705 fail: function fail(code, message) {
11706 this.errors.push(AWS.util.error(new Error(message), {code: code}));
11707 },
11708
11709 validateStructure: function validateStructure(shape, params, context) {
11710 this.validateType(params, context, ['object'], 'structure');
11711
11712 var paramName;
11713 for (var i = 0; shape.required && i < shape.required.length; i++) {
11714 paramName = shape.required[i];
11715 var value = params[paramName];
11716 if (value === undefined || value === null) {
11717 this.fail('MissingRequiredParameter',
11718 'Missing required key \'' + paramName + '\' in ' + context);
11719 }
11720 }
11721
11722 // validate hash members
11723 for (paramName in params) {
11724 if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue;
11725
11726 var paramValue = params[paramName],
11727 memberShape = shape.members[paramName];
11728
11729 if (memberShape !== undefined) {
11730 var memberContext = [context, paramName].join('.');
11731 this.validateMember(memberShape, paramValue, memberContext);
11732 } else {
11733 this.fail('UnexpectedParameter',
11734 'Unexpected key \'' + paramName + '\' found in ' + context);
11735 }
11736 }
11737
11738 return true;
11739 },
11740
11741 validateMember: function validateMember(shape, param, context) {
11742 switch (shape.type) {
11743 case 'structure':
11744 return this.validateStructure(shape, param, context);
11745 case 'list':
11746 return this.validateList(shape, param, context);
11747 case 'map':
11748 return this.validateMap(shape, param, context);
11749 default:
11750 return this.validateScalar(shape, param, context);
11751 }
11752 },
11753
11754 validateList: function validateList(shape, params, context) {
11755 if (this.validateType(params, context, [Array])) {
11756 this.validateRange(shape, params.length, context, 'list member count');
11757 // validate array members
11758 for (var i = 0; i < params.length; i++) {
11759 this.validateMember(shape.member, params[i], context + '[' + i + ']');
11760 }
11761 }
11762 },
11763
11764 validateMap: function validateMap(shape, params, context) {
11765 if (this.validateType(params, context, ['object'], 'map')) {
11766 // Build up a count of map members to validate range traits.
11767 var mapCount = 0;
11768 for (var param in params) {
11769 if (!Object.prototype.hasOwnProperty.call(params, param)) continue;
11770 // Validate any map key trait constraints
11771 this.validateMember(shape.key, param,
11772 context + '[key=\'' + param + '\']');
11773 this.validateMember(shape.value, params[param],
11774 context + '[\'' + param + '\']');
11775 mapCount++;
11776 }
11777 this.validateRange(shape, mapCount, context, 'map member count');
11778 }
11779 },
11780
11781 validateScalar: function validateScalar(shape, value, context) {
11782 switch (shape.type) {
11783 case null:
11784 case undefined:
11785 case 'string':
11786 return this.validateString(shape, value, context);
11787 case 'base64':
11788 case 'binary':
11789 return this.validatePayload(value, context);
11790 case 'integer':
11791 case 'float':
11792 return this.validateNumber(shape, value, context);
11793 case 'boolean':
11794 return this.validateType(value, context, ['boolean']);
11795 case 'timestamp':
11796 return this.validateType(value, context, [Date,
11797 /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'],
11798 'Date object, ISO-8601 string, or a UNIX timestamp');
11799 default:
11800 return this.fail('UnkownType', 'Unhandled type ' +
11801 shape.type + ' for ' + context);
11802 }
11803 },
11804
11805 validateString: function validateString(shape, value, context) {
11806 var validTypes = ['string'];
11807 if (shape.isJsonValue) {
11808 validTypes = validTypes.concat(['number', 'object', 'boolean']);
11809 }
11810 if (value !== null && this.validateType(value, context, validTypes)) {
11811 this.validateEnum(shape, value, context);
11812 this.validateRange(shape, value.length, context, 'string length');
11813 this.validatePattern(shape, value, context);
11814 this.validateUri(shape, value, context);
11815 }
11816 },
11817
11818 validateUri: function validateUri(shape, value, context) {
11819 if (shape['location'] === 'uri') {
11820 if (value.length === 0) {
11821 this.fail('UriParameterError', 'Expected uri parameter to have length >= 1,'
11822 + ' but found "' + value +'" for ' + context);
11823 }
11824 }
11825 },
11826
11827 validatePattern: function validatePattern(shape, value, context) {
11828 if (this.validation['pattern'] && shape['pattern'] !== undefined) {
11829 if (!(new RegExp(shape['pattern'])).test(value)) {
11830 this.fail('PatternMatchError', 'Provided value "' + value + '" '
11831 + 'does not match regex pattern /' + shape['pattern'] + '/ for '
11832 + context);
11833 }
11834 }
11835 },
11836
11837 validateRange: function validateRange(shape, value, context, descriptor) {
11838 if (this.validation['min']) {
11839 if (shape['min'] !== undefined && value < shape['min']) {
11840 this.fail('MinRangeError', 'Expected ' + descriptor + ' >= '
11841 + shape['min'] + ', but found ' + value + ' for ' + context);
11842 }
11843 }
11844 if (this.validation['max']) {
11845 if (shape['max'] !== undefined && value > shape['max']) {
11846 this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= '
11847 + shape['max'] + ', but found ' + value + ' for ' + context);
11848 }
11849 }
11850 },
11851
11852 validateEnum: function validateRange(shape, value, context) {
11853 if (this.validation['enum'] && shape['enum'] !== undefined) {
11854 // Fail if the string value is not present in the enum list
11855 if (shape['enum'].indexOf(value) === -1) {
11856 this.fail('EnumError', 'Found string value of ' + value + ', but '
11857 + 'expected ' + shape['enum'].join('|') + ' for ' + context);
11858 }
11859 }
11860 },
11861
11862 validateType: function validateType(value, context, acceptedTypes, type) {
11863 // We will not log an error for null or undefined, but we will return
11864 // false so that callers know that the expected type was not strictly met.
11865 if (value === null || value === undefined) return false;
11866
11867 var foundInvalidType = false;
11868 for (var i = 0; i < acceptedTypes.length; i++) {
11869 if (typeof acceptedTypes[i] === 'string') {
11870 if (typeof value === acceptedTypes[i]) return true;
11871 } else if (acceptedTypes[i] instanceof RegExp) {
11872 if ((value || '').toString().match(acceptedTypes[i])) return true;
11873 } else {
11874 if (value instanceof acceptedTypes[i]) return true;
11875 if (AWS.util.isType(value, acceptedTypes[i])) return true;
11876 if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice();
11877 acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]);
11878 }
11879 foundInvalidType = true;
11880 }
11881
11882 var acceptedType = type;
11883 if (!acceptedType) {
11884 acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1');
11885 }
11886
11887 var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : '';
11888 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' +
11889 vowel + ' ' + acceptedType);
11890 return false;
11891 },
11892
11893 validateNumber: function validateNumber(shape, value, context) {
11894 if (value === null || value === undefined) return;
11895 if (typeof value === 'string') {
11896 var castedValue = parseFloat(value);
11897 if (castedValue.toString() === value) value = castedValue;
11898 }
11899 if (this.validateType(value, context, ['number'])) {
11900 this.validateRange(shape, value, context, 'numeric value');
11901 }
11902 },
11903
11904 validatePayload: function validatePayload(value, context) {
11905 if (value === null || value === undefined) return;
11906 if (typeof value === 'string') return;
11907 if (value && typeof value.byteLength === 'number') return; // typed arrays
11908 if (AWS.util.isNode()) { // special check for buffer/stream in Node.js
11909 var Stream = AWS.util.stream.Stream;
11910 if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return;
11911 } else {
11912 if (typeof Blob !== void 0 && value instanceof Blob) return;
11913 }
11914
11915 var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView'];
11916 if (value) {
11917 for (var i = 0; i < types.length; i++) {
11918 if (AWS.util.isType(value, types[i])) return;
11919 if (AWS.util.typeName(value.constructor) === types[i]) return;
11920 }
11921 }
11922
11923 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' +
11924 'string, Buffer, Stream, Blob, or typed array object');
11925 }
11926 });
11927
11928
11929/***/ })
11930/******/ ])
11931});
11932;
\No newline at end of file