UNPKG

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