UNPKG

401 kBJavaScriptView Raw
1(function webpackUniversalModuleDefinition(root, factory) {
2 if(typeof exports === 'object' && typeof module === 'object')
3 module.exports = factory();
4 else if(typeof define === 'function' && define.amd)
5 define([], factory);
6 else if(typeof exports === 'object')
7 exports["AWS"] = factory();
8 else
9 root["AWS"] = factory();
10})(this, function() {
11return /******/ (function(modules) { // webpackBootstrap
12/******/ // The module cache
13/******/ var installedModules = {};
14
15/******/ // The require function
16/******/ function __webpack_require__(moduleId) {
17
18/******/ // Check if module is in cache
19/******/ if(installedModules[moduleId])
20/******/ return installedModules[moduleId].exports;
21
22/******/ // Create a new module (and put it into the cache)
23/******/ var module = installedModules[moduleId] = {
24/******/ exports: {},
25/******/ id: moduleId,
26/******/ loaded: false
27/******/ };
28
29/******/ // Execute the module function
30/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31
32/******/ // Flag the module as loaded
33/******/ module.loaded = true;
34
35/******/ // Return the exports of the module
36/******/ return module.exports;
37/******/ }
38
39
40/******/ // expose the modules object (__webpack_modules__)
41/******/ __webpack_require__.m = modules;
42
43/******/ // expose the module cache
44/******/ __webpack_require__.c = installedModules;
45
46/******/ // __webpack_public_path__
47/******/ __webpack_require__.p = "";
48
49/******/ // Load entry module and return exports
50/******/ return __webpack_require__(0);
51/******/ })
52/************************************************************************/
53/******/ ([
54/* 0 */
55/***/ (function(module, exports, __webpack_require__) {
56
57 module.exports = __webpack_require__(1);
58
59
60/***/ }),
61/* 1 */
62/***/ (function(module, exports, __webpack_require__) {
63
64 /**
65 * The main AWS namespace
66 */
67 var AWS = { util: __webpack_require__(2) };
68
69 /**
70 * @api private
71 * @!macro [new] nobrowser
72 * @note This feature is not supported in the browser environment of the SDK.
73 */
74 var _hidden = {}; _hidden.toString(); // hack to parse macro
75
76 /**
77 * @api private
78 */
79 module.exports = AWS;
80
81 AWS.util.update(AWS, {
82
83 /**
84 * @constant
85 */
86 VERSION: '2.433.0',
87
88 /**
89 * @api private
90 */
91 Signers: {},
92
93 /**
94 * @api private
95 */
96 Protocol: {
97 Json: __webpack_require__(13),
98 Query: __webpack_require__(17),
99 Rest: __webpack_require__(21),
100 RestJson: __webpack_require__(22),
101 RestXml: __webpack_require__(23)
102 },
103
104 /**
105 * @api private
106 */
107 XML: {
108 Builder: __webpack_require__(24),
109 Parser: null // conditionally set based on environment
110 },
111
112 /**
113 * @api private
114 */
115 JSON: {
116 Builder: __webpack_require__(14),
117 Parser: __webpack_require__(15)
118 },
119
120 /**
121 * @api private
122 */
123 Model: {
124 Api: __webpack_require__(29),
125 Operation: __webpack_require__(30),
126 Shape: __webpack_require__(19),
127 Paginator: __webpack_require__(31),
128 ResourceWaiter: __webpack_require__(32)
129 },
130
131 /**
132 * @api private
133 */
134 apiLoader: __webpack_require__(33),
135
136 /**
137 * @api private
138 */
139 EndpointCache: __webpack_require__(34).EndpointCache
140 });
141 __webpack_require__(36);
142 __webpack_require__(37);
143 __webpack_require__(40);
144 __webpack_require__(43);
145 __webpack_require__(44);
146 __webpack_require__(49);
147 __webpack_require__(52);
148 __webpack_require__(53);
149 __webpack_require__(54);
150 __webpack_require__(62);
151
152 /**
153 * @readonly
154 * @return [AWS.SequentialExecutor] a collection of global event listeners that
155 * are attached to every sent request.
156 * @see AWS.Request AWS.Request for a list of events to listen for
157 * @example Logging the time taken to send a request
158 * AWS.events.on('send', function startSend(resp) {
159 * resp.startTime = new Date().getTime();
160 * }).on('complete', function calculateTime(resp) {
161 * var time = (new Date().getTime() - resp.startTime) / 1000;
162 * console.log('Request took ' + time + ' seconds');
163 * });
164 *
165 * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds'
166 */
167 AWS.events = new AWS.SequentialExecutor();
168
169 //create endpoint cache lazily
170 AWS.util.memoizedProperty(AWS, 'endpointCache', function() {
171 return new AWS.EndpointCache(AWS.config.endpointCacheSize);
172 }, true);
173
174
175/***/ }),
176/* 2 */
177/***/ (function(module, exports, __webpack_require__) {
178
179 /* WEBPACK VAR INJECTION */(function(process, setImmediate) {/* eslint guard-for-in:0 */
180 var AWS;
181
182 /**
183 * A set of utility methods for use with the AWS SDK.
184 *
185 * @!attribute abort
186 * Return this value from an iterator function {each} or {arrayEach}
187 * to break out of the iteration.
188 * @example Breaking out of an iterator function
189 * AWS.util.each({a: 1, b: 2, c: 3}, function(key, value) {
190 * if (key == 'b') return AWS.util.abort;
191 * });
192 * @see each
193 * @see arrayEach
194 * @api private
195 */
196 var util = {
197 environment: 'nodejs',
198 engine: function engine() {
199 if (util.isBrowser() && typeof navigator !== 'undefined') {
200 return navigator.userAgent;
201 } else {
202 var engine = process.platform + '/' + process.version;
203 if (process.env.AWS_EXECUTION_ENV) {
204 engine += ' exec-env/' + process.env.AWS_EXECUTION_ENV;
205 }
206 return engine;
207 }
208 },
209
210 userAgent: function userAgent() {
211 var name = util.environment;
212 var agent = 'aws-sdk-' + name + '/' + __webpack_require__(1).VERSION;
213 if (name === 'nodejs') agent += ' ' + util.engine();
214 return agent;
215 },
216
217 uriEscape: function uriEscape(string) {
218 var output = encodeURIComponent(string);
219 output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape);
220
221 // AWS percent-encodes some extra non-standard characters in a URI
222 output = output.replace(/[*]/g, function(ch) {
223 return '%' + ch.charCodeAt(0).toString(16).toUpperCase();
224 });
225
226 return output;
227 },
228
229 uriEscapePath: function uriEscapePath(string) {
230 var parts = [];
231 util.arrayEach(string.split('/'), function (part) {
232 parts.push(util.uriEscape(part));
233 });
234 return parts.join('/');
235 },
236
237 urlParse: function urlParse(url) {
238 return util.url.parse(url);
239 },
240
241 urlFormat: function urlFormat(url) {
242 return util.url.format(url);
243 },
244
245 queryStringParse: function queryStringParse(qs) {
246 return util.querystring.parse(qs);
247 },
248
249 queryParamsToString: function queryParamsToString(params) {
250 var items = [];
251 var escape = util.uriEscape;
252 var sortedKeys = Object.keys(params).sort();
253
254 util.arrayEach(sortedKeys, function(name) {
255 var value = params[name];
256 var ename = escape(name);
257 var result = ename + '=';
258 if (Array.isArray(value)) {
259 var vals = [];
260 util.arrayEach(value, function(item) { vals.push(escape(item)); });
261 result = ename + '=' + vals.sort().join('&' + ename + '=');
262 } else if (value !== undefined && value !== null) {
263 result = ename + '=' + escape(value);
264 }
265 items.push(result);
266 });
267
268 return items.join('&');
269 },
270
271 readFileSync: function readFileSync(path) {
272 if (util.isBrowser()) return null;
273 return __webpack_require__(6).readFileSync(path, 'utf-8');
274 },
275
276 base64: {
277 encode: function encode64(string) {
278 if (typeof string === 'number') {
279 throw util.error(new Error('Cannot base64 encode number ' + string));
280 }
281 if (string === null || typeof string === 'undefined') {
282 return string;
283 }
284 var buf = (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(string) : new util.Buffer(string);
285 return buf.toString('base64');
286 },
287
288 decode: function decode64(string) {
289 if (typeof string === 'number') {
290 throw util.error(new Error('Cannot base64 decode number ' + string));
291 }
292 if (string === null || typeof string === 'undefined') {
293 return string;
294 }
295 return (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(string, 'base64') : new util.Buffer(string, 'base64');
296 }
297
298 },
299
300 buffer: {
301 toStream: function toStream(buffer) {
302 if (!util.Buffer.isBuffer(buffer)) buffer = new util.Buffer(buffer);
303
304 var readable = new (util.stream.Readable)();
305 var pos = 0;
306 readable._read = function(size) {
307 if (pos >= buffer.length) return readable.push(null);
308
309 var end = pos + size;
310 if (end > buffer.length) end = buffer.length;
311 readable.push(buffer.slice(pos, end));
312 pos = end;
313 };
314
315 return readable;
316 },
317
318 /**
319 * Concatenates a list of Buffer objects.
320 */
321 concat: function(buffers) {
322 var length = 0,
323 offset = 0,
324 buffer = null, i;
325
326 for (i = 0; i < buffers.length; i++) {
327 length += buffers[i].length;
328 }
329
330 buffer = new util.Buffer(length);
331
332 for (i = 0; i < buffers.length; i++) {
333 buffers[i].copy(buffer, offset);
334 offset += buffers[i].length;
335 }
336
337 return buffer;
338 }
339 },
340
341 string: {
342 byteLength: function byteLength(string) {
343 if (string === null || string === undefined) return 0;
344 if (typeof string === 'string') string = new util.Buffer(string);
345
346 if (typeof string.byteLength === 'number') {
347 return string.byteLength;
348 } else if (typeof string.length === 'number') {
349 return string.length;
350 } else if (typeof string.size === 'number') {
351 return string.size;
352 } else if (typeof string.path === 'string') {
353 return __webpack_require__(6).lstatSync(string.path).size;
354 } else {
355 throw util.error(new Error('Cannot determine length of ' + string),
356 { object: string });
357 }
358 },
359
360 upperFirst: function upperFirst(string) {
361 return string[0].toUpperCase() + string.substr(1);
362 },
363
364 lowerFirst: function lowerFirst(string) {
365 return string[0].toLowerCase() + string.substr(1);
366 }
367 },
368
369 ini: {
370 parse: function string(ini) {
371 var currentSection, map = {};
372 util.arrayEach(ini.split(/\r?\n/), function(line) {
373 line = line.split(/(^|\s)[;#]/)[0]; // remove comments
374 var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/);
375 if (section) {
376 currentSection = section[1];
377 } else if (currentSection) {
378 var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/);
379 if (item) {
380 map[currentSection] = map[currentSection] || {};
381 map[currentSection][item[1]] = item[2];
382 }
383 }
384 });
385
386 return map;
387 }
388 },
389
390 fn: {
391 noop: function() {},
392 callback: function (err) { if (err) throw err; },
393
394 /**
395 * Turn a synchronous function into as "async" function by making it call
396 * a callback. The underlying function is called with all but the last argument,
397 * which is treated as the callback. The callback is passed passed a first argument
398 * of null on success to mimick standard node callbacks.
399 */
400 makeAsync: function makeAsync(fn, expectedArgs) {
401 if (expectedArgs && expectedArgs <= fn.length) {
402 return fn;
403 }
404
405 return function() {
406 var args = Array.prototype.slice.call(arguments, 0);
407 var callback = args.pop();
408 var result = fn.apply(null, args);
409 callback(result);
410 };
411 }
412 },
413
414 /**
415 * Date and time utility functions.
416 */
417 date: {
418
419 /**
420 * @return [Date] the current JavaScript date object. Since all
421 * AWS services rely on this date object, you can override
422 * this function to provide a special time value to AWS service
423 * requests.
424 */
425 getDate: function getDate() {
426 if (!AWS) AWS = __webpack_require__(1);
427 if (AWS.config.systemClockOffset) { // use offset when non-zero
428 return new Date(new Date().getTime() + AWS.config.systemClockOffset);
429 } else {
430 return new Date();
431 }
432 },
433
434 /**
435 * @return [String] the date in ISO-8601 format
436 */
437 iso8601: function iso8601(date) {
438 if (date === undefined) { date = util.date.getDate(); }
439 return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
440 },
441
442 /**
443 * @return [String] the date in RFC 822 format
444 */
445 rfc822: function rfc822(date) {
446 if (date === undefined) { date = util.date.getDate(); }
447 return date.toUTCString();
448 },
449
450 /**
451 * @return [Integer] the UNIX timestamp value for the current time
452 */
453 unixTimestamp: function unixTimestamp(date) {
454 if (date === undefined) { date = util.date.getDate(); }
455 return date.getTime() / 1000;
456 },
457
458 /**
459 * @param [String,number,Date] date
460 * @return [Date]
461 */
462 from: function format(date) {
463 if (typeof date === 'number') {
464 return new Date(date * 1000); // unix timestamp
465 } else {
466 return new Date(date);
467 }
468 },
469
470 /**
471 * Given a Date or date-like value, this function formats the
472 * date into a string of the requested value.
473 * @param [String,number,Date] date
474 * @param [String] formatter Valid formats are:
475 # * 'iso8601'
476 # * 'rfc822'
477 # * 'unixTimestamp'
478 * @return [String]
479 */
480 format: function format(date, formatter) {
481 if (!formatter) formatter = 'iso8601';
482 return util.date[formatter](util.date.from(date));
483 },
484
485 parseTimestamp: function parseTimestamp(value) {
486 if (typeof value === 'number') { // unix timestamp (number)
487 return new Date(value * 1000);
488 } else if (value.match(/^\d+$/)) { // unix timestamp
489 return new Date(value * 1000);
490 } else if (value.match(/^\d{4}/)) { // iso8601
491 return new Date(value);
492 } else if (value.match(/^\w{3},/)) { // rfc822
493 return new Date(value);
494 } else {
495 throw util.error(
496 new Error('unhandled timestamp format: ' + value),
497 {code: 'TimestampParserError'});
498 }
499 }
500
501 },
502
503 crypto: {
504 crc32Table: [
505 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
506 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
507 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
508 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
509 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
510 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
511 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
512 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
513 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
514 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
515 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
516 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
517 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
518 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
519 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
520 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
521 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
522 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
523 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
524 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
525 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
526 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
527 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
528 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
529 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
530 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
531 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
532 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
533 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
534 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
535 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
536 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
537 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
538 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
539 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
540 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
541 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
542 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
543 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
544 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
545 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
546 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
547 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
548 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
549 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
550 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
551 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
552 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
553 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
554 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
555 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
556 0x2D02EF8D],
557
558 crc32: function crc32(data) {
559 var tbl = util.crypto.crc32Table;
560 var crc = 0 ^ -1;
561
562 if (typeof data === 'string') {
563 data = new util.Buffer(data);
564 }
565
566 for (var i = 0; i < data.length; i++) {
567 var code = data.readUInt8(i);
568 crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF];
569 }
570 return (crc ^ -1) >>> 0;
571 },
572
573 hmac: function hmac(key, string, digest, fn) {
574 if (!digest) digest = 'binary';
575 if (digest === 'buffer') { digest = undefined; }
576 if (!fn) fn = 'sha256';
577 if (typeof string === 'string') string = new util.Buffer(string);
578 return util.crypto.lib.createHmac(fn, key).update(string).digest(digest);
579 },
580
581 md5: function md5(data, digest, callback) {
582 return util.crypto.hash('md5', data, digest, callback);
583 },
584
585 sha256: function sha256(data, digest, callback) {
586 return util.crypto.hash('sha256', data, digest, callback);
587 },
588
589 hash: function(algorithm, data, digest, callback) {
590 var hash = util.crypto.createHash(algorithm);
591 if (!digest) { digest = 'binary'; }
592 if (digest === 'buffer') { digest = undefined; }
593 if (typeof data === 'string') data = new util.Buffer(data);
594 var sliceFn = util.arraySliceFn(data);
595 var isBuffer = util.Buffer.isBuffer(data);
596 //Identifying objects with an ArrayBuffer as buffers
597 if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true;
598
599 if (callback && typeof data === 'object' &&
600 typeof data.on === 'function' && !isBuffer) {
601 data.on('data', function(chunk) { hash.update(chunk); });
602 data.on('error', function(err) { callback(err); });
603 data.on('end', function() { callback(null, hash.digest(digest)); });
604 } else if (callback && sliceFn && !isBuffer &&
605 typeof FileReader !== 'undefined') {
606 // this might be a File/Blob
607 var index = 0, size = 1024 * 512;
608 var reader = new FileReader();
609 reader.onerror = function() {
610 callback(new Error('Failed to read data.'));
611 };
612 reader.onload = function() {
613 var buf = new util.Buffer(new Uint8Array(reader.result));
614 hash.update(buf);
615 index += buf.length;
616 reader._continueReading();
617 };
618 reader._continueReading = function() {
619 if (index >= data.size) {
620 callback(null, hash.digest(digest));
621 return;
622 }
623
624 var back = index + size;
625 if (back > data.size) back = data.size;
626 reader.readAsArrayBuffer(sliceFn.call(data, index, back));
627 };
628
629 reader._continueReading();
630 } else {
631 if (util.isBrowser() && typeof data === 'object' && !isBuffer) {
632 data = new util.Buffer(new Uint8Array(data));
633 }
634 var out = hash.update(data).digest(digest);
635 if (callback) callback(null, out);
636 return out;
637 }
638 },
639
640 toHex: function toHex(data) {
641 var out = [];
642 for (var i = 0; i < data.length; i++) {
643 out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2));
644 }
645 return out.join('');
646 },
647
648 createHash: function createHash(algorithm) {
649 return util.crypto.lib.createHash(algorithm);
650 }
651
652 },
653
654 /** @!ignore */
655
656 /* Abort constant */
657 abort: {},
658
659 each: function each(object, iterFunction) {
660 for (var key in object) {
661 if (Object.prototype.hasOwnProperty.call(object, key)) {
662 var ret = iterFunction.call(this, key, object[key]);
663 if (ret === util.abort) break;
664 }
665 }
666 },
667
668 arrayEach: function arrayEach(array, iterFunction) {
669 for (var idx in array) {
670 if (Object.prototype.hasOwnProperty.call(array, idx)) {
671 var ret = iterFunction.call(this, array[idx], parseInt(idx, 10));
672 if (ret === util.abort) break;
673 }
674 }
675 },
676
677 update: function update(obj1, obj2) {
678 util.each(obj2, function iterator(key, item) {
679 obj1[key] = item;
680 });
681 return obj1;
682 },
683
684 merge: function merge(obj1, obj2) {
685 return util.update(util.copy(obj1), obj2);
686 },
687
688 copy: function copy(object) {
689 if (object === null || object === undefined) return object;
690 var dupe = {};
691 // jshint forin:false
692 for (var key in object) {
693 dupe[key] = object[key];
694 }
695 return dupe;
696 },
697
698 isEmpty: function isEmpty(obj) {
699 for (var prop in obj) {
700 if (Object.prototype.hasOwnProperty.call(obj, prop)) {
701 return false;
702 }
703 }
704 return true;
705 },
706
707 arraySliceFn: function arraySliceFn(obj) {
708 var fn = obj.slice || obj.webkitSlice || obj.mozSlice;
709 return typeof fn === 'function' ? fn : null;
710 },
711
712 isType: function isType(obj, type) {
713 // handle cross-"frame" objects
714 if (typeof type === 'function') type = util.typeName(type);
715 return Object.prototype.toString.call(obj) === '[object ' + type + ']';
716 },
717
718 typeName: function typeName(type) {
719 if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name;
720 var str = type.toString();
721 var match = str.match(/^\s*function (.+)\(/);
722 return match ? match[1] : str;
723 },
724
725 error: function error(err, options) {
726 var originalError = null;
727 if (typeof err.message === 'string' && err.message !== '') {
728 if (typeof options === 'string' || (options && options.message)) {
729 originalError = util.copy(err);
730 originalError.message = err.message;
731 }
732 }
733 err.message = err.message || null;
734
735 if (typeof options === 'string') {
736 err.message = options;
737 } else if (typeof options === 'object' && options !== null) {
738 util.update(err, options);
739 if (options.message)
740 err.message = options.message;
741 if (options.code || options.name)
742 err.code = options.code || options.name;
743 if (options.stack)
744 err.stack = options.stack;
745 }
746
747 if (typeof Object.defineProperty === 'function') {
748 Object.defineProperty(err, 'name', {writable: true, enumerable: false});
749 Object.defineProperty(err, 'message', {enumerable: true});
750 }
751
752 err.name = options && options.name || err.name || err.code || 'Error';
753 err.time = new Date();
754
755 if (originalError) err.originalError = originalError;
756
757 return err;
758 },
759
760 /**
761 * @api private
762 */
763 inherit: function inherit(klass, features) {
764 var newObject = null;
765 if (features === undefined) {
766 features = klass;
767 klass = Object;
768 newObject = {};
769 } else {
770 var ctor = function ConstructorWrapper() {};
771 ctor.prototype = klass.prototype;
772 newObject = new ctor();
773 }
774
775 // constructor not supplied, create pass-through ctor
776 if (features.constructor === Object) {
777 features.constructor = function() {
778 if (klass !== Object) {
779 return klass.apply(this, arguments);
780 }
781 };
782 }
783
784 features.constructor.prototype = newObject;
785 util.update(features.constructor.prototype, features);
786 features.constructor.__super__ = klass;
787 return features.constructor;
788 },
789
790 /**
791 * @api private
792 */
793 mixin: function mixin() {
794 var klass = arguments[0];
795 for (var i = 1; i < arguments.length; i++) {
796 // jshint forin:false
797 for (var prop in arguments[i].prototype) {
798 var fn = arguments[i].prototype[prop];
799 if (prop !== 'constructor') {
800 klass.prototype[prop] = fn;
801 }
802 }
803 }
804 return klass;
805 },
806
807 /**
808 * @api private
809 */
810 hideProperties: function hideProperties(obj, props) {
811 if (typeof Object.defineProperty !== 'function') return;
812
813 util.arrayEach(props, function (key) {
814 Object.defineProperty(obj, key, {
815 enumerable: false, writable: true, configurable: true });
816 });
817 },
818
819 /**
820 * @api private
821 */
822 property: function property(obj, name, value, enumerable, isValue) {
823 var opts = {
824 configurable: true,
825 enumerable: enumerable !== undefined ? enumerable : true
826 };
827 if (typeof value === 'function' && !isValue) {
828 opts.get = value;
829 }
830 else {
831 opts.value = value; opts.writable = true;
832 }
833
834 Object.defineProperty(obj, name, opts);
835 },
836
837 /**
838 * @api private
839 */
840 memoizedProperty: function memoizedProperty(obj, name, get, enumerable) {
841 var cachedValue = null;
842
843 // build enumerable attribute for each value with lazy accessor.
844 util.property(obj, name, function() {
845 if (cachedValue === null) {
846 cachedValue = get();
847 }
848 return cachedValue;
849 }, enumerable);
850 },
851
852 /**
853 * TODO Remove in major version revision
854 * This backfill populates response data without the
855 * top-level payload name.
856 *
857 * @api private
858 */
859 hoistPayloadMember: function hoistPayloadMember(resp) {
860 var req = resp.request;
861 var operationName = req.operation;
862 var operation = req.service.api.operations[operationName];
863 var output = operation.output;
864 if (output.payload && !operation.hasEventOutput) {
865 var payloadMember = output.members[output.payload];
866 var responsePayload = resp.data[output.payload];
867 if (payloadMember.type === 'structure') {
868 util.each(responsePayload, function(key, value) {
869 util.property(resp.data, key, value, false);
870 });
871 }
872 }
873 },
874
875 /**
876 * Compute SHA-256 checksums of streams
877 *
878 * @api private
879 */
880 computeSha256: function computeSha256(body, done) {
881 if (util.isNode()) {
882 var Stream = util.stream.Stream;
883 var fs = __webpack_require__(6);
884 if (body instanceof Stream) {
885 if (typeof body.path === 'string') { // assume file object
886 var settings = {};
887 if (typeof body.start === 'number') {
888 settings.start = body.start;
889 }
890 if (typeof body.end === 'number') {
891 settings.end = body.end;
892 }
893 body = fs.createReadStream(body.path, settings);
894 } else { // TODO support other stream types
895 return done(new Error('Non-file stream objects are ' +
896 'not supported with SigV4'));
897 }
898 }
899 }
900
901 util.crypto.sha256(body, 'hex', function(err, sha) {
902 if (err) done(err);
903 else done(null, sha);
904 });
905 },
906
907 /**
908 * @api private
909 */
910 isClockSkewed: function isClockSkewed(serverTime) {
911 if (serverTime) {
912 util.property(AWS.config, 'isClockSkewed',
913 Math.abs(new Date().getTime() - serverTime) >= 300000, false);
914 return AWS.config.isClockSkewed;
915 }
916 },
917
918 applyClockOffset: function applyClockOffset(serverTime) {
919 if (serverTime)
920 AWS.config.systemClockOffset = serverTime - new Date().getTime();
921 },
922
923 /**
924 * @api private
925 */
926 extractRequestId: function extractRequestId(resp) {
927 var requestId = resp.httpResponse.headers['x-amz-request-id'] ||
928 resp.httpResponse.headers['x-amzn-requestid'];
929
930 if (!requestId && resp.data && resp.data.ResponseMetadata) {
931 requestId = resp.data.ResponseMetadata.RequestId;
932 }
933
934 if (requestId) {
935 resp.requestId = requestId;
936 }
937
938 if (resp.error) {
939 resp.error.requestId = requestId;
940 }
941 },
942
943 /**
944 * @api private
945 */
946 addPromises: function addPromises(constructors, PromiseDependency) {
947 var deletePromises = false;
948 if (PromiseDependency === undefined && AWS && AWS.config) {
949 PromiseDependency = AWS.config.getPromisesDependency();
950 }
951 if (PromiseDependency === undefined && typeof Promise !== 'undefined') {
952 PromiseDependency = Promise;
953 }
954 if (typeof PromiseDependency !== 'function') deletePromises = true;
955 if (!Array.isArray(constructors)) constructors = [constructors];
956
957 for (var ind = 0; ind < constructors.length; ind++) {
958 var constructor = constructors[ind];
959 if (deletePromises) {
960 if (constructor.deletePromisesFromClass) {
961 constructor.deletePromisesFromClass();
962 }
963 } else if (constructor.addPromisesToClass) {
964 constructor.addPromisesToClass(PromiseDependency);
965 }
966 }
967 },
968
969 /**
970 * @api private
971 */
972 promisifyMethod: function promisifyMethod(methodName, PromiseDependency) {
973 return function promise() {
974 var self = this;
975 return new PromiseDependency(function(resolve, reject) {
976 self[methodName](function(err, data) {
977 if (err) {
978 reject(err);
979 } else {
980 resolve(data);
981 }
982 });
983 });
984 };
985 },
986
987 /**
988 * @api private
989 */
990 isDualstackAvailable: function isDualstackAvailable(service) {
991 if (!service) return false;
992 var metadata = __webpack_require__(7);
993 if (typeof service !== 'string') service = service.serviceIdentifier;
994 if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false;
995 return !!metadata[service].dualstackAvailable;
996 },
997
998 /**
999 * @api private
1000 */
1001 calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) {
1002 if (!retryDelayOptions) retryDelayOptions = {};
1003 var customBackoff = retryDelayOptions.customBackoff || null;
1004 if (typeof customBackoff === 'function') {
1005 return customBackoff(retryCount);
1006 }
1007 var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100;
1008 var delay = Math.random() * (Math.pow(2, retryCount) * base);
1009 return delay;
1010 },
1011
1012 /**
1013 * @api private
1014 */
1015 handleRequestWithRetries: function handleRequestWithRetries(httpRequest, options, cb) {
1016 if (!options) options = {};
1017 var http = AWS.HttpClient.getInstance();
1018 var httpOptions = options.httpOptions || {};
1019 var retryCount = 0;
1020
1021 var errCallback = function(err) {
1022 var maxRetries = options.maxRetries || 0;
1023 if (err && err.code === 'TimeoutError') err.retryable = true;
1024 if (err && err.retryable && retryCount < maxRetries) {
1025 retryCount++;
1026 var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions);
1027 setTimeout(sendRequest, delay + (err.retryAfter || 0));
1028 } else {
1029 cb(err);
1030 }
1031 };
1032
1033 var sendRequest = function() {
1034 var data = '';
1035 http.handleRequest(httpRequest, httpOptions, function(httpResponse) {
1036 httpResponse.on('data', function(chunk) { data += chunk.toString(); });
1037 httpResponse.on('end', function() {
1038 var statusCode = httpResponse.statusCode;
1039 if (statusCode < 300) {
1040 cb(null, data);
1041 } else {
1042 var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0;
1043 var err = util.error(new Error(),
1044 { retryable: statusCode >= 500 || statusCode === 429 }
1045 );
1046 if (retryAfter && err.retryable) err.retryAfter = retryAfter;
1047 errCallback(err);
1048 }
1049 });
1050 }, errCallback);
1051 };
1052
1053 AWS.util.defer(sendRequest);
1054 },
1055
1056 /**
1057 * @api private
1058 */
1059 uuid: {
1060 v4: function uuidV4() {
1061 return __webpack_require__(8).v4();
1062 }
1063 },
1064
1065 /**
1066 * @api private
1067 */
1068 convertPayloadToString: function convertPayloadToString(resp) {
1069 var req = resp.request;
1070 var operation = req.operation;
1071 var rules = req.service.api.operations[operation].output || {};
1072 if (rules.payload && resp.data[rules.payload]) {
1073 resp.data[rules.payload] = resp.data[rules.payload].toString();
1074 }
1075 },
1076
1077 /**
1078 * @api private
1079 */
1080 defer: function defer(callback) {
1081 if (typeof process === 'object' && typeof process.nextTick === 'function') {
1082 process.nextTick(callback);
1083 } else if (typeof setImmediate === 'function') {
1084 setImmediate(callback);
1085 } else {
1086 setTimeout(callback, 0);
1087 }
1088 },
1089
1090 /**
1091 * @api private
1092 */
1093 defaultProfile: 'default',
1094
1095 /**
1096 * @api private
1097 */
1098 configOptInEnv: 'AWS_SDK_LOAD_CONFIG',
1099
1100 /**
1101 * @api private
1102 */
1103 sharedCredentialsFileEnv: 'AWS_SHARED_CREDENTIALS_FILE',
1104
1105 /**
1106 * @api private
1107 */
1108 sharedConfigFileEnv: 'AWS_CONFIG_FILE',
1109
1110 /**
1111 * @api private
1112 */
1113 imdsDisabledEnv: 'AWS_EC2_METADATA_DISABLED'
1114 };
1115
1116 /**
1117 * @api private
1118 */
1119 module.exports = util;
1120
1121 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(4).setImmediate))
1122
1123/***/ }),
1124/* 3 */
1125/***/ (function(module, exports) {
1126
1127 // shim for using process in browser
1128 var process = module.exports = {};
1129
1130 // cached from whatever global is present so that test runners that stub it
1131 // don't break things. But we need to wrap it in a try catch in case it is
1132 // wrapped in strict mode code which doesn't define any globals. It's inside a
1133 // function because try/catches deoptimize in certain engines.
1134
1135 var cachedSetTimeout;
1136 var cachedClearTimeout;
1137
1138 function defaultSetTimout() {
1139 throw new Error('setTimeout has not been defined');
1140 }
1141 function defaultClearTimeout () {
1142 throw new Error('clearTimeout has not been defined');
1143 }
1144 (function () {
1145 try {
1146 if (typeof setTimeout === 'function') {
1147 cachedSetTimeout = setTimeout;
1148 } else {
1149 cachedSetTimeout = defaultSetTimout;
1150 }
1151 } catch (e) {
1152 cachedSetTimeout = defaultSetTimout;
1153 }
1154 try {
1155 if (typeof clearTimeout === 'function') {
1156 cachedClearTimeout = clearTimeout;
1157 } else {
1158 cachedClearTimeout = defaultClearTimeout;
1159 }
1160 } catch (e) {
1161 cachedClearTimeout = defaultClearTimeout;
1162 }
1163 } ())
1164 function runTimeout(fun) {
1165 if (cachedSetTimeout === setTimeout) {
1166 //normal enviroments in sane situations
1167 return setTimeout(fun, 0);
1168 }
1169 // if setTimeout wasn't available but was latter defined
1170 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
1171 cachedSetTimeout = setTimeout;
1172 return setTimeout(fun, 0);
1173 }
1174 try {
1175 // when when somebody has screwed with setTimeout but no I.E. maddness
1176 return cachedSetTimeout(fun, 0);
1177 } catch(e){
1178 try {
1179 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1180 return cachedSetTimeout.call(null, fun, 0);
1181 } catch(e){
1182 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
1183 return cachedSetTimeout.call(this, fun, 0);
1184 }
1185 }
1186
1187
1188 }
1189 function runClearTimeout(marker) {
1190 if (cachedClearTimeout === clearTimeout) {
1191 //normal enviroments in sane situations
1192 return clearTimeout(marker);
1193 }
1194 // if clearTimeout wasn't available but was latter defined
1195 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
1196 cachedClearTimeout = clearTimeout;
1197 return clearTimeout(marker);
1198 }
1199 try {
1200 // when when somebody has screwed with setTimeout but no I.E. maddness
1201 return cachedClearTimeout(marker);
1202 } catch (e){
1203 try {
1204 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1205 return cachedClearTimeout.call(null, marker);
1206 } catch (e){
1207 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
1208 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
1209 return cachedClearTimeout.call(this, marker);
1210 }
1211 }
1212
1213
1214
1215 }
1216 var queue = [];
1217 var draining = false;
1218 var currentQueue;
1219 var queueIndex = -1;
1220
1221 function cleanUpNextTick() {
1222 if (!draining || !currentQueue) {
1223 return;
1224 }
1225 draining = false;
1226 if (currentQueue.length) {
1227 queue = currentQueue.concat(queue);
1228 } else {
1229 queueIndex = -1;
1230 }
1231 if (queue.length) {
1232 drainQueue();
1233 }
1234 }
1235
1236 function drainQueue() {
1237 if (draining) {
1238 return;
1239 }
1240 var timeout = runTimeout(cleanUpNextTick);
1241 draining = true;
1242
1243 var len = queue.length;
1244 while(len) {
1245 currentQueue = queue;
1246 queue = [];
1247 while (++queueIndex < len) {
1248 if (currentQueue) {
1249 currentQueue[queueIndex].run();
1250 }
1251 }
1252 queueIndex = -1;
1253 len = queue.length;
1254 }
1255 currentQueue = null;
1256 draining = false;
1257 runClearTimeout(timeout);
1258 }
1259
1260 process.nextTick = function (fun) {
1261 var args = new Array(arguments.length - 1);
1262 if (arguments.length > 1) {
1263 for (var i = 1; i < arguments.length; i++) {
1264 args[i - 1] = arguments[i];
1265 }
1266 }
1267 queue.push(new Item(fun, args));
1268 if (queue.length === 1 && !draining) {
1269 runTimeout(drainQueue);
1270 }
1271 };
1272
1273 // v8 likes predictible objects
1274 function Item(fun, array) {
1275 this.fun = fun;
1276 this.array = array;
1277 }
1278 Item.prototype.run = function () {
1279 this.fun.apply(null, this.array);
1280 };
1281 process.title = 'browser';
1282 process.browser = true;
1283 process.env = {};
1284 process.argv = [];
1285 process.version = ''; // empty string to avoid regexp issues
1286 process.versions = {};
1287
1288 function noop() {}
1289
1290 process.on = noop;
1291 process.addListener = noop;
1292 process.once = noop;
1293 process.off = noop;
1294 process.removeListener = noop;
1295 process.removeAllListeners = noop;
1296 process.emit = noop;
1297 process.prependListener = noop;
1298 process.prependOnceListener = noop;
1299
1300 process.listeners = function (name) { return [] }
1301
1302 process.binding = function (name) {
1303 throw new Error('process.binding is not supported');
1304 };
1305
1306 process.cwd = function () { return '/' };
1307 process.chdir = function (dir) {
1308 throw new Error('process.chdir is not supported');
1309 };
1310 process.umask = function() { return 0; };
1311
1312
1313/***/ }),
1314/* 4 */
1315/***/ (function(module, exports, __webpack_require__) {
1316
1317 /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
1318 (typeof self !== "undefined" && self) ||
1319 window;
1320 var apply = Function.prototype.apply;
1321
1322 // DOM APIs, for completeness
1323
1324 exports.setTimeout = function() {
1325 return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
1326 };
1327 exports.setInterval = function() {
1328 return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
1329 };
1330 exports.clearTimeout =
1331 exports.clearInterval = function(timeout) {
1332 if (timeout) {
1333 timeout.close();
1334 }
1335 };
1336
1337 function Timeout(id, clearFn) {
1338 this._id = id;
1339 this._clearFn = clearFn;
1340 }
1341 Timeout.prototype.unref = Timeout.prototype.ref = function() {};
1342 Timeout.prototype.close = function() {
1343 this._clearFn.call(scope, this._id);
1344 };
1345
1346 // Does not start the time, just sets up the members needed.
1347 exports.enroll = function(item, msecs) {
1348 clearTimeout(item._idleTimeoutId);
1349 item._idleTimeout = msecs;
1350 };
1351
1352 exports.unenroll = function(item) {
1353 clearTimeout(item._idleTimeoutId);
1354 item._idleTimeout = -1;
1355 };
1356
1357 exports._unrefActive = exports.active = function(item) {
1358 clearTimeout(item._idleTimeoutId);
1359
1360 var msecs = item._idleTimeout;
1361 if (msecs >= 0) {
1362 item._idleTimeoutId = setTimeout(function onTimeout() {
1363 if (item._onTimeout)
1364 item._onTimeout();
1365 }, msecs);
1366 }
1367 };
1368
1369 // setimmediate attaches itself to the global object
1370 __webpack_require__(5);
1371 // On some exotic environments, it's not clear which object `setimmediate` was
1372 // able to install onto. Search each possibility in the same order as the
1373 // `setimmediate` library.
1374 exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
1375 (typeof global !== "undefined" && global.setImmediate) ||
1376 (this && this.setImmediate);
1377 exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
1378 (typeof global !== "undefined" && global.clearImmediate) ||
1379 (this && this.clearImmediate);
1380
1381 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
1382
1383/***/ }),
1384/* 5 */
1385/***/ (function(module, exports, __webpack_require__) {
1386
1387 /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
1388 "use strict";
1389
1390 if (global.setImmediate) {
1391 return;
1392 }
1393
1394 var nextHandle = 1; // Spec says greater than zero
1395 var tasksByHandle = {};
1396 var currentlyRunningATask = false;
1397 var doc = global.document;
1398 var registerImmediate;
1399
1400 function setImmediate(callback) {
1401 // Callback can either be a function or a string
1402 if (typeof callback !== "function") {
1403 callback = new Function("" + callback);
1404 }
1405 // Copy function arguments
1406 var args = new Array(arguments.length - 1);
1407 for (var i = 0; i < args.length; i++) {
1408 args[i] = arguments[i + 1];
1409 }
1410 // Store and register the task
1411 var task = { callback: callback, args: args };
1412 tasksByHandle[nextHandle] = task;
1413 registerImmediate(nextHandle);
1414 return nextHandle++;
1415 }
1416
1417 function clearImmediate(handle) {
1418 delete tasksByHandle[handle];
1419 }
1420
1421 function run(task) {
1422 var callback = task.callback;
1423 var args = task.args;
1424 switch (args.length) {
1425 case 0:
1426 callback();
1427 break;
1428 case 1:
1429 callback(args[0]);
1430 break;
1431 case 2:
1432 callback(args[0], args[1]);
1433 break;
1434 case 3:
1435 callback(args[0], args[1], args[2]);
1436 break;
1437 default:
1438 callback.apply(undefined, args);
1439 break;
1440 }
1441 }
1442
1443 function runIfPresent(handle) {
1444 // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
1445 // So if we're currently running a task, we'll need to delay this invocation.
1446 if (currentlyRunningATask) {
1447 // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
1448 // "too much recursion" error.
1449 setTimeout(runIfPresent, 0, handle);
1450 } else {
1451 var task = tasksByHandle[handle];
1452 if (task) {
1453 currentlyRunningATask = true;
1454 try {
1455 run(task);
1456 } finally {
1457 clearImmediate(handle);
1458 currentlyRunningATask = false;
1459 }
1460 }
1461 }
1462 }
1463
1464 function installNextTickImplementation() {
1465 registerImmediate = function(handle) {
1466 process.nextTick(function () { runIfPresent(handle); });
1467 };
1468 }
1469
1470 function canUsePostMessage() {
1471 // The test against `importScripts` prevents this implementation from being installed inside a web worker,
1472 // where `global.postMessage` means something completely different and can't be used for this purpose.
1473 if (global.postMessage && !global.importScripts) {
1474 var postMessageIsAsynchronous = true;
1475 var oldOnMessage = global.onmessage;
1476 global.onmessage = function() {
1477 postMessageIsAsynchronous = false;
1478 };
1479 global.postMessage("", "*");
1480 global.onmessage = oldOnMessage;
1481 return postMessageIsAsynchronous;
1482 }
1483 }
1484
1485 function installPostMessageImplementation() {
1486 // Installs an event handler on `global` for the `message` event: see
1487 // * https://developer.mozilla.org/en/DOM/window.postMessage
1488 // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
1489
1490 var messagePrefix = "setImmediate$" + Math.random() + "$";
1491 var onGlobalMessage = function(event) {
1492 if (event.source === global &&
1493 typeof event.data === "string" &&
1494 event.data.indexOf(messagePrefix) === 0) {
1495 runIfPresent(+event.data.slice(messagePrefix.length));
1496 }
1497 };
1498
1499 if (global.addEventListener) {
1500 global.addEventListener("message", onGlobalMessage, false);
1501 } else {
1502 global.attachEvent("onmessage", onGlobalMessage);
1503 }
1504
1505 registerImmediate = function(handle) {
1506 global.postMessage(messagePrefix + handle, "*");
1507 };
1508 }
1509
1510 function installMessageChannelImplementation() {
1511 var channel = new MessageChannel();
1512 channel.port1.onmessage = function(event) {
1513 var handle = event.data;
1514 runIfPresent(handle);
1515 };
1516
1517 registerImmediate = function(handle) {
1518 channel.port2.postMessage(handle);
1519 };
1520 }
1521
1522 function installReadyStateChangeImplementation() {
1523 var html = doc.documentElement;
1524 registerImmediate = function(handle) {
1525 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
1526 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
1527 var script = doc.createElement("script");
1528 script.onreadystatechange = function () {
1529 runIfPresent(handle);
1530 script.onreadystatechange = null;
1531 html.removeChild(script);
1532 script = null;
1533 };
1534 html.appendChild(script);
1535 };
1536 }
1537
1538 function installSetTimeoutImplementation() {
1539 registerImmediate = function(handle) {
1540 setTimeout(runIfPresent, 0, handle);
1541 };
1542 }
1543
1544 // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
1545 var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
1546 attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
1547
1548 // Don't get fooled by e.g. browserify environments.
1549 if ({}.toString.call(global.process) === "[object process]") {
1550 // For Node.js before 0.9
1551 installNextTickImplementation();
1552
1553 } else if (canUsePostMessage()) {
1554 // For non-IE10 modern browsers
1555 installPostMessageImplementation();
1556
1557 } else if (global.MessageChannel) {
1558 // For web workers, where supported
1559 installMessageChannelImplementation();
1560
1561 } else if (doc && "onreadystatechange" in doc.createElement("script")) {
1562 // For IE 6–8
1563 installReadyStateChangeImplementation();
1564
1565 } else {
1566 // For older browsers
1567 installSetTimeoutImplementation();
1568 }
1569
1570 attachTo.setImmediate = setImmediate;
1571 attachTo.clearImmediate = clearImmediate;
1572 }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
1573
1574 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
1575
1576/***/ }),
1577/* 6 */
1578/***/ (function(module, exports) {
1579
1580 /* (ignored) */
1581
1582/***/ }),
1583/* 7 */
1584/***/ (function(module, exports) {
1585
1586 module.exports = {"acm":{"name":"ACM","cors":true},"apigateway":{"name":"APIGateway","cors":true},"applicationautoscaling":{"prefix":"application-autoscaling","name":"ApplicationAutoScaling","cors":true},"appstream":{"name":"AppStream"},"autoscaling":{"name":"AutoScaling","cors":true},"batch":{"name":"Batch"},"budgets":{"name":"Budgets"},"clouddirectory":{"name":"CloudDirectory","versions":["2016-05-10*"]},"cloudformation":{"name":"CloudFormation","cors":true},"cloudfront":{"name":"CloudFront","versions":["2013-05-12*","2013-11-11*","2014-05-31*","2014-10-21*","2014-11-06*","2015-04-17*","2015-07-27*","2015-09-17*","2016-01-13*","2016-01-28*","2016-08-01*","2016-08-20*","2016-09-07*","2016-09-29*","2016-11-25*","2017-03-25*","2017-10-30*","2018-06-18*"],"cors":true},"cloudhsm":{"name":"CloudHSM","cors":true},"cloudsearch":{"name":"CloudSearch"},"cloudsearchdomain":{"name":"CloudSearchDomain"},"cloudtrail":{"name":"CloudTrail","cors":true},"cloudwatch":{"prefix":"monitoring","name":"CloudWatch","cors":true},"cloudwatchevents":{"prefix":"events","name":"CloudWatchEvents","versions":["2014-02-03*"],"cors":true},"cloudwatchlogs":{"prefix":"logs","name":"CloudWatchLogs","cors":true},"codebuild":{"name":"CodeBuild","cors":true},"codecommit":{"name":"CodeCommit","cors":true},"codedeploy":{"name":"CodeDeploy","cors":true},"codepipeline":{"name":"CodePipeline","cors":true},"cognitoidentity":{"prefix":"cognito-identity","name":"CognitoIdentity","cors":true},"cognitoidentityserviceprovider":{"prefix":"cognito-idp","name":"CognitoIdentityServiceProvider","cors":true},"cognitosync":{"prefix":"cognito-sync","name":"CognitoSync","cors":true},"configservice":{"prefix":"config","name":"ConfigService","cors":true},"cur":{"name":"CUR","cors":true},"datapipeline":{"name":"DataPipeline"},"devicefarm":{"name":"DeviceFarm","cors":true},"directconnect":{"name":"DirectConnect","cors":true},"directoryservice":{"prefix":"ds","name":"DirectoryService"},"discovery":{"name":"Discovery"},"dms":{"name":"DMS"},"dynamodb":{"name":"DynamoDB","cors":true},"dynamodbstreams":{"prefix":"streams.dynamodb","name":"DynamoDBStreams","cors":true},"ec2":{"name":"EC2","versions":["2013-06-15*","2013-10-15*","2014-02-01*","2014-05-01*","2014-06-15*","2014-09-01*","2014-10-01*","2015-03-01*","2015-04-15*","2015-10-01*","2016-04-01*","2016-09-15*"],"cors":true},"ecr":{"name":"ECR","cors":true},"ecs":{"name":"ECS","cors":true},"efs":{"prefix":"elasticfilesystem","name":"EFS","cors":true},"elasticache":{"name":"ElastiCache","versions":["2012-11-15*","2014-03-24*","2014-07-15*","2014-09-30*"],"cors":true},"elasticbeanstalk":{"name":"ElasticBeanstalk","cors":true},"elb":{"prefix":"elasticloadbalancing","name":"ELB","cors":true},"elbv2":{"prefix":"elasticloadbalancingv2","name":"ELBv2","cors":true},"emr":{"prefix":"elasticmapreduce","name":"EMR","cors":true},"es":{"name":"ES"},"elastictranscoder":{"name":"ElasticTranscoder","cors":true},"firehose":{"name":"Firehose","cors":true},"gamelift":{"name":"GameLift","cors":true},"glacier":{"name":"Glacier"},"health":{"name":"Health"},"iam":{"name":"IAM","cors":true},"importexport":{"name":"ImportExport"},"inspector":{"name":"Inspector","versions":["2015-08-18*"],"cors":true},"iot":{"name":"Iot","cors":true},"iotdata":{"prefix":"iot-data","name":"IotData","cors":true},"kinesis":{"name":"Kinesis","cors":true},"kinesisanalytics":{"name":"KinesisAnalytics"},"kms":{"name":"KMS","cors":true},"lambda":{"name":"Lambda","cors":true},"lexruntime":{"prefix":"runtime.lex","name":"LexRuntime","cors":true},"lightsail":{"name":"Lightsail"},"machinelearning":{"name":"MachineLearning","cors":true},"marketplacecommerceanalytics":{"name":"MarketplaceCommerceAnalytics","cors":true},"marketplacemetering":{"prefix":"meteringmarketplace","name":"MarketplaceMetering"},"mturk":{"prefix":"mturk-requester","name":"MTurk","cors":true},"mobileanalytics":{"name":"MobileAnalytics","cors":true},"opsworks":{"name":"OpsWorks","cors":true},"opsworkscm":{"name":"OpsWorksCM"},"organizations":{"name":"Organizations"},"pinpoint":{"name":"Pinpoint"},"polly":{"name":"Polly","cors":true},"rds":{"name":"RDS","versions":["2014-09-01*"],"cors":true},"redshift":{"name":"Redshift","cors":true},"rekognition":{"name":"Rekognition","cors":true},"resourcegroupstaggingapi":{"name":"ResourceGroupsTaggingAPI"},"route53":{"name":"Route53","cors":true},"route53domains":{"name":"Route53Domains","cors":true},"s3":{"name":"S3","dualstackAvailable":true,"cors":true},"s3control":{"name":"S3Control","dualstackAvailable":true},"servicecatalog":{"name":"ServiceCatalog","cors":true},"ses":{"prefix":"email","name":"SES","cors":true},"shield":{"name":"Shield"},"simpledb":{"prefix":"sdb","name":"SimpleDB"},"sms":{"name":"SMS"},"snowball":{"name":"Snowball"},"sns":{"name":"SNS","cors":true},"sqs":{"name":"SQS","cors":true},"ssm":{"name":"SSM","cors":true},"storagegateway":{"name":"StorageGateway","cors":true},"stepfunctions":{"prefix":"states","name":"StepFunctions"},"sts":{"name":"STS","cors":true},"support":{"name":"Support"},"swf":{"name":"SWF"},"xray":{"name":"XRay"},"waf":{"name":"WAF","cors":true},"wafregional":{"prefix":"waf-regional","name":"WAFRegional"},"workdocs":{"name":"WorkDocs","cors":true},"workspaces":{"name":"WorkSpaces"},"codestar":{"name":"CodeStar"},"lexmodelbuildingservice":{"prefix":"lex-models","name":"LexModelBuildingService","cors":true},"marketplaceentitlementservice":{"prefix":"entitlement.marketplace","name":"MarketplaceEntitlementService"},"athena":{"name":"Athena"},"greengrass":{"name":"Greengrass"},"dax":{"name":"DAX"},"migrationhub":{"prefix":"AWSMigrationHub","name":"MigrationHub"},"cloudhsmv2":{"name":"CloudHSMV2"},"glue":{"name":"Glue"},"mobile":{"name":"Mobile"},"pricing":{"name":"Pricing","cors":true},"costexplorer":{"prefix":"ce","name":"CostExplorer"},"mediaconvert":{"name":"MediaConvert"},"medialive":{"name":"MediaLive"},"mediapackage":{"name":"MediaPackage"},"mediastore":{"name":"MediaStore"},"mediastoredata":{"prefix":"mediastore-data","name":"MediaStoreData","cors":true},"appsync":{"name":"AppSync"},"guardduty":{"name":"GuardDuty"},"mq":{"name":"MQ"},"comprehend":{"name":"Comprehend","cors":true},"iotjobsdataplane":{"prefix":"iot-jobs-data","name":"IoTJobsDataPlane"},"kinesisvideoarchivedmedia":{"prefix":"kinesis-video-archived-media","name":"KinesisVideoArchivedMedia","cors":true},"kinesisvideomedia":{"prefix":"kinesis-video-media","name":"KinesisVideoMedia","cors":true},"kinesisvideo":{"name":"KinesisVideo","cors":true},"sagemakerruntime":{"prefix":"runtime.sagemaker","name":"SageMakerRuntime"},"sagemaker":{"name":"SageMaker"},"translate":{"name":"Translate","cors":true},"resourcegroups":{"prefix":"resource-groups","name":"ResourceGroups","cors":true},"alexaforbusiness":{"name":"AlexaForBusiness"},"cloud9":{"name":"Cloud9"},"serverlessapplicationrepository":{"prefix":"serverlessrepo","name":"ServerlessApplicationRepository"},"servicediscovery":{"name":"ServiceDiscovery"},"workmail":{"name":"WorkMail"},"autoscalingplans":{"prefix":"autoscaling-plans","name":"AutoScalingPlans"},"transcribeservice":{"prefix":"transcribe","name":"TranscribeService"},"connect":{"name":"Connect"},"acmpca":{"prefix":"acm-pca","name":"ACMPCA"},"fms":{"name":"FMS"},"secretsmanager":{"name":"SecretsManager","cors":true},"iotanalytics":{"name":"IoTAnalytics"},"iot1clickdevicesservice":{"prefix":"iot1click-devices","name":"IoT1ClickDevicesService"},"iot1clickprojects":{"prefix":"iot1click-projects","name":"IoT1ClickProjects"},"pi":{"name":"PI"},"neptune":{"name":"Neptune"},"mediatailor":{"name":"MediaTailor"},"eks":{"name":"EKS"},"macie":{"name":"Macie"},"dlm":{"name":"DLM"},"signer":{"name":"Signer"},"chime":{"name":"Chime"},"pinpointemail":{"prefix":"pinpoint-email","name":"PinpointEmail"},"ram":{"name":"RAM"},"route53resolver":{"name":"Route53Resolver"},"pinpointsmsvoice":{"prefix":"sms-voice","name":"PinpointSMSVoice"},"quicksight":{"name":"QuickSight"},"rdsdataservice":{"prefix":"rds-data","name":"RDSDataService"},"amplify":{"name":"Amplify"},"datasync":{"name":"DataSync"},"robomaker":{"name":"RoboMaker"},"transfer":{"name":"Transfer"},"globalaccelerator":{"name":"GlobalAccelerator"},"comprehendmedical":{"name":"ComprehendMedical","cors":true},"kinesisanalyticsv2":{"name":"KinesisAnalyticsV2"},"mediaconnect":{"name":"MediaConnect"},"fsx":{"name":"FSx"},"securityhub":{"name":"SecurityHub"},"appmesh":{"name":"AppMesh","versions":["2018-10-01*"]},"licensemanager":{"prefix":"license-manager","name":"LicenseManager"},"kafka":{"name":"Kafka"},"apigatewaymanagementapi":{"name":"ApiGatewayManagementApi"},"apigatewayv2":{"name":"ApiGatewayV2"},"docdb":{"name":"DocDB"},"backup":{"name":"Backup"},"worklink":{"name":"WorkLink"},"textract":{"name":"Textract"}}
1587
1588/***/ }),
1589/* 8 */
1590/***/ (function(module, exports, __webpack_require__) {
1591
1592 var v1 = __webpack_require__(9);
1593 var v4 = __webpack_require__(12);
1594
1595 var uuid = v4;
1596 uuid.v1 = v1;
1597 uuid.v4 = v4;
1598
1599 module.exports = uuid;
1600
1601
1602/***/ }),
1603/* 9 */
1604/***/ (function(module, exports, __webpack_require__) {
1605
1606 var rng = __webpack_require__(10);
1607 var bytesToUuid = __webpack_require__(11);
1608
1609 // **`v1()` - Generate time-based UUID**
1610 //
1611 // Inspired by https://github.com/LiosK/UUID.js
1612 // and http://docs.python.org/library/uuid.html
1613
1614 var _nodeId;
1615 var _clockseq;
1616
1617 // Previous uuid creation time
1618 var _lastMSecs = 0;
1619 var _lastNSecs = 0;
1620
1621 // See https://github.com/broofa/node-uuid for API details
1622 function v1(options, buf, offset) {
1623 var i = buf && offset || 0;
1624 var b = buf || [];
1625
1626 options = options || {};
1627 var node = options.node || _nodeId;
1628 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
1629
1630 // node and clockseq need to be initialized to random values if they're not
1631 // specified. We do this lazily to minimize issues related to insufficient
1632 // system entropy. See #189
1633 if (node == null || clockseq == null) {
1634 var seedBytes = rng();
1635 if (node == null) {
1636 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
1637 node = _nodeId = [
1638 seedBytes[0] | 0x01,
1639 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
1640 ];
1641 }
1642 if (clockseq == null) {
1643 // Per 4.2.2, randomize (14 bit) clockseq
1644 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
1645 }
1646 }
1647
1648 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
1649 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
1650 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
1651 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
1652 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
1653
1654 // Per 4.2.1.2, use count of uuid's generated during the current clock
1655 // cycle to simulate higher resolution clock
1656 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
1657
1658 // Time since last uuid creation (in msecs)
1659 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
1660
1661 // Per 4.2.1.2, Bump clockseq on clock regression
1662 if (dt < 0 && options.clockseq === undefined) {
1663 clockseq = clockseq + 1 & 0x3fff;
1664 }
1665
1666 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
1667 // time interval
1668 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
1669 nsecs = 0;
1670 }
1671
1672 // Per 4.2.1.2 Throw error if too many uuids are requested
1673 if (nsecs >= 10000) {
1674 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
1675 }
1676
1677 _lastMSecs = msecs;
1678 _lastNSecs = nsecs;
1679 _clockseq = clockseq;
1680
1681 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
1682 msecs += 12219292800000;
1683
1684 // `time_low`
1685 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
1686 b[i++] = tl >>> 24 & 0xff;
1687 b[i++] = tl >>> 16 & 0xff;
1688 b[i++] = tl >>> 8 & 0xff;
1689 b[i++] = tl & 0xff;
1690
1691 // `time_mid`
1692 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
1693 b[i++] = tmh >>> 8 & 0xff;
1694 b[i++] = tmh & 0xff;
1695
1696 // `time_high_and_version`
1697 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
1698 b[i++] = tmh >>> 16 & 0xff;
1699
1700 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
1701 b[i++] = clockseq >>> 8 | 0x80;
1702
1703 // `clock_seq_low`
1704 b[i++] = clockseq & 0xff;
1705
1706 // `node`
1707 for (var n = 0; n < 6; ++n) {
1708 b[i + n] = node[n];
1709 }
1710
1711 return buf ? buf : bytesToUuid(b);
1712 }
1713
1714 module.exports = v1;
1715
1716
1717/***/ }),
1718/* 10 */
1719/***/ (function(module, exports) {
1720
1721 // Unique ID creation requires a high quality random # generator. In the
1722 // browser this is a little complicated due to unknown quality of Math.random()
1723 // and inconsistent support for the `crypto` API. We do the best we can via
1724 // feature-detection
1725
1726 // getRandomValues needs to be invoked in a context where "this" is a Crypto
1727 // implementation. Also, find the complete implementation of crypto on IE11.
1728 var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
1729 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
1730
1731 if (getRandomValues) {
1732 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
1733 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
1734
1735 module.exports = function whatwgRNG() {
1736 getRandomValues(rnds8);
1737 return rnds8;
1738 };
1739 } else {
1740 // Math.random()-based (RNG)
1741 //
1742 // If all else fails, use Math.random(). It's fast, but is of unspecified
1743 // quality.
1744 var rnds = new Array(16);
1745
1746 module.exports = function mathRNG() {
1747 for (var i = 0, r; i < 16; i++) {
1748 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
1749 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
1750 }
1751
1752 return rnds;
1753 };
1754 }
1755
1756
1757/***/ }),
1758/* 11 */
1759/***/ (function(module, exports) {
1760
1761 /**
1762 * Convert array of 16 byte values to UUID string format of the form:
1763 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1764 */
1765 var byteToHex = [];
1766 for (var i = 0; i < 256; ++i) {
1767 byteToHex[i] = (i + 0x100).toString(16).substr(1);
1768 }
1769
1770 function bytesToUuid(buf, offset) {
1771 var i = offset || 0;
1772 var bth = byteToHex;
1773 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
1774 return ([bth[buf[i++]], bth[buf[i++]],
1775 bth[buf[i++]], bth[buf[i++]], '-',
1776 bth[buf[i++]], bth[buf[i++]], '-',
1777 bth[buf[i++]], bth[buf[i++]], '-',
1778 bth[buf[i++]], bth[buf[i++]], '-',
1779 bth[buf[i++]], bth[buf[i++]],
1780 bth[buf[i++]], bth[buf[i++]],
1781 bth[buf[i++]], bth[buf[i++]]]).join('');
1782 }
1783
1784 module.exports = bytesToUuid;
1785
1786
1787/***/ }),
1788/* 12 */
1789/***/ (function(module, exports, __webpack_require__) {
1790
1791 var rng = __webpack_require__(10);
1792 var bytesToUuid = __webpack_require__(11);
1793
1794 function v4(options, buf, offset) {
1795 var i = buf && offset || 0;
1796
1797 if (typeof(options) == 'string') {
1798 buf = options === 'binary' ? new Array(16) : null;
1799 options = null;
1800 }
1801 options = options || {};
1802
1803 var rnds = options.random || (options.rng || rng)();
1804
1805 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1806 rnds[6] = (rnds[6] & 0x0f) | 0x40;
1807 rnds[8] = (rnds[8] & 0x3f) | 0x80;
1808
1809 // Copy bytes to buffer, if provided
1810 if (buf) {
1811 for (var ii = 0; ii < 16; ++ii) {
1812 buf[i + ii] = rnds[ii];
1813 }
1814 }
1815
1816 return buf || bytesToUuid(rnds);
1817 }
1818
1819 module.exports = v4;
1820
1821
1822/***/ }),
1823/* 13 */
1824/***/ (function(module, exports, __webpack_require__) {
1825
1826 var util = __webpack_require__(2);
1827 var JsonBuilder = __webpack_require__(14);
1828 var JsonParser = __webpack_require__(15);
1829 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
1830
1831 function buildRequest(req) {
1832 var httpRequest = req.httpRequest;
1833 var api = req.service.api;
1834 var target = api.targetPrefix + '.' + api.operations[req.operation].name;
1835 var version = api.jsonVersion || '1.0';
1836 var input = api.operations[req.operation].input;
1837 var builder = new JsonBuilder();
1838
1839 if (version === 1) version = '1.0';
1840 httpRequest.body = builder.build(req.params || {}, input);
1841 httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version;
1842 httpRequest.headers['X-Amz-Target'] = target;
1843
1844 populateHostPrefix(req);
1845 }
1846
1847 function extractError(resp) {
1848 var error = {};
1849 var httpResponse = resp.httpResponse;
1850
1851 error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError';
1852 if (typeof error.code === 'string') {
1853 error.code = error.code.split(':')[0];
1854 }
1855
1856 if (httpResponse.body.length > 0) {
1857 try {
1858 var e = JSON.parse(httpResponse.body.toString());
1859 if (e.__type || e.code) {
1860 error.code = (e.__type || e.code).split('#').pop();
1861 }
1862 if (error.code === 'RequestEntityTooLarge') {
1863 error.message = 'Request body must be less than 1 MB';
1864 } else {
1865 error.message = (e.message || e.Message || null);
1866 }
1867 } catch (e) {
1868 error.statusCode = httpResponse.statusCode;
1869 error.message = httpResponse.statusMessage;
1870 }
1871 } else {
1872 error.statusCode = httpResponse.statusCode;
1873 error.message = httpResponse.statusCode.toString();
1874 }
1875
1876 resp.error = util.error(new Error(), error);
1877 }
1878
1879 function extractData(resp) {
1880 var body = resp.httpResponse.body.toString() || '{}';
1881 if (resp.request.service.config.convertResponseTypes === false) {
1882 resp.data = JSON.parse(body);
1883 } else {
1884 var operation = resp.request.service.api.operations[resp.request.operation];
1885 var shape = operation.output || {};
1886 var parser = new JsonParser();
1887 resp.data = parser.parse(body, shape);
1888 }
1889 }
1890
1891 /**
1892 * @api private
1893 */
1894 module.exports = {
1895 buildRequest: buildRequest,
1896 extractError: extractError,
1897 extractData: extractData
1898 };
1899
1900
1901/***/ }),
1902/* 14 */
1903/***/ (function(module, exports, __webpack_require__) {
1904
1905 var util = __webpack_require__(2);
1906
1907 function JsonBuilder() { }
1908
1909 JsonBuilder.prototype.build = function(value, shape) {
1910 return JSON.stringify(translate(value, shape));
1911 };
1912
1913 function translate(value, shape) {
1914 if (!shape || value === undefined || value === null) return undefined;
1915
1916 switch (shape.type) {
1917 case 'structure': return translateStructure(value, shape);
1918 case 'map': return translateMap(value, shape);
1919 case 'list': return translateList(value, shape);
1920 default: return translateScalar(value, shape);
1921 }
1922 }
1923
1924 function translateStructure(structure, shape) {
1925 var struct = {};
1926 util.each(structure, function(name, value) {
1927 var memberShape = shape.members[name];
1928 if (memberShape) {
1929 if (memberShape.location !== 'body') return;
1930 var locationName = memberShape.isLocationName ? memberShape.name : name;
1931 var result = translate(value, memberShape);
1932 if (result !== undefined) struct[locationName] = result;
1933 }
1934 });
1935 return struct;
1936 }
1937
1938 function translateList(list, shape) {
1939 var out = [];
1940 util.arrayEach(list, function(value) {
1941 var result = translate(value, shape.member);
1942 if (result !== undefined) out.push(result);
1943 });
1944 return out;
1945 }
1946
1947 function translateMap(map, shape) {
1948 var out = {};
1949 util.each(map, function(key, value) {
1950 var result = translate(value, shape.value);
1951 if (result !== undefined) out[key] = result;
1952 });
1953 return out;
1954 }
1955
1956 function translateScalar(value, shape) {
1957 return shape.toWireFormat(value);
1958 }
1959
1960 /**
1961 * @api private
1962 */
1963 module.exports = JsonBuilder;
1964
1965
1966/***/ }),
1967/* 15 */
1968/***/ (function(module, exports, __webpack_require__) {
1969
1970 var util = __webpack_require__(2);
1971
1972 function JsonParser() { }
1973
1974 JsonParser.prototype.parse = function(value, shape) {
1975 return translate(JSON.parse(value), shape);
1976 };
1977
1978 function translate(value, shape) {
1979 if (!shape || value === undefined) return undefined;
1980
1981 switch (shape.type) {
1982 case 'structure': return translateStructure(value, shape);
1983 case 'map': return translateMap(value, shape);
1984 case 'list': return translateList(value, shape);
1985 default: return translateScalar(value, shape);
1986 }
1987 }
1988
1989 function translateStructure(structure, shape) {
1990 if (structure == null) return undefined;
1991
1992 var struct = {};
1993 var shapeMembers = shape.members;
1994 util.each(shapeMembers, function(name, memberShape) {
1995 var locationName = memberShape.isLocationName ? memberShape.name : name;
1996 if (Object.prototype.hasOwnProperty.call(structure, locationName)) {
1997 var value = structure[locationName];
1998 var result = translate(value, memberShape);
1999 if (result !== undefined) struct[name] = result;
2000 }
2001 });
2002 return struct;
2003 }
2004
2005 function translateList(list, shape) {
2006 if (list == null) return undefined;
2007
2008 var out = [];
2009 util.arrayEach(list, function(value) {
2010 var result = translate(value, shape.member);
2011 if (result === undefined) out.push(null);
2012 else out.push(result);
2013 });
2014 return out;
2015 }
2016
2017 function translateMap(map, shape) {
2018 if (map == null) return undefined;
2019
2020 var out = {};
2021 util.each(map, function(key, value) {
2022 var result = translate(value, shape.value);
2023 if (result === undefined) out[key] = null;
2024 else out[key] = result;
2025 });
2026 return out;
2027 }
2028
2029 function translateScalar(value, shape) {
2030 return shape.toType(value);
2031 }
2032
2033 /**
2034 * @api private
2035 */
2036 module.exports = JsonParser;
2037
2038
2039/***/ }),
2040/* 16 */
2041/***/ (function(module, exports, __webpack_require__) {
2042
2043 var util = __webpack_require__(2);
2044 var AWS = __webpack_require__(1);
2045
2046 /**
2047 * Prepend prefix defined by API model to endpoint that's already
2048 * constructed. This feature does not apply to operations using
2049 * endpoint discovery and can be disabled.
2050 * @api private
2051 */
2052 function populateHostPrefix(request) {
2053 var enabled = request.service.config.hostPrefixEnabled;
2054 if (!enabled) return request;
2055 var operationModel = request.service.api.operations[request.operation];
2056 //don't marshal host prefix when operation has endpoint discovery traits
2057 if (hasEndpointDiscover(request)) return request;
2058 if (operationModel.endpoint && operationModel.endpoint.hostPrefix) {
2059 var hostPrefixNotation = operationModel.endpoint.hostPrefix;
2060 var hostPrefix = expandHostPrefix(hostPrefixNotation, request.params, operationModel.input);
2061 prependEndpointPrefix(request.httpRequest.endpoint, hostPrefix);
2062 validateHostname(request.httpRequest.endpoint.hostname);
2063 }
2064 return request;
2065 }
2066
2067 /**
2068 * @api private
2069 */
2070 function hasEndpointDiscover(request) {
2071 var api = request.service.api;
2072 var operationModel = api.operations[request.operation];
2073 var isEndpointOperation = api.endpointOperation && (api.endpointOperation === util.string.lowerFirst(operationModel.name));
2074 return (operationModel.endpointDiscoveryRequired !== 'NULL' || isEndpointOperation === true);
2075 }
2076
2077 /**
2078 * @api private
2079 */
2080 function expandHostPrefix(hostPrefixNotation, params, shape) {
2081 util.each(shape.members, function(name, member) {
2082 if (member.hostLabel === true) {
2083 if (typeof params[name] !== 'string' || params[name] === '') {
2084 throw util.error(new Error(), {
2085 message: 'Parameter ' + name + ' should be a non-empty string.',
2086 code: 'InvalidParameter'
2087 });
2088 }
2089 var regex = new RegExp('\\{' + name + '\\}', 'g');
2090 hostPrefixNotation = hostPrefixNotation.replace(regex, params[name]);
2091 }
2092 });
2093 return hostPrefixNotation;
2094 }
2095
2096 /**
2097 * @api private
2098 */
2099 function prependEndpointPrefix(endpoint, prefix) {
2100 if (endpoint.host) {
2101 endpoint.host = prefix + endpoint.host;
2102 }
2103 if (endpoint.hostname) {
2104 endpoint.hostname = prefix + endpoint.hostname;
2105 }
2106 }
2107
2108 /**
2109 * @api private
2110 */
2111 function validateHostname(hostname) {
2112 var labels = hostname.split('.');
2113 //Reference: https://tools.ietf.org/html/rfc1123#section-2
2114 var hostPattern = /^[a-zA-Z0-9]{1}$|^[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]$/;
2115 util.arrayEach(labels, function(label) {
2116 if (!label.length || label.length < 1 || label.length > 63) {
2117 throw util.error(new Error(), {
2118 code: 'ValidationError',
2119 message: 'Hostname label length should be between 1 to 63 characters, inclusive.'
2120 });
2121 }
2122 if (!hostPattern.test(label)) {
2123 throw AWS.util.error(new Error(),
2124 {code: 'ValidationError', message: label + ' is not hostname compatible.'});
2125 }
2126 });
2127 }
2128
2129 module.exports = {
2130 populateHostPrefix: populateHostPrefix
2131 };
2132
2133
2134/***/ }),
2135/* 17 */
2136/***/ (function(module, exports, __webpack_require__) {
2137
2138 var AWS = __webpack_require__(1);
2139 var util = __webpack_require__(2);
2140 var QueryParamSerializer = __webpack_require__(18);
2141 var Shape = __webpack_require__(19);
2142 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2143
2144 function buildRequest(req) {
2145 var operation = req.service.api.operations[req.operation];
2146 var httpRequest = req.httpRequest;
2147 httpRequest.headers['Content-Type'] =
2148 'application/x-www-form-urlencoded; charset=utf-8';
2149 httpRequest.params = {
2150 Version: req.service.api.apiVersion,
2151 Action: operation.name
2152 };
2153
2154 // convert the request parameters into a list of query params,
2155 // e.g. Deeply.NestedParam.0.Name=value
2156 var builder = new QueryParamSerializer();
2157 builder.serialize(req.params, operation.input, function(name, value) {
2158 httpRequest.params[name] = value;
2159 });
2160 httpRequest.body = util.queryParamsToString(httpRequest.params);
2161
2162 populateHostPrefix(req);
2163 }
2164
2165 function extractError(resp) {
2166 var data, body = resp.httpResponse.body.toString();
2167 if (body.match('<UnknownOperationException')) {
2168 data = {
2169 Code: 'UnknownOperation',
2170 Message: 'Unknown operation ' + resp.request.operation
2171 };
2172 } else {
2173 try {
2174 data = new AWS.XML.Parser().parse(body);
2175 } catch (e) {
2176 data = {
2177 Code: resp.httpResponse.statusCode,
2178 Message: resp.httpResponse.statusMessage
2179 };
2180 }
2181 }
2182
2183 if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
2184 if (data.Errors) data = data.Errors;
2185 if (data.Error) data = data.Error;
2186 if (data.Code) {
2187 resp.error = util.error(new Error(), {
2188 code: data.Code,
2189 message: data.Message
2190 });
2191 } else {
2192 resp.error = util.error(new Error(), {
2193 code: resp.httpResponse.statusCode,
2194 message: null
2195 });
2196 }
2197 }
2198
2199 function extractData(resp) {
2200 var req = resp.request;
2201 var operation = req.service.api.operations[req.operation];
2202 var shape = operation.output || {};
2203 var origRules = shape;
2204
2205 if (origRules.resultWrapper) {
2206 var tmp = Shape.create({type: 'structure'});
2207 tmp.members[origRules.resultWrapper] = shape;
2208 tmp.memberNames = [origRules.resultWrapper];
2209 util.property(shape, 'name', shape.resultWrapper);
2210 shape = tmp;
2211 }
2212
2213 var parser = new AWS.XML.Parser();
2214
2215 // TODO: Refactor XML Parser to parse RequestId from response.
2216 if (shape && shape.members && !shape.members._XAMZRequestId) {
2217 var requestIdShape = Shape.create(
2218 { type: 'string' },
2219 { api: { protocol: 'query' } },
2220 'requestId'
2221 );
2222 shape.members._XAMZRequestId = requestIdShape;
2223 }
2224
2225 var data = parser.parse(resp.httpResponse.body.toString(), shape);
2226 resp.requestId = data._XAMZRequestId || data.requestId;
2227
2228 if (data._XAMZRequestId) delete data._XAMZRequestId;
2229
2230 if (origRules.resultWrapper) {
2231 if (data[origRules.resultWrapper]) {
2232 util.update(data, data[origRules.resultWrapper]);
2233 delete data[origRules.resultWrapper];
2234 }
2235 }
2236
2237 resp.data = data;
2238 }
2239
2240 /**
2241 * @api private
2242 */
2243 module.exports = {
2244 buildRequest: buildRequest,
2245 extractError: extractError,
2246 extractData: extractData
2247 };
2248
2249
2250/***/ }),
2251/* 18 */
2252/***/ (function(module, exports, __webpack_require__) {
2253
2254 var util = __webpack_require__(2);
2255
2256 function QueryParamSerializer() {
2257 }
2258
2259 QueryParamSerializer.prototype.serialize = function(params, shape, fn) {
2260 serializeStructure('', params, shape, fn);
2261 };
2262
2263 function ucfirst(shape) {
2264 if (shape.isQueryName || shape.api.protocol !== 'ec2') {
2265 return shape.name;
2266 } else {
2267 return shape.name[0].toUpperCase() + shape.name.substr(1);
2268 }
2269 }
2270
2271 function serializeStructure(prefix, struct, rules, fn) {
2272 util.each(rules.members, function(name, member) {
2273 var value = struct[name];
2274 if (value === null || value === undefined) return;
2275
2276 var memberName = ucfirst(member);
2277 memberName = prefix ? prefix + '.' + memberName : memberName;
2278 serializeMember(memberName, value, member, fn);
2279 });
2280 }
2281
2282 function serializeMap(name, map, rules, fn) {
2283 var i = 1;
2284 util.each(map, function (key, value) {
2285 var prefix = rules.flattened ? '.' : '.entry.';
2286 var position = prefix + (i++) + '.';
2287 var keyName = position + (rules.key.name || 'key');
2288 var valueName = position + (rules.value.name || 'value');
2289 serializeMember(name + keyName, key, rules.key, fn);
2290 serializeMember(name + valueName, value, rules.value, fn);
2291 });
2292 }
2293
2294 function serializeList(name, list, rules, fn) {
2295 var memberRules = rules.member || {};
2296
2297 if (list.length === 0) {
2298 fn.call(this, name, null);
2299 return;
2300 }
2301
2302 util.arrayEach(list, function (v, n) {
2303 var suffix = '.' + (n + 1);
2304 if (rules.api.protocol === 'ec2') {
2305 // Do nothing for EC2
2306 suffix = suffix + ''; // make linter happy
2307 } else if (rules.flattened) {
2308 if (memberRules.name) {
2309 var parts = name.split('.');
2310 parts.pop();
2311 parts.push(ucfirst(memberRules));
2312 name = parts.join('.');
2313 }
2314 } else {
2315 suffix = '.' + (memberRules.name ? memberRules.name : 'member') + suffix;
2316 }
2317 serializeMember(name + suffix, v, memberRules, fn);
2318 });
2319 }
2320
2321 function serializeMember(name, value, rules, fn) {
2322 if (value === null || value === undefined) return;
2323 if (rules.type === 'structure') {
2324 serializeStructure(name, value, rules, fn);
2325 } else if (rules.type === 'list') {
2326 serializeList(name, value, rules, fn);
2327 } else if (rules.type === 'map') {
2328 serializeMap(name, value, rules, fn);
2329 } else {
2330 fn(name, rules.toWireFormat(value).toString());
2331 }
2332 }
2333
2334 /**
2335 * @api private
2336 */
2337 module.exports = QueryParamSerializer;
2338
2339
2340/***/ }),
2341/* 19 */
2342/***/ (function(module, exports, __webpack_require__) {
2343
2344 var Collection = __webpack_require__(20);
2345
2346 var util = __webpack_require__(2);
2347
2348 function property(obj, name, value) {
2349 if (value !== null && value !== undefined) {
2350 util.property.apply(this, arguments);
2351 }
2352 }
2353
2354 function memoizedProperty(obj, name) {
2355 if (!obj.constructor.prototype[name]) {
2356 util.memoizedProperty.apply(this, arguments);
2357 }
2358 }
2359
2360 function Shape(shape, options, memberName) {
2361 options = options || {};
2362
2363 property(this, 'shape', shape.shape);
2364 property(this, 'api', options.api, false);
2365 property(this, 'type', shape.type);
2366 property(this, 'enum', shape.enum);
2367 property(this, 'min', shape.min);
2368 property(this, 'max', shape.max);
2369 property(this, 'pattern', shape.pattern);
2370 property(this, 'location', shape.location || this.location || 'body');
2371 property(this, 'name', this.name || shape.xmlName || shape.queryName ||
2372 shape.locationName || memberName);
2373 property(this, 'isStreaming', shape.streaming || this.isStreaming || false);
2374 property(this, 'isComposite', shape.isComposite || false);
2375 property(this, 'isShape', true, false);
2376 property(this, 'isQueryName', Boolean(shape.queryName), false);
2377 property(this, 'isLocationName', Boolean(shape.locationName), false);
2378 property(this, 'isIdempotent', shape.idempotencyToken === true);
2379 property(this, 'isJsonValue', shape.jsonvalue === true);
2380 property(this, 'isSensitive', shape.sensitive === true || shape.prototype && shape.prototype.sensitive === true);
2381 property(this, 'isEventStream', Boolean(shape.eventstream), false);
2382 property(this, 'isEvent', Boolean(shape.event), false);
2383 property(this, 'isEventPayload', Boolean(shape.eventpayload), false);
2384 property(this, 'isEventHeader', Boolean(shape.eventheader), false);
2385 property(this, 'isTimestampFormatSet', Boolean(shape.timestampFormat) || shape.prototype && shape.prototype.isTimestampFormatSet === true, false);
2386 property(this, 'endpointDiscoveryId', Boolean(shape.endpointdiscoveryid), false);
2387 property(this, 'hostLabel', Boolean(shape.hostLabel), false);
2388
2389 if (options.documentation) {
2390 property(this, 'documentation', shape.documentation);
2391 property(this, 'documentationUrl', shape.documentationUrl);
2392 }
2393
2394 if (shape.xmlAttribute) {
2395 property(this, 'isXmlAttribute', shape.xmlAttribute || false);
2396 }
2397
2398 // type conversion and parsing
2399 property(this, 'defaultValue', null);
2400 this.toWireFormat = function(value) {
2401 if (value === null || value === undefined) return '';
2402 return value;
2403 };
2404 this.toType = function(value) { return value; };
2405 }
2406
2407 /**
2408 * @api private
2409 */
2410 Shape.normalizedTypes = {
2411 character: 'string',
2412 double: 'float',
2413 long: 'integer',
2414 short: 'integer',
2415 biginteger: 'integer',
2416 bigdecimal: 'float',
2417 blob: 'binary'
2418 };
2419
2420 /**
2421 * @api private
2422 */
2423 Shape.types = {
2424 'structure': StructureShape,
2425 'list': ListShape,
2426 'map': MapShape,
2427 'boolean': BooleanShape,
2428 'timestamp': TimestampShape,
2429 'float': FloatShape,
2430 'integer': IntegerShape,
2431 'string': StringShape,
2432 'base64': Base64Shape,
2433 'binary': BinaryShape
2434 };
2435
2436 Shape.resolve = function resolve(shape, options) {
2437 if (shape.shape) {
2438 var refShape = options.api.shapes[shape.shape];
2439 if (!refShape) {
2440 throw new Error('Cannot find shape reference: ' + shape.shape);
2441 }
2442
2443 return refShape;
2444 } else {
2445 return null;
2446 }
2447 };
2448
2449 Shape.create = function create(shape, options, memberName) {
2450 if (shape.isShape) return shape;
2451
2452 var refShape = Shape.resolve(shape, options);
2453 if (refShape) {
2454 var filteredKeys = Object.keys(shape);
2455 if (!options.documentation) {
2456 filteredKeys = filteredKeys.filter(function(name) {
2457 return !name.match(/documentation/);
2458 });
2459 }
2460
2461 // create an inline shape with extra members
2462 var InlineShape = function() {
2463 refShape.constructor.call(this, shape, options, memberName);
2464 };
2465 InlineShape.prototype = refShape;
2466 return new InlineShape();
2467 } else {
2468 // set type if not set
2469 if (!shape.type) {
2470 if (shape.members) shape.type = 'structure';
2471 else if (shape.member) shape.type = 'list';
2472 else if (shape.key) shape.type = 'map';
2473 else shape.type = 'string';
2474 }
2475
2476 // normalize types
2477 var origType = shape.type;
2478 if (Shape.normalizedTypes[shape.type]) {
2479 shape.type = Shape.normalizedTypes[shape.type];
2480 }
2481
2482 if (Shape.types[shape.type]) {
2483 return new Shape.types[shape.type](shape, options, memberName);
2484 } else {
2485 throw new Error('Unrecognized shape type: ' + origType);
2486 }
2487 }
2488 };
2489
2490 function CompositeShape(shape) {
2491 Shape.apply(this, arguments);
2492 property(this, 'isComposite', true);
2493
2494 if (shape.flattened) {
2495 property(this, 'flattened', shape.flattened || false);
2496 }
2497 }
2498
2499 function StructureShape(shape, options) {
2500 var self = this;
2501 var requiredMap = null, firstInit = !this.isShape;
2502
2503 CompositeShape.apply(this, arguments);
2504
2505 if (firstInit) {
2506 property(this, 'defaultValue', function() { return {}; });
2507 property(this, 'members', {});
2508 property(this, 'memberNames', []);
2509 property(this, 'required', []);
2510 property(this, 'isRequired', function() { return false; });
2511 }
2512
2513 if (shape.members) {
2514 property(this, 'members', new Collection(shape.members, options, function(name, member) {
2515 return Shape.create(member, options, name);
2516 }));
2517 memoizedProperty(this, 'memberNames', function() {
2518 return shape.xmlOrder || Object.keys(shape.members);
2519 });
2520
2521 if (shape.event) {
2522 memoizedProperty(this, 'eventPayloadMemberName', function() {
2523 var members = self.members;
2524 var memberNames = self.memberNames;
2525 // iterate over members to find ones that are event payloads
2526 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2527 if (members[memberNames[i]].isEventPayload) {
2528 return memberNames[i];
2529 }
2530 }
2531 });
2532
2533 memoizedProperty(this, 'eventHeaderMemberNames', function() {
2534 var members = self.members;
2535 var memberNames = self.memberNames;
2536 var eventHeaderMemberNames = [];
2537 // iterate over members to find ones that are event headers
2538 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2539 if (members[memberNames[i]].isEventHeader) {
2540 eventHeaderMemberNames.push(memberNames[i]);
2541 }
2542 }
2543 return eventHeaderMemberNames;
2544 });
2545 }
2546 }
2547
2548 if (shape.required) {
2549 property(this, 'required', shape.required);
2550 property(this, 'isRequired', function(name) {
2551 if (!requiredMap) {
2552 requiredMap = {};
2553 for (var i = 0; i < shape.required.length; i++) {
2554 requiredMap[shape.required[i]] = true;
2555 }
2556 }
2557
2558 return requiredMap[name];
2559 }, false, true);
2560 }
2561
2562 property(this, 'resultWrapper', shape.resultWrapper || null);
2563
2564 if (shape.payload) {
2565 property(this, 'payload', shape.payload);
2566 }
2567
2568 if (typeof shape.xmlNamespace === 'string') {
2569 property(this, 'xmlNamespaceUri', shape.xmlNamespace);
2570 } else if (typeof shape.xmlNamespace === 'object') {
2571 property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix);
2572 property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri);
2573 }
2574 }
2575
2576 function ListShape(shape, options) {
2577 var self = this, firstInit = !this.isShape;
2578 CompositeShape.apply(this, arguments);
2579
2580 if (firstInit) {
2581 property(this, 'defaultValue', function() { return []; });
2582 }
2583
2584 if (shape.member) {
2585 memoizedProperty(this, 'member', function() {
2586 return Shape.create(shape.member, options);
2587 });
2588 }
2589
2590 if (this.flattened) {
2591 var oldName = this.name;
2592 memoizedProperty(this, 'name', function() {
2593 return self.member.name || oldName;
2594 });
2595 }
2596 }
2597
2598 function MapShape(shape, options) {
2599 var firstInit = !this.isShape;
2600 CompositeShape.apply(this, arguments);
2601
2602 if (firstInit) {
2603 property(this, 'defaultValue', function() { return {}; });
2604 property(this, 'key', Shape.create({type: 'string'}, options));
2605 property(this, 'value', Shape.create({type: 'string'}, options));
2606 }
2607
2608 if (shape.key) {
2609 memoizedProperty(this, 'key', function() {
2610 return Shape.create(shape.key, options);
2611 });
2612 }
2613 if (shape.value) {
2614 memoizedProperty(this, 'value', function() {
2615 return Shape.create(shape.value, options);
2616 });
2617 }
2618 }
2619
2620 function TimestampShape(shape) {
2621 var self = this;
2622 Shape.apply(this, arguments);
2623
2624 if (shape.timestampFormat) {
2625 property(this, 'timestampFormat', shape.timestampFormat);
2626 } else if (self.isTimestampFormatSet && this.timestampFormat) {
2627 property(this, 'timestampFormat', this.timestampFormat);
2628 } else if (this.location === 'header') {
2629 property(this, 'timestampFormat', 'rfc822');
2630 } else if (this.location === 'querystring') {
2631 property(this, 'timestampFormat', 'iso8601');
2632 } else if (this.api) {
2633 switch (this.api.protocol) {
2634 case 'json':
2635 case 'rest-json':
2636 property(this, 'timestampFormat', 'unixTimestamp');
2637 break;
2638 case 'rest-xml':
2639 case 'query':
2640 case 'ec2':
2641 property(this, 'timestampFormat', 'iso8601');
2642 break;
2643 }
2644 }
2645
2646 this.toType = function(value) {
2647 if (value === null || value === undefined) return null;
2648 if (typeof value.toUTCString === 'function') return value;
2649 return typeof value === 'string' || typeof value === 'number' ?
2650 util.date.parseTimestamp(value) : null;
2651 };
2652
2653 this.toWireFormat = function(value) {
2654 return util.date.format(value, self.timestampFormat);
2655 };
2656 }
2657
2658 function StringShape() {
2659 Shape.apply(this, arguments);
2660
2661 var nullLessProtocols = ['rest-xml', 'query', 'ec2'];
2662 this.toType = function(value) {
2663 value = this.api && nullLessProtocols.indexOf(this.api.protocol) > -1 ?
2664 value || '' : value;
2665 if (this.isJsonValue) {
2666 return JSON.parse(value);
2667 }
2668
2669 return value && typeof value.toString === 'function' ?
2670 value.toString() : value;
2671 };
2672
2673 this.toWireFormat = function(value) {
2674 return this.isJsonValue ? JSON.stringify(value) : value;
2675 };
2676 }
2677
2678 function FloatShape() {
2679 Shape.apply(this, arguments);
2680
2681 this.toType = function(value) {
2682 if (value === null || value === undefined) return null;
2683 return parseFloat(value);
2684 };
2685 this.toWireFormat = this.toType;
2686 }
2687
2688 function IntegerShape() {
2689 Shape.apply(this, arguments);
2690
2691 this.toType = function(value) {
2692 if (value === null || value === undefined) return null;
2693 return parseInt(value, 10);
2694 };
2695 this.toWireFormat = this.toType;
2696 }
2697
2698 function BinaryShape() {
2699 Shape.apply(this, arguments);
2700 this.toType = util.base64.decode;
2701 this.toWireFormat = util.base64.encode;
2702 }
2703
2704 function Base64Shape() {
2705 BinaryShape.apply(this, arguments);
2706 }
2707
2708 function BooleanShape() {
2709 Shape.apply(this, arguments);
2710
2711 this.toType = function(value) {
2712 if (typeof value === 'boolean') return value;
2713 if (value === null || value === undefined) return null;
2714 return value === 'true';
2715 };
2716 }
2717
2718 /**
2719 * @api private
2720 */
2721 Shape.shapes = {
2722 StructureShape: StructureShape,
2723 ListShape: ListShape,
2724 MapShape: MapShape,
2725 StringShape: StringShape,
2726 BooleanShape: BooleanShape,
2727 Base64Shape: Base64Shape
2728 };
2729
2730 /**
2731 * @api private
2732 */
2733 module.exports = Shape;
2734
2735
2736/***/ }),
2737/* 20 */
2738/***/ (function(module, exports, __webpack_require__) {
2739
2740 var memoizedProperty = __webpack_require__(2).memoizedProperty;
2741
2742 function memoize(name, value, factory, nameTr) {
2743 memoizedProperty(this, nameTr(name), function() {
2744 return factory(name, value);
2745 });
2746 }
2747
2748 function Collection(iterable, options, factory, nameTr, callback) {
2749 nameTr = nameTr || String;
2750 var self = this;
2751
2752 for (var id in iterable) {
2753 if (Object.prototype.hasOwnProperty.call(iterable, id)) {
2754 memoize.call(self, id, iterable[id], factory, nameTr);
2755 if (callback) callback(id, iterable[id]);
2756 }
2757 }
2758 }
2759
2760 /**
2761 * @api private
2762 */
2763 module.exports = Collection;
2764
2765
2766/***/ }),
2767/* 21 */
2768/***/ (function(module, exports, __webpack_require__) {
2769
2770 var util = __webpack_require__(2);
2771 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2772
2773 function populateMethod(req) {
2774 req.httpRequest.method = req.service.api.operations[req.operation].httpMethod;
2775 }
2776
2777 function generateURI(endpointPath, operationPath, input, params) {
2778 var uri = [endpointPath, operationPath].join('/');
2779 uri = uri.replace(/\/+/g, '/');
2780
2781 var queryString = {}, queryStringSet = false;
2782 util.each(input.members, function (name, member) {
2783 var paramValue = params[name];
2784 if (paramValue === null || paramValue === undefined) return;
2785 if (member.location === 'uri') {
2786 var regex = new RegExp('\\{' + member.name + '(\\+)?\\}');
2787 uri = uri.replace(regex, function(_, plus) {
2788 var fn = plus ? util.uriEscapePath : util.uriEscape;
2789 return fn(String(paramValue));
2790 });
2791 } else if (member.location === 'querystring') {
2792 queryStringSet = true;
2793
2794 if (member.type === 'list') {
2795 queryString[member.name] = paramValue.map(function(val) {
2796 return util.uriEscape(member.member.toWireFormat(val).toString());
2797 });
2798 } else if (member.type === 'map') {
2799 util.each(paramValue, function(key, value) {
2800 if (Array.isArray(value)) {
2801 queryString[key] = value.map(function(val) {
2802 return util.uriEscape(String(val));
2803 });
2804 } else {
2805 queryString[key] = util.uriEscape(String(value));
2806 }
2807 });
2808 } else {
2809 queryString[member.name] = util.uriEscape(member.toWireFormat(paramValue).toString());
2810 }
2811 }
2812 });
2813
2814 if (queryStringSet) {
2815 uri += (uri.indexOf('?') >= 0 ? '&' : '?');
2816 var parts = [];
2817 util.arrayEach(Object.keys(queryString).sort(), function(key) {
2818 if (!Array.isArray(queryString[key])) {
2819 queryString[key] = [queryString[key]];
2820 }
2821 for (var i = 0; i < queryString[key].length; i++) {
2822 parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]);
2823 }
2824 });
2825 uri += parts.join('&');
2826 }
2827
2828 return uri;
2829 }
2830
2831 function populateURI(req) {
2832 var operation = req.service.api.operations[req.operation];
2833 var input = operation.input;
2834
2835 var uri = generateURI(req.httpRequest.endpoint.path, operation.httpPath, input, req.params);
2836 req.httpRequest.path = uri;
2837 }
2838
2839 function populateHeaders(req) {
2840 var operation = req.service.api.operations[req.operation];
2841 util.each(operation.input.members, function (name, member) {
2842 var value = req.params[name];
2843 if (value === null || value === undefined) return;
2844
2845 if (member.location === 'headers' && member.type === 'map') {
2846 util.each(value, function(key, memberValue) {
2847 req.httpRequest.headers[member.name + key] = memberValue;
2848 });
2849 } else if (member.location === 'header') {
2850 value = member.toWireFormat(value).toString();
2851 if (member.isJsonValue) {
2852 value = util.base64.encode(value);
2853 }
2854 req.httpRequest.headers[member.name] = value;
2855 }
2856 });
2857 }
2858
2859 function buildRequest(req) {
2860 populateMethod(req);
2861 populateURI(req);
2862 populateHeaders(req);
2863 populateHostPrefix(req);
2864 }
2865
2866 function extractError() {
2867 }
2868
2869 function extractData(resp) {
2870 var req = resp.request;
2871 var data = {};
2872 var r = resp.httpResponse;
2873 var operation = req.service.api.operations[req.operation];
2874 var output = operation.output;
2875
2876 // normalize headers names to lower-cased keys for matching
2877 var headers = {};
2878 util.each(r.headers, function (k, v) {
2879 headers[k.toLowerCase()] = v;
2880 });
2881
2882 util.each(output.members, function(name, member) {
2883 var header = (member.name || name).toLowerCase();
2884 if (member.location === 'headers' && member.type === 'map') {
2885 data[name] = {};
2886 var location = member.isLocationName ? member.name : '';
2887 var pattern = new RegExp('^' + location + '(.+)', 'i');
2888 util.each(r.headers, function (k, v) {
2889 var result = k.match(pattern);
2890 if (result !== null) {
2891 data[name][result[1]] = v;
2892 }
2893 });
2894 } else if (member.location === 'header') {
2895 if (headers[header] !== undefined) {
2896 var value = member.isJsonValue ?
2897 util.base64.decode(headers[header]) :
2898 headers[header];
2899 data[name] = member.toType(value);
2900 }
2901 } else if (member.location === 'statusCode') {
2902 data[name] = parseInt(r.statusCode, 10);
2903 }
2904 });
2905
2906 resp.data = data;
2907 }
2908
2909 /**
2910 * @api private
2911 */
2912 module.exports = {
2913 buildRequest: buildRequest,
2914 extractError: extractError,
2915 extractData: extractData,
2916 generateURI: generateURI
2917 };
2918
2919
2920/***/ }),
2921/* 22 */
2922/***/ (function(module, exports, __webpack_require__) {
2923
2924 var util = __webpack_require__(2);
2925 var Rest = __webpack_require__(21);
2926 var Json = __webpack_require__(13);
2927 var JsonBuilder = __webpack_require__(14);
2928 var JsonParser = __webpack_require__(15);
2929
2930 function populateBody(req) {
2931 var builder = new JsonBuilder();
2932 var input = req.service.api.operations[req.operation].input;
2933
2934 if (input.payload) {
2935 var params = {};
2936 var payloadShape = input.members[input.payload];
2937 params = req.params[input.payload];
2938 if (params === undefined) return;
2939
2940 if (payloadShape.type === 'structure') {
2941 req.httpRequest.body = builder.build(params, payloadShape);
2942 applyContentTypeHeader(req);
2943 } else { // non-JSON payload
2944 req.httpRequest.body = params;
2945 if (payloadShape.type === 'binary' || payloadShape.isStreaming) {
2946 applyContentTypeHeader(req, true);
2947 }
2948 }
2949 } else {
2950 var body = builder.build(req.params, input);
2951 if (body !== '{}' || req.httpRequest.method !== 'GET') { //don't send empty body for GET method
2952 req.httpRequest.body = body;
2953 }
2954 applyContentTypeHeader(req);
2955 }
2956 }
2957
2958 function applyContentTypeHeader(req, isBinary) {
2959 var operation = req.service.api.operations[req.operation];
2960 var input = operation.input;
2961
2962 if (!req.httpRequest.headers['Content-Type']) {
2963 var type = isBinary ? 'binary/octet-stream' : 'application/json';
2964 req.httpRequest.headers['Content-Type'] = type;
2965 }
2966 }
2967
2968 function buildRequest(req) {
2969 Rest.buildRequest(req);
2970
2971 // never send body payload on HEAD/DELETE
2972 if (['HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) {
2973 populateBody(req);
2974 }
2975 }
2976
2977 function extractError(resp) {
2978 Json.extractError(resp);
2979 }
2980
2981 function extractData(resp) {
2982 Rest.extractData(resp);
2983
2984 var req = resp.request;
2985 var operation = req.service.api.operations[req.operation];
2986 var rules = req.service.api.operations[req.operation].output || {};
2987 var parser;
2988 var hasEventOutput = operation.hasEventOutput;
2989
2990 if (rules.payload) {
2991 var payloadMember = rules.members[rules.payload];
2992 var body = resp.httpResponse.body;
2993 if (payloadMember.isEventStream) {
2994 parser = new JsonParser();
2995 resp.data[payload] = util.createEventStream(
2996 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : body,
2997 parser,
2998 payloadMember
2999 );
3000 } else if (payloadMember.type === 'structure' || payloadMember.type === 'list') {
3001 var parser = new JsonParser();
3002 resp.data[rules.payload] = parser.parse(body, payloadMember);
3003 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3004 resp.data[rules.payload] = body;
3005 } else {
3006 resp.data[rules.payload] = payloadMember.toType(body);
3007 }
3008 } else {
3009 var data = resp.data;
3010 Json.extractData(resp);
3011 resp.data = util.merge(data, resp.data);
3012 }
3013 }
3014
3015 /**
3016 * @api private
3017 */
3018 module.exports = {
3019 buildRequest: buildRequest,
3020 extractError: extractError,
3021 extractData: extractData
3022 };
3023
3024
3025/***/ }),
3026/* 23 */
3027/***/ (function(module, exports, __webpack_require__) {
3028
3029 var AWS = __webpack_require__(1);
3030 var util = __webpack_require__(2);
3031 var Rest = __webpack_require__(21);
3032
3033 function populateBody(req) {
3034 var input = req.service.api.operations[req.operation].input;
3035 var builder = new AWS.XML.Builder();
3036 var params = req.params;
3037
3038 var payload = input.payload;
3039 if (payload) {
3040 var payloadMember = input.members[payload];
3041 params = params[payload];
3042 if (params === undefined) return;
3043
3044 if (payloadMember.type === 'structure') {
3045 var rootElement = payloadMember.name;
3046 req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true);
3047 } else { // non-xml payload
3048 req.httpRequest.body = params;
3049 }
3050 } else {
3051 req.httpRequest.body = builder.toXML(params, input, input.name ||
3052 input.shape || util.string.upperFirst(req.operation) + 'Request');
3053 }
3054 }
3055
3056 function buildRequest(req) {
3057 Rest.buildRequest(req);
3058
3059 // never send body payload on GET/HEAD
3060 if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) {
3061 populateBody(req);
3062 }
3063 }
3064
3065 function extractError(resp) {
3066 Rest.extractError(resp);
3067
3068 var data;
3069 try {
3070 data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString());
3071 } catch (e) {
3072 data = {
3073 Code: resp.httpResponse.statusCode,
3074 Message: resp.httpResponse.statusMessage
3075 };
3076 }
3077
3078 if (data.Errors) data = data.Errors;
3079 if (data.Error) data = data.Error;
3080 if (data.Code) {
3081 resp.error = util.error(new Error(), {
3082 code: data.Code,
3083 message: data.Message
3084 });
3085 } else {
3086 resp.error = util.error(new Error(), {
3087 code: resp.httpResponse.statusCode,
3088 message: null
3089 });
3090 }
3091 }
3092
3093 function extractData(resp) {
3094 Rest.extractData(resp);
3095
3096 var parser;
3097 var req = resp.request;
3098 var body = resp.httpResponse.body;
3099 var operation = req.service.api.operations[req.operation];
3100 var output = operation.output;
3101
3102 var hasEventOutput = operation.hasEventOutput;
3103
3104 var payload = output.payload;
3105 if (payload) {
3106 var payloadMember = output.members[payload];
3107 if (payloadMember.isEventStream) {
3108 parser = new AWS.XML.Parser();
3109 resp.data[payload] = util.createEventStream(
3110 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : resp.httpResponse.body,
3111 parser,
3112 payloadMember
3113 );
3114 } else if (payloadMember.type === 'structure') {
3115 parser = new AWS.XML.Parser();
3116 resp.data[payload] = parser.parse(body.toString(), payloadMember);
3117 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3118 resp.data[payload] = body;
3119 } else {
3120 resp.data[payload] = payloadMember.toType(body);
3121 }
3122 } else if (body.length > 0) {
3123 parser = new AWS.XML.Parser();
3124 var data = parser.parse(body.toString(), output);
3125 util.update(resp.data, data);
3126 }
3127 }
3128
3129 /**
3130 * @api private
3131 */
3132 module.exports = {
3133 buildRequest: buildRequest,
3134 extractError: extractError,
3135 extractData: extractData
3136 };
3137
3138
3139/***/ }),
3140/* 24 */
3141/***/ (function(module, exports, __webpack_require__) {
3142
3143 var util = __webpack_require__(2);
3144 var XmlNode = __webpack_require__(25).XmlNode;
3145 var XmlText = __webpack_require__(27).XmlText;
3146
3147 function XmlBuilder() { }
3148
3149 XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) {
3150 var xml = new XmlNode(rootElement);
3151 applyNamespaces(xml, shape, true);
3152 serialize(xml, params, shape);
3153 return xml.children.length > 0 || noEmpty ? xml.toString() : '';
3154 };
3155
3156 function serialize(xml, value, shape) {
3157 switch (shape.type) {
3158 case 'structure': return serializeStructure(xml, value, shape);
3159 case 'map': return serializeMap(xml, value, shape);
3160 case 'list': return serializeList(xml, value, shape);
3161 default: return serializeScalar(xml, value, shape);
3162 }
3163 }
3164
3165 function serializeStructure(xml, params, shape) {
3166 util.arrayEach(shape.memberNames, function(memberName) {
3167 var memberShape = shape.members[memberName];
3168 if (memberShape.location !== 'body') return;
3169
3170 var value = params[memberName];
3171 var name = memberShape.name;
3172 if (value !== undefined && value !== null) {
3173 if (memberShape.isXmlAttribute) {
3174 xml.addAttribute(name, value);
3175 } else if (memberShape.flattened) {
3176 serialize(xml, value, memberShape);
3177 } else {
3178 var element = new XmlNode(name);
3179 xml.addChildNode(element);
3180 applyNamespaces(element, memberShape);
3181 serialize(element, value, memberShape);
3182 }
3183 }
3184 });
3185 }
3186
3187 function serializeMap(xml, map, shape) {
3188 var xmlKey = shape.key.name || 'key';
3189 var xmlValue = shape.value.name || 'value';
3190
3191 util.each(map, function(key, value) {
3192 var entry = new XmlNode(shape.flattened ? shape.name : 'entry');
3193 xml.addChildNode(entry);
3194
3195 var entryKey = new XmlNode(xmlKey);
3196 var entryValue = new XmlNode(xmlValue);
3197 entry.addChildNode(entryKey);
3198 entry.addChildNode(entryValue);
3199
3200 serialize(entryKey, key, shape.key);
3201 serialize(entryValue, value, shape.value);
3202 });
3203 }
3204
3205 function serializeList(xml, list, shape) {
3206 if (shape.flattened) {
3207 util.arrayEach(list, function(value) {
3208 var name = shape.member.name || shape.name;
3209 var element = new XmlNode(name);
3210 xml.addChildNode(element);
3211 serialize(element, value, shape.member);
3212 });
3213 } else {
3214 util.arrayEach(list, function(value) {
3215 var name = shape.member.name || 'member';
3216 var element = new XmlNode(name);
3217 xml.addChildNode(element);
3218 serialize(element, value, shape.member);
3219 });
3220 }
3221 }
3222
3223 function serializeScalar(xml, value, shape) {
3224 xml.addChildNode(
3225 new XmlText(shape.toWireFormat(value))
3226 );
3227 }
3228
3229 function applyNamespaces(xml, shape, isRoot) {
3230 var uri, prefix = 'xmlns';
3231 if (shape.xmlNamespaceUri) {
3232 uri = shape.xmlNamespaceUri;
3233 if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix;
3234 } else if (isRoot && shape.api.xmlNamespaceUri) {
3235 uri = shape.api.xmlNamespaceUri;
3236 }
3237
3238 if (uri) xml.addAttribute(prefix, uri);
3239 }
3240
3241 /**
3242 * @api private
3243 */
3244 module.exports = XmlBuilder;
3245
3246
3247/***/ }),
3248/* 25 */
3249/***/ (function(module, exports, __webpack_require__) {
3250
3251 var escapeAttribute = __webpack_require__(26).escapeAttribute;
3252
3253 /**
3254 * Represents an XML node.
3255 * @api private
3256 */
3257 function XmlNode(name, children) {
3258 if (children === void 0) { children = []; }
3259 this.name = name;
3260 this.children = children;
3261 this.attributes = {};
3262 }
3263 XmlNode.prototype.addAttribute = function (name, value) {
3264 this.attributes[name] = value;
3265 return this;
3266 };
3267 XmlNode.prototype.addChildNode = function (child) {
3268 this.children.push(child);
3269 return this;
3270 };
3271 XmlNode.prototype.removeAttribute = function (name) {
3272 delete this.attributes[name];
3273 return this;
3274 };
3275 XmlNode.prototype.toString = function () {
3276 var hasChildren = Boolean(this.children.length);
3277 var xmlText = '<' + this.name;
3278 // add attributes
3279 var attributes = this.attributes;
3280 for (var i = 0, attributeNames = Object.keys(attributes); i < attributeNames.length; i++) {
3281 var attributeName = attributeNames[i];
3282 var attribute = attributes[attributeName];
3283 if (typeof attribute !== 'undefined' && attribute !== null) {
3284 xmlText += ' ' + attributeName + '=\"' + escapeAttribute('' + attribute) + '\"';
3285 }
3286 }
3287 return xmlText += !hasChildren ? '/>' : '>' + this.children.map(function (c) { return c.toString(); }).join('') + '</' + this.name + '>';
3288 };
3289
3290 /**
3291 * @api private
3292 */
3293 module.exports = {
3294 XmlNode: XmlNode
3295 };
3296
3297
3298/***/ }),
3299/* 26 */
3300/***/ (function(module, exports) {
3301
3302 /**
3303 * Escapes characters that can not be in an XML attribute.
3304 */
3305 function escapeAttribute(value) {
3306 return value.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
3307 }
3308
3309 /**
3310 * @api private
3311 */
3312 module.exports = {
3313 escapeAttribute: escapeAttribute
3314 };
3315
3316
3317/***/ }),
3318/* 27 */
3319/***/ (function(module, exports, __webpack_require__) {
3320
3321 var escapeElement = __webpack_require__(28).escapeElement;
3322
3323 /**
3324 * Represents an XML text value.
3325 * @api private
3326 */
3327 function XmlText(value) {
3328 this.value = value;
3329 }
3330
3331 XmlText.prototype.toString = function () {
3332 return escapeElement('' + this.value);
3333 };
3334
3335 /**
3336 * @api private
3337 */
3338 module.exports = {
3339 XmlText: XmlText
3340 };
3341
3342
3343/***/ }),
3344/* 28 */
3345/***/ (function(module, exports) {
3346
3347 /**
3348 * Escapes characters that can not be in an XML element.
3349 */
3350 function escapeElement(value) {
3351 return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3352 }
3353
3354 /**
3355 * @api private
3356 */
3357 module.exports = {
3358 escapeElement: escapeElement
3359 };
3360
3361
3362/***/ }),
3363/* 29 */
3364/***/ (function(module, exports, __webpack_require__) {
3365
3366 var Collection = __webpack_require__(20);
3367 var Operation = __webpack_require__(30);
3368 var Shape = __webpack_require__(19);
3369 var Paginator = __webpack_require__(31);
3370 var ResourceWaiter = __webpack_require__(32);
3371
3372 var util = __webpack_require__(2);
3373 var property = util.property;
3374 var memoizedProperty = util.memoizedProperty;
3375
3376 function Api(api, options) {
3377 var self = this;
3378 api = api || {};
3379 options = options || {};
3380 options.api = this;
3381
3382 api.metadata = api.metadata || {};
3383
3384 property(this, 'isApi', true, false);
3385 property(this, 'apiVersion', api.metadata.apiVersion);
3386 property(this, 'endpointPrefix', api.metadata.endpointPrefix);
3387 property(this, 'signingName', api.metadata.signingName);
3388 property(this, 'globalEndpoint', api.metadata.globalEndpoint);
3389 property(this, 'signatureVersion', api.metadata.signatureVersion);
3390 property(this, 'jsonVersion', api.metadata.jsonVersion);
3391 property(this, 'targetPrefix', api.metadata.targetPrefix);
3392 property(this, 'protocol', api.metadata.protocol);
3393 property(this, 'timestampFormat', api.metadata.timestampFormat);
3394 property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace);
3395 property(this, 'abbreviation', api.metadata.serviceAbbreviation);
3396 property(this, 'fullName', api.metadata.serviceFullName);
3397 property(this, 'serviceId', api.metadata.serviceId);
3398
3399 memoizedProperty(this, 'className', function() {
3400 var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName;
3401 if (!name) return null;
3402
3403 name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, '');
3404 if (name === 'ElasticLoadBalancing') name = 'ELB';
3405 return name;
3406 });
3407
3408 function addEndpointOperation(name, operation) {
3409 if (operation.endpointoperation === true) {
3410 property(self, 'endpointOperation', util.string.lowerFirst(name));
3411 }
3412 }
3413
3414 property(this, 'operations', new Collection(api.operations, options, function(name, operation) {
3415 return new Operation(name, operation, options);
3416 }, util.string.lowerFirst, addEndpointOperation));
3417
3418 property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) {
3419 return Shape.create(shape, options);
3420 }));
3421
3422 property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) {
3423 return new Paginator(name, paginator, options);
3424 }));
3425
3426 property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) {
3427 return new ResourceWaiter(name, waiter, options);
3428 }, util.string.lowerFirst));
3429
3430 if (options.documentation) {
3431 property(this, 'documentation', api.documentation);
3432 property(this, 'documentationUrl', api.documentationUrl);
3433 }
3434 }
3435
3436 /**
3437 * @api private
3438 */
3439 module.exports = Api;
3440
3441
3442/***/ }),
3443/* 30 */
3444/***/ (function(module, exports, __webpack_require__) {
3445
3446 var Shape = __webpack_require__(19);
3447
3448 var util = __webpack_require__(2);
3449 var property = util.property;
3450 var memoizedProperty = util.memoizedProperty;
3451
3452 function Operation(name, operation, options) {
3453 var self = this;
3454 options = options || {};
3455
3456 property(this, 'name', operation.name || name);
3457 property(this, 'api', options.api, false);
3458
3459 operation.http = operation.http || {};
3460 property(this, 'endpoint', operation.endpoint);
3461 property(this, 'httpMethod', operation.http.method || 'POST');
3462 property(this, 'httpPath', operation.http.requestUri || '/');
3463 property(this, 'authtype', operation.authtype || '');
3464 property(
3465 this,
3466 'endpointDiscoveryRequired',
3467 operation.endpointdiscovery ?
3468 (operation.endpointdiscovery.required ? 'REQUIRED' : 'OPTIONAL') :
3469 'NULL'
3470 );
3471
3472 memoizedProperty(this, 'input', function() {
3473 if (!operation.input) {
3474 return new Shape.create({type: 'structure'}, options);
3475 }
3476 return Shape.create(operation.input, options);
3477 });
3478
3479 memoizedProperty(this, 'output', function() {
3480 if (!operation.output) {
3481 return new Shape.create({type: 'structure'}, options);
3482 }
3483 return Shape.create(operation.output, options);
3484 });
3485
3486 memoizedProperty(this, 'errors', function() {
3487 var list = [];
3488 if (!operation.errors) return null;
3489
3490 for (var i = 0; i < operation.errors.length; i++) {
3491 list.push(Shape.create(operation.errors[i], options));
3492 }
3493
3494 return list;
3495 });
3496
3497 memoizedProperty(this, 'paginator', function() {
3498 return options.api.paginators[name];
3499 });
3500
3501 if (options.documentation) {
3502 property(this, 'documentation', operation.documentation);
3503 property(this, 'documentationUrl', operation.documentationUrl);
3504 }
3505
3506 // idempotentMembers only tracks top-level input shapes
3507 memoizedProperty(this, 'idempotentMembers', function() {
3508 var idempotentMembers = [];
3509 var input = self.input;
3510 var members = input.members;
3511 if (!input.members) {
3512 return idempotentMembers;
3513 }
3514 for (var name in members) {
3515 if (!members.hasOwnProperty(name)) {
3516 continue;
3517 }
3518 if (members[name].isIdempotent === true) {
3519 idempotentMembers.push(name);
3520 }
3521 }
3522 return idempotentMembers;
3523 });
3524
3525 memoizedProperty(this, 'hasEventOutput', function() {
3526 var output = self.output;
3527 return hasEventStream(output);
3528 });
3529 }
3530
3531 function hasEventStream(topLevelShape) {
3532 var members = topLevelShape.members;
3533 var payload = topLevelShape.payload;
3534
3535 if (!topLevelShape.members) {
3536 return false;
3537 }
3538
3539 if (payload) {
3540 var payloadMember = members[payload];
3541 return payloadMember.isEventStream;
3542 }
3543
3544 // check if any member is an event stream
3545 for (var name in members) {
3546 if (!members.hasOwnProperty(name)) {
3547 if (members[name].isEventStream === true) {
3548 return true;
3549 }
3550 }
3551 }
3552 return false;
3553 }
3554
3555 /**
3556 * @api private
3557 */
3558 module.exports = Operation;
3559
3560
3561/***/ }),
3562/* 31 */
3563/***/ (function(module, exports, __webpack_require__) {
3564
3565 var property = __webpack_require__(2).property;
3566
3567 function Paginator(name, paginator) {
3568 property(this, 'inputToken', paginator.input_token);
3569 property(this, 'limitKey', paginator.limit_key);
3570 property(this, 'moreResults', paginator.more_results);
3571 property(this, 'outputToken', paginator.output_token);
3572 property(this, 'resultKey', paginator.result_key);
3573 }
3574
3575 /**
3576 * @api private
3577 */
3578 module.exports = Paginator;
3579
3580
3581/***/ }),
3582/* 32 */
3583/***/ (function(module, exports, __webpack_require__) {
3584
3585 var util = __webpack_require__(2);
3586 var property = util.property;
3587
3588 function ResourceWaiter(name, waiter, options) {
3589 options = options || {};
3590 property(this, 'name', name);
3591 property(this, 'api', options.api, false);
3592
3593 if (waiter.operation) {
3594 property(this, 'operation', util.string.lowerFirst(waiter.operation));
3595 }
3596
3597 var self = this;
3598 var keys = [
3599 'type',
3600 'description',
3601 'delay',
3602 'maxAttempts',
3603 'acceptors'
3604 ];
3605
3606 keys.forEach(function(key) {
3607 var value = waiter[key];
3608 if (value) {
3609 property(self, key, value);
3610 }
3611 });
3612 }
3613
3614 /**
3615 * @api private
3616 */
3617 module.exports = ResourceWaiter;
3618
3619
3620/***/ }),
3621/* 33 */
3622/***/ (function(module, exports) {
3623
3624 function apiLoader(svc, version) {
3625 if (!apiLoader.services.hasOwnProperty(svc)) {
3626 throw new Error('InvalidService: Failed to load api for ' + svc);
3627 }
3628 return apiLoader.services[svc][version];
3629 }
3630
3631 /**
3632 * @api private
3633 *
3634 * This member of AWS.apiLoader is private, but changing it will necessitate a
3635 * change to ../scripts/services-table-generator.ts
3636 */
3637 apiLoader.services = {};
3638
3639 /**
3640 * @api private
3641 */
3642 module.exports = apiLoader;
3643
3644
3645/***/ }),
3646/* 34 */
3647/***/ (function(module, exports, __webpack_require__) {
3648
3649 "use strict";
3650 Object.defineProperty(exports, "__esModule", { value: true });
3651 var LRU_1 = __webpack_require__(35);
3652 var CACHE_SIZE = 1000;
3653 /**
3654 * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache]
3655 */
3656 var EndpointCache = /** @class */ (function () {
3657 function EndpointCache(maxSize) {
3658 if (maxSize === void 0) { maxSize = CACHE_SIZE; }
3659 this.maxSize = maxSize;
3660 this.cache = new LRU_1.LRUCache(maxSize);
3661 }
3662 ;
3663 Object.defineProperty(EndpointCache.prototype, "size", {
3664 get: function () {
3665 return this.cache.length;
3666 },
3667 enumerable: true,
3668 configurable: true
3669 });
3670 EndpointCache.prototype.put = function (key, value) {
3671 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3672 var endpointRecord = this.populateValue(value);
3673 this.cache.put(keyString, endpointRecord);
3674 };
3675 EndpointCache.prototype.get = function (key) {
3676 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3677 var now = Date.now();
3678 var records = this.cache.get(keyString);
3679 if (records) {
3680 for (var i = 0; i < records.length; i++) {
3681 var record = records[i];
3682 if (record.Expire < now) {
3683 this.cache.remove(keyString);
3684 return undefined;
3685 }
3686 }
3687 }
3688 return records;
3689 };
3690 EndpointCache.getKeyString = function (key) {
3691 var identifiers = [];
3692 var identifierNames = Object.keys(key).sort();
3693 for (var i = 0; i < identifierNames.length; i++) {
3694 var identifierName = identifierNames[i];
3695 if (key[identifierName] === undefined)
3696 continue;
3697 identifiers.push(key[identifierName]);
3698 }
3699 return identifiers.join(' ');
3700 };
3701 EndpointCache.prototype.populateValue = function (endpoints) {
3702 var now = Date.now();
3703 return endpoints.map(function (endpoint) { return ({
3704 Address: endpoint.Address || '',
3705 Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000
3706 }); });
3707 };
3708 EndpointCache.prototype.empty = function () {
3709 this.cache.empty();
3710 };
3711 EndpointCache.prototype.remove = function (key) {
3712 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3713 this.cache.remove(keyString);
3714 };
3715 return EndpointCache;
3716 }());
3717 exports.EndpointCache = EndpointCache;
3718
3719/***/ }),
3720/* 35 */
3721/***/ (function(module, exports) {
3722
3723 "use strict";
3724 Object.defineProperty(exports, "__esModule", { value: true });
3725 var LinkedListNode = /** @class */ (function () {
3726 function LinkedListNode(key, value) {
3727 this.key = key;
3728 this.value = value;
3729 }
3730 return LinkedListNode;
3731 }());
3732 var LRUCache = /** @class */ (function () {
3733 function LRUCache(size) {
3734 this.nodeMap = {};
3735 this.size = 0;
3736 if (typeof size !== 'number' || size < 1) {
3737 throw new Error('Cache size can only be positive number');
3738 }
3739 this.sizeLimit = size;
3740 }
3741 Object.defineProperty(LRUCache.prototype, "length", {
3742 get: function () {
3743 return this.size;
3744 },
3745 enumerable: true,
3746 configurable: true
3747 });
3748 LRUCache.prototype.prependToList = function (node) {
3749 if (!this.headerNode) {
3750 this.tailNode = node;
3751 }
3752 else {
3753 this.headerNode.prev = node;
3754 node.next = this.headerNode;
3755 }
3756 this.headerNode = node;
3757 this.size++;
3758 };
3759 LRUCache.prototype.removeFromTail = function () {
3760 if (!this.tailNode) {
3761 return undefined;
3762 }
3763 var node = this.tailNode;
3764 var prevNode = node.prev;
3765 if (prevNode) {
3766 prevNode.next = undefined;
3767 }
3768 node.prev = undefined;
3769 this.tailNode = prevNode;
3770 this.size--;
3771 return node;
3772 };
3773 LRUCache.prototype.detachFromList = function (node) {
3774 if (this.headerNode === node) {
3775 this.headerNode = node.next;
3776 }
3777 if (this.tailNode === node) {
3778 this.tailNode = node.prev;
3779 }
3780 if (node.prev) {
3781 node.prev.next = node.next;
3782 }
3783 if (node.next) {
3784 node.next.prev = node.prev;
3785 }
3786 node.next = undefined;
3787 node.prev = undefined;
3788 this.size--;
3789 };
3790 LRUCache.prototype.get = function (key) {
3791 if (this.nodeMap[key]) {
3792 var node = this.nodeMap[key];
3793 this.detachFromList(node);
3794 this.prependToList(node);
3795 return node.value;
3796 }
3797 };
3798 LRUCache.prototype.remove = function (key) {
3799 if (this.nodeMap[key]) {
3800 var node = this.nodeMap[key];
3801 this.detachFromList(node);
3802 delete this.nodeMap[key];
3803 }
3804 };
3805 LRUCache.prototype.put = function (key, value) {
3806 if (this.nodeMap[key]) {
3807 this.remove(key);
3808 }
3809 else if (this.size === this.sizeLimit) {
3810 var tailNode = this.removeFromTail();
3811 var key_1 = tailNode.key;
3812 delete this.nodeMap[key_1];
3813 }
3814 var newNode = new LinkedListNode(key, value);
3815 this.nodeMap[key] = newNode;
3816 this.prependToList(newNode);
3817 };
3818 LRUCache.prototype.empty = function () {
3819 var keys = Object.keys(this.nodeMap);
3820 for (var i = 0; i < keys.length; i++) {
3821 var key = keys[i];
3822 var node = this.nodeMap[key];
3823 this.detachFromList(node);
3824 delete this.nodeMap[key];
3825 }
3826 };
3827 return LRUCache;
3828 }());
3829 exports.LRUCache = LRUCache;
3830
3831/***/ }),
3832/* 36 */
3833/***/ (function(module, exports, __webpack_require__) {
3834
3835 var AWS = __webpack_require__(1);
3836
3837 /**
3838 * @api private
3839 * @!method on(eventName, callback)
3840 * Registers an event listener callback for the event given by `eventName`.
3841 * Parameters passed to the callback function depend on the individual event
3842 * being triggered. See the event documentation for those parameters.
3843 *
3844 * @param eventName [String] the event name to register the listener for
3845 * @param callback [Function] the listener callback function
3846 * @param toHead [Boolean] attach the listener callback to the head of callback array if set to true.
3847 * Default to be false.
3848 * @return [AWS.SequentialExecutor] the same object for chaining
3849 */
3850 AWS.SequentialExecutor = AWS.util.inherit({
3851
3852 constructor: function SequentialExecutor() {
3853 this._events = {};
3854 },
3855
3856 /**
3857 * @api private
3858 */
3859 listeners: function listeners(eventName) {
3860 return this._events[eventName] ? this._events[eventName].slice(0) : [];
3861 },
3862
3863 on: function on(eventName, listener, toHead) {
3864 if (this._events[eventName]) {
3865 toHead ?
3866 this._events[eventName].unshift(listener) :
3867 this._events[eventName].push(listener);
3868 } else {
3869 this._events[eventName] = [listener];
3870 }
3871 return this;
3872 },
3873
3874 onAsync: function onAsync(eventName, listener, toHead) {
3875 listener._isAsync = true;
3876 return this.on(eventName, listener, toHead);
3877 },
3878
3879 removeListener: function removeListener(eventName, listener) {
3880 var listeners = this._events[eventName];
3881 if (listeners) {
3882 var length = listeners.length;
3883 var position = -1;
3884 for (var i = 0; i < length; ++i) {
3885 if (listeners[i] === listener) {
3886 position = i;
3887 }
3888 }
3889 if (position > -1) {
3890 listeners.splice(position, 1);
3891 }
3892 }
3893 return this;
3894 },
3895
3896 removeAllListeners: function removeAllListeners(eventName) {
3897 if (eventName) {
3898 delete this._events[eventName];
3899 } else {
3900 this._events = {};
3901 }
3902 return this;
3903 },
3904
3905 /**
3906 * @api private
3907 */
3908 emit: function emit(eventName, eventArgs, doneCallback) {
3909 if (!doneCallback) doneCallback = function() { };
3910 var listeners = this.listeners(eventName);
3911 var count = listeners.length;
3912 this.callListeners(listeners, eventArgs, doneCallback);
3913 return count > 0;
3914 },
3915
3916 /**
3917 * @api private
3918 */
3919 callListeners: function callListeners(listeners, args, doneCallback, prevError) {
3920 var self = this;
3921 var error = prevError || null;
3922
3923 function callNextListener(err) {
3924 if (err) {
3925 error = AWS.util.error(error || new Error(), err);
3926 if (self._haltHandlersOnError) {
3927 return doneCallback.call(self, error);
3928 }
3929 }
3930 self.callListeners(listeners, args, doneCallback, error);
3931 }
3932
3933 while (listeners.length > 0) {
3934 var listener = listeners.shift();
3935 if (listener._isAsync) { // asynchronous listener
3936 listener.apply(self, args.concat([callNextListener]));
3937 return; // stop here, callNextListener will continue
3938 } else { // synchronous listener
3939 try {
3940 listener.apply(self, args);
3941 } catch (err) {
3942 error = AWS.util.error(error || new Error(), err);
3943 }
3944 if (error && self._haltHandlersOnError) {
3945 doneCallback.call(self, error);
3946 return;
3947 }
3948 }
3949 }
3950 doneCallback.call(self, error);
3951 },
3952
3953 /**
3954 * Adds or copies a set of listeners from another list of
3955 * listeners or SequentialExecutor object.
3956 *
3957 * @param listeners [map<String,Array<Function>>, AWS.SequentialExecutor]
3958 * a list of events and callbacks, or an event emitter object
3959 * containing listeners to add to this emitter object.
3960 * @return [AWS.SequentialExecutor] the emitter object, for chaining.
3961 * @example Adding listeners from a map of listeners
3962 * emitter.addListeners({
3963 * event1: [function() { ... }, function() { ... }],
3964 * event2: [function() { ... }]
3965 * });
3966 * emitter.emit('event1'); // emitter has event1
3967 * emitter.emit('event2'); // emitter has event2
3968 * @example Adding listeners from another emitter object
3969 * var emitter1 = new AWS.SequentialExecutor();
3970 * emitter1.on('event1', function() { ... });
3971 * emitter1.on('event2', function() { ... });
3972 * var emitter2 = new AWS.SequentialExecutor();
3973 * emitter2.addListeners(emitter1);
3974 * emitter2.emit('event1'); // emitter2 has event1
3975 * emitter2.emit('event2'); // emitter2 has event2
3976 */
3977 addListeners: function addListeners(listeners) {
3978 var self = this;
3979
3980 // extract listeners if parameter is an SequentialExecutor object
3981 if (listeners._events) listeners = listeners._events;
3982
3983 AWS.util.each(listeners, function(event, callbacks) {
3984 if (typeof callbacks === 'function') callbacks = [callbacks];
3985 AWS.util.arrayEach(callbacks, function(callback) {
3986 self.on(event, callback);
3987 });
3988 });
3989
3990 return self;
3991 },
3992
3993 /**
3994 * Registers an event with {on} and saves the callback handle function
3995 * as a property on the emitter object using a given `name`.
3996 *
3997 * @param name [String] the property name to set on this object containing
3998 * the callback function handle so that the listener can be removed in
3999 * the future.
4000 * @param (see on)
4001 * @return (see on)
4002 * @example Adding a named listener DATA_CALLBACK
4003 * var listener = function() { doSomething(); };
4004 * emitter.addNamedListener('DATA_CALLBACK', 'data', listener);
4005 *
4006 * // the following prints: true
4007 * console.log(emitter.DATA_CALLBACK == listener);
4008 */
4009 addNamedListener: function addNamedListener(name, eventName, callback, toHead) {
4010 this[name] = callback;
4011 this.addListener(eventName, callback, toHead);
4012 return this;
4013 },
4014
4015 /**
4016 * @api private
4017 */
4018 addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback, toHead) {
4019 callback._isAsync = true;
4020 return this.addNamedListener(name, eventName, callback, toHead);
4021 },
4022
4023 /**
4024 * Helper method to add a set of named listeners using
4025 * {addNamedListener}. The callback contains a parameter
4026 * with a handle to the `addNamedListener` method.
4027 *
4028 * @callback callback function(add)
4029 * The callback function is called immediately in order to provide
4030 * the `add` function to the block. This simplifies the addition of
4031 * a large group of named listeners.
4032 * @param add [Function] the {addNamedListener} function to call
4033 * when registering listeners.
4034 * @example Adding a set of named listeners
4035 * emitter.addNamedListeners(function(add) {
4036 * add('DATA_CALLBACK', 'data', function() { ... });
4037 * add('OTHER', 'otherEvent', function() { ... });
4038 * add('LAST', 'lastEvent', function() { ... });
4039 * });
4040 *
4041 * // these properties are now set:
4042 * emitter.DATA_CALLBACK;
4043 * emitter.OTHER;
4044 * emitter.LAST;
4045 */
4046 addNamedListeners: function addNamedListeners(callback) {
4047 var self = this;
4048 callback(
4049 function() {
4050 self.addNamedListener.apply(self, arguments);
4051 },
4052 function() {
4053 self.addNamedAsyncListener.apply(self, arguments);
4054 }
4055 );
4056 return this;
4057 }
4058 });
4059
4060 /**
4061 * {on} is the prefered method.
4062 * @api private
4063 */
4064 AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on;
4065
4066 /**
4067 * @api private
4068 */
4069 module.exports = AWS.SequentialExecutor;
4070
4071
4072/***/ }),
4073/* 37 */
4074/***/ (function(module, exports, __webpack_require__) {
4075
4076 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
4077 var Api = __webpack_require__(29);
4078 var regionConfig = __webpack_require__(38);
4079
4080 var inherit = AWS.util.inherit;
4081 var clientCount = 0;
4082
4083 /**
4084 * The service class representing an AWS service.
4085 *
4086 * @class_abstract This class is an abstract class.
4087 *
4088 * @!attribute apiVersions
4089 * @return [Array<String>] the list of API versions supported by this service.
4090 * @readonly
4091 */
4092 AWS.Service = inherit({
4093 /**
4094 * Create a new service object with a configuration object
4095 *
4096 * @param config [map] a map of configuration options
4097 */
4098 constructor: function Service(config) {
4099 if (!this.loadServiceClass) {
4100 throw AWS.util.error(new Error(),
4101 'Service must be constructed with `new\' operator');
4102 }
4103 var ServiceClass = this.loadServiceClass(config || {});
4104 if (ServiceClass) {
4105 var originalConfig = AWS.util.copy(config);
4106 var svc = new ServiceClass(config);
4107 Object.defineProperty(svc, '_originalConfig', {
4108 get: function() { return originalConfig; },
4109 enumerable: false,
4110 configurable: true
4111 });
4112 svc._clientId = ++clientCount;
4113 return svc;
4114 }
4115 this.initialize(config);
4116 },
4117
4118 /**
4119 * @api private
4120 */
4121 initialize: function initialize(config) {
4122 var svcConfig = AWS.config[this.serviceIdentifier];
4123 this.config = new AWS.Config(AWS.config);
4124 if (svcConfig) this.config.update(svcConfig, true);
4125 if (config) this.config.update(config, true);
4126
4127 this.validateService();
4128 if (!this.config.endpoint) regionConfig(this);
4129
4130 this.config.endpoint = this.endpointFromTemplate(this.config.endpoint);
4131 this.setEndpoint(this.config.endpoint);
4132 //enable attaching listeners to service client
4133 AWS.SequentialExecutor.call(this);
4134 AWS.Service.addDefaultMonitoringListeners(this);
4135 if ((this.config.clientSideMonitoring || AWS.Service._clientSideMonitoring) && this.publisher) {
4136 var publisher = this.publisher;
4137 this.addNamedListener('PUBLISH_API_CALL', 'apiCall', function PUBLISH_API_CALL(event) {
4138 process.nextTick(function() {publisher.eventHandler(event);});
4139 });
4140 this.addNamedListener('PUBLISH_API_ATTEMPT', 'apiCallAttempt', function PUBLISH_API_ATTEMPT(event) {
4141 process.nextTick(function() {publisher.eventHandler(event);});
4142 });
4143 }
4144 },
4145
4146 /**
4147 * @api private
4148 */
4149 validateService: function validateService() {
4150 },
4151
4152 /**
4153 * @api private
4154 */
4155 loadServiceClass: function loadServiceClass(serviceConfig) {
4156 var config = serviceConfig;
4157 if (!AWS.util.isEmpty(this.api)) {
4158 return null;
4159 } else if (config.apiConfig) {
4160 return AWS.Service.defineServiceApi(this.constructor, config.apiConfig);
4161 } else if (!this.constructor.services) {
4162 return null;
4163 } else {
4164 config = new AWS.Config(AWS.config);
4165 config.update(serviceConfig, true);
4166 var version = config.apiVersions[this.constructor.serviceIdentifier];
4167 version = version || config.apiVersion;
4168 return this.getLatestServiceClass(version);
4169 }
4170 },
4171
4172 /**
4173 * @api private
4174 */
4175 getLatestServiceClass: function getLatestServiceClass(version) {
4176 version = this.getLatestServiceVersion(version);
4177 if (this.constructor.services[version] === null) {
4178 AWS.Service.defineServiceApi(this.constructor, version);
4179 }
4180
4181 return this.constructor.services[version];
4182 },
4183
4184 /**
4185 * @api private
4186 */
4187 getLatestServiceVersion: function getLatestServiceVersion(version) {
4188 if (!this.constructor.services || this.constructor.services.length === 0) {
4189 throw new Error('No services defined on ' +
4190 this.constructor.serviceIdentifier);
4191 }
4192
4193 if (!version) {
4194 version = 'latest';
4195 } else if (AWS.util.isType(version, Date)) {
4196 version = AWS.util.date.iso8601(version).split('T')[0];
4197 }
4198
4199 if (Object.hasOwnProperty(this.constructor.services, version)) {
4200 return version;
4201 }
4202
4203 var keys = Object.keys(this.constructor.services).sort();
4204 var selectedVersion = null;
4205 for (var i = keys.length - 1; i >= 0; i--) {
4206 // versions that end in "*" are not available on disk and can be
4207 // skipped, so do not choose these as selectedVersions
4208 if (keys[i][keys[i].length - 1] !== '*') {
4209 selectedVersion = keys[i];
4210 }
4211 if (keys[i].substr(0, 10) <= version) {
4212 return selectedVersion;
4213 }
4214 }
4215
4216 throw new Error('Could not find ' + this.constructor.serviceIdentifier +
4217 ' API to satisfy version constraint `' + version + '\'');
4218 },
4219
4220 /**
4221 * @api private
4222 */
4223 api: {},
4224
4225 /**
4226 * @api private
4227 */
4228 defaultRetryCount: 3,
4229
4230 /**
4231 * @api private
4232 */
4233 customizeRequests: function customizeRequests(callback) {
4234 if (!callback) {
4235 this.customRequestHandler = null;
4236 } else if (typeof callback === 'function') {
4237 this.customRequestHandler = callback;
4238 } else {
4239 throw new Error('Invalid callback type \'' + typeof callback + '\' provided in customizeRequests');
4240 }
4241 },
4242
4243 /**
4244 * Calls an operation on a service with the given input parameters.
4245 *
4246 * @param operation [String] the name of the operation to call on the service.
4247 * @param params [map] a map of input options for the operation
4248 * @callback callback function(err, data)
4249 * If a callback is supplied, it is called when a response is returned
4250 * from the service.
4251 * @param err [Error] the error object returned from the request.
4252 * Set to `null` if the request is successful.
4253 * @param data [Object] the de-serialized data returned from
4254 * the request. Set to `null` if a request error occurs.
4255 */
4256 makeRequest: function makeRequest(operation, params, callback) {
4257 if (typeof params === 'function') {
4258 callback = params;
4259 params = null;
4260 }
4261
4262 params = params || {};
4263 if (this.config.params) { // copy only toplevel bound params
4264 var rules = this.api.operations[operation];
4265 if (rules) {
4266 params = AWS.util.copy(params);
4267 AWS.util.each(this.config.params, function(key, value) {
4268 if (rules.input.members[key]) {
4269 if (params[key] === undefined || params[key] === null) {
4270 params[key] = value;
4271 }
4272 }
4273 });
4274 }
4275 }
4276
4277 var request = new AWS.Request(this, operation, params);
4278 this.addAllRequestListeners(request);
4279 this.attachMonitoringEmitter(request);
4280 if (callback) request.send(callback);
4281 return request;
4282 },
4283
4284 /**
4285 * Calls an operation on a service with the given input parameters, without
4286 * any authentication data. This method is useful for "public" API operations.
4287 *
4288 * @param operation [String] the name of the operation to call on the service.
4289 * @param params [map] a map of input options for the operation
4290 * @callback callback function(err, data)
4291 * If a callback is supplied, it is called when a response is returned
4292 * from the service.
4293 * @param err [Error] the error object returned from the request.
4294 * Set to `null` if the request is successful.
4295 * @param data [Object] the de-serialized data returned from
4296 * the request. Set to `null` if a request error occurs.
4297 */
4298 makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) {
4299 if (typeof params === 'function') {
4300 callback = params;
4301 params = {};
4302 }
4303
4304 var request = this.makeRequest(operation, params).toUnauthenticated();
4305 return callback ? request.send(callback) : request;
4306 },
4307
4308 /**
4309 * Waits for a given state
4310 *
4311 * @param state [String] the state on the service to wait for
4312 * @param params [map] a map of parameters to pass with each request
4313 * @option params $waiter [map] a map of configuration options for the waiter
4314 * @option params $waiter.delay [Number] The number of seconds to wait between
4315 * requests
4316 * @option params $waiter.maxAttempts [Number] The maximum number of requests
4317 * to send while waiting
4318 * @callback callback function(err, data)
4319 * If a callback is supplied, it is called when a response is returned
4320 * from the service.
4321 * @param err [Error] the error object returned from the request.
4322 * Set to `null` if the request is successful.
4323 * @param data [Object] the de-serialized data returned from
4324 * the request. Set to `null` if a request error occurs.
4325 */
4326 waitFor: function waitFor(state, params, callback) {
4327 var waiter = new AWS.ResourceWaiter(this, state);
4328 return waiter.wait(params, callback);
4329 },
4330
4331 /**
4332 * @api private
4333 */
4334 addAllRequestListeners: function addAllRequestListeners(request) {
4335 var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(),
4336 AWS.EventListeners.CorePost];
4337 for (var i = 0; i < list.length; i++) {
4338 if (list[i]) request.addListeners(list[i]);
4339 }
4340
4341 // disable parameter validation
4342 if (!this.config.paramValidation) {
4343 request.removeListener('validate',
4344 AWS.EventListeners.Core.VALIDATE_PARAMETERS);
4345 }
4346
4347 if (this.config.logger) { // add logging events
4348 request.addListeners(AWS.EventListeners.Logger);
4349 }
4350
4351 this.setupRequestListeners(request);
4352 // call prototype's customRequestHandler
4353 if (typeof this.constructor.prototype.customRequestHandler === 'function') {
4354 this.constructor.prototype.customRequestHandler(request);
4355 }
4356 // call instance's customRequestHandler
4357 if (Object.prototype.hasOwnProperty.call(this, 'customRequestHandler') && typeof this.customRequestHandler === 'function') {
4358 this.customRequestHandler(request);
4359 }
4360 },
4361
4362 /**
4363 * Event recording metrics for a whole API call.
4364 * @returns {object} a subset of api call metrics
4365 * @api private
4366 */
4367 apiCallEvent: function apiCallEvent(request) {
4368 var api = request.service.api.operations[request.operation];
4369 var monitoringEvent = {
4370 Type: 'ApiCall',
4371 Api: api ? api.name : request.operation,
4372 Version: 1,
4373 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4374 Region: request.httpRequest.region,
4375 MaxRetriesExceeded: 0,
4376 UserAgent: request.httpRequest.getUserAgent(),
4377 };
4378 var response = request.response;
4379 if (response.httpResponse.statusCode) {
4380 monitoringEvent.FinalHttpStatusCode = response.httpResponse.statusCode;
4381 }
4382 if (response.error) {
4383 var error = response.error;
4384 var statusCode = response.httpResponse.statusCode;
4385 if (statusCode > 299) {
4386 if (error.code) monitoringEvent.FinalAwsException = error.code;
4387 if (error.message) monitoringEvent.FinalAwsExceptionMessage = error.message;
4388 } else {
4389 if (error.code || error.name) monitoringEvent.FinalSdkException = error.code || error.name;
4390 if (error.message) monitoringEvent.FinalSdkExceptionMessage = error.message;
4391 }
4392 }
4393 return monitoringEvent;
4394 },
4395
4396 /**
4397 * Event recording metrics for an API call attempt.
4398 * @returns {object} a subset of api call attempt metrics
4399 * @api private
4400 */
4401 apiAttemptEvent: function apiAttemptEvent(request) {
4402 var api = request.service.api.operations[request.operation];
4403 var monitoringEvent = {
4404 Type: 'ApiCallAttempt',
4405 Api: api ? api.name : request.operation,
4406 Version: 1,
4407 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4408 Fqdn: request.httpRequest.endpoint.hostname,
4409 UserAgent: request.httpRequest.getUserAgent(),
4410 };
4411 var response = request.response;
4412 if (response.httpResponse.statusCode) {
4413 monitoringEvent.HttpStatusCode = response.httpResponse.statusCode;
4414 }
4415 if (
4416 !request._unAuthenticated &&
4417 request.service.config.credentials &&
4418 request.service.config.credentials.accessKeyId
4419 ) {
4420 monitoringEvent.AccessKey = request.service.config.credentials.accessKeyId;
4421 }
4422 if (!response.httpResponse.headers) return monitoringEvent;
4423 if (request.httpRequest.headers['x-amz-security-token']) {
4424 monitoringEvent.SessionToken = request.httpRequest.headers['x-amz-security-token'];
4425 }
4426 if (response.httpResponse.headers['x-amzn-requestid']) {
4427 monitoringEvent.XAmznRequestId = response.httpResponse.headers['x-amzn-requestid'];
4428 }
4429 if (response.httpResponse.headers['x-amz-request-id']) {
4430 monitoringEvent.XAmzRequestId = response.httpResponse.headers['x-amz-request-id'];
4431 }
4432 if (response.httpResponse.headers['x-amz-id-2']) {
4433 monitoringEvent.XAmzId2 = response.httpResponse.headers['x-amz-id-2'];
4434 }
4435 return monitoringEvent;
4436 },
4437
4438 /**
4439 * Add metrics of failed request.
4440 * @api private
4441 */
4442 attemptFailEvent: function attemptFailEvent(request) {
4443 var monitoringEvent = this.apiAttemptEvent(request);
4444 var response = request.response;
4445 var error = response.error;
4446 if (response.httpResponse.statusCode > 299 ) {
4447 if (error.code) monitoringEvent.AwsException = error.code;
4448 if (error.message) monitoringEvent.AwsExceptionMessage = error.message;
4449 } else {
4450 if (error.code || error.name) monitoringEvent.SdkException = error.code || error.name;
4451 if (error.message) monitoringEvent.SdkExceptionMessage = error.message;
4452 }
4453 return monitoringEvent;
4454 },
4455
4456 /**
4457 * Attach listeners to request object to fetch metrics of each request
4458 * and emit data object through \'ApiCall\' and \'ApiCallAttempt\' events.
4459 * @api private
4460 */
4461 attachMonitoringEmitter: function attachMonitoringEmitter(request) {
4462 var attemptTimestamp; //timestamp marking the beginning of a request attempt
4463 var attemptStartRealTime; //Start time of request attempt. Used to calculating attemptLatency
4464 var attemptLatency; //latency from request sent out to http response reaching SDK
4465 var callStartRealTime; //Start time of API call. Used to calculating API call latency
4466 var attemptCount = 0; //request.retryCount is not reliable here
4467 var region; //region cache region for each attempt since it can be updated in plase (e.g. s3)
4468 var callTimestamp; //timestamp when the request is created
4469 var self = this;
4470 var addToHead = true;
4471
4472 request.on('validate', function () {
4473 callStartRealTime = AWS.util.realClock.now();
4474 callTimestamp = Date.now();
4475 }, addToHead);
4476 request.on('sign', function () {
4477 attemptStartRealTime = AWS.util.realClock.now();
4478 attemptTimestamp = Date.now();
4479 region = request.httpRequest.region;
4480 attemptCount++;
4481 }, addToHead);
4482 request.on('validateResponse', function() {
4483 attemptLatency = Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4484 });
4485 request.addNamedListener('API_CALL_ATTEMPT', 'success', function API_CALL_ATTEMPT() {
4486 var apiAttemptEvent = self.apiAttemptEvent(request);
4487 apiAttemptEvent.Timestamp = attemptTimestamp;
4488 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4489 apiAttemptEvent.Region = region;
4490 self.emit('apiCallAttempt', [apiAttemptEvent]);
4491 });
4492 request.addNamedListener('API_CALL_ATTEMPT_RETRY', 'retry', function API_CALL_ATTEMPT_RETRY() {
4493 var apiAttemptEvent = self.attemptFailEvent(request);
4494 apiAttemptEvent.Timestamp = attemptTimestamp;
4495 //attemptLatency may not be available if fail before response
4496 attemptLatency = attemptLatency ||
4497 Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4498 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4499 apiAttemptEvent.Region = region;
4500 self.emit('apiCallAttempt', [apiAttemptEvent]);
4501 });
4502 request.addNamedListener('API_CALL', 'complete', function API_CALL() {
4503 var apiCallEvent = self.apiCallEvent(request);
4504 apiCallEvent.AttemptCount = attemptCount;
4505 if (apiCallEvent.AttemptCount <= 0) return;
4506 apiCallEvent.Timestamp = callTimestamp;
4507 var latency = Math.round(AWS.util.realClock.now() - callStartRealTime);
4508 apiCallEvent.Latency = latency >= 0 ? latency : 0;
4509 var response = request.response;
4510 if (
4511 typeof response.retryCount === 'number' &&
4512 typeof response.maxRetries === 'number' &&
4513 (response.retryCount >= response.maxRetries)
4514 ) {
4515 apiCallEvent.MaxRetriesExceeded = 1;
4516 }
4517 self.emit('apiCall', [apiCallEvent]);
4518 });
4519 },
4520
4521 /**
4522 * Override this method to setup any custom request listeners for each
4523 * new request to the service.
4524 *
4525 * @method_abstract This is an abstract method.
4526 */
4527 setupRequestListeners: function setupRequestListeners(request) {
4528 },
4529
4530 /**
4531 * Gets the signer class for a given request
4532 * @api private
4533 */
4534 getSignerClass: function getSignerClass(request) {
4535 var version;
4536 // get operation authtype if present
4537 var operation = null;
4538 var authtype = '';
4539 if (request) {
4540 var operations = request.service.api.operations || {};
4541 operation = operations[request.operation] || null;
4542 authtype = operation ? operation.authtype : '';
4543 }
4544 if (this.config.signatureVersion) {
4545 version = this.config.signatureVersion;
4546 } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') {
4547 version = 'v4';
4548 } else {
4549 version = this.api.signatureVersion;
4550 }
4551 return AWS.Signers.RequestSigner.getVersion(version);
4552 },
4553
4554 /**
4555 * @api private
4556 */
4557 serviceInterface: function serviceInterface() {
4558 switch (this.api.protocol) {
4559 case 'ec2': return AWS.EventListeners.Query;
4560 case 'query': return AWS.EventListeners.Query;
4561 case 'json': return AWS.EventListeners.Json;
4562 case 'rest-json': return AWS.EventListeners.RestJson;
4563 case 'rest-xml': return AWS.EventListeners.RestXml;
4564 }
4565 if (this.api.protocol) {
4566 throw new Error('Invalid service `protocol\' ' +
4567 this.api.protocol + ' in API config');
4568 }
4569 },
4570
4571 /**
4572 * @api private
4573 */
4574 successfulResponse: function successfulResponse(resp) {
4575 return resp.httpResponse.statusCode < 300;
4576 },
4577
4578 /**
4579 * How many times a failed request should be retried before giving up.
4580 * the defaultRetryCount can be overriden by service classes.
4581 *
4582 * @api private
4583 */
4584 numRetries: function numRetries() {
4585 if (this.config.maxRetries !== undefined) {
4586 return this.config.maxRetries;
4587 } else {
4588 return this.defaultRetryCount;
4589 }
4590 },
4591
4592 /**
4593 * @api private
4594 */
4595 retryDelays: function retryDelays(retryCount) {
4596 return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions);
4597 },
4598
4599 /**
4600 * @api private
4601 */
4602 retryableError: function retryableError(error) {
4603 if (this.timeoutError(error)) return true;
4604 if (this.networkingError(error)) return true;
4605 if (this.expiredCredentialsError(error)) return true;
4606 if (this.throttledError(error)) return true;
4607 if (error.statusCode >= 500) return true;
4608 return false;
4609 },
4610
4611 /**
4612 * @api private
4613 */
4614 networkingError: function networkingError(error) {
4615 return error.code === 'NetworkingError';
4616 },
4617
4618 /**
4619 * @api private
4620 */
4621 timeoutError: function timeoutError(error) {
4622 return error.code === 'TimeoutError';
4623 },
4624
4625 /**
4626 * @api private
4627 */
4628 expiredCredentialsError: function expiredCredentialsError(error) {
4629 // TODO : this only handles *one* of the expired credential codes
4630 return (error.code === 'ExpiredTokenException');
4631 },
4632
4633 /**
4634 * @api private
4635 */
4636 clockSkewError: function clockSkewError(error) {
4637 switch (error.code) {
4638 case 'RequestTimeTooSkewed':
4639 case 'RequestExpired':
4640 case 'InvalidSignatureException':
4641 case 'SignatureDoesNotMatch':
4642 case 'AuthFailure':
4643 case 'RequestInTheFuture':
4644 return true;
4645 default: return false;
4646 }
4647 },
4648
4649 /**
4650 * @api private
4651 */
4652 getSkewCorrectedDate: function getSkewCorrectedDate() {
4653 return new Date(Date.now() + this.config.systemClockOffset);
4654 },
4655
4656 /**
4657 * @api private
4658 */
4659 applyClockOffset: function applyClockOffset(newServerTime) {
4660 if (newServerTime) {
4661 this.config.systemClockOffset = newServerTime - Date.now();
4662 }
4663 },
4664
4665 /**
4666 * @api private
4667 */
4668 isClockSkewed: function isClockSkewed(newServerTime) {
4669 if (newServerTime) {
4670 return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 30000;
4671 }
4672 },
4673
4674 /**
4675 * @api private
4676 */
4677 throttledError: function throttledError(error) {
4678 // this logic varies between services
4679 switch (error.code) {
4680 case 'ProvisionedThroughputExceededException':
4681 case 'Throttling':
4682 case 'ThrottlingException':
4683 case 'RequestLimitExceeded':
4684 case 'RequestThrottled':
4685 case 'RequestThrottledException':
4686 case 'TooManyRequestsException':
4687 case 'TransactionInProgressException': //dynamodb
4688 return true;
4689 default:
4690 return false;
4691 }
4692 },
4693
4694 /**
4695 * @api private
4696 */
4697 endpointFromTemplate: function endpointFromTemplate(endpoint) {
4698 if (typeof endpoint !== 'string') return endpoint;
4699
4700 var e = endpoint;
4701 e = e.replace(/\{service\}/g, this.api.endpointPrefix);
4702 e = e.replace(/\{region\}/g, this.config.region);
4703 e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http');
4704 return e;
4705 },
4706
4707 /**
4708 * @api private
4709 */
4710 setEndpoint: function setEndpoint(endpoint) {
4711 this.endpoint = new AWS.Endpoint(endpoint, this.config);
4712 },
4713
4714 /**
4715 * @api private
4716 */
4717 paginationConfig: function paginationConfig(operation, throwException) {
4718 var paginator = this.api.operations[operation].paginator;
4719 if (!paginator) {
4720 if (throwException) {
4721 var e = new Error();
4722 throw AWS.util.error(e, 'No pagination configuration for ' + operation);
4723 }
4724 return null;
4725 }
4726
4727 return paginator;
4728 }
4729 });
4730
4731 AWS.util.update(AWS.Service, {
4732
4733 /**
4734 * Adds one method for each operation described in the api configuration
4735 *
4736 * @api private
4737 */
4738 defineMethods: function defineMethods(svc) {
4739 AWS.util.each(svc.prototype.api.operations, function iterator(method) {
4740 if (svc.prototype[method]) return;
4741 var operation = svc.prototype.api.operations[method];
4742 if (operation.authtype === 'none') {
4743 svc.prototype[method] = function (params, callback) {
4744 return this.makeUnauthenticatedRequest(method, params, callback);
4745 };
4746 } else {
4747 svc.prototype[method] = function (params, callback) {
4748 return this.makeRequest(method, params, callback);
4749 };
4750 }
4751 });
4752 },
4753
4754 /**
4755 * Defines a new Service class using a service identifier and list of versions
4756 * including an optional set of features (functions) to apply to the class
4757 * prototype.
4758 *
4759 * @param serviceIdentifier [String] the identifier for the service
4760 * @param versions [Array<String>] a list of versions that work with this
4761 * service
4762 * @param features [Object] an object to attach to the prototype
4763 * @return [Class<Service>] the service class defined by this function.
4764 */
4765 defineService: function defineService(serviceIdentifier, versions, features) {
4766 AWS.Service._serviceMap[serviceIdentifier] = true;
4767 if (!Array.isArray(versions)) {
4768 features = versions;
4769 versions = [];
4770 }
4771
4772 var svc = inherit(AWS.Service, features || {});
4773
4774 if (typeof serviceIdentifier === 'string') {
4775 AWS.Service.addVersions(svc, versions);
4776
4777 var identifier = svc.serviceIdentifier || serviceIdentifier;
4778 svc.serviceIdentifier = identifier;
4779 } else { // defineService called with an API
4780 svc.prototype.api = serviceIdentifier;
4781 AWS.Service.defineMethods(svc);
4782 }
4783 AWS.SequentialExecutor.call(this.prototype);
4784 //util.clientSideMonitoring is only available in node
4785 if (!this.prototype.publisher && AWS.util.clientSideMonitoring) {
4786 var Publisher = AWS.util.clientSideMonitoring.Publisher;
4787 var configProvider = AWS.util.clientSideMonitoring.configProvider;
4788 var publisherConfig = configProvider();
4789 this.prototype.publisher = new Publisher(publisherConfig);
4790 if (publisherConfig.enabled) {
4791 //if csm is enabled in environment, SDK should send all metrics
4792 AWS.Service._clientSideMonitoring = true;
4793 }
4794 }
4795 AWS.SequentialExecutor.call(svc.prototype);
4796 AWS.Service.addDefaultMonitoringListeners(svc.prototype);
4797 return svc;
4798 },
4799
4800 /**
4801 * @api private
4802 */
4803 addVersions: function addVersions(svc, versions) {
4804 if (!Array.isArray(versions)) versions = [versions];
4805
4806 svc.services = svc.services || {};
4807 for (var i = 0; i < versions.length; i++) {
4808 if (svc.services[versions[i]] === undefined) {
4809 svc.services[versions[i]] = null;
4810 }
4811 }
4812
4813 svc.apiVersions = Object.keys(svc.services).sort();
4814 },
4815
4816 /**
4817 * @api private
4818 */
4819 defineServiceApi: function defineServiceApi(superclass, version, apiConfig) {
4820 var svc = inherit(superclass, {
4821 serviceIdentifier: superclass.serviceIdentifier
4822 });
4823
4824 function setApi(api) {
4825 if (api.isApi) {
4826 svc.prototype.api = api;
4827 } else {
4828 svc.prototype.api = new Api(api);
4829 }
4830 }
4831
4832 if (typeof version === 'string') {
4833 if (apiConfig) {
4834 setApi(apiConfig);
4835 } else {
4836 try {
4837 setApi(AWS.apiLoader(superclass.serviceIdentifier, version));
4838 } catch (err) {
4839 throw AWS.util.error(err, {
4840 message: 'Could not find API configuration ' +
4841 superclass.serviceIdentifier + '-' + version
4842 });
4843 }
4844 }
4845 if (!Object.prototype.hasOwnProperty.call(superclass.services, version)) {
4846 superclass.apiVersions = superclass.apiVersions.concat(version).sort();
4847 }
4848 superclass.services[version] = svc;
4849 } else {
4850 setApi(version);
4851 }
4852
4853 AWS.Service.defineMethods(svc);
4854 return svc;
4855 },
4856
4857 /**
4858 * @api private
4859 */
4860 hasService: function(identifier) {
4861 return Object.prototype.hasOwnProperty.call(AWS.Service._serviceMap, identifier);
4862 },
4863
4864 /**
4865 * @param attachOn attach default monitoring listeners to object
4866 *
4867 * Each monitoring event should be emitted from service client to service constructor prototype and then
4868 * to global service prototype like bubbling up. These default monitoring events listener will transfer
4869 * the monitoring events to the upper layer.
4870 * @api private
4871 */
4872 addDefaultMonitoringListeners: function addDefaultMonitoringListeners(attachOn) {
4873 attachOn.addNamedListener('MONITOR_EVENTS_BUBBLE', 'apiCallAttempt', function EVENTS_BUBBLE(event) {
4874 var baseClass = Object.getPrototypeOf(attachOn);
4875 if (baseClass._events) baseClass.emit('apiCallAttempt', [event]);
4876 });
4877 attachOn.addNamedListener('CALL_EVENTS_BUBBLE', 'apiCall', function CALL_EVENTS_BUBBLE(event) {
4878 var baseClass = Object.getPrototypeOf(attachOn);
4879 if (baseClass._events) baseClass.emit('apiCall', [event]);
4880 });
4881 },
4882
4883 /**
4884 * @api private
4885 */
4886 _serviceMap: {}
4887 });
4888
4889 AWS.util.mixin(AWS.Service, AWS.SequentialExecutor);
4890
4891 /**
4892 * @api private
4893 */
4894 module.exports = AWS.Service;
4895
4896 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
4897
4898/***/ }),
4899/* 38 */
4900/***/ (function(module, exports, __webpack_require__) {
4901
4902 var util = __webpack_require__(2);
4903 var regionConfig = __webpack_require__(39);
4904
4905 function generateRegionPrefix(region) {
4906 if (!region) return null;
4907
4908 var parts = region.split('-');
4909 if (parts.length < 3) return null;
4910 return parts.slice(0, parts.length - 2).join('-') + '-*';
4911 }
4912
4913 function derivedKeys(service) {
4914 var region = service.config.region;
4915 var regionPrefix = generateRegionPrefix(region);
4916 var endpointPrefix = service.api.endpointPrefix;
4917
4918 return [
4919 [region, endpointPrefix],
4920 [regionPrefix, endpointPrefix],
4921 [region, '*'],
4922 [regionPrefix, '*'],
4923 ['*', endpointPrefix],
4924 ['*', '*']
4925 ].map(function(item) {
4926 return item[0] && item[1] ? item.join('/') : null;
4927 });
4928 }
4929
4930 function applyConfig(service, config) {
4931 util.each(config, function(key, value) {
4932 if (key === 'globalEndpoint') return;
4933 if (service.config[key] === undefined || service.config[key] === null) {
4934 service.config[key] = value;
4935 }
4936 });
4937 }
4938
4939 function configureEndpoint(service) {
4940 var keys = derivedKeys(service);
4941 for (var i = 0; i < keys.length; i++) {
4942 var key = keys[i];
4943 if (!key) continue;
4944
4945 if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) {
4946 var config = regionConfig.rules[key];
4947 if (typeof config === 'string') {
4948 config = regionConfig.patterns[config];
4949 }
4950
4951 // set dualstack endpoint
4952 if (service.config.useDualstack && util.isDualstackAvailable(service)) {
4953 config = util.copy(config);
4954 config.endpoint = '{service}.dualstack.{region}.amazonaws.com';
4955 }
4956
4957 // set global endpoint
4958 service.isGlobalEndpoint = !!config.globalEndpoint;
4959
4960 // signature version
4961 if (!config.signatureVersion) config.signatureVersion = 'v4';
4962
4963 // merge config
4964 applyConfig(service, config);
4965 return;
4966 }
4967 }
4968 }
4969
4970 /**
4971 * @api private
4972 */
4973 module.exports = configureEndpoint;
4974
4975
4976/***/ }),
4977/* 39 */
4978/***/ (function(module, exports) {
4979
4980 module.exports = {"rules":{"*/*":{"endpoint":"{service}.{region}.amazonaws.com"},"cn-*/*":{"endpoint":"{service}.{region}.amazonaws.com.cn"},"*/budgets":"globalSSL","*/cloudfront":"globalSSL","*/iam":"globalSSL","*/sts":"globalSSL","*/importexport":{"endpoint":"{service}.amazonaws.com","signatureVersion":"v2","globalEndpoint":true},"*/route53":{"endpoint":"https://{service}.amazonaws.com","signatureVersion":"v3https","globalEndpoint":true},"*/waf":"globalSSL","us-gov-*/iam":"globalGovCloud","us-gov-*/sts":{"endpoint":"{service}.{region}.amazonaws.com"},"us-gov-west-1/s3":"s3signature","us-west-1/s3":"s3signature","us-west-2/s3":"s3signature","eu-west-1/s3":"s3signature","ap-southeast-1/s3":"s3signature","ap-southeast-2/s3":"s3signature","ap-northeast-1/s3":"s3signature","sa-east-1/s3":"s3signature","us-east-1/s3":{"endpoint":"{service}.amazonaws.com","signatureVersion":"s3"},"us-east-1/sdb":{"endpoint":"{service}.amazonaws.com","signatureVersion":"v2"},"*/sdb":{"endpoint":"{service}.{region}.amazonaws.com","signatureVersion":"v2"}},"patterns":{"globalSSL":{"endpoint":"https://{service}.amazonaws.com","globalEndpoint":true},"globalGovCloud":{"endpoint":"{service}.us-gov.amazonaws.com"},"s3signature":{"endpoint":"{service}.{region}.amazonaws.com","signatureVersion":"s3"}}}
4981
4982/***/ }),
4983/* 40 */
4984/***/ (function(module, exports, __webpack_require__) {
4985
4986 var AWS = __webpack_require__(1);
4987 __webpack_require__(41);
4988 __webpack_require__(42);
4989 var PromisesDependency;
4990
4991 /**
4992 * The main configuration class used by all service objects to set
4993 * the region, credentials, and other options for requests.
4994 *
4995 * By default, credentials and region settings are left unconfigured.
4996 * This should be configured by the application before using any
4997 * AWS service APIs.
4998 *
4999 * In order to set global configuration options, properties should
5000 * be assigned to the global {AWS.config} object.
5001 *
5002 * @see AWS.config
5003 *
5004 * @!group General Configuration Options
5005 *
5006 * @!attribute credentials
5007 * @return [AWS.Credentials] the AWS credentials to sign requests with.
5008 *
5009 * @!attribute region
5010 * @example Set the global region setting to us-west-2
5011 * AWS.config.update({region: 'us-west-2'});
5012 * @return [AWS.Credentials] The region to send service requests to.
5013 * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
5014 * A list of available endpoints for each AWS service
5015 *
5016 * @!attribute maxRetries
5017 * @return [Integer] the maximum amount of retries to perform for a
5018 * service request. By default this value is calculated by the specific
5019 * service object that the request is being made to.
5020 *
5021 * @!attribute maxRedirects
5022 * @return [Integer] the maximum amount of redirects to follow for a
5023 * service request. Defaults to 10.
5024 *
5025 * @!attribute paramValidation
5026 * @return [Boolean|map] whether input parameters should be validated against
5027 * the operation description before sending the request. Defaults to true.
5028 * Pass a map to enable any of the following specific validation features:
5029 *
5030 * * **min** [Boolean] &mdash; Validates that a value meets the min
5031 * constraint. This is enabled by default when paramValidation is set
5032 * to `true`.
5033 * * **max** [Boolean] &mdash; Validates that a value meets the max
5034 * constraint.
5035 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5036 * regular expression.
5037 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5038 * of the allowable enum values.
5039 *
5040 * @!attribute computeChecksums
5041 * @return [Boolean] whether to compute checksums for payload bodies when
5042 * the service accepts it (currently supported in S3 only).
5043 *
5044 * @!attribute convertResponseTypes
5045 * @return [Boolean] whether types are converted when parsing response data.
5046 * Currently only supported for JSON based services. Turning this off may
5047 * improve performance on large response payloads. Defaults to `true`.
5048 *
5049 * @!attribute correctClockSkew
5050 * @return [Boolean] whether to apply a clock skew correction and retry
5051 * requests that fail because of an skewed client clock. Defaults to
5052 * `false`.
5053 *
5054 * @!attribute sslEnabled
5055 * @return [Boolean] whether SSL is enabled for requests
5056 *
5057 * @!attribute s3ForcePathStyle
5058 * @return [Boolean] whether to force path style URLs for S3 objects
5059 *
5060 * @!attribute s3BucketEndpoint
5061 * @note Setting this configuration option requires an `endpoint` to be
5062 * provided explicitly to the service constructor.
5063 * @return [Boolean] whether the provided endpoint addresses an individual
5064 * bucket (false if it addresses the root API endpoint).
5065 *
5066 * @!attribute s3DisableBodySigning
5067 * @return [Boolean] whether to disable S3 body signing when using signature version `v4`.
5068 * Body signing can only be disabled when using https. Defaults to `true`.
5069 *
5070 * @!attribute useAccelerateEndpoint
5071 * @note This configuration option is only compatible with S3 while accessing
5072 * dns-compatible buckets.
5073 * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service.
5074 * Defaults to `false`.
5075 *
5076 * @!attribute retryDelayOptions
5077 * @example Set the base retry delay for all services to 300 ms
5078 * AWS.config.update({retryDelayOptions: {base: 300}});
5079 * // Delays with maxRetries = 3: 300, 600, 1200
5080 * @example Set a custom backoff function to provide delay values on retries
5081 * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) {
5082 * // returns delay in ms
5083 * }}});
5084 * @return [map] A set of options to configure the retry delay on retryable errors.
5085 * Currently supported options are:
5086 *
5087 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5088 * exponential backoff for operation retries. Defaults to 100 ms for all services except
5089 * DynamoDB, where it defaults to 50ms.
5090 * * **customBackoff ** [function] &mdash; A custom function that accepts a retry count
5091 * and returns the amount of time to delay in milliseconds. The `base` option will be
5092 * ignored if this option is supplied.
5093 *
5094 * @!attribute httpOptions
5095 * @return [map] A set of options to pass to the low-level HTTP request.
5096 * Currently supported options are:
5097 *
5098 * * **proxy** [String] &mdash; the URL to proxy requests through
5099 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5100 * HTTP requests with. Used for connection pooling. Defaults to the global
5101 * agent (`http.globalAgent`) for non-SSL connections. Note that for
5102 * SSL connections, a special Agent object is used in order to enable
5103 * peer certificate verification. This feature is only supported in the
5104 * Node.js environment.
5105 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5106 * failing to establish a connection with the server after
5107 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5108 * connection has been established.
5109 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5110 * milliseconds of inactivity on the socket. Defaults to two minutes
5111 * (120000)
5112 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5113 * HTTP requests. Used in the browser environment only. Set to false to
5114 * send requests synchronously. Defaults to true (async on).
5115 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5116 * property of an XMLHttpRequest object. Used in the browser environment
5117 * only. Defaults to false.
5118 * @!attribute logger
5119 * @return [#write,#log] an object that responds to .write() (like a stream)
5120 * or .log() (like the console object) in order to log information about
5121 * requests
5122 *
5123 * @!attribute systemClockOffset
5124 * @return [Number] an offset value in milliseconds to apply to all signing
5125 * times. Use this to compensate for clock skew when your system may be
5126 * out of sync with the service time. Note that this configuration option
5127 * can only be applied to the global `AWS.config` object and cannot be
5128 * overridden in service-specific configuration. Defaults to 0 milliseconds.
5129 *
5130 * @!attribute signatureVersion
5131 * @return [String] the signature version to sign requests with (overriding
5132 * the API configuration). Possible values are: 'v2', 'v3', 'v4'.
5133 *
5134 * @!attribute signatureCache
5135 * @return [Boolean] whether the signature to sign requests with (overriding
5136 * the API configuration) is cached. Only applies to the signature version 'v4'.
5137 * Defaults to `true`.
5138 *
5139 * @!attribute endpointDiscoveryEnabled
5140 * @return [Boolean] whether to enable endpoint discovery for operations that
5141 * allow optionally using an endpoint returned by the service.
5142 * Defaults to 'false'
5143 *
5144 * @!attribute endpointCacheSize
5145 * @return [Number] the size of the global cache storing endpoints from endpoint
5146 * discovery operations. Once endpoint cache is created, updating this setting
5147 * cannot change existing cache size.
5148 * Defaults to 1000
5149 *
5150 * @!attribute hostPrefixEnabled
5151 * @return [Boolean] whether to marshal request parameters to the prefix of
5152 * hostname. Defaults to `true`.
5153 */
5154 AWS.Config = AWS.util.inherit({
5155 /**
5156 * @!endgroup
5157 */
5158
5159 /**
5160 * Creates a new configuration object. This is the object that passes
5161 * option data along to service requests, including credentials, security,
5162 * region information, and some service specific settings.
5163 *
5164 * @example Creating a new configuration object with credentials and region
5165 * var config = new AWS.Config({
5166 * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
5167 * });
5168 * @option options accessKeyId [String] your AWS access key ID.
5169 * @option options secretAccessKey [String] your AWS secret access key.
5170 * @option options sessionToken [AWS.Credentials] the optional AWS
5171 * session token to sign requests with.
5172 * @option options credentials [AWS.Credentials] the AWS credentials
5173 * to sign requests with. You can either specify this object, or
5174 * specify the accessKeyId and secretAccessKey options directly.
5175 * @option options credentialProvider [AWS.CredentialProviderChain] the
5176 * provider chain used to resolve credentials if no static `credentials`
5177 * property is set.
5178 * @option options region [String] the region to send service requests to.
5179 * See {region} for more information.
5180 * @option options maxRetries [Integer] the maximum amount of retries to
5181 * attempt with a request. See {maxRetries} for more information.
5182 * @option options maxRedirects [Integer] the maximum amount of redirects to
5183 * follow with a request. See {maxRedirects} for more information.
5184 * @option options sslEnabled [Boolean] whether to enable SSL for
5185 * requests.
5186 * @option options paramValidation [Boolean|map] whether input parameters
5187 * should be validated against the operation description before sending
5188 * the request. Defaults to true. Pass a map to enable any of the
5189 * following specific validation features:
5190 *
5191 * * **min** [Boolean] &mdash; Validates that a value meets the min
5192 * constraint. This is enabled by default when paramValidation is set
5193 * to `true`.
5194 * * **max** [Boolean] &mdash; Validates that a value meets the max
5195 * constraint.
5196 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5197 * regular expression.
5198 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5199 * of the allowable enum values.
5200 * @option options computeChecksums [Boolean] whether to compute checksums
5201 * for payload bodies when the service accepts it (currently supported
5202 * in S3 only)
5203 * @option options convertResponseTypes [Boolean] whether types are converted
5204 * when parsing response data. Currently only supported for JSON based
5205 * services. Turning this off may improve performance on large response
5206 * payloads. Defaults to `true`.
5207 * @option options correctClockSkew [Boolean] whether to apply a clock skew
5208 * correction and retry requests that fail because of an skewed client
5209 * clock. Defaults to `false`.
5210 * @option options s3ForcePathStyle [Boolean] whether to force path
5211 * style URLs for S3 objects.
5212 * @option options s3BucketEndpoint [Boolean] whether the provided endpoint
5213 * addresses an individual bucket (false if it addresses the root API
5214 * endpoint). Note that setting this configuration option requires an
5215 * `endpoint` to be provided explicitly to the service constructor.
5216 * @option options s3DisableBodySigning [Boolean] whether S3 body signing
5217 * should be disabled when using signature version `v4`. Body signing
5218 * can only be disabled when using https. Defaults to `true`.
5219 *
5220 * @option options retryDelayOptions [map] A set of options to configure
5221 * the retry delay on retryable errors. Currently supported options are:
5222 *
5223 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5224 * exponential backoff for operation retries. Defaults to 100 ms for all
5225 * services except DynamoDB, where it defaults to 50ms.
5226 * * **customBackoff ** [function] &mdash; A custom function that accepts a retry count
5227 * and returns the amount of time to delay in milliseconds. The `base` option will be
5228 * ignored if this option is supplied.
5229 * @option options httpOptions [map] A set of options to pass to the low-level
5230 * HTTP request. Currently supported options are:
5231 *
5232 * * **proxy** [String] &mdash; the URL to proxy requests through
5233 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5234 * HTTP requests with. Used for connection pooling. Defaults to the global
5235 * agent (`http.globalAgent`) for non-SSL connections. Note that for
5236 * SSL connections, a special Agent object is used in order to enable
5237 * peer certificate verification. This feature is only available in the
5238 * Node.js environment.
5239 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5240 * failing to establish a connection with the server after
5241 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5242 * connection has been established.
5243 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5244 * milliseconds of inactivity on the socket. Defaults to two minutes
5245 * (120000).
5246 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5247 * HTTP requests. Used in the browser environment only. Set to false to
5248 * send requests synchronously. Defaults to true (async on).
5249 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5250 * property of an XMLHttpRequest object. Used in the browser environment
5251 * only. Defaults to false.
5252 * @option options apiVersion [String, Date] a String in YYYY-MM-DD format
5253 * (or a date) that represents the latest possible API version that can be
5254 * used in all services (unless overridden by `apiVersions`). Specify
5255 * 'latest' to use the latest possible version.
5256 * @option options apiVersions [map<String, String|Date>] a map of service
5257 * identifiers (the lowercase service class name) with the API version to
5258 * use when instantiating a service. Specify 'latest' for each individual
5259 * that can use the latest available version.
5260 * @option options logger [#write,#log] an object that responds to .write()
5261 * (like a stream) or .log() (like the console object) in order to log
5262 * information about requests
5263 * @option options systemClockOffset [Number] an offset value in milliseconds
5264 * to apply to all signing times. Use this to compensate for clock skew
5265 * when your system may be out of sync with the service time. Note that
5266 * this configuration option can only be applied to the global `AWS.config`
5267 * object and cannot be overridden in service-specific configuration.
5268 * Defaults to 0 milliseconds.
5269 * @option options signatureVersion [String] the signature version to sign
5270 * requests with (overriding the API configuration). Possible values are:
5271 * 'v2', 'v3', 'v4'.
5272 * @option options signatureCache [Boolean] whether the signature to sign
5273 * requests with (overriding the API configuration) is cached. Only applies
5274 * to the signature version 'v4'. Defaults to `true`.
5275 * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32
5276 * checksum of HTTP response bodies returned by DynamoDB. Default: `true`.
5277 * @option options useAccelerateEndpoint [Boolean] Whether to use the
5278 * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`.
5279 * @option options clientSideMonitoring [Boolean] whether to collect and
5280 * publish this client's performance metrics of all its API requests.
5281 * @option options endpointDiscoveryEnabled [Boolean] whether to enable endpoint
5282 * discovery for operations that allow optionally using an endpoint returned by
5283 * the service.
5284 * Defaults to 'false'
5285 * @option options endpointCacheSize [Number] the size of the global cache storing
5286 * endpoints from endpoint discovery operations. Once endpoint cache is created,
5287 * updating this setting cannot change existing cache size.
5288 * Defaults to 1000
5289 * @option options hostPrefixEnabled [Boolean] whether to marshal request
5290 * parameters to the prefix of hostname.
5291 * Defaults to `true`.
5292 */
5293 constructor: function Config(options) {
5294 if (options === undefined) options = {};
5295 options = this.extractCredentials(options);
5296
5297 AWS.util.each.call(this, this.keys, function (key, value) {
5298 this.set(key, options[key], value);
5299 });
5300 },
5301
5302 /**
5303 * @!group Managing Credentials
5304 */
5305
5306 /**
5307 * Loads credentials from the configuration object. This is used internally
5308 * by the SDK to ensure that refreshable {Credentials} objects are properly
5309 * refreshed and loaded when sending a request. If you want to ensure that
5310 * your credentials are loaded prior to a request, you can use this method
5311 * directly to provide accurate credential data stored in the object.
5312 *
5313 * @note If you configure the SDK with static or environment credentials,
5314 * the credential data should already be present in {credentials} attribute.
5315 * This method is primarily necessary to load credentials from asynchronous
5316 * sources, or sources that can refresh credentials periodically.
5317 * @example Getting your access key
5318 * AWS.config.getCredentials(function(err) {
5319 * if (err) console.log(err.stack); // credentials not loaded
5320 * else console.log("Access Key:", AWS.config.credentials.accessKeyId);
5321 * })
5322 * @callback callback function(err)
5323 * Called when the {credentials} have been properly set on the configuration
5324 * object.
5325 *
5326 * @param err [Error] if this is set, credentials were not successfully
5327 * loaded and this error provides information why.
5328 * @see credentials
5329 * @see Credentials
5330 */
5331 getCredentials: function getCredentials(callback) {
5332 var self = this;
5333
5334 function finish(err) {
5335 callback(err, err ? null : self.credentials);
5336 }
5337
5338 function credError(msg, err) {
5339 return new AWS.util.error(err || new Error(), {
5340 code: 'CredentialsError',
5341 message: msg,
5342 name: 'CredentialsError'
5343 });
5344 }
5345
5346 function getAsyncCredentials() {
5347 self.credentials.get(function(err) {
5348 if (err) {
5349 var msg = 'Could not load credentials from ' +
5350 self.credentials.constructor.name;
5351 err = credError(msg, err);
5352 }
5353 finish(err);
5354 });
5355 }
5356
5357 function getStaticCredentials() {
5358 var err = null;
5359 if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
5360 err = credError('Missing credentials');
5361 }
5362 finish(err);
5363 }
5364
5365 if (self.credentials) {
5366 if (typeof self.credentials.get === 'function') {
5367 getAsyncCredentials();
5368 } else { // static credentials
5369 getStaticCredentials();
5370 }
5371 } else if (self.credentialProvider) {
5372 self.credentialProvider.resolve(function(err, creds) {
5373 if (err) {
5374 err = credError('Could not load credentials from any providers', err);
5375 }
5376 self.credentials = creds;
5377 finish(err);
5378 });
5379 } else {
5380 finish(credError('No credentials to load'));
5381 }
5382 },
5383
5384 /**
5385 * @!group Loading and Setting Configuration Options
5386 */
5387
5388 /**
5389 * @overload update(options, allowUnknownKeys = false)
5390 * Updates the current configuration object with new options.
5391 *
5392 * @example Update maxRetries property of a configuration object
5393 * config.update({maxRetries: 10});
5394 * @param [Object] options a map of option keys and values.
5395 * @param [Boolean] allowUnknownKeys whether unknown keys can be set on
5396 * the configuration object. Defaults to `false`.
5397 * @see constructor
5398 */
5399 update: function update(options, allowUnknownKeys) {
5400 allowUnknownKeys = allowUnknownKeys || false;
5401 options = this.extractCredentials(options);
5402 AWS.util.each.call(this, options, function (key, value) {
5403 if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) ||
5404 AWS.Service.hasService(key)) {
5405 this.set(key, value);
5406 }
5407 });
5408 },
5409
5410 /**
5411 * Loads configuration data from a JSON file into this config object.
5412 * @note Loading configuration will reset all existing configuration
5413 * on the object.
5414 * @!macro nobrowser
5415 * @param path [String] the path relative to your process's current
5416 * working directory to load configuration from.
5417 * @return [AWS.Config] the same configuration object
5418 */
5419 loadFromPath: function loadFromPath(path) {
5420 this.clear();
5421
5422 var options = JSON.parse(AWS.util.readFileSync(path));
5423 var fileSystemCreds = new AWS.FileSystemCredentials(path);
5424 var chain = new AWS.CredentialProviderChain();
5425 chain.providers.unshift(fileSystemCreds);
5426 chain.resolve(function (err, creds) {
5427 if (err) throw err;
5428 else options.credentials = creds;
5429 });
5430
5431 this.constructor(options);
5432
5433 return this;
5434 },
5435
5436 /**
5437 * Clears configuration data on this object
5438 *
5439 * @api private
5440 */
5441 clear: function clear() {
5442 /*jshint forin:false */
5443 AWS.util.each.call(this, this.keys, function (key) {
5444 delete this[key];
5445 });
5446
5447 // reset credential provider
5448 this.set('credentials', undefined);
5449 this.set('credentialProvider', undefined);
5450 },
5451
5452 /**
5453 * Sets a property on the configuration object, allowing for a
5454 * default value
5455 * @api private
5456 */
5457 set: function set(property, value, defaultValue) {
5458 if (value === undefined) {
5459 if (defaultValue === undefined) {
5460 defaultValue = this.keys[property];
5461 }
5462 if (typeof defaultValue === 'function') {
5463 this[property] = defaultValue.call(this);
5464 } else {
5465 this[property] = defaultValue;
5466 }
5467 } else if (property === 'httpOptions' && this[property]) {
5468 // deep merge httpOptions
5469 this[property] = AWS.util.merge(this[property], value);
5470 } else {
5471 this[property] = value;
5472 }
5473 },
5474
5475 /**
5476 * All of the keys with their default values.
5477 *
5478 * @constant
5479 * @api private
5480 */
5481 keys: {
5482 credentials: null,
5483 credentialProvider: null,
5484 region: null,
5485 logger: null,
5486 apiVersions: {},
5487 apiVersion: null,
5488 endpoint: undefined,
5489 httpOptions: {
5490 timeout: 120000
5491 },
5492 maxRetries: undefined,
5493 maxRedirects: 10,
5494 paramValidation: true,
5495 sslEnabled: true,
5496 s3ForcePathStyle: false,
5497 s3BucketEndpoint: false,
5498 s3DisableBodySigning: true,
5499 computeChecksums: true,
5500 convertResponseTypes: true,
5501 correctClockSkew: false,
5502 customUserAgent: null,
5503 dynamoDbCrc32: true,
5504 systemClockOffset: 0,
5505 signatureVersion: null,
5506 signatureCache: true,
5507 retryDelayOptions: {},
5508 useAccelerateEndpoint: false,
5509 clientSideMonitoring: false,
5510 endpointDiscoveryEnabled: false,
5511 endpointCacheSize: 1000,
5512 hostPrefixEnabled: true
5513 },
5514
5515 /**
5516 * Extracts accessKeyId, secretAccessKey and sessionToken
5517 * from a configuration hash.
5518 *
5519 * @api private
5520 */
5521 extractCredentials: function extractCredentials(options) {
5522 if (options.accessKeyId && options.secretAccessKey) {
5523 options = AWS.util.copy(options);
5524 options.credentials = new AWS.Credentials(options);
5525 }
5526 return options;
5527 },
5528
5529 /**
5530 * Sets the promise dependency the SDK will use wherever Promises are returned.
5531 * Passing `null` will force the SDK to use native Promises if they are available.
5532 * If native Promises are not available, passing `null` will have no effect.
5533 * @param [Constructor] dep A reference to a Promise constructor
5534 */
5535 setPromisesDependency: function setPromisesDependency(dep) {
5536 PromisesDependency = dep;
5537 // if null was passed in, we should try to use native promises
5538 if (dep === null && typeof Promise === 'function') {
5539 PromisesDependency = Promise;
5540 }
5541 var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain];
5542 if (AWS.S3 && AWS.S3.ManagedUpload) constructors.push(AWS.S3.ManagedUpload);
5543 AWS.util.addPromises(constructors, PromisesDependency);
5544 },
5545
5546 /**
5547 * Gets the promise dependency set by `AWS.config.setPromisesDependency`.
5548 */
5549 getPromisesDependency: function getPromisesDependency() {
5550 return PromisesDependency;
5551 }
5552 });
5553
5554 /**
5555 * @return [AWS.Config] The global configuration object singleton instance
5556 * @readonly
5557 * @see AWS.Config
5558 */
5559 AWS.config = new AWS.Config();
5560
5561
5562/***/ }),
5563/* 41 */
5564/***/ (function(module, exports, __webpack_require__) {
5565
5566 var AWS = __webpack_require__(1);
5567
5568 /**
5569 * Represents your AWS security credentials, specifically the
5570 * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}.
5571 * Creating a `Credentials` object allows you to pass around your
5572 * security information to configuration and service objects.
5573 *
5574 * Note that this class typically does not need to be constructed manually,
5575 * as the {AWS.Config} and {AWS.Service} classes both accept simple
5576 * options hashes with the three keys. These structures will be converted
5577 * into Credentials objects automatically.
5578 *
5579 * ## Expiring and Refreshing Credentials
5580 *
5581 * Occasionally credentials can expire in the middle of a long-running
5582 * application. In this case, the SDK will automatically attempt to
5583 * refresh the credentials from the storage location if the Credentials
5584 * class implements the {refresh} method.
5585 *
5586 * If you are implementing a credential storage location, you
5587 * will want to create a subclass of the `Credentials` class and
5588 * override the {refresh} method. This method allows credentials to be
5589 * retrieved from the backing store, be it a file system, database, or
5590 * some network storage. The method should reset the credential attributes
5591 * on the object.
5592 *
5593 * @!attribute expired
5594 * @return [Boolean] whether the credentials have been expired and
5595 * require a refresh. Used in conjunction with {expireTime}.
5596 * @!attribute expireTime
5597 * @return [Date] a time when credentials should be considered expired. Used
5598 * in conjunction with {expired}.
5599 * @!attribute accessKeyId
5600 * @return [String] the AWS access key ID
5601 * @!attribute secretAccessKey
5602 * @return [String] the AWS secret access key
5603 * @!attribute sessionToken
5604 * @return [String] an optional AWS session token
5605 */
5606 AWS.Credentials = AWS.util.inherit({
5607 /**
5608 * A credentials object can be created using positional arguments or an options
5609 * hash.
5610 *
5611 * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
5612 * Creates a Credentials object with a given set of credential information
5613 * as positional arguments.
5614 * @param accessKeyId [String] the AWS access key ID
5615 * @param secretAccessKey [String] the AWS secret access key
5616 * @param sessionToken [String] the optional AWS session token
5617 * @example Create a credentials object with AWS credentials
5618 * var creds = new AWS.Credentials('akid', 'secret', 'session');
5619 * @overload AWS.Credentials(options)
5620 * Creates a Credentials object with a given set of credential information
5621 * as an options hash.
5622 * @option options accessKeyId [String] the AWS access key ID
5623 * @option options secretAccessKey [String] the AWS secret access key
5624 * @option options sessionToken [String] the optional AWS session token
5625 * @example Create a credentials object with AWS credentials
5626 * var creds = new AWS.Credentials({
5627 * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
5628 * });
5629 */
5630 constructor: function Credentials() {
5631 // hide secretAccessKey from being displayed with util.inspect
5632 AWS.util.hideProperties(this, ['secretAccessKey']);
5633
5634 this.expired = false;
5635 this.expireTime = null;
5636 this.refreshCallbacks = [];
5637 if (arguments.length === 1 && typeof arguments[0] === 'object') {
5638 var creds = arguments[0].credentials || arguments[0];
5639 this.accessKeyId = creds.accessKeyId;
5640 this.secretAccessKey = creds.secretAccessKey;
5641 this.sessionToken = creds.sessionToken;
5642 } else {
5643 this.accessKeyId = arguments[0];
5644 this.secretAccessKey = arguments[1];
5645 this.sessionToken = arguments[2];
5646 }
5647 },
5648
5649 /**
5650 * @return [Integer] the number of seconds before {expireTime} during which
5651 * the credentials will be considered expired.
5652 */
5653 expiryWindow: 15,
5654
5655 /**
5656 * @return [Boolean] whether the credentials object should call {refresh}
5657 * @note Subclasses should override this method to provide custom refresh
5658 * logic.
5659 */
5660 needsRefresh: function needsRefresh() {
5661 var currentTime = AWS.util.date.getDate().getTime();
5662 var adjustedTime = new Date(currentTime + this.expiryWindow * 1000);
5663
5664 if (this.expireTime && adjustedTime > this.expireTime) {
5665 return true;
5666 } else {
5667 return this.expired || !this.accessKeyId || !this.secretAccessKey;
5668 }
5669 },
5670
5671 /**
5672 * Gets the existing credentials, refreshing them if they are not yet loaded
5673 * or have expired. Users should call this method before using {refresh},
5674 * as this will not attempt to reload credentials when they are already
5675 * loaded into the object.
5676 *
5677 * @callback callback function(err)
5678 * When this callback is called with no error, it means either credentials
5679 * do not need to be refreshed or refreshed credentials information has
5680 * been loaded into the object (as the `accessKeyId`, `secretAccessKey`,
5681 * and `sessionToken` properties).
5682 * @param err [Error] if an error occurred, this value will be filled
5683 */
5684 get: function get(callback) {
5685 var self = this;
5686 if (this.needsRefresh()) {
5687 this.refresh(function(err) {
5688 if (!err) self.expired = false; // reset expired flag
5689 if (callback) callback(err);
5690 });
5691 } else if (callback) {
5692 callback();
5693 }
5694 },
5695
5696 /**
5697 * @!method getPromise()
5698 * Returns a 'thenable' promise.
5699 * Gets the existing credentials, refreshing them if they are not yet loaded
5700 * or have expired. Users should call this method before using {refresh},
5701 * as this will not attempt to reload credentials when they are already
5702 * loaded into the object.
5703 *
5704 * Two callbacks can be provided to the `then` method on the returned promise.
5705 * The first callback will be called if the promise is fulfilled, and the second
5706 * callback will be called if the promise is rejected.
5707 * @callback fulfilledCallback function()
5708 * Called if the promise is fulfilled. When this callback is called, it
5709 * means either credentials do not need to be refreshed or refreshed
5710 * credentials information has been loaded into the object (as the
5711 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5712 * @callback rejectedCallback function(err)
5713 * Called if the promise is rejected.
5714 * @param err [Error] if an error occurred, this value will be filled
5715 * @return [Promise] A promise that represents the state of the `get` call.
5716 * @example Calling the `getPromise` method.
5717 * var promise = credProvider.getPromise();
5718 * promise.then(function() { ... }, function(err) { ... });
5719 */
5720
5721 /**
5722 * @!method refreshPromise()
5723 * Returns a 'thenable' promise.
5724 * Refreshes the credentials. Users should call {get} before attempting
5725 * to forcibly refresh credentials.
5726 *
5727 * Two callbacks can be provided to the `then` method on the returned promise.
5728 * The first callback will be called if the promise is fulfilled, and the second
5729 * callback will be called if the promise is rejected.
5730 * @callback fulfilledCallback function()
5731 * Called if the promise is fulfilled. When this callback is called, it
5732 * means refreshed credentials information has been loaded into the object
5733 * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5734 * @callback rejectedCallback function(err)
5735 * Called if the promise is rejected.
5736 * @param err [Error] if an error occurred, this value will be filled
5737 * @return [Promise] A promise that represents the state of the `refresh` call.
5738 * @example Calling the `refreshPromise` method.
5739 * var promise = credProvider.refreshPromise();
5740 * promise.then(function() { ... }, function(err) { ... });
5741 */
5742
5743 /**
5744 * Refreshes the credentials. Users should call {get} before attempting
5745 * to forcibly refresh credentials.
5746 *
5747 * @callback callback function(err)
5748 * When this callback is called with no error, it means refreshed
5749 * credentials information has been loaded into the object (as the
5750 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5751 * @param err [Error] if an error occurred, this value will be filled
5752 * @note Subclasses should override this class to reset the
5753 * {accessKeyId}, {secretAccessKey} and optional {sessionToken}
5754 * on the credentials object and then call the callback with
5755 * any error information.
5756 * @see get
5757 */
5758 refresh: function refresh(callback) {
5759 this.expired = false;
5760 callback();
5761 },
5762
5763 /**
5764 * @api private
5765 * @param callback
5766 */
5767 coalesceRefresh: function coalesceRefresh(callback, sync) {
5768 var self = this;
5769 if (self.refreshCallbacks.push(callback) === 1) {
5770 self.load(function onLoad(err) {
5771 AWS.util.arrayEach(self.refreshCallbacks, function(callback) {
5772 if (sync) {
5773 callback(err);
5774 } else {
5775 // callback could throw, so defer to ensure all callbacks are notified
5776 AWS.util.defer(function () {
5777 callback(err);
5778 });
5779 }
5780 });
5781 self.refreshCallbacks.length = 0;
5782 });
5783 }
5784 },
5785
5786 /**
5787 * @api private
5788 * @param callback
5789 */
5790 load: function load(callback) {
5791 callback();
5792 }
5793 });
5794
5795 /**
5796 * @api private
5797 */
5798 AWS.Credentials.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
5799 this.prototype.getPromise = AWS.util.promisifyMethod('get', PromiseDependency);
5800 this.prototype.refreshPromise = AWS.util.promisifyMethod('refresh', PromiseDependency);
5801 };
5802
5803 /**
5804 * @api private
5805 */
5806 AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() {
5807 delete this.prototype.getPromise;
5808 delete this.prototype.refreshPromise;
5809 };
5810
5811 AWS.util.addPromises(AWS.Credentials);
5812
5813
5814/***/ }),
5815/* 42 */
5816/***/ (function(module, exports, __webpack_require__) {
5817
5818 var AWS = __webpack_require__(1);
5819
5820 /**
5821 * Creates a credential provider chain that searches for AWS credentials
5822 * in a list of credential providers specified by the {providers} property.
5823 *
5824 * By default, the chain will use the {defaultProviders} to resolve credentials.
5825 * These providers will look in the environment using the
5826 * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes.
5827 *
5828 * ## Setting Providers
5829 *
5830 * Each provider in the {providers} list should be a function that returns
5831 * a {AWS.Credentials} object, or a hardcoded credentials object. The function
5832 * form allows for delayed execution of the credential construction.
5833 *
5834 * ## Resolving Credentials from a Chain
5835 *
5836 * Call {resolve} to return the first valid credential object that can be
5837 * loaded by the provider chain.
5838 *
5839 * For example, to resolve a chain with a custom provider that checks a file
5840 * on disk after the set of {defaultProviders}:
5841 *
5842 * ```javascript
5843 * var diskProvider = new AWS.FileSystemCredentials('./creds.json');
5844 * var chain = new AWS.CredentialProviderChain();
5845 * chain.providers.push(diskProvider);
5846 * chain.resolve();
5847 * ```
5848 *
5849 * The above code will return the `diskProvider` object if the
5850 * file contains credentials and the `defaultProviders` do not contain
5851 * any credential settings.
5852 *
5853 * @!attribute providers
5854 * @return [Array<AWS.Credentials, Function>]
5855 * a list of credentials objects or functions that return credentials
5856 * objects. If the provider is a function, the function will be
5857 * executed lazily when the provider needs to be checked for valid
5858 * credentials. By default, this object will be set to the
5859 * {defaultProviders}.
5860 * @see defaultProviders
5861 */
5862 AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, {
5863
5864 /**
5865 * Creates a new CredentialProviderChain with a default set of providers
5866 * specified by {defaultProviders}.
5867 */
5868 constructor: function CredentialProviderChain(providers) {
5869 if (providers) {
5870 this.providers = providers;
5871 } else {
5872 this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
5873 }
5874 this.resolveCallbacks = [];
5875 },
5876
5877 /**
5878 * @!method resolvePromise()
5879 * Returns a 'thenable' promise.
5880 * Resolves the provider chain by searching for the first set of
5881 * credentials in {providers}.
5882 *
5883 * Two callbacks can be provided to the `then` method on the returned promise.
5884 * The first callback will be called if the promise is fulfilled, and the second
5885 * callback will be called if the promise is rejected.
5886 * @callback fulfilledCallback function(credentials)
5887 * Called if the promise is fulfilled and the provider resolves the chain
5888 * to a credentials object
5889 * @param credentials [AWS.Credentials] the credentials object resolved
5890 * by the provider chain.
5891 * @callback rejectedCallback function(error)
5892 * Called if the promise is rejected.
5893 * @param err [Error] the error object returned if no credentials are found.
5894 * @return [Promise] A promise that represents the state of the `resolve` method call.
5895 * @example Calling the `resolvePromise` method.
5896 * var promise = chain.resolvePromise();
5897 * promise.then(function(credentials) { ... }, function(err) { ... });
5898 */
5899
5900 /**
5901 * Resolves the provider chain by searching for the first set of
5902 * credentials in {providers}.
5903 *
5904 * @callback callback function(err, credentials)
5905 * Called when the provider resolves the chain to a credentials object
5906 * or null if no credentials can be found.
5907 *
5908 * @param err [Error] the error object returned if no credentials are
5909 * found.
5910 * @param credentials [AWS.Credentials] the credentials object resolved
5911 * by the provider chain.
5912 * @return [AWS.CredentialProviderChain] the provider, for chaining.
5913 */
5914 resolve: function resolve(callback) {
5915 var self = this;
5916 if (self.providers.length === 0) {
5917 callback(new Error('No providers'));
5918 return self;
5919 }
5920
5921 if (self.resolveCallbacks.push(callback) === 1) {
5922 var index = 0;
5923 var providers = self.providers.slice(0);
5924
5925 function resolveNext(err, creds) {
5926 if ((!err && creds) || index === providers.length) {
5927 AWS.util.arrayEach(self.resolveCallbacks, function (callback) {
5928 callback(err, creds);
5929 });
5930 self.resolveCallbacks.length = 0;
5931 return;
5932 }
5933
5934 var provider = providers[index++];
5935 if (typeof provider === 'function') {
5936 creds = provider.call();
5937 } else {
5938 creds = provider;
5939 }
5940
5941 if (creds.get) {
5942 creds.get(function (getErr) {
5943 resolveNext(getErr, getErr ? null : creds);
5944 });
5945 } else {
5946 resolveNext(null, creds);
5947 }
5948 }
5949
5950 resolveNext();
5951 }
5952
5953 return self;
5954 }
5955 });
5956
5957 /**
5958 * The default set of providers used by a vanilla CredentialProviderChain.
5959 *
5960 * In the browser:
5961 *
5962 * ```javascript
5963 * AWS.CredentialProviderChain.defaultProviders = []
5964 * ```
5965 *
5966 * In Node.js:
5967 *
5968 * ```javascript
5969 * AWS.CredentialProviderChain.defaultProviders = [
5970 * function () { return new AWS.EnvironmentCredentials('AWS'); },
5971 * function () { return new AWS.EnvironmentCredentials('AMAZON'); },
5972 * function () { return new AWS.SharedIniFileCredentials(); },
5973 * function () { return new AWS.ECSCredentials(); },
5974 * function () { return new AWS.ProcessCredentials(); },
5975 * function () { return new AWS.EC2MetadataCredentials() }
5976 * ]
5977 * ```
5978 */
5979 AWS.CredentialProviderChain.defaultProviders = [];
5980
5981 /**
5982 * @api private
5983 */
5984 AWS.CredentialProviderChain.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
5985 this.prototype.resolvePromise = AWS.util.promisifyMethod('resolve', PromiseDependency);
5986 };
5987
5988 /**
5989 * @api private
5990 */
5991 AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFromClass() {
5992 delete this.prototype.resolvePromise;
5993 };
5994
5995 AWS.util.addPromises(AWS.CredentialProviderChain);
5996
5997
5998/***/ }),
5999/* 43 */
6000/***/ (function(module, exports, __webpack_require__) {
6001
6002 var AWS = __webpack_require__(1);
6003 var inherit = AWS.util.inherit;
6004
6005 /**
6006 * The endpoint that a service will talk to, for example,
6007 * `'https://ec2.ap-southeast-1.amazonaws.com'`. If
6008 * you need to override an endpoint for a service, you can
6009 * set the endpoint on a service by passing the endpoint
6010 * object with the `endpoint` option key:
6011 *
6012 * ```javascript
6013 * var ep = new AWS.Endpoint('awsproxy.example.com');
6014 * var s3 = new AWS.S3({endpoint: ep});
6015 * s3.service.endpoint.hostname == 'awsproxy.example.com'
6016 * ```
6017 *
6018 * Note that if you do not specify a protocol, the protocol will
6019 * be selected based on your current {AWS.config} configuration.
6020 *
6021 * @!attribute protocol
6022 * @return [String] the protocol (http or https) of the endpoint
6023 * URL
6024 * @!attribute hostname
6025 * @return [String] the host portion of the endpoint, e.g.,
6026 * example.com
6027 * @!attribute host
6028 * @return [String] the host portion of the endpoint including
6029 * the port, e.g., example.com:80
6030 * @!attribute port
6031 * @return [Integer] the port of the endpoint
6032 * @!attribute href
6033 * @return [String] the full URL of the endpoint
6034 */
6035 AWS.Endpoint = inherit({
6036
6037 /**
6038 * @overload Endpoint(endpoint)
6039 * Constructs a new endpoint given an endpoint URL. If the
6040 * URL omits a protocol (http or https), the default protocol
6041 * set in the global {AWS.config} will be used.
6042 * @param endpoint [String] the URL to construct an endpoint from
6043 */
6044 constructor: function Endpoint(endpoint, config) {
6045 AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']);
6046
6047 if (typeof endpoint === 'undefined' || endpoint === null) {
6048 throw new Error('Invalid endpoint: ' + endpoint);
6049 } else if (typeof endpoint !== 'string') {
6050 return AWS.util.copy(endpoint);
6051 }
6052
6053 if (!endpoint.match(/^http/)) {
6054 var useSSL = config && config.sslEnabled !== undefined ?
6055 config.sslEnabled : AWS.config.sslEnabled;
6056 endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
6057 }
6058
6059 AWS.util.update(this, AWS.util.urlParse(endpoint));
6060
6061 // Ensure the port property is set as an integer
6062 if (this.port) {
6063 this.port = parseInt(this.port, 10);
6064 } else {
6065 this.port = this.protocol === 'https:' ? 443 : 80;
6066 }
6067 }
6068
6069 });
6070
6071 /**
6072 * The low level HTTP request object, encapsulating all HTTP header
6073 * and body data sent by a service request.
6074 *
6075 * @!attribute method
6076 * @return [String] the HTTP method of the request
6077 * @!attribute path
6078 * @return [String] the path portion of the URI, e.g.,
6079 * "/list/?start=5&num=10"
6080 * @!attribute headers
6081 * @return [map<String,String>]
6082 * a map of header keys and their respective values
6083 * @!attribute body
6084 * @return [String] the request body payload
6085 * @!attribute endpoint
6086 * @return [AWS.Endpoint] the endpoint for the request
6087 * @!attribute region
6088 * @api private
6089 * @return [String] the region, for signing purposes only.
6090 */
6091 AWS.HttpRequest = inherit({
6092
6093 /**
6094 * @api private
6095 */
6096 constructor: function HttpRequest(endpoint, region) {
6097 endpoint = new AWS.Endpoint(endpoint);
6098 this.method = 'POST';
6099 this.path = endpoint.path || '/';
6100 this.headers = {};
6101 this.body = '';
6102 this.endpoint = endpoint;
6103 this.region = region;
6104 this._userAgent = '';
6105 this.setUserAgent();
6106 },
6107
6108 /**
6109 * @api private
6110 */
6111 setUserAgent: function setUserAgent() {
6112 this._userAgent = this.headers[this.getUserAgentHeaderName()] = AWS.util.userAgent();
6113 },
6114
6115 getUserAgentHeaderName: function getUserAgentHeaderName() {
6116 var prefix = AWS.util.isBrowser() ? 'X-Amz-' : '';
6117 return prefix + 'User-Agent';
6118 },
6119
6120 /**
6121 * @api private
6122 */
6123 appendToUserAgent: function appendToUserAgent(agentPartial) {
6124 if (typeof agentPartial === 'string' && agentPartial) {
6125 this._userAgent += ' ' + agentPartial;
6126 }
6127 this.headers[this.getUserAgentHeaderName()] = this._userAgent;
6128 },
6129
6130 /**
6131 * @api private
6132 */
6133 getUserAgent: function getUserAgent() {
6134 return this._userAgent;
6135 },
6136
6137 /**
6138 * @return [String] the part of the {path} excluding the
6139 * query string
6140 */
6141 pathname: function pathname() {
6142 return this.path.split('?', 1)[0];
6143 },
6144
6145 /**
6146 * @return [String] the query string portion of the {path}
6147 */
6148 search: function search() {
6149 var query = this.path.split('?', 2)[1];
6150 if (query) {
6151 query = AWS.util.queryStringParse(query);
6152 return AWS.util.queryParamsToString(query);
6153 }
6154 return '';
6155 },
6156
6157 /**
6158 * @api private
6159 * update httpRequest endpoint with endpoint string
6160 */
6161 updateEndpoint: function updateEndpoint(endpointStr) {
6162 var newEndpoint = new AWS.Endpoint(endpointStr);
6163 this.endpoint = newEndpoint;
6164 this.path = newEndpoint.path || '/';
6165 }
6166 });
6167
6168 /**
6169 * The low level HTTP response object, encapsulating all HTTP header
6170 * and body data returned from the request.
6171 *
6172 * @!attribute statusCode
6173 * @return [Integer] the HTTP status code of the response (e.g., 200, 404)
6174 * @!attribute headers
6175 * @return [map<String,String>]
6176 * a map of response header keys and their respective values
6177 * @!attribute body
6178 * @return [String] the response body payload
6179 * @!attribute [r] streaming
6180 * @return [Boolean] whether this response is being streamed at a low-level.
6181 * Defaults to `false` (buffered reads). Do not modify this manually, use
6182 * {createUnbufferedStream} to convert the stream to unbuffered mode
6183 * instead.
6184 */
6185 AWS.HttpResponse = inherit({
6186
6187 /**
6188 * @api private
6189 */
6190 constructor: function HttpResponse() {
6191 this.statusCode = undefined;
6192 this.headers = {};
6193 this.body = undefined;
6194 this.streaming = false;
6195 this.stream = null;
6196 },
6197
6198 /**
6199 * Disables buffering on the HTTP response and returns the stream for reading.
6200 * @return [Stream, XMLHttpRequest, null] the underlying stream object.
6201 * Use this object to directly read data off of the stream.
6202 * @note This object is only available after the {AWS.Request~httpHeaders}
6203 * event has fired. This method must be called prior to
6204 * {AWS.Request~httpData}.
6205 * @example Taking control of a stream
6206 * request.on('httpHeaders', function(statusCode, headers) {
6207 * if (statusCode < 300) {
6208 * if (headers.etag === 'xyz') {
6209 * // pipe the stream, disabling buffering
6210 * var stream = this.response.httpResponse.createUnbufferedStream();
6211 * stream.pipe(process.stdout);
6212 * } else { // abort this request and set a better error message
6213 * this.abort();
6214 * this.response.error = new Error('Invalid ETag');
6215 * }
6216 * }
6217 * }).send(console.log);
6218 */
6219 createUnbufferedStream: function createUnbufferedStream() {
6220 this.streaming = true;
6221 return this.stream;
6222 }
6223 });
6224
6225
6226 AWS.HttpClient = inherit({});
6227
6228 /**
6229 * @api private
6230 */
6231 AWS.HttpClient.getInstance = function getInstance() {
6232 if (this.singleton === undefined) {
6233 this.singleton = new this();
6234 }
6235 return this.singleton;
6236 };
6237
6238
6239/***/ }),
6240/* 44 */
6241/***/ (function(module, exports, __webpack_require__) {
6242
6243 var AWS = __webpack_require__(1);
6244 var SequentialExecutor = __webpack_require__(36);
6245 var DISCOVER_ENDPOINT = __webpack_require__(45).discoverEndpoint;
6246 /**
6247 * The namespace used to register global event listeners for request building
6248 * and sending.
6249 */
6250 AWS.EventListeners = {
6251 /**
6252 * @!attribute VALIDATE_CREDENTIALS
6253 * A request listener that validates whether the request is being
6254 * sent with credentials.
6255 * Handles the {AWS.Request~validate 'validate' Request event}
6256 * @example Sending a request without validating credentials
6257 * var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS;
6258 * request.removeListener('validate', listener);
6259 * @readonly
6260 * @return [Function]
6261 * @!attribute VALIDATE_REGION
6262 * A request listener that validates whether the region is set
6263 * for a request.
6264 * Handles the {AWS.Request~validate 'validate' Request event}
6265 * @example Sending a request without validating region configuration
6266 * var listener = AWS.EventListeners.Core.VALIDATE_REGION;
6267 * request.removeListener('validate', listener);
6268 * @readonly
6269 * @return [Function]
6270 * @!attribute VALIDATE_PARAMETERS
6271 * A request listener that validates input parameters in a request.
6272 * Handles the {AWS.Request~validate 'validate' Request event}
6273 * @example Sending a request without validating parameters
6274 * var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS;
6275 * request.removeListener('validate', listener);
6276 * @example Disable parameter validation globally
6277 * AWS.EventListeners.Core.removeListener('validate',
6278 * AWS.EventListeners.Core.VALIDATE_REGION);
6279 * @readonly
6280 * @return [Function]
6281 * @!attribute SEND
6282 * A request listener that initiates the HTTP connection for a
6283 * request being sent. Handles the {AWS.Request~send 'send' Request event}
6284 * @example Replacing the HTTP handler
6285 * var listener = AWS.EventListeners.Core.SEND;
6286 * request.removeListener('send', listener);
6287 * request.on('send', function(response) {
6288 * customHandler.send(response);
6289 * });
6290 * @return [Function]
6291 * @readonly
6292 * @!attribute HTTP_DATA
6293 * A request listener that reads data from the HTTP connection in order
6294 * to build the response data.
6295 * Handles the {AWS.Request~httpData 'httpData' Request event}.
6296 * Remove this handler if you are overriding the 'httpData' event and
6297 * do not want extra data processing and buffering overhead.
6298 * @example Disabling default data processing
6299 * var listener = AWS.EventListeners.Core.HTTP_DATA;
6300 * request.removeListener('httpData', listener);
6301 * @return [Function]
6302 * @readonly
6303 */
6304 Core: {} /* doc hack */
6305 };
6306
6307 /**
6308 * @api private
6309 */
6310 function getOperationAuthtype(req) {
6311 if (!req.service.api.operations) {
6312 return '';
6313 }
6314 var operation = req.service.api.operations[req.operation];
6315 return operation ? operation.authtype : '';
6316 }
6317
6318 AWS.EventListeners = {
6319 Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) {
6320 addAsync('VALIDATE_CREDENTIALS', 'validate',
6321 function VALIDATE_CREDENTIALS(req, done) {
6322 if (!req.service.api.signatureVersion) return done(); // none
6323 req.service.config.getCredentials(function(err) {
6324 if (err) {
6325 req.response.error = AWS.util.error(err,
6326 {code: 'CredentialsError', message: 'Missing credentials in config'});
6327 }
6328 done();
6329 });
6330 });
6331
6332 add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
6333 if (!req.service.config.region && !req.service.isGlobalEndpoint) {
6334 req.response.error = AWS.util.error(new Error(),
6335 {code: 'ConfigError', message: 'Missing region in config'});
6336 }
6337 });
6338
6339 add('BUILD_IDEMPOTENCY_TOKENS', 'validate', function BUILD_IDEMPOTENCY_TOKENS(req) {
6340 if (!req.service.api.operations) {
6341 return;
6342 }
6343 var operation = req.service.api.operations[req.operation];
6344 if (!operation) {
6345 return;
6346 }
6347 var idempotentMembers = operation.idempotentMembers;
6348 if (!idempotentMembers.length) {
6349 return;
6350 }
6351 // creates a copy of params so user's param object isn't mutated
6352 var params = AWS.util.copy(req.params);
6353 for (var i = 0, iLen = idempotentMembers.length; i < iLen; i++) {
6354 if (!params[idempotentMembers[i]]) {
6355 // add the member
6356 params[idempotentMembers[i]] = AWS.util.uuid.v4();
6357 }
6358 }
6359 req.params = params;
6360 });
6361
6362 add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) {
6363 if (!req.service.api.operations) {
6364 return;
6365 }
6366 var rules = req.service.api.operations[req.operation].input;
6367 var validation = req.service.config.paramValidation;
6368 new AWS.ParamValidator(validation).validate(rules, req.params);
6369 });
6370
6371 addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) {
6372 req.haltHandlersOnError();
6373 if (!req.service.api.operations) {
6374 return;
6375 }
6376 var operation = req.service.api.operations[req.operation];
6377 var authtype = operation ? operation.authtype : '';
6378 if (!req.service.api.signatureVersion && !authtype) return done(); // none
6379 if (req.service.getSignerClass(req) === AWS.Signers.V4) {
6380 var body = req.httpRequest.body || '';
6381 if (authtype.indexOf('unsigned-body') >= 0) {
6382 req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD';
6383 return done();
6384 }
6385 AWS.util.computeSha256(body, function(err, sha) {
6386 if (err) {
6387 done(err);
6388 }
6389 else {
6390 req.httpRequest.headers['X-Amz-Content-Sha256'] = sha;
6391 done();
6392 }
6393 });
6394 } else {
6395 done();
6396 }
6397 });
6398
6399 add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) {
6400 var authtype = getOperationAuthtype(req);
6401 if (req.httpRequest.headers['Content-Length'] === undefined) {
6402 try {
6403 var length = AWS.util.string.byteLength(req.httpRequest.body);
6404 req.httpRequest.headers['Content-Length'] = length;
6405 } catch (err) {
6406 if (authtype.indexOf('unsigned-body') === -1) {
6407 throw err;
6408 } else {
6409 // Body isn't signed and may not need content length (lex)
6410 return;
6411 }
6412 }
6413 }
6414 });
6415
6416 add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) {
6417 req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host;
6418 });
6419
6420 add('RESTART', 'restart', function RESTART() {
6421 var err = this.response.error;
6422 if (!err || !err.retryable) return;
6423
6424 this.httpRequest = new AWS.HttpRequest(
6425 this.service.endpoint,
6426 this.service.region
6427 );
6428
6429 if (this.response.retryCount < this.service.config.maxRetries) {
6430 this.response.retryCount++;
6431 } else {
6432 this.response.error = null;
6433 }
6434 });
6435
6436 var addToHead = true;
6437 addAsync('DISCOVER_ENDPOINT', 'sign', DISCOVER_ENDPOINT, addToHead);
6438
6439 addAsync('SIGN', 'sign', function SIGN(req, done) {
6440 var service = req.service;
6441 var operations = req.service.api.operations || {};
6442 var operation = operations[req.operation];
6443 var authtype = operation ? operation.authtype : '';
6444 if (!service.api.signatureVersion && !authtype) return done(); // none
6445
6446 service.config.getCredentials(function (err, credentials) {
6447 if (err) {
6448 req.response.error = err;
6449 return done();
6450 }
6451
6452 try {
6453 var date = service.getSkewCorrectedDate();
6454 var SignerClass = service.getSignerClass(req);
6455 var signer = new SignerClass(req.httpRequest,
6456 service.api.signingName || service.api.endpointPrefix,
6457 {
6458 signatureCache: service.config.signatureCache,
6459 operation: operation,
6460 signatureVersion: service.api.signatureVersion
6461 });
6462 signer.setServiceClientId(service._clientId);
6463
6464 // clear old authorization headers
6465 delete req.httpRequest.headers['Authorization'];
6466 delete req.httpRequest.headers['Date'];
6467 delete req.httpRequest.headers['X-Amz-Date'];
6468
6469 // add new authorization
6470 signer.addAuthorization(credentials, date);
6471 req.signedAt = date;
6472 } catch (e) {
6473 req.response.error = e;
6474 }
6475 done();
6476 });
6477 });
6478
6479 add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) {
6480 if (this.service.successfulResponse(resp, this)) {
6481 resp.data = {};
6482 resp.error = null;
6483 } else {
6484 resp.data = null;
6485 resp.error = AWS.util.error(new Error(),
6486 {code: 'UnknownError', message: 'An unknown error occurred.'});
6487 }
6488 });
6489
6490 addAsync('SEND', 'send', function SEND(resp, done) {
6491 resp.httpResponse._abortCallback = done;
6492 resp.error = null;
6493 resp.data = null;
6494
6495 function callback(httpResp) {
6496 resp.httpResponse.stream = httpResp;
6497 var stream = resp.request.httpRequest.stream;
6498 var service = resp.request.service;
6499 var api = service.api;
6500 var operationName = resp.request.operation;
6501 var operation = api.operations[operationName] || {};
6502
6503 httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) {
6504 resp.request.emit(
6505 'httpHeaders',
6506 [statusCode, headers, resp, statusMessage]
6507 );
6508
6509 if (!resp.httpResponse.streaming) {
6510 if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check
6511 // if we detect event streams, we're going to have to
6512 // return the stream immediately
6513 if (operation.hasEventOutput && service.successfulResponse(resp)) {
6514 // skip reading the IncomingStream
6515 resp.request.emit('httpDone');
6516 done();
6517 return;
6518 }
6519
6520 httpResp.on('readable', function onReadable() {
6521 var data = httpResp.read();
6522 if (data !== null) {
6523 resp.request.emit('httpData', [data, resp]);
6524 }
6525 });
6526 } else { // legacy streams API
6527 httpResp.on('data', function onData(data) {
6528 resp.request.emit('httpData', [data, resp]);
6529 });
6530 }
6531 }
6532 });
6533
6534 httpResp.on('end', function onEnd() {
6535 if (!stream || !stream.didCallback) {
6536 if (AWS.HttpClient.streamsApiVersion === 2 && (operation.hasEventOutput && service.successfulResponse(resp))) {
6537 // don't concatenate response chunks when streaming event stream data when response is successful
6538 return;
6539 }
6540 resp.request.emit('httpDone');
6541 done();
6542 }
6543 });
6544 }
6545
6546 function progress(httpResp) {
6547 httpResp.on('sendProgress', function onSendProgress(value) {
6548 resp.request.emit('httpUploadProgress', [value, resp]);
6549 });
6550
6551 httpResp.on('receiveProgress', function onReceiveProgress(value) {
6552 resp.request.emit('httpDownloadProgress', [value, resp]);
6553 });
6554 }
6555
6556 function error(err) {
6557 if (err.code !== 'RequestAbortedError') {
6558 var errCode = err.code === 'TimeoutError' ? err.code : 'NetworkingError';
6559 err = AWS.util.error(err, {
6560 code: errCode,
6561 region: resp.request.httpRequest.region,
6562 hostname: resp.request.httpRequest.endpoint.hostname,
6563 retryable: true
6564 });
6565 }
6566 resp.error = err;
6567 resp.request.emit('httpError', [resp.error, resp], function() {
6568 done();
6569 });
6570 }
6571
6572 function executeSend() {
6573 var http = AWS.HttpClient.getInstance();
6574 var httpOptions = resp.request.service.config.httpOptions || {};
6575 try {
6576 var stream = http.handleRequest(resp.request.httpRequest, httpOptions,
6577 callback, error);
6578 progress(stream);
6579 } catch (err) {
6580 error(err);
6581 }
6582 }
6583 var timeDiff = (resp.request.service.getSkewCorrectedDate() - this.signedAt) / 1000;
6584 if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign
6585 this.emit('sign', [this], function(err) {
6586 if (err) done(err);
6587 else executeSend();
6588 });
6589 } else {
6590 executeSend();
6591 }
6592 });
6593
6594 add('HTTP_HEADERS', 'httpHeaders',
6595 function HTTP_HEADERS(statusCode, headers, resp, statusMessage) {
6596 resp.httpResponse.statusCode = statusCode;
6597 resp.httpResponse.statusMessage = statusMessage;
6598 resp.httpResponse.headers = headers;
6599 resp.httpResponse.body = new AWS.util.Buffer('');
6600 resp.httpResponse.buffers = [];
6601 resp.httpResponse.numBytes = 0;
6602 var dateHeader = headers.date || headers.Date;
6603 var service = resp.request.service;
6604 if (dateHeader) {
6605 var serverTime = Date.parse(dateHeader);
6606 if (service.config.correctClockSkew
6607 && service.isClockSkewed(serverTime)) {
6608 service.applyClockOffset(serverTime);
6609 }
6610 }
6611 });
6612
6613 add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) {
6614 if (chunk) {
6615 if (AWS.util.isNode()) {
6616 resp.httpResponse.numBytes += chunk.length;
6617
6618 var total = resp.httpResponse.headers['content-length'];
6619 var progress = { loaded: resp.httpResponse.numBytes, total: total };
6620 resp.request.emit('httpDownloadProgress', [progress, resp]);
6621 }
6622
6623 resp.httpResponse.buffers.push(new AWS.util.Buffer(chunk));
6624 }
6625 });
6626
6627 add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) {
6628 // convert buffers array into single buffer
6629 if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) {
6630 var body = AWS.util.buffer.concat(resp.httpResponse.buffers);
6631 resp.httpResponse.body = body;
6632 }
6633 delete resp.httpResponse.numBytes;
6634 delete resp.httpResponse.buffers;
6635 });
6636
6637 add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) {
6638 if (resp.httpResponse.statusCode) {
6639 resp.error.statusCode = resp.httpResponse.statusCode;
6640 if (resp.error.retryable === undefined) {
6641 resp.error.retryable = this.service.retryableError(resp.error, this);
6642 }
6643 }
6644 });
6645
6646 add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) {
6647 if (!resp.error) return;
6648 switch (resp.error.code) {
6649 case 'RequestExpired': // EC2 only
6650 case 'ExpiredTokenException':
6651 case 'ExpiredToken':
6652 resp.error.retryable = true;
6653 resp.request.service.config.credentials.expired = true;
6654 }
6655 });
6656
6657 add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) {
6658 var err = resp.error;
6659 if (!err) return;
6660 if (typeof err.code === 'string' && typeof err.message === 'string') {
6661 if (err.code.match(/Signature/) && err.message.match(/expired/)) {
6662 resp.error.retryable = true;
6663 }
6664 }
6665 });
6666
6667 add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) {
6668 if (!resp.error) return;
6669 if (this.service.clockSkewError(resp.error)
6670 && this.service.config.correctClockSkew) {
6671 resp.error.retryable = true;
6672 }
6673 });
6674
6675 add('REDIRECT', 'retry', function REDIRECT(resp) {
6676 if (resp.error && resp.error.statusCode >= 300 &&
6677 resp.error.statusCode < 400 && resp.httpResponse.headers['location']) {
6678 this.httpRequest.endpoint =
6679 new AWS.Endpoint(resp.httpResponse.headers['location']);
6680 this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host;
6681 resp.error.redirect = true;
6682 resp.error.retryable = true;
6683 }
6684 });
6685
6686 add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) {
6687 if (resp.error) {
6688 if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6689 resp.error.retryDelay = 0;
6690 } else if (resp.retryCount < resp.maxRetries) {
6691 resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0;
6692 }
6693 }
6694 });
6695
6696 addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) {
6697 var delay, willRetry = false;
6698
6699 if (resp.error) {
6700 delay = resp.error.retryDelay || 0;
6701 if (resp.error.retryable && resp.retryCount < resp.maxRetries) {
6702 resp.retryCount++;
6703 willRetry = true;
6704 } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6705 resp.redirectCount++;
6706 willRetry = true;
6707 }
6708 }
6709
6710 if (willRetry) {
6711 resp.error = null;
6712 setTimeout(done, delay);
6713 } else {
6714 done();
6715 }
6716 });
6717 }),
6718
6719 CorePost: new SequentialExecutor().addNamedListeners(function(add) {
6720 add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId);
6721 add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId);
6722
6723 add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) {
6724 if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') {
6725 var message = 'Inaccessible host: `' + err.hostname +
6726 '\'. This service may not be available in the `' + err.region +
6727 '\' region.';
6728 this.response.error = AWS.util.error(new Error(message), {
6729 code: 'UnknownEndpoint',
6730 region: err.region,
6731 hostname: err.hostname,
6732 retryable: true,
6733 originalError: err
6734 });
6735 }
6736 });
6737 }),
6738
6739 Logger: new SequentialExecutor().addNamedListeners(function(add) {
6740 add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) {
6741 var req = resp.request;
6742 var logger = req.service.config.logger;
6743 if (!logger) return;
6744 function filterSensitiveLog(inputShape, shape) {
6745 if (!shape) {
6746 return shape;
6747 }
6748 switch (inputShape.type) {
6749 case 'structure':
6750 var struct = {};
6751 AWS.util.each(shape, function(subShapeName, subShape) {
6752 if (Object.prototype.hasOwnProperty.call(inputShape.members, subShapeName)) {
6753 struct[subShapeName] = filterSensitiveLog(inputShape.members[subShapeName], subShape);
6754 } else {
6755 struct[subShapeName] = subShape;
6756 }
6757 });
6758 return struct;
6759 case 'list':
6760 var list = [];
6761 AWS.util.arrayEach(shape, function(subShape, index) {
6762 list.push(filterSensitiveLog(inputShape.member, subShape));
6763 });
6764 return list;
6765 case 'map':
6766 var map = {};
6767 AWS.util.each(shape, function(key, value) {
6768 map[key] = filterSensitiveLog(inputShape.value, value);
6769 });
6770 return map;
6771 default:
6772 if (inputShape.isSensitive) {
6773 return '***SensitiveInformation***';
6774 } else {
6775 return shape;
6776 }
6777 }
6778 }
6779
6780 function buildMessage() {
6781 var time = resp.request.service.getSkewCorrectedDate().getTime();
6782 var delta = (time - req.startTime.getTime()) / 1000;
6783 var ansi = logger.isTTY ? true : false;
6784 var status = resp.httpResponse.statusCode;
6785 var censoredParams = req.params;
6786 if (
6787 req.service.api.operations &&
6788 req.service.api.operations[req.operation] &&
6789 req.service.api.operations[req.operation].input
6790 ) {
6791 var inputShape = req.service.api.operations[req.operation].input;
6792 censoredParams = filterSensitiveLog(inputShape, req.params);
6793 }
6794 var params = __webpack_require__(46).inspect(censoredParams, true, null);
6795 var message = '';
6796 if (ansi) message += '\x1B[33m';
6797 message += '[AWS ' + req.service.serviceIdentifier + ' ' + status;
6798 message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]';
6799 if (ansi) message += '\x1B[0;1m';
6800 message += ' ' + AWS.util.string.lowerFirst(req.operation);
6801 message += '(' + params + ')';
6802 if (ansi) message += '\x1B[0m';
6803 return message;
6804 }
6805
6806 var line = buildMessage();
6807 if (typeof logger.log === 'function') {
6808 logger.log(line);
6809 } else if (typeof logger.write === 'function') {
6810 logger.write(line + '\n');
6811 }
6812 });
6813 }),
6814
6815 Json: new SequentialExecutor().addNamedListeners(function(add) {
6816 var svc = __webpack_require__(13);
6817 add('BUILD', 'build', svc.buildRequest);
6818 add('EXTRACT_DATA', 'extractData', svc.extractData);
6819 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6820 }),
6821
6822 Rest: new SequentialExecutor().addNamedListeners(function(add) {
6823 var svc = __webpack_require__(21);
6824 add('BUILD', 'build', svc.buildRequest);
6825 add('EXTRACT_DATA', 'extractData', svc.extractData);
6826 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6827 }),
6828
6829 RestJson: new SequentialExecutor().addNamedListeners(function(add) {
6830 var svc = __webpack_require__(22);
6831 add('BUILD', 'build', svc.buildRequest);
6832 add('EXTRACT_DATA', 'extractData', svc.extractData);
6833 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6834 }),
6835
6836 RestXml: new SequentialExecutor().addNamedListeners(function(add) {
6837 var svc = __webpack_require__(23);
6838 add('BUILD', 'build', svc.buildRequest);
6839 add('EXTRACT_DATA', 'extractData', svc.extractData);
6840 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6841 }),
6842
6843 Query: new SequentialExecutor().addNamedListeners(function(add) {
6844 var svc = __webpack_require__(17);
6845 add('BUILD', 'build', svc.buildRequest);
6846 add('EXTRACT_DATA', 'extractData', svc.extractData);
6847 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6848 })
6849 };
6850
6851
6852/***/ }),
6853/* 45 */
6854/***/ (function(module, exports, __webpack_require__) {
6855
6856 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
6857 var util = __webpack_require__(2);
6858 var endpointDiscoveryEnabledEnvs = ['AWS_ENABLE_ENDPOINT_DISCOVERY', 'AWS_ENDPOINT_DISCOVERY_ENABLED'];
6859
6860 /**
6861 * Generate key (except resources and operation part) to index the endpoints in the cache
6862 * If input shape has endpointdiscoveryid trait then use
6863 * accessKey + operation + resources + region + service as cache key
6864 * If input shape doesn't have endpointdiscoveryid trait then use
6865 * accessKey + region + service as cache key
6866 * @return [map<String,String>] object with keys to index endpoints.
6867 * @api private
6868 */
6869 function getCacheKey(request) {
6870 var service = request.service;
6871 var api = service.api || {};
6872 var operations = api.operations;
6873 var identifiers = {};
6874 if (service.config.region) {
6875 identifiers.region = service.config.region;
6876 }
6877 if (api.serviceId) {
6878 identifiers.serviceId = api.serviceId;
6879 }
6880 if (service.config.credentials.accessKeyId) {
6881 identifiers.accessKeyId = service.config.credentials.accessKeyId;
6882 }
6883 return identifiers;
6884 }
6885
6886 /**
6887 * Recursive helper for marshallCustomIdentifiers().
6888 * Looks for required string input members that have 'endpointdiscoveryid' trait.
6889 * @api private
6890 */
6891 function marshallCustomIdentifiersHelper(result, params, shape) {
6892 if (!shape || params === undefined || params === null) return;
6893 if (shape.type === 'structure' && shape.required && shape.required.length > 0) {
6894 util.arrayEach(shape.required, function(name) {
6895 var memberShape = shape.members[name];
6896 if (memberShape.endpointDiscoveryId === true) {
6897 var locationName = memberShape.isLocationName ? memberShape.name : name;
6898 result[locationName] = String(params[name]);
6899 } else {
6900 marshallCustomIdentifiersHelper(result, params[name], memberShape);
6901 }
6902 });
6903 }
6904 }
6905
6906 /**
6907 * Get custom identifiers for cache key.
6908 * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait.
6909 * @param [object] request object
6910 * @param [object] input shape of the given operation's api
6911 * @api private
6912 */
6913 function marshallCustomIdentifiers(request, shape) {
6914 var identifiers = {};
6915 marshallCustomIdentifiersHelper(identifiers, request.params, shape);
6916 return identifiers;
6917 }
6918
6919 /**
6920 * Call endpoint discovery operation when it's optional.
6921 * When endpoint is available in cache then use the cached endpoints. If endpoints
6922 * are unavailable then use regional endpoints and call endpoint discovery operation
6923 * asynchronously. This is turned off by default.
6924 * @param [object] request object
6925 * @api private
6926 */
6927 function optionalDiscoverEndpoint(request) {
6928 var service = request.service;
6929 var api = service.api;
6930 var operationModel = api.operations ? api.operations[request.operation] : undefined;
6931 var inputShape = operationModel ? operationModel.input : undefined;
6932
6933 var identifiers = marshallCustomIdentifiers(request, inputShape);
6934 var cacheKey = getCacheKey(request);
6935 if (Object.keys(identifiers).length > 0) {
6936 cacheKey = util.update(cacheKey, identifiers);
6937 if (operationModel) cacheKey.operation = operationModel.name;
6938 }
6939 var endpoints = AWS.endpointCache.get(cacheKey);
6940 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
6941 //endpoint operation is being made but response not yet received
6942 //or endpoint operation just failed in 1 minute
6943 return;
6944 } else if (endpoints && endpoints.length > 0) {
6945 //found endpoint record from cache
6946 request.httpRequest.updateEndpoint(endpoints[0].Address);
6947 } else {
6948 //endpoint record not in cache or outdated. make discovery operation
6949 var endpointRequest = service.makeRequest(api.endpointOperation, {
6950 Operation: operationModel.name,
6951 Identifiers: identifiers,
6952 });
6953 addApiVersionHeader(endpointRequest);
6954 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
6955 endpointRequest.removeListener('retry', AWS.EventListeners.Core.RETRY_CHECK);
6956 //put in a placeholder for endpoints already requested, prevent
6957 //too much in-flight calls
6958 AWS.endpointCache.put(cacheKey, [{
6959 Address: '',
6960 CachePeriodInMinutes: 1
6961 }]);
6962 endpointRequest.send(function(err, data) {
6963 if (data && data.Endpoints) {
6964 AWS.endpointCache.put(cacheKey, data.Endpoints);
6965 } else if (err) {
6966 AWS.endpointCache.put(cacheKey, [{
6967 Address: '',
6968 CachePeriodInMinutes: 1 //not to make more endpoint operation in next 1 minute
6969 }]);
6970 }
6971 });
6972 }
6973 }
6974
6975 var requestQueue = {};
6976
6977 /**
6978 * Call endpoint discovery operation when it's required.
6979 * When endpoint is available in cache then use cached ones. If endpoints are
6980 * unavailable then SDK should call endpoint operation then use returned new
6981 * endpoint for the api call. SDK will automatically attempt to do endpoint
6982 * discovery. This is turned off by default
6983 * @param [object] request object
6984 * @api private
6985 */
6986 function requiredDiscoverEndpoint(request, done) {
6987 var service = request.service;
6988 var api = service.api;
6989 var operationModel = api.operations ? api.operations[request.operation] : undefined;
6990 var inputShape = operationModel ? operationModel.input : undefined;
6991
6992 var identifiers = marshallCustomIdentifiers(request, inputShape);
6993 var cacheKey = getCacheKey(request);
6994 if (Object.keys(identifiers).length > 0) {
6995 cacheKey = util.update(cacheKey, identifiers);
6996 if (operationModel) cacheKey.operation = operationModel.name;
6997 }
6998 var cacheKeyStr = AWS.EndpointCache.getKeyString(cacheKey);
6999 var endpoints = AWS.endpointCache.get(cacheKeyStr); //endpoint cache also accepts string keys
7000 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
7001 //endpoint operation is being made but response not yet received
7002 //push request object to a pending queue
7003 if (!requestQueue[cacheKeyStr]) requestQueue[cacheKeyStr] = [];
7004 requestQueue[cacheKeyStr].push({request: request, callback: done});
7005 return;
7006 } else if (endpoints && endpoints.length > 0) {
7007 request.httpRequest.updateEndpoint(endpoints[0].Address);
7008 done();
7009 } else {
7010 var endpointRequest = service.makeRequest(api.endpointOperation, {
7011 Operation: operationModel.name,
7012 Identifiers: identifiers,
7013 });
7014 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
7015 addApiVersionHeader(endpointRequest);
7016
7017 //put in a placeholder for endpoints already requested, prevent
7018 //too much in-flight calls
7019 AWS.endpointCache.put(cacheKeyStr, [{
7020 Address: '',
7021 CachePeriodInMinutes: 60 //long-live cache
7022 }]);
7023 endpointRequest.send(function(err, data) {
7024 if (err) {
7025 var errorParams = {
7026 code: 'EndpointDiscoveryException',
7027 message: 'Request cannot be fulfilled without specifying an endpoint',
7028 retryable: false
7029 };
7030 request.response.error = util.error(err, errorParams);
7031 AWS.endpointCache.remove(cacheKey);
7032
7033 //fail all the pending requests in batch
7034 if (requestQueue[cacheKeyStr]) {
7035 var pendingRequests = requestQueue[cacheKeyStr];
7036 util.arrayEach(pendingRequests, function(requestContext) {
7037 requestContext.request.response.error = util.error(err, errorParams);
7038 requestContext.callback();
7039 });
7040 delete requestQueue[cacheKeyStr];
7041 }
7042 } else if (data) {
7043 AWS.endpointCache.put(cacheKeyStr, data.Endpoints);
7044 request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7045
7046 //update the endpoint for all the pending requests in batch
7047 if (requestQueue[cacheKeyStr]) {
7048 var pendingRequests = requestQueue[cacheKeyStr];
7049 util.arrayEach(pendingRequests, function(requestContext) {
7050 requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7051 requestContext.callback();
7052 });
7053 delete requestQueue[cacheKeyStr];
7054 }
7055 }
7056 done();
7057 });
7058 }
7059 }
7060
7061 /**
7062 * add api version header to endpoint operation
7063 * @api private
7064 */
7065 function addApiVersionHeader(endpointRequest) {
7066 var api = endpointRequest.service.api;
7067 var apiVersion = api.apiVersion;
7068 if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) {
7069 endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion;
7070 }
7071 }
7072
7073 /**
7074 * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid
7075 * endpoint from cache.
7076 * @api private
7077 */
7078 function invalidateCachedEndpoints(response) {
7079 var error = response.error;
7080 var httpResponse = response.httpResponse;
7081 if (error &&
7082 (error.code === 'InvalidEndpointException' || httpResponse.statusCode === 421)
7083 ) {
7084 var request = response.request;
7085 var operations = request.service.api.operations || {};
7086 var inputShape = operations[request.operation] ? operations[request.operation].input : undefined;
7087 var identifiers = marshallCustomIdentifiers(request, inputShape);
7088 var cacheKey = getCacheKey(request);
7089 if (Object.keys(identifiers).length > 0) {
7090 cacheKey = util.update(cacheKey, identifiers);
7091 if (operations[request.operation]) cacheKey.operation = operations[request.operation].name;
7092 }
7093 AWS.endpointCache.remove(cacheKey);
7094 }
7095 }
7096
7097 /**
7098 * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime.
7099 * @param [object] client Service client object.
7100 * @api private
7101 */
7102 function hasCustomEndpoint(client) {
7103 //if set endpoint is set for specific client, enable endpoint discovery will raise an error.
7104 if (client._originalConfig && client._originalConfig.endpoint && client._originalConfig.endpointDiscoveryEnabled === true) {
7105 throw util.error(new Error(), {
7106 code: 'ConfigurationException',
7107 message: 'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.'
7108 });
7109 };
7110 var svcConfig = AWS.config[client.serviceIdentifier] || {};
7111 return Boolean(AWS.config.endpoint || svcConfig.endpoint || (client._originalConfig && client._originalConfig.endpoint));
7112 }
7113
7114 /**
7115 * @api private
7116 */
7117 function isFalsy(value) {
7118 return ['false', '0'].indexOf(value) >= 0;
7119 }
7120
7121 /**
7122 * If endpoint discovery should perform for this request when endpoint discovery is optional.
7123 * SDK performs config resolution in order like below:
7124 * 1. If turned on client configuration(default to off) then turn on endpoint discovery.
7125 * 2. If turned on in env AWS_ENABLE_ENDPOINT_DISCOVERY then turn on endpoint discovery.
7126 * 3. If turned on in shared ini config file with key 'endpoint_discovery_enabled', then
7127 * turn on endpoint discovery.
7128 * @param [object] request request object.
7129 * @api private
7130 */
7131 function isEndpointDiscoveryApplicable(request) {
7132 var service = request.service || {};
7133 if (service.config.endpointDiscoveryEnabled === true) return true;
7134
7135 //shared ini file is only available in Node
7136 //not to check env in browser
7137 if (util.isBrowser()) return false;
7138
7139 for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) {
7140 var env = endpointDiscoveryEnabledEnvs[i];
7141 if (Object.prototype.hasOwnProperty.call(process.env, env)) {
7142 if (process.env[env] === '' || process.env[env] === undefined) {
7143 throw util.error(new Error(), {
7144 code: 'ConfigurationException',
7145 message: 'environmental variable ' + env + ' cannot be set to nothing'
7146 });
7147 }
7148 if (!isFalsy(process.env[env])) return true;
7149 }
7150 }
7151
7152 var configFile = {};
7153 try {
7154 configFile = AWS.util.iniLoader ? AWS.util.iniLoader.loadFrom({
7155 isConfig: true,
7156 filename: process.env[AWS.util.sharedConfigFileEnv]
7157 }) : {};
7158 } catch (e) {}
7159 var sharedFileConfig = configFile[
7160 process.env.AWS_PROFILE || AWS.util.defaultProfile
7161 ] || {};
7162 if (Object.prototype.hasOwnProperty.call(sharedFileConfig, 'endpoint_discovery_enabled')) {
7163 if (sharedFileConfig.endpoint_discovery_enabled === undefined) {
7164 throw util.error(new Error(), {
7165 code: 'ConfigurationException',
7166 message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing'
7167 });
7168 }
7169 if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true;
7170 }
7171 return false;
7172 }
7173
7174 /**
7175 * attach endpoint discovery logic to request object
7176 * @param [object] request
7177 * @api private
7178 */
7179 function discoverEndpoint(request, done) {
7180 var service = request.service || {};
7181 if (hasCustomEndpoint(service) || request.isPresigned()) return done();
7182
7183 if (!isEndpointDiscoveryApplicable(request)) return done();
7184
7185 request.httpRequest.appendToUserAgent('endpoint-discovery');
7186
7187 var operations = service.api.operations || {};
7188 var operationModel = operations[request.operation];
7189 var isEndpointDiscoveryRequired = operationModel ? operationModel.endpointDiscoveryRequired : 'NULL';
7190 switch (isEndpointDiscoveryRequired) {
7191 case 'OPTIONAL':
7192 optionalDiscoverEndpoint(request);
7193 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7194 done();
7195 break;
7196 case 'REQUIRED':
7197 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7198 requiredDiscoverEndpoint(request, done);
7199 break;
7200 case 'NULL':
7201 default:
7202 done();
7203 break;
7204 }
7205 }
7206
7207 module.exports = {
7208 discoverEndpoint: discoverEndpoint,
7209 requiredDiscoverEndpoint: requiredDiscoverEndpoint,
7210 optionalDiscoverEndpoint: optionalDiscoverEndpoint,
7211 marshallCustomIdentifiers: marshallCustomIdentifiers,
7212 getCacheKey: getCacheKey,
7213 invalidateCachedEndpoint: invalidateCachedEndpoints,
7214 };
7215
7216 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
7217
7218/***/ }),
7219/* 46 */
7220/***/ (function(module, exports, __webpack_require__) {
7221
7222 /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
7223 //
7224 // Permission is hereby granted, free of charge, to any person obtaining a
7225 // copy of this software and associated documentation files (the
7226 // "Software"), to deal in the Software without restriction, including
7227 // without limitation the rights to use, copy, modify, merge, publish,
7228 // distribute, sublicense, and/or sell copies of the Software, and to permit
7229 // persons to whom the Software is furnished to do so, subject to the
7230 // following conditions:
7231 //
7232 // The above copyright notice and this permission notice shall be included
7233 // in all copies or substantial portions of the Software.
7234 //
7235 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7236 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7237 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7238 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7239 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7240 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7241 // USE OR OTHER DEALINGS IN THE SOFTWARE.
7242
7243 var formatRegExp = /%[sdj%]/g;
7244 exports.format = function(f) {
7245 if (!isString(f)) {
7246 var objects = [];
7247 for (var i = 0; i < arguments.length; i++) {
7248 objects.push(inspect(arguments[i]));
7249 }
7250 return objects.join(' ');
7251 }
7252
7253 var i = 1;
7254 var args = arguments;
7255 var len = args.length;
7256 var str = String(f).replace(formatRegExp, function(x) {
7257 if (x === '%%') return '%';
7258 if (i >= len) return x;
7259 switch (x) {
7260 case '%s': return String(args[i++]);
7261 case '%d': return Number(args[i++]);
7262 case '%j':
7263 try {
7264 return JSON.stringify(args[i++]);
7265 } catch (_) {
7266 return '[Circular]';
7267 }
7268 default:
7269 return x;
7270 }
7271 });
7272 for (var x = args[i]; i < len; x = args[++i]) {
7273 if (isNull(x) || !isObject(x)) {
7274 str += ' ' + x;
7275 } else {
7276 str += ' ' + inspect(x);
7277 }
7278 }
7279 return str;
7280 };
7281
7282
7283 // Mark that a method should not be used.
7284 // Returns a modified function which warns once by default.
7285 // If --no-deprecation is set, then it is a no-op.
7286 exports.deprecate = function(fn, msg) {
7287 // Allow for deprecating things in the process of starting up.
7288 if (isUndefined(global.process)) {
7289 return function() {
7290 return exports.deprecate(fn, msg).apply(this, arguments);
7291 };
7292 }
7293
7294 if (process.noDeprecation === true) {
7295 return fn;
7296 }
7297
7298 var warned = false;
7299 function deprecated() {
7300 if (!warned) {
7301 if (process.throwDeprecation) {
7302 throw new Error(msg);
7303 } else if (process.traceDeprecation) {
7304 console.trace(msg);
7305 } else {
7306 console.error(msg);
7307 }
7308 warned = true;
7309 }
7310 return fn.apply(this, arguments);
7311 }
7312
7313 return deprecated;
7314 };
7315
7316
7317 var debugs = {};
7318 var debugEnviron;
7319 exports.debuglog = function(set) {
7320 if (isUndefined(debugEnviron))
7321 debugEnviron = process.env.NODE_DEBUG || '';
7322 set = set.toUpperCase();
7323 if (!debugs[set]) {
7324 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
7325 var pid = process.pid;
7326 debugs[set] = function() {
7327 var msg = exports.format.apply(exports, arguments);
7328 console.error('%s %d: %s', set, pid, msg);
7329 };
7330 } else {
7331 debugs[set] = function() {};
7332 }
7333 }
7334 return debugs[set];
7335 };
7336
7337
7338 /**
7339 * Echos the value of a value. Trys to print the value out
7340 * in the best way possible given the different types.
7341 *
7342 * @param {Object} obj The object to print out.
7343 * @param {Object} opts Optional options object that alters the output.
7344 */
7345 /* legacy: obj, showHidden, depth, colors*/
7346 function inspect(obj, opts) {
7347 // default options
7348 var ctx = {
7349 seen: [],
7350 stylize: stylizeNoColor
7351 };
7352 // legacy...
7353 if (arguments.length >= 3) ctx.depth = arguments[2];
7354 if (arguments.length >= 4) ctx.colors = arguments[3];
7355 if (isBoolean(opts)) {
7356 // legacy...
7357 ctx.showHidden = opts;
7358 } else if (opts) {
7359 // got an "options" object
7360 exports._extend(ctx, opts);
7361 }
7362 // set default options
7363 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
7364 if (isUndefined(ctx.depth)) ctx.depth = 2;
7365 if (isUndefined(ctx.colors)) ctx.colors = false;
7366 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
7367 if (ctx.colors) ctx.stylize = stylizeWithColor;
7368 return formatValue(ctx, obj, ctx.depth);
7369 }
7370 exports.inspect = inspect;
7371
7372
7373 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
7374 inspect.colors = {
7375 'bold' : [1, 22],
7376 'italic' : [3, 23],
7377 'underline' : [4, 24],
7378 'inverse' : [7, 27],
7379 'white' : [37, 39],
7380 'grey' : [90, 39],
7381 'black' : [30, 39],
7382 'blue' : [34, 39],
7383 'cyan' : [36, 39],
7384 'green' : [32, 39],
7385 'magenta' : [35, 39],
7386 'red' : [31, 39],
7387 'yellow' : [33, 39]
7388 };
7389
7390 // Don't use 'blue' not visible on cmd.exe
7391 inspect.styles = {
7392 'special': 'cyan',
7393 'number': 'yellow',
7394 'boolean': 'yellow',
7395 'undefined': 'grey',
7396 'null': 'bold',
7397 'string': 'green',
7398 'date': 'magenta',
7399 // "name": intentionally not styling
7400 'regexp': 'red'
7401 };
7402
7403
7404 function stylizeWithColor(str, styleType) {
7405 var style = inspect.styles[styleType];
7406
7407 if (style) {
7408 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
7409 '\u001b[' + inspect.colors[style][1] + 'm';
7410 } else {
7411 return str;
7412 }
7413 }
7414
7415
7416 function stylizeNoColor(str, styleType) {
7417 return str;
7418 }
7419
7420
7421 function arrayToHash(array) {
7422 var hash = {};
7423
7424 array.forEach(function(val, idx) {
7425 hash[val] = true;
7426 });
7427
7428 return hash;
7429 }
7430
7431
7432 function formatValue(ctx, value, recurseTimes) {
7433 // Provide a hook for user-specified inspect functions.
7434 // Check that value is an object with an inspect function on it
7435 if (ctx.customInspect &&
7436 value &&
7437 isFunction(value.inspect) &&
7438 // Filter out the util module, it's inspect function is special
7439 value.inspect !== exports.inspect &&
7440 // Also filter out any prototype objects using the circular check.
7441 !(value.constructor && value.constructor.prototype === value)) {
7442 var ret = value.inspect(recurseTimes, ctx);
7443 if (!isString(ret)) {
7444 ret = formatValue(ctx, ret, recurseTimes);
7445 }
7446 return ret;
7447 }
7448
7449 // Primitive types cannot have properties
7450 var primitive = formatPrimitive(ctx, value);
7451 if (primitive) {
7452 return primitive;
7453 }
7454
7455 // Look up the keys of the object.
7456 var keys = Object.keys(value);
7457 var visibleKeys = arrayToHash(keys);
7458
7459 if (ctx.showHidden) {
7460 keys = Object.getOwnPropertyNames(value);
7461 }
7462
7463 // IE doesn't make error fields non-enumerable
7464 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
7465 if (isError(value)
7466 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
7467 return formatError(value);
7468 }
7469
7470 // Some type of object without properties can be shortcutted.
7471 if (keys.length === 0) {
7472 if (isFunction(value)) {
7473 var name = value.name ? ': ' + value.name : '';
7474 return ctx.stylize('[Function' + name + ']', 'special');
7475 }
7476 if (isRegExp(value)) {
7477 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7478 }
7479 if (isDate(value)) {
7480 return ctx.stylize(Date.prototype.toString.call(value), 'date');
7481 }
7482 if (isError(value)) {
7483 return formatError(value);
7484 }
7485 }
7486
7487 var base = '', array = false, braces = ['{', '}'];
7488
7489 // Make Array say that they are Array
7490 if (isArray(value)) {
7491 array = true;
7492 braces = ['[', ']'];
7493 }
7494
7495 // Make functions say that they are functions
7496 if (isFunction(value)) {
7497 var n = value.name ? ': ' + value.name : '';
7498 base = ' [Function' + n + ']';
7499 }
7500
7501 // Make RegExps say that they are RegExps
7502 if (isRegExp(value)) {
7503 base = ' ' + RegExp.prototype.toString.call(value);
7504 }
7505
7506 // Make dates with properties first say the date
7507 if (isDate(value)) {
7508 base = ' ' + Date.prototype.toUTCString.call(value);
7509 }
7510
7511 // Make error with message first say the error
7512 if (isError(value)) {
7513 base = ' ' + formatError(value);
7514 }
7515
7516 if (keys.length === 0 && (!array || value.length == 0)) {
7517 return braces[0] + base + braces[1];
7518 }
7519
7520 if (recurseTimes < 0) {
7521 if (isRegExp(value)) {
7522 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7523 } else {
7524 return ctx.stylize('[Object]', 'special');
7525 }
7526 }
7527
7528 ctx.seen.push(value);
7529
7530 var output;
7531 if (array) {
7532 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
7533 } else {
7534 output = keys.map(function(key) {
7535 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
7536 });
7537 }
7538
7539 ctx.seen.pop();
7540
7541 return reduceToSingleString(output, base, braces);
7542 }
7543
7544
7545 function formatPrimitive(ctx, value) {
7546 if (isUndefined(value))
7547 return ctx.stylize('undefined', 'undefined');
7548 if (isString(value)) {
7549 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
7550 .replace(/'/g, "\\'")
7551 .replace(/\\"/g, '"') + '\'';
7552 return ctx.stylize(simple, 'string');
7553 }
7554 if (isNumber(value))
7555 return ctx.stylize('' + value, 'number');
7556 if (isBoolean(value))
7557 return ctx.stylize('' + value, 'boolean');
7558 // For some reason typeof null is "object", so special case here.
7559 if (isNull(value))
7560 return ctx.stylize('null', 'null');
7561 }
7562
7563
7564 function formatError(value) {
7565 return '[' + Error.prototype.toString.call(value) + ']';
7566 }
7567
7568
7569 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
7570 var output = [];
7571 for (var i = 0, l = value.length; i < l; ++i) {
7572 if (hasOwnProperty(value, String(i))) {
7573 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7574 String(i), true));
7575 } else {
7576 output.push('');
7577 }
7578 }
7579 keys.forEach(function(key) {
7580 if (!key.match(/^\d+$/)) {
7581 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7582 key, true));
7583 }
7584 });
7585 return output;
7586 }
7587
7588
7589 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
7590 var name, str, desc;
7591 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
7592 if (desc.get) {
7593 if (desc.set) {
7594 str = ctx.stylize('[Getter/Setter]', 'special');
7595 } else {
7596 str = ctx.stylize('[Getter]', 'special');
7597 }
7598 } else {
7599 if (desc.set) {
7600 str = ctx.stylize('[Setter]', 'special');
7601 }
7602 }
7603 if (!hasOwnProperty(visibleKeys, key)) {
7604 name = '[' + key + ']';
7605 }
7606 if (!str) {
7607 if (ctx.seen.indexOf(desc.value) < 0) {
7608 if (isNull(recurseTimes)) {
7609 str = formatValue(ctx, desc.value, null);
7610 } else {
7611 str = formatValue(ctx, desc.value, recurseTimes - 1);
7612 }
7613 if (str.indexOf('\n') > -1) {
7614 if (array) {
7615 str = str.split('\n').map(function(line) {
7616 return ' ' + line;
7617 }).join('\n').substr(2);
7618 } else {
7619 str = '\n' + str.split('\n').map(function(line) {
7620 return ' ' + line;
7621 }).join('\n');
7622 }
7623 }
7624 } else {
7625 str = ctx.stylize('[Circular]', 'special');
7626 }
7627 }
7628 if (isUndefined(name)) {
7629 if (array && key.match(/^\d+$/)) {
7630 return str;
7631 }
7632 name = JSON.stringify('' + key);
7633 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
7634 name = name.substr(1, name.length - 2);
7635 name = ctx.stylize(name, 'name');
7636 } else {
7637 name = name.replace(/'/g, "\\'")
7638 .replace(/\\"/g, '"')
7639 .replace(/(^"|"$)/g, "'");
7640 name = ctx.stylize(name, 'string');
7641 }
7642 }
7643
7644 return name + ': ' + str;
7645 }
7646
7647
7648 function reduceToSingleString(output, base, braces) {
7649 var numLinesEst = 0;
7650 var length = output.reduce(function(prev, cur) {
7651 numLinesEst++;
7652 if (cur.indexOf('\n') >= 0) numLinesEst++;
7653 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
7654 }, 0);
7655
7656 if (length > 60) {
7657 return braces[0] +
7658 (base === '' ? '' : base + '\n ') +
7659 ' ' +
7660 output.join(',\n ') +
7661 ' ' +
7662 braces[1];
7663 }
7664
7665 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
7666 }
7667
7668
7669 // NOTE: These type checking functions intentionally don't use `instanceof`
7670 // because it is fragile and can be easily faked with `Object.create()`.
7671 function isArray(ar) {
7672 return Array.isArray(ar);
7673 }
7674 exports.isArray = isArray;
7675
7676 function isBoolean(arg) {
7677 return typeof arg === 'boolean';
7678 }
7679 exports.isBoolean = isBoolean;
7680
7681 function isNull(arg) {
7682 return arg === null;
7683 }
7684 exports.isNull = isNull;
7685
7686 function isNullOrUndefined(arg) {
7687 return arg == null;
7688 }
7689 exports.isNullOrUndefined = isNullOrUndefined;
7690
7691 function isNumber(arg) {
7692 return typeof arg === 'number';
7693 }
7694 exports.isNumber = isNumber;
7695
7696 function isString(arg) {
7697 return typeof arg === 'string';
7698 }
7699 exports.isString = isString;
7700
7701 function isSymbol(arg) {
7702 return typeof arg === 'symbol';
7703 }
7704 exports.isSymbol = isSymbol;
7705
7706 function isUndefined(arg) {
7707 return arg === void 0;
7708 }
7709 exports.isUndefined = isUndefined;
7710
7711 function isRegExp(re) {
7712 return isObject(re) && objectToString(re) === '[object RegExp]';
7713 }
7714 exports.isRegExp = isRegExp;
7715
7716 function isObject(arg) {
7717 return typeof arg === 'object' && arg !== null;
7718 }
7719 exports.isObject = isObject;
7720
7721 function isDate(d) {
7722 return isObject(d) && objectToString(d) === '[object Date]';
7723 }
7724 exports.isDate = isDate;
7725
7726 function isError(e) {
7727 return isObject(e) &&
7728 (objectToString(e) === '[object Error]' || e instanceof Error);
7729 }
7730 exports.isError = isError;
7731
7732 function isFunction(arg) {
7733 return typeof arg === 'function';
7734 }
7735 exports.isFunction = isFunction;
7736
7737 function isPrimitive(arg) {
7738 return arg === null ||
7739 typeof arg === 'boolean' ||
7740 typeof arg === 'number' ||
7741 typeof arg === 'string' ||
7742 typeof arg === 'symbol' || // ES6 symbol
7743 typeof arg === 'undefined';
7744 }
7745 exports.isPrimitive = isPrimitive;
7746
7747 exports.isBuffer = __webpack_require__(47);
7748
7749 function objectToString(o) {
7750 return Object.prototype.toString.call(o);
7751 }
7752
7753
7754 function pad(n) {
7755 return n < 10 ? '0' + n.toString(10) : n.toString(10);
7756 }
7757
7758
7759 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
7760 'Oct', 'Nov', 'Dec'];
7761
7762 // 26 Feb 16:19:34
7763 function timestamp() {
7764 var d = new Date();
7765 var time = [pad(d.getHours()),
7766 pad(d.getMinutes()),
7767 pad(d.getSeconds())].join(':');
7768 return [d.getDate(), months[d.getMonth()], time].join(' ');
7769 }
7770
7771
7772 // log is just a thin wrapper to console.log that prepends a timestamp
7773 exports.log = function() {
7774 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
7775 };
7776
7777
7778 /**
7779 * Inherit the prototype methods from one constructor into another.
7780 *
7781 * The Function.prototype.inherits from lang.js rewritten as a standalone
7782 * function (not on Function.prototype). NOTE: If this file is to be loaded
7783 * during bootstrapping this function needs to be rewritten using some native
7784 * functions as prototype setup using normal JavaScript does not work as
7785 * expected during bootstrapping (see mirror.js in r114903).
7786 *
7787 * @param {function} ctor Constructor function which needs to inherit the
7788 * prototype.
7789 * @param {function} superCtor Constructor function to inherit prototype from.
7790 */
7791 exports.inherits = __webpack_require__(48);
7792
7793 exports._extend = function(origin, add) {
7794 // Don't do anything if add isn't an object
7795 if (!add || !isObject(add)) return origin;
7796
7797 var keys = Object.keys(add);
7798 var i = keys.length;
7799 while (i--) {
7800 origin[keys[i]] = add[keys[i]];
7801 }
7802 return origin;
7803 };
7804
7805 function hasOwnProperty(obj, prop) {
7806 return Object.prototype.hasOwnProperty.call(obj, prop);
7807 }
7808
7809 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
7810
7811/***/ }),
7812/* 47 */
7813/***/ (function(module, exports) {
7814
7815 module.exports = function isBuffer(arg) {
7816 return arg && typeof arg === 'object'
7817 && typeof arg.copy === 'function'
7818 && typeof arg.fill === 'function'
7819 && typeof arg.readUInt8 === 'function';
7820 }
7821
7822/***/ }),
7823/* 48 */
7824/***/ (function(module, exports) {
7825
7826 if (typeof Object.create === 'function') {
7827 // implementation from standard node.js 'util' module
7828 module.exports = function inherits(ctor, superCtor) {
7829 ctor.super_ = superCtor
7830 ctor.prototype = Object.create(superCtor.prototype, {
7831 constructor: {
7832 value: ctor,
7833 enumerable: false,
7834 writable: true,
7835 configurable: true
7836 }
7837 });
7838 };
7839 } else {
7840 // old school shim for old browsers
7841 module.exports = function inherits(ctor, superCtor) {
7842 ctor.super_ = superCtor
7843 var TempCtor = function () {}
7844 TempCtor.prototype = superCtor.prototype
7845 ctor.prototype = new TempCtor()
7846 ctor.prototype.constructor = ctor
7847 }
7848 }
7849
7850
7851/***/ }),
7852/* 49 */
7853/***/ (function(module, exports, __webpack_require__) {
7854
7855 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
7856 var AcceptorStateMachine = __webpack_require__(50);
7857 var inherit = AWS.util.inherit;
7858 var domain = AWS.util.domain;
7859 var jmespath = __webpack_require__(51);
7860
7861 /**
7862 * @api private
7863 */
7864 var hardErrorStates = {success: 1, error: 1, complete: 1};
7865
7866 function isTerminalState(machine) {
7867 return Object.prototype.hasOwnProperty.call(hardErrorStates, machine._asm.currentState);
7868 }
7869
7870 var fsm = new AcceptorStateMachine();
7871 fsm.setupStates = function() {
7872 var transition = function(_, done) {
7873 var self = this;
7874 self._haltHandlersOnError = false;
7875
7876 self.emit(self._asm.currentState, function(err) {
7877 if (err) {
7878 if (isTerminalState(self)) {
7879 if (domain && self.domain instanceof domain.Domain) {
7880 err.domainEmitter = self;
7881 err.domain = self.domain;
7882 err.domainThrown = false;
7883 self.domain.emit('error', err);
7884 } else {
7885 throw err;
7886 }
7887 } else {
7888 self.response.error = err;
7889 done(err);
7890 }
7891 } else {
7892 done(self.response.error);
7893 }
7894 });
7895
7896 };
7897
7898 this.addState('validate', 'build', 'error', transition);
7899 this.addState('build', 'afterBuild', 'restart', transition);
7900 this.addState('afterBuild', 'sign', 'restart', transition);
7901 this.addState('sign', 'send', 'retry', transition);
7902 this.addState('retry', 'afterRetry', 'afterRetry', transition);
7903 this.addState('afterRetry', 'sign', 'error', transition);
7904 this.addState('send', 'validateResponse', 'retry', transition);
7905 this.addState('validateResponse', 'extractData', 'extractError', transition);
7906 this.addState('extractError', 'extractData', 'retry', transition);
7907 this.addState('extractData', 'success', 'retry', transition);
7908 this.addState('restart', 'build', 'error', transition);
7909 this.addState('success', 'complete', 'complete', transition);
7910 this.addState('error', 'complete', 'complete', transition);
7911 this.addState('complete', null, null, transition);
7912 };
7913 fsm.setupStates();
7914
7915 /**
7916 * ## Asynchronous Requests
7917 *
7918 * All requests made through the SDK are asynchronous and use a
7919 * callback interface. Each service method that kicks off a request
7920 * returns an `AWS.Request` object that you can use to register
7921 * callbacks.
7922 *
7923 * For example, the following service method returns the request
7924 * object as "request", which can be used to register callbacks:
7925 *
7926 * ```javascript
7927 * // request is an AWS.Request object
7928 * var request = ec2.describeInstances();
7929 *
7930 * // register callbacks on request to retrieve response data
7931 * request.on('success', function(response) {
7932 * console.log(response.data);
7933 * });
7934 * ```
7935 *
7936 * When a request is ready to be sent, the {send} method should
7937 * be called:
7938 *
7939 * ```javascript
7940 * request.send();
7941 * ```
7942 *
7943 * Since registered callbacks may or may not be idempotent, requests should only
7944 * be sent once. To perform the same operation multiple times, you will need to
7945 * create multiple request objects, each with its own registered callbacks.
7946 *
7947 * ## Removing Default Listeners for Events
7948 *
7949 * Request objects are built with default listeners for the various events,
7950 * depending on the service type. In some cases, you may want to remove
7951 * some built-in listeners to customize behaviour. Doing this requires
7952 * access to the built-in listener functions, which are exposed through
7953 * the {AWS.EventListeners.Core} namespace. For instance, you may
7954 * want to customize the HTTP handler used when sending a request. In this
7955 * case, you can remove the built-in listener associated with the 'send'
7956 * event, the {AWS.EventListeners.Core.SEND} listener and add your own.
7957 *
7958 * ## Multiple Callbacks and Chaining
7959 *
7960 * You can register multiple callbacks on any request object. The
7961 * callbacks can be registered for different events, or all for the
7962 * same event. In addition, you can chain callback registration, for
7963 * example:
7964 *
7965 * ```javascript
7966 * request.
7967 * on('success', function(response) {
7968 * console.log("Success!");
7969 * }).
7970 * on('error', function(response) {
7971 * console.log("Error!");
7972 * }).
7973 * on('complete', function(response) {
7974 * console.log("Always!");
7975 * }).
7976 * send();
7977 * ```
7978 *
7979 * The above example will print either "Success! Always!", or "Error! Always!",
7980 * depending on whether the request succeeded or not.
7981 *
7982 * @!attribute httpRequest
7983 * @readonly
7984 * @!group HTTP Properties
7985 * @return [AWS.HttpRequest] the raw HTTP request object
7986 * containing request headers and body information
7987 * sent by the service.
7988 *
7989 * @!attribute startTime
7990 * @readonly
7991 * @!group Operation Properties
7992 * @return [Date] the time that the request started
7993 *
7994 * @!group Request Building Events
7995 *
7996 * @!event validate(request)
7997 * Triggered when a request is being validated. Listeners
7998 * should throw an error if the request should not be sent.
7999 * @param request [Request] the request object being sent
8000 * @see AWS.EventListeners.Core.VALIDATE_CREDENTIALS
8001 * @see AWS.EventListeners.Core.VALIDATE_REGION
8002 * @example Ensuring that a certain parameter is set before sending a request
8003 * var req = s3.putObject(params);
8004 * req.on('validate', function() {
8005 * if (!req.params.Body.match(/^Hello\s/)) {
8006 * throw new Error('Body must start with "Hello "');
8007 * }
8008 * });
8009 * req.send(function(err, data) { ... });
8010 *
8011 * @!event build(request)
8012 * Triggered when the request payload is being built. Listeners
8013 * should fill the necessary information to send the request
8014 * over HTTP.
8015 * @param (see AWS.Request~validate)
8016 * @example Add a custom HTTP header to a request
8017 * var req = s3.putObject(params);
8018 * req.on('build', function() {
8019 * req.httpRequest.headers['Custom-Header'] = 'value';
8020 * });
8021 * req.send(function(err, data) { ... });
8022 *
8023 * @!event sign(request)
8024 * Triggered when the request is being signed. Listeners should
8025 * add the correct authentication headers and/or adjust the body,
8026 * depending on the authentication mechanism being used.
8027 * @param (see AWS.Request~validate)
8028 *
8029 * @!group Request Sending Events
8030 *
8031 * @!event send(response)
8032 * Triggered when the request is ready to be sent. Listeners
8033 * should call the underlying transport layer to initiate
8034 * the sending of the request.
8035 * @param response [Response] the response object
8036 * @context [Request] the request object that was sent
8037 * @see AWS.EventListeners.Core.SEND
8038 *
8039 * @!event retry(response)
8040 * Triggered when a request failed and might need to be retried or redirected.
8041 * If the response is retryable, the listener should set the
8042 * `response.error.retryable` property to `true`, and optionally set
8043 * `response.error.retryDelay` to the millisecond delay for the next attempt.
8044 * In the case of a redirect, `response.error.redirect` should be set to
8045 * `true` with `retryDelay` set to an optional delay on the next request.
8046 *
8047 * If a listener decides that a request should not be retried,
8048 * it should set both `retryable` and `redirect` to false.
8049 *
8050 * Note that a retryable error will be retried at most
8051 * {AWS.Config.maxRetries} times (based on the service object's config).
8052 * Similarly, a request that is redirected will only redirect at most
8053 * {AWS.Config.maxRedirects} times.
8054 *
8055 * @param (see AWS.Request~send)
8056 * @context (see AWS.Request~send)
8057 * @example Adding a custom retry for a 404 response
8058 * request.on('retry', function(response) {
8059 * // this resource is not yet available, wait 10 seconds to get it again
8060 * if (response.httpResponse.statusCode === 404 && response.error) {
8061 * response.error.retryable = true; // retry this error
8062 * response.error.retryDelay = 10000; // wait 10 seconds
8063 * }
8064 * });
8065 *
8066 * @!group Data Parsing Events
8067 *
8068 * @!event extractError(response)
8069 * Triggered on all non-2xx requests so that listeners can extract
8070 * error details from the response body. Listeners to this event
8071 * should set the `response.error` property.
8072 * @param (see AWS.Request~send)
8073 * @context (see AWS.Request~send)
8074 *
8075 * @!event extractData(response)
8076 * Triggered in successful requests to allow listeners to
8077 * de-serialize the response body into `response.data`.
8078 * @param (see AWS.Request~send)
8079 * @context (see AWS.Request~send)
8080 *
8081 * @!group Completion Events
8082 *
8083 * @!event success(response)
8084 * Triggered when the request completed successfully.
8085 * `response.data` will contain the response data and
8086 * `response.error` will be null.
8087 * @param (see AWS.Request~send)
8088 * @context (see AWS.Request~send)
8089 *
8090 * @!event error(error, response)
8091 * Triggered when an error occurs at any point during the
8092 * request. `response.error` will contain details about the error
8093 * that occurred. `response.data` will be null.
8094 * @param error [Error] the error object containing details about
8095 * the error that occurred.
8096 * @param (see AWS.Request~send)
8097 * @context (see AWS.Request~send)
8098 *
8099 * @!event complete(response)
8100 * Triggered whenever a request cycle completes. `response.error`
8101 * should be checked, since the request may have failed.
8102 * @param (see AWS.Request~send)
8103 * @context (see AWS.Request~send)
8104 *
8105 * @!group HTTP Events
8106 *
8107 * @!event httpHeaders(statusCode, headers, response, statusMessage)
8108 * Triggered when headers are sent by the remote server
8109 * @param statusCode [Integer] the HTTP response code
8110 * @param headers [map<String,String>] the response headers
8111 * @param (see AWS.Request~send)
8112 * @param statusMessage [String] A status message corresponding to the HTTP
8113 * response code
8114 * @context (see AWS.Request~send)
8115 *
8116 * @!event httpData(chunk, response)
8117 * Triggered when data is sent by the remote server
8118 * @param chunk [Buffer] the buffer data containing the next data chunk
8119 * from the server
8120 * @param (see AWS.Request~send)
8121 * @context (see AWS.Request~send)
8122 * @see AWS.EventListeners.Core.HTTP_DATA
8123 *
8124 * @!event httpUploadProgress(progress, response)
8125 * Triggered when the HTTP request has uploaded more data
8126 * @param progress [map] An object containing the `loaded` and `total` bytes
8127 * of the request.
8128 * @param (see AWS.Request~send)
8129 * @context (see AWS.Request~send)
8130 * @note This event will not be emitted in Node.js 0.8.x.
8131 *
8132 * @!event httpDownloadProgress(progress, response)
8133 * Triggered when the HTTP request has downloaded more data
8134 * @param progress [map] An object containing the `loaded` and `total` bytes
8135 * of the request.
8136 * @param (see AWS.Request~send)
8137 * @context (see AWS.Request~send)
8138 * @note This event will not be emitted in Node.js 0.8.x.
8139 *
8140 * @!event httpError(error, response)
8141 * Triggered when the HTTP request failed
8142 * @param error [Error] the error object that was thrown
8143 * @param (see AWS.Request~send)
8144 * @context (see AWS.Request~send)
8145 *
8146 * @!event httpDone(response)
8147 * Triggered when the server is finished sending data
8148 * @param (see AWS.Request~send)
8149 * @context (see AWS.Request~send)
8150 *
8151 * @see AWS.Response
8152 */
8153 AWS.Request = inherit({
8154
8155 /**
8156 * Creates a request for an operation on a given service with
8157 * a set of input parameters.
8158 *
8159 * @param service [AWS.Service] the service to perform the operation on
8160 * @param operation [String] the operation to perform on the service
8161 * @param params [Object] parameters to send to the operation.
8162 * See the operation's documentation for the format of the
8163 * parameters.
8164 */
8165 constructor: function Request(service, operation, params) {
8166 var endpoint = service.endpoint;
8167 var region = service.config.region;
8168 var customUserAgent = service.config.customUserAgent;
8169
8170 // global endpoints sign as us-east-1
8171 if (service.isGlobalEndpoint) region = 'us-east-1';
8172
8173 this.domain = domain && domain.active;
8174 this.service = service;
8175 this.operation = operation;
8176 this.params = params || {};
8177 this.httpRequest = new AWS.HttpRequest(endpoint, region);
8178 this.httpRequest.appendToUserAgent(customUserAgent);
8179 this.startTime = service.getSkewCorrectedDate();
8180
8181 this.response = new AWS.Response(this);
8182 this._asm = new AcceptorStateMachine(fsm.states, 'validate');
8183 this._haltHandlersOnError = false;
8184
8185 AWS.SequentialExecutor.call(this);
8186 this.emit = this.emitEvent;
8187 },
8188
8189 /**
8190 * @!group Sending a Request
8191 */
8192
8193 /**
8194 * @overload send(callback = null)
8195 * Sends the request object.
8196 *
8197 * @callback callback function(err, data)
8198 * If a callback is supplied, it is called when a response is returned
8199 * from the service.
8200 * @context [AWS.Request] the request object being sent.
8201 * @param err [Error] the error object returned from the request.
8202 * Set to `null` if the request is successful.
8203 * @param data [Object] the de-serialized data returned from
8204 * the request. Set to `null` if a request error occurs.
8205 * @example Sending a request with a callback
8206 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8207 * request.send(function(err, data) { console.log(err, data); });
8208 * @example Sending a request with no callback (using event handlers)
8209 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8210 * request.on('complete', function(response) { ... }); // register a callback
8211 * request.send();
8212 */
8213 send: function send(callback) {
8214 if (callback) {
8215 // append to user agent
8216 this.httpRequest.appendToUserAgent('callback');
8217 this.on('complete', function (resp) {
8218 callback.call(resp, resp.error, resp.data);
8219 });
8220 }
8221 this.runTo();
8222
8223 return this.response;
8224 },
8225
8226 /**
8227 * @!method promise()
8228 * Sends the request and returns a 'thenable' promise.
8229 *
8230 * Two callbacks can be provided to the `then` method on the returned promise.
8231 * The first callback will be called if the promise is fulfilled, and the second
8232 * callback will be called if the promise is rejected.
8233 * @callback fulfilledCallback function(data)
8234 * Called if the promise is fulfilled.
8235 * @param data [Object] the de-serialized data returned from the request.
8236 * @callback rejectedCallback function(error)
8237 * Called if the promise is rejected.
8238 * @param error [Error] the error object returned from the request.
8239 * @return [Promise] A promise that represents the state of the request.
8240 * @example Sending a request using promises.
8241 * var request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8242 * var result = request.promise();
8243 * result.then(function(data) { ... }, function(error) { ... });
8244 */
8245
8246 /**
8247 * @api private
8248 */
8249 build: function build(callback) {
8250 return this.runTo('send', callback);
8251 },
8252
8253 /**
8254 * @api private
8255 */
8256 runTo: function runTo(state, done) {
8257 this._asm.runTo(state, done, this);
8258 return this;
8259 },
8260
8261 /**
8262 * Aborts a request, emitting the error and complete events.
8263 *
8264 * @!macro nobrowser
8265 * @example Aborting a request after sending
8266 * var params = {
8267 * Bucket: 'bucket', Key: 'key',
8268 * Body: new Buffer(1024 * 1024 * 5) // 5MB payload
8269 * };
8270 * var request = s3.putObject(params);
8271 * request.send(function (err, data) {
8272 * if (err) console.log("Error:", err.code, err.message);
8273 * else console.log(data);
8274 * });
8275 *
8276 * // abort request in 1 second
8277 * setTimeout(request.abort.bind(request), 1000);
8278 *
8279 * // prints "Error: RequestAbortedError Request aborted by user"
8280 * @return [AWS.Request] the same request object, for chaining.
8281 * @since v1.4.0
8282 */
8283 abort: function abort() {
8284 this.removeAllListeners('validateResponse');
8285 this.removeAllListeners('extractError');
8286 this.on('validateResponse', function addAbortedError(resp) {
8287 resp.error = AWS.util.error(new Error('Request aborted by user'), {
8288 code: 'RequestAbortedError', retryable: false
8289 });
8290 });
8291
8292 if (this.httpRequest.stream && !this.httpRequest.stream.didCallback) { // abort HTTP stream
8293 this.httpRequest.stream.abort();
8294 if (this.httpRequest._abortCallback) {
8295 this.httpRequest._abortCallback();
8296 } else {
8297 this.removeAllListeners('send'); // haven't sent yet, so let's not
8298 }
8299 }
8300
8301 return this;
8302 },
8303
8304 /**
8305 * Iterates over each page of results given a pageable request, calling
8306 * the provided callback with each page of data. After all pages have been
8307 * retrieved, the callback is called with `null` data.
8308 *
8309 * @note This operation can generate multiple requests to a service.
8310 * @example Iterating over multiple pages of objects in an S3 bucket
8311 * var pages = 1;
8312 * s3.listObjects().eachPage(function(err, data) {
8313 * if (err) return;
8314 * console.log("Page", pages++);
8315 * console.log(data);
8316 * });
8317 * @example Iterating over multiple pages with an asynchronous callback
8318 * s3.listObjects(params).eachPage(function(err, data, done) {
8319 * doSomethingAsyncAndOrExpensive(function() {
8320 * // The next page of results isn't fetched until done is called
8321 * done();
8322 * });
8323 * });
8324 * @callback callback function(err, data, [doneCallback])
8325 * Called with each page of resulting data from the request. If the
8326 * optional `doneCallback` is provided in the function, it must be called
8327 * when the callback is complete.
8328 *
8329 * @param err [Error] an error object, if an error occurred.
8330 * @param data [Object] a single page of response data. If there is no
8331 * more data, this object will be `null`.
8332 * @param doneCallback [Function] an optional done callback. If this
8333 * argument is defined in the function declaration, it should be called
8334 * when the next page is ready to be retrieved. This is useful for
8335 * controlling serial pagination across asynchronous operations.
8336 * @return [Boolean] if the callback returns `false`, pagination will
8337 * stop.
8338 *
8339 * @see AWS.Request.eachItem
8340 * @see AWS.Response.nextPage
8341 * @since v1.4.0
8342 */
8343 eachPage: function eachPage(callback) {
8344 // Make all callbacks async-ish
8345 callback = AWS.util.fn.makeAsync(callback, 3);
8346
8347 function wrappedCallback(response) {
8348 callback.call(response, response.error, response.data, function (result) {
8349 if (result === false) return;
8350
8351 if (response.hasNextPage()) {
8352 response.nextPage().on('complete', wrappedCallback).send();
8353 } else {
8354 callback.call(response, null, null, AWS.util.fn.noop);
8355 }
8356 });
8357 }
8358
8359 this.on('complete', wrappedCallback).send();
8360 },
8361
8362 /**
8363 * Enumerates over individual items of a request, paging the responses if
8364 * necessary.
8365 *
8366 * @api experimental
8367 * @since v1.4.0
8368 */
8369 eachItem: function eachItem(callback) {
8370 var self = this;
8371 function wrappedCallback(err, data) {
8372 if (err) return callback(err, null);
8373 if (data === null) return callback(null, null);
8374
8375 var config = self.service.paginationConfig(self.operation);
8376 var resultKey = config.resultKey;
8377 if (Array.isArray(resultKey)) resultKey = resultKey[0];
8378 var items = jmespath.search(data, resultKey);
8379 var continueIteration = true;
8380 AWS.util.arrayEach(items, function(item) {
8381 continueIteration = callback(null, item);
8382 if (continueIteration === false) {
8383 return AWS.util.abort;
8384 }
8385 });
8386 return continueIteration;
8387 }
8388
8389 this.eachPage(wrappedCallback);
8390 },
8391
8392 /**
8393 * @return [Boolean] whether the operation can return multiple pages of
8394 * response data.
8395 * @see AWS.Response.eachPage
8396 * @since v1.4.0
8397 */
8398 isPageable: function isPageable() {
8399 return this.service.paginationConfig(this.operation) ? true : false;
8400 },
8401
8402 /**
8403 * Sends the request and converts the request object into a readable stream
8404 * that can be read from or piped into a writable stream.
8405 *
8406 * @note The data read from a readable stream contains only
8407 * the raw HTTP body contents.
8408 * @example Manually reading from a stream
8409 * request.createReadStream().on('data', function(data) {
8410 * console.log("Got data:", data.toString());
8411 * });
8412 * @example Piping a request body into a file
8413 * var out = fs.createWriteStream('/path/to/outfile.jpg');
8414 * s3.service.getObject(params).createReadStream().pipe(out);
8415 * @return [Stream] the readable stream object that can be piped
8416 * or read from (by registering 'data' event listeners).
8417 * @!macro nobrowser
8418 */
8419 createReadStream: function createReadStream() {
8420 var streams = AWS.util.stream;
8421 var req = this;
8422 var stream = null;
8423
8424 if (AWS.HttpClient.streamsApiVersion === 2) {
8425 stream = new streams.PassThrough();
8426 process.nextTick(function() { req.send(); });
8427 } else {
8428 stream = new streams.Stream();
8429 stream.readable = true;
8430
8431 stream.sent = false;
8432 stream.on('newListener', function(event) {
8433 if (!stream.sent && event === 'data') {
8434 stream.sent = true;
8435 process.nextTick(function() { req.send(); });
8436 }
8437 });
8438 }
8439
8440 this.on('error', function(err) {
8441 stream.emit('error', err);
8442 });
8443
8444 this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
8445 if (statusCode < 300) {
8446 req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
8447 req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
8448 req.on('httpError', function streamHttpError(error) {
8449 resp.error = error;
8450 resp.error.retryable = false;
8451 });
8452
8453 var shouldCheckContentLength = false;
8454 var expectedLen;
8455 if (req.httpRequest.method !== 'HEAD') {
8456 expectedLen = parseInt(headers['content-length'], 10);
8457 }
8458 if (expectedLen !== undefined && !isNaN(expectedLen) && expectedLen >= 0) {
8459 shouldCheckContentLength = true;
8460 var receivedLen = 0;
8461 }
8462
8463 var checkContentLengthAndEmit = function checkContentLengthAndEmit() {
8464 if (shouldCheckContentLength && receivedLen !== expectedLen) {
8465 stream.emit('error', AWS.util.error(
8466 new Error('Stream content length mismatch. Received ' +
8467 receivedLen + ' of ' + expectedLen + ' bytes.'),
8468 { code: 'StreamContentLengthMismatch' }
8469 ));
8470 } else if (AWS.HttpClient.streamsApiVersion === 2) {
8471 stream.end();
8472 } else {
8473 stream.emit('end');
8474 }
8475 };
8476
8477 var httpStream = resp.httpResponse.createUnbufferedStream();
8478
8479 if (AWS.HttpClient.streamsApiVersion === 2) {
8480 if (shouldCheckContentLength) {
8481 var lengthAccumulator = new streams.PassThrough();
8482 lengthAccumulator._write = function(chunk) {
8483 if (chunk && chunk.length) {
8484 receivedLen += chunk.length;
8485 }
8486 return streams.PassThrough.prototype._write.apply(this, arguments);
8487 };
8488
8489 lengthAccumulator.on('end', checkContentLengthAndEmit);
8490 stream.on('error', function(err) {
8491 shouldCheckContentLength = false;
8492 httpStream.unpipe(lengthAccumulator);
8493 lengthAccumulator.emit('end');
8494 lengthAccumulator.end();
8495 });
8496 httpStream.pipe(lengthAccumulator).pipe(stream, { end: false });
8497 } else {
8498 httpStream.pipe(stream);
8499 }
8500 } else {
8501
8502 if (shouldCheckContentLength) {
8503 httpStream.on('data', function(arg) {
8504 if (arg && arg.length) {
8505 receivedLen += arg.length;
8506 }
8507 });
8508 }
8509
8510 httpStream.on('data', function(arg) {
8511 stream.emit('data', arg);
8512 });
8513 httpStream.on('end', checkContentLengthAndEmit);
8514 }
8515
8516 httpStream.on('error', function(err) {
8517 shouldCheckContentLength = false;
8518 stream.emit('error', err);
8519 });
8520 }
8521 });
8522
8523 return stream;
8524 },
8525
8526 /**
8527 * @param [Array,Response] args This should be the response object,
8528 * or an array of args to send to the event.
8529 * @api private
8530 */
8531 emitEvent: function emit(eventName, args, done) {
8532 if (typeof args === 'function') { done = args; args = null; }
8533 if (!done) done = function() { };
8534 if (!args) args = this.eventParameters(eventName, this.response);
8535
8536 var origEmit = AWS.SequentialExecutor.prototype.emit;
8537 origEmit.call(this, eventName, args, function (err) {
8538 if (err) this.response.error = err;
8539 done.call(this, err);
8540 });
8541 },
8542
8543 /**
8544 * @api private
8545 */
8546 eventParameters: function eventParameters(eventName) {
8547 switch (eventName) {
8548 case 'restart':
8549 case 'validate':
8550 case 'sign':
8551 case 'build':
8552 case 'afterValidate':
8553 case 'afterBuild':
8554 return [this];
8555 case 'error':
8556 return [this.response.error, this.response];
8557 default:
8558 return [this.response];
8559 }
8560 },
8561
8562 /**
8563 * @api private
8564 */
8565 presign: function presign(expires, callback) {
8566 if (!callback && typeof expires === 'function') {
8567 callback = expires;
8568 expires = null;
8569 }
8570 return new AWS.Signers.Presign().sign(this.toGet(), expires, callback);
8571 },
8572
8573 /**
8574 * @api private
8575 */
8576 isPresigned: function isPresigned() {
8577 return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires');
8578 },
8579
8580 /**
8581 * @api private
8582 */
8583 toUnauthenticated: function toUnauthenticated() {
8584 this._unAuthenticated = true;
8585 this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS);
8586 this.removeListener('sign', AWS.EventListeners.Core.SIGN);
8587 return this;
8588 },
8589
8590 /**
8591 * @api private
8592 */
8593 toGet: function toGet() {
8594 if (this.service.api.protocol === 'query' ||
8595 this.service.api.protocol === 'ec2') {
8596 this.removeListener('build', this.buildAsGet);
8597 this.addListener('build', this.buildAsGet);
8598 }
8599 return this;
8600 },
8601
8602 /**
8603 * @api private
8604 */
8605 buildAsGet: function buildAsGet(request) {
8606 request.httpRequest.method = 'GET';
8607 request.httpRequest.path = request.service.endpoint.path +
8608 '?' + request.httpRequest.body;
8609 request.httpRequest.body = '';
8610
8611 // don't need these headers on a GET request
8612 delete request.httpRequest.headers['Content-Length'];
8613 delete request.httpRequest.headers['Content-Type'];
8614 },
8615
8616 /**
8617 * @api private
8618 */
8619 haltHandlersOnError: function haltHandlersOnError() {
8620 this._haltHandlersOnError = true;
8621 }
8622 });
8623
8624 /**
8625 * @api private
8626 */
8627 AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
8628 this.prototype.promise = function promise() {
8629 var self = this;
8630 // append to user agent
8631 this.httpRequest.appendToUserAgent('promise');
8632 return new PromiseDependency(function(resolve, reject) {
8633 self.on('complete', function(resp) {
8634 if (resp.error) {
8635 reject(resp.error);
8636 } else {
8637 // define $response property so that it is not enumberable
8638 // this prevents circular reference errors when stringifying the JSON object
8639 resolve(Object.defineProperty(
8640 resp.data || {},
8641 '$response',
8642 {value: resp}
8643 ));
8644 }
8645 });
8646 self.runTo();
8647 });
8648 };
8649 };
8650
8651 /**
8652 * @api private
8653 */
8654 AWS.Request.deletePromisesFromClass = function deletePromisesFromClass() {
8655 delete this.prototype.promise;
8656 };
8657
8658 AWS.util.addPromises(AWS.Request);
8659
8660 AWS.util.mixin(AWS.Request, AWS.SequentialExecutor);
8661
8662 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
8663
8664/***/ }),
8665/* 50 */
8666/***/ (function(module, exports) {
8667
8668 function AcceptorStateMachine(states, state) {
8669 this.currentState = state || null;
8670 this.states = states || {};
8671 }
8672
8673 AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) {
8674 if (typeof finalState === 'function') {
8675 inputError = bindObject; bindObject = done;
8676 done = finalState; finalState = null;
8677 }
8678
8679 var self = this;
8680 var state = self.states[self.currentState];
8681 state.fn.call(bindObject || self, inputError, function(err) {
8682 if (err) {
8683 if (state.fail) self.currentState = state.fail;
8684 else return done ? done.call(bindObject, err) : null;
8685 } else {
8686 if (state.accept) self.currentState = state.accept;
8687 else return done ? done.call(bindObject) : null;
8688 }
8689 if (self.currentState === finalState) {
8690 return done ? done.call(bindObject, err) : null;
8691 }
8692
8693 self.runTo(finalState, done, bindObject, err);
8694 });
8695 };
8696
8697 AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) {
8698 if (typeof acceptState === 'function') {
8699 fn = acceptState; acceptState = null; failState = null;
8700 } else if (typeof failState === 'function') {
8701 fn = failState; failState = null;
8702 }
8703
8704 if (!this.currentState) this.currentState = name;
8705 this.states[name] = { accept: acceptState, fail: failState, fn: fn };
8706 return this;
8707 };
8708
8709 /**
8710 * @api private
8711 */
8712 module.exports = AcceptorStateMachine;
8713
8714
8715/***/ }),
8716/* 51 */
8717/***/ (function(module, exports, __webpack_require__) {
8718
8719 (function(exports) {
8720 "use strict";
8721
8722 function isArray(obj) {
8723 if (obj !== null) {
8724 return Object.prototype.toString.call(obj) === "[object Array]";
8725 } else {
8726 return false;
8727 }
8728 }
8729
8730 function isObject(obj) {
8731 if (obj !== null) {
8732 return Object.prototype.toString.call(obj) === "[object Object]";
8733 } else {
8734 return false;
8735 }
8736 }
8737
8738 function strictDeepEqual(first, second) {
8739 // Check the scalar case first.
8740 if (first === second) {
8741 return true;
8742 }
8743
8744 // Check if they are the same type.
8745 var firstType = Object.prototype.toString.call(first);
8746 if (firstType !== Object.prototype.toString.call(second)) {
8747 return false;
8748 }
8749 // We know that first and second have the same type so we can just check the
8750 // first type from now on.
8751 if (isArray(first) === true) {
8752 // Short circuit if they're not the same length;
8753 if (first.length !== second.length) {
8754 return false;
8755 }
8756 for (var i = 0; i < first.length; i++) {
8757 if (strictDeepEqual(first[i], second[i]) === false) {
8758 return false;
8759 }
8760 }
8761 return true;
8762 }
8763 if (isObject(first) === true) {
8764 // An object is equal if it has the same key/value pairs.
8765 var keysSeen = {};
8766 for (var key in first) {
8767 if (hasOwnProperty.call(first, key)) {
8768 if (strictDeepEqual(first[key], second[key]) === false) {
8769 return false;
8770 }
8771 keysSeen[key] = true;
8772 }
8773 }
8774 // Now check that there aren't any keys in second that weren't
8775 // in first.
8776 for (var key2 in second) {
8777 if (hasOwnProperty.call(second, key2)) {
8778 if (keysSeen[key2] !== true) {
8779 return false;
8780 }
8781 }
8782 }
8783 return true;
8784 }
8785 return false;
8786 }
8787
8788 function isFalse(obj) {
8789 // From the spec:
8790 // A false value corresponds to the following values:
8791 // Empty list
8792 // Empty object
8793 // Empty string
8794 // False boolean
8795 // null value
8796
8797 // First check the scalar values.
8798 if (obj === "" || obj === false || obj === null) {
8799 return true;
8800 } else if (isArray(obj) && obj.length === 0) {
8801 // Check for an empty array.
8802 return true;
8803 } else if (isObject(obj)) {
8804 // Check for an empty object.
8805 for (var key in obj) {
8806 // If there are any keys, then
8807 // the object is not empty so the object
8808 // is not false.
8809 if (obj.hasOwnProperty(key)) {
8810 return false;
8811 }
8812 }
8813 return true;
8814 } else {
8815 return false;
8816 }
8817 }
8818
8819 function objValues(obj) {
8820 var keys = Object.keys(obj);
8821 var values = [];
8822 for (var i = 0; i < keys.length; i++) {
8823 values.push(obj[keys[i]]);
8824 }
8825 return values;
8826 }
8827
8828 function merge(a, b) {
8829 var merged = {};
8830 for (var key in a) {
8831 merged[key] = a[key];
8832 }
8833 for (var key2 in b) {
8834 merged[key2] = b[key2];
8835 }
8836 return merged;
8837 }
8838
8839 var trimLeft;
8840 if (typeof String.prototype.trimLeft === "function") {
8841 trimLeft = function(str) {
8842 return str.trimLeft();
8843 };
8844 } else {
8845 trimLeft = function(str) {
8846 return str.match(/^\s*(.*)/)[1];
8847 };
8848 }
8849
8850 // Type constants used to define functions.
8851 var TYPE_NUMBER = 0;
8852 var TYPE_ANY = 1;
8853 var TYPE_STRING = 2;
8854 var TYPE_ARRAY = 3;
8855 var TYPE_OBJECT = 4;
8856 var TYPE_BOOLEAN = 5;
8857 var TYPE_EXPREF = 6;
8858 var TYPE_NULL = 7;
8859 var TYPE_ARRAY_NUMBER = 8;
8860 var TYPE_ARRAY_STRING = 9;
8861
8862 var TOK_EOF = "EOF";
8863 var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier";
8864 var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier";
8865 var TOK_RBRACKET = "Rbracket";
8866 var TOK_RPAREN = "Rparen";
8867 var TOK_COMMA = "Comma";
8868 var TOK_COLON = "Colon";
8869 var TOK_RBRACE = "Rbrace";
8870 var TOK_NUMBER = "Number";
8871 var TOK_CURRENT = "Current";
8872 var TOK_EXPREF = "Expref";
8873 var TOK_PIPE = "Pipe";
8874 var TOK_OR = "Or";
8875 var TOK_AND = "And";
8876 var TOK_EQ = "EQ";
8877 var TOK_GT = "GT";
8878 var TOK_LT = "LT";
8879 var TOK_GTE = "GTE";
8880 var TOK_LTE = "LTE";
8881 var TOK_NE = "NE";
8882 var TOK_FLATTEN = "Flatten";
8883 var TOK_STAR = "Star";
8884 var TOK_FILTER = "Filter";
8885 var TOK_DOT = "Dot";
8886 var TOK_NOT = "Not";
8887 var TOK_LBRACE = "Lbrace";
8888 var TOK_LBRACKET = "Lbracket";
8889 var TOK_LPAREN= "Lparen";
8890 var TOK_LITERAL= "Literal";
8891
8892 // The "&", "[", "<", ">" tokens
8893 // are not in basicToken because
8894 // there are two token variants
8895 // ("&&", "[?", "<=", ">="). This is specially handled
8896 // below.
8897
8898 var basicTokens = {
8899 ".": TOK_DOT,
8900 "*": TOK_STAR,
8901 ",": TOK_COMMA,
8902 ":": TOK_COLON,
8903 "{": TOK_LBRACE,
8904 "}": TOK_RBRACE,
8905 "]": TOK_RBRACKET,
8906 "(": TOK_LPAREN,
8907 ")": TOK_RPAREN,
8908 "@": TOK_CURRENT
8909 };
8910
8911 var operatorStartToken = {
8912 "<": true,
8913 ">": true,
8914 "=": true,
8915 "!": true
8916 };
8917
8918 var skipChars = {
8919 " ": true,
8920 "\t": true,
8921 "\n": true
8922 };
8923
8924
8925 function isAlpha(ch) {
8926 return (ch >= "a" && ch <= "z") ||
8927 (ch >= "A" && ch <= "Z") ||
8928 ch === "_";
8929 }
8930
8931 function isNum(ch) {
8932 return (ch >= "0" && ch <= "9") ||
8933 ch === "-";
8934 }
8935 function isAlphaNum(ch) {
8936 return (ch >= "a" && ch <= "z") ||
8937 (ch >= "A" && ch <= "Z") ||
8938 (ch >= "0" && ch <= "9") ||
8939 ch === "_";
8940 }
8941
8942 function Lexer() {
8943 }
8944 Lexer.prototype = {
8945 tokenize: function(stream) {
8946 var tokens = [];
8947 this._current = 0;
8948 var start;
8949 var identifier;
8950 var token;
8951 while (this._current < stream.length) {
8952 if (isAlpha(stream[this._current])) {
8953 start = this._current;
8954 identifier = this._consumeUnquotedIdentifier(stream);
8955 tokens.push({type: TOK_UNQUOTEDIDENTIFIER,
8956 value: identifier,
8957 start: start});
8958 } else if (basicTokens[stream[this._current]] !== undefined) {
8959 tokens.push({type: basicTokens[stream[this._current]],
8960 value: stream[this._current],
8961 start: this._current});
8962 this._current++;
8963 } else if (isNum(stream[this._current])) {
8964 token = this._consumeNumber(stream);
8965 tokens.push(token);
8966 } else if (stream[this._current] === "[") {
8967 // No need to increment this._current. This happens
8968 // in _consumeLBracket
8969 token = this._consumeLBracket(stream);
8970 tokens.push(token);
8971 } else if (stream[this._current] === "\"") {
8972 start = this._current;
8973 identifier = this._consumeQuotedIdentifier(stream);
8974 tokens.push({type: TOK_QUOTEDIDENTIFIER,
8975 value: identifier,
8976 start: start});
8977 } else if (stream[this._current] === "'") {
8978 start = this._current;
8979 identifier = this._consumeRawStringLiteral(stream);
8980 tokens.push({type: TOK_LITERAL,
8981 value: identifier,
8982 start: start});
8983 } else if (stream[this._current] === "`") {
8984 start = this._current;
8985 var literal = this._consumeLiteral(stream);
8986 tokens.push({type: TOK_LITERAL,
8987 value: literal,
8988 start: start});
8989 } else if (operatorStartToken[stream[this._current]] !== undefined) {
8990 tokens.push(this._consumeOperator(stream));
8991 } else if (skipChars[stream[this._current]] !== undefined) {
8992 // Ignore whitespace.
8993 this._current++;
8994 } else if (stream[this._current] === "&") {
8995 start = this._current;
8996 this._current++;
8997 if (stream[this._current] === "&") {
8998 this._current++;
8999 tokens.push({type: TOK_AND, value: "&&", start: start});
9000 } else {
9001 tokens.push({type: TOK_EXPREF, value: "&", start: start});
9002 }
9003 } else if (stream[this._current] === "|") {
9004 start = this._current;
9005 this._current++;
9006 if (stream[this._current] === "|") {
9007 this._current++;
9008 tokens.push({type: TOK_OR, value: "||", start: start});
9009 } else {
9010 tokens.push({type: TOK_PIPE, value: "|", start: start});
9011 }
9012 } else {
9013 var error = new Error("Unknown character:" + stream[this._current]);
9014 error.name = "LexerError";
9015 throw error;
9016 }
9017 }
9018 return tokens;
9019 },
9020
9021 _consumeUnquotedIdentifier: function(stream) {
9022 var start = this._current;
9023 this._current++;
9024 while (this._current < stream.length && isAlphaNum(stream[this._current])) {
9025 this._current++;
9026 }
9027 return stream.slice(start, this._current);
9028 },
9029
9030 _consumeQuotedIdentifier: function(stream) {
9031 var start = this._current;
9032 this._current++;
9033 var maxLength = stream.length;
9034 while (stream[this._current] !== "\"" && this._current < maxLength) {
9035 // You can escape a double quote and you can escape an escape.
9036 var current = this._current;
9037 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9038 stream[current + 1] === "\"")) {
9039 current += 2;
9040 } else {
9041 current++;
9042 }
9043 this._current = current;
9044 }
9045 this._current++;
9046 return JSON.parse(stream.slice(start, this._current));
9047 },
9048
9049 _consumeRawStringLiteral: function(stream) {
9050 var start = this._current;
9051 this._current++;
9052 var maxLength = stream.length;
9053 while (stream[this._current] !== "'" && this._current < maxLength) {
9054 // You can escape a single quote and you can escape an escape.
9055 var current = this._current;
9056 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9057 stream[current + 1] === "'")) {
9058 current += 2;
9059 } else {
9060 current++;
9061 }
9062 this._current = current;
9063 }
9064 this._current++;
9065 var literal = stream.slice(start + 1, this._current - 1);
9066 return literal.replace("\\'", "'");
9067 },
9068
9069 _consumeNumber: function(stream) {
9070 var start = this._current;
9071 this._current++;
9072 var maxLength = stream.length;
9073 while (isNum(stream[this._current]) && this._current < maxLength) {
9074 this._current++;
9075 }
9076 var value = parseInt(stream.slice(start, this._current));
9077 return {type: TOK_NUMBER, value: value, start: start};
9078 },
9079
9080 _consumeLBracket: function(stream) {
9081 var start = this._current;
9082 this._current++;
9083 if (stream[this._current] === "?") {
9084 this._current++;
9085 return {type: TOK_FILTER, value: "[?", start: start};
9086 } else if (stream[this._current] === "]") {
9087 this._current++;
9088 return {type: TOK_FLATTEN, value: "[]", start: start};
9089 } else {
9090 return {type: TOK_LBRACKET, value: "[", start: start};
9091 }
9092 },
9093
9094 _consumeOperator: function(stream) {
9095 var start = this._current;
9096 var startingChar = stream[start];
9097 this._current++;
9098 if (startingChar === "!") {
9099 if (stream[this._current] === "=") {
9100 this._current++;
9101 return {type: TOK_NE, value: "!=", start: start};
9102 } else {
9103 return {type: TOK_NOT, value: "!", start: start};
9104 }
9105 } else if (startingChar === "<") {
9106 if (stream[this._current] === "=") {
9107 this._current++;
9108 return {type: TOK_LTE, value: "<=", start: start};
9109 } else {
9110 return {type: TOK_LT, value: "<", start: start};
9111 }
9112 } else if (startingChar === ">") {
9113 if (stream[this._current] === "=") {
9114 this._current++;
9115 return {type: TOK_GTE, value: ">=", start: start};
9116 } else {
9117 return {type: TOK_GT, value: ">", start: start};
9118 }
9119 } else if (startingChar === "=") {
9120 if (stream[this._current] === "=") {
9121 this._current++;
9122 return {type: TOK_EQ, value: "==", start: start};
9123 }
9124 }
9125 },
9126
9127 _consumeLiteral: function(stream) {
9128 this._current++;
9129 var start = this._current;
9130 var maxLength = stream.length;
9131 var literal;
9132 while(stream[this._current] !== "`" && this._current < maxLength) {
9133 // You can escape a literal char or you can escape the escape.
9134 var current = this._current;
9135 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9136 stream[current + 1] === "`")) {
9137 current += 2;
9138 } else {
9139 current++;
9140 }
9141 this._current = current;
9142 }
9143 var literalString = trimLeft(stream.slice(start, this._current));
9144 literalString = literalString.replace("\\`", "`");
9145 if (this._looksLikeJSON(literalString)) {
9146 literal = JSON.parse(literalString);
9147 } else {
9148 // Try to JSON parse it as "<literal>"
9149 literal = JSON.parse("\"" + literalString + "\"");
9150 }
9151 // +1 gets us to the ending "`", +1 to move on to the next char.
9152 this._current++;
9153 return literal;
9154 },
9155
9156 _looksLikeJSON: function(literalString) {
9157 var startingChars = "[{\"";
9158 var jsonLiterals = ["true", "false", "null"];
9159 var numberLooking = "-0123456789";
9160
9161 if (literalString === "") {
9162 return false;
9163 } else if (startingChars.indexOf(literalString[0]) >= 0) {
9164 return true;
9165 } else if (jsonLiterals.indexOf(literalString) >= 0) {
9166 return true;
9167 } else if (numberLooking.indexOf(literalString[0]) >= 0) {
9168 try {
9169 JSON.parse(literalString);
9170 return true;
9171 } catch (ex) {
9172 return false;
9173 }
9174 } else {
9175 return false;
9176 }
9177 }
9178 };
9179
9180 var bindingPower = {};
9181 bindingPower[TOK_EOF] = 0;
9182 bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0;
9183 bindingPower[TOK_QUOTEDIDENTIFIER] = 0;
9184 bindingPower[TOK_RBRACKET] = 0;
9185 bindingPower[TOK_RPAREN] = 0;
9186 bindingPower[TOK_COMMA] = 0;
9187 bindingPower[TOK_RBRACE] = 0;
9188 bindingPower[TOK_NUMBER] = 0;
9189 bindingPower[TOK_CURRENT] = 0;
9190 bindingPower[TOK_EXPREF] = 0;
9191 bindingPower[TOK_PIPE] = 1;
9192 bindingPower[TOK_OR] = 2;
9193 bindingPower[TOK_AND] = 3;
9194 bindingPower[TOK_EQ] = 5;
9195 bindingPower[TOK_GT] = 5;
9196 bindingPower[TOK_LT] = 5;
9197 bindingPower[TOK_GTE] = 5;
9198 bindingPower[TOK_LTE] = 5;
9199 bindingPower[TOK_NE] = 5;
9200 bindingPower[TOK_FLATTEN] = 9;
9201 bindingPower[TOK_STAR] = 20;
9202 bindingPower[TOK_FILTER] = 21;
9203 bindingPower[TOK_DOT] = 40;
9204 bindingPower[TOK_NOT] = 45;
9205 bindingPower[TOK_LBRACE] = 50;
9206 bindingPower[TOK_LBRACKET] = 55;
9207 bindingPower[TOK_LPAREN] = 60;
9208
9209 function Parser() {
9210 }
9211
9212 Parser.prototype = {
9213 parse: function(expression) {
9214 this._loadTokens(expression);
9215 this.index = 0;
9216 var ast = this.expression(0);
9217 if (this._lookahead(0) !== TOK_EOF) {
9218 var t = this._lookaheadToken(0);
9219 var error = new Error(
9220 "Unexpected token type: " + t.type + ", value: " + t.value);
9221 error.name = "ParserError";
9222 throw error;
9223 }
9224 return ast;
9225 },
9226
9227 _loadTokens: function(expression) {
9228 var lexer = new Lexer();
9229 var tokens = lexer.tokenize(expression);
9230 tokens.push({type: TOK_EOF, value: "", start: expression.length});
9231 this.tokens = tokens;
9232 },
9233
9234 expression: function(rbp) {
9235 var leftToken = this._lookaheadToken(0);
9236 this._advance();
9237 var left = this.nud(leftToken);
9238 var currentToken = this._lookahead(0);
9239 while (rbp < bindingPower[currentToken]) {
9240 this._advance();
9241 left = this.led(currentToken, left);
9242 currentToken = this._lookahead(0);
9243 }
9244 return left;
9245 },
9246
9247 _lookahead: function(number) {
9248 return this.tokens[this.index + number].type;
9249 },
9250
9251 _lookaheadToken: function(number) {
9252 return this.tokens[this.index + number];
9253 },
9254
9255 _advance: function() {
9256 this.index++;
9257 },
9258
9259 nud: function(token) {
9260 var left;
9261 var right;
9262 var expression;
9263 switch (token.type) {
9264 case TOK_LITERAL:
9265 return {type: "Literal", value: token.value};
9266 case TOK_UNQUOTEDIDENTIFIER:
9267 return {type: "Field", name: token.value};
9268 case TOK_QUOTEDIDENTIFIER:
9269 var node = {type: "Field", name: token.value};
9270 if (this._lookahead(0) === TOK_LPAREN) {
9271 throw new Error("Quoted identifier not allowed for function names.");
9272 } else {
9273 return node;
9274 }
9275 break;
9276 case TOK_NOT:
9277 right = this.expression(bindingPower.Not);
9278 return {type: "NotExpression", children: [right]};
9279 case TOK_STAR:
9280 left = {type: "Identity"};
9281 right = null;
9282 if (this._lookahead(0) === TOK_RBRACKET) {
9283 // This can happen in a multiselect,
9284 // [a, b, *]
9285 right = {type: "Identity"};
9286 } else {
9287 right = this._parseProjectionRHS(bindingPower.Star);
9288 }
9289 return {type: "ValueProjection", children: [left, right]};
9290 case TOK_FILTER:
9291 return this.led(token.type, {type: "Identity"});
9292 case TOK_LBRACE:
9293 return this._parseMultiselectHash();
9294 case TOK_FLATTEN:
9295 left = {type: TOK_FLATTEN, children: [{type: "Identity"}]};
9296 right = this._parseProjectionRHS(bindingPower.Flatten);
9297 return {type: "Projection", children: [left, right]};
9298 case TOK_LBRACKET:
9299 if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) {
9300 right = this._parseIndexExpression();
9301 return this._projectIfSlice({type: "Identity"}, right);
9302 } else if (this._lookahead(0) === TOK_STAR &&
9303 this._lookahead(1) === TOK_RBRACKET) {
9304 this._advance();
9305 this._advance();
9306 right = this._parseProjectionRHS(bindingPower.Star);
9307 return {type: "Projection",
9308 children: [{type: "Identity"}, right]};
9309 } else {
9310 return this._parseMultiselectList();
9311 }
9312 break;
9313 case TOK_CURRENT:
9314 return {type: TOK_CURRENT};
9315 case TOK_EXPREF:
9316 expression = this.expression(bindingPower.Expref);
9317 return {type: "ExpressionReference", children: [expression]};
9318 case TOK_LPAREN:
9319 var args = [];
9320 while (this._lookahead(0) !== TOK_RPAREN) {
9321 if (this._lookahead(0) === TOK_CURRENT) {
9322 expression = {type: TOK_CURRENT};
9323 this._advance();
9324 } else {
9325 expression = this.expression(0);
9326 }
9327 args.push(expression);
9328 }
9329 this._match(TOK_RPAREN);
9330 return args[0];
9331 default:
9332 this._errorToken(token);
9333 }
9334 },
9335
9336 led: function(tokenName, left) {
9337 var right;
9338 switch(tokenName) {
9339 case TOK_DOT:
9340 var rbp = bindingPower.Dot;
9341 if (this._lookahead(0) !== TOK_STAR) {
9342 right = this._parseDotRHS(rbp);
9343 return {type: "Subexpression", children: [left, right]};
9344 } else {
9345 // Creating a projection.
9346 this._advance();
9347 right = this._parseProjectionRHS(rbp);
9348 return {type: "ValueProjection", children: [left, right]};
9349 }
9350 break;
9351 case TOK_PIPE:
9352 right = this.expression(bindingPower.Pipe);
9353 return {type: TOK_PIPE, children: [left, right]};
9354 case TOK_OR:
9355 right = this.expression(bindingPower.Or);
9356 return {type: "OrExpression", children: [left, right]};
9357 case TOK_AND:
9358 right = this.expression(bindingPower.And);
9359 return {type: "AndExpression", children: [left, right]};
9360 case TOK_LPAREN:
9361 var name = left.name;
9362 var args = [];
9363 var expression, node;
9364 while (this._lookahead(0) !== TOK_RPAREN) {
9365 if (this._lookahead(0) === TOK_CURRENT) {
9366 expression = {type: TOK_CURRENT};
9367 this._advance();
9368 } else {
9369 expression = this.expression(0);
9370 }
9371 if (this._lookahead(0) === TOK_COMMA) {
9372 this._match(TOK_COMMA);
9373 }
9374 args.push(expression);
9375 }
9376 this._match(TOK_RPAREN);
9377 node = {type: "Function", name: name, children: args};
9378 return node;
9379 case TOK_FILTER:
9380 var condition = this.expression(0);
9381 this._match(TOK_RBRACKET);
9382 if (this._lookahead(0) === TOK_FLATTEN) {
9383 right = {type: "Identity"};
9384 } else {
9385 right = this._parseProjectionRHS(bindingPower.Filter);
9386 }
9387 return {type: "FilterProjection", children: [left, right, condition]};
9388 case TOK_FLATTEN:
9389 var leftNode = {type: TOK_FLATTEN, children: [left]};
9390 var rightNode = this._parseProjectionRHS(bindingPower.Flatten);
9391 return {type: "Projection", children: [leftNode, rightNode]};
9392 case TOK_EQ:
9393 case TOK_NE:
9394 case TOK_GT:
9395 case TOK_GTE:
9396 case TOK_LT:
9397 case TOK_LTE:
9398 return this._parseComparator(left, tokenName);
9399 case TOK_LBRACKET:
9400 var token = this._lookaheadToken(0);
9401 if (token.type === TOK_NUMBER || token.type === TOK_COLON) {
9402 right = this._parseIndexExpression();
9403 return this._projectIfSlice(left, right);
9404 } else {
9405 this._match(TOK_STAR);
9406 this._match(TOK_RBRACKET);
9407 right = this._parseProjectionRHS(bindingPower.Star);
9408 return {type: "Projection", children: [left, right]};
9409 }
9410 break;
9411 default:
9412 this._errorToken(this._lookaheadToken(0));
9413 }
9414 },
9415
9416 _match: function(tokenType) {
9417 if (this._lookahead(0) === tokenType) {
9418 this._advance();
9419 } else {
9420 var t = this._lookaheadToken(0);
9421 var error = new Error("Expected " + tokenType + ", got: " + t.type);
9422 error.name = "ParserError";
9423 throw error;
9424 }
9425 },
9426
9427 _errorToken: function(token) {
9428 var error = new Error("Invalid token (" +
9429 token.type + "): \"" +
9430 token.value + "\"");
9431 error.name = "ParserError";
9432 throw error;
9433 },
9434
9435
9436 _parseIndexExpression: function() {
9437 if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) {
9438 return this._parseSliceExpression();
9439 } else {
9440 var node = {
9441 type: "Index",
9442 value: this._lookaheadToken(0).value};
9443 this._advance();
9444 this._match(TOK_RBRACKET);
9445 return node;
9446 }
9447 },
9448
9449 _projectIfSlice: function(left, right) {
9450 var indexExpr = {type: "IndexExpression", children: [left, right]};
9451 if (right.type === "Slice") {
9452 return {
9453 type: "Projection",
9454 children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)]
9455 };
9456 } else {
9457 return indexExpr;
9458 }
9459 },
9460
9461 _parseSliceExpression: function() {
9462 // [start:end:step] where each part is optional, as well as the last
9463 // colon.
9464 var parts = [null, null, null];
9465 var index = 0;
9466 var currentToken = this._lookahead(0);
9467 while (currentToken !== TOK_RBRACKET && index < 3) {
9468 if (currentToken === TOK_COLON) {
9469 index++;
9470 this._advance();
9471 } else if (currentToken === TOK_NUMBER) {
9472 parts[index] = this._lookaheadToken(0).value;
9473 this._advance();
9474 } else {
9475 var t = this._lookahead(0);
9476 var error = new Error("Syntax error, unexpected token: " +
9477 t.value + "(" + t.type + ")");
9478 error.name = "Parsererror";
9479 throw error;
9480 }
9481 currentToken = this._lookahead(0);
9482 }
9483 this._match(TOK_RBRACKET);
9484 return {
9485 type: "Slice",
9486 children: parts
9487 };
9488 },
9489
9490 _parseComparator: function(left, comparator) {
9491 var right = this.expression(bindingPower[comparator]);
9492 return {type: "Comparator", name: comparator, children: [left, right]};
9493 },
9494
9495 _parseDotRHS: function(rbp) {
9496 var lookahead = this._lookahead(0);
9497 var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];
9498 if (exprTokens.indexOf(lookahead) >= 0) {
9499 return this.expression(rbp);
9500 } else if (lookahead === TOK_LBRACKET) {
9501 this._match(TOK_LBRACKET);
9502 return this._parseMultiselectList();
9503 } else if (lookahead === TOK_LBRACE) {
9504 this._match(TOK_LBRACE);
9505 return this._parseMultiselectHash();
9506 }
9507 },
9508
9509 _parseProjectionRHS: function(rbp) {
9510 var right;
9511 if (bindingPower[this._lookahead(0)] < 10) {
9512 right = {type: "Identity"};
9513 } else if (this._lookahead(0) === TOK_LBRACKET) {
9514 right = this.expression(rbp);
9515 } else if (this._lookahead(0) === TOK_FILTER) {
9516 right = this.expression(rbp);
9517 } else if (this._lookahead(0) === TOK_DOT) {
9518 this._match(TOK_DOT);
9519 right = this._parseDotRHS(rbp);
9520 } else {
9521 var t = this._lookaheadToken(0);
9522 var error = new Error("Sytanx error, unexpected token: " +
9523 t.value + "(" + t.type + ")");
9524 error.name = "ParserError";
9525 throw error;
9526 }
9527 return right;
9528 },
9529
9530 _parseMultiselectList: function() {
9531 var expressions = [];
9532 while (this._lookahead(0) !== TOK_RBRACKET) {
9533 var expression = this.expression(0);
9534 expressions.push(expression);
9535 if (this._lookahead(0) === TOK_COMMA) {
9536 this._match(TOK_COMMA);
9537 if (this._lookahead(0) === TOK_RBRACKET) {
9538 throw new Error("Unexpected token Rbracket");
9539 }
9540 }
9541 }
9542 this._match(TOK_RBRACKET);
9543 return {type: "MultiSelectList", children: expressions};
9544 },
9545
9546 _parseMultiselectHash: function() {
9547 var pairs = [];
9548 var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER];
9549 var keyToken, keyName, value, node;
9550 for (;;) {
9551 keyToken = this._lookaheadToken(0);
9552 if (identifierTypes.indexOf(keyToken.type) < 0) {
9553 throw new Error("Expecting an identifier token, got: " +
9554 keyToken.type);
9555 }
9556 keyName = keyToken.value;
9557 this._advance();
9558 this._match(TOK_COLON);
9559 value = this.expression(0);
9560 node = {type: "KeyValuePair", name: keyName, value: value};
9561 pairs.push(node);
9562 if (this._lookahead(0) === TOK_COMMA) {
9563 this._match(TOK_COMMA);
9564 } else if (this._lookahead(0) === TOK_RBRACE) {
9565 this._match(TOK_RBRACE);
9566 break;
9567 }
9568 }
9569 return {type: "MultiSelectHash", children: pairs};
9570 }
9571 };
9572
9573
9574 function TreeInterpreter(runtime) {
9575 this.runtime = runtime;
9576 }
9577
9578 TreeInterpreter.prototype = {
9579 search: function(node, value) {
9580 return this.visit(node, value);
9581 },
9582
9583 visit: function(node, value) {
9584 var matched, current, result, first, second, field, left, right, collected, i;
9585 switch (node.type) {
9586 case "Field":
9587 if (value === null ) {
9588 return null;
9589 } else if (isObject(value)) {
9590 field = value[node.name];
9591 if (field === undefined) {
9592 return null;
9593 } else {
9594 return field;
9595 }
9596 } else {
9597 return null;
9598 }
9599 break;
9600 case "Subexpression":
9601 result = this.visit(node.children[0], value);
9602 for (i = 1; i < node.children.length; i++) {
9603 result = this.visit(node.children[1], result);
9604 if (result === null) {
9605 return null;
9606 }
9607 }
9608 return result;
9609 case "IndexExpression":
9610 left = this.visit(node.children[0], value);
9611 right = this.visit(node.children[1], left);
9612 return right;
9613 case "Index":
9614 if (!isArray(value)) {
9615 return null;
9616 }
9617 var index = node.value;
9618 if (index < 0) {
9619 index = value.length + index;
9620 }
9621 result = value[index];
9622 if (result === undefined) {
9623 result = null;
9624 }
9625 return result;
9626 case "Slice":
9627 if (!isArray(value)) {
9628 return null;
9629 }
9630 var sliceParams = node.children.slice(0);
9631 var computed = this.computeSliceParams(value.length, sliceParams);
9632 var start = computed[0];
9633 var stop = computed[1];
9634 var step = computed[2];
9635 result = [];
9636 if (step > 0) {
9637 for (i = start; i < stop; i += step) {
9638 result.push(value[i]);
9639 }
9640 } else {
9641 for (i = start; i > stop; i += step) {
9642 result.push(value[i]);
9643 }
9644 }
9645 return result;
9646 case "Projection":
9647 // Evaluate left child.
9648 var base = this.visit(node.children[0], value);
9649 if (!isArray(base)) {
9650 return null;
9651 }
9652 collected = [];
9653 for (i = 0; i < base.length; i++) {
9654 current = this.visit(node.children[1], base[i]);
9655 if (current !== null) {
9656 collected.push(current);
9657 }
9658 }
9659 return collected;
9660 case "ValueProjection":
9661 // Evaluate left child.
9662 base = this.visit(node.children[0], value);
9663 if (!isObject(base)) {
9664 return null;
9665 }
9666 collected = [];
9667 var values = objValues(base);
9668 for (i = 0; i < values.length; i++) {
9669 current = this.visit(node.children[1], values[i]);
9670 if (current !== null) {
9671 collected.push(current);
9672 }
9673 }
9674 return collected;
9675 case "FilterProjection":
9676 base = this.visit(node.children[0], value);
9677 if (!isArray(base)) {
9678 return null;
9679 }
9680 var filtered = [];
9681 var finalResults = [];
9682 for (i = 0; i < base.length; i++) {
9683 matched = this.visit(node.children[2], base[i]);
9684 if (!isFalse(matched)) {
9685 filtered.push(base[i]);
9686 }
9687 }
9688 for (var j = 0; j < filtered.length; j++) {
9689 current = this.visit(node.children[1], filtered[j]);
9690 if (current !== null) {
9691 finalResults.push(current);
9692 }
9693 }
9694 return finalResults;
9695 case "Comparator":
9696 first = this.visit(node.children[0], value);
9697 second = this.visit(node.children[1], value);
9698 switch(node.name) {
9699 case TOK_EQ:
9700 result = strictDeepEqual(first, second);
9701 break;
9702 case TOK_NE:
9703 result = !strictDeepEqual(first, second);
9704 break;
9705 case TOK_GT:
9706 result = first > second;
9707 break;
9708 case TOK_GTE:
9709 result = first >= second;
9710 break;
9711 case TOK_LT:
9712 result = first < second;
9713 break;
9714 case TOK_LTE:
9715 result = first <= second;
9716 break;
9717 default:
9718 throw new Error("Unknown comparator: " + node.name);
9719 }
9720 return result;
9721 case TOK_FLATTEN:
9722 var original = this.visit(node.children[0], value);
9723 if (!isArray(original)) {
9724 return null;
9725 }
9726 var merged = [];
9727 for (i = 0; i < original.length; i++) {
9728 current = original[i];
9729 if (isArray(current)) {
9730 merged.push.apply(merged, current);
9731 } else {
9732 merged.push(current);
9733 }
9734 }
9735 return merged;
9736 case "Identity":
9737 return value;
9738 case "MultiSelectList":
9739 if (value === null) {
9740 return null;
9741 }
9742 collected = [];
9743 for (i = 0; i < node.children.length; i++) {
9744 collected.push(this.visit(node.children[i], value));
9745 }
9746 return collected;
9747 case "MultiSelectHash":
9748 if (value === null) {
9749 return null;
9750 }
9751 collected = {};
9752 var child;
9753 for (i = 0; i < node.children.length; i++) {
9754 child = node.children[i];
9755 collected[child.name] = this.visit(child.value, value);
9756 }
9757 return collected;
9758 case "OrExpression":
9759 matched = this.visit(node.children[0], value);
9760 if (isFalse(matched)) {
9761 matched = this.visit(node.children[1], value);
9762 }
9763 return matched;
9764 case "AndExpression":
9765 first = this.visit(node.children[0], value);
9766
9767 if (isFalse(first) === true) {
9768 return first;
9769 }
9770 return this.visit(node.children[1], value);
9771 case "NotExpression":
9772 first = this.visit(node.children[0], value);
9773 return isFalse(first);
9774 case "Literal":
9775 return node.value;
9776 case TOK_PIPE:
9777 left = this.visit(node.children[0], value);
9778 return this.visit(node.children[1], left);
9779 case TOK_CURRENT:
9780 return value;
9781 case "Function":
9782 var resolvedArgs = [];
9783 for (i = 0; i < node.children.length; i++) {
9784 resolvedArgs.push(this.visit(node.children[i], value));
9785 }
9786 return this.runtime.callFunction(node.name, resolvedArgs);
9787 case "ExpressionReference":
9788 var refNode = node.children[0];
9789 // Tag the node with a specific attribute so the type
9790 // checker verify the type.
9791 refNode.jmespathType = TOK_EXPREF;
9792 return refNode;
9793 default:
9794 throw new Error("Unknown node type: " + node.type);
9795 }
9796 },
9797
9798 computeSliceParams: function(arrayLength, sliceParams) {
9799 var start = sliceParams[0];
9800 var stop = sliceParams[1];
9801 var step = sliceParams[2];
9802 var computed = [null, null, null];
9803 if (step === null) {
9804 step = 1;
9805 } else if (step === 0) {
9806 var error = new Error("Invalid slice, step cannot be 0");
9807 error.name = "RuntimeError";
9808 throw error;
9809 }
9810 var stepValueNegative = step < 0 ? true : false;
9811
9812 if (start === null) {
9813 start = stepValueNegative ? arrayLength - 1 : 0;
9814 } else {
9815 start = this.capSliceRange(arrayLength, start, step);
9816 }
9817
9818 if (stop === null) {
9819 stop = stepValueNegative ? -1 : arrayLength;
9820 } else {
9821 stop = this.capSliceRange(arrayLength, stop, step);
9822 }
9823 computed[0] = start;
9824 computed[1] = stop;
9825 computed[2] = step;
9826 return computed;
9827 },
9828
9829 capSliceRange: function(arrayLength, actualValue, step) {
9830 if (actualValue < 0) {
9831 actualValue += arrayLength;
9832 if (actualValue < 0) {
9833 actualValue = step < 0 ? -1 : 0;
9834 }
9835 } else if (actualValue >= arrayLength) {
9836 actualValue = step < 0 ? arrayLength - 1 : arrayLength;
9837 }
9838 return actualValue;
9839 }
9840
9841 };
9842
9843 function Runtime(interpreter) {
9844 this._interpreter = interpreter;
9845 this.functionTable = {
9846 // name: [function, <signature>]
9847 // The <signature> can be:
9848 //
9849 // {
9850 // args: [[type1, type2], [type1, type2]],
9851 // variadic: true|false
9852 // }
9853 //
9854 // Each arg in the arg list is a list of valid types
9855 // (if the function is overloaded and supports multiple
9856 // types. If the type is "any" then no type checking
9857 // occurs on the argument. Variadic is optional
9858 // and if not provided is assumed to be false.
9859 abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]},
9860 avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
9861 ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]},
9862 contains: {
9863 _func: this._functionContains,
9864 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]},
9865 {types: [TYPE_ANY]}]},
9866 "ends_with": {
9867 _func: this._functionEndsWith,
9868 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
9869 floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]},
9870 length: {
9871 _func: this._functionLength,
9872 _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]},
9873 map: {
9874 _func: this._functionMap,
9875 _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]},
9876 max: {
9877 _func: this._functionMax,
9878 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
9879 "merge": {
9880 _func: this._functionMerge,
9881 _signature: [{types: [TYPE_OBJECT], variadic: true}]
9882 },
9883 "max_by": {
9884 _func: this._functionMaxBy,
9885 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9886 },
9887 sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
9888 "starts_with": {
9889 _func: this._functionStartsWith,
9890 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
9891 min: {
9892 _func: this._functionMin,
9893 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
9894 "min_by": {
9895 _func: this._functionMinBy,
9896 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9897 },
9898 type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]},
9899 keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]},
9900 values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]},
9901 sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]},
9902 "sort_by": {
9903 _func: this._functionSortBy,
9904 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9905 },
9906 join: {
9907 _func: this._functionJoin,
9908 _signature: [
9909 {types: [TYPE_STRING]},
9910 {types: [TYPE_ARRAY_STRING]}
9911 ]
9912 },
9913 reverse: {
9914 _func: this._functionReverse,
9915 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]},
9916 "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]},
9917 "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]},
9918 "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]},
9919 "not_null": {
9920 _func: this._functionNotNull,
9921 _signature: [{types: [TYPE_ANY], variadic: true}]
9922 }
9923 };
9924 }
9925
9926 Runtime.prototype = {
9927 callFunction: function(name, resolvedArgs) {
9928 var functionEntry = this.functionTable[name];
9929 if (functionEntry === undefined) {
9930 throw new Error("Unknown function: " + name + "()");
9931 }
9932 this._validateArgs(name, resolvedArgs, functionEntry._signature);
9933 return functionEntry._func.call(this, resolvedArgs);
9934 },
9935
9936 _validateArgs: function(name, args, signature) {
9937 // Validating the args requires validating
9938 // the correct arity and the correct type of each arg.
9939 // If the last argument is declared as variadic, then we need
9940 // a minimum number of args to be required. Otherwise it has to
9941 // be an exact amount.
9942 var pluralized;
9943 if (signature[signature.length - 1].variadic) {
9944 if (args.length < signature.length) {
9945 pluralized = signature.length === 1 ? " argument" : " arguments";
9946 throw new Error("ArgumentError: " + name + "() " +
9947 "takes at least" + signature.length + pluralized +
9948 " but received " + args.length);
9949 }
9950 } else if (args.length !== signature.length) {
9951 pluralized = signature.length === 1 ? " argument" : " arguments";
9952 throw new Error("ArgumentError: " + name + "() " +
9953 "takes " + signature.length + pluralized +
9954 " but received " + args.length);
9955 }
9956 var currentSpec;
9957 var actualType;
9958 var typeMatched;
9959 for (var i = 0; i < signature.length; i++) {
9960 typeMatched = false;
9961 currentSpec = signature[i].types;
9962 actualType = this._getTypeName(args[i]);
9963 for (var j = 0; j < currentSpec.length; j++) {
9964 if (this._typeMatches(actualType, currentSpec[j], args[i])) {
9965 typeMatched = true;
9966 break;
9967 }
9968 }
9969 if (!typeMatched) {
9970 throw new Error("TypeError: " + name + "() " +
9971 "expected argument " + (i + 1) +
9972 " to be type " + currentSpec +
9973 " but received type " + actualType +
9974 " instead.");
9975 }
9976 }
9977 },
9978
9979 _typeMatches: function(actual, expected, argValue) {
9980 if (expected === TYPE_ANY) {
9981 return true;
9982 }
9983 if (expected === TYPE_ARRAY_STRING ||
9984 expected === TYPE_ARRAY_NUMBER ||
9985 expected === TYPE_ARRAY) {
9986 // The expected type can either just be array,
9987 // or it can require a specific subtype (array of numbers).
9988 //
9989 // The simplest case is if "array" with no subtype is specified.
9990 if (expected === TYPE_ARRAY) {
9991 return actual === TYPE_ARRAY;
9992 } else if (actual === TYPE_ARRAY) {
9993 // Otherwise we need to check subtypes.
9994 // I think this has potential to be improved.
9995 var subtype;
9996 if (expected === TYPE_ARRAY_NUMBER) {
9997 subtype = TYPE_NUMBER;
9998 } else if (expected === TYPE_ARRAY_STRING) {
9999 subtype = TYPE_STRING;
10000 }
10001 for (var i = 0; i < argValue.length; i++) {
10002 if (!this._typeMatches(
10003 this._getTypeName(argValue[i]), subtype,
10004 argValue[i])) {
10005 return false;
10006 }
10007 }
10008 return true;
10009 }
10010 } else {
10011 return actual === expected;
10012 }
10013 },
10014 _getTypeName: function(obj) {
10015 switch (Object.prototype.toString.call(obj)) {
10016 case "[object String]":
10017 return TYPE_STRING;
10018 case "[object Number]":
10019 return TYPE_NUMBER;
10020 case "[object Array]":
10021 return TYPE_ARRAY;
10022 case "[object Boolean]":
10023 return TYPE_BOOLEAN;
10024 case "[object Null]":
10025 return TYPE_NULL;
10026 case "[object Object]":
10027 // Check if it's an expref. If it has, it's been
10028 // tagged with a jmespathType attr of 'Expref';
10029 if (obj.jmespathType === TOK_EXPREF) {
10030 return TYPE_EXPREF;
10031 } else {
10032 return TYPE_OBJECT;
10033 }
10034 }
10035 },
10036
10037 _functionStartsWith: function(resolvedArgs) {
10038 return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0;
10039 },
10040
10041 _functionEndsWith: function(resolvedArgs) {
10042 var searchStr = resolvedArgs[0];
10043 var suffix = resolvedArgs[1];
10044 return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1;
10045 },
10046
10047 _functionReverse: function(resolvedArgs) {
10048 var typeName = this._getTypeName(resolvedArgs[0]);
10049 if (typeName === TYPE_STRING) {
10050 var originalStr = resolvedArgs[0];
10051 var reversedStr = "";
10052 for (var i = originalStr.length - 1; i >= 0; i--) {
10053 reversedStr += originalStr[i];
10054 }
10055 return reversedStr;
10056 } else {
10057 var reversedArray = resolvedArgs[0].slice(0);
10058 reversedArray.reverse();
10059 return reversedArray;
10060 }
10061 },
10062
10063 _functionAbs: function(resolvedArgs) {
10064 return Math.abs(resolvedArgs[0]);
10065 },
10066
10067 _functionCeil: function(resolvedArgs) {
10068 return Math.ceil(resolvedArgs[0]);
10069 },
10070
10071 _functionAvg: function(resolvedArgs) {
10072 var sum = 0;
10073 var inputArray = resolvedArgs[0];
10074 for (var i = 0; i < inputArray.length; i++) {
10075 sum += inputArray[i];
10076 }
10077 return sum / inputArray.length;
10078 },
10079
10080 _functionContains: function(resolvedArgs) {
10081 return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0;
10082 },
10083
10084 _functionFloor: function(resolvedArgs) {
10085 return Math.floor(resolvedArgs[0]);
10086 },
10087
10088 _functionLength: function(resolvedArgs) {
10089 if (!isObject(resolvedArgs[0])) {
10090 return resolvedArgs[0].length;
10091 } else {
10092 // As far as I can tell, there's no way to get the length
10093 // of an object without O(n) iteration through the object.
10094 return Object.keys(resolvedArgs[0]).length;
10095 }
10096 },
10097
10098 _functionMap: function(resolvedArgs) {
10099 var mapped = [];
10100 var interpreter = this._interpreter;
10101 var exprefNode = resolvedArgs[0];
10102 var elements = resolvedArgs[1];
10103 for (var i = 0; i < elements.length; i++) {
10104 mapped.push(interpreter.visit(exprefNode, elements[i]));
10105 }
10106 return mapped;
10107 },
10108
10109 _functionMerge: function(resolvedArgs) {
10110 var merged = {};
10111 for (var i = 0; i < resolvedArgs.length; i++) {
10112 var current = resolvedArgs[i];
10113 for (var key in current) {
10114 merged[key] = current[key];
10115 }
10116 }
10117 return merged;
10118 },
10119
10120 _functionMax: function(resolvedArgs) {
10121 if (resolvedArgs[0].length > 0) {
10122 var typeName = this._getTypeName(resolvedArgs[0][0]);
10123 if (typeName === TYPE_NUMBER) {
10124 return Math.max.apply(Math, resolvedArgs[0]);
10125 } else {
10126 var elements = resolvedArgs[0];
10127 var maxElement = elements[0];
10128 for (var i = 1; i < elements.length; i++) {
10129 if (maxElement.localeCompare(elements[i]) < 0) {
10130 maxElement = elements[i];
10131 }
10132 }
10133 return maxElement;
10134 }
10135 } else {
10136 return null;
10137 }
10138 },
10139
10140 _functionMin: function(resolvedArgs) {
10141 if (resolvedArgs[0].length > 0) {
10142 var typeName = this._getTypeName(resolvedArgs[0][0]);
10143 if (typeName === TYPE_NUMBER) {
10144 return Math.min.apply(Math, resolvedArgs[0]);
10145 } else {
10146 var elements = resolvedArgs[0];
10147 var minElement = elements[0];
10148 for (var i = 1; i < elements.length; i++) {
10149 if (elements[i].localeCompare(minElement) < 0) {
10150 minElement = elements[i];
10151 }
10152 }
10153 return minElement;
10154 }
10155 } else {
10156 return null;
10157 }
10158 },
10159
10160 _functionSum: function(resolvedArgs) {
10161 var sum = 0;
10162 var listToSum = resolvedArgs[0];
10163 for (var i = 0; i < listToSum.length; i++) {
10164 sum += listToSum[i];
10165 }
10166 return sum;
10167 },
10168
10169 _functionType: function(resolvedArgs) {
10170 switch (this._getTypeName(resolvedArgs[0])) {
10171 case TYPE_NUMBER:
10172 return "number";
10173 case TYPE_STRING:
10174 return "string";
10175 case TYPE_ARRAY:
10176 return "array";
10177 case TYPE_OBJECT:
10178 return "object";
10179 case TYPE_BOOLEAN:
10180 return "boolean";
10181 case TYPE_EXPREF:
10182 return "expref";
10183 case TYPE_NULL:
10184 return "null";
10185 }
10186 },
10187
10188 _functionKeys: function(resolvedArgs) {
10189 return Object.keys(resolvedArgs[0]);
10190 },
10191
10192 _functionValues: function(resolvedArgs) {
10193 var obj = resolvedArgs[0];
10194 var keys = Object.keys(obj);
10195 var values = [];
10196 for (var i = 0; i < keys.length; i++) {
10197 values.push(obj[keys[i]]);
10198 }
10199 return values;
10200 },
10201
10202 _functionJoin: function(resolvedArgs) {
10203 var joinChar = resolvedArgs[0];
10204 var listJoin = resolvedArgs[1];
10205 return listJoin.join(joinChar);
10206 },
10207
10208 _functionToArray: function(resolvedArgs) {
10209 if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) {
10210 return resolvedArgs[0];
10211 } else {
10212 return [resolvedArgs[0]];
10213 }
10214 },
10215
10216 _functionToString: function(resolvedArgs) {
10217 if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) {
10218 return resolvedArgs[0];
10219 } else {
10220 return JSON.stringify(resolvedArgs[0]);
10221 }
10222 },
10223
10224 _functionToNumber: function(resolvedArgs) {
10225 var typeName = this._getTypeName(resolvedArgs[0]);
10226 var convertedValue;
10227 if (typeName === TYPE_NUMBER) {
10228 return resolvedArgs[0];
10229 } else if (typeName === TYPE_STRING) {
10230 convertedValue = +resolvedArgs[0];
10231 if (!isNaN(convertedValue)) {
10232 return convertedValue;
10233 }
10234 }
10235 return null;
10236 },
10237
10238 _functionNotNull: function(resolvedArgs) {
10239 for (var i = 0; i < resolvedArgs.length; i++) {
10240 if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) {
10241 return resolvedArgs[i];
10242 }
10243 }
10244 return null;
10245 },
10246
10247 _functionSort: function(resolvedArgs) {
10248 var sortedArray = resolvedArgs[0].slice(0);
10249 sortedArray.sort();
10250 return sortedArray;
10251 },
10252
10253 _functionSortBy: function(resolvedArgs) {
10254 var sortedArray = resolvedArgs[0].slice(0);
10255 if (sortedArray.length === 0) {
10256 return sortedArray;
10257 }
10258 var interpreter = this._interpreter;
10259 var exprefNode = resolvedArgs[1];
10260 var requiredType = this._getTypeName(
10261 interpreter.visit(exprefNode, sortedArray[0]));
10262 if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) {
10263 throw new Error("TypeError");
10264 }
10265 var that = this;
10266 // In order to get a stable sort out of an unstable
10267 // sort algorithm, we decorate/sort/undecorate (DSU)
10268 // by creating a new list of [index, element] pairs.
10269 // In the cmp function, if the evaluated elements are
10270 // equal, then the index will be used as the tiebreaker.
10271 // After the decorated list has been sorted, it will be
10272 // undecorated to extract the original elements.
10273 var decorated = [];
10274 for (var i = 0; i < sortedArray.length; i++) {
10275 decorated.push([i, sortedArray[i]]);
10276 }
10277 decorated.sort(function(a, b) {
10278 var exprA = interpreter.visit(exprefNode, a[1]);
10279 var exprB = interpreter.visit(exprefNode, b[1]);
10280 if (that._getTypeName(exprA) !== requiredType) {
10281 throw new Error(
10282 "TypeError: expected " + requiredType + ", received " +
10283 that._getTypeName(exprA));
10284 } else if (that._getTypeName(exprB) !== requiredType) {
10285 throw new Error(
10286 "TypeError: expected " + requiredType + ", received " +
10287 that._getTypeName(exprB));
10288 }
10289 if (exprA > exprB) {
10290 return 1;
10291 } else if (exprA < exprB) {
10292 return -1;
10293 } else {
10294 // If they're equal compare the items by their
10295 // order to maintain relative order of equal keys
10296 // (i.e. to get a stable sort).
10297 return a[0] - b[0];
10298 }
10299 });
10300 // Undecorate: extract out the original list elements.
10301 for (var j = 0; j < decorated.length; j++) {
10302 sortedArray[j] = decorated[j][1];
10303 }
10304 return sortedArray;
10305 },
10306
10307 _functionMaxBy: function(resolvedArgs) {
10308 var exprefNode = resolvedArgs[1];
10309 var resolvedArray = resolvedArgs[0];
10310 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10311 var maxNumber = -Infinity;
10312 var maxRecord;
10313 var current;
10314 for (var i = 0; i < resolvedArray.length; i++) {
10315 current = keyFunction(resolvedArray[i]);
10316 if (current > maxNumber) {
10317 maxNumber = current;
10318 maxRecord = resolvedArray[i];
10319 }
10320 }
10321 return maxRecord;
10322 },
10323
10324 _functionMinBy: function(resolvedArgs) {
10325 var exprefNode = resolvedArgs[1];
10326 var resolvedArray = resolvedArgs[0];
10327 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10328 var minNumber = Infinity;
10329 var minRecord;
10330 var current;
10331 for (var i = 0; i < resolvedArray.length; i++) {
10332 current = keyFunction(resolvedArray[i]);
10333 if (current < minNumber) {
10334 minNumber = current;
10335 minRecord = resolvedArray[i];
10336 }
10337 }
10338 return minRecord;
10339 },
10340
10341 createKeyFunction: function(exprefNode, allowedTypes) {
10342 var that = this;
10343 var interpreter = this._interpreter;
10344 var keyFunc = function(x) {
10345 var current = interpreter.visit(exprefNode, x);
10346 if (allowedTypes.indexOf(that._getTypeName(current)) < 0) {
10347 var msg = "TypeError: expected one of " + allowedTypes +
10348 ", received " + that._getTypeName(current);
10349 throw new Error(msg);
10350 }
10351 return current;
10352 };
10353 return keyFunc;
10354 }
10355
10356 };
10357
10358 function compile(stream) {
10359 var parser = new Parser();
10360 var ast = parser.parse(stream);
10361 return ast;
10362 }
10363
10364 function tokenize(stream) {
10365 var lexer = new Lexer();
10366 return lexer.tokenize(stream);
10367 }
10368
10369 function search(data, expression) {
10370 var parser = new Parser();
10371 // This needs to be improved. Both the interpreter and runtime depend on
10372 // each other. The runtime needs the interpreter to support exprefs.
10373 // There's likely a clean way to avoid the cyclic dependency.
10374 var runtime = new Runtime();
10375 var interpreter = new TreeInterpreter(runtime);
10376 runtime._interpreter = interpreter;
10377 var node = parser.parse(expression);
10378 return interpreter.search(node, data);
10379 }
10380
10381 exports.tokenize = tokenize;
10382 exports.compile = compile;
10383 exports.search = search;
10384 exports.strictDeepEqual = strictDeepEqual;
10385 })( false ? this.jmespath = {} : exports);
10386
10387
10388/***/ }),
10389/* 52 */
10390/***/ (function(module, exports, __webpack_require__) {
10391
10392 var AWS = __webpack_require__(1);
10393 var inherit = AWS.util.inherit;
10394 var jmespath = __webpack_require__(51);
10395
10396 /**
10397 * This class encapsulates the response information
10398 * from a service request operation sent through {AWS.Request}.
10399 * The response object has two main properties for getting information
10400 * back from a request:
10401 *
10402 * ## The `data` property
10403 *
10404 * The `response.data` property contains the serialized object data
10405 * retrieved from the service request. For instance, for an
10406 * Amazon DynamoDB `listTables` method call, the response data might
10407 * look like:
10408 *
10409 * ```
10410 * > resp.data
10411 * { TableNames:
10412 * [ 'table1', 'table2', ... ] }
10413 * ```
10414 *
10415 * The `data` property can be null if an error occurs (see below).
10416 *
10417 * ## The `error` property
10418 *
10419 * In the event of a service error (or transfer error), the
10420 * `response.error` property will be filled with the given
10421 * error data in the form:
10422 *
10423 * ```
10424 * { code: 'SHORT_UNIQUE_ERROR_CODE',
10425 * message: 'Some human readable error message' }
10426 * ```
10427 *
10428 * In the case of an error, the `data` property will be `null`.
10429 * Note that if you handle events that can be in a failure state,
10430 * you should always check whether `response.error` is set
10431 * before attempting to access the `response.data` property.
10432 *
10433 * @!attribute data
10434 * @readonly
10435 * @!group Data Properties
10436 * @note Inside of a {AWS.Request~httpData} event, this
10437 * property contains a single raw packet instead of the
10438 * full de-serialized service response.
10439 * @return [Object] the de-serialized response data
10440 * from the service.
10441 *
10442 * @!attribute error
10443 * An structure containing information about a service
10444 * or networking error.
10445 * @readonly
10446 * @!group Data Properties
10447 * @note This attribute is only filled if a service or
10448 * networking error occurs.
10449 * @return [Error]
10450 * * code [String] a unique short code representing the
10451 * error that was emitted.
10452 * * message [String] a longer human readable error message
10453 * * retryable [Boolean] whether the error message is
10454 * retryable.
10455 * * statusCode [Numeric] in the case of a request that reached the service,
10456 * this value contains the response status code.
10457 * * time [Date] the date time object when the error occurred.
10458 * * hostname [String] set when a networking error occurs to easily
10459 * identify the endpoint of the request.
10460 * * region [String] set when a networking error occurs to easily
10461 * identify the region of the request.
10462 *
10463 * @!attribute requestId
10464 * @readonly
10465 * @!group Data Properties
10466 * @return [String] the unique request ID associated with the response.
10467 * Log this value when debugging requests for AWS support.
10468 *
10469 * @!attribute retryCount
10470 * @readonly
10471 * @!group Operation Properties
10472 * @return [Integer] the number of retries that were
10473 * attempted before the request was completed.
10474 *
10475 * @!attribute redirectCount
10476 * @readonly
10477 * @!group Operation Properties
10478 * @return [Integer] the number of redirects that were
10479 * followed before the request was completed.
10480 *
10481 * @!attribute httpResponse
10482 * @readonly
10483 * @!group HTTP Properties
10484 * @return [AWS.HttpResponse] the raw HTTP response object
10485 * containing the response headers and body information
10486 * from the server.
10487 *
10488 * @see AWS.Request
10489 */
10490 AWS.Response = inherit({
10491
10492 /**
10493 * @api private
10494 */
10495 constructor: function Response(request) {
10496 this.request = request;
10497 this.data = null;
10498 this.error = null;
10499 this.retryCount = 0;
10500 this.redirectCount = 0;
10501 this.httpResponse = new AWS.HttpResponse();
10502 if (request) {
10503 this.maxRetries = request.service.numRetries();
10504 this.maxRedirects = request.service.config.maxRedirects;
10505 }
10506 },
10507
10508 /**
10509 * Creates a new request for the next page of response data, calling the
10510 * callback with the page data if a callback is provided.
10511 *
10512 * @callback callback function(err, data)
10513 * Called when a page of data is returned from the next request.
10514 *
10515 * @param err [Error] an error object, if an error occurred in the request
10516 * @param data [Object] the next page of data, or null, if there are no
10517 * more pages left.
10518 * @return [AWS.Request] the request object for the next page of data
10519 * @return [null] if no callback is provided and there are no pages left
10520 * to retrieve.
10521 * @since v1.4.0
10522 */
10523 nextPage: function nextPage(callback) {
10524 var config;
10525 var service = this.request.service;
10526 var operation = this.request.operation;
10527 try {
10528 config = service.paginationConfig(operation, true);
10529 } catch (e) { this.error = e; }
10530
10531 if (!this.hasNextPage()) {
10532 if (callback) callback(this.error, null);
10533 else if (this.error) throw this.error;
10534 return null;
10535 }
10536
10537 var params = AWS.util.copy(this.request.params);
10538 if (!this.nextPageTokens) {
10539 return callback ? callback(null, null) : null;
10540 } else {
10541 var inputTokens = config.inputToken;
10542 if (typeof inputTokens === 'string') inputTokens = [inputTokens];
10543 for (var i = 0; i < inputTokens.length; i++) {
10544 params[inputTokens[i]] = this.nextPageTokens[i];
10545 }
10546 return service.makeRequest(this.request.operation, params, callback);
10547 }
10548 },
10549
10550 /**
10551 * @return [Boolean] whether more pages of data can be returned by further
10552 * requests
10553 * @since v1.4.0
10554 */
10555 hasNextPage: function hasNextPage() {
10556 this.cacheNextPageTokens();
10557 if (this.nextPageTokens) return true;
10558 if (this.nextPageTokens === undefined) return undefined;
10559 else return false;
10560 },
10561
10562 /**
10563 * @api private
10564 */
10565 cacheNextPageTokens: function cacheNextPageTokens() {
10566 if (Object.prototype.hasOwnProperty.call(this, 'nextPageTokens')) return this.nextPageTokens;
10567 this.nextPageTokens = undefined;
10568
10569 var config = this.request.service.paginationConfig(this.request.operation);
10570 if (!config) return this.nextPageTokens;
10571
10572 this.nextPageTokens = null;
10573 if (config.moreResults) {
10574 if (!jmespath.search(this.data, config.moreResults)) {
10575 return this.nextPageTokens;
10576 }
10577 }
10578
10579 var exprs = config.outputToken;
10580 if (typeof exprs === 'string') exprs = [exprs];
10581 AWS.util.arrayEach.call(this, exprs, function (expr) {
10582 var output = jmespath.search(this.data, expr);
10583 if (output) {
10584 this.nextPageTokens = this.nextPageTokens || [];
10585 this.nextPageTokens.push(output);
10586 }
10587 });
10588
10589 return this.nextPageTokens;
10590 }
10591
10592 });
10593
10594
10595/***/ }),
10596/* 53 */
10597/***/ (function(module, exports, __webpack_require__) {
10598
10599 /**
10600 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
10601 *
10602 * Licensed under the Apache License, Version 2.0 (the "License"). You
10603 * may not use this file except in compliance with the License. A copy of
10604 * the License is located at
10605 *
10606 * http://aws.amazon.com/apache2.0/
10607 *
10608 * or in the "license" file accompanying this file. This file is
10609 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
10610 * ANY KIND, either express or implied. See the License for the specific
10611 * language governing permissions and limitations under the License.
10612 */
10613
10614 var AWS = __webpack_require__(1);
10615 var inherit = AWS.util.inherit;
10616 var jmespath = __webpack_require__(51);
10617
10618 /**
10619 * @api private
10620 */
10621 function CHECK_ACCEPTORS(resp) {
10622 var waiter = resp.request._waiter;
10623 var acceptors = waiter.config.acceptors;
10624 var acceptorMatched = false;
10625 var state = 'retry';
10626
10627 acceptors.forEach(function(acceptor) {
10628 if (!acceptorMatched) {
10629 var matcher = waiter.matchers[acceptor.matcher];
10630 if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) {
10631 acceptorMatched = true;
10632 state = acceptor.state;
10633 }
10634 }
10635 });
10636
10637 if (!acceptorMatched && resp.error) state = 'failure';
10638
10639 if (state === 'success') {
10640 waiter.setSuccess(resp);
10641 } else {
10642 waiter.setError(resp, state === 'retry');
10643 }
10644 }
10645
10646 /**
10647 * @api private
10648 */
10649 AWS.ResourceWaiter = inherit({
10650 /**
10651 * Waits for a given state on a service object
10652 * @param service [Service] the service object to wait on
10653 * @param state [String] the state (defined in waiter configuration) to wait
10654 * for.
10655 * @example Create a waiter for running EC2 instances
10656 * var ec2 = new AWS.EC2;
10657 * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
10658 */
10659 constructor: function constructor(service, state) {
10660 this.service = service;
10661 this.state = state;
10662 this.loadWaiterConfig(this.state);
10663 },
10664
10665 service: null,
10666
10667 state: null,
10668
10669 config: null,
10670
10671 matchers: {
10672 path: function(resp, expected, argument) {
10673 try {
10674 var result = jmespath.search(resp.data, argument);
10675 } catch (err) {
10676 return false;
10677 }
10678
10679 return jmespath.strictDeepEqual(result,expected);
10680 },
10681
10682 pathAll: function(resp, expected, argument) {
10683 try {
10684 var results = jmespath.search(resp.data, argument);
10685 } catch (err) {
10686 return false;
10687 }
10688
10689 if (!Array.isArray(results)) results = [results];
10690 var numResults = results.length;
10691 if (!numResults) return false;
10692 for (var ind = 0 ; ind < numResults; ind++) {
10693 if (!jmespath.strictDeepEqual(results[ind], expected)) {
10694 return false;
10695 }
10696 }
10697 return true;
10698 },
10699
10700 pathAny: function(resp, expected, argument) {
10701 try {
10702 var results = jmespath.search(resp.data, argument);
10703 } catch (err) {
10704 return false;
10705 }
10706
10707 if (!Array.isArray(results)) results = [results];
10708 var numResults = results.length;
10709 for (var ind = 0 ; ind < numResults; ind++) {
10710 if (jmespath.strictDeepEqual(results[ind], expected)) {
10711 return true;
10712 }
10713 }
10714 return false;
10715 },
10716
10717 status: function(resp, expected) {
10718 var statusCode = resp.httpResponse.statusCode;
10719 return (typeof statusCode === 'number') && (statusCode === expected);
10720 },
10721
10722 error: function(resp, expected) {
10723 if (typeof expected === 'string' && resp.error) {
10724 return expected === resp.error.code;
10725 }
10726 // if expected is not string, can be boolean indicating presence of error
10727 return expected === !!resp.error;
10728 }
10729 },
10730
10731 listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) {
10732 add('RETRY_CHECK', 'retry', function(resp) {
10733 var waiter = resp.request._waiter;
10734 if (resp.error && resp.error.code === 'ResourceNotReady') {
10735 resp.error.retryDelay = (waiter.config.delay || 0) * 1000;
10736 }
10737 });
10738
10739 add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS);
10740
10741 add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS);
10742 }),
10743
10744 /**
10745 * @return [AWS.Request]
10746 */
10747 wait: function wait(params, callback) {
10748 if (typeof params === 'function') {
10749 callback = params; params = undefined;
10750 }
10751
10752 if (params && params.$waiter) {
10753 params = AWS.util.copy(params);
10754 if (typeof params.$waiter.delay === 'number') {
10755 this.config.delay = params.$waiter.delay;
10756 }
10757 if (typeof params.$waiter.maxAttempts === 'number') {
10758 this.config.maxAttempts = params.$waiter.maxAttempts;
10759 }
10760 delete params.$waiter;
10761 }
10762
10763 var request = this.service.makeRequest(this.config.operation, params);
10764 request._waiter = this;
10765 request.response.maxRetries = this.config.maxAttempts;
10766 request.addListeners(this.listeners);
10767
10768 if (callback) request.send(callback);
10769 return request;
10770 },
10771
10772 setSuccess: function setSuccess(resp) {
10773 resp.error = null;
10774 resp.data = resp.data || {};
10775 resp.request.removeAllListeners('extractData');
10776 },
10777
10778 setError: function setError(resp, retryable) {
10779 resp.data = null;
10780 resp.error = AWS.util.error(resp.error || new Error(), {
10781 code: 'ResourceNotReady',
10782 message: 'Resource is not in the state ' + this.state,
10783 retryable: retryable
10784 });
10785 },
10786
10787 /**
10788 * Loads waiter configuration from API configuration
10789 *
10790 * @api private
10791 */
10792 loadWaiterConfig: function loadWaiterConfig(state) {
10793 if (!this.service.api.waiters[state]) {
10794 throw new AWS.util.error(new Error(), {
10795 code: 'StateNotFoundError',
10796 message: 'State ' + state + ' not found.'
10797 });
10798 }
10799
10800 this.config = AWS.util.copy(this.service.api.waiters[state]);
10801 }
10802 });
10803
10804
10805/***/ }),
10806/* 54 */
10807/***/ (function(module, exports, __webpack_require__) {
10808
10809 var AWS = __webpack_require__(1);
10810
10811 var inherit = AWS.util.inherit;
10812
10813 /**
10814 * @api private
10815 */
10816 AWS.Signers.RequestSigner = inherit({
10817 constructor: function RequestSigner(request) {
10818 this.request = request;
10819 },
10820
10821 setServiceClientId: function setServiceClientId(id) {
10822 this.serviceClientId = id;
10823 },
10824
10825 getServiceClientId: function getServiceClientId() {
10826 return this.serviceClientId;
10827 }
10828 });
10829
10830 AWS.Signers.RequestSigner.getVersion = function getVersion(version) {
10831 switch (version) {
10832 case 'v2': return AWS.Signers.V2;
10833 case 'v3': return AWS.Signers.V3;
10834 case 's3v4': return AWS.Signers.V4;
10835 case 'v4': return AWS.Signers.V4;
10836 case 's3': return AWS.Signers.S3;
10837 case 'v3https': return AWS.Signers.V3Https;
10838 }
10839 throw new Error('Unknown signing version ' + version);
10840 };
10841
10842 __webpack_require__(55);
10843 __webpack_require__(56);
10844 __webpack_require__(57);
10845 __webpack_require__(58);
10846 __webpack_require__(60);
10847 __webpack_require__(61);
10848
10849
10850/***/ }),
10851/* 55 */
10852/***/ (function(module, exports, __webpack_require__) {
10853
10854 var AWS = __webpack_require__(1);
10855 var inherit = AWS.util.inherit;
10856
10857 /**
10858 * @api private
10859 */
10860 AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, {
10861 addAuthorization: function addAuthorization(credentials, date) {
10862
10863 if (!date) date = AWS.util.date.getDate();
10864
10865 var r = this.request;
10866
10867 r.params.Timestamp = AWS.util.date.iso8601(date);
10868 r.params.SignatureVersion = '2';
10869 r.params.SignatureMethod = 'HmacSHA256';
10870 r.params.AWSAccessKeyId = credentials.accessKeyId;
10871
10872 if (credentials.sessionToken) {
10873 r.params.SecurityToken = credentials.sessionToken;
10874 }
10875
10876 delete r.params.Signature; // delete old Signature for re-signing
10877 r.params.Signature = this.signature(credentials);
10878
10879 r.body = AWS.util.queryParamsToString(r.params);
10880 r.headers['Content-Length'] = r.body.length;
10881 },
10882
10883 signature: function signature(credentials) {
10884 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
10885 },
10886
10887 stringToSign: function stringToSign() {
10888 var parts = [];
10889 parts.push(this.request.method);
10890 parts.push(this.request.endpoint.host.toLowerCase());
10891 parts.push(this.request.pathname());
10892 parts.push(AWS.util.queryParamsToString(this.request.params));
10893 return parts.join('\n');
10894 }
10895
10896 });
10897
10898 /**
10899 * @api private
10900 */
10901 module.exports = AWS.Signers.V2;
10902
10903
10904/***/ }),
10905/* 56 */
10906/***/ (function(module, exports, __webpack_require__) {
10907
10908 var AWS = __webpack_require__(1);
10909 var inherit = AWS.util.inherit;
10910
10911 /**
10912 * @api private
10913 */
10914 AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, {
10915 addAuthorization: function addAuthorization(credentials, date) {
10916
10917 var datetime = AWS.util.date.rfc822(date);
10918
10919 this.request.headers['X-Amz-Date'] = datetime;
10920
10921 if (credentials.sessionToken) {
10922 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
10923 }
10924
10925 this.request.headers['X-Amzn-Authorization'] =
10926 this.authorization(credentials, datetime);
10927
10928 },
10929
10930 authorization: function authorization(credentials) {
10931 return 'AWS3 ' +
10932 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
10933 'Algorithm=HmacSHA256,' +
10934 'SignedHeaders=' + this.signedHeaders() + ',' +
10935 'Signature=' + this.signature(credentials);
10936 },
10937
10938 signedHeaders: function signedHeaders() {
10939 var headers = [];
10940 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
10941 headers.push(h.toLowerCase());
10942 });
10943 return headers.sort().join(';');
10944 },
10945
10946 canonicalHeaders: function canonicalHeaders() {
10947 var headers = this.request.headers;
10948 var parts = [];
10949 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
10950 parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim());
10951 });
10952 return parts.sort().join('\n') + '\n';
10953 },
10954
10955 headersToSign: function headersToSign() {
10956 var headers = [];
10957 AWS.util.each(this.request.headers, function iterator(k) {
10958 if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) {
10959 headers.push(k);
10960 }
10961 });
10962 return headers;
10963 },
10964
10965 signature: function signature(credentials) {
10966 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
10967 },
10968
10969 stringToSign: function stringToSign() {
10970 var parts = [];
10971 parts.push(this.request.method);
10972 parts.push('/');
10973 parts.push('');
10974 parts.push(this.canonicalHeaders());
10975 parts.push(this.request.body);
10976 return AWS.util.crypto.sha256(parts.join('\n'));
10977 }
10978
10979 });
10980
10981 /**
10982 * @api private
10983 */
10984 module.exports = AWS.Signers.V3;
10985
10986
10987/***/ }),
10988/* 57 */
10989/***/ (function(module, exports, __webpack_require__) {
10990
10991 var AWS = __webpack_require__(1);
10992 var inherit = AWS.util.inherit;
10993
10994 __webpack_require__(56);
10995
10996 /**
10997 * @api private
10998 */
10999 AWS.Signers.V3Https = inherit(AWS.Signers.V3, {
11000 authorization: function authorization(credentials) {
11001 return 'AWS3-HTTPS ' +
11002 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
11003 'Algorithm=HmacSHA256,' +
11004 'Signature=' + this.signature(credentials);
11005 },
11006
11007 stringToSign: function stringToSign() {
11008 return this.request.headers['X-Amz-Date'];
11009 }
11010 });
11011
11012 /**
11013 * @api private
11014 */
11015 module.exports = AWS.Signers.V3Https;
11016
11017
11018/***/ }),
11019/* 58 */
11020/***/ (function(module, exports, __webpack_require__) {
11021
11022 var AWS = __webpack_require__(1);
11023 var v4Credentials = __webpack_require__(59);
11024 var inherit = AWS.util.inherit;
11025
11026 /**
11027 * @api private
11028 */
11029 var expiresHeader = 'presigned-expires';
11030
11031 /**
11032 * @api private
11033 */
11034 AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, {
11035 constructor: function V4(request, serviceName, options) {
11036 AWS.Signers.RequestSigner.call(this, request);
11037 this.serviceName = serviceName;
11038 options = options || {};
11039 this.signatureCache = typeof options.signatureCache === 'boolean' ? options.signatureCache : true;
11040 this.operation = options.operation;
11041 this.signatureVersion = options.signatureVersion;
11042 },
11043
11044 algorithm: 'AWS4-HMAC-SHA256',
11045
11046 addAuthorization: function addAuthorization(credentials, date) {
11047 var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '');
11048
11049 if (this.isPresigned()) {
11050 this.updateForPresigned(credentials, datetime);
11051 } else {
11052 this.addHeaders(credentials, datetime);
11053 }
11054
11055 this.request.headers['Authorization'] =
11056 this.authorization(credentials, datetime);
11057 },
11058
11059 addHeaders: function addHeaders(credentials, datetime) {
11060 this.request.headers['X-Amz-Date'] = datetime;
11061 if (credentials.sessionToken) {
11062 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11063 }
11064 },
11065
11066 updateForPresigned: function updateForPresigned(credentials, datetime) {
11067 var credString = this.credentialString(datetime);
11068 var qs = {
11069 'X-Amz-Date': datetime,
11070 'X-Amz-Algorithm': this.algorithm,
11071 'X-Amz-Credential': credentials.accessKeyId + '/' + credString,
11072 'X-Amz-Expires': this.request.headers[expiresHeader],
11073 'X-Amz-SignedHeaders': this.signedHeaders()
11074 };
11075
11076 if (credentials.sessionToken) {
11077 qs['X-Amz-Security-Token'] = credentials.sessionToken;
11078 }
11079
11080 if (this.request.headers['Content-Type']) {
11081 qs['Content-Type'] = this.request.headers['Content-Type'];
11082 }
11083 if (this.request.headers['Content-MD5']) {
11084 qs['Content-MD5'] = this.request.headers['Content-MD5'];
11085 }
11086 if (this.request.headers['Cache-Control']) {
11087 qs['Cache-Control'] = this.request.headers['Cache-Control'];
11088 }
11089
11090 // need to pull in any other X-Amz-* headers
11091 AWS.util.each.call(this, this.request.headers, function(key, value) {
11092 if (key === expiresHeader) return;
11093 if (this.isSignableHeader(key)) {
11094 var lowerKey = key.toLowerCase();
11095 // Metadata should be normalized
11096 if (lowerKey.indexOf('x-amz-meta-') === 0) {
11097 qs[lowerKey] = value;
11098 } else if (lowerKey.indexOf('x-amz-') === 0) {
11099 qs[key] = value;
11100 }
11101 }
11102 });
11103
11104 var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?';
11105 this.request.path += sep + AWS.util.queryParamsToString(qs);
11106 },
11107
11108 authorization: function authorization(credentials, datetime) {
11109 var parts = [];
11110 var credString = this.credentialString(datetime);
11111 parts.push(this.algorithm + ' Credential=' +
11112 credentials.accessKeyId + '/' + credString);
11113 parts.push('SignedHeaders=' + this.signedHeaders());
11114 parts.push('Signature=' + this.signature(credentials, datetime));
11115 return parts.join(', ');
11116 },
11117
11118 signature: function signature(credentials, datetime) {
11119 var signingKey = v4Credentials.getSigningKey(
11120 credentials,
11121 datetime.substr(0, 8),
11122 this.request.region,
11123 this.serviceName,
11124 this.signatureCache
11125 );
11126 return AWS.util.crypto.hmac(signingKey, this.stringToSign(datetime), 'hex');
11127 },
11128
11129 stringToSign: function stringToSign(datetime) {
11130 var parts = [];
11131 parts.push('AWS4-HMAC-SHA256');
11132 parts.push(datetime);
11133 parts.push(this.credentialString(datetime));
11134 parts.push(this.hexEncodedHash(this.canonicalString()));
11135 return parts.join('\n');
11136 },
11137
11138 canonicalString: function canonicalString() {
11139 var parts = [], pathname = this.request.pathname();
11140 if (this.serviceName !== 's3' && this.signatureVersion !== 's3v4') pathname = AWS.util.uriEscapePath(pathname);
11141
11142 parts.push(this.request.method);
11143 parts.push(pathname);
11144 parts.push(this.request.search());
11145 parts.push(this.canonicalHeaders() + '\n');
11146 parts.push(this.signedHeaders());
11147 parts.push(this.hexEncodedBodyHash());
11148 return parts.join('\n');
11149 },
11150
11151 canonicalHeaders: function canonicalHeaders() {
11152 var headers = [];
11153 AWS.util.each.call(this, this.request.headers, function (key, item) {
11154 headers.push([key, item]);
11155 });
11156 headers.sort(function (a, b) {
11157 return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
11158 });
11159 var parts = [];
11160 AWS.util.arrayEach.call(this, headers, function (item) {
11161 var key = item[0].toLowerCase();
11162 if (this.isSignableHeader(key)) {
11163 var value = item[1];
11164 if (typeof value === 'undefined' || value === null || typeof value.toString !== 'function') {
11165 throw AWS.util.error(new Error('Header ' + key + ' contains invalid value'), {
11166 code: 'InvalidHeader'
11167 });
11168 }
11169 parts.push(key + ':' +
11170 this.canonicalHeaderValues(value.toString()));
11171 }
11172 });
11173 return parts.join('\n');
11174 },
11175
11176 canonicalHeaderValues: function canonicalHeaderValues(values) {
11177 return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
11178 },
11179
11180 signedHeaders: function signedHeaders() {
11181 var keys = [];
11182 AWS.util.each.call(this, this.request.headers, function (key) {
11183 key = key.toLowerCase();
11184 if (this.isSignableHeader(key)) keys.push(key);
11185 });
11186 return keys.sort().join(';');
11187 },
11188
11189 credentialString: function credentialString(datetime) {
11190 return v4Credentials.createScope(
11191 datetime.substr(0, 8),
11192 this.request.region,
11193 this.serviceName
11194 );
11195 },
11196
11197 hexEncodedHash: function hash(string) {
11198 return AWS.util.crypto.sha256(string, 'hex');
11199 },
11200
11201 hexEncodedBodyHash: function hexEncodedBodyHash() {
11202 var request = this.request;
11203 if (this.isPresigned() && this.serviceName === 's3' && !request.body) {
11204 return 'UNSIGNED-PAYLOAD';
11205 } else if (request.headers['X-Amz-Content-Sha256']) {
11206 return request.headers['X-Amz-Content-Sha256'];
11207 } else {
11208 return this.hexEncodedHash(this.request.body || '');
11209 }
11210 },
11211
11212 unsignableHeaders: [
11213 'authorization',
11214 'content-type',
11215 'content-length',
11216 'user-agent',
11217 expiresHeader,
11218 'expect',
11219 'x-amzn-trace-id'
11220 ],
11221
11222 isSignableHeader: function isSignableHeader(key) {
11223 if (key.toLowerCase().indexOf('x-amz-') === 0) return true;
11224 return this.unsignableHeaders.indexOf(key) < 0;
11225 },
11226
11227 isPresigned: function isPresigned() {
11228 return this.request.headers[expiresHeader] ? true : false;
11229 }
11230
11231 });
11232
11233 /**
11234 * @api private
11235 */
11236 module.exports = AWS.Signers.V4;
11237
11238
11239/***/ }),
11240/* 59 */
11241/***/ (function(module, exports, __webpack_require__) {
11242
11243 var AWS = __webpack_require__(1);
11244
11245 /**
11246 * @api private
11247 */
11248 var cachedSecret = {};
11249
11250 /**
11251 * @api private
11252 */
11253 var cacheQueue = [];
11254
11255 /**
11256 * @api private
11257 */
11258 var maxCacheEntries = 50;
11259
11260 /**
11261 * @api private
11262 */
11263 var v4Identifier = 'aws4_request';
11264
11265 /**
11266 * @api private
11267 */
11268 module.exports = {
11269 /**
11270 * @api private
11271 *
11272 * @param date [String]
11273 * @param region [String]
11274 * @param serviceName [String]
11275 * @return [String]
11276 */
11277 createScope: function createScope(date, region, serviceName) {
11278 return [
11279 date.substr(0, 8),
11280 region,
11281 serviceName,
11282 v4Identifier
11283 ].join('/');
11284 },
11285
11286 /**
11287 * @api private
11288 *
11289 * @param credentials [Credentials]
11290 * @param date [String]
11291 * @param region [String]
11292 * @param service [String]
11293 * @param shouldCache [Boolean]
11294 * @return [String]
11295 */
11296 getSigningKey: function getSigningKey(
11297 credentials,
11298 date,
11299 region,
11300 service,
11301 shouldCache
11302 ) {
11303 var credsIdentifier = AWS.util.crypto
11304 .hmac(credentials.secretAccessKey, credentials.accessKeyId, 'base64');
11305 var cacheKey = [credsIdentifier, date, region, service].join('_');
11306 shouldCache = shouldCache !== false;
11307 if (shouldCache && (cacheKey in cachedSecret)) {
11308 return cachedSecret[cacheKey];
11309 }
11310
11311 var kDate = AWS.util.crypto.hmac(
11312 'AWS4' + credentials.secretAccessKey,
11313 date,
11314 'buffer'
11315 );
11316 var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer');
11317 var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer');
11318
11319 var signingKey = AWS.util.crypto.hmac(kService, v4Identifier, 'buffer');
11320 if (shouldCache) {
11321 cachedSecret[cacheKey] = signingKey;
11322 cacheQueue.push(cacheKey);
11323 if (cacheQueue.length > maxCacheEntries) {
11324 // remove the oldest entry (not the least recently used)
11325 delete cachedSecret[cacheQueue.shift()];
11326 }
11327 }
11328
11329 return signingKey;
11330 },
11331
11332 /**
11333 * @api private
11334 *
11335 * Empties the derived signing key cache. Made available for testing purposes
11336 * only.
11337 */
11338 emptyCache: function emptyCache() {
11339 cachedSecret = {};
11340 cacheQueue = [];
11341 }
11342 };
11343
11344
11345/***/ }),
11346/* 60 */
11347/***/ (function(module, exports, __webpack_require__) {
11348
11349 var AWS = __webpack_require__(1);
11350 var inherit = AWS.util.inherit;
11351
11352 /**
11353 * @api private
11354 */
11355 AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, {
11356 /**
11357 * When building the stringToSign, these sub resource params should be
11358 * part of the canonical resource string with their NON-decoded values
11359 */
11360 subResources: {
11361 'acl': 1,
11362 'accelerate': 1,
11363 'analytics': 1,
11364 'cors': 1,
11365 'lifecycle': 1,
11366 'delete': 1,
11367 'inventory': 1,
11368 'location': 1,
11369 'logging': 1,
11370 'metrics': 1,
11371 'notification': 1,
11372 'partNumber': 1,
11373 'policy': 1,
11374 'requestPayment': 1,
11375 'replication': 1,
11376 'restore': 1,
11377 'tagging': 1,
11378 'torrent': 1,
11379 'uploadId': 1,
11380 'uploads': 1,
11381 'versionId': 1,
11382 'versioning': 1,
11383 'versions': 1,
11384 'website': 1
11385 },
11386
11387 // when building the stringToSign, these querystring params should be
11388 // part of the canonical resource string with their NON-encoded values
11389 responseHeaders: {
11390 'response-content-type': 1,
11391 'response-content-language': 1,
11392 'response-expires': 1,
11393 'response-cache-control': 1,
11394 'response-content-disposition': 1,
11395 'response-content-encoding': 1
11396 },
11397
11398 addAuthorization: function addAuthorization(credentials, date) {
11399 if (!this.request.headers['presigned-expires']) {
11400 this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date);
11401 }
11402
11403 if (credentials.sessionToken) {
11404 // presigned URLs require this header to be lowercased
11405 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11406 }
11407
11408 var signature = this.sign(credentials.secretAccessKey, this.stringToSign());
11409 var auth = 'AWS ' + credentials.accessKeyId + ':' + signature;
11410
11411 this.request.headers['Authorization'] = auth;
11412 },
11413
11414 stringToSign: function stringToSign() {
11415 var r = this.request;
11416
11417 var parts = [];
11418 parts.push(r.method);
11419 parts.push(r.headers['Content-MD5'] || '');
11420 parts.push(r.headers['Content-Type'] || '');
11421
11422 // This is the "Date" header, but we use X-Amz-Date.
11423 // The S3 signing mechanism requires us to pass an empty
11424 // string for this Date header regardless.
11425 parts.push(r.headers['presigned-expires'] || '');
11426
11427 var headers = this.canonicalizedAmzHeaders();
11428 if (headers) parts.push(headers);
11429 parts.push(this.canonicalizedResource());
11430
11431 return parts.join('\n');
11432
11433 },
11434
11435 canonicalizedAmzHeaders: function canonicalizedAmzHeaders() {
11436
11437 var amzHeaders = [];
11438
11439 AWS.util.each(this.request.headers, function (name) {
11440 if (name.match(/^x-amz-/i))
11441 amzHeaders.push(name);
11442 });
11443
11444 amzHeaders.sort(function (a, b) {
11445 return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
11446 });
11447
11448 var parts = [];
11449 AWS.util.arrayEach.call(this, amzHeaders, function (name) {
11450 parts.push(name.toLowerCase() + ':' + String(this.request.headers[name]));
11451 });
11452
11453 return parts.join('\n');
11454
11455 },
11456
11457 canonicalizedResource: function canonicalizedResource() {
11458
11459 var r = this.request;
11460
11461 var parts = r.path.split('?');
11462 var path = parts[0];
11463 var querystring = parts[1];
11464
11465 var resource = '';
11466
11467 if (r.virtualHostedBucket)
11468 resource += '/' + r.virtualHostedBucket;
11469
11470 resource += path;
11471
11472 if (querystring) {
11473
11474 // collect a list of sub resources and query params that need to be signed
11475 var resources = [];
11476
11477 AWS.util.arrayEach.call(this, querystring.split('&'), function (param) {
11478 var name = param.split('=')[0];
11479 var value = param.split('=')[1];
11480 if (this.subResources[name] || this.responseHeaders[name]) {
11481 var subresource = { name: name };
11482 if (value !== undefined) {
11483 if (this.subResources[name]) {
11484 subresource.value = value;
11485 } else {
11486 subresource.value = decodeURIComponent(value);
11487 }
11488 }
11489 resources.push(subresource);
11490 }
11491 });
11492
11493 resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; });
11494
11495 if (resources.length) {
11496
11497 querystring = [];
11498 AWS.util.arrayEach(resources, function (res) {
11499 if (res.value === undefined) {
11500 querystring.push(res.name);
11501 } else {
11502 querystring.push(res.name + '=' + res.value);
11503 }
11504 });
11505
11506 resource += '?' + querystring.join('&');
11507 }
11508
11509 }
11510
11511 return resource;
11512
11513 },
11514
11515 sign: function sign(secret, string) {
11516 return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1');
11517 }
11518 });
11519
11520 /**
11521 * @api private
11522 */
11523 module.exports = AWS.Signers.S3;
11524
11525
11526/***/ }),
11527/* 61 */
11528/***/ (function(module, exports, __webpack_require__) {
11529
11530 var AWS = __webpack_require__(1);
11531 var inherit = AWS.util.inherit;
11532
11533 /**
11534 * @api private
11535 */
11536 var expiresHeader = 'presigned-expires';
11537
11538 /**
11539 * @api private
11540 */
11541 function signedUrlBuilder(request) {
11542 var expires = request.httpRequest.headers[expiresHeader];
11543 var signerClass = request.service.getSignerClass(request);
11544
11545 delete request.httpRequest.headers['User-Agent'];
11546 delete request.httpRequest.headers['X-Amz-User-Agent'];
11547
11548 if (signerClass === AWS.Signers.V4) {
11549 if (expires > 604800) { // one week expiry is invalid
11550 var message = 'Presigning does not support expiry time greater ' +
11551 'than a week with SigV4 signing.';
11552 throw AWS.util.error(new Error(), {
11553 code: 'InvalidExpiryTime', message: message, retryable: false
11554 });
11555 }
11556 request.httpRequest.headers[expiresHeader] = expires;
11557 } else if (signerClass === AWS.Signers.S3) {
11558 var now = request.service ? request.service.getSkewCorrectedDate() : AWS.util.date.getDate();
11559 request.httpRequest.headers[expiresHeader] = parseInt(
11560 AWS.util.date.unixTimestamp(now) + expires, 10).toString();
11561 } else {
11562 throw AWS.util.error(new Error(), {
11563 message: 'Presigning only supports S3 or SigV4 signing.',
11564 code: 'UnsupportedSigner', retryable: false
11565 });
11566 }
11567 }
11568
11569 /**
11570 * @api private
11571 */
11572 function signedUrlSigner(request) {
11573 var endpoint = request.httpRequest.endpoint;
11574 var parsedUrl = AWS.util.urlParse(request.httpRequest.path);
11575 var queryParams = {};
11576
11577 if (parsedUrl.search) {
11578 queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1));
11579 }
11580
11581 var auth = request.httpRequest.headers['Authorization'].split(' ');
11582 if (auth[0] === 'AWS') {
11583 auth = auth[1].split(':');
11584 queryParams['AWSAccessKeyId'] = auth[0];
11585 queryParams['Signature'] = auth[1];
11586
11587 AWS.util.each(request.httpRequest.headers, function (key, value) {
11588 if (key === expiresHeader) key = 'Expires';
11589 if (key.indexOf('x-amz-meta-') === 0) {
11590 // Delete existing, potentially not normalized key
11591 delete queryParams[key];
11592 key = key.toLowerCase();
11593 }
11594 queryParams[key] = value;
11595 });
11596 delete request.httpRequest.headers[expiresHeader];
11597 delete queryParams['Authorization'];
11598 delete queryParams['Host'];
11599 } else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing
11600 auth.shift();
11601 var rest = auth.join(' ');
11602 var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];
11603 queryParams['X-Amz-Signature'] = signature;
11604 delete queryParams['Expires'];
11605 }
11606
11607 // build URL
11608 endpoint.pathname = parsedUrl.pathname;
11609 endpoint.search = AWS.util.queryParamsToString(queryParams);
11610 }
11611
11612 /**
11613 * @api private
11614 */
11615 AWS.Signers.Presign = inherit({
11616 /**
11617 * @api private
11618 */
11619 sign: function sign(request, expireTime, callback) {
11620 request.httpRequest.headers[expiresHeader] = expireTime || 3600;
11621 request.on('build', signedUrlBuilder);
11622 request.on('sign', signedUrlSigner);
11623 request.removeListener('afterBuild',
11624 AWS.EventListeners.Core.SET_CONTENT_LENGTH);
11625 request.removeListener('afterBuild',
11626 AWS.EventListeners.Core.COMPUTE_SHA256);
11627
11628 request.emit('beforePresign', [request]);
11629
11630 if (callback) {
11631 request.build(function() {
11632 if (this.response.error) callback(this.response.error);
11633 else {
11634 callback(null, AWS.util.urlFormat(request.httpRequest.endpoint));
11635 }
11636 });
11637 } else {
11638 request.build();
11639 if (request.response.error) throw request.response.error;
11640 return AWS.util.urlFormat(request.httpRequest.endpoint);
11641 }
11642 }
11643 });
11644
11645 /**
11646 * @api private
11647 */
11648 module.exports = AWS.Signers.Presign;
11649
11650
11651/***/ }),
11652/* 62 */
11653/***/ (function(module, exports, __webpack_require__) {
11654
11655 var AWS = __webpack_require__(1);
11656
11657 /**
11658 * @api private
11659 */
11660 AWS.ParamValidator = AWS.util.inherit({
11661 /**
11662 * Create a new validator object.
11663 *
11664 * @param validation [Boolean|map] whether input parameters should be
11665 * validated against the operation description before sending the
11666 * request. Pass a map to enable any of the following specific
11667 * validation features:
11668 *
11669 * * **min** [Boolean] &mdash; Validates that a value meets the min
11670 * constraint. This is enabled by default when paramValidation is set
11671 * to `true`.
11672 * * **max** [Boolean] &mdash; Validates that a value meets the max
11673 * constraint.
11674 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
11675 * regular expression.
11676 * * **enum** [Boolean] &mdash; Validates that a string value matches one
11677 * of the allowable enum values.
11678 */
11679 constructor: function ParamValidator(validation) {
11680 if (validation === true || validation === undefined) {
11681 validation = {'min': true};
11682 }
11683 this.validation = validation;
11684 },
11685
11686 validate: function validate(shape, params, context) {
11687 this.errors = [];
11688 this.validateMember(shape, params || {}, context || 'params');
11689
11690 if (this.errors.length > 1) {
11691 var msg = this.errors.join('\n* ');
11692 msg = 'There were ' + this.errors.length +
11693 ' validation errors:\n* ' + msg;
11694 throw AWS.util.error(new Error(msg),
11695 {code: 'MultipleValidationErrors', errors: this.errors});
11696 } else if (this.errors.length === 1) {
11697 throw this.errors[0];
11698 } else {
11699 return true;
11700 }
11701 },
11702
11703 fail: function fail(code, message) {
11704 this.errors.push(AWS.util.error(new Error(message), {code: code}));
11705 },
11706
11707 validateStructure: function validateStructure(shape, params, context) {
11708 this.validateType(params, context, ['object'], 'structure');
11709
11710 var paramName;
11711 for (var i = 0; shape.required && i < shape.required.length; i++) {
11712 paramName = shape.required[i];
11713 var value = params[paramName];
11714 if (value === undefined || value === null) {
11715 this.fail('MissingRequiredParameter',
11716 'Missing required key \'' + paramName + '\' in ' + context);
11717 }
11718 }
11719
11720 // validate hash members
11721 for (paramName in params) {
11722 if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue;
11723
11724 var paramValue = params[paramName],
11725 memberShape = shape.members[paramName];
11726
11727 if (memberShape !== undefined) {
11728 var memberContext = [context, paramName].join('.');
11729 this.validateMember(memberShape, paramValue, memberContext);
11730 } else {
11731 this.fail('UnexpectedParameter',
11732 'Unexpected key \'' + paramName + '\' found in ' + context);
11733 }
11734 }
11735
11736 return true;
11737 },
11738
11739 validateMember: function validateMember(shape, param, context) {
11740 switch (shape.type) {
11741 case 'structure':
11742 return this.validateStructure(shape, param, context);
11743 case 'list':
11744 return this.validateList(shape, param, context);
11745 case 'map':
11746 return this.validateMap(shape, param, context);
11747 default:
11748 return this.validateScalar(shape, param, context);
11749 }
11750 },
11751
11752 validateList: function validateList(shape, params, context) {
11753 if (this.validateType(params, context, [Array])) {
11754 this.validateRange(shape, params.length, context, 'list member count');
11755 // validate array members
11756 for (var i = 0; i < params.length; i++) {
11757 this.validateMember(shape.member, params[i], context + '[' + i + ']');
11758 }
11759 }
11760 },
11761
11762 validateMap: function validateMap(shape, params, context) {
11763 if (this.validateType(params, context, ['object'], 'map')) {
11764 // Build up a count of map members to validate range traits.
11765 var mapCount = 0;
11766 for (var param in params) {
11767 if (!Object.prototype.hasOwnProperty.call(params, param)) continue;
11768 // Validate any map key trait constraints
11769 this.validateMember(shape.key, param,
11770 context + '[key=\'' + param + '\']');
11771 this.validateMember(shape.value, params[param],
11772 context + '[\'' + param + '\']');
11773 mapCount++;
11774 }
11775 this.validateRange(shape, mapCount, context, 'map member count');
11776 }
11777 },
11778
11779 validateScalar: function validateScalar(shape, value, context) {
11780 switch (shape.type) {
11781 case null:
11782 case undefined:
11783 case 'string':
11784 return this.validateString(shape, value, context);
11785 case 'base64':
11786 case 'binary':
11787 return this.validatePayload(value, context);
11788 case 'integer':
11789 case 'float':
11790 return this.validateNumber(shape, value, context);
11791 case 'boolean':
11792 return this.validateType(value, context, ['boolean']);
11793 case 'timestamp':
11794 return this.validateType(value, context, [Date,
11795 /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'],
11796 'Date object, ISO-8601 string, or a UNIX timestamp');
11797 default:
11798 return this.fail('UnkownType', 'Unhandled type ' +
11799 shape.type + ' for ' + context);
11800 }
11801 },
11802
11803 validateString: function validateString(shape, value, context) {
11804 var validTypes = ['string'];
11805 if (shape.isJsonValue) {
11806 validTypes = validTypes.concat(['number', 'object', 'boolean']);
11807 }
11808 if (value !== null && this.validateType(value, context, validTypes)) {
11809 this.validateEnum(shape, value, context);
11810 this.validateRange(shape, value.length, context, 'string length');
11811 this.validatePattern(shape, value, context);
11812 this.validateUri(shape, value, context);
11813 }
11814 },
11815
11816 validateUri: function validateUri(shape, value, context) {
11817 if (shape['location'] === 'uri') {
11818 if (value.length === 0) {
11819 this.fail('UriParameterError', 'Expected uri parameter to have length >= 1,'
11820 + ' but found "' + value +'" for ' + context);
11821 }
11822 }
11823 },
11824
11825 validatePattern: function validatePattern(shape, value, context) {
11826 if (this.validation['pattern'] && shape['pattern'] !== undefined) {
11827 if (!(new RegExp(shape['pattern'])).test(value)) {
11828 this.fail('PatternMatchError', 'Provided value "' + value + '" '
11829 + 'does not match regex pattern /' + shape['pattern'] + '/ for '
11830 + context);
11831 }
11832 }
11833 },
11834
11835 validateRange: function validateRange(shape, value, context, descriptor) {
11836 if (this.validation['min']) {
11837 if (shape['min'] !== undefined && value < shape['min']) {
11838 this.fail('MinRangeError', 'Expected ' + descriptor + ' >= '
11839 + shape['min'] + ', but found ' + value + ' for ' + context);
11840 }
11841 }
11842 if (this.validation['max']) {
11843 if (shape['max'] !== undefined && value > shape['max']) {
11844 this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= '
11845 + shape['max'] + ', but found ' + value + ' for ' + context);
11846 }
11847 }
11848 },
11849
11850 validateEnum: function validateRange(shape, value, context) {
11851 if (this.validation['enum'] && shape['enum'] !== undefined) {
11852 // Fail if the string value is not present in the enum list
11853 if (shape['enum'].indexOf(value) === -1) {
11854 this.fail('EnumError', 'Found string value of ' + value + ', but '
11855 + 'expected ' + shape['enum'].join('|') + ' for ' + context);
11856 }
11857 }
11858 },
11859
11860 validateType: function validateType(value, context, acceptedTypes, type) {
11861 // We will not log an error for null or undefined, but we will return
11862 // false so that callers know that the expected type was not strictly met.
11863 if (value === null || value === undefined) return false;
11864
11865 var foundInvalidType = false;
11866 for (var i = 0; i < acceptedTypes.length; i++) {
11867 if (typeof acceptedTypes[i] === 'string') {
11868 if (typeof value === acceptedTypes[i]) return true;
11869 } else if (acceptedTypes[i] instanceof RegExp) {
11870 if ((value || '').toString().match(acceptedTypes[i])) return true;
11871 } else {
11872 if (value instanceof acceptedTypes[i]) return true;
11873 if (AWS.util.isType(value, acceptedTypes[i])) return true;
11874 if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice();
11875 acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]);
11876 }
11877 foundInvalidType = true;
11878 }
11879
11880 var acceptedType = type;
11881 if (!acceptedType) {
11882 acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1');
11883 }
11884
11885 var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : '';
11886 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' +
11887 vowel + ' ' + acceptedType);
11888 return false;
11889 },
11890
11891 validateNumber: function validateNumber(shape, value, context) {
11892 if (value === null || value === undefined) return;
11893 if (typeof value === 'string') {
11894 var castedValue = parseFloat(value);
11895 if (castedValue.toString() === value) value = castedValue;
11896 }
11897 if (this.validateType(value, context, ['number'])) {
11898 this.validateRange(shape, value, context, 'numeric value');
11899 }
11900 },
11901
11902 validatePayload: function validatePayload(value, context) {
11903 if (value === null || value === undefined) return;
11904 if (typeof value === 'string') return;
11905 if (value && typeof value.byteLength === 'number') return; // typed arrays
11906 if (AWS.util.isNode()) { // special check for buffer/stream in Node.js
11907 var Stream = AWS.util.stream.Stream;
11908 if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return;
11909 } else {
11910 if (typeof Blob !== void 0 && value instanceof Blob) return;
11911 }
11912
11913 var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView'];
11914 if (value) {
11915 for (var i = 0; i < types.length; i++) {
11916 if (AWS.util.isType(value, types[i])) return;
11917 if (AWS.util.typeName(value.constructor) === types[i]) return;
11918 }
11919 }
11920
11921 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' +
11922 'string, Buffer, Stream, Blob, or typed array object');
11923 }
11924 });
11925
11926
11927/***/ })
11928/******/ ])
11929});
11930;
\No newline at end of file