UNPKG

406 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.559.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 = util.buffer.toBuffer(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 util.buffer.toBuffer(string, 'base64');
296 }
297
298 },
299
300 buffer: {
301 /**
302 * Buffer constructor for Node buffer and buffer pollyfill
303 */
304 toBuffer: function(data, encoding) {
305 return (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ?
306 util.Buffer.from(data, encoding) : new util.Buffer(data, encoding);
307 },
308
309 alloc: function(size, fill, encoding) {
310 if (typeof size !== 'number') {
311 throw new Error('size passed to alloc must be a number.');
312 }
313 if (typeof util.Buffer.alloc === 'function') {
314 return util.Buffer.alloc(size, fill, encoding);
315 } else {
316 var buf = new util.Buffer(size);
317 if (fill !== undefined && typeof buf.fill === 'function') {
318 buf.fill(fill, undefined, undefined, encoding);
319 }
320 return buf;
321 }
322 },
323
324 toStream: function toStream(buffer) {
325 if (!util.Buffer.isBuffer(buffer)) buffer = util.buffer.toBuffer(buffer);
326
327 var readable = new (util.stream.Readable)();
328 var pos = 0;
329 readable._read = function(size) {
330 if (pos >= buffer.length) return readable.push(null);
331
332 var end = pos + size;
333 if (end > buffer.length) end = buffer.length;
334 readable.push(buffer.slice(pos, end));
335 pos = end;
336 };
337
338 return readable;
339 },
340
341 /**
342 * Concatenates a list of Buffer objects.
343 */
344 concat: function(buffers) {
345 var length = 0,
346 offset = 0,
347 buffer = null, i;
348
349 for (i = 0; i < buffers.length; i++) {
350 length += buffers[i].length;
351 }
352
353 buffer = util.buffer.alloc(length);
354
355 for (i = 0; i < buffers.length; i++) {
356 buffers[i].copy(buffer, offset);
357 offset += buffers[i].length;
358 }
359
360 return buffer;
361 }
362 },
363
364 string: {
365 byteLength: function byteLength(string) {
366 if (string === null || string === undefined) return 0;
367 if (typeof string === 'string') string = util.buffer.toBuffer(string);
368
369 if (typeof string.byteLength === 'number') {
370 return string.byteLength;
371 } else if (typeof string.length === 'number') {
372 return string.length;
373 } else if (typeof string.size === 'number') {
374 return string.size;
375 } else if (typeof string.path === 'string') {
376 return __webpack_require__(6).lstatSync(string.path).size;
377 } else {
378 throw util.error(new Error('Cannot determine length of ' + string),
379 { object: string });
380 }
381 },
382
383 upperFirst: function upperFirst(string) {
384 return string[0].toUpperCase() + string.substr(1);
385 },
386
387 lowerFirst: function lowerFirst(string) {
388 return string[0].toLowerCase() + string.substr(1);
389 }
390 },
391
392 ini: {
393 parse: function string(ini) {
394 var currentSection, map = {};
395 util.arrayEach(ini.split(/\r?\n/), function(line) {
396 line = line.split(/(^|\s)[;#]/)[0]; // remove comments
397 var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/);
398 if (section) {
399 currentSection = section[1];
400 } else if (currentSection) {
401 var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/);
402 if (item) {
403 map[currentSection] = map[currentSection] || {};
404 map[currentSection][item[1]] = item[2];
405 }
406 }
407 });
408
409 return map;
410 }
411 },
412
413 fn: {
414 noop: function() {},
415 callback: function (err) { if (err) throw err; },
416
417 /**
418 * Turn a synchronous function into as "async" function by making it call
419 * a callback. The underlying function is called with all but the last argument,
420 * which is treated as the callback. The callback is passed passed a first argument
421 * of null on success to mimick standard node callbacks.
422 */
423 makeAsync: function makeAsync(fn, expectedArgs) {
424 if (expectedArgs && expectedArgs <= fn.length) {
425 return fn;
426 }
427
428 return function() {
429 var args = Array.prototype.slice.call(arguments, 0);
430 var callback = args.pop();
431 var result = fn.apply(null, args);
432 callback(result);
433 };
434 }
435 },
436
437 /**
438 * Date and time utility functions.
439 */
440 date: {
441
442 /**
443 * @return [Date] the current JavaScript date object. Since all
444 * AWS services rely on this date object, you can override
445 * this function to provide a special time value to AWS service
446 * requests.
447 */
448 getDate: function getDate() {
449 if (!AWS) AWS = __webpack_require__(1);
450 if (AWS.config.systemClockOffset) { // use offset when non-zero
451 return new Date(new Date().getTime() + AWS.config.systemClockOffset);
452 } else {
453 return new Date();
454 }
455 },
456
457 /**
458 * @return [String] the date in ISO-8601 format
459 */
460 iso8601: function iso8601(date) {
461 if (date === undefined) { date = util.date.getDate(); }
462 return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
463 },
464
465 /**
466 * @return [String] the date in RFC 822 format
467 */
468 rfc822: function rfc822(date) {
469 if (date === undefined) { date = util.date.getDate(); }
470 return date.toUTCString();
471 },
472
473 /**
474 * @return [Integer] the UNIX timestamp value for the current time
475 */
476 unixTimestamp: function unixTimestamp(date) {
477 if (date === undefined) { date = util.date.getDate(); }
478 return date.getTime() / 1000;
479 },
480
481 /**
482 * @param [String,number,Date] date
483 * @return [Date]
484 */
485 from: function format(date) {
486 if (typeof date === 'number') {
487 return new Date(date * 1000); // unix timestamp
488 } else {
489 return new Date(date);
490 }
491 },
492
493 /**
494 * Given a Date or date-like value, this function formats the
495 * date into a string of the requested value.
496 * @param [String,number,Date] date
497 * @param [String] formatter Valid formats are:
498 # * 'iso8601'
499 # * 'rfc822'
500 # * 'unixTimestamp'
501 * @return [String]
502 */
503 format: function format(date, formatter) {
504 if (!formatter) formatter = 'iso8601';
505 return util.date[formatter](util.date.from(date));
506 },
507
508 parseTimestamp: function parseTimestamp(value) {
509 if (typeof value === 'number') { // unix timestamp (number)
510 return new Date(value * 1000);
511 } else if (value.match(/^\d+$/)) { // unix timestamp
512 return new Date(value * 1000);
513 } else if (value.match(/^\d{4}/)) { // iso8601
514 return new Date(value);
515 } else if (value.match(/^\w{3},/)) { // rfc822
516 return new Date(value);
517 } else {
518 throw util.error(
519 new Error('unhandled timestamp format: ' + value),
520 {code: 'TimestampParserError'});
521 }
522 }
523
524 },
525
526 crypto: {
527 crc32Table: [
528 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
529 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
530 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
531 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
532 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
533 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
534 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
535 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
536 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
537 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
538 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
539 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
540 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
541 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
542 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
543 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
544 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
545 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
546 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
547 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
548 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
549 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
550 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
551 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
552 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
553 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
554 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
555 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
556 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
557 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
558 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
559 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
560 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
561 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
562 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
563 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
564 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
565 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
566 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
567 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
568 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
569 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
570 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
571 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
572 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
573 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
574 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
575 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
576 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
577 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
578 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
579 0x2D02EF8D],
580
581 crc32: function crc32(data) {
582 var tbl = util.crypto.crc32Table;
583 var crc = 0 ^ -1;
584
585 if (typeof data === 'string') {
586 data = util.buffer.toBuffer(data);
587 }
588
589 for (var i = 0; i < data.length; i++) {
590 var code = data.readUInt8(i);
591 crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF];
592 }
593 return (crc ^ -1) >>> 0;
594 },
595
596 hmac: function hmac(key, string, digest, fn) {
597 if (!digest) digest = 'binary';
598 if (digest === 'buffer') { digest = undefined; }
599 if (!fn) fn = 'sha256';
600 if (typeof string === 'string') string = util.buffer.toBuffer(string);
601 return util.crypto.lib.createHmac(fn, key).update(string).digest(digest);
602 },
603
604 md5: function md5(data, digest, callback) {
605 return util.crypto.hash('md5', data, digest, callback);
606 },
607
608 sha256: function sha256(data, digest, callback) {
609 return util.crypto.hash('sha256', data, digest, callback);
610 },
611
612 hash: function(algorithm, data, digest, callback) {
613 var hash = util.crypto.createHash(algorithm);
614 if (!digest) { digest = 'binary'; }
615 if (digest === 'buffer') { digest = undefined; }
616 if (typeof data === 'string') data = util.buffer.toBuffer(data);
617 var sliceFn = util.arraySliceFn(data);
618 var isBuffer = util.Buffer.isBuffer(data);
619 //Identifying objects with an ArrayBuffer as buffers
620 if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true;
621
622 if (callback && typeof data === 'object' &&
623 typeof data.on === 'function' && !isBuffer) {
624 data.on('data', function(chunk) { hash.update(chunk); });
625 data.on('error', function(err) { callback(err); });
626 data.on('end', function() { callback(null, hash.digest(digest)); });
627 } else if (callback && sliceFn && !isBuffer &&
628 typeof FileReader !== 'undefined') {
629 // this might be a File/Blob
630 var index = 0, size = 1024 * 512;
631 var reader = new FileReader();
632 reader.onerror = function() {
633 callback(new Error('Failed to read data.'));
634 };
635 reader.onload = function() {
636 var buf = new util.Buffer(new Uint8Array(reader.result));
637 hash.update(buf);
638 index += buf.length;
639 reader._continueReading();
640 };
641 reader._continueReading = function() {
642 if (index >= data.size) {
643 callback(null, hash.digest(digest));
644 return;
645 }
646
647 var back = index + size;
648 if (back > data.size) back = data.size;
649 reader.readAsArrayBuffer(sliceFn.call(data, index, back));
650 };
651
652 reader._continueReading();
653 } else {
654 if (util.isBrowser() && typeof data === 'object' && !isBuffer) {
655 data = new util.Buffer(new Uint8Array(data));
656 }
657 var out = hash.update(data).digest(digest);
658 if (callback) callback(null, out);
659 return out;
660 }
661 },
662
663 toHex: function toHex(data) {
664 var out = [];
665 for (var i = 0; i < data.length; i++) {
666 out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2));
667 }
668 return out.join('');
669 },
670
671 createHash: function createHash(algorithm) {
672 return util.crypto.lib.createHash(algorithm);
673 }
674
675 },
676
677 /** @!ignore */
678
679 /* Abort constant */
680 abort: {},
681
682 each: function each(object, iterFunction) {
683 for (var key in object) {
684 if (Object.prototype.hasOwnProperty.call(object, key)) {
685 var ret = iterFunction.call(this, key, object[key]);
686 if (ret === util.abort) break;
687 }
688 }
689 },
690
691 arrayEach: function arrayEach(array, iterFunction) {
692 for (var idx in array) {
693 if (Object.prototype.hasOwnProperty.call(array, idx)) {
694 var ret = iterFunction.call(this, array[idx], parseInt(idx, 10));
695 if (ret === util.abort) break;
696 }
697 }
698 },
699
700 update: function update(obj1, obj2) {
701 util.each(obj2, function iterator(key, item) {
702 obj1[key] = item;
703 });
704 return obj1;
705 },
706
707 merge: function merge(obj1, obj2) {
708 return util.update(util.copy(obj1), obj2);
709 },
710
711 copy: function copy(object) {
712 if (object === null || object === undefined) return object;
713 var dupe = {};
714 // jshint forin:false
715 for (var key in object) {
716 dupe[key] = object[key];
717 }
718 return dupe;
719 },
720
721 isEmpty: function isEmpty(obj) {
722 for (var prop in obj) {
723 if (Object.prototype.hasOwnProperty.call(obj, prop)) {
724 return false;
725 }
726 }
727 return true;
728 },
729
730 arraySliceFn: function arraySliceFn(obj) {
731 var fn = obj.slice || obj.webkitSlice || obj.mozSlice;
732 return typeof fn === 'function' ? fn : null;
733 },
734
735 isType: function isType(obj, type) {
736 // handle cross-"frame" objects
737 if (typeof type === 'function') type = util.typeName(type);
738 return Object.prototype.toString.call(obj) === '[object ' + type + ']';
739 },
740
741 typeName: function typeName(type) {
742 if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name;
743 var str = type.toString();
744 var match = str.match(/^\s*function (.+)\(/);
745 return match ? match[1] : str;
746 },
747
748 error: function error(err, options) {
749 var originalError = null;
750 if (typeof err.message === 'string' && err.message !== '') {
751 if (typeof options === 'string' || (options && options.message)) {
752 originalError = util.copy(err);
753 originalError.message = err.message;
754 }
755 }
756 err.message = err.message || null;
757
758 if (typeof options === 'string') {
759 err.message = options;
760 } else if (typeof options === 'object' && options !== null) {
761 util.update(err, options);
762 if (options.message)
763 err.message = options.message;
764 if (options.code || options.name)
765 err.code = options.code || options.name;
766 if (options.stack)
767 err.stack = options.stack;
768 }
769
770 if (typeof Object.defineProperty === 'function') {
771 Object.defineProperty(err, 'name', {writable: true, enumerable: false});
772 Object.defineProperty(err, 'message', {enumerable: true});
773 }
774
775 err.name = options && options.name || err.name || err.code || 'Error';
776 err.time = new Date();
777
778 if (originalError) err.originalError = originalError;
779
780 return err;
781 },
782
783 /**
784 * @api private
785 */
786 inherit: function inherit(klass, features) {
787 var newObject = null;
788 if (features === undefined) {
789 features = klass;
790 klass = Object;
791 newObject = {};
792 } else {
793 var ctor = function ConstructorWrapper() {};
794 ctor.prototype = klass.prototype;
795 newObject = new ctor();
796 }
797
798 // constructor not supplied, create pass-through ctor
799 if (features.constructor === Object) {
800 features.constructor = function() {
801 if (klass !== Object) {
802 return klass.apply(this, arguments);
803 }
804 };
805 }
806
807 features.constructor.prototype = newObject;
808 util.update(features.constructor.prototype, features);
809 features.constructor.__super__ = klass;
810 return features.constructor;
811 },
812
813 /**
814 * @api private
815 */
816 mixin: function mixin() {
817 var klass = arguments[0];
818 for (var i = 1; i < arguments.length; i++) {
819 // jshint forin:false
820 for (var prop in arguments[i].prototype) {
821 var fn = arguments[i].prototype[prop];
822 if (prop !== 'constructor') {
823 klass.prototype[prop] = fn;
824 }
825 }
826 }
827 return klass;
828 },
829
830 /**
831 * @api private
832 */
833 hideProperties: function hideProperties(obj, props) {
834 if (typeof Object.defineProperty !== 'function') return;
835
836 util.arrayEach(props, function (key) {
837 Object.defineProperty(obj, key, {
838 enumerable: false, writable: true, configurable: true });
839 });
840 },
841
842 /**
843 * @api private
844 */
845 property: function property(obj, name, value, enumerable, isValue) {
846 var opts = {
847 configurable: true,
848 enumerable: enumerable !== undefined ? enumerable : true
849 };
850 if (typeof value === 'function' && !isValue) {
851 opts.get = value;
852 }
853 else {
854 opts.value = value; opts.writable = true;
855 }
856
857 Object.defineProperty(obj, name, opts);
858 },
859
860 /**
861 * @api private
862 */
863 memoizedProperty: function memoizedProperty(obj, name, get, enumerable) {
864 var cachedValue = null;
865
866 // build enumerable attribute for each value with lazy accessor.
867 util.property(obj, name, function() {
868 if (cachedValue === null) {
869 cachedValue = get();
870 }
871 return cachedValue;
872 }, enumerable);
873 },
874
875 /**
876 * TODO Remove in major version revision
877 * This backfill populates response data without the
878 * top-level payload name.
879 *
880 * @api private
881 */
882 hoistPayloadMember: function hoistPayloadMember(resp) {
883 var req = resp.request;
884 var operationName = req.operation;
885 var operation = req.service.api.operations[operationName];
886 var output = operation.output;
887 if (output.payload && !operation.hasEventOutput) {
888 var payloadMember = output.members[output.payload];
889 var responsePayload = resp.data[output.payload];
890 if (payloadMember.type === 'structure') {
891 util.each(responsePayload, function(key, value) {
892 util.property(resp.data, key, value, false);
893 });
894 }
895 }
896 },
897
898 /**
899 * Compute SHA-256 checksums of streams
900 *
901 * @api private
902 */
903 computeSha256: function computeSha256(body, done) {
904 if (util.isNode()) {
905 var Stream = util.stream.Stream;
906 var fs = __webpack_require__(6);
907 if (typeof Stream === 'function' && body instanceof Stream) {
908 if (typeof body.path === 'string') { // assume file object
909 var settings = {};
910 if (typeof body.start === 'number') {
911 settings.start = body.start;
912 }
913 if (typeof body.end === 'number') {
914 settings.end = body.end;
915 }
916 body = fs.createReadStream(body.path, settings);
917 } else { // TODO support other stream types
918 return done(new Error('Non-file stream objects are ' +
919 'not supported with SigV4'));
920 }
921 }
922 }
923
924 util.crypto.sha256(body, 'hex', function(err, sha) {
925 if (err) done(err);
926 else done(null, sha);
927 });
928 },
929
930 /**
931 * @api private
932 */
933 isClockSkewed: function isClockSkewed(serverTime) {
934 if (serverTime) {
935 util.property(AWS.config, 'isClockSkewed',
936 Math.abs(new Date().getTime() - serverTime) >= 300000, false);
937 return AWS.config.isClockSkewed;
938 }
939 },
940
941 applyClockOffset: function applyClockOffset(serverTime) {
942 if (serverTime)
943 AWS.config.systemClockOffset = serverTime - new Date().getTime();
944 },
945
946 /**
947 * @api private
948 */
949 extractRequestId: function extractRequestId(resp) {
950 var requestId = resp.httpResponse.headers['x-amz-request-id'] ||
951 resp.httpResponse.headers['x-amzn-requestid'];
952
953 if (!requestId && resp.data && resp.data.ResponseMetadata) {
954 requestId = resp.data.ResponseMetadata.RequestId;
955 }
956
957 if (requestId) {
958 resp.requestId = requestId;
959 }
960
961 if (resp.error) {
962 resp.error.requestId = requestId;
963 }
964 },
965
966 /**
967 * @api private
968 */
969 addPromises: function addPromises(constructors, PromiseDependency) {
970 var deletePromises = false;
971 if (PromiseDependency === undefined && AWS && AWS.config) {
972 PromiseDependency = AWS.config.getPromisesDependency();
973 }
974 if (PromiseDependency === undefined && typeof Promise !== 'undefined') {
975 PromiseDependency = Promise;
976 }
977 if (typeof PromiseDependency !== 'function') deletePromises = true;
978 if (!Array.isArray(constructors)) constructors = [constructors];
979
980 for (var ind = 0; ind < constructors.length; ind++) {
981 var constructor = constructors[ind];
982 if (deletePromises) {
983 if (constructor.deletePromisesFromClass) {
984 constructor.deletePromisesFromClass();
985 }
986 } else if (constructor.addPromisesToClass) {
987 constructor.addPromisesToClass(PromiseDependency);
988 }
989 }
990 },
991
992 /**
993 * @api private
994 * Return a function that will return a promise whose fate is decided by the
995 * callback behavior of the given method with `methodName`. The method to be
996 * promisified should conform to node.js convention of accepting a callback as
997 * last argument and calling that callback with error as the first argument
998 * and success value on the second argument.
999 */
1000 promisifyMethod: function promisifyMethod(methodName, PromiseDependency) {
1001 return function promise() {
1002 var self = this;
1003 var args = Array.prototype.slice.call(arguments);
1004 return new PromiseDependency(function(resolve, reject) {
1005 args.push(function(err, data) {
1006 if (err) {
1007 reject(err);
1008 } else {
1009 resolve(data);
1010 }
1011 });
1012 self[methodName].apply(self, args);
1013 });
1014 };
1015 },
1016
1017 /**
1018 * @api private
1019 */
1020 isDualstackAvailable: function isDualstackAvailable(service) {
1021 if (!service) return false;
1022 var metadata = __webpack_require__(7);
1023 if (typeof service !== 'string') service = service.serviceIdentifier;
1024 if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false;
1025 return !!metadata[service].dualstackAvailable;
1026 },
1027
1028 /**
1029 * @api private
1030 */
1031 calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) {
1032 if (!retryDelayOptions) retryDelayOptions = {};
1033 var customBackoff = retryDelayOptions.customBackoff || null;
1034 if (typeof customBackoff === 'function') {
1035 return customBackoff(retryCount);
1036 }
1037 var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100;
1038 var delay = Math.random() * (Math.pow(2, retryCount) * base);
1039 return delay;
1040 },
1041
1042 /**
1043 * @api private
1044 */
1045 handleRequestWithRetries: function handleRequestWithRetries(httpRequest, options, cb) {
1046 if (!options) options = {};
1047 var http = AWS.HttpClient.getInstance();
1048 var httpOptions = options.httpOptions || {};
1049 var retryCount = 0;
1050
1051 var errCallback = function(err) {
1052 var maxRetries = options.maxRetries || 0;
1053 if (err && err.code === 'TimeoutError') err.retryable = true;
1054 if (err && err.retryable && retryCount < maxRetries) {
1055 retryCount++;
1056 var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions);
1057 setTimeout(sendRequest, delay + (err.retryAfter || 0));
1058 } else {
1059 cb(err);
1060 }
1061 };
1062
1063 var sendRequest = function() {
1064 var data = '';
1065 http.handleRequest(httpRequest, httpOptions, function(httpResponse) {
1066 httpResponse.on('data', function(chunk) { data += chunk.toString(); });
1067 httpResponse.on('end', function() {
1068 var statusCode = httpResponse.statusCode;
1069 if (statusCode < 300) {
1070 cb(null, data);
1071 } else {
1072 var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0;
1073 var err = util.error(new Error(),
1074 { retryable: statusCode >= 500 || statusCode === 429 }
1075 );
1076 if (retryAfter && err.retryable) err.retryAfter = retryAfter;
1077 errCallback(err);
1078 }
1079 });
1080 }, errCallback);
1081 };
1082
1083 AWS.util.defer(sendRequest);
1084 },
1085
1086 /**
1087 * @api private
1088 */
1089 uuid: {
1090 v4: function uuidV4() {
1091 return __webpack_require__(8).v4();
1092 }
1093 },
1094
1095 /**
1096 * @api private
1097 */
1098 convertPayloadToString: function convertPayloadToString(resp) {
1099 var req = resp.request;
1100 var operation = req.operation;
1101 var rules = req.service.api.operations[operation].output || {};
1102 if (rules.payload && resp.data[rules.payload]) {
1103 resp.data[rules.payload] = resp.data[rules.payload].toString();
1104 }
1105 },
1106
1107 /**
1108 * @api private
1109 */
1110 defer: function defer(callback) {
1111 if (typeof process === 'object' && typeof process.nextTick === 'function') {
1112 process.nextTick(callback);
1113 } else if (typeof setImmediate === 'function') {
1114 setImmediate(callback);
1115 } else {
1116 setTimeout(callback, 0);
1117 }
1118 },
1119
1120 /**
1121 * @api private
1122 */
1123 getRequestPayloadShape: function getRequestPayloadShape(req) {
1124 var operations = req.service.api.operations;
1125 if (!operations) return undefined;
1126 var operation = (operations || {})[req.operation];
1127 if (!operation || !operation.input || !operation.input.payload) return undefined;
1128 return operation.input.members[operation.input.payload];
1129 },
1130
1131 getProfilesFromSharedConfig: function getProfilesFromSharedConfig(iniLoader, filename) {
1132 var profiles = {};
1133 var profilesFromConfig = {};
1134 if (process.env[util.configOptInEnv]) {
1135 var profilesFromConfig = iniLoader.loadFrom({
1136 isConfig: true,
1137 filename: process.env[util.sharedConfigFileEnv]
1138 });
1139 }
1140 var profilesFromCreds = iniLoader.loadFrom({
1141 filename: filename ||
1142 (process.env[util.configOptInEnv] && process.env[util.sharedCredentialsFileEnv])
1143 });
1144 for (var i = 0, profileNames = Object.keys(profilesFromConfig); i < profileNames.length; i++) {
1145 profiles[profileNames[i]] = profilesFromConfig[profileNames[i]];
1146 }
1147 for (var i = 0, profileNames = Object.keys(profilesFromCreds); i < profileNames.length; i++) {
1148 profiles[profileNames[i]] = profilesFromCreds[profileNames[i]];
1149 }
1150 return profiles;
1151 },
1152
1153 /**
1154 * @api private
1155 */
1156 defaultProfile: 'default',
1157
1158 /**
1159 * @api private
1160 */
1161 configOptInEnv: 'AWS_SDK_LOAD_CONFIG',
1162
1163 /**
1164 * @api private
1165 */
1166 sharedCredentialsFileEnv: 'AWS_SHARED_CREDENTIALS_FILE',
1167
1168 /**
1169 * @api private
1170 */
1171 sharedConfigFileEnv: 'AWS_CONFIG_FILE',
1172
1173 /**
1174 * @api private
1175 */
1176 imdsDisabledEnv: 'AWS_EC2_METADATA_DISABLED'
1177 };
1178
1179 /**
1180 * @api private
1181 */
1182 module.exports = util;
1183
1184 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(4).setImmediate))
1185
1186/***/ }),
1187/* 3 */
1188/***/ (function(module, exports) {
1189
1190 // shim for using process in browser
1191 var process = module.exports = {};
1192
1193 // cached from whatever global is present so that test runners that stub it
1194 // don't break things. But we need to wrap it in a try catch in case it is
1195 // wrapped in strict mode code which doesn't define any globals. It's inside a
1196 // function because try/catches deoptimize in certain engines.
1197
1198 var cachedSetTimeout;
1199 var cachedClearTimeout;
1200
1201 function defaultSetTimout() {
1202 throw new Error('setTimeout has not been defined');
1203 }
1204 function defaultClearTimeout () {
1205 throw new Error('clearTimeout has not been defined');
1206 }
1207 (function () {
1208 try {
1209 if (typeof setTimeout === 'function') {
1210 cachedSetTimeout = setTimeout;
1211 } else {
1212 cachedSetTimeout = defaultSetTimout;
1213 }
1214 } catch (e) {
1215 cachedSetTimeout = defaultSetTimout;
1216 }
1217 try {
1218 if (typeof clearTimeout === 'function') {
1219 cachedClearTimeout = clearTimeout;
1220 } else {
1221 cachedClearTimeout = defaultClearTimeout;
1222 }
1223 } catch (e) {
1224 cachedClearTimeout = defaultClearTimeout;
1225 }
1226 } ())
1227 function runTimeout(fun) {
1228 if (cachedSetTimeout === setTimeout) {
1229 //normal enviroments in sane situations
1230 return setTimeout(fun, 0);
1231 }
1232 // if setTimeout wasn't available but was latter defined
1233 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
1234 cachedSetTimeout = setTimeout;
1235 return setTimeout(fun, 0);
1236 }
1237 try {
1238 // when when somebody has screwed with setTimeout but no I.E. maddness
1239 return cachedSetTimeout(fun, 0);
1240 } catch(e){
1241 try {
1242 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1243 return cachedSetTimeout.call(null, fun, 0);
1244 } catch(e){
1245 // 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
1246 return cachedSetTimeout.call(this, fun, 0);
1247 }
1248 }
1249
1250
1251 }
1252 function runClearTimeout(marker) {
1253 if (cachedClearTimeout === clearTimeout) {
1254 //normal enviroments in sane situations
1255 return clearTimeout(marker);
1256 }
1257 // if clearTimeout wasn't available but was latter defined
1258 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
1259 cachedClearTimeout = clearTimeout;
1260 return clearTimeout(marker);
1261 }
1262 try {
1263 // when when somebody has screwed with setTimeout but no I.E. maddness
1264 return cachedClearTimeout(marker);
1265 } catch (e){
1266 try {
1267 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1268 return cachedClearTimeout.call(null, marker);
1269 } catch (e){
1270 // 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.
1271 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
1272 return cachedClearTimeout.call(this, marker);
1273 }
1274 }
1275
1276
1277
1278 }
1279 var queue = [];
1280 var draining = false;
1281 var currentQueue;
1282 var queueIndex = -1;
1283
1284 function cleanUpNextTick() {
1285 if (!draining || !currentQueue) {
1286 return;
1287 }
1288 draining = false;
1289 if (currentQueue.length) {
1290 queue = currentQueue.concat(queue);
1291 } else {
1292 queueIndex = -1;
1293 }
1294 if (queue.length) {
1295 drainQueue();
1296 }
1297 }
1298
1299 function drainQueue() {
1300 if (draining) {
1301 return;
1302 }
1303 var timeout = runTimeout(cleanUpNextTick);
1304 draining = true;
1305
1306 var len = queue.length;
1307 while(len) {
1308 currentQueue = queue;
1309 queue = [];
1310 while (++queueIndex < len) {
1311 if (currentQueue) {
1312 currentQueue[queueIndex].run();
1313 }
1314 }
1315 queueIndex = -1;
1316 len = queue.length;
1317 }
1318 currentQueue = null;
1319 draining = false;
1320 runClearTimeout(timeout);
1321 }
1322
1323 process.nextTick = function (fun) {
1324 var args = new Array(arguments.length - 1);
1325 if (arguments.length > 1) {
1326 for (var i = 1; i < arguments.length; i++) {
1327 args[i - 1] = arguments[i];
1328 }
1329 }
1330 queue.push(new Item(fun, args));
1331 if (queue.length === 1 && !draining) {
1332 runTimeout(drainQueue);
1333 }
1334 };
1335
1336 // v8 likes predictible objects
1337 function Item(fun, array) {
1338 this.fun = fun;
1339 this.array = array;
1340 }
1341 Item.prototype.run = function () {
1342 this.fun.apply(null, this.array);
1343 };
1344 process.title = 'browser';
1345 process.browser = true;
1346 process.env = {};
1347 process.argv = [];
1348 process.version = ''; // empty string to avoid regexp issues
1349 process.versions = {};
1350
1351 function noop() {}
1352
1353 process.on = noop;
1354 process.addListener = noop;
1355 process.once = noop;
1356 process.off = noop;
1357 process.removeListener = noop;
1358 process.removeAllListeners = noop;
1359 process.emit = noop;
1360 process.prependListener = noop;
1361 process.prependOnceListener = noop;
1362
1363 process.listeners = function (name) { return [] }
1364
1365 process.binding = function (name) {
1366 throw new Error('process.binding is not supported');
1367 };
1368
1369 process.cwd = function () { return '/' };
1370 process.chdir = function (dir) {
1371 throw new Error('process.chdir is not supported');
1372 };
1373 process.umask = function() { return 0; };
1374
1375
1376/***/ }),
1377/* 4 */
1378/***/ (function(module, exports, __webpack_require__) {
1379
1380 /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
1381 (typeof self !== "undefined" && self) ||
1382 window;
1383 var apply = Function.prototype.apply;
1384
1385 // DOM APIs, for completeness
1386
1387 exports.setTimeout = function() {
1388 return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
1389 };
1390 exports.setInterval = function() {
1391 return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
1392 };
1393 exports.clearTimeout =
1394 exports.clearInterval = function(timeout) {
1395 if (timeout) {
1396 timeout.close();
1397 }
1398 };
1399
1400 function Timeout(id, clearFn) {
1401 this._id = id;
1402 this._clearFn = clearFn;
1403 }
1404 Timeout.prototype.unref = Timeout.prototype.ref = function() {};
1405 Timeout.prototype.close = function() {
1406 this._clearFn.call(scope, this._id);
1407 };
1408
1409 // Does not start the time, just sets up the members needed.
1410 exports.enroll = function(item, msecs) {
1411 clearTimeout(item._idleTimeoutId);
1412 item._idleTimeout = msecs;
1413 };
1414
1415 exports.unenroll = function(item) {
1416 clearTimeout(item._idleTimeoutId);
1417 item._idleTimeout = -1;
1418 };
1419
1420 exports._unrefActive = exports.active = function(item) {
1421 clearTimeout(item._idleTimeoutId);
1422
1423 var msecs = item._idleTimeout;
1424 if (msecs >= 0) {
1425 item._idleTimeoutId = setTimeout(function onTimeout() {
1426 if (item._onTimeout)
1427 item._onTimeout();
1428 }, msecs);
1429 }
1430 };
1431
1432 // setimmediate attaches itself to the global object
1433 __webpack_require__(5);
1434 // On some exotic environments, it's not clear which object `setimmediate` was
1435 // able to install onto. Search each possibility in the same order as the
1436 // `setimmediate` library.
1437 exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
1438 (typeof global !== "undefined" && global.setImmediate) ||
1439 (this && this.setImmediate);
1440 exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
1441 (typeof global !== "undefined" && global.clearImmediate) ||
1442 (this && this.clearImmediate);
1443
1444 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
1445
1446/***/ }),
1447/* 5 */
1448/***/ (function(module, exports, __webpack_require__) {
1449
1450 /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
1451 "use strict";
1452
1453 if (global.setImmediate) {
1454 return;
1455 }
1456
1457 var nextHandle = 1; // Spec says greater than zero
1458 var tasksByHandle = {};
1459 var currentlyRunningATask = false;
1460 var doc = global.document;
1461 var registerImmediate;
1462
1463 function setImmediate(callback) {
1464 // Callback can either be a function or a string
1465 if (typeof callback !== "function") {
1466 callback = new Function("" + callback);
1467 }
1468 // Copy function arguments
1469 var args = new Array(arguments.length - 1);
1470 for (var i = 0; i < args.length; i++) {
1471 args[i] = arguments[i + 1];
1472 }
1473 // Store and register the task
1474 var task = { callback: callback, args: args };
1475 tasksByHandle[nextHandle] = task;
1476 registerImmediate(nextHandle);
1477 return nextHandle++;
1478 }
1479
1480 function clearImmediate(handle) {
1481 delete tasksByHandle[handle];
1482 }
1483
1484 function run(task) {
1485 var callback = task.callback;
1486 var args = task.args;
1487 switch (args.length) {
1488 case 0:
1489 callback();
1490 break;
1491 case 1:
1492 callback(args[0]);
1493 break;
1494 case 2:
1495 callback(args[0], args[1]);
1496 break;
1497 case 3:
1498 callback(args[0], args[1], args[2]);
1499 break;
1500 default:
1501 callback.apply(undefined, args);
1502 break;
1503 }
1504 }
1505
1506 function runIfPresent(handle) {
1507 // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
1508 // So if we're currently running a task, we'll need to delay this invocation.
1509 if (currentlyRunningATask) {
1510 // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
1511 // "too much recursion" error.
1512 setTimeout(runIfPresent, 0, handle);
1513 } else {
1514 var task = tasksByHandle[handle];
1515 if (task) {
1516 currentlyRunningATask = true;
1517 try {
1518 run(task);
1519 } finally {
1520 clearImmediate(handle);
1521 currentlyRunningATask = false;
1522 }
1523 }
1524 }
1525 }
1526
1527 function installNextTickImplementation() {
1528 registerImmediate = function(handle) {
1529 process.nextTick(function () { runIfPresent(handle); });
1530 };
1531 }
1532
1533 function canUsePostMessage() {
1534 // The test against `importScripts` prevents this implementation from being installed inside a web worker,
1535 // where `global.postMessage` means something completely different and can't be used for this purpose.
1536 if (global.postMessage && !global.importScripts) {
1537 var postMessageIsAsynchronous = true;
1538 var oldOnMessage = global.onmessage;
1539 global.onmessage = function() {
1540 postMessageIsAsynchronous = false;
1541 };
1542 global.postMessage("", "*");
1543 global.onmessage = oldOnMessage;
1544 return postMessageIsAsynchronous;
1545 }
1546 }
1547
1548 function installPostMessageImplementation() {
1549 // Installs an event handler on `global` for the `message` event: see
1550 // * https://developer.mozilla.org/en/DOM/window.postMessage
1551 // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
1552
1553 var messagePrefix = "setImmediate$" + Math.random() + "$";
1554 var onGlobalMessage = function(event) {
1555 if (event.source === global &&
1556 typeof event.data === "string" &&
1557 event.data.indexOf(messagePrefix) === 0) {
1558 runIfPresent(+event.data.slice(messagePrefix.length));
1559 }
1560 };
1561
1562 if (global.addEventListener) {
1563 global.addEventListener("message", onGlobalMessage, false);
1564 } else {
1565 global.attachEvent("onmessage", onGlobalMessage);
1566 }
1567
1568 registerImmediate = function(handle) {
1569 global.postMessage(messagePrefix + handle, "*");
1570 };
1571 }
1572
1573 function installMessageChannelImplementation() {
1574 var channel = new MessageChannel();
1575 channel.port1.onmessage = function(event) {
1576 var handle = event.data;
1577 runIfPresent(handle);
1578 };
1579
1580 registerImmediate = function(handle) {
1581 channel.port2.postMessage(handle);
1582 };
1583 }
1584
1585 function installReadyStateChangeImplementation() {
1586 var html = doc.documentElement;
1587 registerImmediate = function(handle) {
1588 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
1589 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
1590 var script = doc.createElement("script");
1591 script.onreadystatechange = function () {
1592 runIfPresent(handle);
1593 script.onreadystatechange = null;
1594 html.removeChild(script);
1595 script = null;
1596 };
1597 html.appendChild(script);
1598 };
1599 }
1600
1601 function installSetTimeoutImplementation() {
1602 registerImmediate = function(handle) {
1603 setTimeout(runIfPresent, 0, handle);
1604 };
1605 }
1606
1607 // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
1608 var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
1609 attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
1610
1611 // Don't get fooled by e.g. browserify environments.
1612 if ({}.toString.call(global.process) === "[object process]") {
1613 // For Node.js before 0.9
1614 installNextTickImplementation();
1615
1616 } else if (canUsePostMessage()) {
1617 // For non-IE10 modern browsers
1618 installPostMessageImplementation();
1619
1620 } else if (global.MessageChannel) {
1621 // For web workers, where supported
1622 installMessageChannelImplementation();
1623
1624 } else if (doc && "onreadystatechange" in doc.createElement("script")) {
1625 // For IE 6–8
1626 installReadyStateChangeImplementation();
1627
1628 } else {
1629 // For older browsers
1630 installSetTimeoutImplementation();
1631 }
1632
1633 attachTo.setImmediate = setImmediate;
1634 attachTo.clearImmediate = clearImmediate;
1635 }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
1636
1637 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
1638
1639/***/ }),
1640/* 6 */
1641/***/ (function(module, exports) {
1642
1643 /* (ignored) */
1644
1645/***/ }),
1646/* 7 */
1647/***/ (function(module, exports) {
1648
1649 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*","2018-11-05*"],"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","cors":true},"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","cors":true},"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","cors":true},"acmpca":{"prefix":"acm-pca","name":"ACMPCA"},"fms":{"name":"FMS"},"secretsmanager":{"name":"SecretsManager","cors":true},"iotanalytics":{"name":"IoTAnalytics","cors":true},"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"},"managedblockchain":{"name":"ManagedBlockchain"},"mediapackagevod":{"prefix":"mediapackage-vod","name":"MediaPackageVod"},"groundstation":{"name":"GroundStation"},"iotthingsgraph":{"name":"IoTThingsGraph"},"iotevents":{"name":"IoTEvents"},"ioteventsdata":{"prefix":"iotevents-data","name":"IoTEventsData"},"personalize":{"name":"Personalize","cors":true},"personalizeevents":{"prefix":"personalize-events","name":"PersonalizeEvents","cors":true},"personalizeruntime":{"prefix":"personalize-runtime","name":"PersonalizeRuntime","cors":true},"applicationinsights":{"prefix":"application-insights","name":"ApplicationInsights"},"servicequotas":{"prefix":"service-quotas","name":"ServiceQuotas"},"ec2instanceconnect":{"prefix":"ec2-instance-connect","name":"EC2InstanceConnect"},"eventbridge":{"name":"EventBridge"},"lakeformation":{"name":"LakeFormation"},"forecastservice":{"prefix":"forecast","name":"ForecastService","cors":true},"forecastqueryservice":{"prefix":"forecastquery","name":"ForecastQueryService","cors":true},"qldb":{"name":"QLDB"},"qldbsession":{"prefix":"qldb-session","name":"QLDBSession"},"workmailmessageflow":{"name":"WorkMailMessageFlow"}}
1650
1651/***/ }),
1652/* 8 */
1653/***/ (function(module, exports, __webpack_require__) {
1654
1655 var v1 = __webpack_require__(9);
1656 var v4 = __webpack_require__(12);
1657
1658 var uuid = v4;
1659 uuid.v1 = v1;
1660 uuid.v4 = v4;
1661
1662 module.exports = uuid;
1663
1664
1665/***/ }),
1666/* 9 */
1667/***/ (function(module, exports, __webpack_require__) {
1668
1669 var rng = __webpack_require__(10);
1670 var bytesToUuid = __webpack_require__(11);
1671
1672 // **`v1()` - Generate time-based UUID**
1673 //
1674 // Inspired by https://github.com/LiosK/UUID.js
1675 // and http://docs.python.org/library/uuid.html
1676
1677 var _nodeId;
1678 var _clockseq;
1679
1680 // Previous uuid creation time
1681 var _lastMSecs = 0;
1682 var _lastNSecs = 0;
1683
1684 // See https://github.com/broofa/node-uuid for API details
1685 function v1(options, buf, offset) {
1686 var i = buf && offset || 0;
1687 var b = buf || [];
1688
1689 options = options || {};
1690 var node = options.node || _nodeId;
1691 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
1692
1693 // node and clockseq need to be initialized to random values if they're not
1694 // specified. We do this lazily to minimize issues related to insufficient
1695 // system entropy. See #189
1696 if (node == null || clockseq == null) {
1697 var seedBytes = rng();
1698 if (node == null) {
1699 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
1700 node = _nodeId = [
1701 seedBytes[0] | 0x01,
1702 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
1703 ];
1704 }
1705 if (clockseq == null) {
1706 // Per 4.2.2, randomize (14 bit) clockseq
1707 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
1708 }
1709 }
1710
1711 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
1712 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
1713 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
1714 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
1715 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
1716
1717 // Per 4.2.1.2, use count of uuid's generated during the current clock
1718 // cycle to simulate higher resolution clock
1719 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
1720
1721 // Time since last uuid creation (in msecs)
1722 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
1723
1724 // Per 4.2.1.2, Bump clockseq on clock regression
1725 if (dt < 0 && options.clockseq === undefined) {
1726 clockseq = clockseq + 1 & 0x3fff;
1727 }
1728
1729 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
1730 // time interval
1731 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
1732 nsecs = 0;
1733 }
1734
1735 // Per 4.2.1.2 Throw error if too many uuids are requested
1736 if (nsecs >= 10000) {
1737 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
1738 }
1739
1740 _lastMSecs = msecs;
1741 _lastNSecs = nsecs;
1742 _clockseq = clockseq;
1743
1744 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
1745 msecs += 12219292800000;
1746
1747 // `time_low`
1748 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
1749 b[i++] = tl >>> 24 & 0xff;
1750 b[i++] = tl >>> 16 & 0xff;
1751 b[i++] = tl >>> 8 & 0xff;
1752 b[i++] = tl & 0xff;
1753
1754 // `time_mid`
1755 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
1756 b[i++] = tmh >>> 8 & 0xff;
1757 b[i++] = tmh & 0xff;
1758
1759 // `time_high_and_version`
1760 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
1761 b[i++] = tmh >>> 16 & 0xff;
1762
1763 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
1764 b[i++] = clockseq >>> 8 | 0x80;
1765
1766 // `clock_seq_low`
1767 b[i++] = clockseq & 0xff;
1768
1769 // `node`
1770 for (var n = 0; n < 6; ++n) {
1771 b[i + n] = node[n];
1772 }
1773
1774 return buf ? buf : bytesToUuid(b);
1775 }
1776
1777 module.exports = v1;
1778
1779
1780/***/ }),
1781/* 10 */
1782/***/ (function(module, exports) {
1783
1784 // Unique ID creation requires a high quality random # generator. In the
1785 // browser this is a little complicated due to unknown quality of Math.random()
1786 // and inconsistent support for the `crypto` API. We do the best we can via
1787 // feature-detection
1788
1789 // getRandomValues needs to be invoked in a context where "this" is a Crypto
1790 // implementation. Also, find the complete implementation of crypto on IE11.
1791 var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
1792 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
1793
1794 if (getRandomValues) {
1795 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
1796 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
1797
1798 module.exports = function whatwgRNG() {
1799 getRandomValues(rnds8);
1800 return rnds8;
1801 };
1802 } else {
1803 // Math.random()-based (RNG)
1804 //
1805 // If all else fails, use Math.random(). It's fast, but is of unspecified
1806 // quality.
1807 var rnds = new Array(16);
1808
1809 module.exports = function mathRNG() {
1810 for (var i = 0, r; i < 16; i++) {
1811 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
1812 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
1813 }
1814
1815 return rnds;
1816 };
1817 }
1818
1819
1820/***/ }),
1821/* 11 */
1822/***/ (function(module, exports) {
1823
1824 /**
1825 * Convert array of 16 byte values to UUID string format of the form:
1826 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1827 */
1828 var byteToHex = [];
1829 for (var i = 0; i < 256; ++i) {
1830 byteToHex[i] = (i + 0x100).toString(16).substr(1);
1831 }
1832
1833 function bytesToUuid(buf, offset) {
1834 var i = offset || 0;
1835 var bth = byteToHex;
1836 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
1837 return ([bth[buf[i++]], bth[buf[i++]],
1838 bth[buf[i++]], bth[buf[i++]], '-',
1839 bth[buf[i++]], bth[buf[i++]], '-',
1840 bth[buf[i++]], bth[buf[i++]], '-',
1841 bth[buf[i++]], bth[buf[i++]], '-',
1842 bth[buf[i++]], bth[buf[i++]],
1843 bth[buf[i++]], bth[buf[i++]],
1844 bth[buf[i++]], bth[buf[i++]]]).join('');
1845 }
1846
1847 module.exports = bytesToUuid;
1848
1849
1850/***/ }),
1851/* 12 */
1852/***/ (function(module, exports, __webpack_require__) {
1853
1854 var rng = __webpack_require__(10);
1855 var bytesToUuid = __webpack_require__(11);
1856
1857 function v4(options, buf, offset) {
1858 var i = buf && offset || 0;
1859
1860 if (typeof(options) == 'string') {
1861 buf = options === 'binary' ? new Array(16) : null;
1862 options = null;
1863 }
1864 options = options || {};
1865
1866 var rnds = options.random || (options.rng || rng)();
1867
1868 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1869 rnds[6] = (rnds[6] & 0x0f) | 0x40;
1870 rnds[8] = (rnds[8] & 0x3f) | 0x80;
1871
1872 // Copy bytes to buffer, if provided
1873 if (buf) {
1874 for (var ii = 0; ii < 16; ++ii) {
1875 buf[i + ii] = rnds[ii];
1876 }
1877 }
1878
1879 return buf || bytesToUuid(rnds);
1880 }
1881
1882 module.exports = v4;
1883
1884
1885/***/ }),
1886/* 13 */
1887/***/ (function(module, exports, __webpack_require__) {
1888
1889 var util = __webpack_require__(2);
1890 var JsonBuilder = __webpack_require__(14);
1891 var JsonParser = __webpack_require__(15);
1892 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
1893
1894 function buildRequest(req) {
1895 var httpRequest = req.httpRequest;
1896 var api = req.service.api;
1897 var target = api.targetPrefix + '.' + api.operations[req.operation].name;
1898 var version = api.jsonVersion || '1.0';
1899 var input = api.operations[req.operation].input;
1900 var builder = new JsonBuilder();
1901
1902 if (version === 1) version = '1.0';
1903 httpRequest.body = builder.build(req.params || {}, input);
1904 httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version;
1905 httpRequest.headers['X-Amz-Target'] = target;
1906
1907 populateHostPrefix(req);
1908 }
1909
1910 function extractError(resp) {
1911 var error = {};
1912 var httpResponse = resp.httpResponse;
1913
1914 error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError';
1915 if (typeof error.code === 'string') {
1916 error.code = error.code.split(':')[0];
1917 }
1918
1919 if (httpResponse.body.length > 0) {
1920 try {
1921 var e = JSON.parse(httpResponse.body.toString());
1922 if (e.__type || e.code) {
1923 error.code = (e.__type || e.code).split('#').pop();
1924 }
1925 if (error.code === 'RequestEntityTooLarge') {
1926 error.message = 'Request body must be less than 1 MB';
1927 } else {
1928 error.message = (e.message || e.Message || null);
1929 }
1930 } catch (e) {
1931 error.statusCode = httpResponse.statusCode;
1932 error.message = httpResponse.statusMessage;
1933 }
1934 } else {
1935 error.statusCode = httpResponse.statusCode;
1936 error.message = httpResponse.statusCode.toString();
1937 }
1938
1939 resp.error = util.error(new Error(), error);
1940 }
1941
1942 function extractData(resp) {
1943 var body = resp.httpResponse.body.toString() || '{}';
1944 if (resp.request.service.config.convertResponseTypes === false) {
1945 resp.data = JSON.parse(body);
1946 } else {
1947 var operation = resp.request.service.api.operations[resp.request.operation];
1948 var shape = operation.output || {};
1949 var parser = new JsonParser();
1950 resp.data = parser.parse(body, shape);
1951 }
1952 }
1953
1954 /**
1955 * @api private
1956 */
1957 module.exports = {
1958 buildRequest: buildRequest,
1959 extractError: extractError,
1960 extractData: extractData
1961 };
1962
1963
1964/***/ }),
1965/* 14 */
1966/***/ (function(module, exports, __webpack_require__) {
1967
1968 var util = __webpack_require__(2);
1969
1970 function JsonBuilder() { }
1971
1972 JsonBuilder.prototype.build = function(value, shape) {
1973 return JSON.stringify(translate(value, shape));
1974 };
1975
1976 function translate(value, shape) {
1977 if (!shape || value === undefined || value === null) return undefined;
1978
1979 switch (shape.type) {
1980 case 'structure': return translateStructure(value, shape);
1981 case 'map': return translateMap(value, shape);
1982 case 'list': return translateList(value, shape);
1983 default: return translateScalar(value, shape);
1984 }
1985 }
1986
1987 function translateStructure(structure, shape) {
1988 var struct = {};
1989 util.each(structure, function(name, value) {
1990 var memberShape = shape.members[name];
1991 if (memberShape) {
1992 if (memberShape.location !== 'body') return;
1993 var locationName = memberShape.isLocationName ? memberShape.name : name;
1994 var result = translate(value, memberShape);
1995 if (result !== undefined) struct[locationName] = result;
1996 }
1997 });
1998 return struct;
1999 }
2000
2001 function translateList(list, shape) {
2002 var out = [];
2003 util.arrayEach(list, function(value) {
2004 var result = translate(value, shape.member);
2005 if (result !== undefined) out.push(result);
2006 });
2007 return out;
2008 }
2009
2010 function translateMap(map, shape) {
2011 var out = {};
2012 util.each(map, function(key, value) {
2013 var result = translate(value, shape.value);
2014 if (result !== undefined) out[key] = result;
2015 });
2016 return out;
2017 }
2018
2019 function translateScalar(value, shape) {
2020 return shape.toWireFormat(value);
2021 }
2022
2023 /**
2024 * @api private
2025 */
2026 module.exports = JsonBuilder;
2027
2028
2029/***/ }),
2030/* 15 */
2031/***/ (function(module, exports, __webpack_require__) {
2032
2033 var util = __webpack_require__(2);
2034
2035 function JsonParser() { }
2036
2037 JsonParser.prototype.parse = function(value, shape) {
2038 return translate(JSON.parse(value), shape);
2039 };
2040
2041 function translate(value, shape) {
2042 if (!shape || value === undefined) return undefined;
2043
2044 switch (shape.type) {
2045 case 'structure': return translateStructure(value, shape);
2046 case 'map': return translateMap(value, shape);
2047 case 'list': return translateList(value, shape);
2048 default: return translateScalar(value, shape);
2049 }
2050 }
2051
2052 function translateStructure(structure, shape) {
2053 if (structure == null) return undefined;
2054
2055 var struct = {};
2056 var shapeMembers = shape.members;
2057 util.each(shapeMembers, function(name, memberShape) {
2058 var locationName = memberShape.isLocationName ? memberShape.name : name;
2059 if (Object.prototype.hasOwnProperty.call(structure, locationName)) {
2060 var value = structure[locationName];
2061 var result = translate(value, memberShape);
2062 if (result !== undefined) struct[name] = result;
2063 }
2064 });
2065 return struct;
2066 }
2067
2068 function translateList(list, shape) {
2069 if (list == null) return undefined;
2070
2071 var out = [];
2072 util.arrayEach(list, function(value) {
2073 var result = translate(value, shape.member);
2074 if (result === undefined) out.push(null);
2075 else out.push(result);
2076 });
2077 return out;
2078 }
2079
2080 function translateMap(map, shape) {
2081 if (map == null) return undefined;
2082
2083 var out = {};
2084 util.each(map, function(key, value) {
2085 var result = translate(value, shape.value);
2086 if (result === undefined) out[key] = null;
2087 else out[key] = result;
2088 });
2089 return out;
2090 }
2091
2092 function translateScalar(value, shape) {
2093 return shape.toType(value);
2094 }
2095
2096 /**
2097 * @api private
2098 */
2099 module.exports = JsonParser;
2100
2101
2102/***/ }),
2103/* 16 */
2104/***/ (function(module, exports, __webpack_require__) {
2105
2106 var util = __webpack_require__(2);
2107 var AWS = __webpack_require__(1);
2108
2109 /**
2110 * Prepend prefix defined by API model to endpoint that's already
2111 * constructed. This feature does not apply to operations using
2112 * endpoint discovery and can be disabled.
2113 * @api private
2114 */
2115 function populateHostPrefix(request) {
2116 var enabled = request.service.config.hostPrefixEnabled;
2117 if (!enabled) return request;
2118 var operationModel = request.service.api.operations[request.operation];
2119 //don't marshal host prefix when operation has endpoint discovery traits
2120 if (hasEndpointDiscover(request)) return request;
2121 if (operationModel.endpoint && operationModel.endpoint.hostPrefix) {
2122 var hostPrefixNotation = operationModel.endpoint.hostPrefix;
2123 var hostPrefix = expandHostPrefix(hostPrefixNotation, request.params, operationModel.input);
2124 prependEndpointPrefix(request.httpRequest.endpoint, hostPrefix);
2125 validateHostname(request.httpRequest.endpoint.hostname);
2126 }
2127 return request;
2128 }
2129
2130 /**
2131 * @api private
2132 */
2133 function hasEndpointDiscover(request) {
2134 var api = request.service.api;
2135 var operationModel = api.operations[request.operation];
2136 var isEndpointOperation = api.endpointOperation && (api.endpointOperation === util.string.lowerFirst(operationModel.name));
2137 return (operationModel.endpointDiscoveryRequired !== 'NULL' || isEndpointOperation === true);
2138 }
2139
2140 /**
2141 * @api private
2142 */
2143 function expandHostPrefix(hostPrefixNotation, params, shape) {
2144 util.each(shape.members, function(name, member) {
2145 if (member.hostLabel === true) {
2146 if (typeof params[name] !== 'string' || params[name] === '') {
2147 throw util.error(new Error(), {
2148 message: 'Parameter ' + name + ' should be a non-empty string.',
2149 code: 'InvalidParameter'
2150 });
2151 }
2152 var regex = new RegExp('\\{' + name + '\\}', 'g');
2153 hostPrefixNotation = hostPrefixNotation.replace(regex, params[name]);
2154 }
2155 });
2156 return hostPrefixNotation;
2157 }
2158
2159 /**
2160 * @api private
2161 */
2162 function prependEndpointPrefix(endpoint, prefix) {
2163 if (endpoint.host) {
2164 endpoint.host = prefix + endpoint.host;
2165 }
2166 if (endpoint.hostname) {
2167 endpoint.hostname = prefix + endpoint.hostname;
2168 }
2169 }
2170
2171 /**
2172 * @api private
2173 */
2174 function validateHostname(hostname) {
2175 var labels = hostname.split('.');
2176 //Reference: https://tools.ietf.org/html/rfc1123#section-2
2177 var hostPattern = /^[a-zA-Z0-9]{1}$|^[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]$/;
2178 util.arrayEach(labels, function(label) {
2179 if (!label.length || label.length < 1 || label.length > 63) {
2180 throw util.error(new Error(), {
2181 code: 'ValidationError',
2182 message: 'Hostname label length should be between 1 to 63 characters, inclusive.'
2183 });
2184 }
2185 if (!hostPattern.test(label)) {
2186 throw AWS.util.error(new Error(),
2187 {code: 'ValidationError', message: label + ' is not hostname compatible.'});
2188 }
2189 });
2190 }
2191
2192 module.exports = {
2193 populateHostPrefix: populateHostPrefix
2194 };
2195
2196
2197/***/ }),
2198/* 17 */
2199/***/ (function(module, exports, __webpack_require__) {
2200
2201 var AWS = __webpack_require__(1);
2202 var util = __webpack_require__(2);
2203 var QueryParamSerializer = __webpack_require__(18);
2204 var Shape = __webpack_require__(19);
2205 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2206
2207 function buildRequest(req) {
2208 var operation = req.service.api.operations[req.operation];
2209 var httpRequest = req.httpRequest;
2210 httpRequest.headers['Content-Type'] =
2211 'application/x-www-form-urlencoded; charset=utf-8';
2212 httpRequest.params = {
2213 Version: req.service.api.apiVersion,
2214 Action: operation.name
2215 };
2216
2217 // convert the request parameters into a list of query params,
2218 // e.g. Deeply.NestedParam.0.Name=value
2219 var builder = new QueryParamSerializer();
2220 builder.serialize(req.params, operation.input, function(name, value) {
2221 httpRequest.params[name] = value;
2222 });
2223 httpRequest.body = util.queryParamsToString(httpRequest.params);
2224
2225 populateHostPrefix(req);
2226 }
2227
2228 function extractError(resp) {
2229 var data, body = resp.httpResponse.body.toString();
2230 if (body.match('<UnknownOperationException')) {
2231 data = {
2232 Code: 'UnknownOperation',
2233 Message: 'Unknown operation ' + resp.request.operation
2234 };
2235 } else {
2236 try {
2237 data = new AWS.XML.Parser().parse(body);
2238 } catch (e) {
2239 data = {
2240 Code: resp.httpResponse.statusCode,
2241 Message: resp.httpResponse.statusMessage
2242 };
2243 }
2244 }
2245
2246 if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
2247 if (data.Errors) data = data.Errors;
2248 if (data.Error) data = data.Error;
2249 if (data.Code) {
2250 resp.error = util.error(new Error(), {
2251 code: data.Code,
2252 message: data.Message
2253 });
2254 } else {
2255 resp.error = util.error(new Error(), {
2256 code: resp.httpResponse.statusCode,
2257 message: null
2258 });
2259 }
2260 }
2261
2262 function extractData(resp) {
2263 var req = resp.request;
2264 var operation = req.service.api.operations[req.operation];
2265 var shape = operation.output || {};
2266 var origRules = shape;
2267
2268 if (origRules.resultWrapper) {
2269 var tmp = Shape.create({type: 'structure'});
2270 tmp.members[origRules.resultWrapper] = shape;
2271 tmp.memberNames = [origRules.resultWrapper];
2272 util.property(shape, 'name', shape.resultWrapper);
2273 shape = tmp;
2274 }
2275
2276 var parser = new AWS.XML.Parser();
2277
2278 // TODO: Refactor XML Parser to parse RequestId from response.
2279 if (shape && shape.members && !shape.members._XAMZRequestId) {
2280 var requestIdShape = Shape.create(
2281 { type: 'string' },
2282 { api: { protocol: 'query' } },
2283 'requestId'
2284 );
2285 shape.members._XAMZRequestId = requestIdShape;
2286 }
2287
2288 var data = parser.parse(resp.httpResponse.body.toString(), shape);
2289 resp.requestId = data._XAMZRequestId || data.requestId;
2290
2291 if (data._XAMZRequestId) delete data._XAMZRequestId;
2292
2293 if (origRules.resultWrapper) {
2294 if (data[origRules.resultWrapper]) {
2295 util.update(data, data[origRules.resultWrapper]);
2296 delete data[origRules.resultWrapper];
2297 }
2298 }
2299
2300 resp.data = data;
2301 }
2302
2303 /**
2304 * @api private
2305 */
2306 module.exports = {
2307 buildRequest: buildRequest,
2308 extractError: extractError,
2309 extractData: extractData
2310 };
2311
2312
2313/***/ }),
2314/* 18 */
2315/***/ (function(module, exports, __webpack_require__) {
2316
2317 var util = __webpack_require__(2);
2318
2319 function QueryParamSerializer() {
2320 }
2321
2322 QueryParamSerializer.prototype.serialize = function(params, shape, fn) {
2323 serializeStructure('', params, shape, fn);
2324 };
2325
2326 function ucfirst(shape) {
2327 if (shape.isQueryName || shape.api.protocol !== 'ec2') {
2328 return shape.name;
2329 } else {
2330 return shape.name[0].toUpperCase() + shape.name.substr(1);
2331 }
2332 }
2333
2334 function serializeStructure(prefix, struct, rules, fn) {
2335 util.each(rules.members, function(name, member) {
2336 var value = struct[name];
2337 if (value === null || value === undefined) return;
2338
2339 var memberName = ucfirst(member);
2340 memberName = prefix ? prefix + '.' + memberName : memberName;
2341 serializeMember(memberName, value, member, fn);
2342 });
2343 }
2344
2345 function serializeMap(name, map, rules, fn) {
2346 var i = 1;
2347 util.each(map, function (key, value) {
2348 var prefix = rules.flattened ? '.' : '.entry.';
2349 var position = prefix + (i++) + '.';
2350 var keyName = position + (rules.key.name || 'key');
2351 var valueName = position + (rules.value.name || 'value');
2352 serializeMember(name + keyName, key, rules.key, fn);
2353 serializeMember(name + valueName, value, rules.value, fn);
2354 });
2355 }
2356
2357 function serializeList(name, list, rules, fn) {
2358 var memberRules = rules.member || {};
2359
2360 if (list.length === 0) {
2361 fn.call(this, name, null);
2362 return;
2363 }
2364
2365 util.arrayEach(list, function (v, n) {
2366 var suffix = '.' + (n + 1);
2367 if (rules.api.protocol === 'ec2') {
2368 // Do nothing for EC2
2369 suffix = suffix + ''; // make linter happy
2370 } else if (rules.flattened) {
2371 if (memberRules.name) {
2372 var parts = name.split('.');
2373 parts.pop();
2374 parts.push(ucfirst(memberRules));
2375 name = parts.join('.');
2376 }
2377 } else {
2378 suffix = '.' + (memberRules.name ? memberRules.name : 'member') + suffix;
2379 }
2380 serializeMember(name + suffix, v, memberRules, fn);
2381 });
2382 }
2383
2384 function serializeMember(name, value, rules, fn) {
2385 if (value === null || value === undefined) return;
2386 if (rules.type === 'structure') {
2387 serializeStructure(name, value, rules, fn);
2388 } else if (rules.type === 'list') {
2389 serializeList(name, value, rules, fn);
2390 } else if (rules.type === 'map') {
2391 serializeMap(name, value, rules, fn);
2392 } else {
2393 fn(name, rules.toWireFormat(value).toString());
2394 }
2395 }
2396
2397 /**
2398 * @api private
2399 */
2400 module.exports = QueryParamSerializer;
2401
2402
2403/***/ }),
2404/* 19 */
2405/***/ (function(module, exports, __webpack_require__) {
2406
2407 var Collection = __webpack_require__(20);
2408
2409 var util = __webpack_require__(2);
2410
2411 function property(obj, name, value) {
2412 if (value !== null && value !== undefined) {
2413 util.property.apply(this, arguments);
2414 }
2415 }
2416
2417 function memoizedProperty(obj, name) {
2418 if (!obj.constructor.prototype[name]) {
2419 util.memoizedProperty.apply(this, arguments);
2420 }
2421 }
2422
2423 function Shape(shape, options, memberName) {
2424 options = options || {};
2425
2426 property(this, 'shape', shape.shape);
2427 property(this, 'api', options.api, false);
2428 property(this, 'type', shape.type);
2429 property(this, 'enum', shape.enum);
2430 property(this, 'min', shape.min);
2431 property(this, 'max', shape.max);
2432 property(this, 'pattern', shape.pattern);
2433 property(this, 'location', shape.location || this.location || 'body');
2434 property(this, 'name', this.name || shape.xmlName || shape.queryName ||
2435 shape.locationName || memberName);
2436 property(this, 'isStreaming', shape.streaming || this.isStreaming || false);
2437 property(this, 'requiresLength', shape.requiresLength, false);
2438 property(this, 'isComposite', shape.isComposite || false);
2439 property(this, 'isShape', true, false);
2440 property(this, 'isQueryName', Boolean(shape.queryName), false);
2441 property(this, 'isLocationName', Boolean(shape.locationName), false);
2442 property(this, 'isIdempotent', shape.idempotencyToken === true);
2443 property(this, 'isJsonValue', shape.jsonvalue === true);
2444 property(this, 'isSensitive', shape.sensitive === true || shape.prototype && shape.prototype.sensitive === true);
2445 property(this, 'isEventStream', Boolean(shape.eventstream), false);
2446 property(this, 'isEvent', Boolean(shape.event), false);
2447 property(this, 'isEventPayload', Boolean(shape.eventpayload), false);
2448 property(this, 'isEventHeader', Boolean(shape.eventheader), false);
2449 property(this, 'isTimestampFormatSet', Boolean(shape.timestampFormat) || shape.prototype && shape.prototype.isTimestampFormatSet === true, false);
2450 property(this, 'endpointDiscoveryId', Boolean(shape.endpointdiscoveryid), false);
2451 property(this, 'hostLabel', Boolean(shape.hostLabel), false);
2452
2453 if (options.documentation) {
2454 property(this, 'documentation', shape.documentation);
2455 property(this, 'documentationUrl', shape.documentationUrl);
2456 }
2457
2458 if (shape.xmlAttribute) {
2459 property(this, 'isXmlAttribute', shape.xmlAttribute || false);
2460 }
2461
2462 // type conversion and parsing
2463 property(this, 'defaultValue', null);
2464 this.toWireFormat = function(value) {
2465 if (value === null || value === undefined) return '';
2466 return value;
2467 };
2468 this.toType = function(value) { return value; };
2469 }
2470
2471 /**
2472 * @api private
2473 */
2474 Shape.normalizedTypes = {
2475 character: 'string',
2476 double: 'float',
2477 long: 'integer',
2478 short: 'integer',
2479 biginteger: 'integer',
2480 bigdecimal: 'float',
2481 blob: 'binary'
2482 };
2483
2484 /**
2485 * @api private
2486 */
2487 Shape.types = {
2488 'structure': StructureShape,
2489 'list': ListShape,
2490 'map': MapShape,
2491 'boolean': BooleanShape,
2492 'timestamp': TimestampShape,
2493 'float': FloatShape,
2494 'integer': IntegerShape,
2495 'string': StringShape,
2496 'base64': Base64Shape,
2497 'binary': BinaryShape
2498 };
2499
2500 Shape.resolve = function resolve(shape, options) {
2501 if (shape.shape) {
2502 var refShape = options.api.shapes[shape.shape];
2503 if (!refShape) {
2504 throw new Error('Cannot find shape reference: ' + shape.shape);
2505 }
2506
2507 return refShape;
2508 } else {
2509 return null;
2510 }
2511 };
2512
2513 Shape.create = function create(shape, options, memberName) {
2514 if (shape.isShape) return shape;
2515
2516 var refShape = Shape.resolve(shape, options);
2517 if (refShape) {
2518 var filteredKeys = Object.keys(shape);
2519 if (!options.documentation) {
2520 filteredKeys = filteredKeys.filter(function(name) {
2521 return !name.match(/documentation/);
2522 });
2523 }
2524
2525 // create an inline shape with extra members
2526 var InlineShape = function() {
2527 refShape.constructor.call(this, shape, options, memberName);
2528 };
2529 InlineShape.prototype = refShape;
2530 return new InlineShape();
2531 } else {
2532 // set type if not set
2533 if (!shape.type) {
2534 if (shape.members) shape.type = 'structure';
2535 else if (shape.member) shape.type = 'list';
2536 else if (shape.key) shape.type = 'map';
2537 else shape.type = 'string';
2538 }
2539
2540 // normalize types
2541 var origType = shape.type;
2542 if (Shape.normalizedTypes[shape.type]) {
2543 shape.type = Shape.normalizedTypes[shape.type];
2544 }
2545
2546 if (Shape.types[shape.type]) {
2547 return new Shape.types[shape.type](shape, options, memberName);
2548 } else {
2549 throw new Error('Unrecognized shape type: ' + origType);
2550 }
2551 }
2552 };
2553
2554 function CompositeShape(shape) {
2555 Shape.apply(this, arguments);
2556 property(this, 'isComposite', true);
2557
2558 if (shape.flattened) {
2559 property(this, 'flattened', shape.flattened || false);
2560 }
2561 }
2562
2563 function StructureShape(shape, options) {
2564 var self = this;
2565 var requiredMap = null, firstInit = !this.isShape;
2566
2567 CompositeShape.apply(this, arguments);
2568
2569 if (firstInit) {
2570 property(this, 'defaultValue', function() { return {}; });
2571 property(this, 'members', {});
2572 property(this, 'memberNames', []);
2573 property(this, 'required', []);
2574 property(this, 'isRequired', function() { return false; });
2575 }
2576
2577 if (shape.members) {
2578 property(this, 'members', new Collection(shape.members, options, function(name, member) {
2579 return Shape.create(member, options, name);
2580 }));
2581 memoizedProperty(this, 'memberNames', function() {
2582 return shape.xmlOrder || Object.keys(shape.members);
2583 });
2584
2585 if (shape.event) {
2586 memoizedProperty(this, 'eventPayloadMemberName', function() {
2587 var members = self.members;
2588 var memberNames = self.memberNames;
2589 // iterate over members to find ones that are event payloads
2590 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2591 if (members[memberNames[i]].isEventPayload) {
2592 return memberNames[i];
2593 }
2594 }
2595 });
2596
2597 memoizedProperty(this, 'eventHeaderMemberNames', function() {
2598 var members = self.members;
2599 var memberNames = self.memberNames;
2600 var eventHeaderMemberNames = [];
2601 // iterate over members to find ones that are event headers
2602 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2603 if (members[memberNames[i]].isEventHeader) {
2604 eventHeaderMemberNames.push(memberNames[i]);
2605 }
2606 }
2607 return eventHeaderMemberNames;
2608 });
2609 }
2610 }
2611
2612 if (shape.required) {
2613 property(this, 'required', shape.required);
2614 property(this, 'isRequired', function(name) {
2615 if (!requiredMap) {
2616 requiredMap = {};
2617 for (var i = 0; i < shape.required.length; i++) {
2618 requiredMap[shape.required[i]] = true;
2619 }
2620 }
2621
2622 return requiredMap[name];
2623 }, false, true);
2624 }
2625
2626 property(this, 'resultWrapper', shape.resultWrapper || null);
2627
2628 if (shape.payload) {
2629 property(this, 'payload', shape.payload);
2630 }
2631
2632 if (typeof shape.xmlNamespace === 'string') {
2633 property(this, 'xmlNamespaceUri', shape.xmlNamespace);
2634 } else if (typeof shape.xmlNamespace === 'object') {
2635 property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix);
2636 property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri);
2637 }
2638 }
2639
2640 function ListShape(shape, options) {
2641 var self = this, firstInit = !this.isShape;
2642 CompositeShape.apply(this, arguments);
2643
2644 if (firstInit) {
2645 property(this, 'defaultValue', function() { return []; });
2646 }
2647
2648 if (shape.member) {
2649 memoizedProperty(this, 'member', function() {
2650 return Shape.create(shape.member, options);
2651 });
2652 }
2653
2654 if (this.flattened) {
2655 var oldName = this.name;
2656 memoizedProperty(this, 'name', function() {
2657 return self.member.name || oldName;
2658 });
2659 }
2660 }
2661
2662 function MapShape(shape, options) {
2663 var firstInit = !this.isShape;
2664 CompositeShape.apply(this, arguments);
2665
2666 if (firstInit) {
2667 property(this, 'defaultValue', function() { return {}; });
2668 property(this, 'key', Shape.create({type: 'string'}, options));
2669 property(this, 'value', Shape.create({type: 'string'}, options));
2670 }
2671
2672 if (shape.key) {
2673 memoizedProperty(this, 'key', function() {
2674 return Shape.create(shape.key, options);
2675 });
2676 }
2677 if (shape.value) {
2678 memoizedProperty(this, 'value', function() {
2679 return Shape.create(shape.value, options);
2680 });
2681 }
2682 }
2683
2684 function TimestampShape(shape) {
2685 var self = this;
2686 Shape.apply(this, arguments);
2687
2688 if (shape.timestampFormat) {
2689 property(this, 'timestampFormat', shape.timestampFormat);
2690 } else if (self.isTimestampFormatSet && this.timestampFormat) {
2691 property(this, 'timestampFormat', this.timestampFormat);
2692 } else if (this.location === 'header') {
2693 property(this, 'timestampFormat', 'rfc822');
2694 } else if (this.location === 'querystring') {
2695 property(this, 'timestampFormat', 'iso8601');
2696 } else if (this.api) {
2697 switch (this.api.protocol) {
2698 case 'json':
2699 case 'rest-json':
2700 property(this, 'timestampFormat', 'unixTimestamp');
2701 break;
2702 case 'rest-xml':
2703 case 'query':
2704 case 'ec2':
2705 property(this, 'timestampFormat', 'iso8601');
2706 break;
2707 }
2708 }
2709
2710 this.toType = function(value) {
2711 if (value === null || value === undefined) return null;
2712 if (typeof value.toUTCString === 'function') return value;
2713 return typeof value === 'string' || typeof value === 'number' ?
2714 util.date.parseTimestamp(value) : null;
2715 };
2716
2717 this.toWireFormat = function(value) {
2718 return util.date.format(value, self.timestampFormat);
2719 };
2720 }
2721
2722 function StringShape() {
2723 Shape.apply(this, arguments);
2724
2725 var nullLessProtocols = ['rest-xml', 'query', 'ec2'];
2726 this.toType = function(value) {
2727 value = this.api && nullLessProtocols.indexOf(this.api.protocol) > -1 ?
2728 value || '' : value;
2729 if (this.isJsonValue) {
2730 return JSON.parse(value);
2731 }
2732
2733 return value && typeof value.toString === 'function' ?
2734 value.toString() : value;
2735 };
2736
2737 this.toWireFormat = function(value) {
2738 return this.isJsonValue ? JSON.stringify(value) : value;
2739 };
2740 }
2741
2742 function FloatShape() {
2743 Shape.apply(this, arguments);
2744
2745 this.toType = function(value) {
2746 if (value === null || value === undefined) return null;
2747 return parseFloat(value);
2748 };
2749 this.toWireFormat = this.toType;
2750 }
2751
2752 function IntegerShape() {
2753 Shape.apply(this, arguments);
2754
2755 this.toType = function(value) {
2756 if (value === null || value === undefined) return null;
2757 return parseInt(value, 10);
2758 };
2759 this.toWireFormat = this.toType;
2760 }
2761
2762 function BinaryShape() {
2763 Shape.apply(this, arguments);
2764 this.toType = function(value) {
2765 var buf = util.base64.decode(value);
2766 if (this.isSensitive && util.isNode() && typeof util.Buffer.alloc === 'function') {
2767 /* Node.js can create a Buffer that is not isolated.
2768 * i.e. buf.byteLength !== buf.buffer.byteLength
2769 * This means that the sensitive data is accessible to anyone with access to buf.buffer.
2770 * If this is the node shared Buffer, then other code within this process _could_ find this secret.
2771 * Copy sensitive data to an isolated Buffer and zero the sensitive data.
2772 * While this is safe to do here, copying this code somewhere else may produce unexpected results.
2773 */
2774 var secureBuf = util.Buffer.alloc(buf.length, buf);
2775 buf.fill(0);
2776 buf = secureBuf;
2777 }
2778 return buf;
2779 };
2780 this.toWireFormat = util.base64.encode;
2781 }
2782
2783 function Base64Shape() {
2784 BinaryShape.apply(this, arguments);
2785 }
2786
2787 function BooleanShape() {
2788 Shape.apply(this, arguments);
2789
2790 this.toType = function(value) {
2791 if (typeof value === 'boolean') return value;
2792 if (value === null || value === undefined) return null;
2793 return value === 'true';
2794 };
2795 }
2796
2797 /**
2798 * @api private
2799 */
2800 Shape.shapes = {
2801 StructureShape: StructureShape,
2802 ListShape: ListShape,
2803 MapShape: MapShape,
2804 StringShape: StringShape,
2805 BooleanShape: BooleanShape,
2806 Base64Shape: Base64Shape
2807 };
2808
2809 /**
2810 * @api private
2811 */
2812 module.exports = Shape;
2813
2814
2815/***/ }),
2816/* 20 */
2817/***/ (function(module, exports, __webpack_require__) {
2818
2819 var memoizedProperty = __webpack_require__(2).memoizedProperty;
2820
2821 function memoize(name, value, factory, nameTr) {
2822 memoizedProperty(this, nameTr(name), function() {
2823 return factory(name, value);
2824 });
2825 }
2826
2827 function Collection(iterable, options, factory, nameTr, callback) {
2828 nameTr = nameTr || String;
2829 var self = this;
2830
2831 for (var id in iterable) {
2832 if (Object.prototype.hasOwnProperty.call(iterable, id)) {
2833 memoize.call(self, id, iterable[id], factory, nameTr);
2834 if (callback) callback(id, iterable[id]);
2835 }
2836 }
2837 }
2838
2839 /**
2840 * @api private
2841 */
2842 module.exports = Collection;
2843
2844
2845/***/ }),
2846/* 21 */
2847/***/ (function(module, exports, __webpack_require__) {
2848
2849 var util = __webpack_require__(2);
2850 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2851
2852 function populateMethod(req) {
2853 req.httpRequest.method = req.service.api.operations[req.operation].httpMethod;
2854 }
2855
2856 function generateURI(endpointPath, operationPath, input, params) {
2857 var uri = [endpointPath, operationPath].join('/');
2858 uri = uri.replace(/\/+/g, '/');
2859
2860 var queryString = {}, queryStringSet = false;
2861 util.each(input.members, function (name, member) {
2862 var paramValue = params[name];
2863 if (paramValue === null || paramValue === undefined) return;
2864 if (member.location === 'uri') {
2865 var regex = new RegExp('\\{' + member.name + '(\\+)?\\}');
2866 uri = uri.replace(regex, function(_, plus) {
2867 var fn = plus ? util.uriEscapePath : util.uriEscape;
2868 return fn(String(paramValue));
2869 });
2870 } else if (member.location === 'querystring') {
2871 queryStringSet = true;
2872
2873 if (member.type === 'list') {
2874 queryString[member.name] = paramValue.map(function(val) {
2875 return util.uriEscape(member.member.toWireFormat(val).toString());
2876 });
2877 } else if (member.type === 'map') {
2878 util.each(paramValue, function(key, value) {
2879 if (Array.isArray(value)) {
2880 queryString[key] = value.map(function(val) {
2881 return util.uriEscape(String(val));
2882 });
2883 } else {
2884 queryString[key] = util.uriEscape(String(value));
2885 }
2886 });
2887 } else {
2888 queryString[member.name] = util.uriEscape(member.toWireFormat(paramValue).toString());
2889 }
2890 }
2891 });
2892
2893 if (queryStringSet) {
2894 uri += (uri.indexOf('?') >= 0 ? '&' : '?');
2895 var parts = [];
2896 util.arrayEach(Object.keys(queryString).sort(), function(key) {
2897 if (!Array.isArray(queryString[key])) {
2898 queryString[key] = [queryString[key]];
2899 }
2900 for (var i = 0; i < queryString[key].length; i++) {
2901 parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]);
2902 }
2903 });
2904 uri += parts.join('&');
2905 }
2906
2907 return uri;
2908 }
2909
2910 function populateURI(req) {
2911 var operation = req.service.api.operations[req.operation];
2912 var input = operation.input;
2913
2914 var uri = generateURI(req.httpRequest.endpoint.path, operation.httpPath, input, req.params);
2915 req.httpRequest.path = uri;
2916 }
2917
2918 function populateHeaders(req) {
2919 var operation = req.service.api.operations[req.operation];
2920 util.each(operation.input.members, function (name, member) {
2921 var value = req.params[name];
2922 if (value === null || value === undefined) return;
2923
2924 if (member.location === 'headers' && member.type === 'map') {
2925 util.each(value, function(key, memberValue) {
2926 req.httpRequest.headers[member.name + key] = memberValue;
2927 });
2928 } else if (member.location === 'header') {
2929 value = member.toWireFormat(value).toString();
2930 if (member.isJsonValue) {
2931 value = util.base64.encode(value);
2932 }
2933 req.httpRequest.headers[member.name] = value;
2934 }
2935 });
2936 }
2937
2938 function buildRequest(req) {
2939 populateMethod(req);
2940 populateURI(req);
2941 populateHeaders(req);
2942 populateHostPrefix(req);
2943 }
2944
2945 function extractError() {
2946 }
2947
2948 function extractData(resp) {
2949 var req = resp.request;
2950 var data = {};
2951 var r = resp.httpResponse;
2952 var operation = req.service.api.operations[req.operation];
2953 var output = operation.output;
2954
2955 // normalize headers names to lower-cased keys for matching
2956 var headers = {};
2957 util.each(r.headers, function (k, v) {
2958 headers[k.toLowerCase()] = v;
2959 });
2960
2961 util.each(output.members, function(name, member) {
2962 var header = (member.name || name).toLowerCase();
2963 if (member.location === 'headers' && member.type === 'map') {
2964 data[name] = {};
2965 var location = member.isLocationName ? member.name : '';
2966 var pattern = new RegExp('^' + location + '(.+)', 'i');
2967 util.each(r.headers, function (k, v) {
2968 var result = k.match(pattern);
2969 if (result !== null) {
2970 data[name][result[1]] = v;
2971 }
2972 });
2973 } else if (member.location === 'header') {
2974 if (headers[header] !== undefined) {
2975 var value = member.isJsonValue ?
2976 util.base64.decode(headers[header]) :
2977 headers[header];
2978 data[name] = member.toType(value);
2979 }
2980 } else if (member.location === 'statusCode') {
2981 data[name] = parseInt(r.statusCode, 10);
2982 }
2983 });
2984
2985 resp.data = data;
2986 }
2987
2988 /**
2989 * @api private
2990 */
2991 module.exports = {
2992 buildRequest: buildRequest,
2993 extractError: extractError,
2994 extractData: extractData,
2995 generateURI: generateURI
2996 };
2997
2998
2999/***/ }),
3000/* 22 */
3001/***/ (function(module, exports, __webpack_require__) {
3002
3003 var util = __webpack_require__(2);
3004 var Rest = __webpack_require__(21);
3005 var Json = __webpack_require__(13);
3006 var JsonBuilder = __webpack_require__(14);
3007 var JsonParser = __webpack_require__(15);
3008
3009 function populateBody(req) {
3010 var builder = new JsonBuilder();
3011 var input = req.service.api.operations[req.operation].input;
3012
3013 if (input.payload) {
3014 var params = {};
3015 var payloadShape = input.members[input.payload];
3016 params = req.params[input.payload];
3017 if (params === undefined) return;
3018
3019 if (payloadShape.type === 'structure') {
3020 req.httpRequest.body = builder.build(params, payloadShape);
3021 applyContentTypeHeader(req);
3022 } else { // non-JSON payload
3023 req.httpRequest.body = params;
3024 if (payloadShape.type === 'binary' || payloadShape.isStreaming) {
3025 applyContentTypeHeader(req, true);
3026 }
3027 }
3028 } else {
3029 var body = builder.build(req.params, input);
3030 if (body !== '{}' || req.httpRequest.method !== 'GET') { //don't send empty body for GET method
3031 req.httpRequest.body = body;
3032 }
3033 applyContentTypeHeader(req);
3034 }
3035 }
3036
3037 function applyContentTypeHeader(req, isBinary) {
3038 var operation = req.service.api.operations[req.operation];
3039 var input = operation.input;
3040
3041 if (!req.httpRequest.headers['Content-Type']) {
3042 var type = isBinary ? 'binary/octet-stream' : 'application/json';
3043 req.httpRequest.headers['Content-Type'] = type;
3044 }
3045 }
3046
3047 function buildRequest(req) {
3048 Rest.buildRequest(req);
3049
3050 // never send body payload on HEAD/DELETE
3051 if (['HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) {
3052 populateBody(req);
3053 }
3054 }
3055
3056 function extractError(resp) {
3057 Json.extractError(resp);
3058 }
3059
3060 function extractData(resp) {
3061 Rest.extractData(resp);
3062
3063 var req = resp.request;
3064 var operation = req.service.api.operations[req.operation];
3065 var rules = req.service.api.operations[req.operation].output || {};
3066 var parser;
3067 var hasEventOutput = operation.hasEventOutput;
3068
3069 if (rules.payload) {
3070 var payloadMember = rules.members[rules.payload];
3071 var body = resp.httpResponse.body;
3072 if (payloadMember.isEventStream) {
3073 parser = new JsonParser();
3074 resp.data[payload] = util.createEventStream(
3075 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : body,
3076 parser,
3077 payloadMember
3078 );
3079 } else if (payloadMember.type === 'structure' || payloadMember.type === 'list') {
3080 var parser = new JsonParser();
3081 resp.data[rules.payload] = parser.parse(body, payloadMember);
3082 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3083 resp.data[rules.payload] = body;
3084 } else {
3085 resp.data[rules.payload] = payloadMember.toType(body);
3086 }
3087 } else {
3088 var data = resp.data;
3089 Json.extractData(resp);
3090 resp.data = util.merge(data, resp.data);
3091 }
3092 }
3093
3094 /**
3095 * @api private
3096 */
3097 module.exports = {
3098 buildRequest: buildRequest,
3099 extractError: extractError,
3100 extractData: extractData
3101 };
3102
3103
3104/***/ }),
3105/* 23 */
3106/***/ (function(module, exports, __webpack_require__) {
3107
3108 var AWS = __webpack_require__(1);
3109 var util = __webpack_require__(2);
3110 var Rest = __webpack_require__(21);
3111
3112 function populateBody(req) {
3113 var input = req.service.api.operations[req.operation].input;
3114 var builder = new AWS.XML.Builder();
3115 var params = req.params;
3116
3117 var payload = input.payload;
3118 if (payload) {
3119 var payloadMember = input.members[payload];
3120 params = params[payload];
3121 if (params === undefined) return;
3122
3123 if (payloadMember.type === 'structure') {
3124 var rootElement = payloadMember.name;
3125 req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true);
3126 } else { // non-xml payload
3127 req.httpRequest.body = params;
3128 }
3129 } else {
3130 req.httpRequest.body = builder.toXML(params, input, input.name ||
3131 input.shape || util.string.upperFirst(req.operation) + 'Request');
3132 }
3133 }
3134
3135 function buildRequest(req) {
3136 Rest.buildRequest(req);
3137
3138 // never send body payload on GET/HEAD
3139 if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) {
3140 populateBody(req);
3141 }
3142 }
3143
3144 function extractError(resp) {
3145 Rest.extractError(resp);
3146
3147 var data;
3148 try {
3149 data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString());
3150 } catch (e) {
3151 data = {
3152 Code: resp.httpResponse.statusCode,
3153 Message: resp.httpResponse.statusMessage
3154 };
3155 }
3156
3157 if (data.Errors) data = data.Errors;
3158 if (data.Error) data = data.Error;
3159 if (data.Code) {
3160 resp.error = util.error(new Error(), {
3161 code: data.Code,
3162 message: data.Message
3163 });
3164 } else {
3165 resp.error = util.error(new Error(), {
3166 code: resp.httpResponse.statusCode,
3167 message: null
3168 });
3169 }
3170 }
3171
3172 function extractData(resp) {
3173 Rest.extractData(resp);
3174
3175 var parser;
3176 var req = resp.request;
3177 var body = resp.httpResponse.body;
3178 var operation = req.service.api.operations[req.operation];
3179 var output = operation.output;
3180
3181 var hasEventOutput = operation.hasEventOutput;
3182
3183 var payload = output.payload;
3184 if (payload) {
3185 var payloadMember = output.members[payload];
3186 if (payloadMember.isEventStream) {
3187 parser = new AWS.XML.Parser();
3188 resp.data[payload] = util.createEventStream(
3189 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : resp.httpResponse.body,
3190 parser,
3191 payloadMember
3192 );
3193 } else if (payloadMember.type === 'structure') {
3194 parser = new AWS.XML.Parser();
3195 resp.data[payload] = parser.parse(body.toString(), payloadMember);
3196 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3197 resp.data[payload] = body;
3198 } else {
3199 resp.data[payload] = payloadMember.toType(body);
3200 }
3201 } else if (body.length > 0) {
3202 parser = new AWS.XML.Parser();
3203 var data = parser.parse(body.toString(), output);
3204 util.update(resp.data, data);
3205 }
3206 }
3207
3208 /**
3209 * @api private
3210 */
3211 module.exports = {
3212 buildRequest: buildRequest,
3213 extractError: extractError,
3214 extractData: extractData
3215 };
3216
3217
3218/***/ }),
3219/* 24 */
3220/***/ (function(module, exports, __webpack_require__) {
3221
3222 var util = __webpack_require__(2);
3223 var XmlNode = __webpack_require__(25).XmlNode;
3224 var XmlText = __webpack_require__(27).XmlText;
3225
3226 function XmlBuilder() { }
3227
3228 XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) {
3229 var xml = new XmlNode(rootElement);
3230 applyNamespaces(xml, shape, true);
3231 serialize(xml, params, shape);
3232 return xml.children.length > 0 || noEmpty ? xml.toString() : '';
3233 };
3234
3235 function serialize(xml, value, shape) {
3236 switch (shape.type) {
3237 case 'structure': return serializeStructure(xml, value, shape);
3238 case 'map': return serializeMap(xml, value, shape);
3239 case 'list': return serializeList(xml, value, shape);
3240 default: return serializeScalar(xml, value, shape);
3241 }
3242 }
3243
3244 function serializeStructure(xml, params, shape) {
3245 util.arrayEach(shape.memberNames, function(memberName) {
3246 var memberShape = shape.members[memberName];
3247 if (memberShape.location !== 'body') return;
3248
3249 var value = params[memberName];
3250 var name = memberShape.name;
3251 if (value !== undefined && value !== null) {
3252 if (memberShape.isXmlAttribute) {
3253 xml.addAttribute(name, value);
3254 } else if (memberShape.flattened) {
3255 serialize(xml, value, memberShape);
3256 } else {
3257 var element = new XmlNode(name);
3258 xml.addChildNode(element);
3259 applyNamespaces(element, memberShape);
3260 serialize(element, value, memberShape);
3261 }
3262 }
3263 });
3264 }
3265
3266 function serializeMap(xml, map, shape) {
3267 var xmlKey = shape.key.name || 'key';
3268 var xmlValue = shape.value.name || 'value';
3269
3270 util.each(map, function(key, value) {
3271 var entry = new XmlNode(shape.flattened ? shape.name : 'entry');
3272 xml.addChildNode(entry);
3273
3274 var entryKey = new XmlNode(xmlKey);
3275 var entryValue = new XmlNode(xmlValue);
3276 entry.addChildNode(entryKey);
3277 entry.addChildNode(entryValue);
3278
3279 serialize(entryKey, key, shape.key);
3280 serialize(entryValue, value, shape.value);
3281 });
3282 }
3283
3284 function serializeList(xml, list, shape) {
3285 if (shape.flattened) {
3286 util.arrayEach(list, function(value) {
3287 var name = shape.member.name || shape.name;
3288 var element = new XmlNode(name);
3289 xml.addChildNode(element);
3290 serialize(element, value, shape.member);
3291 });
3292 } else {
3293 util.arrayEach(list, function(value) {
3294 var name = shape.member.name || 'member';
3295 var element = new XmlNode(name);
3296 xml.addChildNode(element);
3297 serialize(element, value, shape.member);
3298 });
3299 }
3300 }
3301
3302 function serializeScalar(xml, value, shape) {
3303 xml.addChildNode(
3304 new XmlText(shape.toWireFormat(value))
3305 );
3306 }
3307
3308 function applyNamespaces(xml, shape, isRoot) {
3309 var uri, prefix = 'xmlns';
3310 if (shape.xmlNamespaceUri) {
3311 uri = shape.xmlNamespaceUri;
3312 if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix;
3313 } else if (isRoot && shape.api.xmlNamespaceUri) {
3314 uri = shape.api.xmlNamespaceUri;
3315 }
3316
3317 if (uri) xml.addAttribute(prefix, uri);
3318 }
3319
3320 /**
3321 * @api private
3322 */
3323 module.exports = XmlBuilder;
3324
3325
3326/***/ }),
3327/* 25 */
3328/***/ (function(module, exports, __webpack_require__) {
3329
3330 var escapeAttribute = __webpack_require__(26).escapeAttribute;
3331
3332 /**
3333 * Represents an XML node.
3334 * @api private
3335 */
3336 function XmlNode(name, children) {
3337 if (children === void 0) { children = []; }
3338 this.name = name;
3339 this.children = children;
3340 this.attributes = {};
3341 }
3342 XmlNode.prototype.addAttribute = function (name, value) {
3343 this.attributes[name] = value;
3344 return this;
3345 };
3346 XmlNode.prototype.addChildNode = function (child) {
3347 this.children.push(child);
3348 return this;
3349 };
3350 XmlNode.prototype.removeAttribute = function (name) {
3351 delete this.attributes[name];
3352 return this;
3353 };
3354 XmlNode.prototype.toString = function () {
3355 var hasChildren = Boolean(this.children.length);
3356 var xmlText = '<' + this.name;
3357 // add attributes
3358 var attributes = this.attributes;
3359 for (var i = 0, attributeNames = Object.keys(attributes); i < attributeNames.length; i++) {
3360 var attributeName = attributeNames[i];
3361 var attribute = attributes[attributeName];
3362 if (typeof attribute !== 'undefined' && attribute !== null) {
3363 xmlText += ' ' + attributeName + '=\"' + escapeAttribute('' + attribute) + '\"';
3364 }
3365 }
3366 return xmlText += !hasChildren ? '/>' : '>' + this.children.map(function (c) { return c.toString(); }).join('') + '</' + this.name + '>';
3367 };
3368
3369 /**
3370 * @api private
3371 */
3372 module.exports = {
3373 XmlNode: XmlNode
3374 };
3375
3376
3377/***/ }),
3378/* 26 */
3379/***/ (function(module, exports) {
3380
3381 /**
3382 * Escapes characters that can not be in an XML attribute.
3383 */
3384 function escapeAttribute(value) {
3385 return value.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
3386 }
3387
3388 /**
3389 * @api private
3390 */
3391 module.exports = {
3392 escapeAttribute: escapeAttribute
3393 };
3394
3395
3396/***/ }),
3397/* 27 */
3398/***/ (function(module, exports, __webpack_require__) {
3399
3400 var escapeElement = __webpack_require__(28).escapeElement;
3401
3402 /**
3403 * Represents an XML text value.
3404 * @api private
3405 */
3406 function XmlText(value) {
3407 this.value = value;
3408 }
3409
3410 XmlText.prototype.toString = function () {
3411 return escapeElement('' + this.value);
3412 };
3413
3414 /**
3415 * @api private
3416 */
3417 module.exports = {
3418 XmlText: XmlText
3419 };
3420
3421
3422/***/ }),
3423/* 28 */
3424/***/ (function(module, exports) {
3425
3426 /**
3427 * Escapes characters that can not be in an XML element.
3428 */
3429 function escapeElement(value) {
3430 return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3431 }
3432
3433 /**
3434 * @api private
3435 */
3436 module.exports = {
3437 escapeElement: escapeElement
3438 };
3439
3440
3441/***/ }),
3442/* 29 */
3443/***/ (function(module, exports, __webpack_require__) {
3444
3445 var Collection = __webpack_require__(20);
3446 var Operation = __webpack_require__(30);
3447 var Shape = __webpack_require__(19);
3448 var Paginator = __webpack_require__(31);
3449 var ResourceWaiter = __webpack_require__(32);
3450
3451 var util = __webpack_require__(2);
3452 var property = util.property;
3453 var memoizedProperty = util.memoizedProperty;
3454
3455 function Api(api, options) {
3456 var self = this;
3457 api = api || {};
3458 options = options || {};
3459 options.api = this;
3460
3461 api.metadata = api.metadata || {};
3462
3463 property(this, 'isApi', true, false);
3464 property(this, 'apiVersion', api.metadata.apiVersion);
3465 property(this, 'endpointPrefix', api.metadata.endpointPrefix);
3466 property(this, 'signingName', api.metadata.signingName);
3467 property(this, 'globalEndpoint', api.metadata.globalEndpoint);
3468 property(this, 'signatureVersion', api.metadata.signatureVersion);
3469 property(this, 'jsonVersion', api.metadata.jsonVersion);
3470 property(this, 'targetPrefix', api.metadata.targetPrefix);
3471 property(this, 'protocol', api.metadata.protocol);
3472 property(this, 'timestampFormat', api.metadata.timestampFormat);
3473 property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace);
3474 property(this, 'abbreviation', api.metadata.serviceAbbreviation);
3475 property(this, 'fullName', api.metadata.serviceFullName);
3476 property(this, 'serviceId', api.metadata.serviceId);
3477
3478 memoizedProperty(this, 'className', function() {
3479 var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName;
3480 if (!name) return null;
3481
3482 name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, '');
3483 if (name === 'ElasticLoadBalancing') name = 'ELB';
3484 return name;
3485 });
3486
3487 function addEndpointOperation(name, operation) {
3488 if (operation.endpointoperation === true) {
3489 property(self, 'endpointOperation', util.string.lowerFirst(name));
3490 }
3491 }
3492
3493 property(this, 'operations', new Collection(api.operations, options, function(name, operation) {
3494 return new Operation(name, operation, options);
3495 }, util.string.lowerFirst, addEndpointOperation));
3496
3497 property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) {
3498 return Shape.create(shape, options);
3499 }));
3500
3501 property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) {
3502 return new Paginator(name, paginator, options);
3503 }));
3504
3505 property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) {
3506 return new ResourceWaiter(name, waiter, options);
3507 }, util.string.lowerFirst));
3508
3509 if (options.documentation) {
3510 property(this, 'documentation', api.documentation);
3511 property(this, 'documentationUrl', api.documentationUrl);
3512 }
3513 }
3514
3515 /**
3516 * @api private
3517 */
3518 module.exports = Api;
3519
3520
3521/***/ }),
3522/* 30 */
3523/***/ (function(module, exports, __webpack_require__) {
3524
3525 var Shape = __webpack_require__(19);
3526
3527 var util = __webpack_require__(2);
3528 var property = util.property;
3529 var memoizedProperty = util.memoizedProperty;
3530
3531 function Operation(name, operation, options) {
3532 var self = this;
3533 options = options || {};
3534
3535 property(this, 'name', operation.name || name);
3536 property(this, 'api', options.api, false);
3537
3538 operation.http = operation.http || {};
3539 property(this, 'endpoint', operation.endpoint);
3540 property(this, 'httpMethod', operation.http.method || 'POST');
3541 property(this, 'httpPath', operation.http.requestUri || '/');
3542 property(this, 'authtype', operation.authtype || '');
3543 property(
3544 this,
3545 'endpointDiscoveryRequired',
3546 operation.endpointdiscovery ?
3547 (operation.endpointdiscovery.required ? 'REQUIRED' : 'OPTIONAL') :
3548 'NULL'
3549 );
3550
3551 memoizedProperty(this, 'input', function() {
3552 if (!operation.input) {
3553 return new Shape.create({type: 'structure'}, options);
3554 }
3555 return Shape.create(operation.input, options);
3556 });
3557
3558 memoizedProperty(this, 'output', function() {
3559 if (!operation.output) {
3560 return new Shape.create({type: 'structure'}, options);
3561 }
3562 return Shape.create(operation.output, options);
3563 });
3564
3565 memoizedProperty(this, 'errors', function() {
3566 var list = [];
3567 if (!operation.errors) return null;
3568
3569 for (var i = 0; i < operation.errors.length; i++) {
3570 list.push(Shape.create(operation.errors[i], options));
3571 }
3572
3573 return list;
3574 });
3575
3576 memoizedProperty(this, 'paginator', function() {
3577 return options.api.paginators[name];
3578 });
3579
3580 if (options.documentation) {
3581 property(this, 'documentation', operation.documentation);
3582 property(this, 'documentationUrl', operation.documentationUrl);
3583 }
3584
3585 // idempotentMembers only tracks top-level input shapes
3586 memoizedProperty(this, 'idempotentMembers', function() {
3587 var idempotentMembers = [];
3588 var input = self.input;
3589 var members = input.members;
3590 if (!input.members) {
3591 return idempotentMembers;
3592 }
3593 for (var name in members) {
3594 if (!members.hasOwnProperty(name)) {
3595 continue;
3596 }
3597 if (members[name].isIdempotent === true) {
3598 idempotentMembers.push(name);
3599 }
3600 }
3601 return idempotentMembers;
3602 });
3603
3604 memoizedProperty(this, 'hasEventOutput', function() {
3605 var output = self.output;
3606 return hasEventStream(output);
3607 });
3608 }
3609
3610 function hasEventStream(topLevelShape) {
3611 var members = topLevelShape.members;
3612 var payload = topLevelShape.payload;
3613
3614 if (!topLevelShape.members) {
3615 return false;
3616 }
3617
3618 if (payload) {
3619 var payloadMember = members[payload];
3620 return payloadMember.isEventStream;
3621 }
3622
3623 // check if any member is an event stream
3624 for (var name in members) {
3625 if (!members.hasOwnProperty(name)) {
3626 if (members[name].isEventStream === true) {
3627 return true;
3628 }
3629 }
3630 }
3631 return false;
3632 }
3633
3634 /**
3635 * @api private
3636 */
3637 module.exports = Operation;
3638
3639
3640/***/ }),
3641/* 31 */
3642/***/ (function(module, exports, __webpack_require__) {
3643
3644 var property = __webpack_require__(2).property;
3645
3646 function Paginator(name, paginator) {
3647 property(this, 'inputToken', paginator.input_token);
3648 property(this, 'limitKey', paginator.limit_key);
3649 property(this, 'moreResults', paginator.more_results);
3650 property(this, 'outputToken', paginator.output_token);
3651 property(this, 'resultKey', paginator.result_key);
3652 }
3653
3654 /**
3655 * @api private
3656 */
3657 module.exports = Paginator;
3658
3659
3660/***/ }),
3661/* 32 */
3662/***/ (function(module, exports, __webpack_require__) {
3663
3664 var util = __webpack_require__(2);
3665 var property = util.property;
3666
3667 function ResourceWaiter(name, waiter, options) {
3668 options = options || {};
3669 property(this, 'name', name);
3670 property(this, 'api', options.api, false);
3671
3672 if (waiter.operation) {
3673 property(this, 'operation', util.string.lowerFirst(waiter.operation));
3674 }
3675
3676 var self = this;
3677 var keys = [
3678 'type',
3679 'description',
3680 'delay',
3681 'maxAttempts',
3682 'acceptors'
3683 ];
3684
3685 keys.forEach(function(key) {
3686 var value = waiter[key];
3687 if (value) {
3688 property(self, key, value);
3689 }
3690 });
3691 }
3692
3693 /**
3694 * @api private
3695 */
3696 module.exports = ResourceWaiter;
3697
3698
3699/***/ }),
3700/* 33 */
3701/***/ (function(module, exports) {
3702
3703 function apiLoader(svc, version) {
3704 if (!apiLoader.services.hasOwnProperty(svc)) {
3705 throw new Error('InvalidService: Failed to load api for ' + svc);
3706 }
3707 return apiLoader.services[svc][version];
3708 }
3709
3710 /**
3711 * @api private
3712 *
3713 * This member of AWS.apiLoader is private, but changing it will necessitate a
3714 * change to ../scripts/services-table-generator.ts
3715 */
3716 apiLoader.services = {};
3717
3718 /**
3719 * @api private
3720 */
3721 module.exports = apiLoader;
3722
3723
3724/***/ }),
3725/* 34 */
3726/***/ (function(module, exports, __webpack_require__) {
3727
3728 "use strict";
3729 Object.defineProperty(exports, "__esModule", { value: true });
3730 var LRU_1 = __webpack_require__(35);
3731 var CACHE_SIZE = 1000;
3732 /**
3733 * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache]
3734 */
3735 var EndpointCache = /** @class */ (function () {
3736 function EndpointCache(maxSize) {
3737 if (maxSize === void 0) { maxSize = CACHE_SIZE; }
3738 this.maxSize = maxSize;
3739 this.cache = new LRU_1.LRUCache(maxSize);
3740 }
3741 ;
3742 Object.defineProperty(EndpointCache.prototype, "size", {
3743 get: function () {
3744 return this.cache.length;
3745 },
3746 enumerable: true,
3747 configurable: true
3748 });
3749 EndpointCache.prototype.put = function (key, value) {
3750 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3751 var endpointRecord = this.populateValue(value);
3752 this.cache.put(keyString, endpointRecord);
3753 };
3754 EndpointCache.prototype.get = function (key) {
3755 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3756 var now = Date.now();
3757 var records = this.cache.get(keyString);
3758 if (records) {
3759 for (var i = 0; i < records.length; i++) {
3760 var record = records[i];
3761 if (record.Expire < now) {
3762 this.cache.remove(keyString);
3763 return undefined;
3764 }
3765 }
3766 }
3767 return records;
3768 };
3769 EndpointCache.getKeyString = function (key) {
3770 var identifiers = [];
3771 var identifierNames = Object.keys(key).sort();
3772 for (var i = 0; i < identifierNames.length; i++) {
3773 var identifierName = identifierNames[i];
3774 if (key[identifierName] === undefined)
3775 continue;
3776 identifiers.push(key[identifierName]);
3777 }
3778 return identifiers.join(' ');
3779 };
3780 EndpointCache.prototype.populateValue = function (endpoints) {
3781 var now = Date.now();
3782 return endpoints.map(function (endpoint) { return ({
3783 Address: endpoint.Address || '',
3784 Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000
3785 }); });
3786 };
3787 EndpointCache.prototype.empty = function () {
3788 this.cache.empty();
3789 };
3790 EndpointCache.prototype.remove = function (key) {
3791 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3792 this.cache.remove(keyString);
3793 };
3794 return EndpointCache;
3795 }());
3796 exports.EndpointCache = EndpointCache;
3797
3798/***/ }),
3799/* 35 */
3800/***/ (function(module, exports) {
3801
3802 "use strict";
3803 Object.defineProperty(exports, "__esModule", { value: true });
3804 var LinkedListNode = /** @class */ (function () {
3805 function LinkedListNode(key, value) {
3806 this.key = key;
3807 this.value = value;
3808 }
3809 return LinkedListNode;
3810 }());
3811 var LRUCache = /** @class */ (function () {
3812 function LRUCache(size) {
3813 this.nodeMap = {};
3814 this.size = 0;
3815 if (typeof size !== 'number' || size < 1) {
3816 throw new Error('Cache size can only be positive number');
3817 }
3818 this.sizeLimit = size;
3819 }
3820 Object.defineProperty(LRUCache.prototype, "length", {
3821 get: function () {
3822 return this.size;
3823 },
3824 enumerable: true,
3825 configurable: true
3826 });
3827 LRUCache.prototype.prependToList = function (node) {
3828 if (!this.headerNode) {
3829 this.tailNode = node;
3830 }
3831 else {
3832 this.headerNode.prev = node;
3833 node.next = this.headerNode;
3834 }
3835 this.headerNode = node;
3836 this.size++;
3837 };
3838 LRUCache.prototype.removeFromTail = function () {
3839 if (!this.tailNode) {
3840 return undefined;
3841 }
3842 var node = this.tailNode;
3843 var prevNode = node.prev;
3844 if (prevNode) {
3845 prevNode.next = undefined;
3846 }
3847 node.prev = undefined;
3848 this.tailNode = prevNode;
3849 this.size--;
3850 return node;
3851 };
3852 LRUCache.prototype.detachFromList = function (node) {
3853 if (this.headerNode === node) {
3854 this.headerNode = node.next;
3855 }
3856 if (this.tailNode === node) {
3857 this.tailNode = node.prev;
3858 }
3859 if (node.prev) {
3860 node.prev.next = node.next;
3861 }
3862 if (node.next) {
3863 node.next.prev = node.prev;
3864 }
3865 node.next = undefined;
3866 node.prev = undefined;
3867 this.size--;
3868 };
3869 LRUCache.prototype.get = function (key) {
3870 if (this.nodeMap[key]) {
3871 var node = this.nodeMap[key];
3872 this.detachFromList(node);
3873 this.prependToList(node);
3874 return node.value;
3875 }
3876 };
3877 LRUCache.prototype.remove = function (key) {
3878 if (this.nodeMap[key]) {
3879 var node = this.nodeMap[key];
3880 this.detachFromList(node);
3881 delete this.nodeMap[key];
3882 }
3883 };
3884 LRUCache.prototype.put = function (key, value) {
3885 if (this.nodeMap[key]) {
3886 this.remove(key);
3887 }
3888 else if (this.size === this.sizeLimit) {
3889 var tailNode = this.removeFromTail();
3890 var key_1 = tailNode.key;
3891 delete this.nodeMap[key_1];
3892 }
3893 var newNode = new LinkedListNode(key, value);
3894 this.nodeMap[key] = newNode;
3895 this.prependToList(newNode);
3896 };
3897 LRUCache.prototype.empty = function () {
3898 var keys = Object.keys(this.nodeMap);
3899 for (var i = 0; i < keys.length; i++) {
3900 var key = keys[i];
3901 var node = this.nodeMap[key];
3902 this.detachFromList(node);
3903 delete this.nodeMap[key];
3904 }
3905 };
3906 return LRUCache;
3907 }());
3908 exports.LRUCache = LRUCache;
3909
3910/***/ }),
3911/* 36 */
3912/***/ (function(module, exports, __webpack_require__) {
3913
3914 var AWS = __webpack_require__(1);
3915
3916 /**
3917 * @api private
3918 * @!method on(eventName, callback)
3919 * Registers an event listener callback for the event given by `eventName`.
3920 * Parameters passed to the callback function depend on the individual event
3921 * being triggered. See the event documentation for those parameters.
3922 *
3923 * @param eventName [String] the event name to register the listener for
3924 * @param callback [Function] the listener callback function
3925 * @param toHead [Boolean] attach the listener callback to the head of callback array if set to true.
3926 * Default to be false.
3927 * @return [AWS.SequentialExecutor] the same object for chaining
3928 */
3929 AWS.SequentialExecutor = AWS.util.inherit({
3930
3931 constructor: function SequentialExecutor() {
3932 this._events = {};
3933 },
3934
3935 /**
3936 * @api private
3937 */
3938 listeners: function listeners(eventName) {
3939 return this._events[eventName] ? this._events[eventName].slice(0) : [];
3940 },
3941
3942 on: function on(eventName, listener, toHead) {
3943 if (this._events[eventName]) {
3944 toHead ?
3945 this._events[eventName].unshift(listener) :
3946 this._events[eventName].push(listener);
3947 } else {
3948 this._events[eventName] = [listener];
3949 }
3950 return this;
3951 },
3952
3953 onAsync: function onAsync(eventName, listener, toHead) {
3954 listener._isAsync = true;
3955 return this.on(eventName, listener, toHead);
3956 },
3957
3958 removeListener: function removeListener(eventName, listener) {
3959 var listeners = this._events[eventName];
3960 if (listeners) {
3961 var length = listeners.length;
3962 var position = -1;
3963 for (var i = 0; i < length; ++i) {
3964 if (listeners[i] === listener) {
3965 position = i;
3966 }
3967 }
3968 if (position > -1) {
3969 listeners.splice(position, 1);
3970 }
3971 }
3972 return this;
3973 },
3974
3975 removeAllListeners: function removeAllListeners(eventName) {
3976 if (eventName) {
3977 delete this._events[eventName];
3978 } else {
3979 this._events = {};
3980 }
3981 return this;
3982 },
3983
3984 /**
3985 * @api private
3986 */
3987 emit: function emit(eventName, eventArgs, doneCallback) {
3988 if (!doneCallback) doneCallback = function() { };
3989 var listeners = this.listeners(eventName);
3990 var count = listeners.length;
3991 this.callListeners(listeners, eventArgs, doneCallback);
3992 return count > 0;
3993 },
3994
3995 /**
3996 * @api private
3997 */
3998 callListeners: function callListeners(listeners, args, doneCallback, prevError) {
3999 var self = this;
4000 var error = prevError || null;
4001
4002 function callNextListener(err) {
4003 if (err) {
4004 error = AWS.util.error(error || new Error(), err);
4005 if (self._haltHandlersOnError) {
4006 return doneCallback.call(self, error);
4007 }
4008 }
4009 self.callListeners(listeners, args, doneCallback, error);
4010 }
4011
4012 while (listeners.length > 0) {
4013 var listener = listeners.shift();
4014 if (listener._isAsync) { // asynchronous listener
4015 listener.apply(self, args.concat([callNextListener]));
4016 return; // stop here, callNextListener will continue
4017 } else { // synchronous listener
4018 try {
4019 listener.apply(self, args);
4020 } catch (err) {
4021 error = AWS.util.error(error || new Error(), err);
4022 }
4023 if (error && self._haltHandlersOnError) {
4024 doneCallback.call(self, error);
4025 return;
4026 }
4027 }
4028 }
4029 doneCallback.call(self, error);
4030 },
4031
4032 /**
4033 * Adds or copies a set of listeners from another list of
4034 * listeners or SequentialExecutor object.
4035 *
4036 * @param listeners [map<String,Array<Function>>, AWS.SequentialExecutor]
4037 * a list of events and callbacks, or an event emitter object
4038 * containing listeners to add to this emitter object.
4039 * @return [AWS.SequentialExecutor] the emitter object, for chaining.
4040 * @example Adding listeners from a map of listeners
4041 * emitter.addListeners({
4042 * event1: [function() { ... }, function() { ... }],
4043 * event2: [function() { ... }]
4044 * });
4045 * emitter.emit('event1'); // emitter has event1
4046 * emitter.emit('event2'); // emitter has event2
4047 * @example Adding listeners from another emitter object
4048 * var emitter1 = new AWS.SequentialExecutor();
4049 * emitter1.on('event1', function() { ... });
4050 * emitter1.on('event2', function() { ... });
4051 * var emitter2 = new AWS.SequentialExecutor();
4052 * emitter2.addListeners(emitter1);
4053 * emitter2.emit('event1'); // emitter2 has event1
4054 * emitter2.emit('event2'); // emitter2 has event2
4055 */
4056 addListeners: function addListeners(listeners) {
4057 var self = this;
4058
4059 // extract listeners if parameter is an SequentialExecutor object
4060 if (listeners._events) listeners = listeners._events;
4061
4062 AWS.util.each(listeners, function(event, callbacks) {
4063 if (typeof callbacks === 'function') callbacks = [callbacks];
4064 AWS.util.arrayEach(callbacks, function(callback) {
4065 self.on(event, callback);
4066 });
4067 });
4068
4069 return self;
4070 },
4071
4072 /**
4073 * Registers an event with {on} and saves the callback handle function
4074 * as a property on the emitter object using a given `name`.
4075 *
4076 * @param name [String] the property name to set on this object containing
4077 * the callback function handle so that the listener can be removed in
4078 * the future.
4079 * @param (see on)
4080 * @return (see on)
4081 * @example Adding a named listener DATA_CALLBACK
4082 * var listener = function() { doSomething(); };
4083 * emitter.addNamedListener('DATA_CALLBACK', 'data', listener);
4084 *
4085 * // the following prints: true
4086 * console.log(emitter.DATA_CALLBACK == listener);
4087 */
4088 addNamedListener: function addNamedListener(name, eventName, callback, toHead) {
4089 this[name] = callback;
4090 this.addListener(eventName, callback, toHead);
4091 return this;
4092 },
4093
4094 /**
4095 * @api private
4096 */
4097 addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback, toHead) {
4098 callback._isAsync = true;
4099 return this.addNamedListener(name, eventName, callback, toHead);
4100 },
4101
4102 /**
4103 * Helper method to add a set of named listeners using
4104 * {addNamedListener}. The callback contains a parameter
4105 * with a handle to the `addNamedListener` method.
4106 *
4107 * @callback callback function(add)
4108 * The callback function is called immediately in order to provide
4109 * the `add` function to the block. This simplifies the addition of
4110 * a large group of named listeners.
4111 * @param add [Function] the {addNamedListener} function to call
4112 * when registering listeners.
4113 * @example Adding a set of named listeners
4114 * emitter.addNamedListeners(function(add) {
4115 * add('DATA_CALLBACK', 'data', function() { ... });
4116 * add('OTHER', 'otherEvent', function() { ... });
4117 * add('LAST', 'lastEvent', function() { ... });
4118 * });
4119 *
4120 * // these properties are now set:
4121 * emitter.DATA_CALLBACK;
4122 * emitter.OTHER;
4123 * emitter.LAST;
4124 */
4125 addNamedListeners: function addNamedListeners(callback) {
4126 var self = this;
4127 callback(
4128 function() {
4129 self.addNamedListener.apply(self, arguments);
4130 },
4131 function() {
4132 self.addNamedAsyncListener.apply(self, arguments);
4133 }
4134 );
4135 return this;
4136 }
4137 });
4138
4139 /**
4140 * {on} is the prefered method.
4141 * @api private
4142 */
4143 AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on;
4144
4145 /**
4146 * @api private
4147 */
4148 module.exports = AWS.SequentialExecutor;
4149
4150
4151/***/ }),
4152/* 37 */
4153/***/ (function(module, exports, __webpack_require__) {
4154
4155 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
4156 var Api = __webpack_require__(29);
4157 var regionConfig = __webpack_require__(38);
4158
4159 var inherit = AWS.util.inherit;
4160 var clientCount = 0;
4161
4162 /**
4163 * The service class representing an AWS service.
4164 *
4165 * @class_abstract This class is an abstract class.
4166 *
4167 * @!attribute apiVersions
4168 * @return [Array<String>] the list of API versions supported by this service.
4169 * @readonly
4170 */
4171 AWS.Service = inherit({
4172 /**
4173 * Create a new service object with a configuration object
4174 *
4175 * @param config [map] a map of configuration options
4176 */
4177 constructor: function Service(config) {
4178 if (!this.loadServiceClass) {
4179 throw AWS.util.error(new Error(),
4180 'Service must be constructed with `new\' operator');
4181 }
4182 var ServiceClass = this.loadServiceClass(config || {});
4183 if (ServiceClass) {
4184 var originalConfig = AWS.util.copy(config);
4185 var svc = new ServiceClass(config);
4186 Object.defineProperty(svc, '_originalConfig', {
4187 get: function() { return originalConfig; },
4188 enumerable: false,
4189 configurable: true
4190 });
4191 svc._clientId = ++clientCount;
4192 return svc;
4193 }
4194 this.initialize(config);
4195 },
4196
4197 /**
4198 * @api private
4199 */
4200 initialize: function initialize(config) {
4201 var svcConfig = AWS.config[this.serviceIdentifier];
4202 this.config = new AWS.Config(AWS.config);
4203 if (svcConfig) this.config.update(svcConfig, true);
4204 if (config) this.config.update(config, true);
4205
4206 this.validateService();
4207 if (!this.config.endpoint) regionConfig(this);
4208
4209 this.config.endpoint = this.endpointFromTemplate(this.config.endpoint);
4210 this.setEndpoint(this.config.endpoint);
4211 //enable attaching listeners to service client
4212 AWS.SequentialExecutor.call(this);
4213 AWS.Service.addDefaultMonitoringListeners(this);
4214 if ((this.config.clientSideMonitoring || AWS.Service._clientSideMonitoring) && this.publisher) {
4215 var publisher = this.publisher;
4216 this.addNamedListener('PUBLISH_API_CALL', 'apiCall', function PUBLISH_API_CALL(event) {
4217 process.nextTick(function() {publisher.eventHandler(event);});
4218 });
4219 this.addNamedListener('PUBLISH_API_ATTEMPT', 'apiCallAttempt', function PUBLISH_API_ATTEMPT(event) {
4220 process.nextTick(function() {publisher.eventHandler(event);});
4221 });
4222 }
4223 },
4224
4225 /**
4226 * @api private
4227 */
4228 validateService: function validateService() {
4229 },
4230
4231 /**
4232 * @api private
4233 */
4234 loadServiceClass: function loadServiceClass(serviceConfig) {
4235 var config = serviceConfig;
4236 if (!AWS.util.isEmpty(this.api)) {
4237 return null;
4238 } else if (config.apiConfig) {
4239 return AWS.Service.defineServiceApi(this.constructor, config.apiConfig);
4240 } else if (!this.constructor.services) {
4241 return null;
4242 } else {
4243 config = new AWS.Config(AWS.config);
4244 config.update(serviceConfig, true);
4245 var version = config.apiVersions[this.constructor.serviceIdentifier];
4246 version = version || config.apiVersion;
4247 return this.getLatestServiceClass(version);
4248 }
4249 },
4250
4251 /**
4252 * @api private
4253 */
4254 getLatestServiceClass: function getLatestServiceClass(version) {
4255 version = this.getLatestServiceVersion(version);
4256 if (this.constructor.services[version] === null) {
4257 AWS.Service.defineServiceApi(this.constructor, version);
4258 }
4259
4260 return this.constructor.services[version];
4261 },
4262
4263 /**
4264 * @api private
4265 */
4266 getLatestServiceVersion: function getLatestServiceVersion(version) {
4267 if (!this.constructor.services || this.constructor.services.length === 0) {
4268 throw new Error('No services defined on ' +
4269 this.constructor.serviceIdentifier);
4270 }
4271
4272 if (!version) {
4273 version = 'latest';
4274 } else if (AWS.util.isType(version, Date)) {
4275 version = AWS.util.date.iso8601(version).split('T')[0];
4276 }
4277
4278 if (Object.hasOwnProperty(this.constructor.services, version)) {
4279 return version;
4280 }
4281
4282 var keys = Object.keys(this.constructor.services).sort();
4283 var selectedVersion = null;
4284 for (var i = keys.length - 1; i >= 0; i--) {
4285 // versions that end in "*" are not available on disk and can be
4286 // skipped, so do not choose these as selectedVersions
4287 if (keys[i][keys[i].length - 1] !== '*') {
4288 selectedVersion = keys[i];
4289 }
4290 if (keys[i].substr(0, 10) <= version) {
4291 return selectedVersion;
4292 }
4293 }
4294
4295 throw new Error('Could not find ' + this.constructor.serviceIdentifier +
4296 ' API to satisfy version constraint `' + version + '\'');
4297 },
4298
4299 /**
4300 * @api private
4301 */
4302 api: {},
4303
4304 /**
4305 * @api private
4306 */
4307 defaultRetryCount: 3,
4308
4309 /**
4310 * @api private
4311 */
4312 customizeRequests: function customizeRequests(callback) {
4313 if (!callback) {
4314 this.customRequestHandler = null;
4315 } else if (typeof callback === 'function') {
4316 this.customRequestHandler = callback;
4317 } else {
4318 throw new Error('Invalid callback type \'' + typeof callback + '\' provided in customizeRequests');
4319 }
4320 },
4321
4322 /**
4323 * Calls an operation on a service with the given input parameters.
4324 *
4325 * @param operation [String] the name of the operation to call on the service.
4326 * @param params [map] a map of input options for the operation
4327 * @callback callback function(err, data)
4328 * If a callback is supplied, it is called when a response is returned
4329 * from the service.
4330 * @param err [Error] the error object returned from the request.
4331 * Set to `null` if the request is successful.
4332 * @param data [Object] the de-serialized data returned from
4333 * the request. Set to `null` if a request error occurs.
4334 */
4335 makeRequest: function makeRequest(operation, params, callback) {
4336 if (typeof params === 'function') {
4337 callback = params;
4338 params = null;
4339 }
4340
4341 params = params || {};
4342 if (this.config.params) { // copy only toplevel bound params
4343 var rules = this.api.operations[operation];
4344 if (rules) {
4345 params = AWS.util.copy(params);
4346 AWS.util.each(this.config.params, function(key, value) {
4347 if (rules.input.members[key]) {
4348 if (params[key] === undefined || params[key] === null) {
4349 params[key] = value;
4350 }
4351 }
4352 });
4353 }
4354 }
4355
4356 var request = new AWS.Request(this, operation, params);
4357 this.addAllRequestListeners(request);
4358 this.attachMonitoringEmitter(request);
4359 if (callback) request.send(callback);
4360 return request;
4361 },
4362
4363 /**
4364 * Calls an operation on a service with the given input parameters, without
4365 * any authentication data. This method is useful for "public" API operations.
4366 *
4367 * @param operation [String] the name of the operation to call on the service.
4368 * @param params [map] a map of input options for the operation
4369 * @callback callback function(err, data)
4370 * If a callback is supplied, it is called when a response is returned
4371 * from the service.
4372 * @param err [Error] the error object returned from the request.
4373 * Set to `null` if the request is successful.
4374 * @param data [Object] the de-serialized data returned from
4375 * the request. Set to `null` if a request error occurs.
4376 */
4377 makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) {
4378 if (typeof params === 'function') {
4379 callback = params;
4380 params = {};
4381 }
4382
4383 var request = this.makeRequest(operation, params).toUnauthenticated();
4384 return callback ? request.send(callback) : request;
4385 },
4386
4387 /**
4388 * Waits for a given state
4389 *
4390 * @param state [String] the state on the service to wait for
4391 * @param params [map] a map of parameters to pass with each request
4392 * @option params $waiter [map] a map of configuration options for the waiter
4393 * @option params $waiter.delay [Number] The number of seconds to wait between
4394 * requests
4395 * @option params $waiter.maxAttempts [Number] The maximum number of requests
4396 * to send while waiting
4397 * @callback callback function(err, data)
4398 * If a callback is supplied, it is called when a response is returned
4399 * from the service.
4400 * @param err [Error] the error object returned from the request.
4401 * Set to `null` if the request is successful.
4402 * @param data [Object] the de-serialized data returned from
4403 * the request. Set to `null` if a request error occurs.
4404 */
4405 waitFor: function waitFor(state, params, callback) {
4406 var waiter = new AWS.ResourceWaiter(this, state);
4407 return waiter.wait(params, callback);
4408 },
4409
4410 /**
4411 * @api private
4412 */
4413 addAllRequestListeners: function addAllRequestListeners(request) {
4414 var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(),
4415 AWS.EventListeners.CorePost];
4416 for (var i = 0; i < list.length; i++) {
4417 if (list[i]) request.addListeners(list[i]);
4418 }
4419
4420 // disable parameter validation
4421 if (!this.config.paramValidation) {
4422 request.removeListener('validate',
4423 AWS.EventListeners.Core.VALIDATE_PARAMETERS);
4424 }
4425
4426 if (this.config.logger) { // add logging events
4427 request.addListeners(AWS.EventListeners.Logger);
4428 }
4429
4430 this.setupRequestListeners(request);
4431 // call prototype's customRequestHandler
4432 if (typeof this.constructor.prototype.customRequestHandler === 'function') {
4433 this.constructor.prototype.customRequestHandler(request);
4434 }
4435 // call instance's customRequestHandler
4436 if (Object.prototype.hasOwnProperty.call(this, 'customRequestHandler') && typeof this.customRequestHandler === 'function') {
4437 this.customRequestHandler(request);
4438 }
4439 },
4440
4441 /**
4442 * Event recording metrics for a whole API call.
4443 * @returns {object} a subset of api call metrics
4444 * @api private
4445 */
4446 apiCallEvent: function apiCallEvent(request) {
4447 var api = request.service.api.operations[request.operation];
4448 var monitoringEvent = {
4449 Type: 'ApiCall',
4450 Api: api ? api.name : request.operation,
4451 Version: 1,
4452 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4453 Region: request.httpRequest.region,
4454 MaxRetriesExceeded: 0,
4455 UserAgent: request.httpRequest.getUserAgent(),
4456 };
4457 var response = request.response;
4458 if (response.httpResponse.statusCode) {
4459 monitoringEvent.FinalHttpStatusCode = response.httpResponse.statusCode;
4460 }
4461 if (response.error) {
4462 var error = response.error;
4463 var statusCode = response.httpResponse.statusCode;
4464 if (statusCode > 299) {
4465 if (error.code) monitoringEvent.FinalAwsException = error.code;
4466 if (error.message) monitoringEvent.FinalAwsExceptionMessage = error.message;
4467 } else {
4468 if (error.code || error.name) monitoringEvent.FinalSdkException = error.code || error.name;
4469 if (error.message) monitoringEvent.FinalSdkExceptionMessage = error.message;
4470 }
4471 }
4472 return monitoringEvent;
4473 },
4474
4475 /**
4476 * Event recording metrics for an API call attempt.
4477 * @returns {object} a subset of api call attempt metrics
4478 * @api private
4479 */
4480 apiAttemptEvent: function apiAttemptEvent(request) {
4481 var api = request.service.api.operations[request.operation];
4482 var monitoringEvent = {
4483 Type: 'ApiCallAttempt',
4484 Api: api ? api.name : request.operation,
4485 Version: 1,
4486 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4487 Fqdn: request.httpRequest.endpoint.hostname,
4488 UserAgent: request.httpRequest.getUserAgent(),
4489 };
4490 var response = request.response;
4491 if (response.httpResponse.statusCode) {
4492 monitoringEvent.HttpStatusCode = response.httpResponse.statusCode;
4493 }
4494 if (
4495 !request._unAuthenticated &&
4496 request.service.config.credentials &&
4497 request.service.config.credentials.accessKeyId
4498 ) {
4499 monitoringEvent.AccessKey = request.service.config.credentials.accessKeyId;
4500 }
4501 if (!response.httpResponse.headers) return monitoringEvent;
4502 if (request.httpRequest.headers['x-amz-security-token']) {
4503 monitoringEvent.SessionToken = request.httpRequest.headers['x-amz-security-token'];
4504 }
4505 if (response.httpResponse.headers['x-amzn-requestid']) {
4506 monitoringEvent.XAmznRequestId = response.httpResponse.headers['x-amzn-requestid'];
4507 }
4508 if (response.httpResponse.headers['x-amz-request-id']) {
4509 monitoringEvent.XAmzRequestId = response.httpResponse.headers['x-amz-request-id'];
4510 }
4511 if (response.httpResponse.headers['x-amz-id-2']) {
4512 monitoringEvent.XAmzId2 = response.httpResponse.headers['x-amz-id-2'];
4513 }
4514 return monitoringEvent;
4515 },
4516
4517 /**
4518 * Add metrics of failed request.
4519 * @api private
4520 */
4521 attemptFailEvent: function attemptFailEvent(request) {
4522 var monitoringEvent = this.apiAttemptEvent(request);
4523 var response = request.response;
4524 var error = response.error;
4525 if (response.httpResponse.statusCode > 299 ) {
4526 if (error.code) monitoringEvent.AwsException = error.code;
4527 if (error.message) monitoringEvent.AwsExceptionMessage = error.message;
4528 } else {
4529 if (error.code || error.name) monitoringEvent.SdkException = error.code || error.name;
4530 if (error.message) monitoringEvent.SdkExceptionMessage = error.message;
4531 }
4532 return monitoringEvent;
4533 },
4534
4535 /**
4536 * Attach listeners to request object to fetch metrics of each request
4537 * and emit data object through \'ApiCall\' and \'ApiCallAttempt\' events.
4538 * @api private
4539 */
4540 attachMonitoringEmitter: function attachMonitoringEmitter(request) {
4541 var attemptTimestamp; //timestamp marking the beginning of a request attempt
4542 var attemptStartRealTime; //Start time of request attempt. Used to calculating attemptLatency
4543 var attemptLatency; //latency from request sent out to http response reaching SDK
4544 var callStartRealTime; //Start time of API call. Used to calculating API call latency
4545 var attemptCount = 0; //request.retryCount is not reliable here
4546 var region; //region cache region for each attempt since it can be updated in plase (e.g. s3)
4547 var callTimestamp; //timestamp when the request is created
4548 var self = this;
4549 var addToHead = true;
4550
4551 request.on('validate', function () {
4552 callStartRealTime = AWS.util.realClock.now();
4553 callTimestamp = Date.now();
4554 }, addToHead);
4555 request.on('sign', function () {
4556 attemptStartRealTime = AWS.util.realClock.now();
4557 attemptTimestamp = Date.now();
4558 region = request.httpRequest.region;
4559 attemptCount++;
4560 }, addToHead);
4561 request.on('validateResponse', function() {
4562 attemptLatency = Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4563 });
4564 request.addNamedListener('API_CALL_ATTEMPT', 'success', function API_CALL_ATTEMPT() {
4565 var apiAttemptEvent = self.apiAttemptEvent(request);
4566 apiAttemptEvent.Timestamp = attemptTimestamp;
4567 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4568 apiAttemptEvent.Region = region;
4569 self.emit('apiCallAttempt', [apiAttemptEvent]);
4570 });
4571 request.addNamedListener('API_CALL_ATTEMPT_RETRY', 'retry', function API_CALL_ATTEMPT_RETRY() {
4572 var apiAttemptEvent = self.attemptFailEvent(request);
4573 apiAttemptEvent.Timestamp = attemptTimestamp;
4574 //attemptLatency may not be available if fail before response
4575 attemptLatency = attemptLatency ||
4576 Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4577 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4578 apiAttemptEvent.Region = region;
4579 self.emit('apiCallAttempt', [apiAttemptEvent]);
4580 });
4581 request.addNamedListener('API_CALL', 'complete', function API_CALL() {
4582 var apiCallEvent = self.apiCallEvent(request);
4583 apiCallEvent.AttemptCount = attemptCount;
4584 if (apiCallEvent.AttemptCount <= 0) return;
4585 apiCallEvent.Timestamp = callTimestamp;
4586 var latency = Math.round(AWS.util.realClock.now() - callStartRealTime);
4587 apiCallEvent.Latency = latency >= 0 ? latency : 0;
4588 var response = request.response;
4589 if (
4590 typeof response.retryCount === 'number' &&
4591 typeof response.maxRetries === 'number' &&
4592 (response.retryCount >= response.maxRetries)
4593 ) {
4594 apiCallEvent.MaxRetriesExceeded = 1;
4595 }
4596 self.emit('apiCall', [apiCallEvent]);
4597 });
4598 },
4599
4600 /**
4601 * Override this method to setup any custom request listeners for each
4602 * new request to the service.
4603 *
4604 * @method_abstract This is an abstract method.
4605 */
4606 setupRequestListeners: function setupRequestListeners(request) {
4607 },
4608
4609 /**
4610 * Gets the signer class for a given request
4611 * @api private
4612 */
4613 getSignerClass: function getSignerClass(request) {
4614 var version;
4615 // get operation authtype if present
4616 var operation = null;
4617 var authtype = '';
4618 if (request) {
4619 var operations = request.service.api.operations || {};
4620 operation = operations[request.operation] || null;
4621 authtype = operation ? operation.authtype : '';
4622 }
4623 if (this.config.signatureVersion) {
4624 version = this.config.signatureVersion;
4625 } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') {
4626 version = 'v4';
4627 } else {
4628 version = this.api.signatureVersion;
4629 }
4630 return AWS.Signers.RequestSigner.getVersion(version);
4631 },
4632
4633 /**
4634 * @api private
4635 */
4636 serviceInterface: function serviceInterface() {
4637 switch (this.api.protocol) {
4638 case 'ec2': return AWS.EventListeners.Query;
4639 case 'query': return AWS.EventListeners.Query;
4640 case 'json': return AWS.EventListeners.Json;
4641 case 'rest-json': return AWS.EventListeners.RestJson;
4642 case 'rest-xml': return AWS.EventListeners.RestXml;
4643 }
4644 if (this.api.protocol) {
4645 throw new Error('Invalid service `protocol\' ' +
4646 this.api.protocol + ' in API config');
4647 }
4648 },
4649
4650 /**
4651 * @api private
4652 */
4653 successfulResponse: function successfulResponse(resp) {
4654 return resp.httpResponse.statusCode < 300;
4655 },
4656
4657 /**
4658 * How many times a failed request should be retried before giving up.
4659 * the defaultRetryCount can be overriden by service classes.
4660 *
4661 * @api private
4662 */
4663 numRetries: function numRetries() {
4664 if (this.config.maxRetries !== undefined) {
4665 return this.config.maxRetries;
4666 } else {
4667 return this.defaultRetryCount;
4668 }
4669 },
4670
4671 /**
4672 * @api private
4673 */
4674 retryDelays: function retryDelays(retryCount) {
4675 return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions);
4676 },
4677
4678 /**
4679 * @api private
4680 */
4681 retryableError: function retryableError(error) {
4682 if (this.timeoutError(error)) return true;
4683 if (this.networkingError(error)) return true;
4684 if (this.expiredCredentialsError(error)) return true;
4685 if (this.throttledError(error)) return true;
4686 if (error.statusCode >= 500) return true;
4687 return false;
4688 },
4689
4690 /**
4691 * @api private
4692 */
4693 networkingError: function networkingError(error) {
4694 return error.code === 'NetworkingError';
4695 },
4696
4697 /**
4698 * @api private
4699 */
4700 timeoutError: function timeoutError(error) {
4701 return error.code === 'TimeoutError';
4702 },
4703
4704 /**
4705 * @api private
4706 */
4707 expiredCredentialsError: function expiredCredentialsError(error) {
4708 // TODO : this only handles *one* of the expired credential codes
4709 return (error.code === 'ExpiredTokenException');
4710 },
4711
4712 /**
4713 * @api private
4714 */
4715 clockSkewError: function clockSkewError(error) {
4716 switch (error.code) {
4717 case 'RequestTimeTooSkewed':
4718 case 'RequestExpired':
4719 case 'InvalidSignatureException':
4720 case 'SignatureDoesNotMatch':
4721 case 'AuthFailure':
4722 case 'RequestInTheFuture':
4723 return true;
4724 default: return false;
4725 }
4726 },
4727
4728 /**
4729 * @api private
4730 */
4731 getSkewCorrectedDate: function getSkewCorrectedDate() {
4732 return new Date(Date.now() + this.config.systemClockOffset);
4733 },
4734
4735 /**
4736 * @api private
4737 */
4738 applyClockOffset: function applyClockOffset(newServerTime) {
4739 if (newServerTime) {
4740 this.config.systemClockOffset = newServerTime - Date.now();
4741 }
4742 },
4743
4744 /**
4745 * @api private
4746 */
4747 isClockSkewed: function isClockSkewed(newServerTime) {
4748 if (newServerTime) {
4749 return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 30000;
4750 }
4751 },
4752
4753 /**
4754 * @api private
4755 */
4756 throttledError: function throttledError(error) {
4757 // this logic varies between services
4758 if (error.statusCode === 429) return true;
4759 switch (error.code) {
4760 case 'ProvisionedThroughputExceededException':
4761 case 'Throttling':
4762 case 'ThrottlingException':
4763 case 'RequestLimitExceeded':
4764 case 'RequestThrottled':
4765 case 'RequestThrottledException':
4766 case 'TooManyRequestsException':
4767 case 'TransactionInProgressException': //dynamodb
4768 return true;
4769 default:
4770 return false;
4771 }
4772 },
4773
4774 /**
4775 * @api private
4776 */
4777 endpointFromTemplate: function endpointFromTemplate(endpoint) {
4778 if (typeof endpoint !== 'string') return endpoint;
4779
4780 var e = endpoint;
4781 e = e.replace(/\{service\}/g, this.api.endpointPrefix);
4782 e = e.replace(/\{region\}/g, this.config.region);
4783 e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http');
4784 return e;
4785 },
4786
4787 /**
4788 * @api private
4789 */
4790 setEndpoint: function setEndpoint(endpoint) {
4791 this.endpoint = new AWS.Endpoint(endpoint, this.config);
4792 },
4793
4794 /**
4795 * @api private
4796 */
4797 paginationConfig: function paginationConfig(operation, throwException) {
4798 var paginator = this.api.operations[operation].paginator;
4799 if (!paginator) {
4800 if (throwException) {
4801 var e = new Error();
4802 throw AWS.util.error(e, 'No pagination configuration for ' + operation);
4803 }
4804 return null;
4805 }
4806
4807 return paginator;
4808 }
4809 });
4810
4811 AWS.util.update(AWS.Service, {
4812
4813 /**
4814 * Adds one method for each operation described in the api configuration
4815 *
4816 * @api private
4817 */
4818 defineMethods: function defineMethods(svc) {
4819 AWS.util.each(svc.prototype.api.operations, function iterator(method) {
4820 if (svc.prototype[method]) return;
4821 var operation = svc.prototype.api.operations[method];
4822 if (operation.authtype === 'none') {
4823 svc.prototype[method] = function (params, callback) {
4824 return this.makeUnauthenticatedRequest(method, params, callback);
4825 };
4826 } else {
4827 svc.prototype[method] = function (params, callback) {
4828 return this.makeRequest(method, params, callback);
4829 };
4830 }
4831 });
4832 },
4833
4834 /**
4835 * Defines a new Service class using a service identifier and list of versions
4836 * including an optional set of features (functions) to apply to the class
4837 * prototype.
4838 *
4839 * @param serviceIdentifier [String] the identifier for the service
4840 * @param versions [Array<String>] a list of versions that work with this
4841 * service
4842 * @param features [Object] an object to attach to the prototype
4843 * @return [Class<Service>] the service class defined by this function.
4844 */
4845 defineService: function defineService(serviceIdentifier, versions, features) {
4846 AWS.Service._serviceMap[serviceIdentifier] = true;
4847 if (!Array.isArray(versions)) {
4848 features = versions;
4849 versions = [];
4850 }
4851
4852 var svc = inherit(AWS.Service, features || {});
4853
4854 if (typeof serviceIdentifier === 'string') {
4855 AWS.Service.addVersions(svc, versions);
4856
4857 var identifier = svc.serviceIdentifier || serviceIdentifier;
4858 svc.serviceIdentifier = identifier;
4859 } else { // defineService called with an API
4860 svc.prototype.api = serviceIdentifier;
4861 AWS.Service.defineMethods(svc);
4862 }
4863 AWS.SequentialExecutor.call(this.prototype);
4864 //util.clientSideMonitoring is only available in node
4865 if (!this.prototype.publisher && AWS.util.clientSideMonitoring) {
4866 var Publisher = AWS.util.clientSideMonitoring.Publisher;
4867 var configProvider = AWS.util.clientSideMonitoring.configProvider;
4868 var publisherConfig = configProvider();
4869 this.prototype.publisher = new Publisher(publisherConfig);
4870 if (publisherConfig.enabled) {
4871 //if csm is enabled in environment, SDK should send all metrics
4872 AWS.Service._clientSideMonitoring = true;
4873 }
4874 }
4875 AWS.SequentialExecutor.call(svc.prototype);
4876 AWS.Service.addDefaultMonitoringListeners(svc.prototype);
4877 return svc;
4878 },
4879
4880 /**
4881 * @api private
4882 */
4883 addVersions: function addVersions(svc, versions) {
4884 if (!Array.isArray(versions)) versions = [versions];
4885
4886 svc.services = svc.services || {};
4887 for (var i = 0; i < versions.length; i++) {
4888 if (svc.services[versions[i]] === undefined) {
4889 svc.services[versions[i]] = null;
4890 }
4891 }
4892
4893 svc.apiVersions = Object.keys(svc.services).sort();
4894 },
4895
4896 /**
4897 * @api private
4898 */
4899 defineServiceApi: function defineServiceApi(superclass, version, apiConfig) {
4900 var svc = inherit(superclass, {
4901 serviceIdentifier: superclass.serviceIdentifier
4902 });
4903
4904 function setApi(api) {
4905 if (api.isApi) {
4906 svc.prototype.api = api;
4907 } else {
4908 svc.prototype.api = new Api(api);
4909 }
4910 }
4911
4912 if (typeof version === 'string') {
4913 if (apiConfig) {
4914 setApi(apiConfig);
4915 } else {
4916 try {
4917 setApi(AWS.apiLoader(superclass.serviceIdentifier, version));
4918 } catch (err) {
4919 throw AWS.util.error(err, {
4920 message: 'Could not find API configuration ' +
4921 superclass.serviceIdentifier + '-' + version
4922 });
4923 }
4924 }
4925 if (!Object.prototype.hasOwnProperty.call(superclass.services, version)) {
4926 superclass.apiVersions = superclass.apiVersions.concat(version).sort();
4927 }
4928 superclass.services[version] = svc;
4929 } else {
4930 setApi(version);
4931 }
4932
4933 AWS.Service.defineMethods(svc);
4934 return svc;
4935 },
4936
4937 /**
4938 * @api private
4939 */
4940 hasService: function(identifier) {
4941 return Object.prototype.hasOwnProperty.call(AWS.Service._serviceMap, identifier);
4942 },
4943
4944 /**
4945 * @param attachOn attach default monitoring listeners to object
4946 *
4947 * Each monitoring event should be emitted from service client to service constructor prototype and then
4948 * to global service prototype like bubbling up. These default monitoring events listener will transfer
4949 * the monitoring events to the upper layer.
4950 * @api private
4951 */
4952 addDefaultMonitoringListeners: function addDefaultMonitoringListeners(attachOn) {
4953 attachOn.addNamedListener('MONITOR_EVENTS_BUBBLE', 'apiCallAttempt', function EVENTS_BUBBLE(event) {
4954 var baseClass = Object.getPrototypeOf(attachOn);
4955 if (baseClass._events) baseClass.emit('apiCallAttempt', [event]);
4956 });
4957 attachOn.addNamedListener('CALL_EVENTS_BUBBLE', 'apiCall', function CALL_EVENTS_BUBBLE(event) {
4958 var baseClass = Object.getPrototypeOf(attachOn);
4959 if (baseClass._events) baseClass.emit('apiCall', [event]);
4960 });
4961 },
4962
4963 /**
4964 * @api private
4965 */
4966 _serviceMap: {}
4967 });
4968
4969 AWS.util.mixin(AWS.Service, AWS.SequentialExecutor);
4970
4971 /**
4972 * @api private
4973 */
4974 module.exports = AWS.Service;
4975
4976 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
4977
4978/***/ }),
4979/* 38 */
4980/***/ (function(module, exports, __webpack_require__) {
4981
4982 var util = __webpack_require__(2);
4983 var regionConfig = __webpack_require__(39);
4984
4985 function generateRegionPrefix(region) {
4986 if (!region) return null;
4987
4988 var parts = region.split('-');
4989 if (parts.length < 3) return null;
4990 return parts.slice(0, parts.length - 2).join('-') + '-*';
4991 }
4992
4993 function derivedKeys(service) {
4994 var region = service.config.region;
4995 var regionPrefix = generateRegionPrefix(region);
4996 var endpointPrefix = service.api.endpointPrefix;
4997
4998 return [
4999 [region, endpointPrefix],
5000 [regionPrefix, endpointPrefix],
5001 [region, '*'],
5002 [regionPrefix, '*'],
5003 ['*', endpointPrefix],
5004 ['*', '*']
5005 ].map(function(item) {
5006 return item[0] && item[1] ? item.join('/') : null;
5007 });
5008 }
5009
5010 function applyConfig(service, config) {
5011 util.each(config, function(key, value) {
5012 if (key === 'globalEndpoint') return;
5013 if (service.config[key] === undefined || service.config[key] === null) {
5014 service.config[key] = value;
5015 }
5016 });
5017 }
5018
5019 function configureEndpoint(service) {
5020 var keys = derivedKeys(service);
5021 for (var i = 0; i < keys.length; i++) {
5022 var key = keys[i];
5023 if (!key) continue;
5024
5025 if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) {
5026 var config = regionConfig.rules[key];
5027 if (typeof config === 'string') {
5028 config = regionConfig.patterns[config];
5029 }
5030
5031 // set dualstack endpoint
5032 if (service.config.useDualstack && util.isDualstackAvailable(service)) {
5033 config = util.copy(config);
5034 config.endpoint = '{service}.dualstack.{region}.amazonaws.com';
5035 }
5036
5037 // set global endpoint
5038 service.isGlobalEndpoint = !!config.globalEndpoint;
5039
5040 // signature version
5041 if (!config.signatureVersion) config.signatureVersion = 'v4';
5042
5043 // merge config
5044 applyConfig(service, config);
5045 return;
5046 }
5047 }
5048 }
5049
5050 /**
5051 * @api private
5052 */
5053 module.exports = configureEndpoint;
5054
5055
5056/***/ }),
5057/* 39 */
5058/***/ (function(module, exports) {
5059
5060 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"}}}
5061
5062/***/ }),
5063/* 40 */
5064/***/ (function(module, exports, __webpack_require__) {
5065
5066 var AWS = __webpack_require__(1);
5067 __webpack_require__(41);
5068 __webpack_require__(42);
5069 var PromisesDependency;
5070
5071 /**
5072 * The main configuration class used by all service objects to set
5073 * the region, credentials, and other options for requests.
5074 *
5075 * By default, credentials and region settings are left unconfigured.
5076 * This should be configured by the application before using any
5077 * AWS service APIs.
5078 *
5079 * In order to set global configuration options, properties should
5080 * be assigned to the global {AWS.config} object.
5081 *
5082 * @see AWS.config
5083 *
5084 * @!group General Configuration Options
5085 *
5086 * @!attribute credentials
5087 * @return [AWS.Credentials] the AWS credentials to sign requests with.
5088 *
5089 * @!attribute region
5090 * @example Set the global region setting to us-west-2
5091 * AWS.config.update({region: 'us-west-2'});
5092 * @return [AWS.Credentials] The region to send service requests to.
5093 * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
5094 * A list of available endpoints for each AWS service
5095 *
5096 * @!attribute maxRetries
5097 * @return [Integer] the maximum amount of retries to perform for a
5098 * service request. By default this value is calculated by the specific
5099 * service object that the request is being made to.
5100 *
5101 * @!attribute maxRedirects
5102 * @return [Integer] the maximum amount of redirects to follow for a
5103 * service request. Defaults to 10.
5104 *
5105 * @!attribute paramValidation
5106 * @return [Boolean|map] whether input parameters should be validated against
5107 * the operation description before sending the request. Defaults to true.
5108 * Pass a map to enable any of the following specific validation features:
5109 *
5110 * * **min** [Boolean] &mdash; Validates that a value meets the min
5111 * constraint. This is enabled by default when paramValidation is set
5112 * to `true`.
5113 * * **max** [Boolean] &mdash; Validates that a value meets the max
5114 * constraint.
5115 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5116 * regular expression.
5117 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5118 * of the allowable enum values.
5119 *
5120 * @!attribute computeChecksums
5121 * @return [Boolean] whether to compute checksums for payload bodies when
5122 * the service accepts it (currently supported in S3 only).
5123 *
5124 * @!attribute convertResponseTypes
5125 * @return [Boolean] whether types are converted when parsing response data.
5126 * Currently only supported for JSON based services. Turning this off may
5127 * improve performance on large response payloads. Defaults to `true`.
5128 *
5129 * @!attribute correctClockSkew
5130 * @return [Boolean] whether to apply a clock skew correction and retry
5131 * requests that fail because of an skewed client clock. Defaults to
5132 * `false`.
5133 *
5134 * @!attribute sslEnabled
5135 * @return [Boolean] whether SSL is enabled for requests
5136 *
5137 * @!attribute s3ForcePathStyle
5138 * @return [Boolean] whether to force path style URLs for S3 objects
5139 *
5140 * @!attribute s3BucketEndpoint
5141 * @note Setting this configuration option requires an `endpoint` to be
5142 * provided explicitly to the service constructor.
5143 * @return [Boolean] whether the provided endpoint addresses an individual
5144 * bucket (false if it addresses the root API endpoint).
5145 *
5146 * @!attribute s3DisableBodySigning
5147 * @return [Boolean] whether to disable S3 body signing when using signature version `v4`.
5148 * Body signing can only be disabled when using https. Defaults to `true`.
5149 *
5150 * @!attribute useAccelerateEndpoint
5151 * @note This configuration option is only compatible with S3 while accessing
5152 * dns-compatible buckets.
5153 * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service.
5154 * Defaults to `false`.
5155 *
5156 * @!attribute retryDelayOptions
5157 * @example Set the base retry delay for all services to 300 ms
5158 * AWS.config.update({retryDelayOptions: {base: 300}});
5159 * // Delays with maxRetries = 3: 300, 600, 1200
5160 * @example Set a custom backoff function to provide delay values on retries
5161 * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) {
5162 * // returns delay in ms
5163 * }}});
5164 * @return [map] A set of options to configure the retry delay on retryable errors.
5165 * Currently supported options are:
5166 *
5167 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5168 * exponential backoff for operation retries. Defaults to 100 ms for all services except
5169 * DynamoDB, where it defaults to 50ms.
5170 * * **customBackoff ** [function] &mdash; A custom function that accepts a retry count
5171 * and returns the amount of time to delay in milliseconds. The `base` option will be
5172 * ignored if this option is supplied.
5173 *
5174 * @!attribute httpOptions
5175 * @return [map] A set of options to pass to the low-level HTTP request.
5176 * Currently supported options are:
5177 *
5178 * * **proxy** [String] &mdash; the URL to proxy requests through
5179 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5180 * HTTP requests with. Used for connection pooling. Note that for
5181 * SSL connections, a special Agent object is used in order to enable
5182 * peer certificate verification. This feature is only supported in the
5183 * Node.js environment.
5184 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5185 * failing to establish a connection with the server after
5186 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5187 * connection has been established.
5188 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5189 * milliseconds of inactivity on the socket. Defaults to two minutes
5190 * (120000)
5191 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5192 * HTTP requests. Used in the browser environment only. Set to false to
5193 * send requests synchronously. Defaults to true (async on).
5194 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5195 * property of an XMLHttpRequest object. Used in the browser environment
5196 * only. Defaults to false.
5197 * @!attribute logger
5198 * @return [#write,#log] an object that responds to .write() (like a stream)
5199 * or .log() (like the console object) in order to log information about
5200 * requests
5201 *
5202 * @!attribute systemClockOffset
5203 * @return [Number] an offset value in milliseconds to apply to all signing
5204 * times. Use this to compensate for clock skew when your system may be
5205 * out of sync with the service time. Note that this configuration option
5206 * can only be applied to the global `AWS.config` object and cannot be
5207 * overridden in service-specific configuration. Defaults to 0 milliseconds.
5208 *
5209 * @!attribute signatureVersion
5210 * @return [String] the signature version to sign requests with (overriding
5211 * the API configuration). Possible values are: 'v2', 'v3', 'v4'.
5212 *
5213 * @!attribute signatureCache
5214 * @return [Boolean] whether the signature to sign requests with (overriding
5215 * the API configuration) is cached. Only applies to the signature version 'v4'.
5216 * Defaults to `true`.
5217 *
5218 * @!attribute endpointDiscoveryEnabled
5219 * @return [Boolean] whether to enable endpoint discovery for operations that
5220 * allow optionally using an endpoint returned by the service.
5221 * Defaults to 'false'
5222 *
5223 * @!attribute endpointCacheSize
5224 * @return [Number] the size of the global cache storing endpoints from endpoint
5225 * discovery operations. Once endpoint cache is created, updating this setting
5226 * cannot change existing cache size.
5227 * Defaults to 1000
5228 *
5229 * @!attribute hostPrefixEnabled
5230 * @return [Boolean] whether to marshal request parameters to the prefix of
5231 * hostname. Defaults to `true`.
5232 *
5233 * @!attribute stsRegionalEndpoints
5234 * @return ['legacy'|'regional'] whether to send sts request to global endpoints or
5235 * regional endpoints.
5236 * Defaults to 'legacy'
5237 */
5238 AWS.Config = AWS.util.inherit({
5239 /**
5240 * @!endgroup
5241 */
5242
5243 /**
5244 * Creates a new configuration object. This is the object that passes
5245 * option data along to service requests, including credentials, security,
5246 * region information, and some service specific settings.
5247 *
5248 * @example Creating a new configuration object with credentials and region
5249 * var config = new AWS.Config({
5250 * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
5251 * });
5252 * @option options accessKeyId [String] your AWS access key ID.
5253 * @option options secretAccessKey [String] your AWS secret access key.
5254 * @option options sessionToken [AWS.Credentials] the optional AWS
5255 * session token to sign requests with.
5256 * @option options credentials [AWS.Credentials] the AWS credentials
5257 * to sign requests with. You can either specify this object, or
5258 * specify the accessKeyId and secretAccessKey options directly.
5259 * @option options credentialProvider [AWS.CredentialProviderChain] the
5260 * provider chain used to resolve credentials if no static `credentials`
5261 * property is set.
5262 * @option options region [String] the region to send service requests to.
5263 * See {region} for more information.
5264 * @option options maxRetries [Integer] the maximum amount of retries to
5265 * attempt with a request. See {maxRetries} for more information.
5266 * @option options maxRedirects [Integer] the maximum amount of redirects to
5267 * follow with a request. See {maxRedirects} for more information.
5268 * @option options sslEnabled [Boolean] whether to enable SSL for
5269 * requests.
5270 * @option options paramValidation [Boolean|map] whether input parameters
5271 * should be validated against the operation description before sending
5272 * the request. Defaults to true. Pass a map to enable any of the
5273 * following specific validation features:
5274 *
5275 * * **min** [Boolean] &mdash; Validates that a value meets the min
5276 * constraint. This is enabled by default when paramValidation is set
5277 * to `true`.
5278 * * **max** [Boolean] &mdash; Validates that a value meets the max
5279 * constraint.
5280 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5281 * regular expression.
5282 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5283 * of the allowable enum values.
5284 * @option options computeChecksums [Boolean] whether to compute checksums
5285 * for payload bodies when the service accepts it (currently supported
5286 * in S3 only)
5287 * @option options convertResponseTypes [Boolean] whether types are converted
5288 * when parsing response data. Currently only supported for JSON based
5289 * services. Turning this off may improve performance on large response
5290 * payloads. Defaults to `true`.
5291 * @option options correctClockSkew [Boolean] whether to apply a clock skew
5292 * correction and retry requests that fail because of an skewed client
5293 * clock. Defaults to `false`.
5294 * @option options s3ForcePathStyle [Boolean] whether to force path
5295 * style URLs for S3 objects.
5296 * @option options s3BucketEndpoint [Boolean] whether the provided endpoint
5297 * addresses an individual bucket (false if it addresses the root API
5298 * endpoint). Note that setting this configuration option requires an
5299 * `endpoint` to be provided explicitly to the service constructor.
5300 * @option options s3DisableBodySigning [Boolean] whether S3 body signing
5301 * should be disabled when using signature version `v4`. Body signing
5302 * can only be disabled when using https. Defaults to `true`.
5303 *
5304 * @option options retryDelayOptions [map] A set of options to configure
5305 * the retry delay on retryable errors. Currently supported options are:
5306 *
5307 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5308 * exponential backoff for operation retries. Defaults to 100 ms for all
5309 * services except DynamoDB, where it defaults to 50ms.
5310 * * **customBackoff ** [function] &mdash; A custom function that accepts a retry count
5311 * and returns the amount of time to delay in milliseconds. The `base` option will be
5312 * ignored if this option is supplied.
5313 * @option options httpOptions [map] A set of options to pass to the low-level
5314 * HTTP request. Currently supported options are:
5315 *
5316 * * **proxy** [String] &mdash; the URL to proxy requests through
5317 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5318 * HTTP requests with. Used for connection pooling. Defaults to the global
5319 * agent (`http.globalAgent`) for non-SSL connections. Note that for
5320 * SSL connections, a special Agent object is used in order to enable
5321 * peer certificate verification. This feature is only available in the
5322 * Node.js environment.
5323 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5324 * failing to establish a connection with the server after
5325 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5326 * connection has been established.
5327 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5328 * milliseconds of inactivity on the socket. Defaults to two minutes
5329 * (120000).
5330 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5331 * HTTP requests. Used in the browser environment only. Set to false to
5332 * send requests synchronously. Defaults to true (async on).
5333 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5334 * property of an XMLHttpRequest object. Used in the browser environment
5335 * only. Defaults to false.
5336 * @option options apiVersion [String, Date] a String in YYYY-MM-DD format
5337 * (or a date) that represents the latest possible API version that can be
5338 * used in all services (unless overridden by `apiVersions`). Specify
5339 * 'latest' to use the latest possible version.
5340 * @option options apiVersions [map<String, String|Date>] a map of service
5341 * identifiers (the lowercase service class name) with the API version to
5342 * use when instantiating a service. Specify 'latest' for each individual
5343 * that can use the latest available version.
5344 * @option options logger [#write,#log] an object that responds to .write()
5345 * (like a stream) or .log() (like the console object) in order to log
5346 * information about requests
5347 * @option options systemClockOffset [Number] an offset value in milliseconds
5348 * to apply to all signing times. Use this to compensate for clock skew
5349 * when your system may be out of sync with the service time. Note that
5350 * this configuration option can only be applied to the global `AWS.config`
5351 * object and cannot be overridden in service-specific configuration.
5352 * Defaults to 0 milliseconds.
5353 * @option options signatureVersion [String] the signature version to sign
5354 * requests with (overriding the API configuration). Possible values are:
5355 * 'v2', 'v3', 'v4'.
5356 * @option options signatureCache [Boolean] whether the signature to sign
5357 * requests with (overriding the API configuration) is cached. Only applies
5358 * to the signature version 'v4'. Defaults to `true`.
5359 * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32
5360 * checksum of HTTP response bodies returned by DynamoDB. Default: `true`.
5361 * @option options useAccelerateEndpoint [Boolean] Whether to use the
5362 * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`.
5363 * @option options clientSideMonitoring [Boolean] whether to collect and
5364 * publish this client's performance metrics of all its API requests.
5365 * @option options endpointDiscoveryEnabled [Boolean] whether to enable endpoint
5366 * discovery for operations that allow optionally using an endpoint returned by
5367 * the service.
5368 * Defaults to 'false'
5369 * @option options endpointCacheSize [Number] the size of the global cache storing
5370 * endpoints from endpoint discovery operations. Once endpoint cache is created,
5371 * updating this setting cannot change existing cache size.
5372 * Defaults to 1000
5373 * @option options hostPrefixEnabled [Boolean] whether to marshal request
5374 * parameters to the prefix of hostname.
5375 * Defaults to `true`.
5376 * @option options stsRegionalEndpoints ['legacy'|'regional'] whether to send sts request
5377 * to global endpoints or regional endpoints.
5378 * Defaults to 'legacy'.
5379 */
5380 constructor: function Config(options) {
5381 if (options === undefined) options = {};
5382 options = this.extractCredentials(options);
5383
5384 AWS.util.each.call(this, this.keys, function (key, value) {
5385 this.set(key, options[key], value);
5386 });
5387 },
5388
5389 /**
5390 * @!group Managing Credentials
5391 */
5392
5393 /**
5394 * Loads credentials from the configuration object. This is used internally
5395 * by the SDK to ensure that refreshable {Credentials} objects are properly
5396 * refreshed and loaded when sending a request. If you want to ensure that
5397 * your credentials are loaded prior to a request, you can use this method
5398 * directly to provide accurate credential data stored in the object.
5399 *
5400 * @note If you configure the SDK with static or environment credentials,
5401 * the credential data should already be present in {credentials} attribute.
5402 * This method is primarily necessary to load credentials from asynchronous
5403 * sources, or sources that can refresh credentials periodically.
5404 * @example Getting your access key
5405 * AWS.config.getCredentials(function(err) {
5406 * if (err) console.log(err.stack); // credentials not loaded
5407 * else console.log("Access Key:", AWS.config.credentials.accessKeyId);
5408 * })
5409 * @callback callback function(err)
5410 * Called when the {credentials} have been properly set on the configuration
5411 * object.
5412 *
5413 * @param err [Error] if this is set, credentials were not successfully
5414 * loaded and this error provides information why.
5415 * @see credentials
5416 * @see Credentials
5417 */
5418 getCredentials: function getCredentials(callback) {
5419 var self = this;
5420
5421 function finish(err) {
5422 callback(err, err ? null : self.credentials);
5423 }
5424
5425 function credError(msg, err) {
5426 return new AWS.util.error(err || new Error(), {
5427 code: 'CredentialsError',
5428 message: msg,
5429 name: 'CredentialsError'
5430 });
5431 }
5432
5433 function getAsyncCredentials() {
5434 self.credentials.get(function(err) {
5435 if (err) {
5436 var msg = 'Could not load credentials from ' +
5437 self.credentials.constructor.name;
5438 err = credError(msg, err);
5439 }
5440 finish(err);
5441 });
5442 }
5443
5444 function getStaticCredentials() {
5445 var err = null;
5446 if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
5447 err = credError('Missing credentials');
5448 }
5449 finish(err);
5450 }
5451
5452 if (self.credentials) {
5453 if (typeof self.credentials.get === 'function') {
5454 getAsyncCredentials();
5455 } else { // static credentials
5456 getStaticCredentials();
5457 }
5458 } else if (self.credentialProvider) {
5459 self.credentialProvider.resolve(function(err, creds) {
5460 if (err) {
5461 err = credError('Could not load credentials from any providers', err);
5462 }
5463 self.credentials = creds;
5464 finish(err);
5465 });
5466 } else {
5467 finish(credError('No credentials to load'));
5468 }
5469 },
5470
5471 /**
5472 * @!group Loading and Setting Configuration Options
5473 */
5474
5475 /**
5476 * @overload update(options, allowUnknownKeys = false)
5477 * Updates the current configuration object with new options.
5478 *
5479 * @example Update maxRetries property of a configuration object
5480 * config.update({maxRetries: 10});
5481 * @param [Object] options a map of option keys and values.
5482 * @param [Boolean] allowUnknownKeys whether unknown keys can be set on
5483 * the configuration object. Defaults to `false`.
5484 * @see constructor
5485 */
5486 update: function update(options, allowUnknownKeys) {
5487 allowUnknownKeys = allowUnknownKeys || false;
5488 options = this.extractCredentials(options);
5489 AWS.util.each.call(this, options, function (key, value) {
5490 if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) ||
5491 AWS.Service.hasService(key)) {
5492 this.set(key, value);
5493 }
5494 });
5495 },
5496
5497 /**
5498 * Loads configuration data from a JSON file into this config object.
5499 * @note Loading configuration will reset all existing configuration
5500 * on the object.
5501 * @!macro nobrowser
5502 * @param path [String] the path relative to your process's current
5503 * working directory to load configuration from.
5504 * @return [AWS.Config] the same configuration object
5505 */
5506 loadFromPath: function loadFromPath(path) {
5507 this.clear();
5508
5509 var options = JSON.parse(AWS.util.readFileSync(path));
5510 var fileSystemCreds = new AWS.FileSystemCredentials(path);
5511 var chain = new AWS.CredentialProviderChain();
5512 chain.providers.unshift(fileSystemCreds);
5513 chain.resolve(function (err, creds) {
5514 if (err) throw err;
5515 else options.credentials = creds;
5516 });
5517
5518 this.constructor(options);
5519
5520 return this;
5521 },
5522
5523 /**
5524 * Clears configuration data on this object
5525 *
5526 * @api private
5527 */
5528 clear: function clear() {
5529 /*jshint forin:false */
5530 AWS.util.each.call(this, this.keys, function (key) {
5531 delete this[key];
5532 });
5533
5534 // reset credential provider
5535 this.set('credentials', undefined);
5536 this.set('credentialProvider', undefined);
5537 },
5538
5539 /**
5540 * Sets a property on the configuration object, allowing for a
5541 * default value
5542 * @api private
5543 */
5544 set: function set(property, value, defaultValue) {
5545 if (value === undefined) {
5546 if (defaultValue === undefined) {
5547 defaultValue = this.keys[property];
5548 }
5549 if (typeof defaultValue === 'function') {
5550 this[property] = defaultValue.call(this);
5551 } else {
5552 this[property] = defaultValue;
5553 }
5554 } else if (property === 'httpOptions' && this[property]) {
5555 // deep merge httpOptions
5556 this[property] = AWS.util.merge(this[property], value);
5557 } else {
5558 this[property] = value;
5559 }
5560 },
5561
5562 /**
5563 * All of the keys with their default values.
5564 *
5565 * @constant
5566 * @api private
5567 */
5568 keys: {
5569 credentials: null,
5570 credentialProvider: null,
5571 region: null,
5572 logger: null,
5573 apiVersions: {},
5574 apiVersion: null,
5575 endpoint: undefined,
5576 httpOptions: {
5577 timeout: 120000
5578 },
5579 maxRetries: undefined,
5580 maxRedirects: 10,
5581 paramValidation: true,
5582 sslEnabled: true,
5583 s3ForcePathStyle: false,
5584 s3BucketEndpoint: false,
5585 s3DisableBodySigning: true,
5586 computeChecksums: true,
5587 convertResponseTypes: true,
5588 correctClockSkew: false,
5589 customUserAgent: null,
5590 dynamoDbCrc32: true,
5591 systemClockOffset: 0,
5592 signatureVersion: null,
5593 signatureCache: true,
5594 retryDelayOptions: {},
5595 useAccelerateEndpoint: false,
5596 clientSideMonitoring: false,
5597 endpointDiscoveryEnabled: false,
5598 endpointCacheSize: 1000,
5599 hostPrefixEnabled: true,
5600 stsRegionalEndpoints: null
5601 },
5602
5603 /**
5604 * Extracts accessKeyId, secretAccessKey and sessionToken
5605 * from a configuration hash.
5606 *
5607 * @api private
5608 */
5609 extractCredentials: function extractCredentials(options) {
5610 if (options.accessKeyId && options.secretAccessKey) {
5611 options = AWS.util.copy(options);
5612 options.credentials = new AWS.Credentials(options);
5613 }
5614 return options;
5615 },
5616
5617 /**
5618 * Sets the promise dependency the SDK will use wherever Promises are returned.
5619 * Passing `null` will force the SDK to use native Promises if they are available.
5620 * If native Promises are not available, passing `null` will have no effect.
5621 * @param [Constructor] dep A reference to a Promise constructor
5622 */
5623 setPromisesDependency: function setPromisesDependency(dep) {
5624 PromisesDependency = dep;
5625 // if null was passed in, we should try to use native promises
5626 if (dep === null && typeof Promise === 'function') {
5627 PromisesDependency = Promise;
5628 }
5629 var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain];
5630 if (AWS.S3) {
5631 constructors.push(AWS.S3);
5632 if (AWS.S3.ManagedUpload) {
5633 constructors.push(AWS.S3.ManagedUpload);
5634 }
5635 }
5636 AWS.util.addPromises(constructors, PromisesDependency);
5637 },
5638
5639 /**
5640 * Gets the promise dependency set by `AWS.config.setPromisesDependency`.
5641 */
5642 getPromisesDependency: function getPromisesDependency() {
5643 return PromisesDependency;
5644 }
5645 });
5646
5647 /**
5648 * @return [AWS.Config] The global configuration object singleton instance
5649 * @readonly
5650 * @see AWS.Config
5651 */
5652 AWS.config = new AWS.Config();
5653
5654
5655/***/ }),
5656/* 41 */
5657/***/ (function(module, exports, __webpack_require__) {
5658
5659 var AWS = __webpack_require__(1);
5660
5661 /**
5662 * Represents your AWS security credentials, specifically the
5663 * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}.
5664 * Creating a `Credentials` object allows you to pass around your
5665 * security information to configuration and service objects.
5666 *
5667 * Note that this class typically does not need to be constructed manually,
5668 * as the {AWS.Config} and {AWS.Service} classes both accept simple
5669 * options hashes with the three keys. These structures will be converted
5670 * into Credentials objects automatically.
5671 *
5672 * ## Expiring and Refreshing Credentials
5673 *
5674 * Occasionally credentials can expire in the middle of a long-running
5675 * application. In this case, the SDK will automatically attempt to
5676 * refresh the credentials from the storage location if the Credentials
5677 * class implements the {refresh} method.
5678 *
5679 * If you are implementing a credential storage location, you
5680 * will want to create a subclass of the `Credentials` class and
5681 * override the {refresh} method. This method allows credentials to be
5682 * retrieved from the backing store, be it a file system, database, or
5683 * some network storage. The method should reset the credential attributes
5684 * on the object.
5685 *
5686 * @!attribute expired
5687 * @return [Boolean] whether the credentials have been expired and
5688 * require a refresh. Used in conjunction with {expireTime}.
5689 * @!attribute expireTime
5690 * @return [Date] a time when credentials should be considered expired. Used
5691 * in conjunction with {expired}.
5692 * @!attribute accessKeyId
5693 * @return [String] the AWS access key ID
5694 * @!attribute secretAccessKey
5695 * @return [String] the AWS secret access key
5696 * @!attribute sessionToken
5697 * @return [String] an optional AWS session token
5698 */
5699 AWS.Credentials = AWS.util.inherit({
5700 /**
5701 * A credentials object can be created using positional arguments or an options
5702 * hash.
5703 *
5704 * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
5705 * Creates a Credentials object with a given set of credential information
5706 * as positional arguments.
5707 * @param accessKeyId [String] the AWS access key ID
5708 * @param secretAccessKey [String] the AWS secret access key
5709 * @param sessionToken [String] the optional AWS session token
5710 * @example Create a credentials object with AWS credentials
5711 * var creds = new AWS.Credentials('akid', 'secret', 'session');
5712 * @overload AWS.Credentials(options)
5713 * Creates a Credentials object with a given set of credential information
5714 * as an options hash.
5715 * @option options accessKeyId [String] the AWS access key ID
5716 * @option options secretAccessKey [String] the AWS secret access key
5717 * @option options sessionToken [String] the optional AWS session token
5718 * @example Create a credentials object with AWS credentials
5719 * var creds = new AWS.Credentials({
5720 * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
5721 * });
5722 */
5723 constructor: function Credentials() {
5724 // hide secretAccessKey from being displayed with util.inspect
5725 AWS.util.hideProperties(this, ['secretAccessKey']);
5726
5727 this.expired = false;
5728 this.expireTime = null;
5729 this.refreshCallbacks = [];
5730 if (arguments.length === 1 && typeof arguments[0] === 'object') {
5731 var creds = arguments[0].credentials || arguments[0];
5732 this.accessKeyId = creds.accessKeyId;
5733 this.secretAccessKey = creds.secretAccessKey;
5734 this.sessionToken = creds.sessionToken;
5735 } else {
5736 this.accessKeyId = arguments[0];
5737 this.secretAccessKey = arguments[1];
5738 this.sessionToken = arguments[2];
5739 }
5740 },
5741
5742 /**
5743 * @return [Integer] the number of seconds before {expireTime} during which
5744 * the credentials will be considered expired.
5745 */
5746 expiryWindow: 15,
5747
5748 /**
5749 * @return [Boolean] whether the credentials object should call {refresh}
5750 * @note Subclasses should override this method to provide custom refresh
5751 * logic.
5752 */
5753 needsRefresh: function needsRefresh() {
5754 var currentTime = AWS.util.date.getDate().getTime();
5755 var adjustedTime = new Date(currentTime + this.expiryWindow * 1000);
5756
5757 if (this.expireTime && adjustedTime > this.expireTime) {
5758 return true;
5759 } else {
5760 return this.expired || !this.accessKeyId || !this.secretAccessKey;
5761 }
5762 },
5763
5764 /**
5765 * Gets the existing credentials, refreshing them if they are not yet loaded
5766 * or have expired. Users should call this method before using {refresh},
5767 * as this will not attempt to reload credentials when they are already
5768 * loaded into the object.
5769 *
5770 * @callback callback function(err)
5771 * When this callback is called with no error, it means either credentials
5772 * do not need to be refreshed or refreshed credentials information has
5773 * been loaded into the object (as the `accessKeyId`, `secretAccessKey`,
5774 * and `sessionToken` properties).
5775 * @param err [Error] if an error occurred, this value will be filled
5776 */
5777 get: function get(callback) {
5778 var self = this;
5779 if (this.needsRefresh()) {
5780 this.refresh(function(err) {
5781 if (!err) self.expired = false; // reset expired flag
5782 if (callback) callback(err);
5783 });
5784 } else if (callback) {
5785 callback();
5786 }
5787 },
5788
5789 /**
5790 * @!method getPromise()
5791 * Returns a 'thenable' promise.
5792 * Gets the existing credentials, refreshing them if they are not yet loaded
5793 * or have expired. Users should call this method before using {refresh},
5794 * as this will not attempt to reload credentials when they are already
5795 * loaded into the object.
5796 *
5797 * Two callbacks can be provided to the `then` method on the returned promise.
5798 * The first callback will be called if the promise is fulfilled, and the second
5799 * callback will be called if the promise is rejected.
5800 * @callback fulfilledCallback function()
5801 * Called if the promise is fulfilled. When this callback is called, it
5802 * means either credentials do not need to be refreshed or refreshed
5803 * credentials information has been loaded into the object (as the
5804 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5805 * @callback rejectedCallback function(err)
5806 * Called if the promise is rejected.
5807 * @param err [Error] if an error occurred, this value will be filled
5808 * @return [Promise] A promise that represents the state of the `get` call.
5809 * @example Calling the `getPromise` method.
5810 * var promise = credProvider.getPromise();
5811 * promise.then(function() { ... }, function(err) { ... });
5812 */
5813
5814 /**
5815 * @!method refreshPromise()
5816 * Returns a 'thenable' promise.
5817 * Refreshes the credentials. Users should call {get} before attempting
5818 * to forcibly refresh credentials.
5819 *
5820 * Two callbacks can be provided to the `then` method on the returned promise.
5821 * The first callback will be called if the promise is fulfilled, and the second
5822 * callback will be called if the promise is rejected.
5823 * @callback fulfilledCallback function()
5824 * Called if the promise is fulfilled. When this callback is called, it
5825 * means refreshed credentials information has been loaded into the object
5826 * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5827 * @callback rejectedCallback function(err)
5828 * Called if the promise is rejected.
5829 * @param err [Error] if an error occurred, this value will be filled
5830 * @return [Promise] A promise that represents the state of the `refresh` call.
5831 * @example Calling the `refreshPromise` method.
5832 * var promise = credProvider.refreshPromise();
5833 * promise.then(function() { ... }, function(err) { ... });
5834 */
5835
5836 /**
5837 * Refreshes the credentials. Users should call {get} before attempting
5838 * to forcibly refresh credentials.
5839 *
5840 * @callback callback function(err)
5841 * When this callback is called with no error, it means refreshed
5842 * credentials information has been loaded into the object (as the
5843 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5844 * @param err [Error] if an error occurred, this value will be filled
5845 * @note Subclasses should override this class to reset the
5846 * {accessKeyId}, {secretAccessKey} and optional {sessionToken}
5847 * on the credentials object and then call the callback with
5848 * any error information.
5849 * @see get
5850 */
5851 refresh: function refresh(callback) {
5852 this.expired = false;
5853 callback();
5854 },
5855
5856 /**
5857 * @api private
5858 * @param callback
5859 */
5860 coalesceRefresh: function coalesceRefresh(callback, sync) {
5861 var self = this;
5862 if (self.refreshCallbacks.push(callback) === 1) {
5863 self.load(function onLoad(err) {
5864 AWS.util.arrayEach(self.refreshCallbacks, function(callback) {
5865 if (sync) {
5866 callback(err);
5867 } else {
5868 // callback could throw, so defer to ensure all callbacks are notified
5869 AWS.util.defer(function () {
5870 callback(err);
5871 });
5872 }
5873 });
5874 self.refreshCallbacks.length = 0;
5875 });
5876 }
5877 },
5878
5879 /**
5880 * @api private
5881 * @param callback
5882 */
5883 load: function load(callback) {
5884 callback();
5885 }
5886 });
5887
5888 /**
5889 * @api private
5890 */
5891 AWS.Credentials.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
5892 this.prototype.getPromise = AWS.util.promisifyMethod('get', PromiseDependency);
5893 this.prototype.refreshPromise = AWS.util.promisifyMethod('refresh', PromiseDependency);
5894 };
5895
5896 /**
5897 * @api private
5898 */
5899 AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() {
5900 delete this.prototype.getPromise;
5901 delete this.prototype.refreshPromise;
5902 };
5903
5904 AWS.util.addPromises(AWS.Credentials);
5905
5906
5907/***/ }),
5908/* 42 */
5909/***/ (function(module, exports, __webpack_require__) {
5910
5911 var AWS = __webpack_require__(1);
5912
5913 /**
5914 * Creates a credential provider chain that searches for AWS credentials
5915 * in a list of credential providers specified by the {providers} property.
5916 *
5917 * By default, the chain will use the {defaultProviders} to resolve credentials.
5918 * These providers will look in the environment using the
5919 * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes.
5920 *
5921 * ## Setting Providers
5922 *
5923 * Each provider in the {providers} list should be a function that returns
5924 * a {AWS.Credentials} object, or a hardcoded credentials object. The function
5925 * form allows for delayed execution of the credential construction.
5926 *
5927 * ## Resolving Credentials from a Chain
5928 *
5929 * Call {resolve} to return the first valid credential object that can be
5930 * loaded by the provider chain.
5931 *
5932 * For example, to resolve a chain with a custom provider that checks a file
5933 * on disk after the set of {defaultProviders}:
5934 *
5935 * ```javascript
5936 * var diskProvider = new AWS.FileSystemCredentials('./creds.json');
5937 * var chain = new AWS.CredentialProviderChain();
5938 * chain.providers.push(diskProvider);
5939 * chain.resolve();
5940 * ```
5941 *
5942 * The above code will return the `diskProvider` object if the
5943 * file contains credentials and the `defaultProviders` do not contain
5944 * any credential settings.
5945 *
5946 * @!attribute providers
5947 * @return [Array<AWS.Credentials, Function>]
5948 * a list of credentials objects or functions that return credentials
5949 * objects. If the provider is a function, the function will be
5950 * executed lazily when the provider needs to be checked for valid
5951 * credentials. By default, this object will be set to the
5952 * {defaultProviders}.
5953 * @see defaultProviders
5954 */
5955 AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, {
5956
5957 /**
5958 * Creates a new CredentialProviderChain with a default set of providers
5959 * specified by {defaultProviders}.
5960 */
5961 constructor: function CredentialProviderChain(providers) {
5962 if (providers) {
5963 this.providers = providers;
5964 } else {
5965 this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
5966 }
5967 this.resolveCallbacks = [];
5968 },
5969
5970 /**
5971 * @!method resolvePromise()
5972 * Returns a 'thenable' promise.
5973 * Resolves the provider chain by searching for the first set of
5974 * credentials in {providers}.
5975 *
5976 * Two callbacks can be provided to the `then` method on the returned promise.
5977 * The first callback will be called if the promise is fulfilled, and the second
5978 * callback will be called if the promise is rejected.
5979 * @callback fulfilledCallback function(credentials)
5980 * Called if the promise is fulfilled and the provider resolves the chain
5981 * to a credentials object
5982 * @param credentials [AWS.Credentials] the credentials object resolved
5983 * by the provider chain.
5984 * @callback rejectedCallback function(error)
5985 * Called if the promise is rejected.
5986 * @param err [Error] the error object returned if no credentials are found.
5987 * @return [Promise] A promise that represents the state of the `resolve` method call.
5988 * @example Calling the `resolvePromise` method.
5989 * var promise = chain.resolvePromise();
5990 * promise.then(function(credentials) { ... }, function(err) { ... });
5991 */
5992
5993 /**
5994 * Resolves the provider chain by searching for the first set of
5995 * credentials in {providers}.
5996 *
5997 * @callback callback function(err, credentials)
5998 * Called when the provider resolves the chain to a credentials object
5999 * or null if no credentials can be found.
6000 *
6001 * @param err [Error] the error object returned if no credentials are
6002 * found.
6003 * @param credentials [AWS.Credentials] the credentials object resolved
6004 * by the provider chain.
6005 * @return [AWS.CredentialProviderChain] the provider, for chaining.
6006 */
6007 resolve: function resolve(callback) {
6008 var self = this;
6009 if (self.providers.length === 0) {
6010 callback(new Error('No providers'));
6011 return self;
6012 }
6013
6014 if (self.resolveCallbacks.push(callback) === 1) {
6015 var index = 0;
6016 var providers = self.providers.slice(0);
6017
6018 function resolveNext(err, creds) {
6019 if ((!err && creds) || index === providers.length) {
6020 AWS.util.arrayEach(self.resolveCallbacks, function (callback) {
6021 callback(err, creds);
6022 });
6023 self.resolveCallbacks.length = 0;
6024 return;
6025 }
6026
6027 var provider = providers[index++];
6028 if (typeof provider === 'function') {
6029 creds = provider.call();
6030 } else {
6031 creds = provider;
6032 }
6033
6034 if (creds.get) {
6035 creds.get(function (getErr) {
6036 resolveNext(getErr, getErr ? null : creds);
6037 });
6038 } else {
6039 resolveNext(null, creds);
6040 }
6041 }
6042
6043 resolveNext();
6044 }
6045
6046 return self;
6047 }
6048 });
6049
6050 /**
6051 * The default set of providers used by a vanilla CredentialProviderChain.
6052 *
6053 * In the browser:
6054 *
6055 * ```javascript
6056 * AWS.CredentialProviderChain.defaultProviders = []
6057 * ```
6058 *
6059 * In Node.js:
6060 *
6061 * ```javascript
6062 * AWS.CredentialProviderChain.defaultProviders = [
6063 * function () { return new AWS.EnvironmentCredentials('AWS'); },
6064 * function () { return new AWS.EnvironmentCredentials('AMAZON'); },
6065 * function () { return new AWS.SharedIniFileCredentials(); },
6066 * function () { return new AWS.ECSCredentials(); },
6067 * function () { return new AWS.ProcessCredentials(); },
6068 * function () { return new AWS.TokenFileWebIdentityCredentials(); },
6069 * function () { return new AWS.EC2MetadataCredentials() }
6070 * ]
6071 * ```
6072 */
6073 AWS.CredentialProviderChain.defaultProviders = [];
6074
6075 /**
6076 * @api private
6077 */
6078 AWS.CredentialProviderChain.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
6079 this.prototype.resolvePromise = AWS.util.promisifyMethod('resolve', PromiseDependency);
6080 };
6081
6082 /**
6083 * @api private
6084 */
6085 AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFromClass() {
6086 delete this.prototype.resolvePromise;
6087 };
6088
6089 AWS.util.addPromises(AWS.CredentialProviderChain);
6090
6091
6092/***/ }),
6093/* 43 */
6094/***/ (function(module, exports, __webpack_require__) {
6095
6096 var AWS = __webpack_require__(1);
6097 var inherit = AWS.util.inherit;
6098
6099 /**
6100 * The endpoint that a service will talk to, for example,
6101 * `'https://ec2.ap-southeast-1.amazonaws.com'`. If
6102 * you need to override an endpoint for a service, you can
6103 * set the endpoint on a service by passing the endpoint
6104 * object with the `endpoint` option key:
6105 *
6106 * ```javascript
6107 * var ep = new AWS.Endpoint('awsproxy.example.com');
6108 * var s3 = new AWS.S3({endpoint: ep});
6109 * s3.service.endpoint.hostname == 'awsproxy.example.com'
6110 * ```
6111 *
6112 * Note that if you do not specify a protocol, the protocol will
6113 * be selected based on your current {AWS.config} configuration.
6114 *
6115 * @!attribute protocol
6116 * @return [String] the protocol (http or https) of the endpoint
6117 * URL
6118 * @!attribute hostname
6119 * @return [String] the host portion of the endpoint, e.g.,
6120 * example.com
6121 * @!attribute host
6122 * @return [String] the host portion of the endpoint including
6123 * the port, e.g., example.com:80
6124 * @!attribute port
6125 * @return [Integer] the port of the endpoint
6126 * @!attribute href
6127 * @return [String] the full URL of the endpoint
6128 */
6129 AWS.Endpoint = inherit({
6130
6131 /**
6132 * @overload Endpoint(endpoint)
6133 * Constructs a new endpoint given an endpoint URL. If the
6134 * URL omits a protocol (http or https), the default protocol
6135 * set in the global {AWS.config} will be used.
6136 * @param endpoint [String] the URL to construct an endpoint from
6137 */
6138 constructor: function Endpoint(endpoint, config) {
6139 AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']);
6140
6141 if (typeof endpoint === 'undefined' || endpoint === null) {
6142 throw new Error('Invalid endpoint: ' + endpoint);
6143 } else if (typeof endpoint !== 'string') {
6144 return AWS.util.copy(endpoint);
6145 }
6146
6147 if (!endpoint.match(/^http/)) {
6148 var useSSL = config && config.sslEnabled !== undefined ?
6149 config.sslEnabled : AWS.config.sslEnabled;
6150 endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
6151 }
6152
6153 AWS.util.update(this, AWS.util.urlParse(endpoint));
6154
6155 // Ensure the port property is set as an integer
6156 if (this.port) {
6157 this.port = parseInt(this.port, 10);
6158 } else {
6159 this.port = this.protocol === 'https:' ? 443 : 80;
6160 }
6161 }
6162
6163 });
6164
6165 /**
6166 * The low level HTTP request object, encapsulating all HTTP header
6167 * and body data sent by a service request.
6168 *
6169 * @!attribute method
6170 * @return [String] the HTTP method of the request
6171 * @!attribute path
6172 * @return [String] the path portion of the URI, e.g.,
6173 * "/list/?start=5&num=10"
6174 * @!attribute headers
6175 * @return [map<String,String>]
6176 * a map of header keys and their respective values
6177 * @!attribute body
6178 * @return [String] the request body payload
6179 * @!attribute endpoint
6180 * @return [AWS.Endpoint] the endpoint for the request
6181 * @!attribute region
6182 * @api private
6183 * @return [String] the region, for signing purposes only.
6184 */
6185 AWS.HttpRequest = inherit({
6186
6187 /**
6188 * @api private
6189 */
6190 constructor: function HttpRequest(endpoint, region) {
6191 endpoint = new AWS.Endpoint(endpoint);
6192 this.method = 'POST';
6193 this.path = endpoint.path || '/';
6194 this.headers = {};
6195 this.body = '';
6196 this.endpoint = endpoint;
6197 this.region = region;
6198 this._userAgent = '';
6199 this.setUserAgent();
6200 },
6201
6202 /**
6203 * @api private
6204 */
6205 setUserAgent: function setUserAgent() {
6206 this._userAgent = this.headers[this.getUserAgentHeaderName()] = AWS.util.userAgent();
6207 },
6208
6209 getUserAgentHeaderName: function getUserAgentHeaderName() {
6210 var prefix = AWS.util.isBrowser() ? 'X-Amz-' : '';
6211 return prefix + 'User-Agent';
6212 },
6213
6214 /**
6215 * @api private
6216 */
6217 appendToUserAgent: function appendToUserAgent(agentPartial) {
6218 if (typeof agentPartial === 'string' && agentPartial) {
6219 this._userAgent += ' ' + agentPartial;
6220 }
6221 this.headers[this.getUserAgentHeaderName()] = this._userAgent;
6222 },
6223
6224 /**
6225 * @api private
6226 */
6227 getUserAgent: function getUserAgent() {
6228 return this._userAgent;
6229 },
6230
6231 /**
6232 * @return [String] the part of the {path} excluding the
6233 * query string
6234 */
6235 pathname: function pathname() {
6236 return this.path.split('?', 1)[0];
6237 },
6238
6239 /**
6240 * @return [String] the query string portion of the {path}
6241 */
6242 search: function search() {
6243 var query = this.path.split('?', 2)[1];
6244 if (query) {
6245 query = AWS.util.queryStringParse(query);
6246 return AWS.util.queryParamsToString(query);
6247 }
6248 return '';
6249 },
6250
6251 /**
6252 * @api private
6253 * update httpRequest endpoint with endpoint string
6254 */
6255 updateEndpoint: function updateEndpoint(endpointStr) {
6256 var newEndpoint = new AWS.Endpoint(endpointStr);
6257 this.endpoint = newEndpoint;
6258 this.path = newEndpoint.path || '/';
6259 }
6260 });
6261
6262 /**
6263 * The low level HTTP response object, encapsulating all HTTP header
6264 * and body data returned from the request.
6265 *
6266 * @!attribute statusCode
6267 * @return [Integer] the HTTP status code of the response (e.g., 200, 404)
6268 * @!attribute headers
6269 * @return [map<String,String>]
6270 * a map of response header keys and their respective values
6271 * @!attribute body
6272 * @return [String] the response body payload
6273 * @!attribute [r] streaming
6274 * @return [Boolean] whether this response is being streamed at a low-level.
6275 * Defaults to `false` (buffered reads). Do not modify this manually, use
6276 * {createUnbufferedStream} to convert the stream to unbuffered mode
6277 * instead.
6278 */
6279 AWS.HttpResponse = inherit({
6280
6281 /**
6282 * @api private
6283 */
6284 constructor: function HttpResponse() {
6285 this.statusCode = undefined;
6286 this.headers = {};
6287 this.body = undefined;
6288 this.streaming = false;
6289 this.stream = null;
6290 },
6291
6292 /**
6293 * Disables buffering on the HTTP response and returns the stream for reading.
6294 * @return [Stream, XMLHttpRequest, null] the underlying stream object.
6295 * Use this object to directly read data off of the stream.
6296 * @note This object is only available after the {AWS.Request~httpHeaders}
6297 * event has fired. This method must be called prior to
6298 * {AWS.Request~httpData}.
6299 * @example Taking control of a stream
6300 * request.on('httpHeaders', function(statusCode, headers) {
6301 * if (statusCode < 300) {
6302 * if (headers.etag === 'xyz') {
6303 * // pipe the stream, disabling buffering
6304 * var stream = this.response.httpResponse.createUnbufferedStream();
6305 * stream.pipe(process.stdout);
6306 * } else { // abort this request and set a better error message
6307 * this.abort();
6308 * this.response.error = new Error('Invalid ETag');
6309 * }
6310 * }
6311 * }).send(console.log);
6312 */
6313 createUnbufferedStream: function createUnbufferedStream() {
6314 this.streaming = true;
6315 return this.stream;
6316 }
6317 });
6318
6319
6320 AWS.HttpClient = inherit({});
6321
6322 /**
6323 * @api private
6324 */
6325 AWS.HttpClient.getInstance = function getInstance() {
6326 if (this.singleton === undefined) {
6327 this.singleton = new this();
6328 }
6329 return this.singleton;
6330 };
6331
6332
6333/***/ }),
6334/* 44 */
6335/***/ (function(module, exports, __webpack_require__) {
6336
6337 var AWS = __webpack_require__(1);
6338 var SequentialExecutor = __webpack_require__(36);
6339 var DISCOVER_ENDPOINT = __webpack_require__(45).discoverEndpoint;
6340 /**
6341 * The namespace used to register global event listeners for request building
6342 * and sending.
6343 */
6344 AWS.EventListeners = {
6345 /**
6346 * @!attribute VALIDATE_CREDENTIALS
6347 * A request listener that validates whether the request is being
6348 * sent with credentials.
6349 * Handles the {AWS.Request~validate 'validate' Request event}
6350 * @example Sending a request without validating credentials
6351 * var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS;
6352 * request.removeListener('validate', listener);
6353 * @readonly
6354 * @return [Function]
6355 * @!attribute VALIDATE_REGION
6356 * A request listener that validates whether the region is set
6357 * for a request.
6358 * Handles the {AWS.Request~validate 'validate' Request event}
6359 * @example Sending a request without validating region configuration
6360 * var listener = AWS.EventListeners.Core.VALIDATE_REGION;
6361 * request.removeListener('validate', listener);
6362 * @readonly
6363 * @return [Function]
6364 * @!attribute VALIDATE_PARAMETERS
6365 * A request listener that validates input parameters in a request.
6366 * Handles the {AWS.Request~validate 'validate' Request event}
6367 * @example Sending a request without validating parameters
6368 * var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS;
6369 * request.removeListener('validate', listener);
6370 * @example Disable parameter validation globally
6371 * AWS.EventListeners.Core.removeListener('validate',
6372 * AWS.EventListeners.Core.VALIDATE_REGION);
6373 * @readonly
6374 * @return [Function]
6375 * @!attribute SEND
6376 * A request listener that initiates the HTTP connection for a
6377 * request being sent. Handles the {AWS.Request~send 'send' Request event}
6378 * @example Replacing the HTTP handler
6379 * var listener = AWS.EventListeners.Core.SEND;
6380 * request.removeListener('send', listener);
6381 * request.on('send', function(response) {
6382 * customHandler.send(response);
6383 * });
6384 * @return [Function]
6385 * @readonly
6386 * @!attribute HTTP_DATA
6387 * A request listener that reads data from the HTTP connection in order
6388 * to build the response data.
6389 * Handles the {AWS.Request~httpData 'httpData' Request event}.
6390 * Remove this handler if you are overriding the 'httpData' event and
6391 * do not want extra data processing and buffering overhead.
6392 * @example Disabling default data processing
6393 * var listener = AWS.EventListeners.Core.HTTP_DATA;
6394 * request.removeListener('httpData', listener);
6395 * @return [Function]
6396 * @readonly
6397 */
6398 Core: {} /* doc hack */
6399 };
6400
6401 /**
6402 * @api private
6403 */
6404 function getOperationAuthtype(req) {
6405 if (!req.service.api.operations) {
6406 return '';
6407 }
6408 var operation = req.service.api.operations[req.operation];
6409 return operation ? operation.authtype : '';
6410 }
6411
6412 AWS.EventListeners = {
6413 Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) {
6414 addAsync('VALIDATE_CREDENTIALS', 'validate',
6415 function VALIDATE_CREDENTIALS(req, done) {
6416 if (!req.service.api.signatureVersion && !req.service.config.signatureVersion) return done(); // none
6417 req.service.config.getCredentials(function(err) {
6418 if (err) {
6419 req.response.error = AWS.util.error(err,
6420 {code: 'CredentialsError', message: 'Missing credentials in config'});
6421 }
6422 done();
6423 });
6424 });
6425
6426 add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
6427 if (!req.service.config.region && !req.service.isGlobalEndpoint) {
6428 req.response.error = AWS.util.error(new Error(),
6429 {code: 'ConfigError', message: 'Missing region in config'});
6430 }
6431 });
6432
6433 add('BUILD_IDEMPOTENCY_TOKENS', 'validate', function BUILD_IDEMPOTENCY_TOKENS(req) {
6434 if (!req.service.api.operations) {
6435 return;
6436 }
6437 var operation = req.service.api.operations[req.operation];
6438 if (!operation) {
6439 return;
6440 }
6441 var idempotentMembers = operation.idempotentMembers;
6442 if (!idempotentMembers.length) {
6443 return;
6444 }
6445 // creates a copy of params so user's param object isn't mutated
6446 var params = AWS.util.copy(req.params);
6447 for (var i = 0, iLen = idempotentMembers.length; i < iLen; i++) {
6448 if (!params[idempotentMembers[i]]) {
6449 // add the member
6450 params[idempotentMembers[i]] = AWS.util.uuid.v4();
6451 }
6452 }
6453 req.params = params;
6454 });
6455
6456 add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) {
6457 if (!req.service.api.operations) {
6458 return;
6459 }
6460 var rules = req.service.api.operations[req.operation].input;
6461 var validation = req.service.config.paramValidation;
6462 new AWS.ParamValidator(validation).validate(rules, req.params);
6463 });
6464
6465 addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) {
6466 req.haltHandlersOnError();
6467 if (!req.service.api.operations) {
6468 return;
6469 }
6470 var operation = req.service.api.operations[req.operation];
6471 var authtype = operation ? operation.authtype : '';
6472 if (!req.service.api.signatureVersion && !authtype && !req.service.config.signatureVersion) return done(); // none
6473 if (req.service.getSignerClass(req) === AWS.Signers.V4) {
6474 var body = req.httpRequest.body || '';
6475 if (authtype.indexOf('unsigned-body') >= 0) {
6476 req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD';
6477 return done();
6478 }
6479 AWS.util.computeSha256(body, function(err, sha) {
6480 if (err) {
6481 done(err);
6482 }
6483 else {
6484 req.httpRequest.headers['X-Amz-Content-Sha256'] = sha;
6485 done();
6486 }
6487 });
6488 } else {
6489 done();
6490 }
6491 });
6492
6493 add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) {
6494 var authtype = getOperationAuthtype(req);
6495 var payloadMember = AWS.util.getRequestPayloadShape(req);
6496 if (req.httpRequest.headers['Content-Length'] === undefined) {
6497 try {
6498 var length = AWS.util.string.byteLength(req.httpRequest.body);
6499 req.httpRequest.headers['Content-Length'] = length;
6500 } catch (err) {
6501 if (payloadMember && payloadMember.isStreaming) {
6502 if (payloadMember.requiresLength) {
6503 //streaming payload requires length(s3, glacier)
6504 throw err;
6505 } else if (authtype.indexOf('unsigned-body') >= 0) {
6506 //unbounded streaming payload(lex, mediastore)
6507 req.httpRequest.headers['Transfer-Encoding'] = 'chunked';
6508 return;
6509 } else {
6510 throw err;
6511 }
6512 }
6513 throw err;
6514 }
6515 }
6516 });
6517
6518 add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) {
6519 req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host;
6520 });
6521
6522 add('RESTART', 'restart', function RESTART() {
6523 var err = this.response.error;
6524 if (!err || !err.retryable) return;
6525
6526 this.httpRequest = new AWS.HttpRequest(
6527 this.service.endpoint,
6528 this.service.region
6529 );
6530
6531 if (this.response.retryCount < this.service.config.maxRetries) {
6532 this.response.retryCount++;
6533 } else {
6534 this.response.error = null;
6535 }
6536 });
6537
6538 var addToHead = true;
6539 addAsync('DISCOVER_ENDPOINT', 'sign', DISCOVER_ENDPOINT, addToHead);
6540
6541 addAsync('SIGN', 'sign', function SIGN(req, done) {
6542 var service = req.service;
6543 var operations = req.service.api.operations || {};
6544 var operation = operations[req.operation];
6545 var authtype = operation ? operation.authtype : '';
6546 if (!service.api.signatureVersion && !authtype && !service.config.signatureVersion) return done(); // none
6547
6548 service.config.getCredentials(function (err, credentials) {
6549 if (err) {
6550 req.response.error = err;
6551 return done();
6552 }
6553
6554 try {
6555 var date = service.getSkewCorrectedDate();
6556 var SignerClass = service.getSignerClass(req);
6557 var signer = new SignerClass(req.httpRequest,
6558 service.api.signingName || service.api.endpointPrefix,
6559 {
6560 signatureCache: service.config.signatureCache,
6561 operation: operation,
6562 signatureVersion: service.api.signatureVersion
6563 });
6564 signer.setServiceClientId(service._clientId);
6565
6566 // clear old authorization headers
6567 delete req.httpRequest.headers['Authorization'];
6568 delete req.httpRequest.headers['Date'];
6569 delete req.httpRequest.headers['X-Amz-Date'];
6570
6571 // add new authorization
6572 signer.addAuthorization(credentials, date);
6573 req.signedAt = date;
6574 } catch (e) {
6575 req.response.error = e;
6576 }
6577 done();
6578 });
6579 });
6580
6581 add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) {
6582 if (this.service.successfulResponse(resp, this)) {
6583 resp.data = {};
6584 resp.error = null;
6585 } else {
6586 resp.data = null;
6587 resp.error = AWS.util.error(new Error(),
6588 {code: 'UnknownError', message: 'An unknown error occurred.'});
6589 }
6590 });
6591
6592 addAsync('SEND', 'send', function SEND(resp, done) {
6593 resp.httpResponse._abortCallback = done;
6594 resp.error = null;
6595 resp.data = null;
6596
6597 function callback(httpResp) {
6598 resp.httpResponse.stream = httpResp;
6599 var stream = resp.request.httpRequest.stream;
6600 var service = resp.request.service;
6601 var api = service.api;
6602 var operationName = resp.request.operation;
6603 var operation = api.operations[operationName] || {};
6604
6605 httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) {
6606 resp.request.emit(
6607 'httpHeaders',
6608 [statusCode, headers, resp, statusMessage]
6609 );
6610
6611 if (!resp.httpResponse.streaming) {
6612 if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check
6613 // if we detect event streams, we're going to have to
6614 // return the stream immediately
6615 if (operation.hasEventOutput && service.successfulResponse(resp)) {
6616 // skip reading the IncomingStream
6617 resp.request.emit('httpDone');
6618 done();
6619 return;
6620 }
6621
6622 httpResp.on('readable', function onReadable() {
6623 var data = httpResp.read();
6624 if (data !== null) {
6625 resp.request.emit('httpData', [data, resp]);
6626 }
6627 });
6628 } else { // legacy streams API
6629 httpResp.on('data', function onData(data) {
6630 resp.request.emit('httpData', [data, resp]);
6631 });
6632 }
6633 }
6634 });
6635
6636 httpResp.on('end', function onEnd() {
6637 if (!stream || !stream.didCallback) {
6638 if (AWS.HttpClient.streamsApiVersion === 2 && (operation.hasEventOutput && service.successfulResponse(resp))) {
6639 // don't concatenate response chunks when streaming event stream data when response is successful
6640 return;
6641 }
6642 resp.request.emit('httpDone');
6643 done();
6644 }
6645 });
6646 }
6647
6648 function progress(httpResp) {
6649 httpResp.on('sendProgress', function onSendProgress(value) {
6650 resp.request.emit('httpUploadProgress', [value, resp]);
6651 });
6652
6653 httpResp.on('receiveProgress', function onReceiveProgress(value) {
6654 resp.request.emit('httpDownloadProgress', [value, resp]);
6655 });
6656 }
6657
6658 function error(err) {
6659 if (err.code !== 'RequestAbortedError') {
6660 var errCode = err.code === 'TimeoutError' ? err.code : 'NetworkingError';
6661 err = AWS.util.error(err, {
6662 code: errCode,
6663 region: resp.request.httpRequest.region,
6664 hostname: resp.request.httpRequest.endpoint.hostname,
6665 retryable: true
6666 });
6667 }
6668 resp.error = err;
6669 resp.request.emit('httpError', [resp.error, resp], function() {
6670 done();
6671 });
6672 }
6673
6674 function executeSend() {
6675 var http = AWS.HttpClient.getInstance();
6676 var httpOptions = resp.request.service.config.httpOptions || {};
6677 try {
6678 var stream = http.handleRequest(resp.request.httpRequest, httpOptions,
6679 callback, error);
6680 progress(stream);
6681 } catch (err) {
6682 error(err);
6683 }
6684 }
6685 var timeDiff = (resp.request.service.getSkewCorrectedDate() - this.signedAt) / 1000;
6686 if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign
6687 this.emit('sign', [this], function(err) {
6688 if (err) done(err);
6689 else executeSend();
6690 });
6691 } else {
6692 executeSend();
6693 }
6694 });
6695
6696 add('HTTP_HEADERS', 'httpHeaders',
6697 function HTTP_HEADERS(statusCode, headers, resp, statusMessage) {
6698 resp.httpResponse.statusCode = statusCode;
6699 resp.httpResponse.statusMessage = statusMessage;
6700 resp.httpResponse.headers = headers;
6701 resp.httpResponse.body = AWS.util.buffer.toBuffer('');
6702 resp.httpResponse.buffers = [];
6703 resp.httpResponse.numBytes = 0;
6704 var dateHeader = headers.date || headers.Date;
6705 var service = resp.request.service;
6706 if (dateHeader) {
6707 var serverTime = Date.parse(dateHeader);
6708 if (service.config.correctClockSkew
6709 && service.isClockSkewed(serverTime)) {
6710 service.applyClockOffset(serverTime);
6711 }
6712 }
6713 });
6714
6715 add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) {
6716 if (chunk) {
6717 if (AWS.util.isNode()) {
6718 resp.httpResponse.numBytes += chunk.length;
6719
6720 var total = resp.httpResponse.headers['content-length'];
6721 var progress = { loaded: resp.httpResponse.numBytes, total: total };
6722 resp.request.emit('httpDownloadProgress', [progress, resp]);
6723 }
6724
6725 resp.httpResponse.buffers.push(AWS.util.buffer.toBuffer(chunk));
6726 }
6727 });
6728
6729 add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) {
6730 // convert buffers array into single buffer
6731 if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) {
6732 var body = AWS.util.buffer.concat(resp.httpResponse.buffers);
6733 resp.httpResponse.body = body;
6734 }
6735 delete resp.httpResponse.numBytes;
6736 delete resp.httpResponse.buffers;
6737 });
6738
6739 add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) {
6740 if (resp.httpResponse.statusCode) {
6741 resp.error.statusCode = resp.httpResponse.statusCode;
6742 if (resp.error.retryable === undefined) {
6743 resp.error.retryable = this.service.retryableError(resp.error, this);
6744 }
6745 }
6746 });
6747
6748 add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) {
6749 if (!resp.error) return;
6750 switch (resp.error.code) {
6751 case 'RequestExpired': // EC2 only
6752 case 'ExpiredTokenException':
6753 case 'ExpiredToken':
6754 resp.error.retryable = true;
6755 resp.request.service.config.credentials.expired = true;
6756 }
6757 });
6758
6759 add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) {
6760 var err = resp.error;
6761 if (!err) return;
6762 if (typeof err.code === 'string' && typeof err.message === 'string') {
6763 if (err.code.match(/Signature/) && err.message.match(/expired/)) {
6764 resp.error.retryable = true;
6765 }
6766 }
6767 });
6768
6769 add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) {
6770 if (!resp.error) return;
6771 if (this.service.clockSkewError(resp.error)
6772 && this.service.config.correctClockSkew) {
6773 resp.error.retryable = true;
6774 }
6775 });
6776
6777 add('REDIRECT', 'retry', function REDIRECT(resp) {
6778 if (resp.error && resp.error.statusCode >= 300 &&
6779 resp.error.statusCode < 400 && resp.httpResponse.headers['location']) {
6780 this.httpRequest.endpoint =
6781 new AWS.Endpoint(resp.httpResponse.headers['location']);
6782 this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host;
6783 resp.error.redirect = true;
6784 resp.error.retryable = true;
6785 }
6786 });
6787
6788 add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) {
6789 if (resp.error) {
6790 if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6791 resp.error.retryDelay = 0;
6792 } else if (resp.retryCount < resp.maxRetries) {
6793 resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0;
6794 }
6795 }
6796 });
6797
6798 addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) {
6799 var delay, willRetry = false;
6800
6801 if (resp.error) {
6802 delay = resp.error.retryDelay || 0;
6803 if (resp.error.retryable && resp.retryCount < resp.maxRetries) {
6804 resp.retryCount++;
6805 willRetry = true;
6806 } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6807 resp.redirectCount++;
6808 willRetry = true;
6809 }
6810 }
6811
6812 if (willRetry) {
6813 resp.error = null;
6814 setTimeout(done, delay);
6815 } else {
6816 done();
6817 }
6818 });
6819 }),
6820
6821 CorePost: new SequentialExecutor().addNamedListeners(function(add) {
6822 add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId);
6823 add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId);
6824
6825 add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) {
6826 if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') {
6827 var message = 'Inaccessible host: `' + err.hostname +
6828 '\'. This service may not be available in the `' + err.region +
6829 '\' region.';
6830 this.response.error = AWS.util.error(new Error(message), {
6831 code: 'UnknownEndpoint',
6832 region: err.region,
6833 hostname: err.hostname,
6834 retryable: true,
6835 originalError: err
6836 });
6837 }
6838 });
6839 }),
6840
6841 Logger: new SequentialExecutor().addNamedListeners(function(add) {
6842 add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) {
6843 var req = resp.request;
6844 var logger = req.service.config.logger;
6845 if (!logger) return;
6846 function filterSensitiveLog(inputShape, shape) {
6847 if (!shape) {
6848 return shape;
6849 }
6850 switch (inputShape.type) {
6851 case 'structure':
6852 var struct = {};
6853 AWS.util.each(shape, function(subShapeName, subShape) {
6854 if (Object.prototype.hasOwnProperty.call(inputShape.members, subShapeName)) {
6855 struct[subShapeName] = filterSensitiveLog(inputShape.members[subShapeName], subShape);
6856 } else {
6857 struct[subShapeName] = subShape;
6858 }
6859 });
6860 return struct;
6861 case 'list':
6862 var list = [];
6863 AWS.util.arrayEach(shape, function(subShape, index) {
6864 list.push(filterSensitiveLog(inputShape.member, subShape));
6865 });
6866 return list;
6867 case 'map':
6868 var map = {};
6869 AWS.util.each(shape, function(key, value) {
6870 map[key] = filterSensitiveLog(inputShape.value, value);
6871 });
6872 return map;
6873 default:
6874 if (inputShape.isSensitive) {
6875 return '***SensitiveInformation***';
6876 } else {
6877 return shape;
6878 }
6879 }
6880 }
6881
6882 function buildMessage() {
6883 var time = resp.request.service.getSkewCorrectedDate().getTime();
6884 var delta = (time - req.startTime.getTime()) / 1000;
6885 var ansi = logger.isTTY ? true : false;
6886 var status = resp.httpResponse.statusCode;
6887 var censoredParams = req.params;
6888 if (
6889 req.service.api.operations &&
6890 req.service.api.operations[req.operation] &&
6891 req.service.api.operations[req.operation].input
6892 ) {
6893 var inputShape = req.service.api.operations[req.operation].input;
6894 censoredParams = filterSensitiveLog(inputShape, req.params);
6895 }
6896 var params = __webpack_require__(46).inspect(censoredParams, true, null);
6897 var message = '';
6898 if (ansi) message += '\x1B[33m';
6899 message += '[AWS ' + req.service.serviceIdentifier + ' ' + status;
6900 message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]';
6901 if (ansi) message += '\x1B[0;1m';
6902 message += ' ' + AWS.util.string.lowerFirst(req.operation);
6903 message += '(' + params + ')';
6904 if (ansi) message += '\x1B[0m';
6905 return message;
6906 }
6907
6908 var line = buildMessage();
6909 if (typeof logger.log === 'function') {
6910 logger.log(line);
6911 } else if (typeof logger.write === 'function') {
6912 logger.write(line + '\n');
6913 }
6914 });
6915 }),
6916
6917 Json: new SequentialExecutor().addNamedListeners(function(add) {
6918 var svc = __webpack_require__(13);
6919 add('BUILD', 'build', svc.buildRequest);
6920 add('EXTRACT_DATA', 'extractData', svc.extractData);
6921 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6922 }),
6923
6924 Rest: new SequentialExecutor().addNamedListeners(function(add) {
6925 var svc = __webpack_require__(21);
6926 add('BUILD', 'build', svc.buildRequest);
6927 add('EXTRACT_DATA', 'extractData', svc.extractData);
6928 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6929 }),
6930
6931 RestJson: new SequentialExecutor().addNamedListeners(function(add) {
6932 var svc = __webpack_require__(22);
6933 add('BUILD', 'build', svc.buildRequest);
6934 add('EXTRACT_DATA', 'extractData', svc.extractData);
6935 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6936 }),
6937
6938 RestXml: new SequentialExecutor().addNamedListeners(function(add) {
6939 var svc = __webpack_require__(23);
6940 add('BUILD', 'build', svc.buildRequest);
6941 add('EXTRACT_DATA', 'extractData', svc.extractData);
6942 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6943 }),
6944
6945 Query: new SequentialExecutor().addNamedListeners(function(add) {
6946 var svc = __webpack_require__(17);
6947 add('BUILD', 'build', svc.buildRequest);
6948 add('EXTRACT_DATA', 'extractData', svc.extractData);
6949 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6950 })
6951 };
6952
6953
6954/***/ }),
6955/* 45 */
6956/***/ (function(module, exports, __webpack_require__) {
6957
6958 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
6959 var util = __webpack_require__(2);
6960 var endpointDiscoveryEnabledEnvs = ['AWS_ENABLE_ENDPOINT_DISCOVERY', 'AWS_ENDPOINT_DISCOVERY_ENABLED'];
6961
6962 /**
6963 * Generate key (except resources and operation part) to index the endpoints in the cache
6964 * If input shape has endpointdiscoveryid trait then use
6965 * accessKey + operation + resources + region + service as cache key
6966 * If input shape doesn't have endpointdiscoveryid trait then use
6967 * accessKey + region + service as cache key
6968 * @return [map<String,String>] object with keys to index endpoints.
6969 * @api private
6970 */
6971 function getCacheKey(request) {
6972 var service = request.service;
6973 var api = service.api || {};
6974 var operations = api.operations;
6975 var identifiers = {};
6976 if (service.config.region) {
6977 identifiers.region = service.config.region;
6978 }
6979 if (api.serviceId) {
6980 identifiers.serviceId = api.serviceId;
6981 }
6982 if (service.config.credentials.accessKeyId) {
6983 identifiers.accessKeyId = service.config.credentials.accessKeyId;
6984 }
6985 return identifiers;
6986 }
6987
6988 /**
6989 * Recursive helper for marshallCustomIdentifiers().
6990 * Looks for required string input members that have 'endpointdiscoveryid' trait.
6991 * @api private
6992 */
6993 function marshallCustomIdentifiersHelper(result, params, shape) {
6994 if (!shape || params === undefined || params === null) return;
6995 if (shape.type === 'structure' && shape.required && shape.required.length > 0) {
6996 util.arrayEach(shape.required, function(name) {
6997 var memberShape = shape.members[name];
6998 if (memberShape.endpointDiscoveryId === true) {
6999 var locationName = memberShape.isLocationName ? memberShape.name : name;
7000 result[locationName] = String(params[name]);
7001 } else {
7002 marshallCustomIdentifiersHelper(result, params[name], memberShape);
7003 }
7004 });
7005 }
7006 }
7007
7008 /**
7009 * Get custom identifiers for cache key.
7010 * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait.
7011 * @param [object] request object
7012 * @param [object] input shape of the given operation's api
7013 * @api private
7014 */
7015 function marshallCustomIdentifiers(request, shape) {
7016 var identifiers = {};
7017 marshallCustomIdentifiersHelper(identifiers, request.params, shape);
7018 return identifiers;
7019 }
7020
7021 /**
7022 * Call endpoint discovery operation when it's optional.
7023 * When endpoint is available in cache then use the cached endpoints. If endpoints
7024 * are unavailable then use regional endpoints and call endpoint discovery operation
7025 * asynchronously. This is turned off by default.
7026 * @param [object] request object
7027 * @api private
7028 */
7029 function optionalDiscoverEndpoint(request) {
7030 var service = request.service;
7031 var api = service.api;
7032 var operationModel = api.operations ? api.operations[request.operation] : undefined;
7033 var inputShape = operationModel ? operationModel.input : undefined;
7034
7035 var identifiers = marshallCustomIdentifiers(request, inputShape);
7036 var cacheKey = getCacheKey(request);
7037 if (Object.keys(identifiers).length > 0) {
7038 cacheKey = util.update(cacheKey, identifiers);
7039 if (operationModel) cacheKey.operation = operationModel.name;
7040 }
7041 var endpoints = AWS.endpointCache.get(cacheKey);
7042 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
7043 //endpoint operation is being made but response not yet received
7044 //or endpoint operation just failed in 1 minute
7045 return;
7046 } else if (endpoints && endpoints.length > 0) {
7047 //found endpoint record from cache
7048 request.httpRequest.updateEndpoint(endpoints[0].Address);
7049 } else {
7050 //endpoint record not in cache or outdated. make discovery operation
7051 var endpointRequest = service.makeRequest(api.endpointOperation, {
7052 Operation: operationModel.name,
7053 Identifiers: identifiers,
7054 });
7055 addApiVersionHeader(endpointRequest);
7056 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
7057 endpointRequest.removeListener('retry', AWS.EventListeners.Core.RETRY_CHECK);
7058 //put in a placeholder for endpoints already requested, prevent
7059 //too much in-flight calls
7060 AWS.endpointCache.put(cacheKey, [{
7061 Address: '',
7062 CachePeriodInMinutes: 1
7063 }]);
7064 endpointRequest.send(function(err, data) {
7065 if (data && data.Endpoints) {
7066 AWS.endpointCache.put(cacheKey, data.Endpoints);
7067 } else if (err) {
7068 AWS.endpointCache.put(cacheKey, [{
7069 Address: '',
7070 CachePeriodInMinutes: 1 //not to make more endpoint operation in next 1 minute
7071 }]);
7072 }
7073 });
7074 }
7075 }
7076
7077 var requestQueue = {};
7078
7079 /**
7080 * Call endpoint discovery operation when it's required.
7081 * When endpoint is available in cache then use cached ones. If endpoints are
7082 * unavailable then SDK should call endpoint operation then use returned new
7083 * endpoint for the api call. SDK will automatically attempt to do endpoint
7084 * discovery. This is turned off by default
7085 * @param [object] request object
7086 * @api private
7087 */
7088 function requiredDiscoverEndpoint(request, done) {
7089 var service = request.service;
7090 var api = service.api;
7091 var operationModel = api.operations ? api.operations[request.operation] : undefined;
7092 var inputShape = operationModel ? operationModel.input : undefined;
7093
7094 var identifiers = marshallCustomIdentifiers(request, inputShape);
7095 var cacheKey = getCacheKey(request);
7096 if (Object.keys(identifiers).length > 0) {
7097 cacheKey = util.update(cacheKey, identifiers);
7098 if (operationModel) cacheKey.operation = operationModel.name;
7099 }
7100 var cacheKeyStr = AWS.EndpointCache.getKeyString(cacheKey);
7101 var endpoints = AWS.endpointCache.get(cacheKeyStr); //endpoint cache also accepts string keys
7102 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
7103 //endpoint operation is being made but response not yet received
7104 //push request object to a pending queue
7105 if (!requestQueue[cacheKeyStr]) requestQueue[cacheKeyStr] = [];
7106 requestQueue[cacheKeyStr].push({request: request, callback: done});
7107 return;
7108 } else if (endpoints && endpoints.length > 0) {
7109 request.httpRequest.updateEndpoint(endpoints[0].Address);
7110 done();
7111 } else {
7112 var endpointRequest = service.makeRequest(api.endpointOperation, {
7113 Operation: operationModel.name,
7114 Identifiers: identifiers,
7115 });
7116 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
7117 addApiVersionHeader(endpointRequest);
7118
7119 //put in a placeholder for endpoints already requested, prevent
7120 //too much in-flight calls
7121 AWS.endpointCache.put(cacheKeyStr, [{
7122 Address: '',
7123 CachePeriodInMinutes: 60 //long-live cache
7124 }]);
7125 endpointRequest.send(function(err, data) {
7126 if (err) {
7127 var errorParams = {
7128 code: 'EndpointDiscoveryException',
7129 message: 'Request cannot be fulfilled without specifying an endpoint',
7130 retryable: false
7131 };
7132 request.response.error = util.error(err, errorParams);
7133 AWS.endpointCache.remove(cacheKey);
7134
7135 //fail all the pending requests in batch
7136 if (requestQueue[cacheKeyStr]) {
7137 var pendingRequests = requestQueue[cacheKeyStr];
7138 util.arrayEach(pendingRequests, function(requestContext) {
7139 requestContext.request.response.error = util.error(err, errorParams);
7140 requestContext.callback();
7141 });
7142 delete requestQueue[cacheKeyStr];
7143 }
7144 } else if (data) {
7145 AWS.endpointCache.put(cacheKeyStr, data.Endpoints);
7146 request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7147
7148 //update the endpoint for all the pending requests in batch
7149 if (requestQueue[cacheKeyStr]) {
7150 var pendingRequests = requestQueue[cacheKeyStr];
7151 util.arrayEach(pendingRequests, function(requestContext) {
7152 requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7153 requestContext.callback();
7154 });
7155 delete requestQueue[cacheKeyStr];
7156 }
7157 }
7158 done();
7159 });
7160 }
7161 }
7162
7163 /**
7164 * add api version header to endpoint operation
7165 * @api private
7166 */
7167 function addApiVersionHeader(endpointRequest) {
7168 var api = endpointRequest.service.api;
7169 var apiVersion = api.apiVersion;
7170 if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) {
7171 endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion;
7172 }
7173 }
7174
7175 /**
7176 * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid
7177 * endpoint from cache.
7178 * @api private
7179 */
7180 function invalidateCachedEndpoints(response) {
7181 var error = response.error;
7182 var httpResponse = response.httpResponse;
7183 if (error &&
7184 (error.code === 'InvalidEndpointException' || httpResponse.statusCode === 421)
7185 ) {
7186 var request = response.request;
7187 var operations = request.service.api.operations || {};
7188 var inputShape = operations[request.operation] ? operations[request.operation].input : undefined;
7189 var identifiers = marshallCustomIdentifiers(request, inputShape);
7190 var cacheKey = getCacheKey(request);
7191 if (Object.keys(identifiers).length > 0) {
7192 cacheKey = util.update(cacheKey, identifiers);
7193 if (operations[request.operation]) cacheKey.operation = operations[request.operation].name;
7194 }
7195 AWS.endpointCache.remove(cacheKey);
7196 }
7197 }
7198
7199 /**
7200 * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime.
7201 * @param [object] client Service client object.
7202 * @api private
7203 */
7204 function hasCustomEndpoint(client) {
7205 //if set endpoint is set for specific client, enable endpoint discovery will raise an error.
7206 if (client._originalConfig && client._originalConfig.endpoint && client._originalConfig.endpointDiscoveryEnabled === true) {
7207 throw util.error(new Error(), {
7208 code: 'ConfigurationException',
7209 message: 'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.'
7210 });
7211 };
7212 var svcConfig = AWS.config[client.serviceIdentifier] || {};
7213 return Boolean(AWS.config.endpoint || svcConfig.endpoint || (client._originalConfig && client._originalConfig.endpoint));
7214 }
7215
7216 /**
7217 * @api private
7218 */
7219 function isFalsy(value) {
7220 return ['false', '0'].indexOf(value) >= 0;
7221 }
7222
7223 /**
7224 * If endpoint discovery should perform for this request when endpoint discovery is optional.
7225 * SDK performs config resolution in order like below:
7226 * 1. If turned on client configuration(default to off) then turn on endpoint discovery.
7227 * 2. If turned on in env AWS_ENABLE_ENDPOINT_DISCOVERY then turn on endpoint discovery.
7228 * 3. If turned on in shared ini config file with key 'endpoint_discovery_enabled', then
7229 * turn on endpoint discovery.
7230 * @param [object] request request object.
7231 * @api private
7232 */
7233 function isEndpointDiscoveryApplicable(request) {
7234 var service = request.service || {};
7235 if (service.config.endpointDiscoveryEnabled === true) return true;
7236
7237 //shared ini file is only available in Node
7238 //not to check env in browser
7239 if (util.isBrowser()) return false;
7240
7241 for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) {
7242 var env = endpointDiscoveryEnabledEnvs[i];
7243 if (Object.prototype.hasOwnProperty.call(process.env, env)) {
7244 if (process.env[env] === '' || process.env[env] === undefined) {
7245 throw util.error(new Error(), {
7246 code: 'ConfigurationException',
7247 message: 'environmental variable ' + env + ' cannot be set to nothing'
7248 });
7249 }
7250 if (!isFalsy(process.env[env])) return true;
7251 }
7252 }
7253
7254 var configFile = {};
7255 try {
7256 configFile = AWS.util.iniLoader ? AWS.util.iniLoader.loadFrom({
7257 isConfig: true,
7258 filename: process.env[AWS.util.sharedConfigFileEnv]
7259 }) : {};
7260 } catch (e) {}
7261 var sharedFileConfig = configFile[
7262 process.env.AWS_PROFILE || AWS.util.defaultProfile
7263 ] || {};
7264 if (Object.prototype.hasOwnProperty.call(sharedFileConfig, 'endpoint_discovery_enabled')) {
7265 if (sharedFileConfig.endpoint_discovery_enabled === undefined) {
7266 throw util.error(new Error(), {
7267 code: 'ConfigurationException',
7268 message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing'
7269 });
7270 }
7271 if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true;
7272 }
7273 return false;
7274 }
7275
7276 /**
7277 * attach endpoint discovery logic to request object
7278 * @param [object] request
7279 * @api private
7280 */
7281 function discoverEndpoint(request, done) {
7282 var service = request.service || {};
7283 if (hasCustomEndpoint(service) || request.isPresigned()) return done();
7284
7285 if (!isEndpointDiscoveryApplicable(request)) return done();
7286
7287 request.httpRequest.appendToUserAgent('endpoint-discovery');
7288
7289 var operations = service.api.operations || {};
7290 var operationModel = operations[request.operation];
7291 var isEndpointDiscoveryRequired = operationModel ? operationModel.endpointDiscoveryRequired : 'NULL';
7292 switch (isEndpointDiscoveryRequired) {
7293 case 'OPTIONAL':
7294 optionalDiscoverEndpoint(request);
7295 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7296 done();
7297 break;
7298 case 'REQUIRED':
7299 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7300 requiredDiscoverEndpoint(request, done);
7301 break;
7302 case 'NULL':
7303 default:
7304 done();
7305 break;
7306 }
7307 }
7308
7309 module.exports = {
7310 discoverEndpoint: discoverEndpoint,
7311 requiredDiscoverEndpoint: requiredDiscoverEndpoint,
7312 optionalDiscoverEndpoint: optionalDiscoverEndpoint,
7313 marshallCustomIdentifiers: marshallCustomIdentifiers,
7314 getCacheKey: getCacheKey,
7315 invalidateCachedEndpoint: invalidateCachedEndpoints,
7316 };
7317
7318 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
7319
7320/***/ }),
7321/* 46 */
7322/***/ (function(module, exports, __webpack_require__) {
7323
7324 /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
7325 //
7326 // Permission is hereby granted, free of charge, to any person obtaining a
7327 // copy of this software and associated documentation files (the
7328 // "Software"), to deal in the Software without restriction, including
7329 // without limitation the rights to use, copy, modify, merge, publish,
7330 // distribute, sublicense, and/or sell copies of the Software, and to permit
7331 // persons to whom the Software is furnished to do so, subject to the
7332 // following conditions:
7333 //
7334 // The above copyright notice and this permission notice shall be included
7335 // in all copies or substantial portions of the Software.
7336 //
7337 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7338 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7339 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7340 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7341 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7342 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7343 // USE OR OTHER DEALINGS IN THE SOFTWARE.
7344
7345 var formatRegExp = /%[sdj%]/g;
7346 exports.format = function(f) {
7347 if (!isString(f)) {
7348 var objects = [];
7349 for (var i = 0; i < arguments.length; i++) {
7350 objects.push(inspect(arguments[i]));
7351 }
7352 return objects.join(' ');
7353 }
7354
7355 var i = 1;
7356 var args = arguments;
7357 var len = args.length;
7358 var str = String(f).replace(formatRegExp, function(x) {
7359 if (x === '%%') return '%';
7360 if (i >= len) return x;
7361 switch (x) {
7362 case '%s': return String(args[i++]);
7363 case '%d': return Number(args[i++]);
7364 case '%j':
7365 try {
7366 return JSON.stringify(args[i++]);
7367 } catch (_) {
7368 return '[Circular]';
7369 }
7370 default:
7371 return x;
7372 }
7373 });
7374 for (var x = args[i]; i < len; x = args[++i]) {
7375 if (isNull(x) || !isObject(x)) {
7376 str += ' ' + x;
7377 } else {
7378 str += ' ' + inspect(x);
7379 }
7380 }
7381 return str;
7382 };
7383
7384
7385 // Mark that a method should not be used.
7386 // Returns a modified function which warns once by default.
7387 // If --no-deprecation is set, then it is a no-op.
7388 exports.deprecate = function(fn, msg) {
7389 // Allow for deprecating things in the process of starting up.
7390 if (isUndefined(global.process)) {
7391 return function() {
7392 return exports.deprecate(fn, msg).apply(this, arguments);
7393 };
7394 }
7395
7396 if (process.noDeprecation === true) {
7397 return fn;
7398 }
7399
7400 var warned = false;
7401 function deprecated() {
7402 if (!warned) {
7403 if (process.throwDeprecation) {
7404 throw new Error(msg);
7405 } else if (process.traceDeprecation) {
7406 console.trace(msg);
7407 } else {
7408 console.error(msg);
7409 }
7410 warned = true;
7411 }
7412 return fn.apply(this, arguments);
7413 }
7414
7415 return deprecated;
7416 };
7417
7418
7419 var debugs = {};
7420 var debugEnviron;
7421 exports.debuglog = function(set) {
7422 if (isUndefined(debugEnviron))
7423 debugEnviron = process.env.NODE_DEBUG || '';
7424 set = set.toUpperCase();
7425 if (!debugs[set]) {
7426 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
7427 var pid = process.pid;
7428 debugs[set] = function() {
7429 var msg = exports.format.apply(exports, arguments);
7430 console.error('%s %d: %s', set, pid, msg);
7431 };
7432 } else {
7433 debugs[set] = function() {};
7434 }
7435 }
7436 return debugs[set];
7437 };
7438
7439
7440 /**
7441 * Echos the value of a value. Trys to print the value out
7442 * in the best way possible given the different types.
7443 *
7444 * @param {Object} obj The object to print out.
7445 * @param {Object} opts Optional options object that alters the output.
7446 */
7447 /* legacy: obj, showHidden, depth, colors*/
7448 function inspect(obj, opts) {
7449 // default options
7450 var ctx = {
7451 seen: [],
7452 stylize: stylizeNoColor
7453 };
7454 // legacy...
7455 if (arguments.length >= 3) ctx.depth = arguments[2];
7456 if (arguments.length >= 4) ctx.colors = arguments[3];
7457 if (isBoolean(opts)) {
7458 // legacy...
7459 ctx.showHidden = opts;
7460 } else if (opts) {
7461 // got an "options" object
7462 exports._extend(ctx, opts);
7463 }
7464 // set default options
7465 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
7466 if (isUndefined(ctx.depth)) ctx.depth = 2;
7467 if (isUndefined(ctx.colors)) ctx.colors = false;
7468 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
7469 if (ctx.colors) ctx.stylize = stylizeWithColor;
7470 return formatValue(ctx, obj, ctx.depth);
7471 }
7472 exports.inspect = inspect;
7473
7474
7475 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
7476 inspect.colors = {
7477 'bold' : [1, 22],
7478 'italic' : [3, 23],
7479 'underline' : [4, 24],
7480 'inverse' : [7, 27],
7481 'white' : [37, 39],
7482 'grey' : [90, 39],
7483 'black' : [30, 39],
7484 'blue' : [34, 39],
7485 'cyan' : [36, 39],
7486 'green' : [32, 39],
7487 'magenta' : [35, 39],
7488 'red' : [31, 39],
7489 'yellow' : [33, 39]
7490 };
7491
7492 // Don't use 'blue' not visible on cmd.exe
7493 inspect.styles = {
7494 'special': 'cyan',
7495 'number': 'yellow',
7496 'boolean': 'yellow',
7497 'undefined': 'grey',
7498 'null': 'bold',
7499 'string': 'green',
7500 'date': 'magenta',
7501 // "name": intentionally not styling
7502 'regexp': 'red'
7503 };
7504
7505
7506 function stylizeWithColor(str, styleType) {
7507 var style = inspect.styles[styleType];
7508
7509 if (style) {
7510 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
7511 '\u001b[' + inspect.colors[style][1] + 'm';
7512 } else {
7513 return str;
7514 }
7515 }
7516
7517
7518 function stylizeNoColor(str, styleType) {
7519 return str;
7520 }
7521
7522
7523 function arrayToHash(array) {
7524 var hash = {};
7525
7526 array.forEach(function(val, idx) {
7527 hash[val] = true;
7528 });
7529
7530 return hash;
7531 }
7532
7533
7534 function formatValue(ctx, value, recurseTimes) {
7535 // Provide a hook for user-specified inspect functions.
7536 // Check that value is an object with an inspect function on it
7537 if (ctx.customInspect &&
7538 value &&
7539 isFunction(value.inspect) &&
7540 // Filter out the util module, it's inspect function is special
7541 value.inspect !== exports.inspect &&
7542 // Also filter out any prototype objects using the circular check.
7543 !(value.constructor && value.constructor.prototype === value)) {
7544 var ret = value.inspect(recurseTimes, ctx);
7545 if (!isString(ret)) {
7546 ret = formatValue(ctx, ret, recurseTimes);
7547 }
7548 return ret;
7549 }
7550
7551 // Primitive types cannot have properties
7552 var primitive = formatPrimitive(ctx, value);
7553 if (primitive) {
7554 return primitive;
7555 }
7556
7557 // Look up the keys of the object.
7558 var keys = Object.keys(value);
7559 var visibleKeys = arrayToHash(keys);
7560
7561 if (ctx.showHidden) {
7562 keys = Object.getOwnPropertyNames(value);
7563 }
7564
7565 // IE doesn't make error fields non-enumerable
7566 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
7567 if (isError(value)
7568 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
7569 return formatError(value);
7570 }
7571
7572 // Some type of object without properties can be shortcutted.
7573 if (keys.length === 0) {
7574 if (isFunction(value)) {
7575 var name = value.name ? ': ' + value.name : '';
7576 return ctx.stylize('[Function' + name + ']', 'special');
7577 }
7578 if (isRegExp(value)) {
7579 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7580 }
7581 if (isDate(value)) {
7582 return ctx.stylize(Date.prototype.toString.call(value), 'date');
7583 }
7584 if (isError(value)) {
7585 return formatError(value);
7586 }
7587 }
7588
7589 var base = '', array = false, braces = ['{', '}'];
7590
7591 // Make Array say that they are Array
7592 if (isArray(value)) {
7593 array = true;
7594 braces = ['[', ']'];
7595 }
7596
7597 // Make functions say that they are functions
7598 if (isFunction(value)) {
7599 var n = value.name ? ': ' + value.name : '';
7600 base = ' [Function' + n + ']';
7601 }
7602
7603 // Make RegExps say that they are RegExps
7604 if (isRegExp(value)) {
7605 base = ' ' + RegExp.prototype.toString.call(value);
7606 }
7607
7608 // Make dates with properties first say the date
7609 if (isDate(value)) {
7610 base = ' ' + Date.prototype.toUTCString.call(value);
7611 }
7612
7613 // Make error with message first say the error
7614 if (isError(value)) {
7615 base = ' ' + formatError(value);
7616 }
7617
7618 if (keys.length === 0 && (!array || value.length == 0)) {
7619 return braces[0] + base + braces[1];
7620 }
7621
7622 if (recurseTimes < 0) {
7623 if (isRegExp(value)) {
7624 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7625 } else {
7626 return ctx.stylize('[Object]', 'special');
7627 }
7628 }
7629
7630 ctx.seen.push(value);
7631
7632 var output;
7633 if (array) {
7634 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
7635 } else {
7636 output = keys.map(function(key) {
7637 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
7638 });
7639 }
7640
7641 ctx.seen.pop();
7642
7643 return reduceToSingleString(output, base, braces);
7644 }
7645
7646
7647 function formatPrimitive(ctx, value) {
7648 if (isUndefined(value))
7649 return ctx.stylize('undefined', 'undefined');
7650 if (isString(value)) {
7651 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
7652 .replace(/'/g, "\\'")
7653 .replace(/\\"/g, '"') + '\'';
7654 return ctx.stylize(simple, 'string');
7655 }
7656 if (isNumber(value))
7657 return ctx.stylize('' + value, 'number');
7658 if (isBoolean(value))
7659 return ctx.stylize('' + value, 'boolean');
7660 // For some reason typeof null is "object", so special case here.
7661 if (isNull(value))
7662 return ctx.stylize('null', 'null');
7663 }
7664
7665
7666 function formatError(value) {
7667 return '[' + Error.prototype.toString.call(value) + ']';
7668 }
7669
7670
7671 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
7672 var output = [];
7673 for (var i = 0, l = value.length; i < l; ++i) {
7674 if (hasOwnProperty(value, String(i))) {
7675 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7676 String(i), true));
7677 } else {
7678 output.push('');
7679 }
7680 }
7681 keys.forEach(function(key) {
7682 if (!key.match(/^\d+$/)) {
7683 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7684 key, true));
7685 }
7686 });
7687 return output;
7688 }
7689
7690
7691 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
7692 var name, str, desc;
7693 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
7694 if (desc.get) {
7695 if (desc.set) {
7696 str = ctx.stylize('[Getter/Setter]', 'special');
7697 } else {
7698 str = ctx.stylize('[Getter]', 'special');
7699 }
7700 } else {
7701 if (desc.set) {
7702 str = ctx.stylize('[Setter]', 'special');
7703 }
7704 }
7705 if (!hasOwnProperty(visibleKeys, key)) {
7706 name = '[' + key + ']';
7707 }
7708 if (!str) {
7709 if (ctx.seen.indexOf(desc.value) < 0) {
7710 if (isNull(recurseTimes)) {
7711 str = formatValue(ctx, desc.value, null);
7712 } else {
7713 str = formatValue(ctx, desc.value, recurseTimes - 1);
7714 }
7715 if (str.indexOf('\n') > -1) {
7716 if (array) {
7717 str = str.split('\n').map(function(line) {
7718 return ' ' + line;
7719 }).join('\n').substr(2);
7720 } else {
7721 str = '\n' + str.split('\n').map(function(line) {
7722 return ' ' + line;
7723 }).join('\n');
7724 }
7725 }
7726 } else {
7727 str = ctx.stylize('[Circular]', 'special');
7728 }
7729 }
7730 if (isUndefined(name)) {
7731 if (array && key.match(/^\d+$/)) {
7732 return str;
7733 }
7734 name = JSON.stringify('' + key);
7735 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
7736 name = name.substr(1, name.length - 2);
7737 name = ctx.stylize(name, 'name');
7738 } else {
7739 name = name.replace(/'/g, "\\'")
7740 .replace(/\\"/g, '"')
7741 .replace(/(^"|"$)/g, "'");
7742 name = ctx.stylize(name, 'string');
7743 }
7744 }
7745
7746 return name + ': ' + str;
7747 }
7748
7749
7750 function reduceToSingleString(output, base, braces) {
7751 var numLinesEst = 0;
7752 var length = output.reduce(function(prev, cur) {
7753 numLinesEst++;
7754 if (cur.indexOf('\n') >= 0) numLinesEst++;
7755 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
7756 }, 0);
7757
7758 if (length > 60) {
7759 return braces[0] +
7760 (base === '' ? '' : base + '\n ') +
7761 ' ' +
7762 output.join(',\n ') +
7763 ' ' +
7764 braces[1];
7765 }
7766
7767 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
7768 }
7769
7770
7771 // NOTE: These type checking functions intentionally don't use `instanceof`
7772 // because it is fragile and can be easily faked with `Object.create()`.
7773 function isArray(ar) {
7774 return Array.isArray(ar);
7775 }
7776 exports.isArray = isArray;
7777
7778 function isBoolean(arg) {
7779 return typeof arg === 'boolean';
7780 }
7781 exports.isBoolean = isBoolean;
7782
7783 function isNull(arg) {
7784 return arg === null;
7785 }
7786 exports.isNull = isNull;
7787
7788 function isNullOrUndefined(arg) {
7789 return arg == null;
7790 }
7791 exports.isNullOrUndefined = isNullOrUndefined;
7792
7793 function isNumber(arg) {
7794 return typeof arg === 'number';
7795 }
7796 exports.isNumber = isNumber;
7797
7798 function isString(arg) {
7799 return typeof arg === 'string';
7800 }
7801 exports.isString = isString;
7802
7803 function isSymbol(arg) {
7804 return typeof arg === 'symbol';
7805 }
7806 exports.isSymbol = isSymbol;
7807
7808 function isUndefined(arg) {
7809 return arg === void 0;
7810 }
7811 exports.isUndefined = isUndefined;
7812
7813 function isRegExp(re) {
7814 return isObject(re) && objectToString(re) === '[object RegExp]';
7815 }
7816 exports.isRegExp = isRegExp;
7817
7818 function isObject(arg) {
7819 return typeof arg === 'object' && arg !== null;
7820 }
7821 exports.isObject = isObject;
7822
7823 function isDate(d) {
7824 return isObject(d) && objectToString(d) === '[object Date]';
7825 }
7826 exports.isDate = isDate;
7827
7828 function isError(e) {
7829 return isObject(e) &&
7830 (objectToString(e) === '[object Error]' || e instanceof Error);
7831 }
7832 exports.isError = isError;
7833
7834 function isFunction(arg) {
7835 return typeof arg === 'function';
7836 }
7837 exports.isFunction = isFunction;
7838
7839 function isPrimitive(arg) {
7840 return arg === null ||
7841 typeof arg === 'boolean' ||
7842 typeof arg === 'number' ||
7843 typeof arg === 'string' ||
7844 typeof arg === 'symbol' || // ES6 symbol
7845 typeof arg === 'undefined';
7846 }
7847 exports.isPrimitive = isPrimitive;
7848
7849 exports.isBuffer = __webpack_require__(47);
7850
7851 function objectToString(o) {
7852 return Object.prototype.toString.call(o);
7853 }
7854
7855
7856 function pad(n) {
7857 return n < 10 ? '0' + n.toString(10) : n.toString(10);
7858 }
7859
7860
7861 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
7862 'Oct', 'Nov', 'Dec'];
7863
7864 // 26 Feb 16:19:34
7865 function timestamp() {
7866 var d = new Date();
7867 var time = [pad(d.getHours()),
7868 pad(d.getMinutes()),
7869 pad(d.getSeconds())].join(':');
7870 return [d.getDate(), months[d.getMonth()], time].join(' ');
7871 }
7872
7873
7874 // log is just a thin wrapper to console.log that prepends a timestamp
7875 exports.log = function() {
7876 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
7877 };
7878
7879
7880 /**
7881 * Inherit the prototype methods from one constructor into another.
7882 *
7883 * The Function.prototype.inherits from lang.js rewritten as a standalone
7884 * function (not on Function.prototype). NOTE: If this file is to be loaded
7885 * during bootstrapping this function needs to be rewritten using some native
7886 * functions as prototype setup using normal JavaScript does not work as
7887 * expected during bootstrapping (see mirror.js in r114903).
7888 *
7889 * @param {function} ctor Constructor function which needs to inherit the
7890 * prototype.
7891 * @param {function} superCtor Constructor function to inherit prototype from.
7892 */
7893 exports.inherits = __webpack_require__(48);
7894
7895 exports._extend = function(origin, add) {
7896 // Don't do anything if add isn't an object
7897 if (!add || !isObject(add)) return origin;
7898
7899 var keys = Object.keys(add);
7900 var i = keys.length;
7901 while (i--) {
7902 origin[keys[i]] = add[keys[i]];
7903 }
7904 return origin;
7905 };
7906
7907 function hasOwnProperty(obj, prop) {
7908 return Object.prototype.hasOwnProperty.call(obj, prop);
7909 }
7910
7911 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
7912
7913/***/ }),
7914/* 47 */
7915/***/ (function(module, exports) {
7916
7917 module.exports = function isBuffer(arg) {
7918 return arg && typeof arg === 'object'
7919 && typeof arg.copy === 'function'
7920 && typeof arg.fill === 'function'
7921 && typeof arg.readUInt8 === 'function';
7922 }
7923
7924/***/ }),
7925/* 48 */
7926/***/ (function(module, exports) {
7927
7928 if (typeof Object.create === 'function') {
7929 // implementation from standard node.js 'util' module
7930 module.exports = function inherits(ctor, superCtor) {
7931 ctor.super_ = superCtor
7932 ctor.prototype = Object.create(superCtor.prototype, {
7933 constructor: {
7934 value: ctor,
7935 enumerable: false,
7936 writable: true,
7937 configurable: true
7938 }
7939 });
7940 };
7941 } else {
7942 // old school shim for old browsers
7943 module.exports = function inherits(ctor, superCtor) {
7944 ctor.super_ = superCtor
7945 var TempCtor = function () {}
7946 TempCtor.prototype = superCtor.prototype
7947 ctor.prototype = new TempCtor()
7948 ctor.prototype.constructor = ctor
7949 }
7950 }
7951
7952
7953/***/ }),
7954/* 49 */
7955/***/ (function(module, exports, __webpack_require__) {
7956
7957 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
7958 var AcceptorStateMachine = __webpack_require__(50);
7959 var inherit = AWS.util.inherit;
7960 var domain = AWS.util.domain;
7961 var jmespath = __webpack_require__(51);
7962
7963 /**
7964 * @api private
7965 */
7966 var hardErrorStates = {success: 1, error: 1, complete: 1};
7967
7968 function isTerminalState(machine) {
7969 return Object.prototype.hasOwnProperty.call(hardErrorStates, machine._asm.currentState);
7970 }
7971
7972 var fsm = new AcceptorStateMachine();
7973 fsm.setupStates = function() {
7974 var transition = function(_, done) {
7975 var self = this;
7976 self._haltHandlersOnError = false;
7977
7978 self.emit(self._asm.currentState, function(err) {
7979 if (err) {
7980 if (isTerminalState(self)) {
7981 if (domain && self.domain instanceof domain.Domain) {
7982 err.domainEmitter = self;
7983 err.domain = self.domain;
7984 err.domainThrown = false;
7985 self.domain.emit('error', err);
7986 } else {
7987 throw err;
7988 }
7989 } else {
7990 self.response.error = err;
7991 done(err);
7992 }
7993 } else {
7994 done(self.response.error);
7995 }
7996 });
7997
7998 };
7999
8000 this.addState('validate', 'build', 'error', transition);
8001 this.addState('build', 'afterBuild', 'restart', transition);
8002 this.addState('afterBuild', 'sign', 'restart', transition);
8003 this.addState('sign', 'send', 'retry', transition);
8004 this.addState('retry', 'afterRetry', 'afterRetry', transition);
8005 this.addState('afterRetry', 'sign', 'error', transition);
8006 this.addState('send', 'validateResponse', 'retry', transition);
8007 this.addState('validateResponse', 'extractData', 'extractError', transition);
8008 this.addState('extractError', 'extractData', 'retry', transition);
8009 this.addState('extractData', 'success', 'retry', transition);
8010 this.addState('restart', 'build', 'error', transition);
8011 this.addState('success', 'complete', 'complete', transition);
8012 this.addState('error', 'complete', 'complete', transition);
8013 this.addState('complete', null, null, transition);
8014 };
8015 fsm.setupStates();
8016
8017 /**
8018 * ## Asynchronous Requests
8019 *
8020 * All requests made through the SDK are asynchronous and use a
8021 * callback interface. Each service method that kicks off a request
8022 * returns an `AWS.Request` object that you can use to register
8023 * callbacks.
8024 *
8025 * For example, the following service method returns the request
8026 * object as "request", which can be used to register callbacks:
8027 *
8028 * ```javascript
8029 * // request is an AWS.Request object
8030 * var request = ec2.describeInstances();
8031 *
8032 * // register callbacks on request to retrieve response data
8033 * request.on('success', function(response) {
8034 * console.log(response.data);
8035 * });
8036 * ```
8037 *
8038 * When a request is ready to be sent, the {send} method should
8039 * be called:
8040 *
8041 * ```javascript
8042 * request.send();
8043 * ```
8044 *
8045 * Since registered callbacks may or may not be idempotent, requests should only
8046 * be sent once. To perform the same operation multiple times, you will need to
8047 * create multiple request objects, each with its own registered callbacks.
8048 *
8049 * ## Removing Default Listeners for Events
8050 *
8051 * Request objects are built with default listeners for the various events,
8052 * depending on the service type. In some cases, you may want to remove
8053 * some built-in listeners to customize behaviour. Doing this requires
8054 * access to the built-in listener functions, which are exposed through
8055 * the {AWS.EventListeners.Core} namespace. For instance, you may
8056 * want to customize the HTTP handler used when sending a request. In this
8057 * case, you can remove the built-in listener associated with the 'send'
8058 * event, the {AWS.EventListeners.Core.SEND} listener and add your own.
8059 *
8060 * ## Multiple Callbacks and Chaining
8061 *
8062 * You can register multiple callbacks on any request object. The
8063 * callbacks can be registered for different events, or all for the
8064 * same event. In addition, you can chain callback registration, for
8065 * example:
8066 *
8067 * ```javascript
8068 * request.
8069 * on('success', function(response) {
8070 * console.log("Success!");
8071 * }).
8072 * on('error', function(error, response) {
8073 * console.log("Error!");
8074 * }).
8075 * on('complete', function(response) {
8076 * console.log("Always!");
8077 * }).
8078 * send();
8079 * ```
8080 *
8081 * The above example will print either "Success! Always!", or "Error! Always!",
8082 * depending on whether the request succeeded or not.
8083 *
8084 * @!attribute httpRequest
8085 * @readonly
8086 * @!group HTTP Properties
8087 * @return [AWS.HttpRequest] the raw HTTP request object
8088 * containing request headers and body information
8089 * sent by the service.
8090 *
8091 * @!attribute startTime
8092 * @readonly
8093 * @!group Operation Properties
8094 * @return [Date] the time that the request started
8095 *
8096 * @!group Request Building Events
8097 *
8098 * @!event validate(request)
8099 * Triggered when a request is being validated. Listeners
8100 * should throw an error if the request should not be sent.
8101 * @param request [Request] the request object being sent
8102 * @see AWS.EventListeners.Core.VALIDATE_CREDENTIALS
8103 * @see AWS.EventListeners.Core.VALIDATE_REGION
8104 * @example Ensuring that a certain parameter is set before sending a request
8105 * var req = s3.putObject(params);
8106 * req.on('validate', function() {
8107 * if (!req.params.Body.match(/^Hello\s/)) {
8108 * throw new Error('Body must start with "Hello "');
8109 * }
8110 * });
8111 * req.send(function(err, data) { ... });
8112 *
8113 * @!event build(request)
8114 * Triggered when the request payload is being built. Listeners
8115 * should fill the necessary information to send the request
8116 * over HTTP.
8117 * @param (see AWS.Request~validate)
8118 * @example Add a custom HTTP header to a request
8119 * var req = s3.putObject(params);
8120 * req.on('build', function() {
8121 * req.httpRequest.headers['Custom-Header'] = 'value';
8122 * });
8123 * req.send(function(err, data) { ... });
8124 *
8125 * @!event sign(request)
8126 * Triggered when the request is being signed. Listeners should
8127 * add the correct authentication headers and/or adjust the body,
8128 * depending on the authentication mechanism being used.
8129 * @param (see AWS.Request~validate)
8130 *
8131 * @!group Request Sending Events
8132 *
8133 * @!event send(response)
8134 * Triggered when the request is ready to be sent. Listeners
8135 * should call the underlying transport layer to initiate
8136 * the sending of the request.
8137 * @param response [Response] the response object
8138 * @context [Request] the request object that was sent
8139 * @see AWS.EventListeners.Core.SEND
8140 *
8141 * @!event retry(response)
8142 * Triggered when a request failed and might need to be retried or redirected.
8143 * If the response is retryable, the listener should set the
8144 * `response.error.retryable` property to `true`, and optionally set
8145 * `response.error.retryDelay` to the millisecond delay for the next attempt.
8146 * In the case of a redirect, `response.error.redirect` should be set to
8147 * `true` with `retryDelay` set to an optional delay on the next request.
8148 *
8149 * If a listener decides that a request should not be retried,
8150 * it should set both `retryable` and `redirect` to false.
8151 *
8152 * Note that a retryable error will be retried at most
8153 * {AWS.Config.maxRetries} times (based on the service object's config).
8154 * Similarly, a request that is redirected will only redirect at most
8155 * {AWS.Config.maxRedirects} times.
8156 *
8157 * @param (see AWS.Request~send)
8158 * @context (see AWS.Request~send)
8159 * @example Adding a custom retry for a 404 response
8160 * request.on('retry', function(response) {
8161 * // this resource is not yet available, wait 10 seconds to get it again
8162 * if (response.httpResponse.statusCode === 404 && response.error) {
8163 * response.error.retryable = true; // retry this error
8164 * response.error.retryDelay = 10000; // wait 10 seconds
8165 * }
8166 * });
8167 *
8168 * @!group Data Parsing Events
8169 *
8170 * @!event extractError(response)
8171 * Triggered on all non-2xx requests so that listeners can extract
8172 * error details from the response body. Listeners to this event
8173 * should set the `response.error` property.
8174 * @param (see AWS.Request~send)
8175 * @context (see AWS.Request~send)
8176 *
8177 * @!event extractData(response)
8178 * Triggered in successful requests to allow listeners to
8179 * de-serialize the response body into `response.data`.
8180 * @param (see AWS.Request~send)
8181 * @context (see AWS.Request~send)
8182 *
8183 * @!group Completion Events
8184 *
8185 * @!event success(response)
8186 * Triggered when the request completed successfully.
8187 * `response.data` will contain the response data and
8188 * `response.error` will be null.
8189 * @param (see AWS.Request~send)
8190 * @context (see AWS.Request~send)
8191 *
8192 * @!event error(error, response)
8193 * Triggered when an error occurs at any point during the
8194 * request. `response.error` will contain details about the error
8195 * that occurred. `response.data` will be null.
8196 * @param error [Error] the error object containing details about
8197 * the error that occurred.
8198 * @param (see AWS.Request~send)
8199 * @context (see AWS.Request~send)
8200 *
8201 * @!event complete(response)
8202 * Triggered whenever a request cycle completes. `response.error`
8203 * should be checked, since the request may have failed.
8204 * @param (see AWS.Request~send)
8205 * @context (see AWS.Request~send)
8206 *
8207 * @!group HTTP Events
8208 *
8209 * @!event httpHeaders(statusCode, headers, response, statusMessage)
8210 * Triggered when headers are sent by the remote server
8211 * @param statusCode [Integer] the HTTP response code
8212 * @param headers [map<String,String>] the response headers
8213 * @param (see AWS.Request~send)
8214 * @param statusMessage [String] A status message corresponding to the HTTP
8215 * response code
8216 * @context (see AWS.Request~send)
8217 *
8218 * @!event httpData(chunk, response)
8219 * Triggered when data is sent by the remote server
8220 * @param chunk [Buffer] the buffer data containing the next data chunk
8221 * from the server
8222 * @param (see AWS.Request~send)
8223 * @context (see AWS.Request~send)
8224 * @see AWS.EventListeners.Core.HTTP_DATA
8225 *
8226 * @!event httpUploadProgress(progress, response)
8227 * Triggered when the HTTP request has uploaded more data
8228 * @param progress [map] An object containing the `loaded` and `total` bytes
8229 * of the request.
8230 * @param (see AWS.Request~send)
8231 * @context (see AWS.Request~send)
8232 * @note This event will not be emitted in Node.js 0.8.x.
8233 *
8234 * @!event httpDownloadProgress(progress, response)
8235 * Triggered when the HTTP request has downloaded more data
8236 * @param progress [map] An object containing the `loaded` and `total` bytes
8237 * of the request.
8238 * @param (see AWS.Request~send)
8239 * @context (see AWS.Request~send)
8240 * @note This event will not be emitted in Node.js 0.8.x.
8241 *
8242 * @!event httpError(error, response)
8243 * Triggered when the HTTP request failed
8244 * @param error [Error] the error object that was thrown
8245 * @param (see AWS.Request~send)
8246 * @context (see AWS.Request~send)
8247 *
8248 * @!event httpDone(response)
8249 * Triggered when the server is finished sending data
8250 * @param (see AWS.Request~send)
8251 * @context (see AWS.Request~send)
8252 *
8253 * @see AWS.Response
8254 */
8255 AWS.Request = inherit({
8256
8257 /**
8258 * Creates a request for an operation on a given service with
8259 * a set of input parameters.
8260 *
8261 * @param service [AWS.Service] the service to perform the operation on
8262 * @param operation [String] the operation to perform on the service
8263 * @param params [Object] parameters to send to the operation.
8264 * See the operation's documentation for the format of the
8265 * parameters.
8266 */
8267 constructor: function Request(service, operation, params) {
8268 var endpoint = service.endpoint;
8269 var region = service.config.region;
8270 var customUserAgent = service.config.customUserAgent;
8271
8272 // global endpoints sign as us-east-1
8273 if (service.isGlobalEndpoint) region = 'us-east-1';
8274
8275 this.domain = domain && domain.active;
8276 this.service = service;
8277 this.operation = operation;
8278 this.params = params || {};
8279 this.httpRequest = new AWS.HttpRequest(endpoint, region);
8280 this.httpRequest.appendToUserAgent(customUserAgent);
8281 this.startTime = service.getSkewCorrectedDate();
8282
8283 this.response = new AWS.Response(this);
8284 this._asm = new AcceptorStateMachine(fsm.states, 'validate');
8285 this._haltHandlersOnError = false;
8286
8287 AWS.SequentialExecutor.call(this);
8288 this.emit = this.emitEvent;
8289 },
8290
8291 /**
8292 * @!group Sending a Request
8293 */
8294
8295 /**
8296 * @overload send(callback = null)
8297 * Sends the request object.
8298 *
8299 * @callback callback function(err, data)
8300 * If a callback is supplied, it is called when a response is returned
8301 * from the service.
8302 * @context [AWS.Request] the request object being sent.
8303 * @param err [Error] the error object returned from the request.
8304 * Set to `null` if the request is successful.
8305 * @param data [Object] the de-serialized data returned from
8306 * the request. Set to `null` if a request error occurs.
8307 * @example Sending a request with a callback
8308 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8309 * request.send(function(err, data) { console.log(err, data); });
8310 * @example Sending a request with no callback (using event handlers)
8311 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8312 * request.on('complete', function(response) { ... }); // register a callback
8313 * request.send();
8314 */
8315 send: function send(callback) {
8316 if (callback) {
8317 // append to user agent
8318 this.httpRequest.appendToUserAgent('callback');
8319 this.on('complete', function (resp) {
8320 callback.call(resp, resp.error, resp.data);
8321 });
8322 }
8323 this.runTo();
8324
8325 return this.response;
8326 },
8327
8328 /**
8329 * @!method promise()
8330 * Sends the request and returns a 'thenable' promise.
8331 *
8332 * Two callbacks can be provided to the `then` method on the returned promise.
8333 * The first callback will be called if the promise is fulfilled, and the second
8334 * callback will be called if the promise is rejected.
8335 * @callback fulfilledCallback function(data)
8336 * Called if the promise is fulfilled.
8337 * @param data [Object] the de-serialized data returned from the request.
8338 * @callback rejectedCallback function(error)
8339 * Called if the promise is rejected.
8340 * @param error [Error] the error object returned from the request.
8341 * @return [Promise] A promise that represents the state of the request.
8342 * @example Sending a request using promises.
8343 * var request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8344 * var result = request.promise();
8345 * result.then(function(data) { ... }, function(error) { ... });
8346 */
8347
8348 /**
8349 * @api private
8350 */
8351 build: function build(callback) {
8352 return this.runTo('send', callback);
8353 },
8354
8355 /**
8356 * @api private
8357 */
8358 runTo: function runTo(state, done) {
8359 this._asm.runTo(state, done, this);
8360 return this;
8361 },
8362
8363 /**
8364 * Aborts a request, emitting the error and complete events.
8365 *
8366 * @!macro nobrowser
8367 * @example Aborting a request after sending
8368 * var params = {
8369 * Bucket: 'bucket', Key: 'key',
8370 * Body: Buffer.alloc(1024 * 1024 * 5) // 5MB payload
8371 * };
8372 * var request = s3.putObject(params);
8373 * request.send(function (err, data) {
8374 * if (err) console.log("Error:", err.code, err.message);
8375 * else console.log(data);
8376 * });
8377 *
8378 * // abort request in 1 second
8379 * setTimeout(request.abort.bind(request), 1000);
8380 *
8381 * // prints "Error: RequestAbortedError Request aborted by user"
8382 * @return [AWS.Request] the same request object, for chaining.
8383 * @since v1.4.0
8384 */
8385 abort: function abort() {
8386 this.removeAllListeners('validateResponse');
8387 this.removeAllListeners('extractError');
8388 this.on('validateResponse', function addAbortedError(resp) {
8389 resp.error = AWS.util.error(new Error('Request aborted by user'), {
8390 code: 'RequestAbortedError', retryable: false
8391 });
8392 });
8393
8394 if (this.httpRequest.stream && !this.httpRequest.stream.didCallback) { // abort HTTP stream
8395 this.httpRequest.stream.abort();
8396 if (this.httpRequest._abortCallback) {
8397 this.httpRequest._abortCallback();
8398 } else {
8399 this.removeAllListeners('send'); // haven't sent yet, so let's not
8400 }
8401 }
8402
8403 return this;
8404 },
8405
8406 /**
8407 * Iterates over each page of results given a pageable request, calling
8408 * the provided callback with each page of data. After all pages have been
8409 * retrieved, the callback is called with `null` data.
8410 *
8411 * @note This operation can generate multiple requests to a service.
8412 * @example Iterating over multiple pages of objects in an S3 bucket
8413 * var pages = 1;
8414 * s3.listObjects().eachPage(function(err, data) {
8415 * if (err) return;
8416 * console.log("Page", pages++);
8417 * console.log(data);
8418 * });
8419 * @example Iterating over multiple pages with an asynchronous callback
8420 * s3.listObjects(params).eachPage(function(err, data, done) {
8421 * doSomethingAsyncAndOrExpensive(function() {
8422 * // The next page of results isn't fetched until done is called
8423 * done();
8424 * });
8425 * });
8426 * @callback callback function(err, data, [doneCallback])
8427 * Called with each page of resulting data from the request. If the
8428 * optional `doneCallback` is provided in the function, it must be called
8429 * when the callback is complete.
8430 *
8431 * @param err [Error] an error object, if an error occurred.
8432 * @param data [Object] a single page of response data. If there is no
8433 * more data, this object will be `null`.
8434 * @param doneCallback [Function] an optional done callback. If this
8435 * argument is defined in the function declaration, it should be called
8436 * when the next page is ready to be retrieved. This is useful for
8437 * controlling serial pagination across asynchronous operations.
8438 * @return [Boolean] if the callback returns `false`, pagination will
8439 * stop.
8440 *
8441 * @see AWS.Request.eachItem
8442 * @see AWS.Response.nextPage
8443 * @since v1.4.0
8444 */
8445 eachPage: function eachPage(callback) {
8446 // Make all callbacks async-ish
8447 callback = AWS.util.fn.makeAsync(callback, 3);
8448
8449 function wrappedCallback(response) {
8450 callback.call(response, response.error, response.data, function (result) {
8451 if (result === false) return;
8452
8453 if (response.hasNextPage()) {
8454 response.nextPage().on('complete', wrappedCallback).send();
8455 } else {
8456 callback.call(response, null, null, AWS.util.fn.noop);
8457 }
8458 });
8459 }
8460
8461 this.on('complete', wrappedCallback).send();
8462 },
8463
8464 /**
8465 * Enumerates over individual items of a request, paging the responses if
8466 * necessary.
8467 *
8468 * @api experimental
8469 * @since v1.4.0
8470 */
8471 eachItem: function eachItem(callback) {
8472 var self = this;
8473 function wrappedCallback(err, data) {
8474 if (err) return callback(err, null);
8475 if (data === null) return callback(null, null);
8476
8477 var config = self.service.paginationConfig(self.operation);
8478 var resultKey = config.resultKey;
8479 if (Array.isArray(resultKey)) resultKey = resultKey[0];
8480 var items = jmespath.search(data, resultKey);
8481 var continueIteration = true;
8482 AWS.util.arrayEach(items, function(item) {
8483 continueIteration = callback(null, item);
8484 if (continueIteration === false) {
8485 return AWS.util.abort;
8486 }
8487 });
8488 return continueIteration;
8489 }
8490
8491 this.eachPage(wrappedCallback);
8492 },
8493
8494 /**
8495 * @return [Boolean] whether the operation can return multiple pages of
8496 * response data.
8497 * @see AWS.Response.eachPage
8498 * @since v1.4.0
8499 */
8500 isPageable: function isPageable() {
8501 return this.service.paginationConfig(this.operation) ? true : false;
8502 },
8503
8504 /**
8505 * Sends the request and converts the request object into a readable stream
8506 * that can be read from or piped into a writable stream.
8507 *
8508 * @note The data read from a readable stream contains only
8509 * the raw HTTP body contents.
8510 * @example Manually reading from a stream
8511 * request.createReadStream().on('data', function(data) {
8512 * console.log("Got data:", data.toString());
8513 * });
8514 * @example Piping a request body into a file
8515 * var out = fs.createWriteStream('/path/to/outfile.jpg');
8516 * s3.service.getObject(params).createReadStream().pipe(out);
8517 * @return [Stream] the readable stream object that can be piped
8518 * or read from (by registering 'data' event listeners).
8519 * @!macro nobrowser
8520 */
8521 createReadStream: function createReadStream() {
8522 var streams = AWS.util.stream;
8523 var req = this;
8524 var stream = null;
8525
8526 if (AWS.HttpClient.streamsApiVersion === 2) {
8527 stream = new streams.PassThrough();
8528 process.nextTick(function() { req.send(); });
8529 } else {
8530 stream = new streams.Stream();
8531 stream.readable = true;
8532
8533 stream.sent = false;
8534 stream.on('newListener', function(event) {
8535 if (!stream.sent && event === 'data') {
8536 stream.sent = true;
8537 process.nextTick(function() { req.send(); });
8538 }
8539 });
8540 }
8541
8542 this.on('error', function(err) {
8543 stream.emit('error', err);
8544 });
8545
8546 this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
8547 if (statusCode < 300) {
8548 req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
8549 req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
8550 req.on('httpError', function streamHttpError(error) {
8551 resp.error = error;
8552 resp.error.retryable = false;
8553 });
8554
8555 var shouldCheckContentLength = false;
8556 var expectedLen;
8557 if (req.httpRequest.method !== 'HEAD') {
8558 expectedLen = parseInt(headers['content-length'], 10);
8559 }
8560 if (expectedLen !== undefined && !isNaN(expectedLen) && expectedLen >= 0) {
8561 shouldCheckContentLength = true;
8562 var receivedLen = 0;
8563 }
8564
8565 var checkContentLengthAndEmit = function checkContentLengthAndEmit() {
8566 if (shouldCheckContentLength && receivedLen !== expectedLen) {
8567 stream.emit('error', AWS.util.error(
8568 new Error('Stream content length mismatch. Received ' +
8569 receivedLen + ' of ' + expectedLen + ' bytes.'),
8570 { code: 'StreamContentLengthMismatch' }
8571 ));
8572 } else if (AWS.HttpClient.streamsApiVersion === 2) {
8573 stream.end();
8574 } else {
8575 stream.emit('end');
8576 }
8577 };
8578
8579 var httpStream = resp.httpResponse.createUnbufferedStream();
8580
8581 if (AWS.HttpClient.streamsApiVersion === 2) {
8582 if (shouldCheckContentLength) {
8583 var lengthAccumulator = new streams.PassThrough();
8584 lengthAccumulator._write = function(chunk) {
8585 if (chunk && chunk.length) {
8586 receivedLen += chunk.length;
8587 }
8588 return streams.PassThrough.prototype._write.apply(this, arguments);
8589 };
8590
8591 lengthAccumulator.on('end', checkContentLengthAndEmit);
8592 stream.on('error', function(err) {
8593 shouldCheckContentLength = false;
8594 httpStream.unpipe(lengthAccumulator);
8595 lengthAccumulator.emit('end');
8596 lengthAccumulator.end();
8597 });
8598 httpStream.pipe(lengthAccumulator).pipe(stream, { end: false });
8599 } else {
8600 httpStream.pipe(stream);
8601 }
8602 } else {
8603
8604 if (shouldCheckContentLength) {
8605 httpStream.on('data', function(arg) {
8606 if (arg && arg.length) {
8607 receivedLen += arg.length;
8608 }
8609 });
8610 }
8611
8612 httpStream.on('data', function(arg) {
8613 stream.emit('data', arg);
8614 });
8615 httpStream.on('end', checkContentLengthAndEmit);
8616 }
8617
8618 httpStream.on('error', function(err) {
8619 shouldCheckContentLength = false;
8620 stream.emit('error', err);
8621 });
8622 }
8623 });
8624
8625 return stream;
8626 },
8627
8628 /**
8629 * @param [Array,Response] args This should be the response object,
8630 * or an array of args to send to the event.
8631 * @api private
8632 */
8633 emitEvent: function emit(eventName, args, done) {
8634 if (typeof args === 'function') { done = args; args = null; }
8635 if (!done) done = function() { };
8636 if (!args) args = this.eventParameters(eventName, this.response);
8637
8638 var origEmit = AWS.SequentialExecutor.prototype.emit;
8639 origEmit.call(this, eventName, args, function (err) {
8640 if (err) this.response.error = err;
8641 done.call(this, err);
8642 });
8643 },
8644
8645 /**
8646 * @api private
8647 */
8648 eventParameters: function eventParameters(eventName) {
8649 switch (eventName) {
8650 case 'restart':
8651 case 'validate':
8652 case 'sign':
8653 case 'build':
8654 case 'afterValidate':
8655 case 'afterBuild':
8656 return [this];
8657 case 'error':
8658 return [this.response.error, this.response];
8659 default:
8660 return [this.response];
8661 }
8662 },
8663
8664 /**
8665 * @api private
8666 */
8667 presign: function presign(expires, callback) {
8668 if (!callback && typeof expires === 'function') {
8669 callback = expires;
8670 expires = null;
8671 }
8672 return new AWS.Signers.Presign().sign(this.toGet(), expires, callback);
8673 },
8674
8675 /**
8676 * @api private
8677 */
8678 isPresigned: function isPresigned() {
8679 return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires');
8680 },
8681
8682 /**
8683 * @api private
8684 */
8685 toUnauthenticated: function toUnauthenticated() {
8686 this._unAuthenticated = true;
8687 this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS);
8688 this.removeListener('sign', AWS.EventListeners.Core.SIGN);
8689 return this;
8690 },
8691
8692 /**
8693 * @api private
8694 */
8695 toGet: function toGet() {
8696 if (this.service.api.protocol === 'query' ||
8697 this.service.api.protocol === 'ec2') {
8698 this.removeListener('build', this.buildAsGet);
8699 this.addListener('build', this.buildAsGet);
8700 }
8701 return this;
8702 },
8703
8704 /**
8705 * @api private
8706 */
8707 buildAsGet: function buildAsGet(request) {
8708 request.httpRequest.method = 'GET';
8709 request.httpRequest.path = request.service.endpoint.path +
8710 '?' + request.httpRequest.body;
8711 request.httpRequest.body = '';
8712
8713 // don't need these headers on a GET request
8714 delete request.httpRequest.headers['Content-Length'];
8715 delete request.httpRequest.headers['Content-Type'];
8716 },
8717
8718 /**
8719 * @api private
8720 */
8721 haltHandlersOnError: function haltHandlersOnError() {
8722 this._haltHandlersOnError = true;
8723 }
8724 });
8725
8726 /**
8727 * @api private
8728 */
8729 AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
8730 this.prototype.promise = function promise() {
8731 var self = this;
8732 // append to user agent
8733 this.httpRequest.appendToUserAgent('promise');
8734 return new PromiseDependency(function(resolve, reject) {
8735 self.on('complete', function(resp) {
8736 if (resp.error) {
8737 reject(resp.error);
8738 } else {
8739 // define $response property so that it is not enumberable
8740 // this prevents circular reference errors when stringifying the JSON object
8741 resolve(Object.defineProperty(
8742 resp.data || {},
8743 '$response',
8744 {value: resp}
8745 ));
8746 }
8747 });
8748 self.runTo();
8749 });
8750 };
8751 };
8752
8753 /**
8754 * @api private
8755 */
8756 AWS.Request.deletePromisesFromClass = function deletePromisesFromClass() {
8757 delete this.prototype.promise;
8758 };
8759
8760 AWS.util.addPromises(AWS.Request);
8761
8762 AWS.util.mixin(AWS.Request, AWS.SequentialExecutor);
8763
8764 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
8765
8766/***/ }),
8767/* 50 */
8768/***/ (function(module, exports) {
8769
8770 function AcceptorStateMachine(states, state) {
8771 this.currentState = state || null;
8772 this.states = states || {};
8773 }
8774
8775 AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) {
8776 if (typeof finalState === 'function') {
8777 inputError = bindObject; bindObject = done;
8778 done = finalState; finalState = null;
8779 }
8780
8781 var self = this;
8782 var state = self.states[self.currentState];
8783 state.fn.call(bindObject || self, inputError, function(err) {
8784 if (err) {
8785 if (state.fail) self.currentState = state.fail;
8786 else return done ? done.call(bindObject, err) : null;
8787 } else {
8788 if (state.accept) self.currentState = state.accept;
8789 else return done ? done.call(bindObject) : null;
8790 }
8791 if (self.currentState === finalState) {
8792 return done ? done.call(bindObject, err) : null;
8793 }
8794
8795 self.runTo(finalState, done, bindObject, err);
8796 });
8797 };
8798
8799 AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) {
8800 if (typeof acceptState === 'function') {
8801 fn = acceptState; acceptState = null; failState = null;
8802 } else if (typeof failState === 'function') {
8803 fn = failState; failState = null;
8804 }
8805
8806 if (!this.currentState) this.currentState = name;
8807 this.states[name] = { accept: acceptState, fail: failState, fn: fn };
8808 return this;
8809 };
8810
8811 /**
8812 * @api private
8813 */
8814 module.exports = AcceptorStateMachine;
8815
8816
8817/***/ }),
8818/* 51 */
8819/***/ (function(module, exports, __webpack_require__) {
8820
8821 (function(exports) {
8822 "use strict";
8823
8824 function isArray(obj) {
8825 if (obj !== null) {
8826 return Object.prototype.toString.call(obj) === "[object Array]";
8827 } else {
8828 return false;
8829 }
8830 }
8831
8832 function isObject(obj) {
8833 if (obj !== null) {
8834 return Object.prototype.toString.call(obj) === "[object Object]";
8835 } else {
8836 return false;
8837 }
8838 }
8839
8840 function strictDeepEqual(first, second) {
8841 // Check the scalar case first.
8842 if (first === second) {
8843 return true;
8844 }
8845
8846 // Check if they are the same type.
8847 var firstType = Object.prototype.toString.call(first);
8848 if (firstType !== Object.prototype.toString.call(second)) {
8849 return false;
8850 }
8851 // We know that first and second have the same type so we can just check the
8852 // first type from now on.
8853 if (isArray(first) === true) {
8854 // Short circuit if they're not the same length;
8855 if (first.length !== second.length) {
8856 return false;
8857 }
8858 for (var i = 0; i < first.length; i++) {
8859 if (strictDeepEqual(first[i], second[i]) === false) {
8860 return false;
8861 }
8862 }
8863 return true;
8864 }
8865 if (isObject(first) === true) {
8866 // An object is equal if it has the same key/value pairs.
8867 var keysSeen = {};
8868 for (var key in first) {
8869 if (hasOwnProperty.call(first, key)) {
8870 if (strictDeepEqual(first[key], second[key]) === false) {
8871 return false;
8872 }
8873 keysSeen[key] = true;
8874 }
8875 }
8876 // Now check that there aren't any keys in second that weren't
8877 // in first.
8878 for (var key2 in second) {
8879 if (hasOwnProperty.call(second, key2)) {
8880 if (keysSeen[key2] !== true) {
8881 return false;
8882 }
8883 }
8884 }
8885 return true;
8886 }
8887 return false;
8888 }
8889
8890 function isFalse(obj) {
8891 // From the spec:
8892 // A false value corresponds to the following values:
8893 // Empty list
8894 // Empty object
8895 // Empty string
8896 // False boolean
8897 // null value
8898
8899 // First check the scalar values.
8900 if (obj === "" || obj === false || obj === null) {
8901 return true;
8902 } else if (isArray(obj) && obj.length === 0) {
8903 // Check for an empty array.
8904 return true;
8905 } else if (isObject(obj)) {
8906 // Check for an empty object.
8907 for (var key in obj) {
8908 // If there are any keys, then
8909 // the object is not empty so the object
8910 // is not false.
8911 if (obj.hasOwnProperty(key)) {
8912 return false;
8913 }
8914 }
8915 return true;
8916 } else {
8917 return false;
8918 }
8919 }
8920
8921 function objValues(obj) {
8922 var keys = Object.keys(obj);
8923 var values = [];
8924 for (var i = 0; i < keys.length; i++) {
8925 values.push(obj[keys[i]]);
8926 }
8927 return values;
8928 }
8929
8930 function merge(a, b) {
8931 var merged = {};
8932 for (var key in a) {
8933 merged[key] = a[key];
8934 }
8935 for (var key2 in b) {
8936 merged[key2] = b[key2];
8937 }
8938 return merged;
8939 }
8940
8941 var trimLeft;
8942 if (typeof String.prototype.trimLeft === "function") {
8943 trimLeft = function(str) {
8944 return str.trimLeft();
8945 };
8946 } else {
8947 trimLeft = function(str) {
8948 return str.match(/^\s*(.*)/)[1];
8949 };
8950 }
8951
8952 // Type constants used to define functions.
8953 var TYPE_NUMBER = 0;
8954 var TYPE_ANY = 1;
8955 var TYPE_STRING = 2;
8956 var TYPE_ARRAY = 3;
8957 var TYPE_OBJECT = 4;
8958 var TYPE_BOOLEAN = 5;
8959 var TYPE_EXPREF = 6;
8960 var TYPE_NULL = 7;
8961 var TYPE_ARRAY_NUMBER = 8;
8962 var TYPE_ARRAY_STRING = 9;
8963
8964 var TOK_EOF = "EOF";
8965 var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier";
8966 var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier";
8967 var TOK_RBRACKET = "Rbracket";
8968 var TOK_RPAREN = "Rparen";
8969 var TOK_COMMA = "Comma";
8970 var TOK_COLON = "Colon";
8971 var TOK_RBRACE = "Rbrace";
8972 var TOK_NUMBER = "Number";
8973 var TOK_CURRENT = "Current";
8974 var TOK_EXPREF = "Expref";
8975 var TOK_PIPE = "Pipe";
8976 var TOK_OR = "Or";
8977 var TOK_AND = "And";
8978 var TOK_EQ = "EQ";
8979 var TOK_GT = "GT";
8980 var TOK_LT = "LT";
8981 var TOK_GTE = "GTE";
8982 var TOK_LTE = "LTE";
8983 var TOK_NE = "NE";
8984 var TOK_FLATTEN = "Flatten";
8985 var TOK_STAR = "Star";
8986 var TOK_FILTER = "Filter";
8987 var TOK_DOT = "Dot";
8988 var TOK_NOT = "Not";
8989 var TOK_LBRACE = "Lbrace";
8990 var TOK_LBRACKET = "Lbracket";
8991 var TOK_LPAREN= "Lparen";
8992 var TOK_LITERAL= "Literal";
8993
8994 // The "&", "[", "<", ">" tokens
8995 // are not in basicToken because
8996 // there are two token variants
8997 // ("&&", "[?", "<=", ">="). This is specially handled
8998 // below.
8999
9000 var basicTokens = {
9001 ".": TOK_DOT,
9002 "*": TOK_STAR,
9003 ",": TOK_COMMA,
9004 ":": TOK_COLON,
9005 "{": TOK_LBRACE,
9006 "}": TOK_RBRACE,
9007 "]": TOK_RBRACKET,
9008 "(": TOK_LPAREN,
9009 ")": TOK_RPAREN,
9010 "@": TOK_CURRENT
9011 };
9012
9013 var operatorStartToken = {
9014 "<": true,
9015 ">": true,
9016 "=": true,
9017 "!": true
9018 };
9019
9020 var skipChars = {
9021 " ": true,
9022 "\t": true,
9023 "\n": true
9024 };
9025
9026
9027 function isAlpha(ch) {
9028 return (ch >= "a" && ch <= "z") ||
9029 (ch >= "A" && ch <= "Z") ||
9030 ch === "_";
9031 }
9032
9033 function isNum(ch) {
9034 return (ch >= "0" && ch <= "9") ||
9035 ch === "-";
9036 }
9037 function isAlphaNum(ch) {
9038 return (ch >= "a" && ch <= "z") ||
9039 (ch >= "A" && ch <= "Z") ||
9040 (ch >= "0" && ch <= "9") ||
9041 ch === "_";
9042 }
9043
9044 function Lexer() {
9045 }
9046 Lexer.prototype = {
9047 tokenize: function(stream) {
9048 var tokens = [];
9049 this._current = 0;
9050 var start;
9051 var identifier;
9052 var token;
9053 while (this._current < stream.length) {
9054 if (isAlpha(stream[this._current])) {
9055 start = this._current;
9056 identifier = this._consumeUnquotedIdentifier(stream);
9057 tokens.push({type: TOK_UNQUOTEDIDENTIFIER,
9058 value: identifier,
9059 start: start});
9060 } else if (basicTokens[stream[this._current]] !== undefined) {
9061 tokens.push({type: basicTokens[stream[this._current]],
9062 value: stream[this._current],
9063 start: this._current});
9064 this._current++;
9065 } else if (isNum(stream[this._current])) {
9066 token = this._consumeNumber(stream);
9067 tokens.push(token);
9068 } else if (stream[this._current] === "[") {
9069 // No need to increment this._current. This happens
9070 // in _consumeLBracket
9071 token = this._consumeLBracket(stream);
9072 tokens.push(token);
9073 } else if (stream[this._current] === "\"") {
9074 start = this._current;
9075 identifier = this._consumeQuotedIdentifier(stream);
9076 tokens.push({type: TOK_QUOTEDIDENTIFIER,
9077 value: identifier,
9078 start: start});
9079 } else if (stream[this._current] === "'") {
9080 start = this._current;
9081 identifier = this._consumeRawStringLiteral(stream);
9082 tokens.push({type: TOK_LITERAL,
9083 value: identifier,
9084 start: start});
9085 } else if (stream[this._current] === "`") {
9086 start = this._current;
9087 var literal = this._consumeLiteral(stream);
9088 tokens.push({type: TOK_LITERAL,
9089 value: literal,
9090 start: start});
9091 } else if (operatorStartToken[stream[this._current]] !== undefined) {
9092 tokens.push(this._consumeOperator(stream));
9093 } else if (skipChars[stream[this._current]] !== undefined) {
9094 // Ignore whitespace.
9095 this._current++;
9096 } else if (stream[this._current] === "&") {
9097 start = this._current;
9098 this._current++;
9099 if (stream[this._current] === "&") {
9100 this._current++;
9101 tokens.push({type: TOK_AND, value: "&&", start: start});
9102 } else {
9103 tokens.push({type: TOK_EXPREF, value: "&", start: start});
9104 }
9105 } else if (stream[this._current] === "|") {
9106 start = this._current;
9107 this._current++;
9108 if (stream[this._current] === "|") {
9109 this._current++;
9110 tokens.push({type: TOK_OR, value: "||", start: start});
9111 } else {
9112 tokens.push({type: TOK_PIPE, value: "|", start: start});
9113 }
9114 } else {
9115 var error = new Error("Unknown character:" + stream[this._current]);
9116 error.name = "LexerError";
9117 throw error;
9118 }
9119 }
9120 return tokens;
9121 },
9122
9123 _consumeUnquotedIdentifier: function(stream) {
9124 var start = this._current;
9125 this._current++;
9126 while (this._current < stream.length && isAlphaNum(stream[this._current])) {
9127 this._current++;
9128 }
9129 return stream.slice(start, this._current);
9130 },
9131
9132 _consumeQuotedIdentifier: function(stream) {
9133 var start = this._current;
9134 this._current++;
9135 var maxLength = stream.length;
9136 while (stream[this._current] !== "\"" && this._current < maxLength) {
9137 // You can escape a double quote and you can escape an escape.
9138 var current = this._current;
9139 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9140 stream[current + 1] === "\"")) {
9141 current += 2;
9142 } else {
9143 current++;
9144 }
9145 this._current = current;
9146 }
9147 this._current++;
9148 return JSON.parse(stream.slice(start, this._current));
9149 },
9150
9151 _consumeRawStringLiteral: function(stream) {
9152 var start = this._current;
9153 this._current++;
9154 var maxLength = stream.length;
9155 while (stream[this._current] !== "'" && this._current < maxLength) {
9156 // You can escape a single quote and you can escape an escape.
9157 var current = this._current;
9158 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9159 stream[current + 1] === "'")) {
9160 current += 2;
9161 } else {
9162 current++;
9163 }
9164 this._current = current;
9165 }
9166 this._current++;
9167 var literal = stream.slice(start + 1, this._current - 1);
9168 return literal.replace("\\'", "'");
9169 },
9170
9171 _consumeNumber: function(stream) {
9172 var start = this._current;
9173 this._current++;
9174 var maxLength = stream.length;
9175 while (isNum(stream[this._current]) && this._current < maxLength) {
9176 this._current++;
9177 }
9178 var value = parseInt(stream.slice(start, this._current));
9179 return {type: TOK_NUMBER, value: value, start: start};
9180 },
9181
9182 _consumeLBracket: function(stream) {
9183 var start = this._current;
9184 this._current++;
9185 if (stream[this._current] === "?") {
9186 this._current++;
9187 return {type: TOK_FILTER, value: "[?", start: start};
9188 } else if (stream[this._current] === "]") {
9189 this._current++;
9190 return {type: TOK_FLATTEN, value: "[]", start: start};
9191 } else {
9192 return {type: TOK_LBRACKET, value: "[", start: start};
9193 }
9194 },
9195
9196 _consumeOperator: function(stream) {
9197 var start = this._current;
9198 var startingChar = stream[start];
9199 this._current++;
9200 if (startingChar === "!") {
9201 if (stream[this._current] === "=") {
9202 this._current++;
9203 return {type: TOK_NE, value: "!=", start: start};
9204 } else {
9205 return {type: TOK_NOT, value: "!", start: start};
9206 }
9207 } else if (startingChar === "<") {
9208 if (stream[this._current] === "=") {
9209 this._current++;
9210 return {type: TOK_LTE, value: "<=", start: start};
9211 } else {
9212 return {type: TOK_LT, value: "<", start: start};
9213 }
9214 } else if (startingChar === ">") {
9215 if (stream[this._current] === "=") {
9216 this._current++;
9217 return {type: TOK_GTE, value: ">=", start: start};
9218 } else {
9219 return {type: TOK_GT, value: ">", start: start};
9220 }
9221 } else if (startingChar === "=") {
9222 if (stream[this._current] === "=") {
9223 this._current++;
9224 return {type: TOK_EQ, value: "==", start: start};
9225 }
9226 }
9227 },
9228
9229 _consumeLiteral: function(stream) {
9230 this._current++;
9231 var start = this._current;
9232 var maxLength = stream.length;
9233 var literal;
9234 while(stream[this._current] !== "`" && this._current < maxLength) {
9235 // You can escape a literal char or you can escape the escape.
9236 var current = this._current;
9237 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9238 stream[current + 1] === "`")) {
9239 current += 2;
9240 } else {
9241 current++;
9242 }
9243 this._current = current;
9244 }
9245 var literalString = trimLeft(stream.slice(start, this._current));
9246 literalString = literalString.replace("\\`", "`");
9247 if (this._looksLikeJSON(literalString)) {
9248 literal = JSON.parse(literalString);
9249 } else {
9250 // Try to JSON parse it as "<literal>"
9251 literal = JSON.parse("\"" + literalString + "\"");
9252 }
9253 // +1 gets us to the ending "`", +1 to move on to the next char.
9254 this._current++;
9255 return literal;
9256 },
9257
9258 _looksLikeJSON: function(literalString) {
9259 var startingChars = "[{\"";
9260 var jsonLiterals = ["true", "false", "null"];
9261 var numberLooking = "-0123456789";
9262
9263 if (literalString === "") {
9264 return false;
9265 } else if (startingChars.indexOf(literalString[0]) >= 0) {
9266 return true;
9267 } else if (jsonLiterals.indexOf(literalString) >= 0) {
9268 return true;
9269 } else if (numberLooking.indexOf(literalString[0]) >= 0) {
9270 try {
9271 JSON.parse(literalString);
9272 return true;
9273 } catch (ex) {
9274 return false;
9275 }
9276 } else {
9277 return false;
9278 }
9279 }
9280 };
9281
9282 var bindingPower = {};
9283 bindingPower[TOK_EOF] = 0;
9284 bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0;
9285 bindingPower[TOK_QUOTEDIDENTIFIER] = 0;
9286 bindingPower[TOK_RBRACKET] = 0;
9287 bindingPower[TOK_RPAREN] = 0;
9288 bindingPower[TOK_COMMA] = 0;
9289 bindingPower[TOK_RBRACE] = 0;
9290 bindingPower[TOK_NUMBER] = 0;
9291 bindingPower[TOK_CURRENT] = 0;
9292 bindingPower[TOK_EXPREF] = 0;
9293 bindingPower[TOK_PIPE] = 1;
9294 bindingPower[TOK_OR] = 2;
9295 bindingPower[TOK_AND] = 3;
9296 bindingPower[TOK_EQ] = 5;
9297 bindingPower[TOK_GT] = 5;
9298 bindingPower[TOK_LT] = 5;
9299 bindingPower[TOK_GTE] = 5;
9300 bindingPower[TOK_LTE] = 5;
9301 bindingPower[TOK_NE] = 5;
9302 bindingPower[TOK_FLATTEN] = 9;
9303 bindingPower[TOK_STAR] = 20;
9304 bindingPower[TOK_FILTER] = 21;
9305 bindingPower[TOK_DOT] = 40;
9306 bindingPower[TOK_NOT] = 45;
9307 bindingPower[TOK_LBRACE] = 50;
9308 bindingPower[TOK_LBRACKET] = 55;
9309 bindingPower[TOK_LPAREN] = 60;
9310
9311 function Parser() {
9312 }
9313
9314 Parser.prototype = {
9315 parse: function(expression) {
9316 this._loadTokens(expression);
9317 this.index = 0;
9318 var ast = this.expression(0);
9319 if (this._lookahead(0) !== TOK_EOF) {
9320 var t = this._lookaheadToken(0);
9321 var error = new Error(
9322 "Unexpected token type: " + t.type + ", value: " + t.value);
9323 error.name = "ParserError";
9324 throw error;
9325 }
9326 return ast;
9327 },
9328
9329 _loadTokens: function(expression) {
9330 var lexer = new Lexer();
9331 var tokens = lexer.tokenize(expression);
9332 tokens.push({type: TOK_EOF, value: "", start: expression.length});
9333 this.tokens = tokens;
9334 },
9335
9336 expression: function(rbp) {
9337 var leftToken = this._lookaheadToken(0);
9338 this._advance();
9339 var left = this.nud(leftToken);
9340 var currentToken = this._lookahead(0);
9341 while (rbp < bindingPower[currentToken]) {
9342 this._advance();
9343 left = this.led(currentToken, left);
9344 currentToken = this._lookahead(0);
9345 }
9346 return left;
9347 },
9348
9349 _lookahead: function(number) {
9350 return this.tokens[this.index + number].type;
9351 },
9352
9353 _lookaheadToken: function(number) {
9354 return this.tokens[this.index + number];
9355 },
9356
9357 _advance: function() {
9358 this.index++;
9359 },
9360
9361 nud: function(token) {
9362 var left;
9363 var right;
9364 var expression;
9365 switch (token.type) {
9366 case TOK_LITERAL:
9367 return {type: "Literal", value: token.value};
9368 case TOK_UNQUOTEDIDENTIFIER:
9369 return {type: "Field", name: token.value};
9370 case TOK_QUOTEDIDENTIFIER:
9371 var node = {type: "Field", name: token.value};
9372 if (this._lookahead(0) === TOK_LPAREN) {
9373 throw new Error("Quoted identifier not allowed for function names.");
9374 } else {
9375 return node;
9376 }
9377 break;
9378 case TOK_NOT:
9379 right = this.expression(bindingPower.Not);
9380 return {type: "NotExpression", children: [right]};
9381 case TOK_STAR:
9382 left = {type: "Identity"};
9383 right = null;
9384 if (this._lookahead(0) === TOK_RBRACKET) {
9385 // This can happen in a multiselect,
9386 // [a, b, *]
9387 right = {type: "Identity"};
9388 } else {
9389 right = this._parseProjectionRHS(bindingPower.Star);
9390 }
9391 return {type: "ValueProjection", children: [left, right]};
9392 case TOK_FILTER:
9393 return this.led(token.type, {type: "Identity"});
9394 case TOK_LBRACE:
9395 return this._parseMultiselectHash();
9396 case TOK_FLATTEN:
9397 left = {type: TOK_FLATTEN, children: [{type: "Identity"}]};
9398 right = this._parseProjectionRHS(bindingPower.Flatten);
9399 return {type: "Projection", children: [left, right]};
9400 case TOK_LBRACKET:
9401 if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) {
9402 right = this._parseIndexExpression();
9403 return this._projectIfSlice({type: "Identity"}, right);
9404 } else if (this._lookahead(0) === TOK_STAR &&
9405 this._lookahead(1) === TOK_RBRACKET) {
9406 this._advance();
9407 this._advance();
9408 right = this._parseProjectionRHS(bindingPower.Star);
9409 return {type: "Projection",
9410 children: [{type: "Identity"}, right]};
9411 } else {
9412 return this._parseMultiselectList();
9413 }
9414 break;
9415 case TOK_CURRENT:
9416 return {type: TOK_CURRENT};
9417 case TOK_EXPREF:
9418 expression = this.expression(bindingPower.Expref);
9419 return {type: "ExpressionReference", children: [expression]};
9420 case TOK_LPAREN:
9421 var args = [];
9422 while (this._lookahead(0) !== TOK_RPAREN) {
9423 if (this._lookahead(0) === TOK_CURRENT) {
9424 expression = {type: TOK_CURRENT};
9425 this._advance();
9426 } else {
9427 expression = this.expression(0);
9428 }
9429 args.push(expression);
9430 }
9431 this._match(TOK_RPAREN);
9432 return args[0];
9433 default:
9434 this._errorToken(token);
9435 }
9436 },
9437
9438 led: function(tokenName, left) {
9439 var right;
9440 switch(tokenName) {
9441 case TOK_DOT:
9442 var rbp = bindingPower.Dot;
9443 if (this._lookahead(0) !== TOK_STAR) {
9444 right = this._parseDotRHS(rbp);
9445 return {type: "Subexpression", children: [left, right]};
9446 } else {
9447 // Creating a projection.
9448 this._advance();
9449 right = this._parseProjectionRHS(rbp);
9450 return {type: "ValueProjection", children: [left, right]};
9451 }
9452 break;
9453 case TOK_PIPE:
9454 right = this.expression(bindingPower.Pipe);
9455 return {type: TOK_PIPE, children: [left, right]};
9456 case TOK_OR:
9457 right = this.expression(bindingPower.Or);
9458 return {type: "OrExpression", children: [left, right]};
9459 case TOK_AND:
9460 right = this.expression(bindingPower.And);
9461 return {type: "AndExpression", children: [left, right]};
9462 case TOK_LPAREN:
9463 var name = left.name;
9464 var args = [];
9465 var expression, node;
9466 while (this._lookahead(0) !== TOK_RPAREN) {
9467 if (this._lookahead(0) === TOK_CURRENT) {
9468 expression = {type: TOK_CURRENT};
9469 this._advance();
9470 } else {
9471 expression = this.expression(0);
9472 }
9473 if (this._lookahead(0) === TOK_COMMA) {
9474 this._match(TOK_COMMA);
9475 }
9476 args.push(expression);
9477 }
9478 this._match(TOK_RPAREN);
9479 node = {type: "Function", name: name, children: args};
9480 return node;
9481 case TOK_FILTER:
9482 var condition = this.expression(0);
9483 this._match(TOK_RBRACKET);
9484 if (this._lookahead(0) === TOK_FLATTEN) {
9485 right = {type: "Identity"};
9486 } else {
9487 right = this._parseProjectionRHS(bindingPower.Filter);
9488 }
9489 return {type: "FilterProjection", children: [left, right, condition]};
9490 case TOK_FLATTEN:
9491 var leftNode = {type: TOK_FLATTEN, children: [left]};
9492 var rightNode = this._parseProjectionRHS(bindingPower.Flatten);
9493 return {type: "Projection", children: [leftNode, rightNode]};
9494 case TOK_EQ:
9495 case TOK_NE:
9496 case TOK_GT:
9497 case TOK_GTE:
9498 case TOK_LT:
9499 case TOK_LTE:
9500 return this._parseComparator(left, tokenName);
9501 case TOK_LBRACKET:
9502 var token = this._lookaheadToken(0);
9503 if (token.type === TOK_NUMBER || token.type === TOK_COLON) {
9504 right = this._parseIndexExpression();
9505 return this._projectIfSlice(left, right);
9506 } else {
9507 this._match(TOK_STAR);
9508 this._match(TOK_RBRACKET);
9509 right = this._parseProjectionRHS(bindingPower.Star);
9510 return {type: "Projection", children: [left, right]};
9511 }
9512 break;
9513 default:
9514 this._errorToken(this._lookaheadToken(0));
9515 }
9516 },
9517
9518 _match: function(tokenType) {
9519 if (this._lookahead(0) === tokenType) {
9520 this._advance();
9521 } else {
9522 var t = this._lookaheadToken(0);
9523 var error = new Error("Expected " + tokenType + ", got: " + t.type);
9524 error.name = "ParserError";
9525 throw error;
9526 }
9527 },
9528
9529 _errorToken: function(token) {
9530 var error = new Error("Invalid token (" +
9531 token.type + "): \"" +
9532 token.value + "\"");
9533 error.name = "ParserError";
9534 throw error;
9535 },
9536
9537
9538 _parseIndexExpression: function() {
9539 if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) {
9540 return this._parseSliceExpression();
9541 } else {
9542 var node = {
9543 type: "Index",
9544 value: this._lookaheadToken(0).value};
9545 this._advance();
9546 this._match(TOK_RBRACKET);
9547 return node;
9548 }
9549 },
9550
9551 _projectIfSlice: function(left, right) {
9552 var indexExpr = {type: "IndexExpression", children: [left, right]};
9553 if (right.type === "Slice") {
9554 return {
9555 type: "Projection",
9556 children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)]
9557 };
9558 } else {
9559 return indexExpr;
9560 }
9561 },
9562
9563 _parseSliceExpression: function() {
9564 // [start:end:step] where each part is optional, as well as the last
9565 // colon.
9566 var parts = [null, null, null];
9567 var index = 0;
9568 var currentToken = this._lookahead(0);
9569 while (currentToken !== TOK_RBRACKET && index < 3) {
9570 if (currentToken === TOK_COLON) {
9571 index++;
9572 this._advance();
9573 } else if (currentToken === TOK_NUMBER) {
9574 parts[index] = this._lookaheadToken(0).value;
9575 this._advance();
9576 } else {
9577 var t = this._lookahead(0);
9578 var error = new Error("Syntax error, unexpected token: " +
9579 t.value + "(" + t.type + ")");
9580 error.name = "Parsererror";
9581 throw error;
9582 }
9583 currentToken = this._lookahead(0);
9584 }
9585 this._match(TOK_RBRACKET);
9586 return {
9587 type: "Slice",
9588 children: parts
9589 };
9590 },
9591
9592 _parseComparator: function(left, comparator) {
9593 var right = this.expression(bindingPower[comparator]);
9594 return {type: "Comparator", name: comparator, children: [left, right]};
9595 },
9596
9597 _parseDotRHS: function(rbp) {
9598 var lookahead = this._lookahead(0);
9599 var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];
9600 if (exprTokens.indexOf(lookahead) >= 0) {
9601 return this.expression(rbp);
9602 } else if (lookahead === TOK_LBRACKET) {
9603 this._match(TOK_LBRACKET);
9604 return this._parseMultiselectList();
9605 } else if (lookahead === TOK_LBRACE) {
9606 this._match(TOK_LBRACE);
9607 return this._parseMultiselectHash();
9608 }
9609 },
9610
9611 _parseProjectionRHS: function(rbp) {
9612 var right;
9613 if (bindingPower[this._lookahead(0)] < 10) {
9614 right = {type: "Identity"};
9615 } else if (this._lookahead(0) === TOK_LBRACKET) {
9616 right = this.expression(rbp);
9617 } else if (this._lookahead(0) === TOK_FILTER) {
9618 right = this.expression(rbp);
9619 } else if (this._lookahead(0) === TOK_DOT) {
9620 this._match(TOK_DOT);
9621 right = this._parseDotRHS(rbp);
9622 } else {
9623 var t = this._lookaheadToken(0);
9624 var error = new Error("Sytanx error, unexpected token: " +
9625 t.value + "(" + t.type + ")");
9626 error.name = "ParserError";
9627 throw error;
9628 }
9629 return right;
9630 },
9631
9632 _parseMultiselectList: function() {
9633 var expressions = [];
9634 while (this._lookahead(0) !== TOK_RBRACKET) {
9635 var expression = this.expression(0);
9636 expressions.push(expression);
9637 if (this._lookahead(0) === TOK_COMMA) {
9638 this._match(TOK_COMMA);
9639 if (this._lookahead(0) === TOK_RBRACKET) {
9640 throw new Error("Unexpected token Rbracket");
9641 }
9642 }
9643 }
9644 this._match(TOK_RBRACKET);
9645 return {type: "MultiSelectList", children: expressions};
9646 },
9647
9648 _parseMultiselectHash: function() {
9649 var pairs = [];
9650 var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER];
9651 var keyToken, keyName, value, node;
9652 for (;;) {
9653 keyToken = this._lookaheadToken(0);
9654 if (identifierTypes.indexOf(keyToken.type) < 0) {
9655 throw new Error("Expecting an identifier token, got: " +
9656 keyToken.type);
9657 }
9658 keyName = keyToken.value;
9659 this._advance();
9660 this._match(TOK_COLON);
9661 value = this.expression(0);
9662 node = {type: "KeyValuePair", name: keyName, value: value};
9663 pairs.push(node);
9664 if (this._lookahead(0) === TOK_COMMA) {
9665 this._match(TOK_COMMA);
9666 } else if (this._lookahead(0) === TOK_RBRACE) {
9667 this._match(TOK_RBRACE);
9668 break;
9669 }
9670 }
9671 return {type: "MultiSelectHash", children: pairs};
9672 }
9673 };
9674
9675
9676 function TreeInterpreter(runtime) {
9677 this.runtime = runtime;
9678 }
9679
9680 TreeInterpreter.prototype = {
9681 search: function(node, value) {
9682 return this.visit(node, value);
9683 },
9684
9685 visit: function(node, value) {
9686 var matched, current, result, first, second, field, left, right, collected, i;
9687 switch (node.type) {
9688 case "Field":
9689 if (value === null ) {
9690 return null;
9691 } else if (isObject(value)) {
9692 field = value[node.name];
9693 if (field === undefined) {
9694 return null;
9695 } else {
9696 return field;
9697 }
9698 } else {
9699 return null;
9700 }
9701 break;
9702 case "Subexpression":
9703 result = this.visit(node.children[0], value);
9704 for (i = 1; i < node.children.length; i++) {
9705 result = this.visit(node.children[1], result);
9706 if (result === null) {
9707 return null;
9708 }
9709 }
9710 return result;
9711 case "IndexExpression":
9712 left = this.visit(node.children[0], value);
9713 right = this.visit(node.children[1], left);
9714 return right;
9715 case "Index":
9716 if (!isArray(value)) {
9717 return null;
9718 }
9719 var index = node.value;
9720 if (index < 0) {
9721 index = value.length + index;
9722 }
9723 result = value[index];
9724 if (result === undefined) {
9725 result = null;
9726 }
9727 return result;
9728 case "Slice":
9729 if (!isArray(value)) {
9730 return null;
9731 }
9732 var sliceParams = node.children.slice(0);
9733 var computed = this.computeSliceParams(value.length, sliceParams);
9734 var start = computed[0];
9735 var stop = computed[1];
9736 var step = computed[2];
9737 result = [];
9738 if (step > 0) {
9739 for (i = start; i < stop; i += step) {
9740 result.push(value[i]);
9741 }
9742 } else {
9743 for (i = start; i > stop; i += step) {
9744 result.push(value[i]);
9745 }
9746 }
9747 return result;
9748 case "Projection":
9749 // Evaluate left child.
9750 var base = this.visit(node.children[0], value);
9751 if (!isArray(base)) {
9752 return null;
9753 }
9754 collected = [];
9755 for (i = 0; i < base.length; i++) {
9756 current = this.visit(node.children[1], base[i]);
9757 if (current !== null) {
9758 collected.push(current);
9759 }
9760 }
9761 return collected;
9762 case "ValueProjection":
9763 // Evaluate left child.
9764 base = this.visit(node.children[0], value);
9765 if (!isObject(base)) {
9766 return null;
9767 }
9768 collected = [];
9769 var values = objValues(base);
9770 for (i = 0; i < values.length; i++) {
9771 current = this.visit(node.children[1], values[i]);
9772 if (current !== null) {
9773 collected.push(current);
9774 }
9775 }
9776 return collected;
9777 case "FilterProjection":
9778 base = this.visit(node.children[0], value);
9779 if (!isArray(base)) {
9780 return null;
9781 }
9782 var filtered = [];
9783 var finalResults = [];
9784 for (i = 0; i < base.length; i++) {
9785 matched = this.visit(node.children[2], base[i]);
9786 if (!isFalse(matched)) {
9787 filtered.push(base[i]);
9788 }
9789 }
9790 for (var j = 0; j < filtered.length; j++) {
9791 current = this.visit(node.children[1], filtered[j]);
9792 if (current !== null) {
9793 finalResults.push(current);
9794 }
9795 }
9796 return finalResults;
9797 case "Comparator":
9798 first = this.visit(node.children[0], value);
9799 second = this.visit(node.children[1], value);
9800 switch(node.name) {
9801 case TOK_EQ:
9802 result = strictDeepEqual(first, second);
9803 break;
9804 case TOK_NE:
9805 result = !strictDeepEqual(first, second);
9806 break;
9807 case TOK_GT:
9808 result = first > second;
9809 break;
9810 case TOK_GTE:
9811 result = first >= second;
9812 break;
9813 case TOK_LT:
9814 result = first < second;
9815 break;
9816 case TOK_LTE:
9817 result = first <= second;
9818 break;
9819 default:
9820 throw new Error("Unknown comparator: " + node.name);
9821 }
9822 return result;
9823 case TOK_FLATTEN:
9824 var original = this.visit(node.children[0], value);
9825 if (!isArray(original)) {
9826 return null;
9827 }
9828 var merged = [];
9829 for (i = 0; i < original.length; i++) {
9830 current = original[i];
9831 if (isArray(current)) {
9832 merged.push.apply(merged, current);
9833 } else {
9834 merged.push(current);
9835 }
9836 }
9837 return merged;
9838 case "Identity":
9839 return value;
9840 case "MultiSelectList":
9841 if (value === null) {
9842 return null;
9843 }
9844 collected = [];
9845 for (i = 0; i < node.children.length; i++) {
9846 collected.push(this.visit(node.children[i], value));
9847 }
9848 return collected;
9849 case "MultiSelectHash":
9850 if (value === null) {
9851 return null;
9852 }
9853 collected = {};
9854 var child;
9855 for (i = 0; i < node.children.length; i++) {
9856 child = node.children[i];
9857 collected[child.name] = this.visit(child.value, value);
9858 }
9859 return collected;
9860 case "OrExpression":
9861 matched = this.visit(node.children[0], value);
9862 if (isFalse(matched)) {
9863 matched = this.visit(node.children[1], value);
9864 }
9865 return matched;
9866 case "AndExpression":
9867 first = this.visit(node.children[0], value);
9868
9869 if (isFalse(first) === true) {
9870 return first;
9871 }
9872 return this.visit(node.children[1], value);
9873 case "NotExpression":
9874 first = this.visit(node.children[0], value);
9875 return isFalse(first);
9876 case "Literal":
9877 return node.value;
9878 case TOK_PIPE:
9879 left = this.visit(node.children[0], value);
9880 return this.visit(node.children[1], left);
9881 case TOK_CURRENT:
9882 return value;
9883 case "Function":
9884 var resolvedArgs = [];
9885 for (i = 0; i < node.children.length; i++) {
9886 resolvedArgs.push(this.visit(node.children[i], value));
9887 }
9888 return this.runtime.callFunction(node.name, resolvedArgs);
9889 case "ExpressionReference":
9890 var refNode = node.children[0];
9891 // Tag the node with a specific attribute so the type
9892 // checker verify the type.
9893 refNode.jmespathType = TOK_EXPREF;
9894 return refNode;
9895 default:
9896 throw new Error("Unknown node type: " + node.type);
9897 }
9898 },
9899
9900 computeSliceParams: function(arrayLength, sliceParams) {
9901 var start = sliceParams[0];
9902 var stop = sliceParams[1];
9903 var step = sliceParams[2];
9904 var computed = [null, null, null];
9905 if (step === null) {
9906 step = 1;
9907 } else if (step === 0) {
9908 var error = new Error("Invalid slice, step cannot be 0");
9909 error.name = "RuntimeError";
9910 throw error;
9911 }
9912 var stepValueNegative = step < 0 ? true : false;
9913
9914 if (start === null) {
9915 start = stepValueNegative ? arrayLength - 1 : 0;
9916 } else {
9917 start = this.capSliceRange(arrayLength, start, step);
9918 }
9919
9920 if (stop === null) {
9921 stop = stepValueNegative ? -1 : arrayLength;
9922 } else {
9923 stop = this.capSliceRange(arrayLength, stop, step);
9924 }
9925 computed[0] = start;
9926 computed[1] = stop;
9927 computed[2] = step;
9928 return computed;
9929 },
9930
9931 capSliceRange: function(arrayLength, actualValue, step) {
9932 if (actualValue < 0) {
9933 actualValue += arrayLength;
9934 if (actualValue < 0) {
9935 actualValue = step < 0 ? -1 : 0;
9936 }
9937 } else if (actualValue >= arrayLength) {
9938 actualValue = step < 0 ? arrayLength - 1 : arrayLength;
9939 }
9940 return actualValue;
9941 }
9942
9943 };
9944
9945 function Runtime(interpreter) {
9946 this._interpreter = interpreter;
9947 this.functionTable = {
9948 // name: [function, <signature>]
9949 // The <signature> can be:
9950 //
9951 // {
9952 // args: [[type1, type2], [type1, type2]],
9953 // variadic: true|false
9954 // }
9955 //
9956 // Each arg in the arg list is a list of valid types
9957 // (if the function is overloaded and supports multiple
9958 // types. If the type is "any" then no type checking
9959 // occurs on the argument. Variadic is optional
9960 // and if not provided is assumed to be false.
9961 abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]},
9962 avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
9963 ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]},
9964 contains: {
9965 _func: this._functionContains,
9966 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]},
9967 {types: [TYPE_ANY]}]},
9968 "ends_with": {
9969 _func: this._functionEndsWith,
9970 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
9971 floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]},
9972 length: {
9973 _func: this._functionLength,
9974 _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]},
9975 map: {
9976 _func: this._functionMap,
9977 _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]},
9978 max: {
9979 _func: this._functionMax,
9980 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
9981 "merge": {
9982 _func: this._functionMerge,
9983 _signature: [{types: [TYPE_OBJECT], variadic: true}]
9984 },
9985 "max_by": {
9986 _func: this._functionMaxBy,
9987 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9988 },
9989 sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
9990 "starts_with": {
9991 _func: this._functionStartsWith,
9992 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
9993 min: {
9994 _func: this._functionMin,
9995 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
9996 "min_by": {
9997 _func: this._functionMinBy,
9998 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9999 },
10000 type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]},
10001 keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]},
10002 values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]},
10003 sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]},
10004 "sort_by": {
10005 _func: this._functionSortBy,
10006 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
10007 },
10008 join: {
10009 _func: this._functionJoin,
10010 _signature: [
10011 {types: [TYPE_STRING]},
10012 {types: [TYPE_ARRAY_STRING]}
10013 ]
10014 },
10015 reverse: {
10016 _func: this._functionReverse,
10017 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]},
10018 "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]},
10019 "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]},
10020 "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]},
10021 "not_null": {
10022 _func: this._functionNotNull,
10023 _signature: [{types: [TYPE_ANY], variadic: true}]
10024 }
10025 };
10026 }
10027
10028 Runtime.prototype = {
10029 callFunction: function(name, resolvedArgs) {
10030 var functionEntry = this.functionTable[name];
10031 if (functionEntry === undefined) {
10032 throw new Error("Unknown function: " + name + "()");
10033 }
10034 this._validateArgs(name, resolvedArgs, functionEntry._signature);
10035 return functionEntry._func.call(this, resolvedArgs);
10036 },
10037
10038 _validateArgs: function(name, args, signature) {
10039 // Validating the args requires validating
10040 // the correct arity and the correct type of each arg.
10041 // If the last argument is declared as variadic, then we need
10042 // a minimum number of args to be required. Otherwise it has to
10043 // be an exact amount.
10044 var pluralized;
10045 if (signature[signature.length - 1].variadic) {
10046 if (args.length < signature.length) {
10047 pluralized = signature.length === 1 ? " argument" : " arguments";
10048 throw new Error("ArgumentError: " + name + "() " +
10049 "takes at least" + signature.length + pluralized +
10050 " but received " + args.length);
10051 }
10052 } else if (args.length !== signature.length) {
10053 pluralized = signature.length === 1 ? " argument" : " arguments";
10054 throw new Error("ArgumentError: " + name + "() " +
10055 "takes " + signature.length + pluralized +
10056 " but received " + args.length);
10057 }
10058 var currentSpec;
10059 var actualType;
10060 var typeMatched;
10061 for (var i = 0; i < signature.length; i++) {
10062 typeMatched = false;
10063 currentSpec = signature[i].types;
10064 actualType = this._getTypeName(args[i]);
10065 for (var j = 0; j < currentSpec.length; j++) {
10066 if (this._typeMatches(actualType, currentSpec[j], args[i])) {
10067 typeMatched = true;
10068 break;
10069 }
10070 }
10071 if (!typeMatched) {
10072 throw new Error("TypeError: " + name + "() " +
10073 "expected argument " + (i + 1) +
10074 " to be type " + currentSpec +
10075 " but received type " + actualType +
10076 " instead.");
10077 }
10078 }
10079 },
10080
10081 _typeMatches: function(actual, expected, argValue) {
10082 if (expected === TYPE_ANY) {
10083 return true;
10084 }
10085 if (expected === TYPE_ARRAY_STRING ||
10086 expected === TYPE_ARRAY_NUMBER ||
10087 expected === TYPE_ARRAY) {
10088 // The expected type can either just be array,
10089 // or it can require a specific subtype (array of numbers).
10090 //
10091 // The simplest case is if "array" with no subtype is specified.
10092 if (expected === TYPE_ARRAY) {
10093 return actual === TYPE_ARRAY;
10094 } else if (actual === TYPE_ARRAY) {
10095 // Otherwise we need to check subtypes.
10096 // I think this has potential to be improved.
10097 var subtype;
10098 if (expected === TYPE_ARRAY_NUMBER) {
10099 subtype = TYPE_NUMBER;
10100 } else if (expected === TYPE_ARRAY_STRING) {
10101 subtype = TYPE_STRING;
10102 }
10103 for (var i = 0; i < argValue.length; i++) {
10104 if (!this._typeMatches(
10105 this._getTypeName(argValue[i]), subtype,
10106 argValue[i])) {
10107 return false;
10108 }
10109 }
10110 return true;
10111 }
10112 } else {
10113 return actual === expected;
10114 }
10115 },
10116 _getTypeName: function(obj) {
10117 switch (Object.prototype.toString.call(obj)) {
10118 case "[object String]":
10119 return TYPE_STRING;
10120 case "[object Number]":
10121 return TYPE_NUMBER;
10122 case "[object Array]":
10123 return TYPE_ARRAY;
10124 case "[object Boolean]":
10125 return TYPE_BOOLEAN;
10126 case "[object Null]":
10127 return TYPE_NULL;
10128 case "[object Object]":
10129 // Check if it's an expref. If it has, it's been
10130 // tagged with a jmespathType attr of 'Expref';
10131 if (obj.jmespathType === TOK_EXPREF) {
10132 return TYPE_EXPREF;
10133 } else {
10134 return TYPE_OBJECT;
10135 }
10136 }
10137 },
10138
10139 _functionStartsWith: function(resolvedArgs) {
10140 return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0;
10141 },
10142
10143 _functionEndsWith: function(resolvedArgs) {
10144 var searchStr = resolvedArgs[0];
10145 var suffix = resolvedArgs[1];
10146 return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1;
10147 },
10148
10149 _functionReverse: function(resolvedArgs) {
10150 var typeName = this._getTypeName(resolvedArgs[0]);
10151 if (typeName === TYPE_STRING) {
10152 var originalStr = resolvedArgs[0];
10153 var reversedStr = "";
10154 for (var i = originalStr.length - 1; i >= 0; i--) {
10155 reversedStr += originalStr[i];
10156 }
10157 return reversedStr;
10158 } else {
10159 var reversedArray = resolvedArgs[0].slice(0);
10160 reversedArray.reverse();
10161 return reversedArray;
10162 }
10163 },
10164
10165 _functionAbs: function(resolvedArgs) {
10166 return Math.abs(resolvedArgs[0]);
10167 },
10168
10169 _functionCeil: function(resolvedArgs) {
10170 return Math.ceil(resolvedArgs[0]);
10171 },
10172
10173 _functionAvg: function(resolvedArgs) {
10174 var sum = 0;
10175 var inputArray = resolvedArgs[0];
10176 for (var i = 0; i < inputArray.length; i++) {
10177 sum += inputArray[i];
10178 }
10179 return sum / inputArray.length;
10180 },
10181
10182 _functionContains: function(resolvedArgs) {
10183 return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0;
10184 },
10185
10186 _functionFloor: function(resolvedArgs) {
10187 return Math.floor(resolvedArgs[0]);
10188 },
10189
10190 _functionLength: function(resolvedArgs) {
10191 if (!isObject(resolvedArgs[0])) {
10192 return resolvedArgs[0].length;
10193 } else {
10194 // As far as I can tell, there's no way to get the length
10195 // of an object without O(n) iteration through the object.
10196 return Object.keys(resolvedArgs[0]).length;
10197 }
10198 },
10199
10200 _functionMap: function(resolvedArgs) {
10201 var mapped = [];
10202 var interpreter = this._interpreter;
10203 var exprefNode = resolvedArgs[0];
10204 var elements = resolvedArgs[1];
10205 for (var i = 0; i < elements.length; i++) {
10206 mapped.push(interpreter.visit(exprefNode, elements[i]));
10207 }
10208 return mapped;
10209 },
10210
10211 _functionMerge: function(resolvedArgs) {
10212 var merged = {};
10213 for (var i = 0; i < resolvedArgs.length; i++) {
10214 var current = resolvedArgs[i];
10215 for (var key in current) {
10216 merged[key] = current[key];
10217 }
10218 }
10219 return merged;
10220 },
10221
10222 _functionMax: function(resolvedArgs) {
10223 if (resolvedArgs[0].length > 0) {
10224 var typeName = this._getTypeName(resolvedArgs[0][0]);
10225 if (typeName === TYPE_NUMBER) {
10226 return Math.max.apply(Math, resolvedArgs[0]);
10227 } else {
10228 var elements = resolvedArgs[0];
10229 var maxElement = elements[0];
10230 for (var i = 1; i < elements.length; i++) {
10231 if (maxElement.localeCompare(elements[i]) < 0) {
10232 maxElement = elements[i];
10233 }
10234 }
10235 return maxElement;
10236 }
10237 } else {
10238 return null;
10239 }
10240 },
10241
10242 _functionMin: function(resolvedArgs) {
10243 if (resolvedArgs[0].length > 0) {
10244 var typeName = this._getTypeName(resolvedArgs[0][0]);
10245 if (typeName === TYPE_NUMBER) {
10246 return Math.min.apply(Math, resolvedArgs[0]);
10247 } else {
10248 var elements = resolvedArgs[0];
10249 var minElement = elements[0];
10250 for (var i = 1; i < elements.length; i++) {
10251 if (elements[i].localeCompare(minElement) < 0) {
10252 minElement = elements[i];
10253 }
10254 }
10255 return minElement;
10256 }
10257 } else {
10258 return null;
10259 }
10260 },
10261
10262 _functionSum: function(resolvedArgs) {
10263 var sum = 0;
10264 var listToSum = resolvedArgs[0];
10265 for (var i = 0; i < listToSum.length; i++) {
10266 sum += listToSum[i];
10267 }
10268 return sum;
10269 },
10270
10271 _functionType: function(resolvedArgs) {
10272 switch (this._getTypeName(resolvedArgs[0])) {
10273 case TYPE_NUMBER:
10274 return "number";
10275 case TYPE_STRING:
10276 return "string";
10277 case TYPE_ARRAY:
10278 return "array";
10279 case TYPE_OBJECT:
10280 return "object";
10281 case TYPE_BOOLEAN:
10282 return "boolean";
10283 case TYPE_EXPREF:
10284 return "expref";
10285 case TYPE_NULL:
10286 return "null";
10287 }
10288 },
10289
10290 _functionKeys: function(resolvedArgs) {
10291 return Object.keys(resolvedArgs[0]);
10292 },
10293
10294 _functionValues: function(resolvedArgs) {
10295 var obj = resolvedArgs[0];
10296 var keys = Object.keys(obj);
10297 var values = [];
10298 for (var i = 0; i < keys.length; i++) {
10299 values.push(obj[keys[i]]);
10300 }
10301 return values;
10302 },
10303
10304 _functionJoin: function(resolvedArgs) {
10305 var joinChar = resolvedArgs[0];
10306 var listJoin = resolvedArgs[1];
10307 return listJoin.join(joinChar);
10308 },
10309
10310 _functionToArray: function(resolvedArgs) {
10311 if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) {
10312 return resolvedArgs[0];
10313 } else {
10314 return [resolvedArgs[0]];
10315 }
10316 },
10317
10318 _functionToString: function(resolvedArgs) {
10319 if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) {
10320 return resolvedArgs[0];
10321 } else {
10322 return JSON.stringify(resolvedArgs[0]);
10323 }
10324 },
10325
10326 _functionToNumber: function(resolvedArgs) {
10327 var typeName = this._getTypeName(resolvedArgs[0]);
10328 var convertedValue;
10329 if (typeName === TYPE_NUMBER) {
10330 return resolvedArgs[0];
10331 } else if (typeName === TYPE_STRING) {
10332 convertedValue = +resolvedArgs[0];
10333 if (!isNaN(convertedValue)) {
10334 return convertedValue;
10335 }
10336 }
10337 return null;
10338 },
10339
10340 _functionNotNull: function(resolvedArgs) {
10341 for (var i = 0; i < resolvedArgs.length; i++) {
10342 if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) {
10343 return resolvedArgs[i];
10344 }
10345 }
10346 return null;
10347 },
10348
10349 _functionSort: function(resolvedArgs) {
10350 var sortedArray = resolvedArgs[0].slice(0);
10351 sortedArray.sort();
10352 return sortedArray;
10353 },
10354
10355 _functionSortBy: function(resolvedArgs) {
10356 var sortedArray = resolvedArgs[0].slice(0);
10357 if (sortedArray.length === 0) {
10358 return sortedArray;
10359 }
10360 var interpreter = this._interpreter;
10361 var exprefNode = resolvedArgs[1];
10362 var requiredType = this._getTypeName(
10363 interpreter.visit(exprefNode, sortedArray[0]));
10364 if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) {
10365 throw new Error("TypeError");
10366 }
10367 var that = this;
10368 // In order to get a stable sort out of an unstable
10369 // sort algorithm, we decorate/sort/undecorate (DSU)
10370 // by creating a new list of [index, element] pairs.
10371 // In the cmp function, if the evaluated elements are
10372 // equal, then the index will be used as the tiebreaker.
10373 // After the decorated list has been sorted, it will be
10374 // undecorated to extract the original elements.
10375 var decorated = [];
10376 for (var i = 0; i < sortedArray.length; i++) {
10377 decorated.push([i, sortedArray[i]]);
10378 }
10379 decorated.sort(function(a, b) {
10380 var exprA = interpreter.visit(exprefNode, a[1]);
10381 var exprB = interpreter.visit(exprefNode, b[1]);
10382 if (that._getTypeName(exprA) !== requiredType) {
10383 throw new Error(
10384 "TypeError: expected " + requiredType + ", received " +
10385 that._getTypeName(exprA));
10386 } else if (that._getTypeName(exprB) !== requiredType) {
10387 throw new Error(
10388 "TypeError: expected " + requiredType + ", received " +
10389 that._getTypeName(exprB));
10390 }
10391 if (exprA > exprB) {
10392 return 1;
10393 } else if (exprA < exprB) {
10394 return -1;
10395 } else {
10396 // If they're equal compare the items by their
10397 // order to maintain relative order of equal keys
10398 // (i.e. to get a stable sort).
10399 return a[0] - b[0];
10400 }
10401 });
10402 // Undecorate: extract out the original list elements.
10403 for (var j = 0; j < decorated.length; j++) {
10404 sortedArray[j] = decorated[j][1];
10405 }
10406 return sortedArray;
10407 },
10408
10409 _functionMaxBy: function(resolvedArgs) {
10410 var exprefNode = resolvedArgs[1];
10411 var resolvedArray = resolvedArgs[0];
10412 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10413 var maxNumber = -Infinity;
10414 var maxRecord;
10415 var current;
10416 for (var i = 0; i < resolvedArray.length; i++) {
10417 current = keyFunction(resolvedArray[i]);
10418 if (current > maxNumber) {
10419 maxNumber = current;
10420 maxRecord = resolvedArray[i];
10421 }
10422 }
10423 return maxRecord;
10424 },
10425
10426 _functionMinBy: function(resolvedArgs) {
10427 var exprefNode = resolvedArgs[1];
10428 var resolvedArray = resolvedArgs[0];
10429 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10430 var minNumber = Infinity;
10431 var minRecord;
10432 var current;
10433 for (var i = 0; i < resolvedArray.length; i++) {
10434 current = keyFunction(resolvedArray[i]);
10435 if (current < minNumber) {
10436 minNumber = current;
10437 minRecord = resolvedArray[i];
10438 }
10439 }
10440 return minRecord;
10441 },
10442
10443 createKeyFunction: function(exprefNode, allowedTypes) {
10444 var that = this;
10445 var interpreter = this._interpreter;
10446 var keyFunc = function(x) {
10447 var current = interpreter.visit(exprefNode, x);
10448 if (allowedTypes.indexOf(that._getTypeName(current)) < 0) {
10449 var msg = "TypeError: expected one of " + allowedTypes +
10450 ", received " + that._getTypeName(current);
10451 throw new Error(msg);
10452 }
10453 return current;
10454 };
10455 return keyFunc;
10456 }
10457
10458 };
10459
10460 function compile(stream) {
10461 var parser = new Parser();
10462 var ast = parser.parse(stream);
10463 return ast;
10464 }
10465
10466 function tokenize(stream) {
10467 var lexer = new Lexer();
10468 return lexer.tokenize(stream);
10469 }
10470
10471 function search(data, expression) {
10472 var parser = new Parser();
10473 // This needs to be improved. Both the interpreter and runtime depend on
10474 // each other. The runtime needs the interpreter to support exprefs.
10475 // There's likely a clean way to avoid the cyclic dependency.
10476 var runtime = new Runtime();
10477 var interpreter = new TreeInterpreter(runtime);
10478 runtime._interpreter = interpreter;
10479 var node = parser.parse(expression);
10480 return interpreter.search(node, data);
10481 }
10482
10483 exports.tokenize = tokenize;
10484 exports.compile = compile;
10485 exports.search = search;
10486 exports.strictDeepEqual = strictDeepEqual;
10487 })( false ? this.jmespath = {} : exports);
10488
10489
10490/***/ }),
10491/* 52 */
10492/***/ (function(module, exports, __webpack_require__) {
10493
10494 var AWS = __webpack_require__(1);
10495 var inherit = AWS.util.inherit;
10496 var jmespath = __webpack_require__(51);
10497
10498 /**
10499 * This class encapsulates the response information
10500 * from a service request operation sent through {AWS.Request}.
10501 * The response object has two main properties for getting information
10502 * back from a request:
10503 *
10504 * ## The `data` property
10505 *
10506 * The `response.data` property contains the serialized object data
10507 * retrieved from the service request. For instance, for an
10508 * Amazon DynamoDB `listTables` method call, the response data might
10509 * look like:
10510 *
10511 * ```
10512 * > resp.data
10513 * { TableNames:
10514 * [ 'table1', 'table2', ... ] }
10515 * ```
10516 *
10517 * The `data` property can be null if an error occurs (see below).
10518 *
10519 * ## The `error` property
10520 *
10521 * In the event of a service error (or transfer error), the
10522 * `response.error` property will be filled with the given
10523 * error data in the form:
10524 *
10525 * ```
10526 * { code: 'SHORT_UNIQUE_ERROR_CODE',
10527 * message: 'Some human readable error message' }
10528 * ```
10529 *
10530 * In the case of an error, the `data` property will be `null`.
10531 * Note that if you handle events that can be in a failure state,
10532 * you should always check whether `response.error` is set
10533 * before attempting to access the `response.data` property.
10534 *
10535 * @!attribute data
10536 * @readonly
10537 * @!group Data Properties
10538 * @note Inside of a {AWS.Request~httpData} event, this
10539 * property contains a single raw packet instead of the
10540 * full de-serialized service response.
10541 * @return [Object] the de-serialized response data
10542 * from the service.
10543 *
10544 * @!attribute error
10545 * An structure containing information about a service
10546 * or networking error.
10547 * @readonly
10548 * @!group Data Properties
10549 * @note This attribute is only filled if a service or
10550 * networking error occurs.
10551 * @return [Error]
10552 * * code [String] a unique short code representing the
10553 * error that was emitted.
10554 * * message [String] a longer human readable error message
10555 * * retryable [Boolean] whether the error message is
10556 * retryable.
10557 * * statusCode [Numeric] in the case of a request that reached the service,
10558 * this value contains the response status code.
10559 * * time [Date] the date time object when the error occurred.
10560 * * hostname [String] set when a networking error occurs to easily
10561 * identify the endpoint of the request.
10562 * * region [String] set when a networking error occurs to easily
10563 * identify the region of the request.
10564 *
10565 * @!attribute requestId
10566 * @readonly
10567 * @!group Data Properties
10568 * @return [String] the unique request ID associated with the response.
10569 * Log this value when debugging requests for AWS support.
10570 *
10571 * @!attribute retryCount
10572 * @readonly
10573 * @!group Operation Properties
10574 * @return [Integer] the number of retries that were
10575 * attempted before the request was completed.
10576 *
10577 * @!attribute redirectCount
10578 * @readonly
10579 * @!group Operation Properties
10580 * @return [Integer] the number of redirects that were
10581 * followed before the request was completed.
10582 *
10583 * @!attribute httpResponse
10584 * @readonly
10585 * @!group HTTP Properties
10586 * @return [AWS.HttpResponse] the raw HTTP response object
10587 * containing the response headers and body information
10588 * from the server.
10589 *
10590 * @see AWS.Request
10591 */
10592 AWS.Response = inherit({
10593
10594 /**
10595 * @api private
10596 */
10597 constructor: function Response(request) {
10598 this.request = request;
10599 this.data = null;
10600 this.error = null;
10601 this.retryCount = 0;
10602 this.redirectCount = 0;
10603 this.httpResponse = new AWS.HttpResponse();
10604 if (request) {
10605 this.maxRetries = request.service.numRetries();
10606 this.maxRedirects = request.service.config.maxRedirects;
10607 }
10608 },
10609
10610 /**
10611 * Creates a new request for the next page of response data, calling the
10612 * callback with the page data if a callback is provided.
10613 *
10614 * @callback callback function(err, data)
10615 * Called when a page of data is returned from the next request.
10616 *
10617 * @param err [Error] an error object, if an error occurred in the request
10618 * @param data [Object] the next page of data, or null, if there are no
10619 * more pages left.
10620 * @return [AWS.Request] the request object for the next page of data
10621 * @return [null] if no callback is provided and there are no pages left
10622 * to retrieve.
10623 * @since v1.4.0
10624 */
10625 nextPage: function nextPage(callback) {
10626 var config;
10627 var service = this.request.service;
10628 var operation = this.request.operation;
10629 try {
10630 config = service.paginationConfig(operation, true);
10631 } catch (e) { this.error = e; }
10632
10633 if (!this.hasNextPage()) {
10634 if (callback) callback(this.error, null);
10635 else if (this.error) throw this.error;
10636 return null;
10637 }
10638
10639 var params = AWS.util.copy(this.request.params);
10640 if (!this.nextPageTokens) {
10641 return callback ? callback(null, null) : null;
10642 } else {
10643 var inputTokens = config.inputToken;
10644 if (typeof inputTokens === 'string') inputTokens = [inputTokens];
10645 for (var i = 0; i < inputTokens.length; i++) {
10646 params[inputTokens[i]] = this.nextPageTokens[i];
10647 }
10648 return service.makeRequest(this.request.operation, params, callback);
10649 }
10650 },
10651
10652 /**
10653 * @return [Boolean] whether more pages of data can be returned by further
10654 * requests
10655 * @since v1.4.0
10656 */
10657 hasNextPage: function hasNextPage() {
10658 this.cacheNextPageTokens();
10659 if (this.nextPageTokens) return true;
10660 if (this.nextPageTokens === undefined) return undefined;
10661 else return false;
10662 },
10663
10664 /**
10665 * @api private
10666 */
10667 cacheNextPageTokens: function cacheNextPageTokens() {
10668 if (Object.prototype.hasOwnProperty.call(this, 'nextPageTokens')) return this.nextPageTokens;
10669 this.nextPageTokens = undefined;
10670
10671 var config = this.request.service.paginationConfig(this.request.operation);
10672 if (!config) return this.nextPageTokens;
10673
10674 this.nextPageTokens = null;
10675 if (config.moreResults) {
10676 if (!jmespath.search(this.data, config.moreResults)) {
10677 return this.nextPageTokens;
10678 }
10679 }
10680
10681 var exprs = config.outputToken;
10682 if (typeof exprs === 'string') exprs = [exprs];
10683 AWS.util.arrayEach.call(this, exprs, function (expr) {
10684 var output = jmespath.search(this.data, expr);
10685 if (output) {
10686 this.nextPageTokens = this.nextPageTokens || [];
10687 this.nextPageTokens.push(output);
10688 }
10689 });
10690
10691 return this.nextPageTokens;
10692 }
10693
10694 });
10695
10696
10697/***/ }),
10698/* 53 */
10699/***/ (function(module, exports, __webpack_require__) {
10700
10701 /**
10702 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
10703 *
10704 * Licensed under the Apache License, Version 2.0 (the "License"). You
10705 * may not use this file except in compliance with the License. A copy of
10706 * the License is located at
10707 *
10708 * http://aws.amazon.com/apache2.0/
10709 *
10710 * or in the "license" file accompanying this file. This file is
10711 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
10712 * ANY KIND, either express or implied. See the License for the specific
10713 * language governing permissions and limitations under the License.
10714 */
10715
10716 var AWS = __webpack_require__(1);
10717 var inherit = AWS.util.inherit;
10718 var jmespath = __webpack_require__(51);
10719
10720 /**
10721 * @api private
10722 */
10723 function CHECK_ACCEPTORS(resp) {
10724 var waiter = resp.request._waiter;
10725 var acceptors = waiter.config.acceptors;
10726 var acceptorMatched = false;
10727 var state = 'retry';
10728
10729 acceptors.forEach(function(acceptor) {
10730 if (!acceptorMatched) {
10731 var matcher = waiter.matchers[acceptor.matcher];
10732 if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) {
10733 acceptorMatched = true;
10734 state = acceptor.state;
10735 }
10736 }
10737 });
10738
10739 if (!acceptorMatched && resp.error) state = 'failure';
10740
10741 if (state === 'success') {
10742 waiter.setSuccess(resp);
10743 } else {
10744 waiter.setError(resp, state === 'retry');
10745 }
10746 }
10747
10748 /**
10749 * @api private
10750 */
10751 AWS.ResourceWaiter = inherit({
10752 /**
10753 * Waits for a given state on a service object
10754 * @param service [Service] the service object to wait on
10755 * @param state [String] the state (defined in waiter configuration) to wait
10756 * for.
10757 * @example Create a waiter for running EC2 instances
10758 * var ec2 = new AWS.EC2;
10759 * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
10760 */
10761 constructor: function constructor(service, state) {
10762 this.service = service;
10763 this.state = state;
10764 this.loadWaiterConfig(this.state);
10765 },
10766
10767 service: null,
10768
10769 state: null,
10770
10771 config: null,
10772
10773 matchers: {
10774 path: function(resp, expected, argument) {
10775 try {
10776 var result = jmespath.search(resp.data, argument);
10777 } catch (err) {
10778 return false;
10779 }
10780
10781 return jmespath.strictDeepEqual(result,expected);
10782 },
10783
10784 pathAll: function(resp, expected, argument) {
10785 try {
10786 var results = jmespath.search(resp.data, argument);
10787 } catch (err) {
10788 return false;
10789 }
10790
10791 if (!Array.isArray(results)) results = [results];
10792 var numResults = results.length;
10793 if (!numResults) return false;
10794 for (var ind = 0 ; ind < numResults; ind++) {
10795 if (!jmespath.strictDeepEqual(results[ind], expected)) {
10796 return false;
10797 }
10798 }
10799 return true;
10800 },
10801
10802 pathAny: function(resp, expected, argument) {
10803 try {
10804 var results = jmespath.search(resp.data, argument);
10805 } catch (err) {
10806 return false;
10807 }
10808
10809 if (!Array.isArray(results)) results = [results];
10810 var numResults = results.length;
10811 for (var ind = 0 ; ind < numResults; ind++) {
10812 if (jmespath.strictDeepEqual(results[ind], expected)) {
10813 return true;
10814 }
10815 }
10816 return false;
10817 },
10818
10819 status: function(resp, expected) {
10820 var statusCode = resp.httpResponse.statusCode;
10821 return (typeof statusCode === 'number') && (statusCode === expected);
10822 },
10823
10824 error: function(resp, expected) {
10825 if (typeof expected === 'string' && resp.error) {
10826 return expected === resp.error.code;
10827 }
10828 // if expected is not string, can be boolean indicating presence of error
10829 return expected === !!resp.error;
10830 }
10831 },
10832
10833 listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) {
10834 add('RETRY_CHECK', 'retry', function(resp) {
10835 var waiter = resp.request._waiter;
10836 if (resp.error && resp.error.code === 'ResourceNotReady') {
10837 resp.error.retryDelay = (waiter.config.delay || 0) * 1000;
10838 }
10839 });
10840
10841 add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS);
10842
10843 add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS);
10844 }),
10845
10846 /**
10847 * @return [AWS.Request]
10848 */
10849 wait: function wait(params, callback) {
10850 if (typeof params === 'function') {
10851 callback = params; params = undefined;
10852 }
10853
10854 if (params && params.$waiter) {
10855 params = AWS.util.copy(params);
10856 if (typeof params.$waiter.delay === 'number') {
10857 this.config.delay = params.$waiter.delay;
10858 }
10859 if (typeof params.$waiter.maxAttempts === 'number') {
10860 this.config.maxAttempts = params.$waiter.maxAttempts;
10861 }
10862 delete params.$waiter;
10863 }
10864
10865 var request = this.service.makeRequest(this.config.operation, params);
10866 request._waiter = this;
10867 request.response.maxRetries = this.config.maxAttempts;
10868 request.addListeners(this.listeners);
10869
10870 if (callback) request.send(callback);
10871 return request;
10872 },
10873
10874 setSuccess: function setSuccess(resp) {
10875 resp.error = null;
10876 resp.data = resp.data || {};
10877 resp.request.removeAllListeners('extractData');
10878 },
10879
10880 setError: function setError(resp, retryable) {
10881 resp.data = null;
10882 resp.error = AWS.util.error(resp.error || new Error(), {
10883 code: 'ResourceNotReady',
10884 message: 'Resource is not in the state ' + this.state,
10885 retryable: retryable
10886 });
10887 },
10888
10889 /**
10890 * Loads waiter configuration from API configuration
10891 *
10892 * @api private
10893 */
10894 loadWaiterConfig: function loadWaiterConfig(state) {
10895 if (!this.service.api.waiters[state]) {
10896 throw new AWS.util.error(new Error(), {
10897 code: 'StateNotFoundError',
10898 message: 'State ' + state + ' not found.'
10899 });
10900 }
10901
10902 this.config = AWS.util.copy(this.service.api.waiters[state]);
10903 }
10904 });
10905
10906
10907/***/ }),
10908/* 54 */
10909/***/ (function(module, exports, __webpack_require__) {
10910
10911 var AWS = __webpack_require__(1);
10912
10913 var inherit = AWS.util.inherit;
10914
10915 /**
10916 * @api private
10917 */
10918 AWS.Signers.RequestSigner = inherit({
10919 constructor: function RequestSigner(request) {
10920 this.request = request;
10921 },
10922
10923 setServiceClientId: function setServiceClientId(id) {
10924 this.serviceClientId = id;
10925 },
10926
10927 getServiceClientId: function getServiceClientId() {
10928 return this.serviceClientId;
10929 }
10930 });
10931
10932 AWS.Signers.RequestSigner.getVersion = function getVersion(version) {
10933 switch (version) {
10934 case 'v2': return AWS.Signers.V2;
10935 case 'v3': return AWS.Signers.V3;
10936 case 's3v4': return AWS.Signers.V4;
10937 case 'v4': return AWS.Signers.V4;
10938 case 's3': return AWS.Signers.S3;
10939 case 'v3https': return AWS.Signers.V3Https;
10940 }
10941 throw new Error('Unknown signing version ' + version);
10942 };
10943
10944 __webpack_require__(55);
10945 __webpack_require__(56);
10946 __webpack_require__(57);
10947 __webpack_require__(58);
10948 __webpack_require__(60);
10949 __webpack_require__(61);
10950
10951
10952/***/ }),
10953/* 55 */
10954/***/ (function(module, exports, __webpack_require__) {
10955
10956 var AWS = __webpack_require__(1);
10957 var inherit = AWS.util.inherit;
10958
10959 /**
10960 * @api private
10961 */
10962 AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, {
10963 addAuthorization: function addAuthorization(credentials, date) {
10964
10965 if (!date) date = AWS.util.date.getDate();
10966
10967 var r = this.request;
10968
10969 r.params.Timestamp = AWS.util.date.iso8601(date);
10970 r.params.SignatureVersion = '2';
10971 r.params.SignatureMethod = 'HmacSHA256';
10972 r.params.AWSAccessKeyId = credentials.accessKeyId;
10973
10974 if (credentials.sessionToken) {
10975 r.params.SecurityToken = credentials.sessionToken;
10976 }
10977
10978 delete r.params.Signature; // delete old Signature for re-signing
10979 r.params.Signature = this.signature(credentials);
10980
10981 r.body = AWS.util.queryParamsToString(r.params);
10982 r.headers['Content-Length'] = r.body.length;
10983 },
10984
10985 signature: function signature(credentials) {
10986 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
10987 },
10988
10989 stringToSign: function stringToSign() {
10990 var parts = [];
10991 parts.push(this.request.method);
10992 parts.push(this.request.endpoint.host.toLowerCase());
10993 parts.push(this.request.pathname());
10994 parts.push(AWS.util.queryParamsToString(this.request.params));
10995 return parts.join('\n');
10996 }
10997
10998 });
10999
11000 /**
11001 * @api private
11002 */
11003 module.exports = AWS.Signers.V2;
11004
11005
11006/***/ }),
11007/* 56 */
11008/***/ (function(module, exports, __webpack_require__) {
11009
11010 var AWS = __webpack_require__(1);
11011 var inherit = AWS.util.inherit;
11012
11013 /**
11014 * @api private
11015 */
11016 AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, {
11017 addAuthorization: function addAuthorization(credentials, date) {
11018
11019 var datetime = AWS.util.date.rfc822(date);
11020
11021 this.request.headers['X-Amz-Date'] = datetime;
11022
11023 if (credentials.sessionToken) {
11024 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11025 }
11026
11027 this.request.headers['X-Amzn-Authorization'] =
11028 this.authorization(credentials, datetime);
11029
11030 },
11031
11032 authorization: function authorization(credentials) {
11033 return 'AWS3 ' +
11034 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
11035 'Algorithm=HmacSHA256,' +
11036 'SignedHeaders=' + this.signedHeaders() + ',' +
11037 'Signature=' + this.signature(credentials);
11038 },
11039
11040 signedHeaders: function signedHeaders() {
11041 var headers = [];
11042 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
11043 headers.push(h.toLowerCase());
11044 });
11045 return headers.sort().join(';');
11046 },
11047
11048 canonicalHeaders: function canonicalHeaders() {
11049 var headers = this.request.headers;
11050 var parts = [];
11051 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
11052 parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim());
11053 });
11054 return parts.sort().join('\n') + '\n';
11055 },
11056
11057 headersToSign: function headersToSign() {
11058 var headers = [];
11059 AWS.util.each(this.request.headers, function iterator(k) {
11060 if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) {
11061 headers.push(k);
11062 }
11063 });
11064 return headers;
11065 },
11066
11067 signature: function signature(credentials) {
11068 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
11069 },
11070
11071 stringToSign: function stringToSign() {
11072 var parts = [];
11073 parts.push(this.request.method);
11074 parts.push('/');
11075 parts.push('');
11076 parts.push(this.canonicalHeaders());
11077 parts.push(this.request.body);
11078 return AWS.util.crypto.sha256(parts.join('\n'));
11079 }
11080
11081 });
11082
11083 /**
11084 * @api private
11085 */
11086 module.exports = AWS.Signers.V3;
11087
11088
11089/***/ }),
11090/* 57 */
11091/***/ (function(module, exports, __webpack_require__) {
11092
11093 var AWS = __webpack_require__(1);
11094 var inherit = AWS.util.inherit;
11095
11096 __webpack_require__(56);
11097
11098 /**
11099 * @api private
11100 */
11101 AWS.Signers.V3Https = inherit(AWS.Signers.V3, {
11102 authorization: function authorization(credentials) {
11103 return 'AWS3-HTTPS ' +
11104 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
11105 'Algorithm=HmacSHA256,' +
11106 'Signature=' + this.signature(credentials);
11107 },
11108
11109 stringToSign: function stringToSign() {
11110 return this.request.headers['X-Amz-Date'];
11111 }
11112 });
11113
11114 /**
11115 * @api private
11116 */
11117 module.exports = AWS.Signers.V3Https;
11118
11119
11120/***/ }),
11121/* 58 */
11122/***/ (function(module, exports, __webpack_require__) {
11123
11124 var AWS = __webpack_require__(1);
11125 var v4Credentials = __webpack_require__(59);
11126 var inherit = AWS.util.inherit;
11127
11128 /**
11129 * @api private
11130 */
11131 var expiresHeader = 'presigned-expires';
11132
11133 /**
11134 * @api private
11135 */
11136 AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, {
11137 constructor: function V4(request, serviceName, options) {
11138 AWS.Signers.RequestSigner.call(this, request);
11139 this.serviceName = serviceName;
11140 options = options || {};
11141 this.signatureCache = typeof options.signatureCache === 'boolean' ? options.signatureCache : true;
11142 this.operation = options.operation;
11143 this.signatureVersion = options.signatureVersion;
11144 },
11145
11146 algorithm: 'AWS4-HMAC-SHA256',
11147
11148 addAuthorization: function addAuthorization(credentials, date) {
11149 var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '');
11150
11151 if (this.isPresigned()) {
11152 this.updateForPresigned(credentials, datetime);
11153 } else {
11154 this.addHeaders(credentials, datetime);
11155 }
11156
11157 this.request.headers['Authorization'] =
11158 this.authorization(credentials, datetime);
11159 },
11160
11161 addHeaders: function addHeaders(credentials, datetime) {
11162 this.request.headers['X-Amz-Date'] = datetime;
11163 if (credentials.sessionToken) {
11164 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11165 }
11166 },
11167
11168 updateForPresigned: function updateForPresigned(credentials, datetime) {
11169 var credString = this.credentialString(datetime);
11170 var qs = {
11171 'X-Amz-Date': datetime,
11172 'X-Amz-Algorithm': this.algorithm,
11173 'X-Amz-Credential': credentials.accessKeyId + '/' + credString,
11174 'X-Amz-Expires': this.request.headers[expiresHeader],
11175 'X-Amz-SignedHeaders': this.signedHeaders()
11176 };
11177
11178 if (credentials.sessionToken) {
11179 qs['X-Amz-Security-Token'] = credentials.sessionToken;
11180 }
11181
11182 if (this.request.headers['Content-Type']) {
11183 qs['Content-Type'] = this.request.headers['Content-Type'];
11184 }
11185 if (this.request.headers['Content-MD5']) {
11186 qs['Content-MD5'] = this.request.headers['Content-MD5'];
11187 }
11188 if (this.request.headers['Cache-Control']) {
11189 qs['Cache-Control'] = this.request.headers['Cache-Control'];
11190 }
11191
11192 // need to pull in any other X-Amz-* headers
11193 AWS.util.each.call(this, this.request.headers, function(key, value) {
11194 if (key === expiresHeader) return;
11195 if (this.isSignableHeader(key)) {
11196 var lowerKey = key.toLowerCase();
11197 // Metadata should be normalized
11198 if (lowerKey.indexOf('x-amz-meta-') === 0) {
11199 qs[lowerKey] = value;
11200 } else if (lowerKey.indexOf('x-amz-') === 0) {
11201 qs[key] = value;
11202 }
11203 }
11204 });
11205
11206 var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?';
11207 this.request.path += sep + AWS.util.queryParamsToString(qs);
11208 },
11209
11210 authorization: function authorization(credentials, datetime) {
11211 var parts = [];
11212 var credString = this.credentialString(datetime);
11213 parts.push(this.algorithm + ' Credential=' +
11214 credentials.accessKeyId + '/' + credString);
11215 parts.push('SignedHeaders=' + this.signedHeaders());
11216 parts.push('Signature=' + this.signature(credentials, datetime));
11217 return parts.join(', ');
11218 },
11219
11220 signature: function signature(credentials, datetime) {
11221 var signingKey = v4Credentials.getSigningKey(
11222 credentials,
11223 datetime.substr(0, 8),
11224 this.request.region,
11225 this.serviceName,
11226 this.signatureCache
11227 );
11228 return AWS.util.crypto.hmac(signingKey, this.stringToSign(datetime), 'hex');
11229 },
11230
11231 stringToSign: function stringToSign(datetime) {
11232 var parts = [];
11233 parts.push('AWS4-HMAC-SHA256');
11234 parts.push(datetime);
11235 parts.push(this.credentialString(datetime));
11236 parts.push(this.hexEncodedHash(this.canonicalString()));
11237 return parts.join('\n');
11238 },
11239
11240 canonicalString: function canonicalString() {
11241 var parts = [], pathname = this.request.pathname();
11242 if (this.serviceName !== 's3' && this.signatureVersion !== 's3v4') pathname = AWS.util.uriEscapePath(pathname);
11243
11244 parts.push(this.request.method);
11245 parts.push(pathname);
11246 parts.push(this.request.search());
11247 parts.push(this.canonicalHeaders() + '\n');
11248 parts.push(this.signedHeaders());
11249 parts.push(this.hexEncodedBodyHash());
11250 return parts.join('\n');
11251 },
11252
11253 canonicalHeaders: function canonicalHeaders() {
11254 var headers = [];
11255 AWS.util.each.call(this, this.request.headers, function (key, item) {
11256 headers.push([key, item]);
11257 });
11258 headers.sort(function (a, b) {
11259 return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
11260 });
11261 var parts = [];
11262 AWS.util.arrayEach.call(this, headers, function (item) {
11263 var key = item[0].toLowerCase();
11264 if (this.isSignableHeader(key)) {
11265 var value = item[1];
11266 if (typeof value === 'undefined' || value === null || typeof value.toString !== 'function') {
11267 throw AWS.util.error(new Error('Header ' + key + ' contains invalid value'), {
11268 code: 'InvalidHeader'
11269 });
11270 }
11271 parts.push(key + ':' +
11272 this.canonicalHeaderValues(value.toString()));
11273 }
11274 });
11275 return parts.join('\n');
11276 },
11277
11278 canonicalHeaderValues: function canonicalHeaderValues(values) {
11279 return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
11280 },
11281
11282 signedHeaders: function signedHeaders() {
11283 var keys = [];
11284 AWS.util.each.call(this, this.request.headers, function (key) {
11285 key = key.toLowerCase();
11286 if (this.isSignableHeader(key)) keys.push(key);
11287 });
11288 return keys.sort().join(';');
11289 },
11290
11291 credentialString: function credentialString(datetime) {
11292 return v4Credentials.createScope(
11293 datetime.substr(0, 8),
11294 this.request.region,
11295 this.serviceName
11296 );
11297 },
11298
11299 hexEncodedHash: function hash(string) {
11300 return AWS.util.crypto.sha256(string, 'hex');
11301 },
11302
11303 hexEncodedBodyHash: function hexEncodedBodyHash() {
11304 var request = this.request;
11305 if (this.isPresigned() && this.serviceName === 's3' && !request.body) {
11306 return 'UNSIGNED-PAYLOAD';
11307 } else if (request.headers['X-Amz-Content-Sha256']) {
11308 return request.headers['X-Amz-Content-Sha256'];
11309 } else {
11310 return this.hexEncodedHash(this.request.body || '');
11311 }
11312 },
11313
11314 unsignableHeaders: [
11315 'authorization',
11316 'content-type',
11317 'content-length',
11318 'user-agent',
11319 expiresHeader,
11320 'expect',
11321 'x-amzn-trace-id'
11322 ],
11323
11324 isSignableHeader: function isSignableHeader(key) {
11325 if (key.toLowerCase().indexOf('x-amz-') === 0) return true;
11326 return this.unsignableHeaders.indexOf(key) < 0;
11327 },
11328
11329 isPresigned: function isPresigned() {
11330 return this.request.headers[expiresHeader] ? true : false;
11331 }
11332
11333 });
11334
11335 /**
11336 * @api private
11337 */
11338 module.exports = AWS.Signers.V4;
11339
11340
11341/***/ }),
11342/* 59 */
11343/***/ (function(module, exports, __webpack_require__) {
11344
11345 var AWS = __webpack_require__(1);
11346
11347 /**
11348 * @api private
11349 */
11350 var cachedSecret = {};
11351
11352 /**
11353 * @api private
11354 */
11355 var cacheQueue = [];
11356
11357 /**
11358 * @api private
11359 */
11360 var maxCacheEntries = 50;
11361
11362 /**
11363 * @api private
11364 */
11365 var v4Identifier = 'aws4_request';
11366
11367 /**
11368 * @api private
11369 */
11370 module.exports = {
11371 /**
11372 * @api private
11373 *
11374 * @param date [String]
11375 * @param region [String]
11376 * @param serviceName [String]
11377 * @return [String]
11378 */
11379 createScope: function createScope(date, region, serviceName) {
11380 return [
11381 date.substr(0, 8),
11382 region,
11383 serviceName,
11384 v4Identifier
11385 ].join('/');
11386 },
11387
11388 /**
11389 * @api private
11390 *
11391 * @param credentials [Credentials]
11392 * @param date [String]
11393 * @param region [String]
11394 * @param service [String]
11395 * @param shouldCache [Boolean]
11396 * @return [String]
11397 */
11398 getSigningKey: function getSigningKey(
11399 credentials,
11400 date,
11401 region,
11402 service,
11403 shouldCache
11404 ) {
11405 var credsIdentifier = AWS.util.crypto
11406 .hmac(credentials.secretAccessKey, credentials.accessKeyId, 'base64');
11407 var cacheKey = [credsIdentifier, date, region, service].join('_');
11408 shouldCache = shouldCache !== false;
11409 if (shouldCache && (cacheKey in cachedSecret)) {
11410 return cachedSecret[cacheKey];
11411 }
11412
11413 var kDate = AWS.util.crypto.hmac(
11414 'AWS4' + credentials.secretAccessKey,
11415 date,
11416 'buffer'
11417 );
11418 var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer');
11419 var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer');
11420
11421 var signingKey = AWS.util.crypto.hmac(kService, v4Identifier, 'buffer');
11422 if (shouldCache) {
11423 cachedSecret[cacheKey] = signingKey;
11424 cacheQueue.push(cacheKey);
11425 if (cacheQueue.length > maxCacheEntries) {
11426 // remove the oldest entry (not the least recently used)
11427 delete cachedSecret[cacheQueue.shift()];
11428 }
11429 }
11430
11431 return signingKey;
11432 },
11433
11434 /**
11435 * @api private
11436 *
11437 * Empties the derived signing key cache. Made available for testing purposes
11438 * only.
11439 */
11440 emptyCache: function emptyCache() {
11441 cachedSecret = {};
11442 cacheQueue = [];
11443 }
11444 };
11445
11446
11447/***/ }),
11448/* 60 */
11449/***/ (function(module, exports, __webpack_require__) {
11450
11451 var AWS = __webpack_require__(1);
11452 var inherit = AWS.util.inherit;
11453
11454 /**
11455 * @api private
11456 */
11457 AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, {
11458 /**
11459 * When building the stringToSign, these sub resource params should be
11460 * part of the canonical resource string with their NON-decoded values
11461 */
11462 subResources: {
11463 'acl': 1,
11464 'accelerate': 1,
11465 'analytics': 1,
11466 'cors': 1,
11467 'lifecycle': 1,
11468 'delete': 1,
11469 'inventory': 1,
11470 'location': 1,
11471 'logging': 1,
11472 'metrics': 1,
11473 'notification': 1,
11474 'partNumber': 1,
11475 'policy': 1,
11476 'requestPayment': 1,
11477 'replication': 1,
11478 'restore': 1,
11479 'tagging': 1,
11480 'torrent': 1,
11481 'uploadId': 1,
11482 'uploads': 1,
11483 'versionId': 1,
11484 'versioning': 1,
11485 'versions': 1,
11486 'website': 1
11487 },
11488
11489 // when building the stringToSign, these querystring params should be
11490 // part of the canonical resource string with their NON-encoded values
11491 responseHeaders: {
11492 'response-content-type': 1,
11493 'response-content-language': 1,
11494 'response-expires': 1,
11495 'response-cache-control': 1,
11496 'response-content-disposition': 1,
11497 'response-content-encoding': 1
11498 },
11499
11500 addAuthorization: function addAuthorization(credentials, date) {
11501 if (!this.request.headers['presigned-expires']) {
11502 this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date);
11503 }
11504
11505 if (credentials.sessionToken) {
11506 // presigned URLs require this header to be lowercased
11507 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11508 }
11509
11510 var signature = this.sign(credentials.secretAccessKey, this.stringToSign());
11511 var auth = 'AWS ' + credentials.accessKeyId + ':' + signature;
11512
11513 this.request.headers['Authorization'] = auth;
11514 },
11515
11516 stringToSign: function stringToSign() {
11517 var r = this.request;
11518
11519 var parts = [];
11520 parts.push(r.method);
11521 parts.push(r.headers['Content-MD5'] || '');
11522 parts.push(r.headers['Content-Type'] || '');
11523
11524 // This is the "Date" header, but we use X-Amz-Date.
11525 // The S3 signing mechanism requires us to pass an empty
11526 // string for this Date header regardless.
11527 parts.push(r.headers['presigned-expires'] || '');
11528
11529 var headers = this.canonicalizedAmzHeaders();
11530 if (headers) parts.push(headers);
11531 parts.push(this.canonicalizedResource());
11532
11533 return parts.join('\n');
11534
11535 },
11536
11537 canonicalizedAmzHeaders: function canonicalizedAmzHeaders() {
11538
11539 var amzHeaders = [];
11540
11541 AWS.util.each(this.request.headers, function (name) {
11542 if (name.match(/^x-amz-/i))
11543 amzHeaders.push(name);
11544 });
11545
11546 amzHeaders.sort(function (a, b) {
11547 return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
11548 });
11549
11550 var parts = [];
11551 AWS.util.arrayEach.call(this, amzHeaders, function (name) {
11552 parts.push(name.toLowerCase() + ':' + String(this.request.headers[name]));
11553 });
11554
11555 return parts.join('\n');
11556
11557 },
11558
11559 canonicalizedResource: function canonicalizedResource() {
11560
11561 var r = this.request;
11562
11563 var parts = r.path.split('?');
11564 var path = parts[0];
11565 var querystring = parts[1];
11566
11567 var resource = '';
11568
11569 if (r.virtualHostedBucket)
11570 resource += '/' + r.virtualHostedBucket;
11571
11572 resource += path;
11573
11574 if (querystring) {
11575
11576 // collect a list of sub resources and query params that need to be signed
11577 var resources = [];
11578
11579 AWS.util.arrayEach.call(this, querystring.split('&'), function (param) {
11580 var name = param.split('=')[0];
11581 var value = param.split('=')[1];
11582 if (this.subResources[name] || this.responseHeaders[name]) {
11583 var subresource = { name: name };
11584 if (value !== undefined) {
11585 if (this.subResources[name]) {
11586 subresource.value = value;
11587 } else {
11588 subresource.value = decodeURIComponent(value);
11589 }
11590 }
11591 resources.push(subresource);
11592 }
11593 });
11594
11595 resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; });
11596
11597 if (resources.length) {
11598
11599 querystring = [];
11600 AWS.util.arrayEach(resources, function (res) {
11601 if (res.value === undefined) {
11602 querystring.push(res.name);
11603 } else {
11604 querystring.push(res.name + '=' + res.value);
11605 }
11606 });
11607
11608 resource += '?' + querystring.join('&');
11609 }
11610
11611 }
11612
11613 return resource;
11614
11615 },
11616
11617 sign: function sign(secret, string) {
11618 return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1');
11619 }
11620 });
11621
11622 /**
11623 * @api private
11624 */
11625 module.exports = AWS.Signers.S3;
11626
11627
11628/***/ }),
11629/* 61 */
11630/***/ (function(module, exports, __webpack_require__) {
11631
11632 var AWS = __webpack_require__(1);
11633 var inherit = AWS.util.inherit;
11634
11635 /**
11636 * @api private
11637 */
11638 var expiresHeader = 'presigned-expires';
11639
11640 /**
11641 * @api private
11642 */
11643 function signedUrlBuilder(request) {
11644 var expires = request.httpRequest.headers[expiresHeader];
11645 var signerClass = request.service.getSignerClass(request);
11646
11647 delete request.httpRequest.headers['User-Agent'];
11648 delete request.httpRequest.headers['X-Amz-User-Agent'];
11649
11650 if (signerClass === AWS.Signers.V4) {
11651 if (expires > 604800) { // one week expiry is invalid
11652 var message = 'Presigning does not support expiry time greater ' +
11653 'than a week with SigV4 signing.';
11654 throw AWS.util.error(new Error(), {
11655 code: 'InvalidExpiryTime', message: message, retryable: false
11656 });
11657 }
11658 request.httpRequest.headers[expiresHeader] = expires;
11659 } else if (signerClass === AWS.Signers.S3) {
11660 var now = request.service ? request.service.getSkewCorrectedDate() : AWS.util.date.getDate();
11661 request.httpRequest.headers[expiresHeader] = parseInt(
11662 AWS.util.date.unixTimestamp(now) + expires, 10).toString();
11663 } else {
11664 throw AWS.util.error(new Error(), {
11665 message: 'Presigning only supports S3 or SigV4 signing.',
11666 code: 'UnsupportedSigner', retryable: false
11667 });
11668 }
11669 }
11670
11671 /**
11672 * @api private
11673 */
11674 function signedUrlSigner(request) {
11675 var endpoint = request.httpRequest.endpoint;
11676 var parsedUrl = AWS.util.urlParse(request.httpRequest.path);
11677 var queryParams = {};
11678
11679 if (parsedUrl.search) {
11680 queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1));
11681 }
11682
11683 var auth = request.httpRequest.headers['Authorization'].split(' ');
11684 if (auth[0] === 'AWS') {
11685 auth = auth[1].split(':');
11686 queryParams['AWSAccessKeyId'] = auth[0];
11687 queryParams['Signature'] = auth[1];
11688
11689 AWS.util.each(request.httpRequest.headers, function (key, value) {
11690 if (key === expiresHeader) key = 'Expires';
11691 if (key.indexOf('x-amz-meta-') === 0) {
11692 // Delete existing, potentially not normalized key
11693 delete queryParams[key];
11694 key = key.toLowerCase();
11695 }
11696 queryParams[key] = value;
11697 });
11698 delete request.httpRequest.headers[expiresHeader];
11699 delete queryParams['Authorization'];
11700 delete queryParams['Host'];
11701 } else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing
11702 auth.shift();
11703 var rest = auth.join(' ');
11704 var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];
11705 queryParams['X-Amz-Signature'] = signature;
11706 delete queryParams['Expires'];
11707 }
11708
11709 // build URL
11710 endpoint.pathname = parsedUrl.pathname;
11711 endpoint.search = AWS.util.queryParamsToString(queryParams);
11712 }
11713
11714 /**
11715 * @api private
11716 */
11717 AWS.Signers.Presign = inherit({
11718 /**
11719 * @api private
11720 */
11721 sign: function sign(request, expireTime, callback) {
11722 request.httpRequest.headers[expiresHeader] = expireTime || 3600;
11723 request.on('build', signedUrlBuilder);
11724 request.on('sign', signedUrlSigner);
11725 request.removeListener('afterBuild',
11726 AWS.EventListeners.Core.SET_CONTENT_LENGTH);
11727 request.removeListener('afterBuild',
11728 AWS.EventListeners.Core.COMPUTE_SHA256);
11729
11730 request.emit('beforePresign', [request]);
11731
11732 if (callback) {
11733 request.build(function() {
11734 if (this.response.error) callback(this.response.error);
11735 else {
11736 callback(null, AWS.util.urlFormat(request.httpRequest.endpoint));
11737 }
11738 });
11739 } else {
11740 request.build();
11741 if (request.response.error) throw request.response.error;
11742 return AWS.util.urlFormat(request.httpRequest.endpoint);
11743 }
11744 }
11745 });
11746
11747 /**
11748 * @api private
11749 */
11750 module.exports = AWS.Signers.Presign;
11751
11752
11753/***/ }),
11754/* 62 */
11755/***/ (function(module, exports, __webpack_require__) {
11756
11757 var AWS = __webpack_require__(1);
11758
11759 /**
11760 * @api private
11761 */
11762 AWS.ParamValidator = AWS.util.inherit({
11763 /**
11764 * Create a new validator object.
11765 *
11766 * @param validation [Boolean|map] whether input parameters should be
11767 * validated against the operation description before sending the
11768 * request. Pass a map to enable any of the following specific
11769 * validation features:
11770 *
11771 * * **min** [Boolean] &mdash; Validates that a value meets the min
11772 * constraint. This is enabled by default when paramValidation is set
11773 * to `true`.
11774 * * **max** [Boolean] &mdash; Validates that a value meets the max
11775 * constraint.
11776 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
11777 * regular expression.
11778 * * **enum** [Boolean] &mdash; Validates that a string value matches one
11779 * of the allowable enum values.
11780 */
11781 constructor: function ParamValidator(validation) {
11782 if (validation === true || validation === undefined) {
11783 validation = {'min': true};
11784 }
11785 this.validation = validation;
11786 },
11787
11788 validate: function validate(shape, params, context) {
11789 this.errors = [];
11790 this.validateMember(shape, params || {}, context || 'params');
11791
11792 if (this.errors.length > 1) {
11793 var msg = this.errors.join('\n* ');
11794 msg = 'There were ' + this.errors.length +
11795 ' validation errors:\n* ' + msg;
11796 throw AWS.util.error(new Error(msg),
11797 {code: 'MultipleValidationErrors', errors: this.errors});
11798 } else if (this.errors.length === 1) {
11799 throw this.errors[0];
11800 } else {
11801 return true;
11802 }
11803 },
11804
11805 fail: function fail(code, message) {
11806 this.errors.push(AWS.util.error(new Error(message), {code: code}));
11807 },
11808
11809 validateStructure: function validateStructure(shape, params, context) {
11810 this.validateType(params, context, ['object'], 'structure');
11811
11812 var paramName;
11813 for (var i = 0; shape.required && i < shape.required.length; i++) {
11814 paramName = shape.required[i];
11815 var value = params[paramName];
11816 if (value === undefined || value === null) {
11817 this.fail('MissingRequiredParameter',
11818 'Missing required key \'' + paramName + '\' in ' + context);
11819 }
11820 }
11821
11822 // validate hash members
11823 for (paramName in params) {
11824 if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue;
11825
11826 var paramValue = params[paramName],
11827 memberShape = shape.members[paramName];
11828
11829 if (memberShape !== undefined) {
11830 var memberContext = [context, paramName].join('.');
11831 this.validateMember(memberShape, paramValue, memberContext);
11832 } else {
11833 this.fail('UnexpectedParameter',
11834 'Unexpected key \'' + paramName + '\' found in ' + context);
11835 }
11836 }
11837
11838 return true;
11839 },
11840
11841 validateMember: function validateMember(shape, param, context) {
11842 switch (shape.type) {
11843 case 'structure':
11844 return this.validateStructure(shape, param, context);
11845 case 'list':
11846 return this.validateList(shape, param, context);
11847 case 'map':
11848 return this.validateMap(shape, param, context);
11849 default:
11850 return this.validateScalar(shape, param, context);
11851 }
11852 },
11853
11854 validateList: function validateList(shape, params, context) {
11855 if (this.validateType(params, context, [Array])) {
11856 this.validateRange(shape, params.length, context, 'list member count');
11857 // validate array members
11858 for (var i = 0; i < params.length; i++) {
11859 this.validateMember(shape.member, params[i], context + '[' + i + ']');
11860 }
11861 }
11862 },
11863
11864 validateMap: function validateMap(shape, params, context) {
11865 if (this.validateType(params, context, ['object'], 'map')) {
11866 // Build up a count of map members to validate range traits.
11867 var mapCount = 0;
11868 for (var param in params) {
11869 if (!Object.prototype.hasOwnProperty.call(params, param)) continue;
11870 // Validate any map key trait constraints
11871 this.validateMember(shape.key, param,
11872 context + '[key=\'' + param + '\']');
11873 this.validateMember(shape.value, params[param],
11874 context + '[\'' + param + '\']');
11875 mapCount++;
11876 }
11877 this.validateRange(shape, mapCount, context, 'map member count');
11878 }
11879 },
11880
11881 validateScalar: function validateScalar(shape, value, context) {
11882 switch (shape.type) {
11883 case null:
11884 case undefined:
11885 case 'string':
11886 return this.validateString(shape, value, context);
11887 case 'base64':
11888 case 'binary':
11889 return this.validatePayload(value, context);
11890 case 'integer':
11891 case 'float':
11892 return this.validateNumber(shape, value, context);
11893 case 'boolean':
11894 return this.validateType(value, context, ['boolean']);
11895 case 'timestamp':
11896 return this.validateType(value, context, [Date,
11897 /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'],
11898 'Date object, ISO-8601 string, or a UNIX timestamp');
11899 default:
11900 return this.fail('UnkownType', 'Unhandled type ' +
11901 shape.type + ' for ' + context);
11902 }
11903 },
11904
11905 validateString: function validateString(shape, value, context) {
11906 var validTypes = ['string'];
11907 if (shape.isJsonValue) {
11908 validTypes = validTypes.concat(['number', 'object', 'boolean']);
11909 }
11910 if (value !== null && this.validateType(value, context, validTypes)) {
11911 this.validateEnum(shape, value, context);
11912 this.validateRange(shape, value.length, context, 'string length');
11913 this.validatePattern(shape, value, context);
11914 this.validateUri(shape, value, context);
11915 }
11916 },
11917
11918 validateUri: function validateUri(shape, value, context) {
11919 if (shape['location'] === 'uri') {
11920 if (value.length === 0) {
11921 this.fail('UriParameterError', 'Expected uri parameter to have length >= 1,'
11922 + ' but found "' + value +'" for ' + context);
11923 }
11924 }
11925 },
11926
11927 validatePattern: function validatePattern(shape, value, context) {
11928 if (this.validation['pattern'] && shape['pattern'] !== undefined) {
11929 if (!(new RegExp(shape['pattern'])).test(value)) {
11930 this.fail('PatternMatchError', 'Provided value "' + value + '" '
11931 + 'does not match regex pattern /' + shape['pattern'] + '/ for '
11932 + context);
11933 }
11934 }
11935 },
11936
11937 validateRange: function validateRange(shape, value, context, descriptor) {
11938 if (this.validation['min']) {
11939 if (shape['min'] !== undefined && value < shape['min']) {
11940 this.fail('MinRangeError', 'Expected ' + descriptor + ' >= '
11941 + shape['min'] + ', but found ' + value + ' for ' + context);
11942 }
11943 }
11944 if (this.validation['max']) {
11945 if (shape['max'] !== undefined && value > shape['max']) {
11946 this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= '
11947 + shape['max'] + ', but found ' + value + ' for ' + context);
11948 }
11949 }
11950 },
11951
11952 validateEnum: function validateRange(shape, value, context) {
11953 if (this.validation['enum'] && shape['enum'] !== undefined) {
11954 // Fail if the string value is not present in the enum list
11955 if (shape['enum'].indexOf(value) === -1) {
11956 this.fail('EnumError', 'Found string value of ' + value + ', but '
11957 + 'expected ' + shape['enum'].join('|') + ' for ' + context);
11958 }
11959 }
11960 },
11961
11962 validateType: function validateType(value, context, acceptedTypes, type) {
11963 // We will not log an error for null or undefined, but we will return
11964 // false so that callers know that the expected type was not strictly met.
11965 if (value === null || value === undefined) return false;
11966
11967 var foundInvalidType = false;
11968 for (var i = 0; i < acceptedTypes.length; i++) {
11969 if (typeof acceptedTypes[i] === 'string') {
11970 if (typeof value === acceptedTypes[i]) return true;
11971 } else if (acceptedTypes[i] instanceof RegExp) {
11972 if ((value || '').toString().match(acceptedTypes[i])) return true;
11973 } else {
11974 if (value instanceof acceptedTypes[i]) return true;
11975 if (AWS.util.isType(value, acceptedTypes[i])) return true;
11976 if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice();
11977 acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]);
11978 }
11979 foundInvalidType = true;
11980 }
11981
11982 var acceptedType = type;
11983 if (!acceptedType) {
11984 acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1');
11985 }
11986
11987 var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : '';
11988 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' +
11989 vowel + ' ' + acceptedType);
11990 return false;
11991 },
11992
11993 validateNumber: function validateNumber(shape, value, context) {
11994 if (value === null || value === undefined) return;
11995 if (typeof value === 'string') {
11996 var castedValue = parseFloat(value);
11997 if (castedValue.toString() === value) value = castedValue;
11998 }
11999 if (this.validateType(value, context, ['number'])) {
12000 this.validateRange(shape, value, context, 'numeric value');
12001 }
12002 },
12003
12004 validatePayload: function validatePayload(value, context) {
12005 if (value === null || value === undefined) return;
12006 if (typeof value === 'string') return;
12007 if (value && typeof value.byteLength === 'number') return; // typed arrays
12008 if (AWS.util.isNode()) { // special check for buffer/stream in Node.js
12009 var Stream = AWS.util.stream.Stream;
12010 if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return;
12011 } else {
12012 if (typeof Blob !== void 0 && value instanceof Blob) return;
12013 }
12014
12015 var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView'];
12016 if (value) {
12017 for (var i = 0; i < types.length; i++) {
12018 if (AWS.util.isType(value, types[i])) return;
12019 if (AWS.util.typeName(value.constructor) === types[i]) return;
12020 }
12021 }
12022
12023 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' +
12024 'string, Buffer, Stream, Blob, or typed array object');
12025 }
12026 });
12027
12028
12029/***/ })
12030/******/ ])
12031});
12032;
\No newline at end of file