UNPKG

501 kBJavaScriptView Raw
1(function webpackUniversalModuleDefinition(root, factory) {
2 if(typeof exports === 'object' && typeof module === 'object')
3 module.exports = factory(require("aws_amplify_core"));
4 else if(typeof define === 'function' && define.amd)
5 define("aws_amplify_auth", ["aws_amplify_core"], factory);
6 else if(typeof exports === 'object')
7 exports["aws_amplify_auth"] = factory(require("aws_amplify_core"));
8 else
9 root["aws_amplify_auth"] = factory(root["aws_amplify_core"]);
10})(this, function(__WEBPACK_EXTERNAL_MODULE__aws_amplify_core__) {
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/******/ i: moduleId,
25/******/ l: false,
26/******/ exports: {}
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.l = 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/******/ // define getter function for harmony exports
47/******/ __webpack_require__.d = function(exports, name, getter) {
48/******/ if(!__webpack_require__.o(exports, name)) {
49/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
50/******/ }
51/******/ };
52/******/
53/******/ // define __esModule on exports
54/******/ __webpack_require__.r = function(exports) {
55/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
56/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
57/******/ }
58/******/ Object.defineProperty(exports, '__esModule', { value: true });
59/******/ };
60/******/
61/******/ // create a fake namespace object
62/******/ // mode & 1: value is a module id, require it
63/******/ // mode & 2: merge all properties of value into the ns
64/******/ // mode & 4: return value when already ns object
65/******/ // mode & 8|1: behave like require
66/******/ __webpack_require__.t = function(value, mode) {
67/******/ if(mode & 1) value = __webpack_require__(value);
68/******/ if(mode & 8) return value;
69/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
70/******/ var ns = Object.create(null);
71/******/ __webpack_require__.r(ns);
72/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
73/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
74/******/ return ns;
75/******/ };
76/******/
77/******/ // getDefaultExport function for compatibility with non-harmony modules
78/******/ __webpack_require__.n = function(module) {
79/******/ var getter = module && module.__esModule ?
80/******/ function getDefault() { return module['default']; } :
81/******/ function getModuleExports() { return module; };
82/******/ __webpack_require__.d(getter, 'a', getter);
83/******/ return getter;
84/******/ };
85/******/
86/******/ // Object.prototype.hasOwnProperty.call
87/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
88/******/
89/******/ // __webpack_public_path__
90/******/ __webpack_require__.p = "";
91/******/
92/******/
93/******/ // Load entry module and return exports
94/******/ return __webpack_require__(__webpack_require__.s = "./lib-esm/index.js");
95/******/ })
96/************************************************************************/
97/******/ ({
98
99/***/ "../../node_modules/base64-js/index.js":
100/*!********************************************************!*\
101 !*** /root/amplify-js/node_modules/base64-js/index.js ***!
102 \********************************************************/
103/*! no static exports found */
104/***/ (function(module, exports, __webpack_require__) {
105
106"use strict";
107
108
109exports.byteLength = byteLength
110exports.toByteArray = toByteArray
111exports.fromByteArray = fromByteArray
112
113var lookup = []
114var revLookup = []
115var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
116
117var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
118for (var i = 0, len = code.length; i < len; ++i) {
119 lookup[i] = code[i]
120 revLookup[code.charCodeAt(i)] = i
121}
122
123// Support decoding URL-safe base64 strings, as Node.js does.
124// See: https://en.wikipedia.org/wiki/Base64#URL_applications
125revLookup['-'.charCodeAt(0)] = 62
126revLookup['_'.charCodeAt(0)] = 63
127
128function getLens (b64) {
129 var len = b64.length
130
131 if (len % 4 > 0) {
132 throw new Error('Invalid string. Length must be a multiple of 4')
133 }
134
135 // Trim off extra bytes after placeholder bytes are found
136 // See: https://github.com/beatgammit/base64-js/issues/42
137 var validLen = b64.indexOf('=')
138 if (validLen === -1) validLen = len
139
140 var placeHoldersLen = validLen === len
141 ? 0
142 : 4 - (validLen % 4)
143
144 return [validLen, placeHoldersLen]
145}
146
147// base64 is 4/3 + up to two characters of the original data
148function byteLength (b64) {
149 var lens = getLens(b64)
150 var validLen = lens[0]
151 var placeHoldersLen = lens[1]
152 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
153}
154
155function _byteLength (b64, validLen, placeHoldersLen) {
156 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
157}
158
159function toByteArray (b64) {
160 var tmp
161 var lens = getLens(b64)
162 var validLen = lens[0]
163 var placeHoldersLen = lens[1]
164
165 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
166
167 var curByte = 0
168
169 // if there are placeholders, only get up to the last complete 4 chars
170 var len = placeHoldersLen > 0
171 ? validLen - 4
172 : validLen
173
174 var i
175 for (i = 0; i < len; i += 4) {
176 tmp =
177 (revLookup[b64.charCodeAt(i)] << 18) |
178 (revLookup[b64.charCodeAt(i + 1)] << 12) |
179 (revLookup[b64.charCodeAt(i + 2)] << 6) |
180 revLookup[b64.charCodeAt(i + 3)]
181 arr[curByte++] = (tmp >> 16) & 0xFF
182 arr[curByte++] = (tmp >> 8) & 0xFF
183 arr[curByte++] = tmp & 0xFF
184 }
185
186 if (placeHoldersLen === 2) {
187 tmp =
188 (revLookup[b64.charCodeAt(i)] << 2) |
189 (revLookup[b64.charCodeAt(i + 1)] >> 4)
190 arr[curByte++] = tmp & 0xFF
191 }
192
193 if (placeHoldersLen === 1) {
194 tmp =
195 (revLookup[b64.charCodeAt(i)] << 10) |
196 (revLookup[b64.charCodeAt(i + 1)] << 4) |
197 (revLookup[b64.charCodeAt(i + 2)] >> 2)
198 arr[curByte++] = (tmp >> 8) & 0xFF
199 arr[curByte++] = tmp & 0xFF
200 }
201
202 return arr
203}
204
205function tripletToBase64 (num) {
206 return lookup[num >> 18 & 0x3F] +
207 lookup[num >> 12 & 0x3F] +
208 lookup[num >> 6 & 0x3F] +
209 lookup[num & 0x3F]
210}
211
212function encodeChunk (uint8, start, end) {
213 var tmp
214 var output = []
215 for (var i = start; i < end; i += 3) {
216 tmp =
217 ((uint8[i] << 16) & 0xFF0000) +
218 ((uint8[i + 1] << 8) & 0xFF00) +
219 (uint8[i + 2] & 0xFF)
220 output.push(tripletToBase64(tmp))
221 }
222 return output.join('')
223}
224
225function fromByteArray (uint8) {
226 var tmp
227 var len = uint8.length
228 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
229 var parts = []
230 var maxChunkLength = 16383 // must be multiple of 3
231
232 // go through the array every three bytes, we'll deal with trailing stuff later
233 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
234 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
235 }
236
237 // pad the end with zeros, but make sure to not forget the extra bytes
238 if (extraBytes === 1) {
239 tmp = uint8[len - 1]
240 parts.push(
241 lookup[tmp >> 2] +
242 lookup[(tmp << 4) & 0x3F] +
243 '=='
244 )
245 } else if (extraBytes === 2) {
246 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
247 parts.push(
248 lookup[tmp >> 10] +
249 lookup[(tmp >> 4) & 0x3F] +
250 lookup[(tmp << 2) & 0x3F] +
251 '='
252 )
253 }
254
255 return parts.join('')
256}
257
258
259/***/ }),
260
261/***/ "../../node_modules/buffer/index.js":
262/*!*****************************************************!*\
263 !*** /root/amplify-js/node_modules/buffer/index.js ***!
264 \*****************************************************/
265/*! no static exports found */
266/***/ (function(module, exports, __webpack_require__) {
267
268"use strict";
269/* WEBPACK VAR INJECTION */(function(global) {/*!
270 * The buffer module from node.js, for the browser.
271 *
272 * @author Feross Aboukhadijeh <http://feross.org>
273 * @license MIT
274 */
275/* eslint-disable no-proto */
276
277
278
279var base64 = __webpack_require__(/*! base64-js */ "../../node_modules/base64-js/index.js")
280var ieee754 = __webpack_require__(/*! ieee754 */ "../../node_modules/ieee754/index.js")
281var isArray = __webpack_require__(/*! isarray */ "../../node_modules/isarray/index.js")
282
283exports.Buffer = Buffer
284exports.SlowBuffer = SlowBuffer
285exports.INSPECT_MAX_BYTES = 50
286
287/**
288 * If `Buffer.TYPED_ARRAY_SUPPORT`:
289 * === true Use Uint8Array implementation (fastest)
290 * === false Use Object implementation (most compatible, even IE6)
291 *
292 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
293 * Opera 11.6+, iOS 4.2+.
294 *
295 * Due to various browser bugs, sometimes the Object implementation will be used even
296 * when the browser supports typed arrays.
297 *
298 * Note:
299 *
300 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
301 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
302 *
303 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
304 *
305 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
306 * incorrect length in some situations.
307
308 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
309 * get the Object implementation, which is slower but behaves correctly.
310 */
311Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
312 ? global.TYPED_ARRAY_SUPPORT
313 : typedArraySupport()
314
315/*
316 * Export kMaxLength after typed array support is determined.
317 */
318exports.kMaxLength = kMaxLength()
319
320function typedArraySupport () {
321 try {
322 var arr = new Uint8Array(1)
323 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
324 return arr.foo() === 42 && // typed array instances can be augmented
325 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
326 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
327 } catch (e) {
328 return false
329 }
330}
331
332function kMaxLength () {
333 return Buffer.TYPED_ARRAY_SUPPORT
334 ? 0x7fffffff
335 : 0x3fffffff
336}
337
338function createBuffer (that, length) {
339 if (kMaxLength() < length) {
340 throw new RangeError('Invalid typed array length')
341 }
342 if (Buffer.TYPED_ARRAY_SUPPORT) {
343 // Return an augmented `Uint8Array` instance, for best performance
344 that = new Uint8Array(length)
345 that.__proto__ = Buffer.prototype
346 } else {
347 // Fallback: Return an object instance of the Buffer class
348 if (that === null) {
349 that = new Buffer(length)
350 }
351 that.length = length
352 }
353
354 return that
355}
356
357/**
358 * The Buffer constructor returns instances of `Uint8Array` that have their
359 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
360 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
361 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
362 * returns a single octet.
363 *
364 * The `Uint8Array` prototype remains unmodified.
365 */
366
367function Buffer (arg, encodingOrOffset, length) {
368 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
369 return new Buffer(arg, encodingOrOffset, length)
370 }
371
372 // Common case.
373 if (typeof arg === 'number') {
374 if (typeof encodingOrOffset === 'string') {
375 throw new Error(
376 'If encoding is specified then the first argument must be a string'
377 )
378 }
379 return allocUnsafe(this, arg)
380 }
381 return from(this, arg, encodingOrOffset, length)
382}
383
384Buffer.poolSize = 8192 // not used by this implementation
385
386// TODO: Legacy, not needed anymore. Remove in next major version.
387Buffer._augment = function (arr) {
388 arr.__proto__ = Buffer.prototype
389 return arr
390}
391
392function from (that, value, encodingOrOffset, length) {
393 if (typeof value === 'number') {
394 throw new TypeError('"value" argument must not be a number')
395 }
396
397 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
398 return fromArrayBuffer(that, value, encodingOrOffset, length)
399 }
400
401 if (typeof value === 'string') {
402 return fromString(that, value, encodingOrOffset)
403 }
404
405 return fromObject(that, value)
406}
407
408/**
409 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
410 * if value is a number.
411 * Buffer.from(str[, encoding])
412 * Buffer.from(array)
413 * Buffer.from(buffer)
414 * Buffer.from(arrayBuffer[, byteOffset[, length]])
415 **/
416Buffer.from = function (value, encodingOrOffset, length) {
417 return from(null, value, encodingOrOffset, length)
418}
419
420if (Buffer.TYPED_ARRAY_SUPPORT) {
421 Buffer.prototype.__proto__ = Uint8Array.prototype
422 Buffer.__proto__ = Uint8Array
423 if (typeof Symbol !== 'undefined' && Symbol.species &&
424 Buffer[Symbol.species] === Buffer) {
425 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
426 Object.defineProperty(Buffer, Symbol.species, {
427 value: null,
428 configurable: true
429 })
430 }
431}
432
433function assertSize (size) {
434 if (typeof size !== 'number') {
435 throw new TypeError('"size" argument must be a number')
436 } else if (size < 0) {
437 throw new RangeError('"size" argument must not be negative')
438 }
439}
440
441function alloc (that, size, fill, encoding) {
442 assertSize(size)
443 if (size <= 0) {
444 return createBuffer(that, size)
445 }
446 if (fill !== undefined) {
447 // Only pay attention to encoding if it's a string. This
448 // prevents accidentally sending in a number that would
449 // be interpretted as a start offset.
450 return typeof encoding === 'string'
451 ? createBuffer(that, size).fill(fill, encoding)
452 : createBuffer(that, size).fill(fill)
453 }
454 return createBuffer(that, size)
455}
456
457/**
458 * Creates a new filled Buffer instance.
459 * alloc(size[, fill[, encoding]])
460 **/
461Buffer.alloc = function (size, fill, encoding) {
462 return alloc(null, size, fill, encoding)
463}
464
465function allocUnsafe (that, size) {
466 assertSize(size)
467 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
468 if (!Buffer.TYPED_ARRAY_SUPPORT) {
469 for (var i = 0; i < size; ++i) {
470 that[i] = 0
471 }
472 }
473 return that
474}
475
476/**
477 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
478 * */
479Buffer.allocUnsafe = function (size) {
480 return allocUnsafe(null, size)
481}
482/**
483 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
484 */
485Buffer.allocUnsafeSlow = function (size) {
486 return allocUnsafe(null, size)
487}
488
489function fromString (that, string, encoding) {
490 if (typeof encoding !== 'string' || encoding === '') {
491 encoding = 'utf8'
492 }
493
494 if (!Buffer.isEncoding(encoding)) {
495 throw new TypeError('"encoding" must be a valid string encoding')
496 }
497
498 var length = byteLength(string, encoding) | 0
499 that = createBuffer(that, length)
500
501 var actual = that.write(string, encoding)
502
503 if (actual !== length) {
504 // Writing a hex string, for example, that contains invalid characters will
505 // cause everything after the first invalid character to be ignored. (e.g.
506 // 'abxxcd' will be treated as 'ab')
507 that = that.slice(0, actual)
508 }
509
510 return that
511}
512
513function fromArrayLike (that, array) {
514 var length = array.length < 0 ? 0 : checked(array.length) | 0
515 that = createBuffer(that, length)
516 for (var i = 0; i < length; i += 1) {
517 that[i] = array[i] & 255
518 }
519 return that
520}
521
522function fromArrayBuffer (that, array, byteOffset, length) {
523 array.byteLength // this throws if `array` is not a valid ArrayBuffer
524
525 if (byteOffset < 0 || array.byteLength < byteOffset) {
526 throw new RangeError('\'offset\' is out of bounds')
527 }
528
529 if (array.byteLength < byteOffset + (length || 0)) {
530 throw new RangeError('\'length\' is out of bounds')
531 }
532
533 if (byteOffset === undefined && length === undefined) {
534 array = new Uint8Array(array)
535 } else if (length === undefined) {
536 array = new Uint8Array(array, byteOffset)
537 } else {
538 array = new Uint8Array(array, byteOffset, length)
539 }
540
541 if (Buffer.TYPED_ARRAY_SUPPORT) {
542 // Return an augmented `Uint8Array` instance, for best performance
543 that = array
544 that.__proto__ = Buffer.prototype
545 } else {
546 // Fallback: Return an object instance of the Buffer class
547 that = fromArrayLike(that, array)
548 }
549 return that
550}
551
552function fromObject (that, obj) {
553 if (Buffer.isBuffer(obj)) {
554 var len = checked(obj.length) | 0
555 that = createBuffer(that, len)
556
557 if (that.length === 0) {
558 return that
559 }
560
561 obj.copy(that, 0, 0, len)
562 return that
563 }
564
565 if (obj) {
566 if ((typeof ArrayBuffer !== 'undefined' &&
567 obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
568 if (typeof obj.length !== 'number' || isnan(obj.length)) {
569 return createBuffer(that, 0)
570 }
571 return fromArrayLike(that, obj)
572 }
573
574 if (obj.type === 'Buffer' && isArray(obj.data)) {
575 return fromArrayLike(that, obj.data)
576 }
577 }
578
579 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
580}
581
582function checked (length) {
583 // Note: cannot use `length < kMaxLength()` here because that fails when
584 // length is NaN (which is otherwise coerced to zero.)
585 if (length >= kMaxLength()) {
586 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
587 'size: 0x' + kMaxLength().toString(16) + ' bytes')
588 }
589 return length | 0
590}
591
592function SlowBuffer (length) {
593 if (+length != length) { // eslint-disable-line eqeqeq
594 length = 0
595 }
596 return Buffer.alloc(+length)
597}
598
599Buffer.isBuffer = function isBuffer (b) {
600 return !!(b != null && b._isBuffer)
601}
602
603Buffer.compare = function compare (a, b) {
604 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
605 throw new TypeError('Arguments must be Buffers')
606 }
607
608 if (a === b) return 0
609
610 var x = a.length
611 var y = b.length
612
613 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
614 if (a[i] !== b[i]) {
615 x = a[i]
616 y = b[i]
617 break
618 }
619 }
620
621 if (x < y) return -1
622 if (y < x) return 1
623 return 0
624}
625
626Buffer.isEncoding = function isEncoding (encoding) {
627 switch (String(encoding).toLowerCase()) {
628 case 'hex':
629 case 'utf8':
630 case 'utf-8':
631 case 'ascii':
632 case 'latin1':
633 case 'binary':
634 case 'base64':
635 case 'ucs2':
636 case 'ucs-2':
637 case 'utf16le':
638 case 'utf-16le':
639 return true
640 default:
641 return false
642 }
643}
644
645Buffer.concat = function concat (list, length) {
646 if (!isArray(list)) {
647 throw new TypeError('"list" argument must be an Array of Buffers')
648 }
649
650 if (list.length === 0) {
651 return Buffer.alloc(0)
652 }
653
654 var i
655 if (length === undefined) {
656 length = 0
657 for (i = 0; i < list.length; ++i) {
658 length += list[i].length
659 }
660 }
661
662 var buffer = Buffer.allocUnsafe(length)
663 var pos = 0
664 for (i = 0; i < list.length; ++i) {
665 var buf = list[i]
666 if (!Buffer.isBuffer(buf)) {
667 throw new TypeError('"list" argument must be an Array of Buffers')
668 }
669 buf.copy(buffer, pos)
670 pos += buf.length
671 }
672 return buffer
673}
674
675function byteLength (string, encoding) {
676 if (Buffer.isBuffer(string)) {
677 return string.length
678 }
679 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
680 (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
681 return string.byteLength
682 }
683 if (typeof string !== 'string') {
684 string = '' + string
685 }
686
687 var len = string.length
688 if (len === 0) return 0
689
690 // Use a for loop to avoid recursion
691 var loweredCase = false
692 for (;;) {
693 switch (encoding) {
694 case 'ascii':
695 case 'latin1':
696 case 'binary':
697 return len
698 case 'utf8':
699 case 'utf-8':
700 case undefined:
701 return utf8ToBytes(string).length
702 case 'ucs2':
703 case 'ucs-2':
704 case 'utf16le':
705 case 'utf-16le':
706 return len * 2
707 case 'hex':
708 return len >>> 1
709 case 'base64':
710 return base64ToBytes(string).length
711 default:
712 if (loweredCase) return utf8ToBytes(string).length // assume utf8
713 encoding = ('' + encoding).toLowerCase()
714 loweredCase = true
715 }
716 }
717}
718Buffer.byteLength = byteLength
719
720function slowToString (encoding, start, end) {
721 var loweredCase = false
722
723 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
724 // property of a typed array.
725
726 // This behaves neither like String nor Uint8Array in that we set start/end
727 // to their upper/lower bounds if the value passed is out of range.
728 // undefined is handled specially as per ECMA-262 6th Edition,
729 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
730 if (start === undefined || start < 0) {
731 start = 0
732 }
733 // Return early if start > this.length. Done here to prevent potential uint32
734 // coercion fail below.
735 if (start > this.length) {
736 return ''
737 }
738
739 if (end === undefined || end > this.length) {
740 end = this.length
741 }
742
743 if (end <= 0) {
744 return ''
745 }
746
747 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
748 end >>>= 0
749 start >>>= 0
750
751 if (end <= start) {
752 return ''
753 }
754
755 if (!encoding) encoding = 'utf8'
756
757 while (true) {
758 switch (encoding) {
759 case 'hex':
760 return hexSlice(this, start, end)
761
762 case 'utf8':
763 case 'utf-8':
764 return utf8Slice(this, start, end)
765
766 case 'ascii':
767 return asciiSlice(this, start, end)
768
769 case 'latin1':
770 case 'binary':
771 return latin1Slice(this, start, end)
772
773 case 'base64':
774 return base64Slice(this, start, end)
775
776 case 'ucs2':
777 case 'ucs-2':
778 case 'utf16le':
779 case 'utf-16le':
780 return utf16leSlice(this, start, end)
781
782 default:
783 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
784 encoding = (encoding + '').toLowerCase()
785 loweredCase = true
786 }
787 }
788}
789
790// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
791// Buffer instances.
792Buffer.prototype._isBuffer = true
793
794function swap (b, n, m) {
795 var i = b[n]
796 b[n] = b[m]
797 b[m] = i
798}
799
800Buffer.prototype.swap16 = function swap16 () {
801 var len = this.length
802 if (len % 2 !== 0) {
803 throw new RangeError('Buffer size must be a multiple of 16-bits')
804 }
805 for (var i = 0; i < len; i += 2) {
806 swap(this, i, i + 1)
807 }
808 return this
809}
810
811Buffer.prototype.swap32 = function swap32 () {
812 var len = this.length
813 if (len % 4 !== 0) {
814 throw new RangeError('Buffer size must be a multiple of 32-bits')
815 }
816 for (var i = 0; i < len; i += 4) {
817 swap(this, i, i + 3)
818 swap(this, i + 1, i + 2)
819 }
820 return this
821}
822
823Buffer.prototype.swap64 = function swap64 () {
824 var len = this.length
825 if (len % 8 !== 0) {
826 throw new RangeError('Buffer size must be a multiple of 64-bits')
827 }
828 for (var i = 0; i < len; i += 8) {
829 swap(this, i, i + 7)
830 swap(this, i + 1, i + 6)
831 swap(this, i + 2, i + 5)
832 swap(this, i + 3, i + 4)
833 }
834 return this
835}
836
837Buffer.prototype.toString = function toString () {
838 var length = this.length | 0
839 if (length === 0) return ''
840 if (arguments.length === 0) return utf8Slice(this, 0, length)
841 return slowToString.apply(this, arguments)
842}
843
844Buffer.prototype.equals = function equals (b) {
845 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
846 if (this === b) return true
847 return Buffer.compare(this, b) === 0
848}
849
850Buffer.prototype.inspect = function inspect () {
851 var str = ''
852 var max = exports.INSPECT_MAX_BYTES
853 if (this.length > 0) {
854 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
855 if (this.length > max) str += ' ... '
856 }
857 return '<Buffer ' + str + '>'
858}
859
860Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
861 if (!Buffer.isBuffer(target)) {
862 throw new TypeError('Argument must be a Buffer')
863 }
864
865 if (start === undefined) {
866 start = 0
867 }
868 if (end === undefined) {
869 end = target ? target.length : 0
870 }
871 if (thisStart === undefined) {
872 thisStart = 0
873 }
874 if (thisEnd === undefined) {
875 thisEnd = this.length
876 }
877
878 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
879 throw new RangeError('out of range index')
880 }
881
882 if (thisStart >= thisEnd && start >= end) {
883 return 0
884 }
885 if (thisStart >= thisEnd) {
886 return -1
887 }
888 if (start >= end) {
889 return 1
890 }
891
892 start >>>= 0
893 end >>>= 0
894 thisStart >>>= 0
895 thisEnd >>>= 0
896
897 if (this === target) return 0
898
899 var x = thisEnd - thisStart
900 var y = end - start
901 var len = Math.min(x, y)
902
903 var thisCopy = this.slice(thisStart, thisEnd)
904 var targetCopy = target.slice(start, end)
905
906 for (var i = 0; i < len; ++i) {
907 if (thisCopy[i] !== targetCopy[i]) {
908 x = thisCopy[i]
909 y = targetCopy[i]
910 break
911 }
912 }
913
914 if (x < y) return -1
915 if (y < x) return 1
916 return 0
917}
918
919// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
920// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
921//
922// Arguments:
923// - buffer - a Buffer to search
924// - val - a string, Buffer, or number
925// - byteOffset - an index into `buffer`; will be clamped to an int32
926// - encoding - an optional encoding, relevant is val is a string
927// - dir - true for indexOf, false for lastIndexOf
928function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
929 // Empty buffer means no match
930 if (buffer.length === 0) return -1
931
932 // Normalize byteOffset
933 if (typeof byteOffset === 'string') {
934 encoding = byteOffset
935 byteOffset = 0
936 } else if (byteOffset > 0x7fffffff) {
937 byteOffset = 0x7fffffff
938 } else if (byteOffset < -0x80000000) {
939 byteOffset = -0x80000000
940 }
941 byteOffset = +byteOffset // Coerce to Number.
942 if (isNaN(byteOffset)) {
943 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
944 byteOffset = dir ? 0 : (buffer.length - 1)
945 }
946
947 // Normalize byteOffset: negative offsets start from the end of the buffer
948 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
949 if (byteOffset >= buffer.length) {
950 if (dir) return -1
951 else byteOffset = buffer.length - 1
952 } else if (byteOffset < 0) {
953 if (dir) byteOffset = 0
954 else return -1
955 }
956
957 // Normalize val
958 if (typeof val === 'string') {
959 val = Buffer.from(val, encoding)
960 }
961
962 // Finally, search either indexOf (if dir is true) or lastIndexOf
963 if (Buffer.isBuffer(val)) {
964 // Special case: looking for empty string/buffer always fails
965 if (val.length === 0) {
966 return -1
967 }
968 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
969 } else if (typeof val === 'number') {
970 val = val & 0xFF // Search for a byte value [0-255]
971 if (Buffer.TYPED_ARRAY_SUPPORT &&
972 typeof Uint8Array.prototype.indexOf === 'function') {
973 if (dir) {
974 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
975 } else {
976 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
977 }
978 }
979 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
980 }
981
982 throw new TypeError('val must be string, number or Buffer')
983}
984
985function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
986 var indexSize = 1
987 var arrLength = arr.length
988 var valLength = val.length
989
990 if (encoding !== undefined) {
991 encoding = String(encoding).toLowerCase()
992 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
993 encoding === 'utf16le' || encoding === 'utf-16le') {
994 if (arr.length < 2 || val.length < 2) {
995 return -1
996 }
997 indexSize = 2
998 arrLength /= 2
999 valLength /= 2
1000 byteOffset /= 2
1001 }
1002 }
1003
1004 function read (buf, i) {
1005 if (indexSize === 1) {
1006 return buf[i]
1007 } else {
1008 return buf.readUInt16BE(i * indexSize)
1009 }
1010 }
1011
1012 var i
1013 if (dir) {
1014 var foundIndex = -1
1015 for (i = byteOffset; i < arrLength; i++) {
1016 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1017 if (foundIndex === -1) foundIndex = i
1018 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1019 } else {
1020 if (foundIndex !== -1) i -= i - foundIndex
1021 foundIndex = -1
1022 }
1023 }
1024 } else {
1025 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1026 for (i = byteOffset; i >= 0; i--) {
1027 var found = true
1028 for (var j = 0; j < valLength; j++) {
1029 if (read(arr, i + j) !== read(val, j)) {
1030 found = false
1031 break
1032 }
1033 }
1034 if (found) return i
1035 }
1036 }
1037
1038 return -1
1039}
1040
1041Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1042 return this.indexOf(val, byteOffset, encoding) !== -1
1043}
1044
1045Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1046 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1047}
1048
1049Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1050 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1051}
1052
1053function hexWrite (buf, string, offset, length) {
1054 offset = Number(offset) || 0
1055 var remaining = buf.length - offset
1056 if (!length) {
1057 length = remaining
1058 } else {
1059 length = Number(length)
1060 if (length > remaining) {
1061 length = remaining
1062 }
1063 }
1064
1065 // must be an even number of digits
1066 var strLen = string.length
1067 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1068
1069 if (length > strLen / 2) {
1070 length = strLen / 2
1071 }
1072 for (var i = 0; i < length; ++i) {
1073 var parsed = parseInt(string.substr(i * 2, 2), 16)
1074 if (isNaN(parsed)) return i
1075 buf[offset + i] = parsed
1076 }
1077 return i
1078}
1079
1080function utf8Write (buf, string, offset, length) {
1081 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1082}
1083
1084function asciiWrite (buf, string, offset, length) {
1085 return blitBuffer(asciiToBytes(string), buf, offset, length)
1086}
1087
1088function latin1Write (buf, string, offset, length) {
1089 return asciiWrite(buf, string, offset, length)
1090}
1091
1092function base64Write (buf, string, offset, length) {
1093 return blitBuffer(base64ToBytes(string), buf, offset, length)
1094}
1095
1096function ucs2Write (buf, string, offset, length) {
1097 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1098}
1099
1100Buffer.prototype.write = function write (string, offset, length, encoding) {
1101 // Buffer#write(string)
1102 if (offset === undefined) {
1103 encoding = 'utf8'
1104 length = this.length
1105 offset = 0
1106 // Buffer#write(string, encoding)
1107 } else if (length === undefined && typeof offset === 'string') {
1108 encoding = offset
1109 length = this.length
1110 offset = 0
1111 // Buffer#write(string, offset[, length][, encoding])
1112 } else if (isFinite(offset)) {
1113 offset = offset | 0
1114 if (isFinite(length)) {
1115 length = length | 0
1116 if (encoding === undefined) encoding = 'utf8'
1117 } else {
1118 encoding = length
1119 length = undefined
1120 }
1121 // legacy write(string, encoding, offset, length) - remove in v0.13
1122 } else {
1123 throw new Error(
1124 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1125 )
1126 }
1127
1128 var remaining = this.length - offset
1129 if (length === undefined || length > remaining) length = remaining
1130
1131 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1132 throw new RangeError('Attempt to write outside buffer bounds')
1133 }
1134
1135 if (!encoding) encoding = 'utf8'
1136
1137 var loweredCase = false
1138 for (;;) {
1139 switch (encoding) {
1140 case 'hex':
1141 return hexWrite(this, string, offset, length)
1142
1143 case 'utf8':
1144 case 'utf-8':
1145 return utf8Write(this, string, offset, length)
1146
1147 case 'ascii':
1148 return asciiWrite(this, string, offset, length)
1149
1150 case 'latin1':
1151 case 'binary':
1152 return latin1Write(this, string, offset, length)
1153
1154 case 'base64':
1155 // Warning: maxLength not taken into account in base64Write
1156 return base64Write(this, string, offset, length)
1157
1158 case 'ucs2':
1159 case 'ucs-2':
1160 case 'utf16le':
1161 case 'utf-16le':
1162 return ucs2Write(this, string, offset, length)
1163
1164 default:
1165 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1166 encoding = ('' + encoding).toLowerCase()
1167 loweredCase = true
1168 }
1169 }
1170}
1171
1172Buffer.prototype.toJSON = function toJSON () {
1173 return {
1174 type: 'Buffer',
1175 data: Array.prototype.slice.call(this._arr || this, 0)
1176 }
1177}
1178
1179function base64Slice (buf, start, end) {
1180 if (start === 0 && end === buf.length) {
1181 return base64.fromByteArray(buf)
1182 } else {
1183 return base64.fromByteArray(buf.slice(start, end))
1184 }
1185}
1186
1187function utf8Slice (buf, start, end) {
1188 end = Math.min(buf.length, end)
1189 var res = []
1190
1191 var i = start
1192 while (i < end) {
1193 var firstByte = buf[i]
1194 var codePoint = null
1195 var bytesPerSequence = (firstByte > 0xEF) ? 4
1196 : (firstByte > 0xDF) ? 3
1197 : (firstByte > 0xBF) ? 2
1198 : 1
1199
1200 if (i + bytesPerSequence <= end) {
1201 var secondByte, thirdByte, fourthByte, tempCodePoint
1202
1203 switch (bytesPerSequence) {
1204 case 1:
1205 if (firstByte < 0x80) {
1206 codePoint = firstByte
1207 }
1208 break
1209 case 2:
1210 secondByte = buf[i + 1]
1211 if ((secondByte & 0xC0) === 0x80) {
1212 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1213 if (tempCodePoint > 0x7F) {
1214 codePoint = tempCodePoint
1215 }
1216 }
1217 break
1218 case 3:
1219 secondByte = buf[i + 1]
1220 thirdByte = buf[i + 2]
1221 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1222 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1223 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1224 codePoint = tempCodePoint
1225 }
1226 }
1227 break
1228 case 4:
1229 secondByte = buf[i + 1]
1230 thirdByte = buf[i + 2]
1231 fourthByte = buf[i + 3]
1232 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1233 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1234 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1235 codePoint = tempCodePoint
1236 }
1237 }
1238 }
1239 }
1240
1241 if (codePoint === null) {
1242 // we did not generate a valid codePoint so insert a
1243 // replacement char (U+FFFD) and advance only 1 byte
1244 codePoint = 0xFFFD
1245 bytesPerSequence = 1
1246 } else if (codePoint > 0xFFFF) {
1247 // encode to utf16 (surrogate pair dance)
1248 codePoint -= 0x10000
1249 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1250 codePoint = 0xDC00 | codePoint & 0x3FF
1251 }
1252
1253 res.push(codePoint)
1254 i += bytesPerSequence
1255 }
1256
1257 return decodeCodePointsArray(res)
1258}
1259
1260// Based on http://stackoverflow.com/a/22747272/680742, the browser with
1261// the lowest limit is Chrome, with 0x10000 args.
1262// We go 1 magnitude less, for safety
1263var MAX_ARGUMENTS_LENGTH = 0x1000
1264
1265function decodeCodePointsArray (codePoints) {
1266 var len = codePoints.length
1267 if (len <= MAX_ARGUMENTS_LENGTH) {
1268 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1269 }
1270
1271 // Decode in chunks to avoid "call stack size exceeded".
1272 var res = ''
1273 var i = 0
1274 while (i < len) {
1275 res += String.fromCharCode.apply(
1276 String,
1277 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1278 )
1279 }
1280 return res
1281}
1282
1283function asciiSlice (buf, start, end) {
1284 var ret = ''
1285 end = Math.min(buf.length, end)
1286
1287 for (var i = start; i < end; ++i) {
1288 ret += String.fromCharCode(buf[i] & 0x7F)
1289 }
1290 return ret
1291}
1292
1293function latin1Slice (buf, start, end) {
1294 var ret = ''
1295 end = Math.min(buf.length, end)
1296
1297 for (var i = start; i < end; ++i) {
1298 ret += String.fromCharCode(buf[i])
1299 }
1300 return ret
1301}
1302
1303function hexSlice (buf, start, end) {
1304 var len = buf.length
1305
1306 if (!start || start < 0) start = 0
1307 if (!end || end < 0 || end > len) end = len
1308
1309 var out = ''
1310 for (var i = start; i < end; ++i) {
1311 out += toHex(buf[i])
1312 }
1313 return out
1314}
1315
1316function utf16leSlice (buf, start, end) {
1317 var bytes = buf.slice(start, end)
1318 var res = ''
1319 for (var i = 0; i < bytes.length; i += 2) {
1320 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
1321 }
1322 return res
1323}
1324
1325Buffer.prototype.slice = function slice (start, end) {
1326 var len = this.length
1327 start = ~~start
1328 end = end === undefined ? len : ~~end
1329
1330 if (start < 0) {
1331 start += len
1332 if (start < 0) start = 0
1333 } else if (start > len) {
1334 start = len
1335 }
1336
1337 if (end < 0) {
1338 end += len
1339 if (end < 0) end = 0
1340 } else if (end > len) {
1341 end = len
1342 }
1343
1344 if (end < start) end = start
1345
1346 var newBuf
1347 if (Buffer.TYPED_ARRAY_SUPPORT) {
1348 newBuf = this.subarray(start, end)
1349 newBuf.__proto__ = Buffer.prototype
1350 } else {
1351 var sliceLen = end - start
1352 newBuf = new Buffer(sliceLen, undefined)
1353 for (var i = 0; i < sliceLen; ++i) {
1354 newBuf[i] = this[i + start]
1355 }
1356 }
1357
1358 return newBuf
1359}
1360
1361/*
1362 * Need to make sure that buffer isn't trying to write out of bounds.
1363 */
1364function checkOffset (offset, ext, length) {
1365 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1366 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1367}
1368
1369Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1370 offset = offset | 0
1371 byteLength = byteLength | 0
1372 if (!noAssert) checkOffset(offset, byteLength, this.length)
1373
1374 var val = this[offset]
1375 var mul = 1
1376 var i = 0
1377 while (++i < byteLength && (mul *= 0x100)) {
1378 val += this[offset + i] * mul
1379 }
1380
1381 return val
1382}
1383
1384Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1385 offset = offset | 0
1386 byteLength = byteLength | 0
1387 if (!noAssert) {
1388 checkOffset(offset, byteLength, this.length)
1389 }
1390
1391 var val = this[offset + --byteLength]
1392 var mul = 1
1393 while (byteLength > 0 && (mul *= 0x100)) {
1394 val += this[offset + --byteLength] * mul
1395 }
1396
1397 return val
1398}
1399
1400Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1401 if (!noAssert) checkOffset(offset, 1, this.length)
1402 return this[offset]
1403}
1404
1405Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1406 if (!noAssert) checkOffset(offset, 2, this.length)
1407 return this[offset] | (this[offset + 1] << 8)
1408}
1409
1410Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1411 if (!noAssert) checkOffset(offset, 2, this.length)
1412 return (this[offset] << 8) | this[offset + 1]
1413}
1414
1415Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1416 if (!noAssert) checkOffset(offset, 4, this.length)
1417
1418 return ((this[offset]) |
1419 (this[offset + 1] << 8) |
1420 (this[offset + 2] << 16)) +
1421 (this[offset + 3] * 0x1000000)
1422}
1423
1424Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1425 if (!noAssert) checkOffset(offset, 4, this.length)
1426
1427 return (this[offset] * 0x1000000) +
1428 ((this[offset + 1] << 16) |
1429 (this[offset + 2] << 8) |
1430 this[offset + 3])
1431}
1432
1433Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1434 offset = offset | 0
1435 byteLength = byteLength | 0
1436 if (!noAssert) checkOffset(offset, byteLength, this.length)
1437
1438 var val = this[offset]
1439 var mul = 1
1440 var i = 0
1441 while (++i < byteLength && (mul *= 0x100)) {
1442 val += this[offset + i] * mul
1443 }
1444 mul *= 0x80
1445
1446 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1447
1448 return val
1449}
1450
1451Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1452 offset = offset | 0
1453 byteLength = byteLength | 0
1454 if (!noAssert) checkOffset(offset, byteLength, this.length)
1455
1456 var i = byteLength
1457 var mul = 1
1458 var val = this[offset + --i]
1459 while (i > 0 && (mul *= 0x100)) {
1460 val += this[offset + --i] * mul
1461 }
1462 mul *= 0x80
1463
1464 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1465
1466 return val
1467}
1468
1469Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1470 if (!noAssert) checkOffset(offset, 1, this.length)
1471 if (!(this[offset] & 0x80)) return (this[offset])
1472 return ((0xff - this[offset] + 1) * -1)
1473}
1474
1475Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1476 if (!noAssert) checkOffset(offset, 2, this.length)
1477 var val = this[offset] | (this[offset + 1] << 8)
1478 return (val & 0x8000) ? val | 0xFFFF0000 : val
1479}
1480
1481Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1482 if (!noAssert) checkOffset(offset, 2, this.length)
1483 var val = this[offset + 1] | (this[offset] << 8)
1484 return (val & 0x8000) ? val | 0xFFFF0000 : val
1485}
1486
1487Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1488 if (!noAssert) checkOffset(offset, 4, this.length)
1489
1490 return (this[offset]) |
1491 (this[offset + 1] << 8) |
1492 (this[offset + 2] << 16) |
1493 (this[offset + 3] << 24)
1494}
1495
1496Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1497 if (!noAssert) checkOffset(offset, 4, this.length)
1498
1499 return (this[offset] << 24) |
1500 (this[offset + 1] << 16) |
1501 (this[offset + 2] << 8) |
1502 (this[offset + 3])
1503}
1504
1505Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1506 if (!noAssert) checkOffset(offset, 4, this.length)
1507 return ieee754.read(this, offset, true, 23, 4)
1508}
1509
1510Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1511 if (!noAssert) checkOffset(offset, 4, this.length)
1512 return ieee754.read(this, offset, false, 23, 4)
1513}
1514
1515Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1516 if (!noAssert) checkOffset(offset, 8, this.length)
1517 return ieee754.read(this, offset, true, 52, 8)
1518}
1519
1520Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1521 if (!noAssert) checkOffset(offset, 8, this.length)
1522 return ieee754.read(this, offset, false, 52, 8)
1523}
1524
1525function checkInt (buf, value, offset, ext, max, min) {
1526 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1527 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1528 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1529}
1530
1531Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1532 value = +value
1533 offset = offset | 0
1534 byteLength = byteLength | 0
1535 if (!noAssert) {
1536 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1537 checkInt(this, value, offset, byteLength, maxBytes, 0)
1538 }
1539
1540 var mul = 1
1541 var i = 0
1542 this[offset] = value & 0xFF
1543 while (++i < byteLength && (mul *= 0x100)) {
1544 this[offset + i] = (value / mul) & 0xFF
1545 }
1546
1547 return offset + byteLength
1548}
1549
1550Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1551 value = +value
1552 offset = offset | 0
1553 byteLength = byteLength | 0
1554 if (!noAssert) {
1555 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1556 checkInt(this, value, offset, byteLength, maxBytes, 0)
1557 }
1558
1559 var i = byteLength - 1
1560 var mul = 1
1561 this[offset + i] = value & 0xFF
1562 while (--i >= 0 && (mul *= 0x100)) {
1563 this[offset + i] = (value / mul) & 0xFF
1564 }
1565
1566 return offset + byteLength
1567}
1568
1569Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1570 value = +value
1571 offset = offset | 0
1572 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1573 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1574 this[offset] = (value & 0xff)
1575 return offset + 1
1576}
1577
1578function objectWriteUInt16 (buf, value, offset, littleEndian) {
1579 if (value < 0) value = 0xffff + value + 1
1580 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
1581 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1582 (littleEndian ? i : 1 - i) * 8
1583 }
1584}
1585
1586Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1587 value = +value
1588 offset = offset | 0
1589 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1590 if (Buffer.TYPED_ARRAY_SUPPORT) {
1591 this[offset] = (value & 0xff)
1592 this[offset + 1] = (value >>> 8)
1593 } else {
1594 objectWriteUInt16(this, value, offset, true)
1595 }
1596 return offset + 2
1597}
1598
1599Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1600 value = +value
1601 offset = offset | 0
1602 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1603 if (Buffer.TYPED_ARRAY_SUPPORT) {
1604 this[offset] = (value >>> 8)
1605 this[offset + 1] = (value & 0xff)
1606 } else {
1607 objectWriteUInt16(this, value, offset, false)
1608 }
1609 return offset + 2
1610}
1611
1612function objectWriteUInt32 (buf, value, offset, littleEndian) {
1613 if (value < 0) value = 0xffffffff + value + 1
1614 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
1615 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
1616 }
1617}
1618
1619Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1620 value = +value
1621 offset = offset | 0
1622 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1623 if (Buffer.TYPED_ARRAY_SUPPORT) {
1624 this[offset + 3] = (value >>> 24)
1625 this[offset + 2] = (value >>> 16)
1626 this[offset + 1] = (value >>> 8)
1627 this[offset] = (value & 0xff)
1628 } else {
1629 objectWriteUInt32(this, value, offset, true)
1630 }
1631 return offset + 4
1632}
1633
1634Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1635 value = +value
1636 offset = offset | 0
1637 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1638 if (Buffer.TYPED_ARRAY_SUPPORT) {
1639 this[offset] = (value >>> 24)
1640 this[offset + 1] = (value >>> 16)
1641 this[offset + 2] = (value >>> 8)
1642 this[offset + 3] = (value & 0xff)
1643 } else {
1644 objectWriteUInt32(this, value, offset, false)
1645 }
1646 return offset + 4
1647}
1648
1649Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1650 value = +value
1651 offset = offset | 0
1652 if (!noAssert) {
1653 var limit = Math.pow(2, 8 * byteLength - 1)
1654
1655 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1656 }
1657
1658 var i = 0
1659 var mul = 1
1660 var sub = 0
1661 this[offset] = value & 0xFF
1662 while (++i < byteLength && (mul *= 0x100)) {
1663 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1664 sub = 1
1665 }
1666 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1667 }
1668
1669 return offset + byteLength
1670}
1671
1672Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1673 value = +value
1674 offset = offset | 0
1675 if (!noAssert) {
1676 var limit = Math.pow(2, 8 * byteLength - 1)
1677
1678 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1679 }
1680
1681 var i = byteLength - 1
1682 var mul = 1
1683 var sub = 0
1684 this[offset + i] = value & 0xFF
1685 while (--i >= 0 && (mul *= 0x100)) {
1686 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1687 sub = 1
1688 }
1689 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1690 }
1691
1692 return offset + byteLength
1693}
1694
1695Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1696 value = +value
1697 offset = offset | 0
1698 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1699 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1700 if (value < 0) value = 0xff + value + 1
1701 this[offset] = (value & 0xff)
1702 return offset + 1
1703}
1704
1705Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1706 value = +value
1707 offset = offset | 0
1708 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1709 if (Buffer.TYPED_ARRAY_SUPPORT) {
1710 this[offset] = (value & 0xff)
1711 this[offset + 1] = (value >>> 8)
1712 } else {
1713 objectWriteUInt16(this, value, offset, true)
1714 }
1715 return offset + 2
1716}
1717
1718Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1719 value = +value
1720 offset = offset | 0
1721 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1722 if (Buffer.TYPED_ARRAY_SUPPORT) {
1723 this[offset] = (value >>> 8)
1724 this[offset + 1] = (value & 0xff)
1725 } else {
1726 objectWriteUInt16(this, value, offset, false)
1727 }
1728 return offset + 2
1729}
1730
1731Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1732 value = +value
1733 offset = offset | 0
1734 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1735 if (Buffer.TYPED_ARRAY_SUPPORT) {
1736 this[offset] = (value & 0xff)
1737 this[offset + 1] = (value >>> 8)
1738 this[offset + 2] = (value >>> 16)
1739 this[offset + 3] = (value >>> 24)
1740 } else {
1741 objectWriteUInt32(this, value, offset, true)
1742 }
1743 return offset + 4
1744}
1745
1746Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1747 value = +value
1748 offset = offset | 0
1749 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1750 if (value < 0) value = 0xffffffff + value + 1
1751 if (Buffer.TYPED_ARRAY_SUPPORT) {
1752 this[offset] = (value >>> 24)
1753 this[offset + 1] = (value >>> 16)
1754 this[offset + 2] = (value >>> 8)
1755 this[offset + 3] = (value & 0xff)
1756 } else {
1757 objectWriteUInt32(this, value, offset, false)
1758 }
1759 return offset + 4
1760}
1761
1762function checkIEEE754 (buf, value, offset, ext, max, min) {
1763 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1764 if (offset < 0) throw new RangeError('Index out of range')
1765}
1766
1767function writeFloat (buf, value, offset, littleEndian, noAssert) {
1768 if (!noAssert) {
1769 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1770 }
1771 ieee754.write(buf, value, offset, littleEndian, 23, 4)
1772 return offset + 4
1773}
1774
1775Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1776 return writeFloat(this, value, offset, true, noAssert)
1777}
1778
1779Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1780 return writeFloat(this, value, offset, false, noAssert)
1781}
1782
1783function writeDouble (buf, value, offset, littleEndian, noAssert) {
1784 if (!noAssert) {
1785 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1786 }
1787 ieee754.write(buf, value, offset, littleEndian, 52, 8)
1788 return offset + 8
1789}
1790
1791Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1792 return writeDouble(this, value, offset, true, noAssert)
1793}
1794
1795Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1796 return writeDouble(this, value, offset, false, noAssert)
1797}
1798
1799// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1800Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1801 if (!start) start = 0
1802 if (!end && end !== 0) end = this.length
1803 if (targetStart >= target.length) targetStart = target.length
1804 if (!targetStart) targetStart = 0
1805 if (end > 0 && end < start) end = start
1806
1807 // Copy 0 bytes; we're done
1808 if (end === start) return 0
1809 if (target.length === 0 || this.length === 0) return 0
1810
1811 // Fatal error conditions
1812 if (targetStart < 0) {
1813 throw new RangeError('targetStart out of bounds')
1814 }
1815 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1816 if (end < 0) throw new RangeError('sourceEnd out of bounds')
1817
1818 // Are we oob?
1819 if (end > this.length) end = this.length
1820 if (target.length - targetStart < end - start) {
1821 end = target.length - targetStart + start
1822 }
1823
1824 var len = end - start
1825 var i
1826
1827 if (this === target && start < targetStart && targetStart < end) {
1828 // descending copy from end
1829 for (i = len - 1; i >= 0; --i) {
1830 target[i + targetStart] = this[i + start]
1831 }
1832 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1833 // ascending copy from start
1834 for (i = 0; i < len; ++i) {
1835 target[i + targetStart] = this[i + start]
1836 }
1837 } else {
1838 Uint8Array.prototype.set.call(
1839 target,
1840 this.subarray(start, start + len),
1841 targetStart
1842 )
1843 }
1844
1845 return len
1846}
1847
1848// Usage:
1849// buffer.fill(number[, offset[, end]])
1850// buffer.fill(buffer[, offset[, end]])
1851// buffer.fill(string[, offset[, end]][, encoding])
1852Buffer.prototype.fill = function fill (val, start, end, encoding) {
1853 // Handle string cases:
1854 if (typeof val === 'string') {
1855 if (typeof start === 'string') {
1856 encoding = start
1857 start = 0
1858 end = this.length
1859 } else if (typeof end === 'string') {
1860 encoding = end
1861 end = this.length
1862 }
1863 if (val.length === 1) {
1864 var code = val.charCodeAt(0)
1865 if (code < 256) {
1866 val = code
1867 }
1868 }
1869 if (encoding !== undefined && typeof encoding !== 'string') {
1870 throw new TypeError('encoding must be a string')
1871 }
1872 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1873 throw new TypeError('Unknown encoding: ' + encoding)
1874 }
1875 } else if (typeof val === 'number') {
1876 val = val & 255
1877 }
1878
1879 // Invalid ranges are not set to a default, so can range check early.
1880 if (start < 0 || this.length < start || this.length < end) {
1881 throw new RangeError('Out of range index')
1882 }
1883
1884 if (end <= start) {
1885 return this
1886 }
1887
1888 start = start >>> 0
1889 end = end === undefined ? this.length : end >>> 0
1890
1891 if (!val) val = 0
1892
1893 var i
1894 if (typeof val === 'number') {
1895 for (i = start; i < end; ++i) {
1896 this[i] = val
1897 }
1898 } else {
1899 var bytes = Buffer.isBuffer(val)
1900 ? val
1901 : utf8ToBytes(new Buffer(val, encoding).toString())
1902 var len = bytes.length
1903 for (i = 0; i < end - start; ++i) {
1904 this[i + start] = bytes[i % len]
1905 }
1906 }
1907
1908 return this
1909}
1910
1911// HELPER FUNCTIONS
1912// ================
1913
1914var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
1915
1916function base64clean (str) {
1917 // Node strips out invalid characters like \n and \t from the string, base64-js does not
1918 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
1919 // Node converts strings with length < 2 to ''
1920 if (str.length < 2) return ''
1921 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1922 while (str.length % 4 !== 0) {
1923 str = str + '='
1924 }
1925 return str
1926}
1927
1928function stringtrim (str) {
1929 if (str.trim) return str.trim()
1930 return str.replace(/^\s+|\s+$/g, '')
1931}
1932
1933function toHex (n) {
1934 if (n < 16) return '0' + n.toString(16)
1935 return n.toString(16)
1936}
1937
1938function utf8ToBytes (string, units) {
1939 units = units || Infinity
1940 var codePoint
1941 var length = string.length
1942 var leadSurrogate = null
1943 var bytes = []
1944
1945 for (var i = 0; i < length; ++i) {
1946 codePoint = string.charCodeAt(i)
1947
1948 // is surrogate component
1949 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1950 // last char was a lead
1951 if (!leadSurrogate) {
1952 // no lead yet
1953 if (codePoint > 0xDBFF) {
1954 // unexpected trail
1955 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1956 continue
1957 } else if (i + 1 === length) {
1958 // unpaired lead
1959 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1960 continue
1961 }
1962
1963 // valid lead
1964 leadSurrogate = codePoint
1965
1966 continue
1967 }
1968
1969 // 2 leads in a row
1970 if (codePoint < 0xDC00) {
1971 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1972 leadSurrogate = codePoint
1973 continue
1974 }
1975
1976 // valid surrogate pair
1977 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
1978 } else if (leadSurrogate) {
1979 // valid bmp char, but last char was a lead
1980 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1981 }
1982
1983 leadSurrogate = null
1984
1985 // encode utf8
1986 if (codePoint < 0x80) {
1987 if ((units -= 1) < 0) break
1988 bytes.push(codePoint)
1989 } else if (codePoint < 0x800) {
1990 if ((units -= 2) < 0) break
1991 bytes.push(
1992 codePoint >> 0x6 | 0xC0,
1993 codePoint & 0x3F | 0x80
1994 )
1995 } else if (codePoint < 0x10000) {
1996 if ((units -= 3) < 0) break
1997 bytes.push(
1998 codePoint >> 0xC | 0xE0,
1999 codePoint >> 0x6 & 0x3F | 0x80,
2000 codePoint & 0x3F | 0x80
2001 )
2002 } else if (codePoint < 0x110000) {
2003 if ((units -= 4) < 0) break
2004 bytes.push(
2005 codePoint >> 0x12 | 0xF0,
2006 codePoint >> 0xC & 0x3F | 0x80,
2007 codePoint >> 0x6 & 0x3F | 0x80,
2008 codePoint & 0x3F | 0x80
2009 )
2010 } else {
2011 throw new Error('Invalid code point')
2012 }
2013 }
2014
2015 return bytes
2016}
2017
2018function asciiToBytes (str) {
2019 var byteArray = []
2020 for (var i = 0; i < str.length; ++i) {
2021 // Node's code seems to be doing this and not & 0x7F..
2022 byteArray.push(str.charCodeAt(i) & 0xFF)
2023 }
2024 return byteArray
2025}
2026
2027function utf16leToBytes (str, units) {
2028 var c, hi, lo
2029 var byteArray = []
2030 for (var i = 0; i < str.length; ++i) {
2031 if ((units -= 2) < 0) break
2032
2033 c = str.charCodeAt(i)
2034 hi = c >> 8
2035 lo = c % 256
2036 byteArray.push(lo)
2037 byteArray.push(hi)
2038 }
2039
2040 return byteArray
2041}
2042
2043function base64ToBytes (str) {
2044 return base64.toByteArray(base64clean(str))
2045}
2046
2047function blitBuffer (src, dst, offset, length) {
2048 for (var i = 0; i < length; ++i) {
2049 if ((i + offset >= dst.length) || (i >= src.length)) break
2050 dst[i + offset] = src[i]
2051 }
2052 return i
2053}
2054
2055function isnan (val) {
2056 return val !== val // eslint-disable-line no-self-compare
2057}
2058
2059/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
2060
2061/***/ }),
2062
2063/***/ "../../node_modules/ieee754/index.js":
2064/*!******************************************************!*\
2065 !*** /root/amplify-js/node_modules/ieee754/index.js ***!
2066 \******************************************************/
2067/*! no static exports found */
2068/***/ (function(module, exports) {
2069
2070/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
2071exports.read = function (buffer, offset, isLE, mLen, nBytes) {
2072 var e, m
2073 var eLen = (nBytes * 8) - mLen - 1
2074 var eMax = (1 << eLen) - 1
2075 var eBias = eMax >> 1
2076 var nBits = -7
2077 var i = isLE ? (nBytes - 1) : 0
2078 var d = isLE ? -1 : 1
2079 var s = buffer[offset + i]
2080
2081 i += d
2082
2083 e = s & ((1 << (-nBits)) - 1)
2084 s >>= (-nBits)
2085 nBits += eLen
2086 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
2087
2088 m = e & ((1 << (-nBits)) - 1)
2089 e >>= (-nBits)
2090 nBits += mLen
2091 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
2092
2093 if (e === 0) {
2094 e = 1 - eBias
2095 } else if (e === eMax) {
2096 return m ? NaN : ((s ? -1 : 1) * Infinity)
2097 } else {
2098 m = m + Math.pow(2, mLen)
2099 e = e - eBias
2100 }
2101 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
2102}
2103
2104exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
2105 var e, m, c
2106 var eLen = (nBytes * 8) - mLen - 1
2107 var eMax = (1 << eLen) - 1
2108 var eBias = eMax >> 1
2109 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
2110 var i = isLE ? 0 : (nBytes - 1)
2111 var d = isLE ? 1 : -1
2112 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
2113
2114 value = Math.abs(value)
2115
2116 if (isNaN(value) || value === Infinity) {
2117 m = isNaN(value) ? 1 : 0
2118 e = eMax
2119 } else {
2120 e = Math.floor(Math.log(value) / Math.LN2)
2121 if (value * (c = Math.pow(2, -e)) < 1) {
2122 e--
2123 c *= 2
2124 }
2125 if (e + eBias >= 1) {
2126 value += rt / c
2127 } else {
2128 value += rt * Math.pow(2, 1 - eBias)
2129 }
2130 if (value * c >= 2) {
2131 e++
2132 c /= 2
2133 }
2134
2135 if (e + eBias >= eMax) {
2136 m = 0
2137 e = eMax
2138 } else if (e + eBias >= 1) {
2139 m = ((value * c) - 1) * Math.pow(2, mLen)
2140 e = e + eBias
2141 } else {
2142 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
2143 e = 0
2144 }
2145 }
2146
2147 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2148
2149 e = (e << mLen) | m
2150 eLen += mLen
2151 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2152
2153 buffer[offset + i - d] |= s * 128
2154}
2155
2156
2157/***/ }),
2158
2159/***/ "../../node_modules/isarray/index.js":
2160/*!******************************************************!*\
2161 !*** /root/amplify-js/node_modules/isarray/index.js ***!
2162 \******************************************************/
2163/*! no static exports found */
2164/***/ (function(module, exports) {
2165
2166var toString = {}.toString;
2167
2168module.exports = Array.isArray || function (arr) {
2169 return toString.call(arr) == '[object Array]';
2170};
2171
2172
2173/***/ }),
2174
2175/***/ "../../node_modules/isomorphic-unfetch/browser.js":
2176/*!*******************************************************************!*\
2177 !*** /root/amplify-js/node_modules/isomorphic-unfetch/browser.js ***!
2178 \*******************************************************************/
2179/*! no static exports found */
2180/***/ (function(module, exports, __webpack_require__) {
2181
2182module.exports = self.fetch || (self.fetch = __webpack_require__(/*! unfetch */ "../../node_modules/unfetch/dist/unfetch.module.js").default || __webpack_require__(/*! unfetch */ "../../node_modules/unfetch/dist/unfetch.module.js"));
2183
2184
2185/***/ }),
2186
2187/***/ "../../node_modules/js-cookie/src/js.cookie.js":
2188/*!****************************************************************!*\
2189 !*** /root/amplify-js/node_modules/js-cookie/src/js.cookie.js ***!
2190 \****************************************************************/
2191/*! no static exports found */
2192/***/ (function(module, exports, __webpack_require__) {
2193
2194var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
2195 * JavaScript Cookie v2.2.1
2196 * https://github.com/js-cookie/js-cookie
2197 *
2198 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
2199 * Released under the MIT license
2200 */
2201;(function (factory) {
2202 var registeredInModuleLoader;
2203 if (true) {
2204 !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
2205 __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
2206 (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
2207 __WEBPACK_AMD_DEFINE_FACTORY__),
2208 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
2209 registeredInModuleLoader = true;
2210 }
2211 if (true) {
2212 module.exports = factory();
2213 registeredInModuleLoader = true;
2214 }
2215 if (!registeredInModuleLoader) {
2216 var OldCookies = window.Cookies;
2217 var api = window.Cookies = factory();
2218 api.noConflict = function () {
2219 window.Cookies = OldCookies;
2220 return api;
2221 };
2222 }
2223}(function () {
2224 function extend () {
2225 var i = 0;
2226 var result = {};
2227 for (; i < arguments.length; i++) {
2228 var attributes = arguments[ i ];
2229 for (var key in attributes) {
2230 result[key] = attributes[key];
2231 }
2232 }
2233 return result;
2234 }
2235
2236 function decode (s) {
2237 return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
2238 }
2239
2240 function init (converter) {
2241 function api() {}
2242
2243 function set (key, value, attributes) {
2244 if (typeof document === 'undefined') {
2245 return;
2246 }
2247
2248 attributes = extend({
2249 path: '/'
2250 }, api.defaults, attributes);
2251
2252 if (typeof attributes.expires === 'number') {
2253 attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
2254 }
2255
2256 // We're using "expires" because "max-age" is not supported by IE
2257 attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
2258
2259 try {
2260 var result = JSON.stringify(value);
2261 if (/^[\{\[]/.test(result)) {
2262 value = result;
2263 }
2264 } catch (e) {}
2265
2266 value = converter.write ?
2267 converter.write(value, key) :
2268 encodeURIComponent(String(value))
2269 .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
2270
2271 key = encodeURIComponent(String(key))
2272 .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
2273 .replace(/[\(\)]/g, escape);
2274
2275 var stringifiedAttributes = '';
2276 for (var attributeName in attributes) {
2277 if (!attributes[attributeName]) {
2278 continue;
2279 }
2280 stringifiedAttributes += '; ' + attributeName;
2281 if (attributes[attributeName] === true) {
2282 continue;
2283 }
2284
2285 // Considers RFC 6265 section 5.2:
2286 // ...
2287 // 3. If the remaining unparsed-attributes contains a %x3B (";")
2288 // character:
2289 // Consume the characters of the unparsed-attributes up to,
2290 // not including, the first %x3B (";") character.
2291 // ...
2292 stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
2293 }
2294
2295 return (document.cookie = key + '=' + value + stringifiedAttributes);
2296 }
2297
2298 function get (key, json) {
2299 if (typeof document === 'undefined') {
2300 return;
2301 }
2302
2303 var jar = {};
2304 // To prevent the for loop in the first place assign an empty array
2305 // in case there are no cookies at all.
2306 var cookies = document.cookie ? document.cookie.split('; ') : [];
2307 var i = 0;
2308
2309 for (; i < cookies.length; i++) {
2310 var parts = cookies[i].split('=');
2311 var cookie = parts.slice(1).join('=');
2312
2313 if (!json && cookie.charAt(0) === '"') {
2314 cookie = cookie.slice(1, -1);
2315 }
2316
2317 try {
2318 var name = decode(parts[0]);
2319 cookie = (converter.read || converter)(cookie, name) ||
2320 decode(cookie);
2321
2322 if (json) {
2323 try {
2324 cookie = JSON.parse(cookie);
2325 } catch (e) {}
2326 }
2327
2328 jar[name] = cookie;
2329
2330 if (key === name) {
2331 break;
2332 }
2333 } catch (e) {}
2334 }
2335
2336 return key ? jar[key] : jar;
2337 }
2338
2339 api.set = set;
2340 api.get = function (key) {
2341 return get(key, false /* read as raw */);
2342 };
2343 api.getJSON = function (key) {
2344 return get(key, true /* read as json */);
2345 };
2346 api.remove = function (key, attributes) {
2347 set(key, '', extend(attributes, {
2348 expires: -1
2349 }));
2350 };
2351
2352 api.defaults = {};
2353
2354 api.withConverter = init;
2355
2356 return api;
2357 }
2358
2359 return init(function () {});
2360}));
2361
2362
2363/***/ }),
2364
2365/***/ "../../node_modules/punycode/punycode.js":
2366/*!**********************************************************!*\
2367 !*** /root/amplify-js/node_modules/punycode/punycode.js ***!
2368 \**********************************************************/
2369/*! no static exports found */
2370/***/ (function(module, exports, __webpack_require__) {
2371
2372/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */
2373;(function(root) {
2374
2375 /** Detect free variables */
2376 var freeExports = true && exports &&
2377 !exports.nodeType && exports;
2378 var freeModule = true && module &&
2379 !module.nodeType && module;
2380 var freeGlobal = typeof global == 'object' && global;
2381 if (
2382 freeGlobal.global === freeGlobal ||
2383 freeGlobal.window === freeGlobal ||
2384 freeGlobal.self === freeGlobal
2385 ) {
2386 root = freeGlobal;
2387 }
2388
2389 /**
2390 * The `punycode` object.
2391 * @name punycode
2392 * @type Object
2393 */
2394 var punycode,
2395
2396 /** Highest positive signed 32-bit float value */
2397 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
2398
2399 /** Bootstring parameters */
2400 base = 36,
2401 tMin = 1,
2402 tMax = 26,
2403 skew = 38,
2404 damp = 700,
2405 initialBias = 72,
2406 initialN = 128, // 0x80
2407 delimiter = '-', // '\x2D'
2408
2409 /** Regular expressions */
2410 regexPunycode = /^xn--/,
2411 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
2412 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
2413
2414 /** Error messages */
2415 errors = {
2416 'overflow': 'Overflow: input needs wider integers to process',
2417 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
2418 'invalid-input': 'Invalid input'
2419 },
2420
2421 /** Convenience shortcuts */
2422 baseMinusTMin = base - tMin,
2423 floor = Math.floor,
2424 stringFromCharCode = String.fromCharCode,
2425
2426 /** Temporary variable */
2427 key;
2428
2429 /*--------------------------------------------------------------------------*/
2430
2431 /**
2432 * A generic error utility function.
2433 * @private
2434 * @param {String} type The error type.
2435 * @returns {Error} Throws a `RangeError` with the applicable error message.
2436 */
2437 function error(type) {
2438 throw new RangeError(errors[type]);
2439 }
2440
2441 /**
2442 * A generic `Array#map` utility function.
2443 * @private
2444 * @param {Array} array The array to iterate over.
2445 * @param {Function} callback The function that gets called for every array
2446 * item.
2447 * @returns {Array} A new array of values returned by the callback function.
2448 */
2449 function map(array, fn) {
2450 var length = array.length;
2451 var result = [];
2452 while (length--) {
2453 result[length] = fn(array[length]);
2454 }
2455 return result;
2456 }
2457
2458 /**
2459 * A simple `Array#map`-like wrapper to work with domain name strings or email
2460 * addresses.
2461 * @private
2462 * @param {String} domain The domain name or email address.
2463 * @param {Function} callback The function that gets called for every
2464 * character.
2465 * @returns {Array} A new string of characters returned by the callback
2466 * function.
2467 */
2468 function mapDomain(string, fn) {
2469 var parts = string.split('@');
2470 var result = '';
2471 if (parts.length > 1) {
2472 // In email addresses, only the domain name should be punycoded. Leave
2473 // the local part (i.e. everything up to `@`) intact.
2474 result = parts[0] + '@';
2475 string = parts[1];
2476 }
2477 // Avoid `split(regex)` for IE8 compatibility. See #17.
2478 string = string.replace(regexSeparators, '\x2E');
2479 var labels = string.split('.');
2480 var encoded = map(labels, fn).join('.');
2481 return result + encoded;
2482 }
2483
2484 /**
2485 * Creates an array containing the numeric code points of each Unicode
2486 * character in the string. While JavaScript uses UCS-2 internally,
2487 * this function will convert a pair of surrogate halves (each of which
2488 * UCS-2 exposes as separate characters) into a single code point,
2489 * matching UTF-16.
2490 * @see `punycode.ucs2.encode`
2491 * @see <https://mathiasbynens.be/notes/javascript-encoding>
2492 * @memberOf punycode.ucs2
2493 * @name decode
2494 * @param {String} string The Unicode input string (UCS-2).
2495 * @returns {Array} The new array of code points.
2496 */
2497 function ucs2decode(string) {
2498 var output = [],
2499 counter = 0,
2500 length = string.length,
2501 value,
2502 extra;
2503 while (counter < length) {
2504 value = string.charCodeAt(counter++);
2505 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
2506 // high surrogate, and there is a next character
2507 extra = string.charCodeAt(counter++);
2508 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
2509 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
2510 } else {
2511 // unmatched surrogate; only append this code unit, in case the next
2512 // code unit is the high surrogate of a surrogate pair
2513 output.push(value);
2514 counter--;
2515 }
2516 } else {
2517 output.push(value);
2518 }
2519 }
2520 return output;
2521 }
2522
2523 /**
2524 * Creates a string based on an array of numeric code points.
2525 * @see `punycode.ucs2.decode`
2526 * @memberOf punycode.ucs2
2527 * @name encode
2528 * @param {Array} codePoints The array of numeric code points.
2529 * @returns {String} The new Unicode string (UCS-2).
2530 */
2531 function ucs2encode(array) {
2532 return map(array, function(value) {
2533 var output = '';
2534 if (value > 0xFFFF) {
2535 value -= 0x10000;
2536 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
2537 value = 0xDC00 | value & 0x3FF;
2538 }
2539 output += stringFromCharCode(value);
2540 return output;
2541 }).join('');
2542 }
2543
2544 /**
2545 * Converts a basic code point into a digit/integer.
2546 * @see `digitToBasic()`
2547 * @private
2548 * @param {Number} codePoint The basic numeric code point value.
2549 * @returns {Number} The numeric value of a basic code point (for use in
2550 * representing integers) in the range `0` to `base - 1`, or `base` if
2551 * the code point does not represent a value.
2552 */
2553 function basicToDigit(codePoint) {
2554 if (codePoint - 48 < 10) {
2555 return codePoint - 22;
2556 }
2557 if (codePoint - 65 < 26) {
2558 return codePoint - 65;
2559 }
2560 if (codePoint - 97 < 26) {
2561 return codePoint - 97;
2562 }
2563 return base;
2564 }
2565
2566 /**
2567 * Converts a digit/integer into a basic code point.
2568 * @see `basicToDigit()`
2569 * @private
2570 * @param {Number} digit The numeric value of a basic code point.
2571 * @returns {Number} The basic code point whose value (when used for
2572 * representing integers) is `digit`, which needs to be in the range
2573 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
2574 * used; else, the lowercase form is used. The behavior is undefined
2575 * if `flag` is non-zero and `digit` has no uppercase form.
2576 */
2577 function digitToBasic(digit, flag) {
2578 // 0..25 map to ASCII a..z or A..Z
2579 // 26..35 map to ASCII 0..9
2580 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
2581 }
2582
2583 /**
2584 * Bias adaptation function as per section 3.4 of RFC 3492.
2585 * https://tools.ietf.org/html/rfc3492#section-3.4
2586 * @private
2587 */
2588 function adapt(delta, numPoints, firstTime) {
2589 var k = 0;
2590 delta = firstTime ? floor(delta / damp) : delta >> 1;
2591 delta += floor(delta / numPoints);
2592 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
2593 delta = floor(delta / baseMinusTMin);
2594 }
2595 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
2596 }
2597
2598 /**
2599 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
2600 * symbols.
2601 * @memberOf punycode
2602 * @param {String} input The Punycode string of ASCII-only symbols.
2603 * @returns {String} The resulting string of Unicode symbols.
2604 */
2605 function decode(input) {
2606 // Don't use UCS-2
2607 var output = [],
2608 inputLength = input.length,
2609 out,
2610 i = 0,
2611 n = initialN,
2612 bias = initialBias,
2613 basic,
2614 j,
2615 index,
2616 oldi,
2617 w,
2618 k,
2619 digit,
2620 t,
2621 /** Cached calculation results */
2622 baseMinusT;
2623
2624 // Handle the basic code points: let `basic` be the number of input code
2625 // points before the last delimiter, or `0` if there is none, then copy
2626 // the first basic code points to the output.
2627
2628 basic = input.lastIndexOf(delimiter);
2629 if (basic < 0) {
2630 basic = 0;
2631 }
2632
2633 for (j = 0; j < basic; ++j) {
2634 // if it's not a basic code point
2635 if (input.charCodeAt(j) >= 0x80) {
2636 error('not-basic');
2637 }
2638 output.push(input.charCodeAt(j));
2639 }
2640
2641 // Main decoding loop: start just after the last delimiter if any basic code
2642 // points were copied; start at the beginning otherwise.
2643
2644 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
2645
2646 // `index` is the index of the next character to be consumed.
2647 // Decode a generalized variable-length integer into `delta`,
2648 // which gets added to `i`. The overflow checking is easier
2649 // if we increase `i` as we go, then subtract off its starting
2650 // value at the end to obtain `delta`.
2651 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
2652
2653 if (index >= inputLength) {
2654 error('invalid-input');
2655 }
2656
2657 digit = basicToDigit(input.charCodeAt(index++));
2658
2659 if (digit >= base || digit > floor((maxInt - i) / w)) {
2660 error('overflow');
2661 }
2662
2663 i += digit * w;
2664 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
2665
2666 if (digit < t) {
2667 break;
2668 }
2669
2670 baseMinusT = base - t;
2671 if (w > floor(maxInt / baseMinusT)) {
2672 error('overflow');
2673 }
2674
2675 w *= baseMinusT;
2676
2677 }
2678
2679 out = output.length + 1;
2680 bias = adapt(i - oldi, out, oldi == 0);
2681
2682 // `i` was supposed to wrap around from `out` to `0`,
2683 // incrementing `n` each time, so we'll fix that now:
2684 if (floor(i / out) > maxInt - n) {
2685 error('overflow');
2686 }
2687
2688 n += floor(i / out);
2689 i %= out;
2690
2691 // Insert `n` at position `i` of the output
2692 output.splice(i++, 0, n);
2693
2694 }
2695
2696 return ucs2encode(output);
2697 }
2698
2699 /**
2700 * Converts a string of Unicode symbols (e.g. a domain name label) to a
2701 * Punycode string of ASCII-only symbols.
2702 * @memberOf punycode
2703 * @param {String} input The string of Unicode symbols.
2704 * @returns {String} The resulting Punycode string of ASCII-only symbols.
2705 */
2706 function encode(input) {
2707 var n,
2708 delta,
2709 handledCPCount,
2710 basicLength,
2711 bias,
2712 j,
2713 m,
2714 q,
2715 k,
2716 t,
2717 currentValue,
2718 output = [],
2719 /** `inputLength` will hold the number of code points in `input`. */
2720 inputLength,
2721 /** Cached calculation results */
2722 handledCPCountPlusOne,
2723 baseMinusT,
2724 qMinusT;
2725
2726 // Convert the input in UCS-2 to Unicode
2727 input = ucs2decode(input);
2728
2729 // Cache the length
2730 inputLength = input.length;
2731
2732 // Initialize the state
2733 n = initialN;
2734 delta = 0;
2735 bias = initialBias;
2736
2737 // Handle the basic code points
2738 for (j = 0; j < inputLength; ++j) {
2739 currentValue = input[j];
2740 if (currentValue < 0x80) {
2741 output.push(stringFromCharCode(currentValue));
2742 }
2743 }
2744
2745 handledCPCount = basicLength = output.length;
2746
2747 // `handledCPCount` is the number of code points that have been handled;
2748 // `basicLength` is the number of basic code points.
2749
2750 // Finish the basic string - if it is not empty - with a delimiter
2751 if (basicLength) {
2752 output.push(delimiter);
2753 }
2754
2755 // Main encoding loop:
2756 while (handledCPCount < inputLength) {
2757
2758 // All non-basic code points < n have been handled already. Find the next
2759 // larger one:
2760 for (m = maxInt, j = 0; j < inputLength; ++j) {
2761 currentValue = input[j];
2762 if (currentValue >= n && currentValue < m) {
2763 m = currentValue;
2764 }
2765 }
2766
2767 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
2768 // but guard against overflow
2769 handledCPCountPlusOne = handledCPCount + 1;
2770 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
2771 error('overflow');
2772 }
2773
2774 delta += (m - n) * handledCPCountPlusOne;
2775 n = m;
2776
2777 for (j = 0; j < inputLength; ++j) {
2778 currentValue = input[j];
2779
2780 if (currentValue < n && ++delta > maxInt) {
2781 error('overflow');
2782 }
2783
2784 if (currentValue == n) {
2785 // Represent delta as a generalized variable-length integer
2786 for (q = delta, k = base; /* no condition */; k += base) {
2787 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
2788 if (q < t) {
2789 break;
2790 }
2791 qMinusT = q - t;
2792 baseMinusT = base - t;
2793 output.push(
2794 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
2795 );
2796 q = floor(qMinusT / baseMinusT);
2797 }
2798
2799 output.push(stringFromCharCode(digitToBasic(q, 0)));
2800 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
2801 delta = 0;
2802 ++handledCPCount;
2803 }
2804 }
2805
2806 ++delta;
2807 ++n;
2808
2809 }
2810 return output.join('');
2811 }
2812
2813 /**
2814 * Converts a Punycode string representing a domain name or an email address
2815 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
2816 * it doesn't matter if you call it on a string that has already been
2817 * converted to Unicode.
2818 * @memberOf punycode
2819 * @param {String} input The Punycoded domain name or email address to
2820 * convert to Unicode.
2821 * @returns {String} The Unicode representation of the given Punycode
2822 * string.
2823 */
2824 function toUnicode(input) {
2825 return mapDomain(input, function(string) {
2826 return regexPunycode.test(string)
2827 ? decode(string.slice(4).toLowerCase())
2828 : string;
2829 });
2830 }
2831
2832 /**
2833 * Converts a Unicode string representing a domain name or an email address to
2834 * Punycode. Only the non-ASCII parts of the domain name will be converted,
2835 * i.e. it doesn't matter if you call it with a domain that's already in
2836 * ASCII.
2837 * @memberOf punycode
2838 * @param {String} input The domain name or email address to convert, as a
2839 * Unicode string.
2840 * @returns {String} The Punycode representation of the given domain name or
2841 * email address.
2842 */
2843 function toASCII(input) {
2844 return mapDomain(input, function(string) {
2845 return regexNonASCII.test(string)
2846 ? 'xn--' + encode(string)
2847 : string;
2848 });
2849 }
2850
2851 /*--------------------------------------------------------------------------*/
2852
2853 /** Define the public API */
2854 punycode = {
2855 /**
2856 * A string representing the current Punycode.js version number.
2857 * @memberOf punycode
2858 * @type String
2859 */
2860 'version': '1.4.1',
2861 /**
2862 * An object of methods to convert from JavaScript's internal character
2863 * representation (UCS-2) to Unicode code points, and back.
2864 * @see <https://mathiasbynens.be/notes/javascript-encoding>
2865 * @memberOf punycode
2866 * @type Object
2867 */
2868 'ucs2': {
2869 'decode': ucs2decode,
2870 'encode': ucs2encode
2871 },
2872 'decode': decode,
2873 'encode': encode,
2874 'toASCII': toASCII,
2875 'toUnicode': toUnicode
2876 };
2877
2878 /** Expose `punycode` */
2879 // Some AMD build optimizers, like r.js, check for specific condition patterns
2880 // like the following:
2881 if (
2882 true
2883 ) {
2884 !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
2885 return punycode;
2886 }).call(exports, __webpack_require__, exports, module),
2887 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
2888 } else {}
2889
2890}(this));
2891
2892/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "../../node_modules/webpack/buildin/module.js")(module), __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
2893
2894/***/ }),
2895
2896/***/ "../../node_modules/querystring-es3/decode.js":
2897/*!***************************************************************!*\
2898 !*** /root/amplify-js/node_modules/querystring-es3/decode.js ***!
2899 \***************************************************************/
2900/*! no static exports found */
2901/***/ (function(module, exports, __webpack_require__) {
2902
2903"use strict";
2904// Copyright Joyent, Inc. and other Node contributors.
2905//
2906// Permission is hereby granted, free of charge, to any person obtaining a
2907// copy of this software and associated documentation files (the
2908// "Software"), to deal in the Software without restriction, including
2909// without limitation the rights to use, copy, modify, merge, publish,
2910// distribute, sublicense, and/or sell copies of the Software, and to permit
2911// persons to whom the Software is furnished to do so, subject to the
2912// following conditions:
2913//
2914// The above copyright notice and this permission notice shall be included
2915// in all copies or substantial portions of the Software.
2916//
2917// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2918// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2919// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2920// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2921// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2922// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2923// USE OR OTHER DEALINGS IN THE SOFTWARE.
2924
2925
2926
2927// If obj.hasOwnProperty has been overridden, then calling
2928// obj.hasOwnProperty(prop) will break.
2929// See: https://github.com/joyent/node/issues/1707
2930function hasOwnProperty(obj, prop) {
2931 return Object.prototype.hasOwnProperty.call(obj, prop);
2932}
2933
2934module.exports = function(qs, sep, eq, options) {
2935 sep = sep || '&';
2936 eq = eq || '=';
2937 var obj = {};
2938
2939 if (typeof qs !== 'string' || qs.length === 0) {
2940 return obj;
2941 }
2942
2943 var regexp = /\+/g;
2944 qs = qs.split(sep);
2945
2946 var maxKeys = 1000;
2947 if (options && typeof options.maxKeys === 'number') {
2948 maxKeys = options.maxKeys;
2949 }
2950
2951 var len = qs.length;
2952 // maxKeys <= 0 means that we should not limit keys count
2953 if (maxKeys > 0 && len > maxKeys) {
2954 len = maxKeys;
2955 }
2956
2957 for (var i = 0; i < len; ++i) {
2958 var x = qs[i].replace(regexp, '%20'),
2959 idx = x.indexOf(eq),
2960 kstr, vstr, k, v;
2961
2962 if (idx >= 0) {
2963 kstr = x.substr(0, idx);
2964 vstr = x.substr(idx + 1);
2965 } else {
2966 kstr = x;
2967 vstr = '';
2968 }
2969
2970 k = decodeURIComponent(kstr);
2971 v = decodeURIComponent(vstr);
2972
2973 if (!hasOwnProperty(obj, k)) {
2974 obj[k] = v;
2975 } else if (isArray(obj[k])) {
2976 obj[k].push(v);
2977 } else {
2978 obj[k] = [obj[k], v];
2979 }
2980 }
2981
2982 return obj;
2983};
2984
2985var isArray = Array.isArray || function (xs) {
2986 return Object.prototype.toString.call(xs) === '[object Array]';
2987};
2988
2989
2990/***/ }),
2991
2992/***/ "../../node_modules/querystring-es3/encode.js":
2993/*!***************************************************************!*\
2994 !*** /root/amplify-js/node_modules/querystring-es3/encode.js ***!
2995 \***************************************************************/
2996/*! no static exports found */
2997/***/ (function(module, exports, __webpack_require__) {
2998
2999"use strict";
3000// Copyright Joyent, Inc. and other Node contributors.
3001//
3002// Permission is hereby granted, free of charge, to any person obtaining a
3003// copy of this software and associated documentation files (the
3004// "Software"), to deal in the Software without restriction, including
3005// without limitation the rights to use, copy, modify, merge, publish,
3006// distribute, sublicense, and/or sell copies of the Software, and to permit
3007// persons to whom the Software is furnished to do so, subject to the
3008// following conditions:
3009//
3010// The above copyright notice and this permission notice shall be included
3011// in all copies or substantial portions of the Software.
3012//
3013// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3014// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3015// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3016// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3017// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3018// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3019// USE OR OTHER DEALINGS IN THE SOFTWARE.
3020
3021
3022
3023var stringifyPrimitive = function(v) {
3024 switch (typeof v) {
3025 case 'string':
3026 return v;
3027
3028 case 'boolean':
3029 return v ? 'true' : 'false';
3030
3031 case 'number':
3032 return isFinite(v) ? v : '';
3033
3034 default:
3035 return '';
3036 }
3037};
3038
3039module.exports = function(obj, sep, eq, name) {
3040 sep = sep || '&';
3041 eq = eq || '=';
3042 if (obj === null) {
3043 obj = undefined;
3044 }
3045
3046 if (typeof obj === 'object') {
3047 return map(objectKeys(obj), function(k) {
3048 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
3049 if (isArray(obj[k])) {
3050 return map(obj[k], function(v) {
3051 return ks + encodeURIComponent(stringifyPrimitive(v));
3052 }).join(sep);
3053 } else {
3054 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
3055 }
3056 }).join(sep);
3057
3058 }
3059
3060 if (!name) return '';
3061 return encodeURIComponent(stringifyPrimitive(name)) + eq +
3062 encodeURIComponent(stringifyPrimitive(obj));
3063};
3064
3065var isArray = Array.isArray || function (xs) {
3066 return Object.prototype.toString.call(xs) === '[object Array]';
3067};
3068
3069function map (xs, f) {
3070 if (xs.map) return xs.map(f);
3071 var res = [];
3072 for (var i = 0; i < xs.length; i++) {
3073 res.push(f(xs[i], i));
3074 }
3075 return res;
3076}
3077
3078var objectKeys = Object.keys || function (obj) {
3079 var res = [];
3080 for (var key in obj) {
3081 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
3082 }
3083 return res;
3084};
3085
3086
3087/***/ }),
3088
3089/***/ "../../node_modules/querystring-es3/index.js":
3090/*!**************************************************************!*\
3091 !*** /root/amplify-js/node_modules/querystring-es3/index.js ***!
3092 \**************************************************************/
3093/*! no static exports found */
3094/***/ (function(module, exports, __webpack_require__) {
3095
3096"use strict";
3097
3098
3099exports.decode = exports.parse = __webpack_require__(/*! ./decode */ "../../node_modules/querystring-es3/decode.js");
3100exports.encode = exports.stringify = __webpack_require__(/*! ./encode */ "../../node_modules/querystring-es3/encode.js");
3101
3102
3103/***/ }),
3104
3105/***/ "../../node_modules/unfetch/dist/unfetch.module.js":
3106/*!********************************************************************!*\
3107 !*** /root/amplify-js/node_modules/unfetch/dist/unfetch.module.js ***!
3108 \********************************************************************/
3109/*! exports provided: default */
3110/***/ (function(module, __webpack_exports__, __webpack_require__) {
3111
3112"use strict";
3113__webpack_require__.r(__webpack_exports__);
3114/* harmony default export */ __webpack_exports__["default"] = (function(e,n){return n=n||{},new Promise(function(t,r){var s=new XMLHttpRequest,o=[],u=[],i={},a=function(){return{ok:2==(s.status/100|0),statusText:s.statusText,status:s.status,url:s.responseURL,text:function(){return Promise.resolve(s.responseText)},json:function(){return Promise.resolve(s.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([s.response]))},clone:a,headers:{keys:function(){return o},entries:function(){return u},get:function(e){return i[e.toLowerCase()]},has:function(e){return e.toLowerCase()in i}}}};for(var l in s.open(n.method||"get",e,!0),s.onload=function(){s.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,n,t){o.push(n=n.toLowerCase()),u.push([n,t]),i[n]=i[n]?i[n]+","+t:t}),t(a())},s.onerror=r,s.withCredentials="include"==n.credentials,n.headers)s.setRequestHeader(l,n.headers[l]);s.send(n.body||null)})});
3115//# sourceMappingURL=unfetch.module.js.map
3116
3117
3118/***/ }),
3119
3120/***/ "../../node_modules/url/url.js":
3121/*!************************************************!*\
3122 !*** /root/amplify-js/node_modules/url/url.js ***!
3123 \************************************************/
3124/*! no static exports found */
3125/***/ (function(module, exports, __webpack_require__) {
3126
3127"use strict";
3128// Copyright Joyent, Inc. and other Node contributors.
3129//
3130// Permission is hereby granted, free of charge, to any person obtaining a
3131// copy of this software and associated documentation files (the
3132// "Software"), to deal in the Software without restriction, including
3133// without limitation the rights to use, copy, modify, merge, publish,
3134// distribute, sublicense, and/or sell copies of the Software, and to permit
3135// persons to whom the Software is furnished to do so, subject to the
3136// following conditions:
3137//
3138// The above copyright notice and this permission notice shall be included
3139// in all copies or substantial portions of the Software.
3140//
3141// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3142// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3143// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3144// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3145// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3146// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3147// USE OR OTHER DEALINGS IN THE SOFTWARE.
3148
3149
3150
3151var punycode = __webpack_require__(/*! punycode */ "../../node_modules/punycode/punycode.js");
3152var util = __webpack_require__(/*! ./util */ "../../node_modules/url/util.js");
3153
3154exports.parse = urlParse;
3155exports.resolve = urlResolve;
3156exports.resolveObject = urlResolveObject;
3157exports.format = urlFormat;
3158
3159exports.Url = Url;
3160
3161function Url() {
3162 this.protocol = null;
3163 this.slashes = null;
3164 this.auth = null;
3165 this.host = null;
3166 this.port = null;
3167 this.hostname = null;
3168 this.hash = null;
3169 this.search = null;
3170 this.query = null;
3171 this.pathname = null;
3172 this.path = null;
3173 this.href = null;
3174}
3175
3176// Reference: RFC 3986, RFC 1808, RFC 2396
3177
3178// define these here so at least they only have to be
3179// compiled once on the first module load.
3180var protocolPattern = /^([a-z0-9.+-]+:)/i,
3181 portPattern = /:[0-9]*$/,
3182
3183 // Special case for a simple path URL
3184 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
3185
3186 // RFC 2396: characters reserved for delimiting URLs.
3187 // We actually just auto-escape these.
3188 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
3189
3190 // RFC 2396: characters not allowed for various reasons.
3191 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
3192
3193 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
3194 autoEscape = ['\''].concat(unwise),
3195 // Characters that are never ever allowed in a hostname.
3196 // Note that any invalid chars are also handled, but these
3197 // are the ones that are *expected* to be seen, so we fast-path
3198 // them.
3199 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
3200 hostEndingChars = ['/', '?', '#'],
3201 hostnameMaxLen = 255,
3202 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
3203 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
3204 // protocols that can allow "unsafe" and "unwise" chars.
3205 unsafeProtocol = {
3206 'javascript': true,
3207 'javascript:': true
3208 },
3209 // protocols that never have a hostname.
3210 hostlessProtocol = {
3211 'javascript': true,
3212 'javascript:': true
3213 },
3214 // protocols that always contain a // bit.
3215 slashedProtocol = {
3216 'http': true,
3217 'https': true,
3218 'ftp': true,
3219 'gopher': true,
3220 'file': true,
3221 'http:': true,
3222 'https:': true,
3223 'ftp:': true,
3224 'gopher:': true,
3225 'file:': true
3226 },
3227 querystring = __webpack_require__(/*! querystring */ "../../node_modules/querystring-es3/index.js");
3228
3229function urlParse(url, parseQueryString, slashesDenoteHost) {
3230 if (url && util.isObject(url) && url instanceof Url) return url;
3231
3232 var u = new Url;
3233 u.parse(url, parseQueryString, slashesDenoteHost);
3234 return u;
3235}
3236
3237Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
3238 if (!util.isString(url)) {
3239 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
3240 }
3241
3242 // Copy chrome, IE, opera backslash-handling behavior.
3243 // Back slashes before the query string get converted to forward slashes
3244 // See: https://code.google.com/p/chromium/issues/detail?id=25916
3245 var queryIndex = url.indexOf('?'),
3246 splitter =
3247 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
3248 uSplit = url.split(splitter),
3249 slashRegex = /\\/g;
3250 uSplit[0] = uSplit[0].replace(slashRegex, '/');
3251 url = uSplit.join(splitter);
3252
3253 var rest = url;
3254
3255 // trim before proceeding.
3256 // This is to support parse stuff like " http://foo.com \n"
3257 rest = rest.trim();
3258
3259 if (!slashesDenoteHost && url.split('#').length === 1) {
3260 // Try fast path regexp
3261 var simplePath = simplePathPattern.exec(rest);
3262 if (simplePath) {
3263 this.path = rest;
3264 this.href = rest;
3265 this.pathname = simplePath[1];
3266 if (simplePath[2]) {
3267 this.search = simplePath[2];
3268 if (parseQueryString) {
3269 this.query = querystring.parse(this.search.substr(1));
3270 } else {
3271 this.query = this.search.substr(1);
3272 }
3273 } else if (parseQueryString) {
3274 this.search = '';
3275 this.query = {};
3276 }
3277 return this;
3278 }
3279 }
3280
3281 var proto = protocolPattern.exec(rest);
3282 if (proto) {
3283 proto = proto[0];
3284 var lowerProto = proto.toLowerCase();
3285 this.protocol = lowerProto;
3286 rest = rest.substr(proto.length);
3287 }
3288
3289 // figure out if it's got a host
3290 // user@server is *always* interpreted as a hostname, and url
3291 // resolution will treat //foo/bar as host=foo,path=bar because that's
3292 // how the browser resolves relative URLs.
3293 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
3294 var slashes = rest.substr(0, 2) === '//';
3295 if (slashes && !(proto && hostlessProtocol[proto])) {
3296 rest = rest.substr(2);
3297 this.slashes = true;
3298 }
3299 }
3300
3301 if (!hostlessProtocol[proto] &&
3302 (slashes || (proto && !slashedProtocol[proto]))) {
3303
3304 // there's a hostname.
3305 // the first instance of /, ?, ;, or # ends the host.
3306 //
3307 // If there is an @ in the hostname, then non-host chars *are* allowed
3308 // to the left of the last @ sign, unless some host-ending character
3309 // comes *before* the @-sign.
3310 // URLs are obnoxious.
3311 //
3312 // ex:
3313 // http://a@b@c/ => user:a@b host:c
3314 // http://a@b?@c => user:a host:c path:/?@c
3315
3316 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
3317 // Review our test case against browsers more comprehensively.
3318
3319 // find the first instance of any hostEndingChars
3320 var hostEnd = -1;
3321 for (var i = 0; i < hostEndingChars.length; i++) {
3322 var hec = rest.indexOf(hostEndingChars[i]);
3323 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
3324 hostEnd = hec;
3325 }
3326
3327 // at this point, either we have an explicit point where the
3328 // auth portion cannot go past, or the last @ char is the decider.
3329 var auth, atSign;
3330 if (hostEnd === -1) {
3331 // atSign can be anywhere.
3332 atSign = rest.lastIndexOf('@');
3333 } else {
3334 // atSign must be in auth portion.
3335 // http://a@b/c@d => host:b auth:a path:/c@d
3336 atSign = rest.lastIndexOf('@', hostEnd);
3337 }
3338
3339 // Now we have a portion which is definitely the auth.
3340 // Pull that off.
3341 if (atSign !== -1) {
3342 auth = rest.slice(0, atSign);
3343 rest = rest.slice(atSign + 1);
3344 this.auth = decodeURIComponent(auth);
3345 }
3346
3347 // the host is the remaining to the left of the first non-host char
3348 hostEnd = -1;
3349 for (var i = 0; i < nonHostChars.length; i++) {
3350 var hec = rest.indexOf(nonHostChars[i]);
3351 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
3352 hostEnd = hec;
3353 }
3354 // if we still have not hit it, then the entire thing is a host.
3355 if (hostEnd === -1)
3356 hostEnd = rest.length;
3357
3358 this.host = rest.slice(0, hostEnd);
3359 rest = rest.slice(hostEnd);
3360
3361 // pull out port.
3362 this.parseHost();
3363
3364 // we've indicated that there is a hostname,
3365 // so even if it's empty, it has to be present.
3366 this.hostname = this.hostname || '';
3367
3368 // if hostname begins with [ and ends with ]
3369 // assume that it's an IPv6 address.
3370 var ipv6Hostname = this.hostname[0] === '[' &&
3371 this.hostname[this.hostname.length - 1] === ']';
3372
3373 // validate a little.
3374 if (!ipv6Hostname) {
3375 var hostparts = this.hostname.split(/\./);
3376 for (var i = 0, l = hostparts.length; i < l; i++) {
3377 var part = hostparts[i];
3378 if (!part) continue;
3379 if (!part.match(hostnamePartPattern)) {
3380 var newpart = '';
3381 for (var j = 0, k = part.length; j < k; j++) {
3382 if (part.charCodeAt(j) > 127) {
3383 // we replace non-ASCII char with a temporary placeholder
3384 // we need this to make sure size of hostname is not
3385 // broken by replacing non-ASCII by nothing
3386 newpart += 'x';
3387 } else {
3388 newpart += part[j];
3389 }
3390 }
3391 // we test again with ASCII char only
3392 if (!newpart.match(hostnamePartPattern)) {
3393 var validParts = hostparts.slice(0, i);
3394 var notHost = hostparts.slice(i + 1);
3395 var bit = part.match(hostnamePartStart);
3396 if (bit) {
3397 validParts.push(bit[1]);
3398 notHost.unshift(bit[2]);
3399 }
3400 if (notHost.length) {
3401 rest = '/' + notHost.join('.') + rest;
3402 }
3403 this.hostname = validParts.join('.');
3404 break;
3405 }
3406 }
3407 }
3408 }
3409
3410 if (this.hostname.length > hostnameMaxLen) {
3411 this.hostname = '';
3412 } else {
3413 // hostnames are always lower case.
3414 this.hostname = this.hostname.toLowerCase();
3415 }
3416
3417 if (!ipv6Hostname) {
3418 // IDNA Support: Returns a punycoded representation of "domain".
3419 // It only converts parts of the domain name that
3420 // have non-ASCII characters, i.e. it doesn't matter if
3421 // you call it with a domain that already is ASCII-only.
3422 this.hostname = punycode.toASCII(this.hostname);
3423 }
3424
3425 var p = this.port ? ':' + this.port : '';
3426 var h = this.hostname || '';
3427 this.host = h + p;
3428 this.href += this.host;
3429
3430 // strip [ and ] from the hostname
3431 // the host field still retains them, though
3432 if (ipv6Hostname) {
3433 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
3434 if (rest[0] !== '/') {
3435 rest = '/' + rest;
3436 }
3437 }
3438 }
3439
3440 // now rest is set to the post-host stuff.
3441 // chop off any delim chars.
3442 if (!unsafeProtocol[lowerProto]) {
3443
3444 // First, make 100% sure that any "autoEscape" chars get
3445 // escaped, even if encodeURIComponent doesn't think they
3446 // need to be.
3447 for (var i = 0, l = autoEscape.length; i < l; i++) {
3448 var ae = autoEscape[i];
3449 if (rest.indexOf(ae) === -1)
3450 continue;
3451 var esc = encodeURIComponent(ae);
3452 if (esc === ae) {
3453 esc = escape(ae);
3454 }
3455 rest = rest.split(ae).join(esc);
3456 }
3457 }
3458
3459
3460 // chop off from the tail first.
3461 var hash = rest.indexOf('#');
3462 if (hash !== -1) {
3463 // got a fragment string.
3464 this.hash = rest.substr(hash);
3465 rest = rest.slice(0, hash);
3466 }
3467 var qm = rest.indexOf('?');
3468 if (qm !== -1) {
3469 this.search = rest.substr(qm);
3470 this.query = rest.substr(qm + 1);
3471 if (parseQueryString) {
3472 this.query = querystring.parse(this.query);
3473 }
3474 rest = rest.slice(0, qm);
3475 } else if (parseQueryString) {
3476 // no query string, but parseQueryString still requested
3477 this.search = '';
3478 this.query = {};
3479 }
3480 if (rest) this.pathname = rest;
3481 if (slashedProtocol[lowerProto] &&
3482 this.hostname && !this.pathname) {
3483 this.pathname = '/';
3484 }
3485
3486 //to support http.request
3487 if (this.pathname || this.search) {
3488 var p = this.pathname || '';
3489 var s = this.search || '';
3490 this.path = p + s;
3491 }
3492
3493 // finally, reconstruct the href based on what has been validated.
3494 this.href = this.format();
3495 return this;
3496};
3497
3498// format a parsed object into a url string
3499function urlFormat(obj) {
3500 // ensure it's an object, and not a string url.
3501 // If it's an obj, this is a no-op.
3502 // this way, you can call url_format() on strings
3503 // to clean up potentially wonky urls.
3504 if (util.isString(obj)) obj = urlParse(obj);
3505 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
3506 return obj.format();
3507}
3508
3509Url.prototype.format = function() {
3510 var auth = this.auth || '';
3511 if (auth) {
3512 auth = encodeURIComponent(auth);
3513 auth = auth.replace(/%3A/i, ':');
3514 auth += '@';
3515 }
3516
3517 var protocol = this.protocol || '',
3518 pathname = this.pathname || '',
3519 hash = this.hash || '',
3520 host = false,
3521 query = '';
3522
3523 if (this.host) {
3524 host = auth + this.host;
3525 } else if (this.hostname) {
3526 host = auth + (this.hostname.indexOf(':') === -1 ?
3527 this.hostname :
3528 '[' + this.hostname + ']');
3529 if (this.port) {
3530 host += ':' + this.port;
3531 }
3532 }
3533
3534 if (this.query &&
3535 util.isObject(this.query) &&
3536 Object.keys(this.query).length) {
3537 query = querystring.stringify(this.query);
3538 }
3539
3540 var search = this.search || (query && ('?' + query)) || '';
3541
3542 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
3543
3544 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
3545 // unless they had them to begin with.
3546 if (this.slashes ||
3547 (!protocol || slashedProtocol[protocol]) && host !== false) {
3548 host = '//' + (host || '');
3549 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
3550 } else if (!host) {
3551 host = '';
3552 }
3553
3554 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
3555 if (search && search.charAt(0) !== '?') search = '?' + search;
3556
3557 pathname = pathname.replace(/[?#]/g, function(match) {
3558 return encodeURIComponent(match);
3559 });
3560 search = search.replace('#', '%23');
3561
3562 return protocol + host + pathname + search + hash;
3563};
3564
3565function urlResolve(source, relative) {
3566 return urlParse(source, false, true).resolve(relative);
3567}
3568
3569Url.prototype.resolve = function(relative) {
3570 return this.resolveObject(urlParse(relative, false, true)).format();
3571};
3572
3573function urlResolveObject(source, relative) {
3574 if (!source) return relative;
3575 return urlParse(source, false, true).resolveObject(relative);
3576}
3577
3578Url.prototype.resolveObject = function(relative) {
3579 if (util.isString(relative)) {
3580 var rel = new Url();
3581 rel.parse(relative, false, true);
3582 relative = rel;
3583 }
3584
3585 var result = new Url();
3586 var tkeys = Object.keys(this);
3587 for (var tk = 0; tk < tkeys.length; tk++) {
3588 var tkey = tkeys[tk];
3589 result[tkey] = this[tkey];
3590 }
3591
3592 // hash is always overridden, no matter what.
3593 // even href="" will remove it.
3594 result.hash = relative.hash;
3595
3596 // if the relative url is empty, then there's nothing left to do here.
3597 if (relative.href === '') {
3598 result.href = result.format();
3599 return result;
3600 }
3601
3602 // hrefs like //foo/bar always cut to the protocol.
3603 if (relative.slashes && !relative.protocol) {
3604 // take everything except the protocol from relative
3605 var rkeys = Object.keys(relative);
3606 for (var rk = 0; rk < rkeys.length; rk++) {
3607 var rkey = rkeys[rk];
3608 if (rkey !== 'protocol')
3609 result[rkey] = relative[rkey];
3610 }
3611
3612 //urlParse appends trailing / to urls like http://www.example.com
3613 if (slashedProtocol[result.protocol] &&
3614 result.hostname && !result.pathname) {
3615 result.path = result.pathname = '/';
3616 }
3617
3618 result.href = result.format();
3619 return result;
3620 }
3621
3622 if (relative.protocol && relative.protocol !== result.protocol) {
3623 // if it's a known url protocol, then changing
3624 // the protocol does weird things
3625 // first, if it's not file:, then we MUST have a host,
3626 // and if there was a path
3627 // to begin with, then we MUST have a path.
3628 // if it is file:, then the host is dropped,
3629 // because that's known to be hostless.
3630 // anything else is assumed to be absolute.
3631 if (!slashedProtocol[relative.protocol]) {
3632 var keys = Object.keys(relative);
3633 for (var v = 0; v < keys.length; v++) {
3634 var k = keys[v];
3635 result[k] = relative[k];
3636 }
3637 result.href = result.format();
3638 return result;
3639 }
3640
3641 result.protocol = relative.protocol;
3642 if (!relative.host && !hostlessProtocol[relative.protocol]) {
3643 var relPath = (relative.pathname || '').split('/');
3644 while (relPath.length && !(relative.host = relPath.shift()));
3645 if (!relative.host) relative.host = '';
3646 if (!relative.hostname) relative.hostname = '';
3647 if (relPath[0] !== '') relPath.unshift('');
3648 if (relPath.length < 2) relPath.unshift('');
3649 result.pathname = relPath.join('/');
3650 } else {
3651 result.pathname = relative.pathname;
3652 }
3653 result.search = relative.search;
3654 result.query = relative.query;
3655 result.host = relative.host || '';
3656 result.auth = relative.auth;
3657 result.hostname = relative.hostname || relative.host;
3658 result.port = relative.port;
3659 // to support http.request
3660 if (result.pathname || result.search) {
3661 var p = result.pathname || '';
3662 var s = result.search || '';
3663 result.path = p + s;
3664 }
3665 result.slashes = result.slashes || relative.slashes;
3666 result.href = result.format();
3667 return result;
3668 }
3669
3670 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
3671 isRelAbs = (
3672 relative.host ||
3673 relative.pathname && relative.pathname.charAt(0) === '/'
3674 ),
3675 mustEndAbs = (isRelAbs || isSourceAbs ||
3676 (result.host && relative.pathname)),
3677 removeAllDots = mustEndAbs,
3678 srcPath = result.pathname && result.pathname.split('/') || [],
3679 relPath = relative.pathname && relative.pathname.split('/') || [],
3680 psychotic = result.protocol && !slashedProtocol[result.protocol];
3681
3682 // if the url is a non-slashed url, then relative
3683 // links like ../.. should be able
3684 // to crawl up to the hostname, as well. This is strange.
3685 // result.protocol has already been set by now.
3686 // Later on, put the first path part into the host field.
3687 if (psychotic) {
3688 result.hostname = '';
3689 result.port = null;
3690 if (result.host) {
3691 if (srcPath[0] === '') srcPath[0] = result.host;
3692 else srcPath.unshift(result.host);
3693 }
3694 result.host = '';
3695 if (relative.protocol) {
3696 relative.hostname = null;
3697 relative.port = null;
3698 if (relative.host) {
3699 if (relPath[0] === '') relPath[0] = relative.host;
3700 else relPath.unshift(relative.host);
3701 }
3702 relative.host = null;
3703 }
3704 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
3705 }
3706
3707 if (isRelAbs) {
3708 // it's absolute.
3709 result.host = (relative.host || relative.host === '') ?
3710 relative.host : result.host;
3711 result.hostname = (relative.hostname || relative.hostname === '') ?
3712 relative.hostname : result.hostname;
3713 result.search = relative.search;
3714 result.query = relative.query;
3715 srcPath = relPath;
3716 // fall through to the dot-handling below.
3717 } else if (relPath.length) {
3718 // it's relative
3719 // throw away the existing file, and take the new path instead.
3720 if (!srcPath) srcPath = [];
3721 srcPath.pop();
3722 srcPath = srcPath.concat(relPath);
3723 result.search = relative.search;
3724 result.query = relative.query;
3725 } else if (!util.isNullOrUndefined(relative.search)) {
3726 // just pull out the search.
3727 // like href='?foo'.
3728 // Put this after the other two cases because it simplifies the booleans
3729 if (psychotic) {
3730 result.hostname = result.host = srcPath.shift();
3731 //occationaly the auth can get stuck only in host
3732 //this especially happens in cases like
3733 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
3734 var authInHost = result.host && result.host.indexOf('@') > 0 ?
3735 result.host.split('@') : false;
3736 if (authInHost) {
3737 result.auth = authInHost.shift();
3738 result.host = result.hostname = authInHost.shift();
3739 }
3740 }
3741 result.search = relative.search;
3742 result.query = relative.query;
3743 //to support http.request
3744 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
3745 result.path = (result.pathname ? result.pathname : '') +
3746 (result.search ? result.search : '');
3747 }
3748 result.href = result.format();
3749 return result;
3750 }
3751
3752 if (!srcPath.length) {
3753 // no path at all. easy.
3754 // we've already handled the other stuff above.
3755 result.pathname = null;
3756 //to support http.request
3757 if (result.search) {
3758 result.path = '/' + result.search;
3759 } else {
3760 result.path = null;
3761 }
3762 result.href = result.format();
3763 return result;
3764 }
3765
3766 // if a url ENDs in . or .., then it must get a trailing slash.
3767 // however, if it ends in anything else non-slashy,
3768 // then it must NOT get a trailing slash.
3769 var last = srcPath.slice(-1)[0];
3770 var hasTrailingSlash = (
3771 (result.host || relative.host || srcPath.length > 1) &&
3772 (last === '.' || last === '..') || last === '');
3773
3774 // strip single dots, resolve double dots to parent dir
3775 // if the path tries to go above the root, `up` ends up > 0
3776 var up = 0;
3777 for (var i = srcPath.length; i >= 0; i--) {
3778 last = srcPath[i];
3779 if (last === '.') {
3780 srcPath.splice(i, 1);
3781 } else if (last === '..') {
3782 srcPath.splice(i, 1);
3783 up++;
3784 } else if (up) {
3785 srcPath.splice(i, 1);
3786 up--;
3787 }
3788 }
3789
3790 // if the path is allowed to go above the root, restore leading ..s
3791 if (!mustEndAbs && !removeAllDots) {
3792 for (; up--; up) {
3793 srcPath.unshift('..');
3794 }
3795 }
3796
3797 if (mustEndAbs && srcPath[0] !== '' &&
3798 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
3799 srcPath.unshift('');
3800 }
3801
3802 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
3803 srcPath.push('');
3804 }
3805
3806 var isAbsolute = srcPath[0] === '' ||
3807 (srcPath[0] && srcPath[0].charAt(0) === '/');
3808
3809 // put the host back
3810 if (psychotic) {
3811 result.hostname = result.host = isAbsolute ? '' :
3812 srcPath.length ? srcPath.shift() : '';
3813 //occationaly the auth can get stuck only in host
3814 //this especially happens in cases like
3815 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
3816 var authInHost = result.host && result.host.indexOf('@') > 0 ?
3817 result.host.split('@') : false;
3818 if (authInHost) {
3819 result.auth = authInHost.shift();
3820 result.host = result.hostname = authInHost.shift();
3821 }
3822 }
3823
3824 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
3825
3826 if (mustEndAbs && !isAbsolute) {
3827 srcPath.unshift('');
3828 }
3829
3830 if (!srcPath.length) {
3831 result.pathname = null;
3832 result.path = null;
3833 } else {
3834 result.pathname = srcPath.join('/');
3835 }
3836
3837 //to support request.http
3838 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
3839 result.path = (result.pathname ? result.pathname : '') +
3840 (result.search ? result.search : '');
3841 }
3842 result.auth = relative.auth || result.auth;
3843 result.slashes = result.slashes || relative.slashes;
3844 result.href = result.format();
3845 return result;
3846};
3847
3848Url.prototype.parseHost = function() {
3849 var host = this.host;
3850 var port = portPattern.exec(host);
3851 if (port) {
3852 port = port[0];
3853 if (port !== ':') {
3854 this.port = port.substr(1);
3855 }
3856 host = host.substr(0, host.length - port.length);
3857 }
3858 if (host) this.hostname = host;
3859};
3860
3861
3862/***/ }),
3863
3864/***/ "../../node_modules/url/util.js":
3865/*!*************************************************!*\
3866 !*** /root/amplify-js/node_modules/url/util.js ***!
3867 \*************************************************/
3868/*! no static exports found */
3869/***/ (function(module, exports, __webpack_require__) {
3870
3871"use strict";
3872
3873
3874module.exports = {
3875 isString: function(arg) {
3876 return typeof(arg) === 'string';
3877 },
3878 isObject: function(arg) {
3879 return typeof(arg) === 'object' && arg !== null;
3880 },
3881 isNull: function(arg) {
3882 return arg === null;
3883 },
3884 isNullOrUndefined: function(arg) {
3885 return arg == null;
3886 }
3887};
3888
3889
3890/***/ }),
3891
3892/***/ "../../node_modules/webpack/buildin/global.js":
3893/*!***********************************!*\
3894 !*** (webpack)/buildin/global.js ***!
3895 \***********************************/
3896/*! no static exports found */
3897/***/ (function(module, exports) {
3898
3899var g;
3900
3901// This works in non-strict mode
3902g = (function() {
3903 return this;
3904})();
3905
3906try {
3907 // This works if eval is allowed (see CSP)
3908 g = g || new Function("return this")();
3909} catch (e) {
3910 // This works if the window reference is available
3911 if (typeof window === "object") g = window;
3912}
3913
3914// g can still be undefined, but nothing to do about it...
3915// We return undefined, instead of nothing here, so it's
3916// easier to handle this case. if(!global) { ...}
3917
3918module.exports = g;
3919
3920
3921/***/ }),
3922
3923/***/ "../../node_modules/webpack/buildin/module.js":
3924/*!***********************************!*\
3925 !*** (webpack)/buildin/module.js ***!
3926 \***********************************/
3927/*! no static exports found */
3928/***/ (function(module, exports) {
3929
3930module.exports = function(module) {
3931 if (!module.webpackPolyfill) {
3932 module.deprecate = function() {};
3933 module.paths = [];
3934 // module.parent = undefined by default
3935 if (!module.children) module.children = [];
3936 Object.defineProperty(module, "loaded", {
3937 enumerable: true,
3938 get: function() {
3939 return module.l;
3940 }
3941 });
3942 Object.defineProperty(module, "id", {
3943 enumerable: true,
3944 get: function() {
3945 return module.i;
3946 }
3947 });
3948 module.webpackPolyfill = 1;
3949 }
3950 return module;
3951};
3952
3953
3954/***/ }),
3955
3956/***/ "../amazon-cognito-identity-js/es/AuthenticationDetails.js":
3957/*!*****************************************************************!*\
3958 !*** ../amazon-cognito-identity-js/es/AuthenticationDetails.js ***!
3959 \*****************************************************************/
3960/*! exports provided: default */
3961/***/ (function(module, __webpack_exports__, __webpack_require__) {
3962
3963"use strict";
3964__webpack_require__.r(__webpack_exports__);
3965/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AuthenticationDetails; });
3966/*!
3967 * Copyright 2016 Amazon.com,
3968 * Inc. or its affiliates. All Rights Reserved.
3969 *
3970 * Licensed under the Amazon Software License (the "License").
3971 * You may not use this file except in compliance with the
3972 * License. A copy of the License is located at
3973 *
3974 * http://aws.amazon.com/asl/
3975 *
3976 * or in the "license" file accompanying this file. This file is
3977 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
3978 * CONDITIONS OF ANY KIND, express or implied. See the License
3979 * for the specific language governing permissions and
3980 * limitations under the License.
3981 */
3982
3983/** @class */
3984var AuthenticationDetails = /*#__PURE__*/function () {
3985 /**
3986 * Constructs a new AuthenticationDetails object
3987 * @param {object=} data Creation options.
3988 * @param {string} data.Username User being authenticated.
3989 * @param {string} data.Password Plain-text password to authenticate with.
3990 * @param {(AttributeArg[])?} data.ValidationData Application extra metadata.
3991 * @param {(AttributeArg[])?} data.AuthParamaters Authentication paramaters for custom auth.
3992 */
3993 function AuthenticationDetails(data) {
3994 var _ref = data || {},
3995 ValidationData = _ref.ValidationData,
3996 Username = _ref.Username,
3997 Password = _ref.Password,
3998 AuthParameters = _ref.AuthParameters,
3999 ClientMetadata = _ref.ClientMetadata;
4000
4001 this.validationData = ValidationData || {};
4002 this.authParameters = AuthParameters || {};
4003 this.clientMetadata = ClientMetadata || {};
4004 this.username = Username;
4005 this.password = Password;
4006 }
4007 /**
4008 * @returns {string} the record's username
4009 */
4010
4011
4012 var _proto = AuthenticationDetails.prototype;
4013
4014 _proto.getUsername = function getUsername() {
4015 return this.username;
4016 }
4017 /**
4018 * @returns {string} the record's password
4019 */
4020 ;
4021
4022 _proto.getPassword = function getPassword() {
4023 return this.password;
4024 }
4025 /**
4026 * @returns {Array} the record's validationData
4027 */
4028 ;
4029
4030 _proto.getValidationData = function getValidationData() {
4031 return this.validationData;
4032 }
4033 /**
4034 * @returns {Array} the record's authParameters
4035 */
4036 ;
4037
4038 _proto.getAuthParameters = function getAuthParameters() {
4039 return this.authParameters;
4040 }
4041 /**
4042 * @returns {ClientMetadata} the clientMetadata for a Lambda trigger
4043 */
4044 ;
4045
4046 _proto.getClientMetadata = function getClientMetadata() {
4047 return this.clientMetadata;
4048 };
4049
4050 return AuthenticationDetails;
4051}();
4052
4053
4054
4055/***/ }),
4056
4057/***/ "../amazon-cognito-identity-js/es/AuthenticationHelper.js":
4058/*!****************************************************************!*\
4059 !*** ../amazon-cognito-identity-js/es/AuthenticationHelper.js ***!
4060 \****************************************************************/
4061/*! exports provided: default */
4062/***/ (function(module, __webpack_exports__, __webpack_require__) {
4063
4064"use strict";
4065__webpack_require__.r(__webpack_exports__);
4066/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AuthenticationHelper; });
4067/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer */ "../../node_modules/buffer/index.js");
4068/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(buffer__WEBPACK_IMPORTED_MODULE_0__);
4069/* harmony import */ var crypto_js_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! crypto-js/core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js");
4070/* harmony import */ var crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(crypto_js_core__WEBPACK_IMPORTED_MODULE_1__);
4071/* harmony import */ var crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! crypto-js/lib-typedarrays */ "../amazon-cognito-identity-js/node_modules/crypto-js/lib-typedarrays.js");
4072/* harmony import */ var crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2__);
4073/* harmony import */ var crypto_js_sha256__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! crypto-js/sha256 */ "../amazon-cognito-identity-js/node_modules/crypto-js/sha256.js");
4074/* harmony import */ var crypto_js_sha256__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(crypto_js_sha256__WEBPACK_IMPORTED_MODULE_3__);
4075/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! crypto-js/hmac-sha256 */ "../amazon-cognito-identity-js/node_modules/crypto-js/hmac-sha256.js");
4076/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4__);
4077/* harmony import */ var _utils_WordArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/WordArray */ "../amazon-cognito-identity-js/es/utils/WordArray.js");
4078/* harmony import */ var _BigInteger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./BigInteger */ "../amazon-cognito-identity-js/es/BigInteger.js");
4079/*!
4080 * Copyright 2016 Amazon.com,
4081 * Inc. or its affiliates. All Rights Reserved.
4082 *
4083 * Licensed under the Amazon Software License (the "License").
4084 * You may not use this file except in compliance with the
4085 * License. A copy of the License is located at
4086 *
4087 * http://aws.amazon.com/asl/
4088 *
4089 * or in the "license" file accompanying this file. This file is
4090 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
4091 * CONDITIONS OF ANY KIND, express or implied. See the License
4092 * for the specific language governing permissions and
4093 * limitations under the License.
4094 */
4095
4096
4097 // necessary for crypto js
4098
4099
4100
4101
4102/**
4103 * Returns a Buffer with a sequence of random nBytes
4104 *
4105 * @param {number} nBytes
4106 * @returns {Buffer} fixed-length sequence of random bytes
4107 */
4108
4109function randomBytes(nBytes) {
4110 return buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(new _utils_WordArray__WEBPACK_IMPORTED_MODULE_5__["default"]().random(nBytes).toString(), 'hex');
4111}
4112
4113
4114/**
4115 * Tests if a hex string has it most significant bit set (case-insensitive regex)
4116 */
4117
4118var HEX_MSB_REGEX = /^[89a-f]/i;
4119var initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF';
4120var newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.';
4121/** @class */
4122
4123var AuthenticationHelper = /*#__PURE__*/function () {
4124 /**
4125 * Constructs a new AuthenticationHelper object
4126 * @param {string} PoolName Cognito user pool name.
4127 */
4128 function AuthenticationHelper(PoolName) {
4129 this.N = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](initN, 16);
4130 this.g = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"]('2', 16);
4131 this.k = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](this.hexHash("" + this.padHex(this.N) + this.padHex(this.g)), 16);
4132 this.smallAValue = this.generateRandomSmallA();
4133 this.getLargeAValue(function () {});
4134 this.infoBits = buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from('Caldera Derived Key', 'utf8');
4135 this.poolName = PoolName;
4136 }
4137 /**
4138 * @returns {BigInteger} small A, a random number
4139 */
4140
4141
4142 var _proto = AuthenticationHelper.prototype;
4143
4144 _proto.getSmallAValue = function getSmallAValue() {
4145 return this.smallAValue;
4146 }
4147 /**
4148 * @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
4149 * @returns {void}
4150 */
4151 ;
4152
4153 _proto.getLargeAValue = function getLargeAValue(callback) {
4154 var _this = this;
4155
4156 if (this.largeAValue) {
4157 callback(null, this.largeAValue);
4158 } else {
4159 this.calculateA(this.smallAValue, function (err, largeAValue) {
4160 if (err) {
4161 callback(err, null);
4162 }
4163
4164 _this.largeAValue = largeAValue;
4165 callback(null, _this.largeAValue);
4166 });
4167 }
4168 }
4169 /**
4170 * helper function to generate a random big integer
4171 * @returns {BigInteger} a random value.
4172 * @private
4173 */
4174 ;
4175
4176 _proto.generateRandomSmallA = function generateRandomSmallA() {
4177 // This will be interpreted as a postive 128-bit integer
4178 var hexRandom = randomBytes(128).toString('hex');
4179 var randomBigInt = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](hexRandom, 16); // There is no need to do randomBigInt.mod(this.N - 1) as N (3072-bit) is > 128 bytes (1024-bit)
4180
4181 return randomBigInt;
4182 }
4183 /**
4184 * helper function to generate a random string
4185 * @returns {string} a random value.
4186 * @private
4187 */
4188 ;
4189
4190 _proto.generateRandomString = function generateRandomString() {
4191 return randomBytes(40).toString('base64');
4192 }
4193 /**
4194 * @returns {string} Generated random value included in password hash.
4195 */
4196 ;
4197
4198 _proto.getRandomPassword = function getRandomPassword() {
4199 return this.randomPassword;
4200 }
4201 /**
4202 * @returns {string} Generated random value included in devices hash.
4203 */
4204 ;
4205
4206 _proto.getSaltDevices = function getSaltDevices() {
4207 return this.SaltToHashDevices;
4208 }
4209 /**
4210 * @returns {string} Value used to verify devices.
4211 */
4212 ;
4213
4214 _proto.getVerifierDevices = function getVerifierDevices() {
4215 return this.verifierDevices;
4216 }
4217 /**
4218 * Generate salts and compute verifier.
4219 * @param {string} deviceGroupKey Devices to generate verifier for.
4220 * @param {string} username User to generate verifier for.
4221 * @param {nodeCallback<null>} callback Called with (err, null)
4222 * @returns {void}
4223 */
4224 ;
4225
4226 _proto.generateHashDevice = function generateHashDevice(deviceGroupKey, username, callback) {
4227 var _this2 = this;
4228
4229 this.randomPassword = this.generateRandomString();
4230 var combinedString = "" + deviceGroupKey + username + ":" + this.randomPassword;
4231 var hashedString = this.hash(combinedString);
4232 var hexRandom = randomBytes(16).toString('hex'); // The random hex will be unambiguously represented as a postive integer
4233
4234 this.SaltToHashDevices = this.padHex(new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](hexRandom, 16));
4235 this.g.modPow(new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, function (err, verifierDevicesNotPadded) {
4236 if (err) {
4237 callback(err, null);
4238 }
4239
4240 _this2.verifierDevices = _this2.padHex(verifierDevicesNotPadded);
4241 callback(null, null);
4242 });
4243 }
4244 /**
4245 * Calculate the client's public value A = g^a%N
4246 * with the generated random number a
4247 * @param {BigInteger} a Randomly generated small A.
4248 * @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
4249 * @returns {void}
4250 * @private
4251 */
4252 ;
4253
4254 _proto.calculateA = function calculateA(a, callback) {
4255 var _this3 = this;
4256
4257 this.g.modPow(a, this.N, function (err, A) {
4258 if (err) {
4259 callback(err, null);
4260 }
4261
4262 if (A.mod(_this3.N).equals(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ZERO)) {
4263 callback(new Error('Illegal paramater. A mod N cannot be 0.'), null);
4264 }
4265
4266 callback(null, A);
4267 });
4268 }
4269 /**
4270 * Calculate the client's value U which is the hash of A and B
4271 * @param {BigInteger} A Large A value.
4272 * @param {BigInteger} B Server B value.
4273 * @returns {BigInteger} Computed U value.
4274 * @private
4275 */
4276 ;
4277
4278 _proto.calculateU = function calculateU(A, B) {
4279 this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B));
4280 var finalU = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](this.UHexHash, 16);
4281 return finalU;
4282 }
4283 /**
4284 * Calculate a hash from a bitArray
4285 * @param {Buffer} buf Value to hash.
4286 * @returns {String} Hex-encoded hash.
4287 * @private
4288 */
4289 ;
4290
4291 _proto.hash = function hash(buf) {
4292 var str = buf instanceof buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"] ? crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(buf) : buf;
4293 var hashHex = crypto_js_sha256__WEBPACK_IMPORTED_MODULE_3___default()(str).toString();
4294 return new Array(64 - hashHex.length).join('0') + hashHex;
4295 }
4296 /**
4297 * Calculate a hash from a hex string
4298 * @param {String} hexStr Value to hash.
4299 * @returns {String} Hex-encoded hash.
4300 * @private
4301 */
4302 ;
4303
4304 _proto.hexHash = function hexHash(hexStr) {
4305 return this.hash(buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(hexStr, 'hex'));
4306 }
4307 /**
4308 * Standard hkdf algorithm
4309 * @param {Buffer} ikm Input key material.
4310 * @param {Buffer} salt Salt value.
4311 * @returns {Buffer} Strong key material.
4312 * @private
4313 */
4314 ;
4315
4316 _proto.computehkdf = function computehkdf(ikm, salt) {
4317 var infoBitsWordArray = crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].concat([this.infoBits, buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(String.fromCharCode(1), 'utf8')]));
4318 var ikmWordArray = ikm instanceof buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"] ? crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(ikm) : ikm;
4319 var saltWordArray = salt instanceof buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"] ? crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(salt) : salt;
4320 var prk = crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default()(ikmWordArray, saltWordArray);
4321 var hmac = crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default()(infoBitsWordArray, prk);
4322 return buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(hmac.toString(), 'hex').slice(0, 16);
4323 }
4324 /**
4325 * Calculates the final hkdf based on computed S value, and computed U value and the key
4326 * @param {String} username Username.
4327 * @param {String} password Password.
4328 * @param {BigInteger} serverBValue Server B value.
4329 * @param {BigInteger} salt Generated salt.
4330 * @param {nodeCallback<Buffer>} callback Called with (err, hkdfValue)
4331 * @returns {void}
4332 */
4333 ;
4334
4335 _proto.getPasswordAuthenticationKey = function getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) {
4336 var _this4 = this;
4337
4338 if (serverBValue.mod(this.N).equals(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ZERO)) {
4339 throw new Error('B cannot be zero.');
4340 }
4341
4342 this.UValue = this.calculateU(this.largeAValue, serverBValue);
4343
4344 if (this.UValue.equals(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ZERO)) {
4345 throw new Error('U cannot be zero.');
4346 }
4347
4348 var usernamePassword = "" + this.poolName + username + ":" + password;
4349 var usernamePasswordHash = this.hash(usernamePassword);
4350 var xValue = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](this.hexHash(this.padHex(salt) + usernamePasswordHash), 16);
4351 this.calculateS(xValue, serverBValue, function (err, sValue) {
4352 if (err) {
4353 callback(err, null);
4354 }
4355
4356 var hkdf = _this4.computehkdf(buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(_this4.padHex(sValue), 'hex'), buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(_this4.padHex(_this4.UValue), 'hex'));
4357
4358 callback(null, hkdf);
4359 });
4360 }
4361 /**
4362 * Calculates the S value used in getPasswordAuthenticationKey
4363 * @param {BigInteger} xValue Salted password hash value.
4364 * @param {BigInteger} serverBValue Server B value.
4365 * @param {nodeCallback<string>} callback Called on success or error.
4366 * @returns {void}
4367 */
4368 ;
4369
4370 _proto.calculateS = function calculateS(xValue, serverBValue, callback) {
4371 var _this5 = this;
4372
4373 this.g.modPow(xValue, this.N, function (err, gModPowXN) {
4374 if (err) {
4375 callback(err, null);
4376 }
4377
4378 var intValue2 = serverBValue.subtract(_this5.k.multiply(gModPowXN));
4379 intValue2.modPow(_this5.smallAValue.add(_this5.UValue.multiply(xValue)), _this5.N, function (err2, result) {
4380 if (err2) {
4381 callback(err2, null);
4382 }
4383
4384 callback(null, result.mod(_this5.N));
4385 });
4386 });
4387 }
4388 /**
4389 * Return constant newPasswordRequiredChallengeUserAttributePrefix
4390 * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value
4391 */
4392 ;
4393
4394 _proto.getNewPasswordRequiredChallengeUserAttributePrefix = function getNewPasswordRequiredChallengeUserAttributePrefix() {
4395 return newPasswordRequiredChallengeUserAttributePrefix;
4396 }
4397 /**
4398 * Returns an unambiguous, even-length hex string of the two's complement encoding of an integer.
4399 *
4400 * It is compatible with the hex encoding of Java's BigInteger's toByteArray(), wich returns a
4401 * byte array containing the two's-complement representation of a BigInteger. The array contains
4402 * the minimum number of bytes required to represent the BigInteger, including at least one sign bit.
4403 *
4404 * Examples showing how ambiguity is avoided by left padding with:
4405 * "00" (for positive values where the most-significant-bit is set)
4406 * "FF" (for negative values where the most-significant-bit is set)
4407 *
4408 * padHex(bigInteger.fromInt(-236)) === "FF14"
4409 * padHex(bigInteger.fromInt(20)) === "14"
4410 *
4411 * padHex(bigInteger.fromInt(-200)) === "FF38"
4412 * padHex(bigInteger.fromInt(56)) === "38"
4413 *
4414 * padHex(bigInteger.fromInt(-20)) === "EC"
4415 * padHex(bigInteger.fromInt(236)) === "00EC"
4416 *
4417 * padHex(bigInteger.fromInt(-56)) === "C8"
4418 * padHex(bigInteger.fromInt(200)) === "00C8"
4419 *
4420 * @param {BigInteger} bigInt Number to encode.
4421 * @returns {String} even-length hex string of the two's complement encoding.
4422 */
4423 ;
4424
4425 _proto.padHex = function padHex(bigInt) {
4426 if (!(bigInt instanceof _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"])) {
4427 throw new Error('Not a BigInteger');
4428 }
4429
4430 var isNegative = bigInt.compareTo(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ZERO) < 0;
4431 /* Get a hex string for abs(bigInt) */
4432
4433 var hexStr = bigInt.abs().toString(16);
4434 /* Pad hex to even length if needed */
4435
4436 hexStr = hexStr.length % 2 !== 0 ? "0" + hexStr : hexStr;
4437 /* Prepend "00" if the most significant bit is set */
4438
4439 hexStr = HEX_MSB_REGEX.test(hexStr) ? "00" + hexStr : hexStr;
4440
4441 if (isNegative) {
4442 /* Flip the bits of the representation */
4443 var invertedNibbles = hexStr.split('').map(function (x) {
4444 var invertedNibble = ~parseInt(x, 16) & 0xf;
4445 return '0123456789ABCDEF'.charAt(invertedNibble);
4446 }).join('');
4447 /* After flipping the bits, add one to get the 2's complement representation */
4448
4449 var flippedBitsBI = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](invertedNibbles, 16).add(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ONE);
4450 hexStr = flippedBitsBI.toString(16);
4451 /*
4452 For hex strings starting with 'FF8', 'FF' can be dropped, e.g. 0xFFFF80=0xFF80=0x80=-128
4453 Any sequence of '1' bits on the left can always be substituted with a single '1' bit
4454 without changing the represented value.
4455 This only happens in the case when the input is 80...00
4456 */
4457
4458 if (hexStr.toUpperCase().startsWith('FF8')) {
4459 hexStr = hexStr.substring(2);
4460 }
4461 }
4462
4463 return hexStr;
4464 };
4465
4466 return AuthenticationHelper;
4467}();
4468
4469
4470
4471/***/ }),
4472
4473/***/ "../amazon-cognito-identity-js/es/BigInteger.js":
4474/*!******************************************************!*\
4475 !*** ../amazon-cognito-identity-js/es/BigInteger.js ***!
4476 \******************************************************/
4477/*! exports provided: default */
4478/***/ (function(module, __webpack_exports__, __webpack_require__) {
4479
4480"use strict";
4481__webpack_require__.r(__webpack_exports__);
4482// A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/
4483//
4484// All public methods have been removed except the following:
4485// new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported)
4486// toString (only radix 2, 4, 8, 16 and 32 supported)
4487// negate
4488// abs
4489// compareTo
4490// bitLength
4491// mod
4492// equals
4493// add
4494// subtract
4495// multiply
4496// divide
4497// modPow
4498/* harmony default export */ __webpack_exports__["default"] = (BigInteger);
4499/*
4500 * Copyright (c) 2003-2005 Tom Wu
4501 * All Rights Reserved.
4502 *
4503 * Permission is hereby granted, free of charge, to any person obtaining
4504 * a copy of this software and associated documentation files (the
4505 * "Software"), to deal in the Software without restriction, including
4506 * without limitation the rights to use, copy, modify, merge, publish,
4507 * distribute, sublicense, and/or sell copies of the Software, and to
4508 * permit persons to whom the Software is furnished to do so, subject to
4509 * the following conditions:
4510 *
4511 * The above copyright notice and this permission notice shall be
4512 * included in all copies or substantial portions of the Software.
4513 *
4514 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
4515 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
4516 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
4517 *
4518 * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
4519 * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
4520 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
4521 * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
4522 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
4523 *
4524 * In addition, the following condition applies:
4525 *
4526 * All redistributions must retain an intact copy of this copyright notice
4527 * and disclaimer.
4528 */
4529// (public) Constructor
4530
4531function BigInteger(a, b) {
4532 if (a != null) this.fromString(a, b);
4533} // return new, unset BigInteger
4534
4535
4536function nbi() {
4537 return new BigInteger(null);
4538} // Bits per digit
4539
4540
4541var dbits; // JavaScript engine analysis
4542
4543var canary = 0xdeadbeefcafe;
4544var j_lm = (canary & 0xffffff) == 0xefcafe; // am: Compute w_j += (x*this_i), propagate carries,
4545// c is initial carry, returns final carry.
4546// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
4547// We need to select the fastest one that works in this environment.
4548// am1: use a single mult and divide to get the high bits,
4549// max digit bits should be 26 because
4550// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
4551
4552function am1(i, x, w, j, c, n) {
4553 while (--n >= 0) {
4554 var v = x * this[i++] + w[j] + c;
4555 c = Math.floor(v / 0x4000000);
4556 w[j++] = v & 0x3ffffff;
4557 }
4558
4559 return c;
4560} // am2 avoids a big mult-and-extract completely.
4561// Max digit bits should be <= 30 because we do bitwise ops
4562// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
4563
4564
4565function am2(i, x, w, j, c, n) {
4566 var xl = x & 0x7fff,
4567 xh = x >> 15;
4568
4569 while (--n >= 0) {
4570 var l = this[i] & 0x7fff;
4571 var h = this[i++] >> 15;
4572 var m = xh * l + h * xl;
4573 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
4574 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
4575 w[j++] = l & 0x3fffffff;
4576 }
4577
4578 return c;
4579} // Alternately, set max digit bits to 28 since some
4580// browsers slow down when dealing with 32-bit numbers.
4581
4582
4583function am3(i, x, w, j, c, n) {
4584 var xl = x & 0x3fff,
4585 xh = x >> 14;
4586
4587 while (--n >= 0) {
4588 var l = this[i] & 0x3fff;
4589 var h = this[i++] >> 14;
4590 var m = xh * l + h * xl;
4591 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
4592 c = (l >> 28) + (m >> 14) + xh * h;
4593 w[j++] = l & 0xfffffff;
4594 }
4595
4596 return c;
4597}
4598
4599var inBrowser = typeof navigator !== 'undefined';
4600
4601if (inBrowser && j_lm && navigator.appName == 'Microsoft Internet Explorer') {
4602 BigInteger.prototype.am = am2;
4603 dbits = 30;
4604} else if (inBrowser && j_lm && navigator.appName != 'Netscape') {
4605 BigInteger.prototype.am = am1;
4606 dbits = 26;
4607} else {
4608 // Mozilla/Netscape seems to prefer am3
4609 BigInteger.prototype.am = am3;
4610 dbits = 28;
4611}
4612
4613BigInteger.prototype.DB = dbits;
4614BigInteger.prototype.DM = (1 << dbits) - 1;
4615BigInteger.prototype.DV = 1 << dbits;
4616var BI_FP = 52;
4617BigInteger.prototype.FV = Math.pow(2, BI_FP);
4618BigInteger.prototype.F1 = BI_FP - dbits;
4619BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions
4620
4621var BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz';
4622var BI_RC = new Array();
4623var rr, vv;
4624rr = '0'.charCodeAt(0);
4625
4626for (vv = 0; vv <= 9; ++vv) {
4627 BI_RC[rr++] = vv;
4628}
4629
4630rr = 'a'.charCodeAt(0);
4631
4632for (vv = 10; vv < 36; ++vv) {
4633 BI_RC[rr++] = vv;
4634}
4635
4636rr = 'A'.charCodeAt(0);
4637
4638for (vv = 10; vv < 36; ++vv) {
4639 BI_RC[rr++] = vv;
4640}
4641
4642function int2char(n) {
4643 return BI_RM.charAt(n);
4644}
4645
4646function intAt(s, i) {
4647 var c = BI_RC[s.charCodeAt(i)];
4648 return c == null ? -1 : c;
4649} // (protected) copy this to r
4650
4651
4652function bnpCopyTo(r) {
4653 for (var i = this.t - 1; i >= 0; --i) {
4654 r[i] = this[i];
4655 }
4656
4657 r.t = this.t;
4658 r.s = this.s;
4659} // (protected) set from integer value x, -DV <= x < DV
4660
4661
4662function bnpFromInt(x) {
4663 this.t = 1;
4664 this.s = x < 0 ? -1 : 0;
4665 if (x > 0) this[0] = x;else if (x < -1) this[0] = x + this.DV;else this.t = 0;
4666} // return bigint initialized to value
4667
4668
4669function nbv(i) {
4670 var r = nbi();
4671 r.fromInt(i);
4672 return r;
4673} // (protected) set from string and radix
4674
4675
4676function bnpFromString(s, b) {
4677 var k;
4678 if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else throw new Error('Only radix 2, 4, 8, 16, 32 are supported');
4679 this.t = 0;
4680 this.s = 0;
4681 var i = s.length,
4682 mi = false,
4683 sh = 0;
4684
4685 while (--i >= 0) {
4686 var x = intAt(s, i);
4687
4688 if (x < 0) {
4689 if (s.charAt(i) == '-') mi = true;
4690 continue;
4691 }
4692
4693 mi = false;
4694 if (sh == 0) this[this.t++] = x;else if (sh + k > this.DB) {
4695 this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh;
4696 this[this.t++] = x >> this.DB - sh;
4697 } else this[this.t - 1] |= x << sh;
4698 sh += k;
4699 if (sh >= this.DB) sh -= this.DB;
4700 }
4701
4702 this.clamp();
4703 if (mi) BigInteger.ZERO.subTo(this, this);
4704} // (protected) clamp off excess high words
4705
4706
4707function bnpClamp() {
4708 var c = this.s & this.DM;
4709
4710 while (this.t > 0 && this[this.t - 1] == c) {
4711 --this.t;
4712 }
4713} // (public) return string representation in given radix
4714
4715
4716function bnToString(b) {
4717 if (this.s < 0) return '-' + this.negate().toString(b);
4718 var k;
4719 if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else throw new Error('Only radix 2, 4, 8, 16, 32 are supported');
4720 var km = (1 << k) - 1,
4721 d,
4722 m = false,
4723 r = '',
4724 i = this.t;
4725 var p = this.DB - i * this.DB % k;
4726
4727 if (i-- > 0) {
4728 if (p < this.DB && (d = this[i] >> p) > 0) {
4729 m = true;
4730 r = int2char(d);
4731 }
4732
4733 while (i >= 0) {
4734 if (p < k) {
4735 d = (this[i] & (1 << p) - 1) << k - p;
4736 d |= this[--i] >> (p += this.DB - k);
4737 } else {
4738 d = this[i] >> (p -= k) & km;
4739
4740 if (p <= 0) {
4741 p += this.DB;
4742 --i;
4743 }
4744 }
4745
4746 if (d > 0) m = true;
4747 if (m) r += int2char(d);
4748 }
4749 }
4750
4751 return m ? r : '0';
4752} // (public) -this
4753
4754
4755function bnNegate() {
4756 var r = nbi();
4757 BigInteger.ZERO.subTo(this, r);
4758 return r;
4759} // (public) |this|
4760
4761
4762function bnAbs() {
4763 return this.s < 0 ? this.negate() : this;
4764} // (public) return + if this > a, - if this < a, 0 if equal
4765
4766
4767function bnCompareTo(a) {
4768 var r = this.s - a.s;
4769 if (r != 0) return r;
4770 var i = this.t;
4771 r = i - a.t;
4772 if (r != 0) return this.s < 0 ? -r : r;
4773
4774 while (--i >= 0) {
4775 if ((r = this[i] - a[i]) != 0) return r;
4776 }
4777
4778 return 0;
4779} // returns bit length of the integer x
4780
4781
4782function nbits(x) {
4783 var r = 1,
4784 t;
4785
4786 if ((t = x >>> 16) != 0) {
4787 x = t;
4788 r += 16;
4789 }
4790
4791 if ((t = x >> 8) != 0) {
4792 x = t;
4793 r += 8;
4794 }
4795
4796 if ((t = x >> 4) != 0) {
4797 x = t;
4798 r += 4;
4799 }
4800
4801 if ((t = x >> 2) != 0) {
4802 x = t;
4803 r += 2;
4804 }
4805
4806 if ((t = x >> 1) != 0) {
4807 x = t;
4808 r += 1;
4809 }
4810
4811 return r;
4812} // (public) return the number of bits in "this"
4813
4814
4815function bnBitLength() {
4816 if (this.t <= 0) return 0;
4817 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM);
4818} // (protected) r = this << n*DB
4819
4820
4821function bnpDLShiftTo(n, r) {
4822 var i;
4823
4824 for (i = this.t - 1; i >= 0; --i) {
4825 r[i + n] = this[i];
4826 }
4827
4828 for (i = n - 1; i >= 0; --i) {
4829 r[i] = 0;
4830 }
4831
4832 r.t = this.t + n;
4833 r.s = this.s;
4834} // (protected) r = this >> n*DB
4835
4836
4837function bnpDRShiftTo(n, r) {
4838 for (var i = n; i < this.t; ++i) {
4839 r[i - n] = this[i];
4840 }
4841
4842 r.t = Math.max(this.t - n, 0);
4843 r.s = this.s;
4844} // (protected) r = this << n
4845
4846
4847function bnpLShiftTo(n, r) {
4848 var bs = n % this.DB;
4849 var cbs = this.DB - bs;
4850 var bm = (1 << cbs) - 1;
4851 var ds = Math.floor(n / this.DB),
4852 c = this.s << bs & this.DM,
4853 i;
4854
4855 for (i = this.t - 1; i >= 0; --i) {
4856 r[i + ds + 1] = this[i] >> cbs | c;
4857 c = (this[i] & bm) << bs;
4858 }
4859
4860 for (i = ds - 1; i >= 0; --i) {
4861 r[i] = 0;
4862 }
4863
4864 r[ds] = c;
4865 r.t = this.t + ds + 1;
4866 r.s = this.s;
4867 r.clamp();
4868} // (protected) r = this >> n
4869
4870
4871function bnpRShiftTo(n, r) {
4872 r.s = this.s;
4873 var ds = Math.floor(n / this.DB);
4874
4875 if (ds >= this.t) {
4876 r.t = 0;
4877 return;
4878 }
4879
4880 var bs = n % this.DB;
4881 var cbs = this.DB - bs;
4882 var bm = (1 << bs) - 1;
4883 r[0] = this[ds] >> bs;
4884
4885 for (var i = ds + 1; i < this.t; ++i) {
4886 r[i - ds - 1] |= (this[i] & bm) << cbs;
4887 r[i - ds] = this[i] >> bs;
4888 }
4889
4890 if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs;
4891 r.t = this.t - ds;
4892 r.clamp();
4893} // (protected) r = this - a
4894
4895
4896function bnpSubTo(a, r) {
4897 var i = 0,
4898 c = 0,
4899 m = Math.min(a.t, this.t);
4900
4901 while (i < m) {
4902 c += this[i] - a[i];
4903 r[i++] = c & this.DM;
4904 c >>= this.DB;
4905 }
4906
4907 if (a.t < this.t) {
4908 c -= a.s;
4909
4910 while (i < this.t) {
4911 c += this[i];
4912 r[i++] = c & this.DM;
4913 c >>= this.DB;
4914 }
4915
4916 c += this.s;
4917 } else {
4918 c += this.s;
4919
4920 while (i < a.t) {
4921 c -= a[i];
4922 r[i++] = c & this.DM;
4923 c >>= this.DB;
4924 }
4925
4926 c -= a.s;
4927 }
4928
4929 r.s = c < 0 ? -1 : 0;
4930 if (c < -1) r[i++] = this.DV + c;else if (c > 0) r[i++] = c;
4931 r.t = i;
4932 r.clamp();
4933} // (protected) r = this * a, r != this,a (HAC 14.12)
4934// "this" should be the larger one if appropriate.
4935
4936
4937function bnpMultiplyTo(a, r) {
4938 var x = this.abs(),
4939 y = a.abs();
4940 var i = x.t;
4941 r.t = i + y.t;
4942
4943 while (--i >= 0) {
4944 r[i] = 0;
4945 }
4946
4947 for (i = 0; i < y.t; ++i) {
4948 r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
4949 }
4950
4951 r.s = 0;
4952 r.clamp();
4953 if (this.s != a.s) BigInteger.ZERO.subTo(r, r);
4954} // (protected) r = this^2, r != this (HAC 14.16)
4955
4956
4957function bnpSquareTo(r) {
4958 var x = this.abs();
4959 var i = r.t = 2 * x.t;
4960
4961 while (--i >= 0) {
4962 r[i] = 0;
4963 }
4964
4965 for (i = 0; i < x.t - 1; ++i) {
4966 var c = x.am(i, x[i], r, 2 * i, 0, 1);
4967
4968 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
4969 r[i + x.t] -= x.DV;
4970 r[i + x.t + 1] = 1;
4971 }
4972 }
4973
4974 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
4975 r.s = 0;
4976 r.clamp();
4977} // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
4978// r != q, this != m. q or r may be null.
4979
4980
4981function bnpDivRemTo(m, q, r) {
4982 var pm = m.abs();
4983 if (pm.t <= 0) return;
4984 var pt = this.abs();
4985
4986 if (pt.t < pm.t) {
4987 if (q != null) q.fromInt(0);
4988 if (r != null) this.copyTo(r);
4989 return;
4990 }
4991
4992 if (r == null) r = nbi();
4993 var y = nbi(),
4994 ts = this.s,
4995 ms = m.s;
4996 var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
4997
4998 if (nsh > 0) {
4999 pm.lShiftTo(nsh, y);
5000 pt.lShiftTo(nsh, r);
5001 } else {
5002 pm.copyTo(y);
5003 pt.copyTo(r);
5004 }
5005
5006 var ys = y.t;
5007 var y0 = y[ys - 1];
5008 if (y0 == 0) return;
5009 var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0);
5010 var d1 = this.FV / yt,
5011 d2 = (1 << this.F1) / yt,
5012 e = 1 << this.F2;
5013 var i = r.t,
5014 j = i - ys,
5015 t = q == null ? nbi() : q;
5016 y.dlShiftTo(j, t);
5017
5018 if (r.compareTo(t) >= 0) {
5019 r[r.t++] = 1;
5020 r.subTo(t, r);
5021 }
5022
5023 BigInteger.ONE.dlShiftTo(ys, t);
5024 t.subTo(y, y); // "negative" y so we can replace sub with am later
5025
5026 while (y.t < ys) {
5027 y[y.t++] = 0;
5028 }
5029
5030 while (--j >= 0) {
5031 // Estimate quotient digit
5032 var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
5033
5034 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {
5035 // Try it out
5036 y.dlShiftTo(j, t);
5037 r.subTo(t, r);
5038
5039 while (r[i] < --qd) {
5040 r.subTo(t, r);
5041 }
5042 }
5043 }
5044
5045 if (q != null) {
5046 r.drShiftTo(ys, q);
5047 if (ts != ms) BigInteger.ZERO.subTo(q, q);
5048 }
5049
5050 r.t = ys;
5051 r.clamp();
5052 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
5053
5054 if (ts < 0) BigInteger.ZERO.subTo(r, r);
5055} // (public) this mod a
5056
5057
5058function bnMod(a) {
5059 var r = nbi();
5060 this.abs().divRemTo(a, null, r);
5061 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r);
5062 return r;
5063} // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
5064// justification:
5065// xy == 1 (mod m)
5066// xy = 1+km
5067// xy(2-xy) = (1+km)(1-km)
5068// x[y(2-xy)] = 1-k^2m^2
5069// x[y(2-xy)] == 1 (mod m^2)
5070// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
5071// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
5072// JS multiply "overflows" differently from C/C++, so care is needed here.
5073
5074
5075function bnpInvDigit() {
5076 if (this.t < 1) return 0;
5077 var x = this[0];
5078 if ((x & 1) == 0) return 0;
5079 var y = x & 3; // y == 1/x mod 2^2
5080
5081 y = y * (2 - (x & 0xf) * y) & 0xf; // y == 1/x mod 2^4
5082
5083 y = y * (2 - (x & 0xff) * y) & 0xff; // y == 1/x mod 2^8
5084
5085 y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; // y == 1/x mod 2^16
5086 // last step - calculate inverse mod DV directly;
5087 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
5088
5089 y = y * (2 - x * y % this.DV) % this.DV; // y == 1/x mod 2^dbits
5090 // we really want the negative inverse, and -DV < y < DV
5091
5092 return y > 0 ? this.DV - y : -y;
5093}
5094
5095function bnEquals(a) {
5096 return this.compareTo(a) == 0;
5097} // (protected) r = this + a
5098
5099
5100function bnpAddTo(a, r) {
5101 var i = 0,
5102 c = 0,
5103 m = Math.min(a.t, this.t);
5104
5105 while (i < m) {
5106 c += this[i] + a[i];
5107 r[i++] = c & this.DM;
5108 c >>= this.DB;
5109 }
5110
5111 if (a.t < this.t) {
5112 c += a.s;
5113
5114 while (i < this.t) {
5115 c += this[i];
5116 r[i++] = c & this.DM;
5117 c >>= this.DB;
5118 }
5119
5120 c += this.s;
5121 } else {
5122 c += this.s;
5123
5124 while (i < a.t) {
5125 c += a[i];
5126 r[i++] = c & this.DM;
5127 c >>= this.DB;
5128 }
5129
5130 c += a.s;
5131 }
5132
5133 r.s = c < 0 ? -1 : 0;
5134 if (c > 0) r[i++] = c;else if (c < -1) r[i++] = this.DV + c;
5135 r.t = i;
5136 r.clamp();
5137} // (public) this + a
5138
5139
5140function bnAdd(a) {
5141 var r = nbi();
5142 this.addTo(a, r);
5143 return r;
5144} // (public) this - a
5145
5146
5147function bnSubtract(a) {
5148 var r = nbi();
5149 this.subTo(a, r);
5150 return r;
5151} // (public) this * a
5152
5153
5154function bnMultiply(a) {
5155 var r = nbi();
5156 this.multiplyTo(a, r);
5157 return r;
5158} // (public) this / a
5159
5160
5161function bnDivide(a) {
5162 var r = nbi();
5163 this.divRemTo(a, r, null);
5164 return r;
5165} // Montgomery reduction
5166
5167
5168function Montgomery(m) {
5169 this.m = m;
5170 this.mp = m.invDigit();
5171 this.mpl = this.mp & 0x7fff;
5172 this.mph = this.mp >> 15;
5173 this.um = (1 << m.DB - 15) - 1;
5174 this.mt2 = 2 * m.t;
5175} // xR mod m
5176
5177
5178function montConvert(x) {
5179 var r = nbi();
5180 x.abs().dlShiftTo(this.m.t, r);
5181 r.divRemTo(this.m, null, r);
5182 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r);
5183 return r;
5184} // x/R mod m
5185
5186
5187function montRevert(x) {
5188 var r = nbi();
5189 x.copyTo(r);
5190 this.reduce(r);
5191 return r;
5192} // x = x/R mod m (HAC 14.32)
5193
5194
5195function montReduce(x) {
5196 while (x.t <= this.mt2) {
5197 // pad x so am has enough room later
5198 x[x.t++] = 0;
5199 }
5200
5201 for (var i = 0; i < this.m.t; ++i) {
5202 // faster way of calculating u0 = x[i]*mp mod DV
5203 var j = x[i] & 0x7fff;
5204 var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM; // use am to combine the multiply-shift-add into one call
5205
5206 j = i + this.m.t;
5207 x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry
5208
5209 while (x[j] >= x.DV) {
5210 x[j] -= x.DV;
5211 x[++j]++;
5212 }
5213 }
5214
5215 x.clamp();
5216 x.drShiftTo(this.m.t, x);
5217 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x);
5218} // r = "x^2/R mod m"; x != r
5219
5220
5221function montSqrTo(x, r) {
5222 x.squareTo(r);
5223 this.reduce(r);
5224} // r = "xy/R mod m"; x,y != r
5225
5226
5227function montMulTo(x, y, r) {
5228 x.multiplyTo(y, r);
5229 this.reduce(r);
5230}
5231
5232Montgomery.prototype.convert = montConvert;
5233Montgomery.prototype.revert = montRevert;
5234Montgomery.prototype.reduce = montReduce;
5235Montgomery.prototype.mulTo = montMulTo;
5236Montgomery.prototype.sqrTo = montSqrTo; // (public) this^e % m (HAC 14.85)
5237
5238function bnModPow(e, m, callback) {
5239 var i = e.bitLength(),
5240 k,
5241 r = nbv(1),
5242 z = new Montgomery(m);
5243 if (i <= 0) return r;else if (i < 18) k = 1;else if (i < 48) k = 3;else if (i < 144) k = 4;else if (i < 768) k = 5;else k = 6; // precomputation
5244
5245 var g = new Array(),
5246 n = 3,
5247 k1 = k - 1,
5248 km = (1 << k) - 1;
5249 g[1] = z.convert(this);
5250
5251 if (k > 1) {
5252 var g2 = nbi();
5253 z.sqrTo(g[1], g2);
5254
5255 while (n <= km) {
5256 g[n] = nbi();
5257 z.mulTo(g2, g[n - 2], g[n]);
5258 n += 2;
5259 }
5260 }
5261
5262 var j = e.t - 1,
5263 w,
5264 is1 = true,
5265 r2 = nbi(),
5266 t;
5267 i = nbits(e[j]) - 1;
5268
5269 while (j >= 0) {
5270 if (i >= k1) w = e[j] >> i - k1 & km;else {
5271 w = (e[j] & (1 << i + 1) - 1) << k1 - i;
5272 if (j > 0) w |= e[j - 1] >> this.DB + i - k1;
5273 }
5274 n = k;
5275
5276 while ((w & 1) == 0) {
5277 w >>= 1;
5278 --n;
5279 }
5280
5281 if ((i -= n) < 0) {
5282 i += this.DB;
5283 --j;
5284 }
5285
5286 if (is1) {
5287 // ret == 1, don't bother squaring or multiplying it
5288 g[w].copyTo(r);
5289 is1 = false;
5290 } else {
5291 while (n > 1) {
5292 z.sqrTo(r, r2);
5293 z.sqrTo(r2, r);
5294 n -= 2;
5295 }
5296
5297 if (n > 0) z.sqrTo(r, r2);else {
5298 t = r;
5299 r = r2;
5300 r2 = t;
5301 }
5302 z.mulTo(r2, g[w], r);
5303 }
5304
5305 while (j >= 0 && (e[j] & 1 << i) == 0) {
5306 z.sqrTo(r, r2);
5307 t = r;
5308 r = r2;
5309 r2 = t;
5310
5311 if (--i < 0) {
5312 i = this.DB - 1;
5313 --j;
5314 }
5315 }
5316 }
5317
5318 var result = z.revert(r);
5319 callback(null, result);
5320 return result;
5321} // protected
5322
5323
5324BigInteger.prototype.copyTo = bnpCopyTo;
5325BigInteger.prototype.fromInt = bnpFromInt;
5326BigInteger.prototype.fromString = bnpFromString;
5327BigInteger.prototype.clamp = bnpClamp;
5328BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
5329BigInteger.prototype.drShiftTo = bnpDRShiftTo;
5330BigInteger.prototype.lShiftTo = bnpLShiftTo;
5331BigInteger.prototype.rShiftTo = bnpRShiftTo;
5332BigInteger.prototype.subTo = bnpSubTo;
5333BigInteger.prototype.multiplyTo = bnpMultiplyTo;
5334BigInteger.prototype.squareTo = bnpSquareTo;
5335BigInteger.prototype.divRemTo = bnpDivRemTo;
5336BigInteger.prototype.invDigit = bnpInvDigit;
5337BigInteger.prototype.addTo = bnpAddTo; // public
5338
5339BigInteger.prototype.toString = bnToString;
5340BigInteger.prototype.negate = bnNegate;
5341BigInteger.prototype.abs = bnAbs;
5342BigInteger.prototype.compareTo = bnCompareTo;
5343BigInteger.prototype.bitLength = bnBitLength;
5344BigInteger.prototype.mod = bnMod;
5345BigInteger.prototype.equals = bnEquals;
5346BigInteger.prototype.add = bnAdd;
5347BigInteger.prototype.subtract = bnSubtract;
5348BigInteger.prototype.multiply = bnMultiply;
5349BigInteger.prototype.divide = bnDivide;
5350BigInteger.prototype.modPow = bnModPow; // "constants"
5351
5352BigInteger.ZERO = nbv(0);
5353BigInteger.ONE = nbv(1);
5354
5355/***/ }),
5356
5357/***/ "../amazon-cognito-identity-js/es/Client.js":
5358/*!**************************************************!*\
5359 !*** ../amazon-cognito-identity-js/es/Client.js ***!
5360 \**************************************************/
5361/*! exports provided: default */
5362/***/ (function(module, __webpack_exports__, __webpack_require__) {
5363
5364"use strict";
5365__webpack_require__.r(__webpack_exports__);
5366/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Client; });
5367/* harmony import */ var isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! isomorphic-unfetch */ "../../node_modules/isomorphic-unfetch/browser.js");
5368/* harmony import */ var isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_0__);
5369/* harmony import */ var _UserAgent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./UserAgent */ "../amazon-cognito-identity-js/es/UserAgent.js");
5370function _inheritsLoose(subClass, superClass) {
5371 subClass.prototype = Object.create(superClass.prototype);
5372 subClass.prototype.constructor = subClass;
5373
5374 _setPrototypeOf(subClass, superClass);
5375}
5376
5377function _wrapNativeSuper(Class) {
5378 var _cache = typeof Map === "function" ? new Map() : undefined;
5379
5380 _wrapNativeSuper = function _wrapNativeSuper(Class) {
5381 if (Class === null || !_isNativeFunction(Class)) return Class;
5382
5383 if (typeof Class !== "function") {
5384 throw new TypeError("Super expression must either be null or a function");
5385 }
5386
5387 if (typeof _cache !== "undefined") {
5388 if (_cache.has(Class)) return _cache.get(Class);
5389
5390 _cache.set(Class, Wrapper);
5391 }
5392
5393 function Wrapper() {
5394 return _construct(Class, arguments, _getPrototypeOf(this).constructor);
5395 }
5396
5397 Wrapper.prototype = Object.create(Class.prototype, {
5398 constructor: {
5399 value: Wrapper,
5400 enumerable: false,
5401 writable: true,
5402 configurable: true
5403 }
5404 });
5405 return _setPrototypeOf(Wrapper, Class);
5406 };
5407
5408 return _wrapNativeSuper(Class);
5409}
5410
5411function _construct(Parent, args, Class) {
5412 if (_isNativeReflectConstruct()) {
5413 _construct = Reflect.construct;
5414 } else {
5415 _construct = function _construct(Parent, args, Class) {
5416 var a = [null];
5417 a.push.apply(a, args);
5418 var Constructor = Function.bind.apply(Parent, a);
5419 var instance = new Constructor();
5420 if (Class) _setPrototypeOf(instance, Class.prototype);
5421 return instance;
5422 };
5423 }
5424
5425 return _construct.apply(null, arguments);
5426}
5427
5428function _isNativeReflectConstruct() {
5429 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
5430 if (Reflect.construct.sham) return false;
5431 if (typeof Proxy === "function") return true;
5432
5433 try {
5434 Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
5435 return true;
5436 } catch (e) {
5437 return false;
5438 }
5439}
5440
5441function _isNativeFunction(fn) {
5442 return Function.toString.call(fn).indexOf("[native code]") !== -1;
5443}
5444
5445function _setPrototypeOf(o, p) {
5446 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
5447 o.__proto__ = p;
5448 return o;
5449 };
5450
5451 return _setPrototypeOf(o, p);
5452}
5453
5454function _getPrototypeOf(o) {
5455 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
5456 return o.__proto__ || Object.getPrototypeOf(o);
5457 };
5458 return _getPrototypeOf(o);
5459}
5460
5461
5462
5463
5464var CognitoError = /*#__PURE__*/function (_Error) {
5465 _inheritsLoose(CognitoError, _Error);
5466
5467 function CognitoError(message, code, name, statusCode) {
5468 var _this;
5469
5470 _this = _Error.call(this, message) || this;
5471 _this.code = code;
5472 _this.name = name;
5473 _this.statusCode = statusCode;
5474 return _this;
5475 }
5476
5477 return CognitoError;
5478}( /*#__PURE__*/_wrapNativeSuper(Error));
5479/** @class */
5480
5481
5482var Client = /*#__PURE__*/function () {
5483 /**
5484 * Constructs a new AWS Cognito Identity Provider client object
5485 * @param {string} region AWS region
5486 * @param {string} endpoint endpoint
5487 * @param {object} fetchOptions options for fetch API (only credentials is supported)
5488 */
5489 function Client(region, endpoint, fetchOptions) {
5490 this.endpoint = endpoint || "https://cognito-idp." + region + ".amazonaws.com/";
5491
5492 var _ref = fetchOptions || {},
5493 credentials = _ref.credentials;
5494
5495 this.fetchOptions = credentials ? {
5496 credentials: credentials
5497 } : {};
5498 }
5499 /**
5500 * Makes an unauthenticated request on AWS Cognito Identity Provider API
5501 * using fetch
5502 * @param {string} operation API operation
5503 * @param {object} params Input parameters
5504 * @returns Promise<object>
5505 */
5506
5507
5508 var _proto = Client.prototype;
5509
5510 _proto.promisifyRequest = function promisifyRequest(operation, params) {
5511 var _this2 = this;
5512
5513 return new Promise(function (resolve, reject) {
5514 _this2.request(operation, params, function (err, data) {
5515 if (err) {
5516 reject(new CognitoError(err.message, err.code, err.name, err.statusCode));
5517 } else {
5518 resolve(data);
5519 }
5520 });
5521 });
5522 };
5523
5524 _proto.requestWithRetry = function requestWithRetry(operation, params, callback) {
5525 var _this3 = this;
5526
5527 var MAX_DELAY_IN_MILLIS = 5 * 1000;
5528 jitteredExponentialRetry(function (p) {
5529 return new Promise(function (res, rej) {
5530 _this3.request(operation, p, function (error, result) {
5531 if (error) {
5532 rej(error);
5533 } else {
5534 res(result);
5535 }
5536 });
5537 });
5538 }, [params], MAX_DELAY_IN_MILLIS).then(function (result) {
5539 return callback(null, result);
5540 })["catch"](function (error) {
5541 return callback(error);
5542 });
5543 }
5544 /**
5545 * Makes an unauthenticated request on AWS Cognito Identity Provider API
5546 * using fetch
5547 * @param {string} operation API operation
5548 * @param {object} params Input parameters
5549 * @param {function} callback Callback called when a response is returned
5550 * @returns {void}
5551 */
5552 ;
5553
5554 _proto.request = function request(operation, params, callback) {
5555 var headers = {
5556 'Content-Type': 'application/x-amz-json-1.1',
5557 'X-Amz-Target': "AWSCognitoIdentityProviderService." + operation,
5558 'X-Amz-User-Agent': _UserAgent__WEBPACK_IMPORTED_MODULE_1__["default"].prototype.userAgent
5559 };
5560 var options = Object.assign({}, this.fetchOptions, {
5561 headers: headers,
5562 method: 'POST',
5563 mode: 'cors',
5564 cache: 'no-cache',
5565 body: JSON.stringify(params)
5566 });
5567 var response;
5568 var responseJsonData;
5569 fetch(this.endpoint, options).then(function (resp) {
5570 response = resp;
5571 return resp;
5572 }, function (err) {
5573 // If error happens here, the request failed
5574 // if it is TypeError throw network error
5575 if (err instanceof TypeError) {
5576 throw new Error('Network error');
5577 }
5578
5579 throw err;
5580 }).then(function (resp) {
5581 return resp.json()["catch"](function () {
5582 return {};
5583 });
5584 }).then(function (data) {
5585 // return parsed body stream
5586 if (response.ok) return callback(null, data);
5587 responseJsonData = data; // Taken from aws-sdk-js/lib/protocol/json.js
5588 // eslint-disable-next-line no-underscore-dangle
5589
5590 var code = (data.__type || data.code).split('#').pop();
5591 var error = new Error(data.message || data.Message || null);
5592 error.name = code;
5593 error.code = code;
5594 return callback(error);
5595 })["catch"](function (err) {
5596 // first check if we have a service error
5597 if (response && response.headers && response.headers.get('x-amzn-errortype')) {
5598 try {
5599 var code = response.headers.get('x-amzn-errortype').split(':')[0];
5600 var error = new Error(response.status ? response.status.toString() : null);
5601 error.code = code;
5602 error.name = code;
5603 error.statusCode = response.status;
5604 return callback(error);
5605 } catch (ex) {
5606 return callback(err);
5607 } // otherwise check if error is Network error
5608
5609 } else if (err instanceof Error && err.message === 'Network error') {
5610 err.code = 'NetworkError';
5611 }
5612
5613 return callback(err);
5614 });
5615 };
5616
5617 return Client;
5618}();
5619
5620
5621var logger = {
5622 debug: function debug() {// Intentionally blank. This package doesn't have logging
5623 }
5624};
5625/**
5626 * For now, all errors are retryable.
5627 */
5628
5629var NonRetryableError = /*#__PURE__*/function (_Error2) {
5630 _inheritsLoose(NonRetryableError, _Error2);
5631
5632 function NonRetryableError(message) {
5633 var _this4;
5634
5635 _this4 = _Error2.call(this, message) || this;
5636 _this4.nonRetryable = true;
5637 return _this4;
5638 }
5639
5640 return NonRetryableError;
5641}( /*#__PURE__*/_wrapNativeSuper(Error));
5642
5643var isNonRetryableError = function isNonRetryableError(obj) {
5644 var key = 'nonRetryable';
5645 return obj && obj[key];
5646};
5647
5648function retry(functionToRetry, args, delayFn, attempt) {
5649 if (attempt === void 0) {
5650 attempt = 1;
5651 }
5652
5653 if (typeof functionToRetry !== 'function') {
5654 throw Error('functionToRetry must be a function');
5655 }
5656
5657 logger.debug(functionToRetry.name + " attempt #" + attempt + " with args: " + JSON.stringify(args));
5658 return functionToRetry.apply(void 0, args)["catch"](function (err) {
5659 logger.debug("error on " + functionToRetry.name, err);
5660
5661 if (isNonRetryableError(err)) {
5662 logger.debug(functionToRetry.name + " non retryable error", err);
5663 throw err;
5664 }
5665
5666 var retryIn = delayFn(attempt, args, err);
5667 logger.debug(functionToRetry.name + " retrying in " + retryIn + " ms");
5668
5669 if (retryIn !== false) {
5670 return new Promise(function (res) {
5671 return setTimeout(res, retryIn);
5672 }).then(function () {
5673 return retry(functionToRetry, args, delayFn, attempt + 1);
5674 });
5675 } else {
5676 throw err;
5677 }
5678 });
5679}
5680
5681function jitteredBackoff(maxDelayMs) {
5682 var BASE_TIME_MS = 100;
5683 var JITTER_FACTOR = 100;
5684 return function (attempt) {
5685 var delay = Math.pow(2, attempt) * BASE_TIME_MS + JITTER_FACTOR * Math.random();
5686 return delay > maxDelayMs ? false : delay;
5687 };
5688}
5689
5690var MAX_DELAY_MS = 5 * 60 * 1000;
5691
5692function jitteredExponentialRetry(functionToRetry, args, maxDelayMs) {
5693 if (maxDelayMs === void 0) {
5694 maxDelayMs = MAX_DELAY_MS;
5695 }
5696
5697 return retry(functionToRetry, args, jitteredBackoff(maxDelayMs));
5698}
5699
5700;
5701
5702/***/ }),
5703
5704/***/ "../amazon-cognito-identity-js/es/CognitoAccessToken.js":
5705/*!**************************************************************!*\
5706 !*** ../amazon-cognito-identity-js/es/CognitoAccessToken.js ***!
5707 \**************************************************************/
5708/*! exports provided: default */
5709/***/ (function(module, __webpack_exports__, __webpack_require__) {
5710
5711"use strict";
5712__webpack_require__.r(__webpack_exports__);
5713/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoAccessToken; });
5714/* harmony import */ var _CognitoJwtToken__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CognitoJwtToken */ "../amazon-cognito-identity-js/es/CognitoJwtToken.js");
5715function _inheritsLoose(subClass, superClass) {
5716 subClass.prototype = Object.create(superClass.prototype);
5717 subClass.prototype.constructor = subClass;
5718
5719 _setPrototypeOf(subClass, superClass);
5720}
5721
5722function _setPrototypeOf(o, p) {
5723 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
5724 o.__proto__ = p;
5725 return o;
5726 };
5727
5728 return _setPrototypeOf(o, p);
5729}
5730/*
5731 * Copyright 2016 Amazon.com,
5732 * Inc. or its affiliates. All Rights Reserved.
5733 *
5734 * Licensed under the Amazon Software License (the "License").
5735 * You may not use this file except in compliance with the
5736 * License. A copy of the License is located at
5737 *
5738 * http://aws.amazon.com/asl/
5739 *
5740 * or in the "license" file accompanying this file. This file is
5741 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
5742 * CONDITIONS OF ANY KIND, express or implied. See the License
5743 * for the specific language governing permissions and
5744 * limitations under the License.
5745 */
5746
5747
5748
5749/** @class */
5750
5751var CognitoAccessToken = /*#__PURE__*/function (_CognitoJwtToken) {
5752 _inheritsLoose(CognitoAccessToken, _CognitoJwtToken);
5753 /**
5754 * Constructs a new CognitoAccessToken object
5755 * @param {string=} AccessToken The JWT access token.
5756 */
5757
5758
5759 function CognitoAccessToken(_temp) {
5760 var _ref = _temp === void 0 ? {} : _temp,
5761 AccessToken = _ref.AccessToken;
5762
5763 return _CognitoJwtToken.call(this, AccessToken || '') || this;
5764 }
5765
5766 return CognitoAccessToken;
5767}(_CognitoJwtToken__WEBPACK_IMPORTED_MODULE_0__["default"]);
5768
5769
5770
5771/***/ }),
5772
5773/***/ "../amazon-cognito-identity-js/es/CognitoIdToken.js":
5774/*!**********************************************************!*\
5775 !*** ../amazon-cognito-identity-js/es/CognitoIdToken.js ***!
5776 \**********************************************************/
5777/*! exports provided: default */
5778/***/ (function(module, __webpack_exports__, __webpack_require__) {
5779
5780"use strict";
5781__webpack_require__.r(__webpack_exports__);
5782/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoIdToken; });
5783/* harmony import */ var _CognitoJwtToken__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CognitoJwtToken */ "../amazon-cognito-identity-js/es/CognitoJwtToken.js");
5784function _inheritsLoose(subClass, superClass) {
5785 subClass.prototype = Object.create(superClass.prototype);
5786 subClass.prototype.constructor = subClass;
5787
5788 _setPrototypeOf(subClass, superClass);
5789}
5790
5791function _setPrototypeOf(o, p) {
5792 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
5793 o.__proto__ = p;
5794 return o;
5795 };
5796
5797 return _setPrototypeOf(o, p);
5798}
5799/*!
5800 * Copyright 2016 Amazon.com,
5801 * Inc. or its affiliates. All Rights Reserved.
5802 *
5803 * Licensed under the Amazon Software License (the "License").
5804 * You may not use this file except in compliance with the
5805 * License. A copy of the License is located at
5806 *
5807 * http://aws.amazon.com/asl/
5808 *
5809 * or in the "license" file accompanying this file. This file is
5810 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
5811 * CONDITIONS OF ANY KIND, express or implied. See the License
5812 * for the specific language governing permissions and
5813 * limitations under the License.
5814 */
5815
5816
5817
5818/** @class */
5819
5820var CognitoIdToken = /*#__PURE__*/function (_CognitoJwtToken) {
5821 _inheritsLoose(CognitoIdToken, _CognitoJwtToken);
5822 /**
5823 * Constructs a new CognitoIdToken object
5824 * @param {string=} IdToken The JWT Id token
5825 */
5826
5827
5828 function CognitoIdToken(_temp) {
5829 var _ref = _temp === void 0 ? {} : _temp,
5830 IdToken = _ref.IdToken;
5831
5832 return _CognitoJwtToken.call(this, IdToken || '') || this;
5833 }
5834
5835 return CognitoIdToken;
5836}(_CognitoJwtToken__WEBPACK_IMPORTED_MODULE_0__["default"]);
5837
5838
5839
5840/***/ }),
5841
5842/***/ "../amazon-cognito-identity-js/es/CognitoJwtToken.js":
5843/*!***********************************************************!*\
5844 !*** ../amazon-cognito-identity-js/es/CognitoJwtToken.js ***!
5845 \***********************************************************/
5846/*! exports provided: default */
5847/***/ (function(module, __webpack_exports__, __webpack_require__) {
5848
5849"use strict";
5850__webpack_require__.r(__webpack_exports__);
5851/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoJwtToken; });
5852/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer */ "../../node_modules/buffer/index.js");
5853/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(buffer__WEBPACK_IMPORTED_MODULE_0__);
5854/*!
5855 * Copyright 2016 Amazon.com,
5856 * Inc. or its affiliates. All Rights Reserved.
5857 *
5858 * Licensed under the Amazon Software License (the "License").
5859 * You may not use this file except in compliance with the
5860 * License. A copy of the License is located at
5861 *
5862 * http://aws.amazon.com/asl/
5863 *
5864 * or in the "license" file accompanying this file. This file is
5865 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
5866 * CONDITIONS OF ANY KIND, express or implied. See the License
5867 * for the specific language governing permissions and
5868 * limitations under the License.
5869 */
5870
5871/** @class */
5872
5873var CognitoJwtToken = /*#__PURE__*/function () {
5874 /**
5875 * Constructs a new CognitoJwtToken object
5876 * @param {string=} token The JWT token.
5877 */
5878 function CognitoJwtToken(token) {
5879 // Assign object
5880 this.jwtToken = token || '';
5881 this.payload = this.decodePayload();
5882 }
5883 /**
5884 * @returns {string} the record's token.
5885 */
5886
5887
5888 var _proto = CognitoJwtToken.prototype;
5889
5890 _proto.getJwtToken = function getJwtToken() {
5891 return this.jwtToken;
5892 }
5893 /**
5894 * @returns {int} the token's expiration (exp member).
5895 */
5896 ;
5897
5898 _proto.getExpiration = function getExpiration() {
5899 return this.payload.exp;
5900 }
5901 /**
5902 * @returns {int} the token's "issued at" (iat member).
5903 */
5904 ;
5905
5906 _proto.getIssuedAt = function getIssuedAt() {
5907 return this.payload.iat;
5908 }
5909 /**
5910 * @returns {object} the token's payload.
5911 */
5912 ;
5913
5914 _proto.decodePayload = function decodePayload() {
5915 var payload = this.jwtToken.split('.')[1];
5916
5917 try {
5918 return JSON.parse(buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(payload, 'base64').toString('utf8'));
5919 } catch (err) {
5920 return {};
5921 }
5922 };
5923
5924 return CognitoJwtToken;
5925}();
5926
5927
5928
5929/***/ }),
5930
5931/***/ "../amazon-cognito-identity-js/es/CognitoRefreshToken.js":
5932/*!***************************************************************!*\
5933 !*** ../amazon-cognito-identity-js/es/CognitoRefreshToken.js ***!
5934 \***************************************************************/
5935/*! exports provided: default */
5936/***/ (function(module, __webpack_exports__, __webpack_require__) {
5937
5938"use strict";
5939__webpack_require__.r(__webpack_exports__);
5940/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoRefreshToken; });
5941/*!
5942 * Copyright 2016 Amazon.com,
5943 * Inc. or its affiliates. All Rights Reserved.
5944 *
5945 * Licensed under the Amazon Software License (the "License").
5946 * You may not use this file except in compliance with the
5947 * License. A copy of the License is located at
5948 *
5949 * http://aws.amazon.com/asl/
5950 *
5951 * or in the "license" file accompanying this file. This file is
5952 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
5953 * CONDITIONS OF ANY KIND, express or implied. See the License
5954 * for the specific language governing permissions and
5955 * limitations under the License.
5956 */
5957
5958/** @class */
5959var CognitoRefreshToken = /*#__PURE__*/function () {
5960 /**
5961 * Constructs a new CognitoRefreshToken object
5962 * @param {string=} RefreshToken The JWT refresh token.
5963 */
5964 function CognitoRefreshToken(_temp) {
5965 var _ref = _temp === void 0 ? {} : _temp,
5966 RefreshToken = _ref.RefreshToken; // Assign object
5967
5968
5969 this.token = RefreshToken || '';
5970 }
5971 /**
5972 * @returns {string} the record's token.
5973 */
5974
5975
5976 var _proto = CognitoRefreshToken.prototype;
5977
5978 _proto.getToken = function getToken() {
5979 return this.token;
5980 };
5981
5982 return CognitoRefreshToken;
5983}();
5984
5985
5986
5987/***/ }),
5988
5989/***/ "../amazon-cognito-identity-js/es/CognitoUser.js":
5990/*!*******************************************************!*\
5991 !*** ../amazon-cognito-identity-js/es/CognitoUser.js ***!
5992 \*******************************************************/
5993/*! exports provided: default */
5994/***/ (function(module, __webpack_exports__, __webpack_require__) {
5995
5996"use strict";
5997__webpack_require__.r(__webpack_exports__);
5998/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoUser; });
5999/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer */ "../../node_modules/buffer/index.js");
6000/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(buffer__WEBPACK_IMPORTED_MODULE_0__);
6001/* harmony import */ var crypto_js_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! crypto-js/core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js");
6002/* harmony import */ var crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(crypto_js_core__WEBPACK_IMPORTED_MODULE_1__);
6003/* harmony import */ var crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! crypto-js/lib-typedarrays */ "../amazon-cognito-identity-js/node_modules/crypto-js/lib-typedarrays.js");
6004/* harmony import */ var crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2__);
6005/* harmony import */ var crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! crypto-js/enc-base64 */ "../amazon-cognito-identity-js/node_modules/crypto-js/enc-base64.js");
6006/* harmony import */ var crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3__);
6007/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! crypto-js/hmac-sha256 */ "../amazon-cognito-identity-js/node_modules/crypto-js/hmac-sha256.js");
6008/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4__);
6009/* harmony import */ var _BigInteger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./BigInteger */ "../amazon-cognito-identity-js/es/BigInteger.js");
6010/* harmony import */ var _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./AuthenticationHelper */ "../amazon-cognito-identity-js/es/AuthenticationHelper.js");
6011/* harmony import */ var _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CognitoAccessToken */ "../amazon-cognito-identity-js/es/CognitoAccessToken.js");
6012/* harmony import */ var _CognitoIdToken__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./CognitoIdToken */ "../amazon-cognito-identity-js/es/CognitoIdToken.js");
6013/* harmony import */ var _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./CognitoRefreshToken */ "../amazon-cognito-identity-js/es/CognitoRefreshToken.js");
6014/* harmony import */ var _CognitoUserSession__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./CognitoUserSession */ "../amazon-cognito-identity-js/es/CognitoUserSession.js");
6015/* harmony import */ var _DateHelper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./DateHelper */ "../amazon-cognito-identity-js/es/DateHelper.js");
6016/* harmony import */ var _CognitoUserAttribute__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./CognitoUserAttribute */ "../amazon-cognito-identity-js/es/CognitoUserAttribute.js");
6017/* harmony import */ var _StorageHelper__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./StorageHelper */ "../amazon-cognito-identity-js/es/StorageHelper.js");
6018/*!
6019 * Copyright 2016 Amazon.com,
6020 * Inc. or its affiliates. All Rights Reserved.
6021 *
6022 * Licensed under the Amazon Software License (the "License").
6023 * You may not use this file except in compliance with the
6024 * License. A copy of the License is located at
6025 *
6026 * http://aws.amazon.com/asl/
6027 *
6028 * or in the "license" file accompanying this file. This file is
6029 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6030 * CONDITIONS OF ANY KIND, express or implied. See the License
6031 * for the specific language governing permissions and
6032 * limitations under the License.
6033 */
6034
6035
6036 // necessary for crypto js
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049/**
6050 * @callback nodeCallback
6051 * @template T result
6052 * @param {*} err The operation failure reason, or null.
6053 * @param {T} result The operation result.
6054 */
6055
6056/**
6057 * @callback onFailure
6058 * @param {*} err Failure reason.
6059 */
6060
6061/**
6062 * @callback onSuccess
6063 * @template T result
6064 * @param {T} result The operation result.
6065 */
6066
6067/**
6068 * @callback mfaRequired
6069 * @param {*} details MFA challenge details.
6070 */
6071
6072/**
6073 * @callback customChallenge
6074 * @param {*} details Custom challenge details.
6075 */
6076
6077/**
6078 * @callback inputVerificationCode
6079 * @param {*} data Server response.
6080 */
6081
6082/**
6083 * @callback authSuccess
6084 * @param {CognitoUserSession} session The new session.
6085 * @param {bool=} userConfirmationNecessary User must be confirmed.
6086 */
6087
6088var isBrowser = typeof navigator !== 'undefined';
6089var userAgent = isBrowser ? navigator.userAgent : 'nodejs';
6090/** @class */
6091
6092var CognitoUser = /*#__PURE__*/function () {
6093 /**
6094 * Constructs a new CognitoUser object
6095 * @param {object} data Creation options
6096 * @param {string} data.Username The user's username.
6097 * @param {CognitoUserPool} data.Pool Pool containing the user.
6098 * @param {object} data.Storage Optional storage object.
6099 */
6100 function CognitoUser(data) {
6101 if (data == null || data.Username == null || data.Pool == null) {
6102 throw new Error('Username and Pool information are required.');
6103 }
6104
6105 this.username = data.Username || '';
6106 this.pool = data.Pool;
6107 this.Session = null;
6108 this.client = data.Pool.client;
6109 this.signInUserSession = null;
6110 this.authenticationFlowType = 'USER_SRP_AUTH';
6111 this.storage = data.Storage || new _StorageHelper__WEBPACK_IMPORTED_MODULE_13__["default"]().getStorage();
6112 this.keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
6113 this.userDataKey = this.keyPrefix + "." + this.username + ".userData";
6114 }
6115 /**
6116 * Sets the session for this user
6117 * @param {CognitoUserSession} signInUserSession the session
6118 * @returns {void}
6119 */
6120
6121
6122 var _proto = CognitoUser.prototype;
6123
6124 _proto.setSignInUserSession = function setSignInUserSession(signInUserSession) {
6125 this.clearCachedUserData();
6126 this.signInUserSession = signInUserSession;
6127 this.cacheTokens();
6128 }
6129 /**
6130 * @returns {CognitoUserSession} the current session for this user
6131 */
6132 ;
6133
6134 _proto.getSignInUserSession = function getSignInUserSession() {
6135 return this.signInUserSession;
6136 }
6137 /**
6138 * @returns {string} the user's username
6139 */
6140 ;
6141
6142 _proto.getUsername = function getUsername() {
6143 return this.username;
6144 }
6145 /**
6146 * @returns {String} the authentication flow type
6147 */
6148 ;
6149
6150 _proto.getAuthenticationFlowType = function getAuthenticationFlowType() {
6151 return this.authenticationFlowType;
6152 }
6153 /**
6154 * sets authentication flow type
6155 * @param {string} authenticationFlowType New value.
6156 * @returns {void}
6157 */
6158 ;
6159
6160 _proto.setAuthenticationFlowType = function setAuthenticationFlowType(authenticationFlowType) {
6161 this.authenticationFlowType = authenticationFlowType;
6162 }
6163 /**
6164 * This is used for authenticating the user through the custom authentication flow.
6165 * @param {AuthenticationDetails} authDetails Contains the authentication data
6166 * @param {object} callback Result callback map.
6167 * @param {onFailure} callback.onFailure Called on any error.
6168 * @param {customChallenge} callback.customChallenge Custom challenge
6169 * response required to continue.
6170 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6171 * @returns {void}
6172 */
6173 ;
6174
6175 _proto.initiateAuth = function initiateAuth(authDetails, callback) {
6176 var _this = this;
6177
6178 var authParameters = authDetails.getAuthParameters();
6179 authParameters.USERNAME = this.username;
6180 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
6181 var jsonReq = {
6182 AuthFlow: 'CUSTOM_AUTH',
6183 ClientId: this.pool.getClientId(),
6184 AuthParameters: authParameters,
6185 ClientMetadata: clientMetaData
6186 };
6187
6188 if (this.getUserContextData()) {
6189 jsonReq.UserContextData = this.getUserContextData();
6190 }
6191
6192 this.client.request('InitiateAuth', jsonReq, function (err, data) {
6193 if (err) {
6194 return callback.onFailure(err);
6195 }
6196
6197 var challengeName = data.ChallengeName;
6198 var challengeParameters = data.ChallengeParameters;
6199
6200 if (challengeName === 'CUSTOM_CHALLENGE') {
6201 _this.Session = data.Session;
6202 return callback.customChallenge(challengeParameters);
6203 }
6204
6205 _this.signInUserSession = _this.getCognitoUserSession(data.AuthenticationResult);
6206
6207 _this.cacheTokens();
6208
6209 return callback.onSuccess(_this.signInUserSession);
6210 });
6211 }
6212 /**
6213 * This is used for authenticating the user.
6214 * stuff
6215 * @param {AuthenticationDetails} authDetails Contains the authentication data
6216 * @param {object} callback Result callback map.
6217 * @param {onFailure} callback.onFailure Called on any error.
6218 * @param {newPasswordRequired} callback.newPasswordRequired new
6219 * password and any required attributes are required to continue
6220 * @param {mfaRequired} callback.mfaRequired MFA code
6221 * required to continue.
6222 * @param {customChallenge} callback.customChallenge Custom challenge
6223 * response required to continue.
6224 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6225 * @returns {void}
6226 */
6227 ;
6228
6229 _proto.authenticateUser = function authenticateUser(authDetails, callback) {
6230 if (this.authenticationFlowType === 'USER_PASSWORD_AUTH') {
6231 return this.authenticateUserPlainUsernamePassword(authDetails, callback);
6232 } else if (this.authenticationFlowType === 'USER_SRP_AUTH' || this.authenticationFlowType === 'CUSTOM_AUTH') {
6233 return this.authenticateUserDefaultAuth(authDetails, callback);
6234 }
6235
6236 return callback.onFailure(new Error('Authentication flow type is invalid.'));
6237 }
6238 /**
6239 * PRIVATE ONLY: This is an internal only method and should not
6240 * be directly called by the consumers.
6241 * It calls the AuthenticationHelper for SRP related
6242 * stuff
6243 * @param {AuthenticationDetails} authDetails Contains the authentication data
6244 * @param {object} callback Result callback map.
6245 * @param {onFailure} callback.onFailure Called on any error.
6246 * @param {newPasswordRequired} callback.newPasswordRequired new
6247 * password and any required attributes are required to continue
6248 * @param {mfaRequired} callback.mfaRequired MFA code
6249 * required to continue.
6250 * @param {customChallenge} callback.customChallenge Custom challenge
6251 * response required to continue.
6252 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6253 * @returns {void}
6254 */
6255 ;
6256
6257 _proto.authenticateUserDefaultAuth = function authenticateUserDefaultAuth(authDetails, callback) {
6258 var _this2 = this;
6259
6260 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.pool.getUserPoolId().split('_')[1]);
6261 var dateHelper = new _DateHelper__WEBPACK_IMPORTED_MODULE_11__["default"]();
6262 var serverBValue;
6263 var salt;
6264 var authParameters = {};
6265
6266 if (this.deviceKey != null) {
6267 authParameters.DEVICE_KEY = this.deviceKey;
6268 }
6269
6270 authParameters.USERNAME = this.username;
6271 authenticationHelper.getLargeAValue(function (errOnAValue, aValue) {
6272 // getLargeAValue callback start
6273 if (errOnAValue) {
6274 callback.onFailure(errOnAValue);
6275 }
6276
6277 authParameters.SRP_A = aValue.toString(16);
6278
6279 if (_this2.authenticationFlowType === 'CUSTOM_AUTH') {
6280 authParameters.CHALLENGE_NAME = 'SRP_A';
6281 }
6282
6283 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
6284 var jsonReq = {
6285 AuthFlow: _this2.authenticationFlowType,
6286 ClientId: _this2.pool.getClientId(),
6287 AuthParameters: authParameters,
6288 ClientMetadata: clientMetaData
6289 };
6290
6291 if (_this2.getUserContextData(_this2.username)) {
6292 jsonReq.UserContextData = _this2.getUserContextData(_this2.username);
6293 }
6294
6295 _this2.client.request('InitiateAuth', jsonReq, function (err, data) {
6296 if (err) {
6297 return callback.onFailure(err);
6298 }
6299
6300 var challengeParameters = data.ChallengeParameters;
6301 _this2.username = challengeParameters.USER_ID_FOR_SRP;
6302 _this2.userDataKey = _this2.keyPrefix + "." + _this2.username + ".userData";
6303 serverBValue = new _BigInteger__WEBPACK_IMPORTED_MODULE_5__["default"](challengeParameters.SRP_B, 16);
6304 salt = new _BigInteger__WEBPACK_IMPORTED_MODULE_5__["default"](challengeParameters.SALT, 16);
6305
6306 _this2.getCachedDeviceKeyAndPassword();
6307
6308 authenticationHelper.getPasswordAuthenticationKey(_this2.username, authDetails.getPassword(), serverBValue, salt, function (errOnHkdf, hkdf) {
6309 // getPasswordAuthenticationKey callback start
6310 if (errOnHkdf) {
6311 callback.onFailure(errOnHkdf);
6312 }
6313
6314 var dateNow = dateHelper.getNowString();
6315 var message = crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].concat([buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(_this2.pool.getUserPoolId().split('_')[1], 'utf8'), buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(_this2.username, 'utf8'), buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(challengeParameters.SECRET_BLOCK, 'base64'), buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(dateNow, 'utf8')]));
6316 var key = crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(hkdf);
6317 var signatureString = crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3___default.a.stringify(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default()(message, key));
6318 var challengeResponses = {};
6319 challengeResponses.USERNAME = _this2.username;
6320 challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK;
6321 challengeResponses.TIMESTAMP = dateNow;
6322 challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString;
6323
6324 if (_this2.deviceKey != null) {
6325 challengeResponses.DEVICE_KEY = _this2.deviceKey;
6326 }
6327
6328 var respondToAuthChallenge = function respondToAuthChallenge(challenge, challengeCallback) {
6329 return _this2.client.request('RespondToAuthChallenge', challenge, function (errChallenge, dataChallenge) {
6330 if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) {
6331 challengeResponses.DEVICE_KEY = null;
6332 _this2.deviceKey = null;
6333 _this2.randomPassword = null;
6334 _this2.deviceGroupKey = null;
6335
6336 _this2.clearCachedDeviceKeyAndPassword();
6337
6338 return respondToAuthChallenge(challenge, challengeCallback);
6339 }
6340
6341 return challengeCallback(errChallenge, dataChallenge);
6342 });
6343 };
6344
6345 var jsonReqResp = {
6346 ChallengeName: 'PASSWORD_VERIFIER',
6347 ClientId: _this2.pool.getClientId(),
6348 ChallengeResponses: challengeResponses,
6349 Session: data.Session,
6350 ClientMetadata: clientMetaData
6351 };
6352
6353 if (_this2.getUserContextData()) {
6354 jsonReqResp.UserContextData = _this2.getUserContextData();
6355 }
6356
6357 respondToAuthChallenge(jsonReqResp, function (errAuthenticate, dataAuthenticate) {
6358 if (errAuthenticate) {
6359 return callback.onFailure(errAuthenticate);
6360 }
6361
6362 return _this2.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback);
6363 });
6364 return undefined; // getPasswordAuthenticationKey callback end
6365 });
6366 return undefined;
6367 }); // getLargeAValue callback end
6368
6369 });
6370 }
6371 /**
6372 * PRIVATE ONLY: This is an internal only method and should not
6373 * be directly called by the consumers.
6374 * @param {AuthenticationDetails} authDetails Contains the authentication data.
6375 * @param {object} callback Result callback map.
6376 * @param {onFailure} callback.onFailure Called on any error.
6377 * @param {mfaRequired} callback.mfaRequired MFA code
6378 * required to continue.
6379 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6380 * @returns {void}
6381 */
6382 ;
6383
6384 _proto.authenticateUserPlainUsernamePassword = function authenticateUserPlainUsernamePassword(authDetails, callback) {
6385 var _this3 = this;
6386
6387 var authParameters = {};
6388 authParameters.USERNAME = this.username;
6389 authParameters.PASSWORD = authDetails.getPassword();
6390
6391 if (!authParameters.PASSWORD) {
6392 callback.onFailure(new Error('PASSWORD parameter is required'));
6393 return;
6394 }
6395
6396 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.pool.getUserPoolId().split('_')[1]);
6397 this.getCachedDeviceKeyAndPassword();
6398
6399 if (this.deviceKey != null) {
6400 authParameters.DEVICE_KEY = this.deviceKey;
6401 }
6402
6403 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
6404 var jsonReq = {
6405 AuthFlow: 'USER_PASSWORD_AUTH',
6406 ClientId: this.pool.getClientId(),
6407 AuthParameters: authParameters,
6408 ClientMetadata: clientMetaData
6409 };
6410
6411 if (this.getUserContextData(this.username)) {
6412 jsonReq.UserContextData = this.getUserContextData(this.username);
6413 } // USER_PASSWORD_AUTH happens in a single round-trip: client sends userName and password,
6414 // Cognito UserPools verifies password and returns tokens.
6415
6416
6417 this.client.request('InitiateAuth', jsonReq, function (err, authResult) {
6418 if (err) {
6419 return callback.onFailure(err);
6420 }
6421
6422 return _this3.authenticateUserInternal(authResult, authenticationHelper, callback);
6423 });
6424 }
6425 /**
6426 * PRIVATE ONLY: This is an internal only method and should not
6427 * be directly called by the consumers.
6428 * @param {object} dataAuthenticate authentication data
6429 * @param {object} authenticationHelper helper created
6430 * @param {callback} callback passed on from caller
6431 * @returns {void}
6432 */
6433 ;
6434
6435 _proto.authenticateUserInternal = function authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) {
6436 var _this4 = this;
6437
6438 var challengeName = dataAuthenticate.ChallengeName;
6439 var challengeParameters = dataAuthenticate.ChallengeParameters;
6440
6441 if (challengeName === 'SMS_MFA') {
6442 this.Session = dataAuthenticate.Session;
6443 return callback.mfaRequired(challengeName, challengeParameters);
6444 }
6445
6446 if (challengeName === 'SELECT_MFA_TYPE') {
6447 this.Session = dataAuthenticate.Session;
6448 return callback.selectMFAType(challengeName, challengeParameters);
6449 }
6450
6451 if (challengeName === 'MFA_SETUP') {
6452 this.Session = dataAuthenticate.Session;
6453 return callback.mfaSetup(challengeName, challengeParameters);
6454 }
6455
6456 if (challengeName === 'SOFTWARE_TOKEN_MFA') {
6457 this.Session = dataAuthenticate.Session;
6458 return callback.totpRequired(challengeName, challengeParameters);
6459 }
6460
6461 if (challengeName === 'CUSTOM_CHALLENGE') {
6462 this.Session = dataAuthenticate.Session;
6463 return callback.customChallenge(challengeParameters);
6464 }
6465
6466 if (challengeName === 'NEW_PASSWORD_REQUIRED') {
6467 this.Session = dataAuthenticate.Session;
6468 var userAttributes = null;
6469 var rawRequiredAttributes = null;
6470 var requiredAttributes = [];
6471 var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix();
6472
6473 if (challengeParameters) {
6474 userAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.userAttributes);
6475 rawRequiredAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.requiredAttributes);
6476 }
6477
6478 if (rawRequiredAttributes) {
6479 for (var i = 0; i < rawRequiredAttributes.length; i++) {
6480 requiredAttributes[i] = rawRequiredAttributes[i].substr(userAttributesPrefix.length);
6481 }
6482 }
6483
6484 return callback.newPasswordRequired(userAttributes, requiredAttributes);
6485 }
6486
6487 if (challengeName === 'DEVICE_SRP_AUTH') {
6488 this.Session = dataAuthenticate.Session;
6489 this.getDeviceResponse(callback);
6490 return undefined;
6491 }
6492
6493 this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
6494 this.challengeName = challengeName;
6495 this.cacheTokens();
6496 var newDeviceMetadata = dataAuthenticate.AuthenticationResult.NewDeviceMetadata;
6497
6498 if (newDeviceMetadata == null) {
6499 return callback.onSuccess(this.signInUserSession);
6500 }
6501
6502 authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) {
6503 if (errGenHash) {
6504 return callback.onFailure(errGenHash);
6505 }
6506
6507 var deviceSecretVerifierConfig = {
6508 Salt: buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'),
6509 PasswordVerifier: buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64')
6510 };
6511 _this4.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier;
6512 _this4.deviceGroupKey = newDeviceMetadata.DeviceGroupKey;
6513 _this4.randomPassword = authenticationHelper.getRandomPassword();
6514
6515 _this4.client.request('ConfirmDevice', {
6516 DeviceKey: newDeviceMetadata.DeviceKey,
6517 AccessToken: _this4.signInUserSession.getAccessToken().getJwtToken(),
6518 DeviceSecretVerifierConfig: deviceSecretVerifierConfig,
6519 DeviceName: userAgent
6520 }, function (errConfirm, dataConfirm) {
6521 if (errConfirm) {
6522 return callback.onFailure(errConfirm);
6523 }
6524
6525 _this4.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey;
6526
6527 _this4.cacheDeviceKeyAndPassword();
6528
6529 if (dataConfirm.UserConfirmationNecessary === true) {
6530 return callback.onSuccess(_this4.signInUserSession, dataConfirm.UserConfirmationNecessary);
6531 }
6532
6533 return callback.onSuccess(_this4.signInUserSession);
6534 });
6535
6536 return undefined;
6537 });
6538 return undefined;
6539 }
6540 /**
6541 * This method is user to complete the NEW_PASSWORD_REQUIRED challenge.
6542 * Pass the new password with any new user attributes to be updated.
6543 * User attribute keys must be of format userAttributes.<attribute_name>.
6544 * @param {string} newPassword new password for this user
6545 * @param {object} requiredAttributeData map with values for all required attributes
6546 * @param {object} callback Result callback map.
6547 * @param {onFailure} callback.onFailure Called on any error.
6548 * @param {mfaRequired} callback.mfaRequired MFA code required to continue.
6549 * @param {customChallenge} callback.customChallenge Custom challenge
6550 * response required to continue.
6551 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6552 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6553 * @returns {void}
6554 */
6555 ;
6556
6557 _proto.completeNewPasswordChallenge = function completeNewPasswordChallenge(newPassword, requiredAttributeData, callback, clientMetadata) {
6558 var _this5 = this;
6559
6560 if (!newPassword) {
6561 return callback.onFailure(new Error('New password is required.'));
6562 }
6563
6564 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.pool.getUserPoolId().split('_')[1]);
6565 var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix();
6566 var finalUserAttributes = {};
6567
6568 if (requiredAttributeData) {
6569 Object.keys(requiredAttributeData).forEach(function (key) {
6570 finalUserAttributes[userAttributesPrefix + key] = requiredAttributeData[key];
6571 });
6572 }
6573
6574 finalUserAttributes.NEW_PASSWORD = newPassword;
6575 finalUserAttributes.USERNAME = this.username;
6576 var jsonReq = {
6577 ChallengeName: 'NEW_PASSWORD_REQUIRED',
6578 ClientId: this.pool.getClientId(),
6579 ChallengeResponses: finalUserAttributes,
6580 Session: this.Session,
6581 ClientMetadata: clientMetadata
6582 };
6583
6584 if (this.getUserContextData()) {
6585 jsonReq.UserContextData = this.getUserContextData();
6586 }
6587
6588 this.client.request('RespondToAuthChallenge', jsonReq, function (errAuthenticate, dataAuthenticate) {
6589 if (errAuthenticate) {
6590 return callback.onFailure(errAuthenticate);
6591 }
6592
6593 return _this5.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback);
6594 });
6595 return undefined;
6596 }
6597 /**
6598 * This is used to get a session using device authentication. It is called at the end of user
6599 * authentication
6600 *
6601 * @param {object} callback Result callback map.
6602 * @param {onFailure} callback.onFailure Called on any error.
6603 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6604 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6605 * @returns {void}
6606 * @private
6607 */
6608 ;
6609
6610 _proto.getDeviceResponse = function getDeviceResponse(callback, clientMetadata) {
6611 var _this6 = this;
6612
6613 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.deviceGroupKey);
6614 var dateHelper = new _DateHelper__WEBPACK_IMPORTED_MODULE_11__["default"]();
6615 var authParameters = {};
6616 authParameters.USERNAME = this.username;
6617 authParameters.DEVICE_KEY = this.deviceKey;
6618 authenticationHelper.getLargeAValue(function (errAValue, aValue) {
6619 // getLargeAValue callback start
6620 if (errAValue) {
6621 callback.onFailure(errAValue);
6622 }
6623
6624 authParameters.SRP_A = aValue.toString(16);
6625 var jsonReq = {
6626 ChallengeName: 'DEVICE_SRP_AUTH',
6627 ClientId: _this6.pool.getClientId(),
6628 ChallengeResponses: authParameters,
6629 ClientMetadata: clientMetadata,
6630 Session: _this6.Session
6631 };
6632
6633 if (_this6.getUserContextData()) {
6634 jsonReq.UserContextData = _this6.getUserContextData();
6635 }
6636
6637 _this6.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
6638 if (err) {
6639 return callback.onFailure(err);
6640 }
6641
6642 var challengeParameters = data.ChallengeParameters;
6643 var serverBValue = new _BigInteger__WEBPACK_IMPORTED_MODULE_5__["default"](challengeParameters.SRP_B, 16);
6644 var salt = new _BigInteger__WEBPACK_IMPORTED_MODULE_5__["default"](challengeParameters.SALT, 16);
6645 authenticationHelper.getPasswordAuthenticationKey(_this6.deviceKey, _this6.randomPassword, serverBValue, salt, function (errHkdf, hkdf) {
6646 // getPasswordAuthenticationKey callback start
6647 if (errHkdf) {
6648 return callback.onFailure(errHkdf);
6649 }
6650
6651 var dateNow = dateHelper.getNowString();
6652 var message = crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].concat([buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(_this6.deviceGroupKey, 'utf8'), buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(_this6.deviceKey, 'utf8'), buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(challengeParameters.SECRET_BLOCK, 'base64'), buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(dateNow, 'utf8')]));
6653 var key = crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(hkdf);
6654 var signatureString = crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3___default.a.stringify(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default()(message, key));
6655 var challengeResponses = {};
6656 challengeResponses.USERNAME = _this6.username;
6657 challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK;
6658 challengeResponses.TIMESTAMP = dateNow;
6659 challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString;
6660 challengeResponses.DEVICE_KEY = _this6.deviceKey;
6661 var jsonReqResp = {
6662 ChallengeName: 'DEVICE_PASSWORD_VERIFIER',
6663 ClientId: _this6.pool.getClientId(),
6664 ChallengeResponses: challengeResponses,
6665 Session: data.Session
6666 };
6667
6668 if (_this6.getUserContextData()) {
6669 jsonReqResp.UserContextData = _this6.getUserContextData();
6670 }
6671
6672 _this6.client.request('RespondToAuthChallenge', jsonReqResp, function (errAuthenticate, dataAuthenticate) {
6673 if (errAuthenticate) {
6674 return callback.onFailure(errAuthenticate);
6675 }
6676
6677 _this6.signInUserSession = _this6.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
6678
6679 _this6.cacheTokens();
6680
6681 return callback.onSuccess(_this6.signInUserSession);
6682 });
6683
6684 return undefined; // getPasswordAuthenticationKey callback end
6685 });
6686 return undefined;
6687 }); // getLargeAValue callback end
6688
6689 });
6690 }
6691 /**
6692 * This is used for a certain user to confirm the registration by using a confirmation code
6693 * @param {string} confirmationCode Code entered by user.
6694 * @param {bool} forceAliasCreation Allow migrating from an existing email / phone number.
6695 * @param {nodeCallback<string>} callback Called on success or error.
6696 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6697 * @returns {void}
6698 */
6699 ;
6700
6701 _proto.confirmRegistration = function confirmRegistration(confirmationCode, forceAliasCreation, callback, clientMetadata) {
6702 var jsonReq = {
6703 ClientId: this.pool.getClientId(),
6704 ConfirmationCode: confirmationCode,
6705 Username: this.username,
6706 ForceAliasCreation: forceAliasCreation,
6707 ClientMetadata: clientMetadata
6708 };
6709
6710 if (this.getUserContextData()) {
6711 jsonReq.UserContextData = this.getUserContextData();
6712 }
6713
6714 this.client.request('ConfirmSignUp', jsonReq, function (err) {
6715 if (err) {
6716 return callback(err, null);
6717 }
6718
6719 return callback(null, 'SUCCESS');
6720 });
6721 }
6722 /**
6723 * This is used by the user once he has the responses to a custom challenge
6724 * @param {string} answerChallenge The custom challenge answer.
6725 * @param {object} callback Result callback map.
6726 * @param {onFailure} callback.onFailure Called on any error.
6727 * @param {customChallenge} callback.customChallenge
6728 * Custom challenge response required to continue.
6729 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6730 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6731 * @returns {void}
6732 */
6733 ;
6734
6735 _proto.sendCustomChallengeAnswer = function sendCustomChallengeAnswer(answerChallenge, callback, clientMetadata) {
6736 var _this7 = this;
6737
6738 var challengeResponses = {};
6739 challengeResponses.USERNAME = this.username;
6740 challengeResponses.ANSWER = answerChallenge;
6741 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.pool.getUserPoolId().split('_')[1]);
6742 this.getCachedDeviceKeyAndPassword();
6743
6744 if (this.deviceKey != null) {
6745 challengeResponses.DEVICE_KEY = this.deviceKey;
6746 }
6747
6748 var jsonReq = {
6749 ChallengeName: 'CUSTOM_CHALLENGE',
6750 ChallengeResponses: challengeResponses,
6751 ClientId: this.pool.getClientId(),
6752 Session: this.Session,
6753 ClientMetadata: clientMetadata
6754 };
6755
6756 if (this.getUserContextData()) {
6757 jsonReq.UserContextData = this.getUserContextData();
6758 }
6759
6760 this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
6761 if (err) {
6762 return callback.onFailure(err);
6763 }
6764
6765 return _this7.authenticateUserInternal(data, authenticationHelper, callback);
6766 });
6767 }
6768 /**
6769 * This is used by the user once he has an MFA code
6770 * @param {string} confirmationCode The MFA code entered by the user.
6771 * @param {object} callback Result callback map.
6772 * @param {string} mfaType The mfa we are replying to.
6773 * @param {onFailure} callback.onFailure Called on any error.
6774 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6775 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6776 * @returns {void}
6777 */
6778 ;
6779
6780 _proto.sendMFACode = function sendMFACode(confirmationCode, callback, mfaType, clientMetadata) {
6781 var _this8 = this;
6782
6783 var challengeResponses = {};
6784 challengeResponses.USERNAME = this.username;
6785 challengeResponses.SMS_MFA_CODE = confirmationCode;
6786 var mfaTypeSelection = mfaType || 'SMS_MFA';
6787
6788 if (mfaTypeSelection === 'SOFTWARE_TOKEN_MFA') {
6789 challengeResponses.SOFTWARE_TOKEN_MFA_CODE = confirmationCode;
6790 }
6791
6792 if (this.deviceKey != null) {
6793 challengeResponses.DEVICE_KEY = this.deviceKey;
6794 }
6795
6796 var jsonReq = {
6797 ChallengeName: mfaTypeSelection,
6798 ChallengeResponses: challengeResponses,
6799 ClientId: this.pool.getClientId(),
6800 Session: this.Session,
6801 ClientMetadata: clientMetadata
6802 };
6803
6804 if (this.getUserContextData()) {
6805 jsonReq.UserContextData = this.getUserContextData();
6806 }
6807
6808 this.client.request('RespondToAuthChallenge', jsonReq, function (err, dataAuthenticate) {
6809 if (err) {
6810 return callback.onFailure(err);
6811 }
6812
6813 var challengeName = dataAuthenticate.ChallengeName;
6814
6815 if (challengeName === 'DEVICE_SRP_AUTH') {
6816 _this8.getDeviceResponse(callback);
6817
6818 return undefined;
6819 }
6820
6821 _this8.signInUserSession = _this8.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
6822
6823 _this8.cacheTokens();
6824
6825 if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) {
6826 return callback.onSuccess(_this8.signInUserSession);
6827 }
6828
6829 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](_this8.pool.getUserPoolId().split('_')[1]);
6830 authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) {
6831 if (errGenHash) {
6832 return callback.onFailure(errGenHash);
6833 }
6834
6835 var deviceSecretVerifierConfig = {
6836 Salt: buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'),
6837 PasswordVerifier: buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64')
6838 };
6839 _this8.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier;
6840 _this8.deviceGroupKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey;
6841 _this8.randomPassword = authenticationHelper.getRandomPassword();
6842
6843 _this8.client.request('ConfirmDevice', {
6844 DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey,
6845 AccessToken: _this8.signInUserSession.getAccessToken().getJwtToken(),
6846 DeviceSecretVerifierConfig: deviceSecretVerifierConfig,
6847 DeviceName: userAgent
6848 }, function (errConfirm, dataConfirm) {
6849 if (errConfirm) {
6850 return callback.onFailure(errConfirm);
6851 }
6852
6853 _this8.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey;
6854
6855 _this8.cacheDeviceKeyAndPassword();
6856
6857 if (dataConfirm.UserConfirmationNecessary === true) {
6858 return callback.onSuccess(_this8.signInUserSession, dataConfirm.UserConfirmationNecessary);
6859 }
6860
6861 return callback.onSuccess(_this8.signInUserSession);
6862 });
6863
6864 return undefined;
6865 });
6866 return undefined;
6867 });
6868 }
6869 /**
6870 * This is used by an authenticated user to change the current password
6871 * @param {string} oldUserPassword The current password.
6872 * @param {string} newUserPassword The requested new password.
6873 * @param {nodeCallback<string>} callback Called on success or error.
6874 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6875 * @returns {void}
6876 */
6877 ;
6878
6879 _proto.changePassword = function changePassword(oldUserPassword, newUserPassword, callback, clientMetadata) {
6880 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
6881 return callback(new Error('User is not authenticated'), null);
6882 }
6883
6884 this.client.request('ChangePassword', {
6885 PreviousPassword: oldUserPassword,
6886 ProposedPassword: newUserPassword,
6887 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6888 ClientMetadata: clientMetadata
6889 }, function (err) {
6890 if (err) {
6891 return callback(err, null);
6892 }
6893
6894 return callback(null, 'SUCCESS');
6895 });
6896 return undefined;
6897 }
6898 /**
6899 * This is used by an authenticated user to enable MFA for itself
6900 * @deprecated
6901 * @param {nodeCallback<string>} callback Called on success or error.
6902 * @returns {void}
6903 */
6904 ;
6905
6906 _proto.enableMFA = function enableMFA(callback) {
6907 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6908 return callback(new Error('User is not authenticated'), null);
6909 }
6910
6911 var mfaOptions = [];
6912 var mfaEnabled = {
6913 DeliveryMedium: 'SMS',
6914 AttributeName: 'phone_number'
6915 };
6916 mfaOptions.push(mfaEnabled);
6917 this.client.request('SetUserSettings', {
6918 MFAOptions: mfaOptions,
6919 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6920 }, function (err) {
6921 if (err) {
6922 return callback(err, null);
6923 }
6924
6925 return callback(null, 'SUCCESS');
6926 });
6927 return undefined;
6928 }
6929 /**
6930 * This is used by an authenticated user to enable MFA for itself
6931 * @param {IMfaSettings} smsMfaSettings the sms mfa settings
6932 * @param {IMFASettings} softwareTokenMfaSettings the software token mfa settings
6933 * @param {nodeCallback<string>} callback Called on success or error.
6934 * @returns {void}
6935 */
6936 ;
6937
6938 _proto.setUserMfaPreference = function setUserMfaPreference(smsMfaSettings, softwareTokenMfaSettings, callback) {
6939 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6940 return callback(new Error('User is not authenticated'), null);
6941 }
6942
6943 this.client.request('SetUserMFAPreference', {
6944 SMSMfaSettings: smsMfaSettings,
6945 SoftwareTokenMfaSettings: softwareTokenMfaSettings,
6946 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6947 }, function (err) {
6948 if (err) {
6949 return callback(err, null);
6950 }
6951
6952 return callback(null, 'SUCCESS');
6953 });
6954 return undefined;
6955 }
6956 /**
6957 * This is used by an authenticated user to disable MFA for itself
6958 * @deprecated
6959 * @param {nodeCallback<string>} callback Called on success or error.
6960 * @returns {void}
6961 */
6962 ;
6963
6964 _proto.disableMFA = function disableMFA(callback) {
6965 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6966 return callback(new Error('User is not authenticated'), null);
6967 }
6968
6969 var mfaOptions = [];
6970 this.client.request('SetUserSettings', {
6971 MFAOptions: mfaOptions,
6972 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6973 }, function (err) {
6974 if (err) {
6975 return callback(err, null);
6976 }
6977
6978 return callback(null, 'SUCCESS');
6979 });
6980 return undefined;
6981 }
6982 /**
6983 * This is used by an authenticated user to delete itself
6984 * @param {nodeCallback<string>} callback Called on success or error.
6985 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6986 * @returns {void}
6987 */
6988 ;
6989
6990 _proto.deleteUser = function deleteUser(callback, clientMetadata) {
6991 var _this9 = this;
6992
6993 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6994 return callback(new Error('User is not authenticated'), null);
6995 }
6996
6997 this.client.request('DeleteUser', {
6998 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6999 ClientMetadata: clientMetadata
7000 }, function (err) {
7001 if (err) {
7002 return callback(err, null);
7003 }
7004
7005 _this9.clearCachedUser();
7006
7007 return callback(null, 'SUCCESS');
7008 });
7009 return undefined;
7010 }
7011 /**
7012 * @typedef {CognitoUserAttribute | { Name:string, Value:string }} AttributeArg
7013 */
7014
7015 /**
7016 * This is used by an authenticated user to change a list of attributes
7017 * @param {AttributeArg[]} attributes A list of the new user attributes.
7018 * @param {nodeCallback<string>} callback Called on success or error.
7019 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7020 * @returns {void}
7021 */
7022 ;
7023
7024 _proto.updateAttributes = function updateAttributes(attributes, callback, clientMetadata) {
7025 var _this10 = this;
7026
7027 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7028 return callback(new Error('User is not authenticated'), null);
7029 }
7030
7031 this.client.request('UpdateUserAttributes', {
7032 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7033 UserAttributes: attributes,
7034 ClientMetadata: clientMetadata
7035 }, function (err) {
7036 if (err) {
7037 return callback(err, null);
7038 } // update cached user
7039
7040
7041 return _this10.getUserData(function () {
7042 return callback(null, 'SUCCESS');
7043 }, {
7044 bypassCache: true
7045 });
7046 });
7047 return undefined;
7048 }
7049 /**
7050 * This is used by an authenticated user to get a list of attributes
7051 * @param {nodeCallback<CognitoUserAttribute[]>} callback Called on success or error.
7052 * @returns {void}
7053 */
7054 ;
7055
7056 _proto.getUserAttributes = function getUserAttributes(callback) {
7057 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7058 return callback(new Error('User is not authenticated'), null);
7059 }
7060
7061 this.client.request('GetUser', {
7062 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7063 }, function (err, userData) {
7064 if (err) {
7065 return callback(err, null);
7066 }
7067
7068 var attributeList = [];
7069
7070 for (var i = 0; i < userData.UserAttributes.length; i++) {
7071 var attribute = {
7072 Name: userData.UserAttributes[i].Name,
7073 Value: userData.UserAttributes[i].Value
7074 };
7075 var userAttribute = new _CognitoUserAttribute__WEBPACK_IMPORTED_MODULE_12__["default"](attribute);
7076 attributeList.push(userAttribute);
7077 }
7078
7079 return callback(null, attributeList);
7080 });
7081 return undefined;
7082 }
7083 /**
7084 * This was previously used by an authenticated user to get MFAOptions,
7085 * but no longer returns a meaningful response. Refer to the documentation for
7086 * how to setup and use MFA: https://docs.amplify.aws/lib/auth/mfa/q/platform/js
7087 * @deprecated
7088 * @param {nodeCallback<MFAOptions>} callback Called on success or error.
7089 * @returns {void}
7090 */
7091 ;
7092
7093 _proto.getMFAOptions = function getMFAOptions(callback) {
7094 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7095 return callback(new Error('User is not authenticated'), null);
7096 }
7097
7098 this.client.request('GetUser', {
7099 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7100 }, function (err, userData) {
7101 if (err) {
7102 return callback(err, null);
7103 }
7104
7105 return callback(null, userData.MFAOptions);
7106 });
7107 return undefined;
7108 }
7109 /**
7110 * PRIVATE ONLY: This is an internal only method and should not
7111 * be directly called by the consumers.
7112 */
7113 ;
7114
7115 _proto.createGetUserRequest = function createGetUserRequest() {
7116 return this.client.promisifyRequest('GetUser', {
7117 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7118 });
7119 }
7120 /**
7121 * PRIVATE ONLY: This is an internal only method and should not
7122 * be directly called by the consumers.
7123 */
7124 ;
7125
7126 _proto.refreshSessionIfPossible = function refreshSessionIfPossible(options) {
7127 var _this11 = this;
7128
7129 if (options === void 0) {
7130 options = {};
7131 } // best effort, if not possible
7132
7133
7134 return new Promise(function (resolve) {
7135 var refresh = _this11.signInUserSession.getRefreshToken();
7136
7137 if (refresh && refresh.getToken()) {
7138 _this11.refreshSession(refresh, resolve, options.clientMetadata);
7139 } else {
7140 resolve();
7141 }
7142 });
7143 }
7144 /**
7145 * @typedef {Object} GetUserDataOptions
7146 * @property {boolean} bypassCache - force getting data from Cognito service
7147 * @property {Record<string, string>} clientMetadata - clientMetadata for getSession
7148 */
7149
7150 /**
7151 * This is used by an authenticated users to get the userData
7152 * @param {nodeCallback<UserData>} callback Called on success or error.
7153 * @param {GetUserDataOptions} params
7154 * @returns {void}
7155 */
7156 ;
7157
7158 _proto.getUserData = function getUserData(callback, params) {
7159 var _this12 = this;
7160
7161 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7162 this.clearCachedUserData();
7163 return callback(new Error('User is not authenticated'), null);
7164 }
7165
7166 var userData = this.getUserDataFromCache();
7167
7168 if (!userData) {
7169 this.fetchUserData().then(function (data) {
7170 callback(null, data);
7171 })["catch"](callback);
7172 return;
7173 }
7174
7175 if (this.isFetchUserDataAndTokenRequired(params)) {
7176 this.fetchUserData().then(function (data) {
7177 return _this12.refreshSessionIfPossible(params).then(function () {
7178 return data;
7179 });
7180 }).then(function (data) {
7181 return callback(null, data);
7182 })["catch"](callback);
7183 return;
7184 }
7185
7186 try {
7187 callback(null, JSON.parse(userData));
7188 return;
7189 } catch (err) {
7190 this.clearCachedUserData();
7191 callback(err, null);
7192 return;
7193 }
7194 }
7195 /**
7196 *
7197 * PRIVATE ONLY: This is an internal only method and should not
7198 * be directly called by the consumers.
7199 */
7200 ;
7201
7202 _proto.getUserDataFromCache = function getUserDataFromCache() {
7203 var userData = this.storage.getItem(this.userDataKey);
7204 return userData;
7205 }
7206 /**
7207 *
7208 * PRIVATE ONLY: This is an internal only method and should not
7209 * be directly called by the consumers.
7210 */
7211 ;
7212
7213 _proto.isFetchUserDataAndTokenRequired = function isFetchUserDataAndTokenRequired(params) {
7214 var _ref = params || {},
7215 _ref$bypassCache = _ref.bypassCache,
7216 bypassCache = _ref$bypassCache === void 0 ? false : _ref$bypassCache;
7217
7218 return bypassCache;
7219 }
7220 /**
7221 *
7222 * PRIVATE ONLY: This is an internal only method and should not
7223 * be directly called by the consumers.
7224 */
7225 ;
7226
7227 _proto.fetchUserData = function fetchUserData() {
7228 var _this13 = this;
7229
7230 return this.createGetUserRequest().then(function (data) {
7231 _this13.cacheUserData(data);
7232
7233 return data;
7234 });
7235 }
7236 /**
7237 * This is used by an authenticated user to delete a list of attributes
7238 * @param {string[]} attributeList Names of the attributes to delete.
7239 * @param {nodeCallback<string>} callback Called on success or error.
7240 * @returns {void}
7241 */
7242 ;
7243
7244 _proto.deleteAttributes = function deleteAttributes(attributeList, callback) {
7245 var _this14 = this;
7246
7247 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7248 return callback(new Error('User is not authenticated'), null);
7249 }
7250
7251 this.client.request('DeleteUserAttributes', {
7252 UserAttributeNames: attributeList,
7253 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7254 }, function (err) {
7255 if (err) {
7256 return callback(err, null);
7257 } // update cached user
7258
7259
7260 return _this14.getUserData(function () {
7261 return callback(null, 'SUCCESS');
7262 }, {
7263 bypassCache: true
7264 });
7265 });
7266 return undefined;
7267 }
7268 /**
7269 * This is used by a user to resend a confirmation code
7270 * @param {nodeCallback<string>} callback Called on success or error.
7271 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7272 * @returns {void}
7273 */
7274 ;
7275
7276 _proto.resendConfirmationCode = function resendConfirmationCode(callback, clientMetadata) {
7277 var jsonReq = {
7278 ClientId: this.pool.getClientId(),
7279 Username: this.username,
7280 ClientMetadata: clientMetadata
7281 };
7282 this.client.request('ResendConfirmationCode', jsonReq, function (err, result) {
7283 if (err) {
7284 return callback(err, null);
7285 }
7286
7287 return callback(null, result);
7288 });
7289 }
7290 /**
7291 * @typedef {Object} GetSessionOptions
7292 * @property {Record<string, string>} clientMetadata - clientMetadata for getSession
7293 */
7294
7295 /**
7296 * This is used to get a session, either from the session object
7297 * or from the local storage, or by using a refresh token
7298 *
7299 * @param {nodeCallback<CognitoUserSession>} callback Called on success or error.
7300 * @param {GetSessionOptions} options
7301 * @returns {void}
7302 */
7303 ;
7304
7305 _proto.getSession = function getSession(callback, options) {
7306 if (options === void 0) {
7307 options = {};
7308 }
7309
7310 if (this.username == null) {
7311 return callback(new Error('Username is null. Cannot retrieve a new session'), null);
7312 }
7313
7314 if (this.signInUserSession != null && this.signInUserSession.isValid()) {
7315 return callback(null, this.signInUserSession);
7316 }
7317
7318 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
7319 var idTokenKey = keyPrefix + ".idToken";
7320 var accessTokenKey = keyPrefix + ".accessToken";
7321 var refreshTokenKey = keyPrefix + ".refreshToken";
7322 var clockDriftKey = keyPrefix + ".clockDrift";
7323
7324 if (this.storage.getItem(idTokenKey)) {
7325 var idToken = new _CognitoIdToken__WEBPACK_IMPORTED_MODULE_8__["default"]({
7326 IdToken: this.storage.getItem(idTokenKey)
7327 });
7328 var accessToken = new _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_7__["default"]({
7329 AccessToken: this.storage.getItem(accessTokenKey)
7330 });
7331 var refreshToken = new _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_9__["default"]({
7332 RefreshToken: this.storage.getItem(refreshTokenKey)
7333 });
7334 var clockDrift = parseInt(this.storage.getItem(clockDriftKey), 0) || 0;
7335 var sessionData = {
7336 IdToken: idToken,
7337 AccessToken: accessToken,
7338 RefreshToken: refreshToken,
7339 ClockDrift: clockDrift
7340 };
7341 var cachedSession = new _CognitoUserSession__WEBPACK_IMPORTED_MODULE_10__["default"](sessionData);
7342
7343 if (cachedSession.isValid()) {
7344 this.signInUserSession = cachedSession;
7345 return callback(null, this.signInUserSession);
7346 }
7347
7348 if (!refreshToken.getToken()) {
7349 return callback(new Error('Cannot retrieve a new session. Please authenticate.'), null);
7350 }
7351
7352 this.refreshSession(refreshToken, callback, options.clientMetadata);
7353 } else {
7354 callback(new Error('Local storage is missing an ID Token, Please authenticate'), null);
7355 }
7356
7357 return undefined;
7358 }
7359 /**
7360 * This uses the refreshToken to retrieve a new session
7361 * @param {CognitoRefreshToken} refreshToken A previous session's refresh token.
7362 * @param {nodeCallback<CognitoUserSession>} callback Called on success or error.
7363 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7364 * @returns {void}
7365 */
7366 ;
7367
7368 _proto.refreshSession = function refreshSession(refreshToken, callback, clientMetadata) {
7369 var _this15 = this;
7370
7371 var wrappedCallback = this.pool.wrapRefreshSessionCallback ? this.pool.wrapRefreshSessionCallback(callback) : callback;
7372 var authParameters = {};
7373 authParameters.REFRESH_TOKEN = refreshToken.getToken();
7374 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
7375 var lastUserKey = keyPrefix + ".LastAuthUser";
7376
7377 if (this.storage.getItem(lastUserKey)) {
7378 this.username = this.storage.getItem(lastUserKey);
7379 var deviceKeyKey = keyPrefix + "." + this.username + ".deviceKey";
7380 this.deviceKey = this.storage.getItem(deviceKeyKey);
7381 authParameters.DEVICE_KEY = this.deviceKey;
7382 }
7383
7384 var jsonReq = {
7385 ClientId: this.pool.getClientId(),
7386 AuthFlow: 'REFRESH_TOKEN_AUTH',
7387 AuthParameters: authParameters,
7388 ClientMetadata: clientMetadata
7389 };
7390
7391 if (this.getUserContextData()) {
7392 jsonReq.UserContextData = this.getUserContextData();
7393 }
7394
7395 this.client.request('InitiateAuth', jsonReq, function (err, authResult) {
7396 if (err) {
7397 if (err.code === 'NotAuthorizedException') {
7398 _this15.clearCachedUser();
7399 }
7400
7401 return wrappedCallback(err, null);
7402 }
7403
7404 if (authResult) {
7405 var authenticationResult = authResult.AuthenticationResult;
7406
7407 if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) {
7408 authenticationResult.RefreshToken = refreshToken.getToken();
7409 }
7410
7411 _this15.signInUserSession = _this15.getCognitoUserSession(authenticationResult);
7412
7413 _this15.cacheTokens();
7414
7415 return wrappedCallback(null, _this15.signInUserSession);
7416 }
7417
7418 return undefined;
7419 });
7420 }
7421 /**
7422 * This is used to save the session tokens to local storage
7423 * @returns {void}
7424 */
7425 ;
7426
7427 _proto.cacheTokens = function cacheTokens() {
7428 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
7429 var idTokenKey = keyPrefix + "." + this.username + ".idToken";
7430 var accessTokenKey = keyPrefix + "." + this.username + ".accessToken";
7431 var refreshTokenKey = keyPrefix + "." + this.username + ".refreshToken";
7432 var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift";
7433 var lastUserKey = keyPrefix + ".LastAuthUser";
7434 this.storage.setItem(idTokenKey, this.signInUserSession.getIdToken().getJwtToken());
7435 this.storage.setItem(accessTokenKey, this.signInUserSession.getAccessToken().getJwtToken());
7436 this.storage.setItem(refreshTokenKey, this.signInUserSession.getRefreshToken().getToken());
7437 this.storage.setItem(clockDriftKey, "" + this.signInUserSession.getClockDrift());
7438 this.storage.setItem(lastUserKey, this.username);
7439 }
7440 /**
7441 * This is to cache user data
7442 */
7443 ;
7444
7445 _proto.cacheUserData = function cacheUserData(userData) {
7446 this.storage.setItem(this.userDataKey, JSON.stringify(userData));
7447 }
7448 /**
7449 * This is to remove cached user data
7450 */
7451 ;
7452
7453 _proto.clearCachedUserData = function clearCachedUserData() {
7454 this.storage.removeItem(this.userDataKey);
7455 };
7456
7457 _proto.clearCachedUser = function clearCachedUser() {
7458 this.clearCachedTokens();
7459 this.clearCachedUserData();
7460 }
7461 /**
7462 * This is used to cache the device key and device group and device password
7463 * @returns {void}
7464 */
7465 ;
7466
7467 _proto.cacheDeviceKeyAndPassword = function cacheDeviceKeyAndPassword() {
7468 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
7469 var deviceKeyKey = keyPrefix + ".deviceKey";
7470 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
7471 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
7472 this.storage.setItem(deviceKeyKey, this.deviceKey);
7473 this.storage.setItem(randomPasswordKey, this.randomPassword);
7474 this.storage.setItem(deviceGroupKeyKey, this.deviceGroupKey);
7475 }
7476 /**
7477 * This is used to get current device key and device group and device password
7478 * @returns {void}
7479 */
7480 ;
7481
7482 _proto.getCachedDeviceKeyAndPassword = function getCachedDeviceKeyAndPassword() {
7483 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
7484 var deviceKeyKey = keyPrefix + ".deviceKey";
7485 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
7486 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
7487
7488 if (this.storage.getItem(deviceKeyKey)) {
7489 this.deviceKey = this.storage.getItem(deviceKeyKey);
7490 this.randomPassword = this.storage.getItem(randomPasswordKey);
7491 this.deviceGroupKey = this.storage.getItem(deviceGroupKeyKey);
7492 }
7493 }
7494 /**
7495 * This is used to clear the device key info from local storage
7496 * @returns {void}
7497 */
7498 ;
7499
7500 _proto.clearCachedDeviceKeyAndPassword = function clearCachedDeviceKeyAndPassword() {
7501 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
7502 var deviceKeyKey = keyPrefix + ".deviceKey";
7503 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
7504 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
7505 this.storage.removeItem(deviceKeyKey);
7506 this.storage.removeItem(randomPasswordKey);
7507 this.storage.removeItem(deviceGroupKeyKey);
7508 }
7509 /**
7510 * This is used to clear the session tokens from local storage
7511 * @returns {void}
7512 */
7513 ;
7514
7515 _proto.clearCachedTokens = function clearCachedTokens() {
7516 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
7517 var idTokenKey = keyPrefix + "." + this.username + ".idToken";
7518 var accessTokenKey = keyPrefix + "." + this.username + ".accessToken";
7519 var refreshTokenKey = keyPrefix + "." + this.username + ".refreshToken";
7520 var lastUserKey = keyPrefix + ".LastAuthUser";
7521 var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift";
7522 this.storage.removeItem(idTokenKey);
7523 this.storage.removeItem(accessTokenKey);
7524 this.storage.removeItem(refreshTokenKey);
7525 this.storage.removeItem(lastUserKey);
7526 this.storage.removeItem(clockDriftKey);
7527 }
7528 /**
7529 * This is used to build a user session from tokens retrieved in the authentication result
7530 * @param {object} authResult Successful auth response from server.
7531 * @returns {CognitoUserSession} The new user session.
7532 * @private
7533 */
7534 ;
7535
7536 _proto.getCognitoUserSession = function getCognitoUserSession(authResult) {
7537 var idToken = new _CognitoIdToken__WEBPACK_IMPORTED_MODULE_8__["default"](authResult);
7538 var accessToken = new _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_7__["default"](authResult);
7539 var refreshToken = new _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_9__["default"](authResult);
7540 var sessionData = {
7541 IdToken: idToken,
7542 AccessToken: accessToken,
7543 RefreshToken: refreshToken
7544 };
7545 return new _CognitoUserSession__WEBPACK_IMPORTED_MODULE_10__["default"](sessionData);
7546 }
7547 /**
7548 * This is used to initiate a forgot password request
7549 * @param {object} callback Result callback map.
7550 * @param {onFailure} callback.onFailure Called on any error.
7551 * @param {inputVerificationCode?} callback.inputVerificationCode
7552 * Optional callback raised instead of onSuccess with response data.
7553 * @param {onSuccess} callback.onSuccess Called on success.
7554 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7555 * @returns {void}
7556 */
7557 ;
7558
7559 _proto.forgotPassword = function forgotPassword(callback, clientMetadata) {
7560 var jsonReq = {
7561 ClientId: this.pool.getClientId(),
7562 Username: this.username,
7563 ClientMetadata: clientMetadata
7564 };
7565
7566 if (this.getUserContextData()) {
7567 jsonReq.UserContextData = this.getUserContextData();
7568 }
7569
7570 this.client.request('ForgotPassword', jsonReq, function (err, data) {
7571 if (err) {
7572 return callback.onFailure(err);
7573 }
7574
7575 if (typeof callback.inputVerificationCode === 'function') {
7576 return callback.inputVerificationCode(data);
7577 }
7578
7579 return callback.onSuccess(data);
7580 });
7581 }
7582 /**
7583 * This is used to confirm a new password using a confirmationCode
7584 * @param {string} confirmationCode Code entered by user.
7585 * @param {string} newPassword Confirm new password.
7586 * @param {object} callback Result callback map.
7587 * @param {onFailure} callback.onFailure Called on any error.
7588 * @param {onSuccess<void>} callback.onSuccess Called on success.
7589 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7590 * @returns {void}
7591 */
7592 ;
7593
7594 _proto.confirmPassword = function confirmPassword(confirmationCode, newPassword, callback, clientMetadata) {
7595 var jsonReq = {
7596 ClientId: this.pool.getClientId(),
7597 Username: this.username,
7598 ConfirmationCode: confirmationCode,
7599 Password: newPassword,
7600 ClientMetadata: clientMetadata
7601 };
7602
7603 if (this.getUserContextData()) {
7604 jsonReq.UserContextData = this.getUserContextData();
7605 }
7606
7607 this.client.request('ConfirmForgotPassword', jsonReq, function (err) {
7608 if (err) {
7609 return callback.onFailure(err);
7610 }
7611
7612 return callback.onSuccess('SUCCESS');
7613 });
7614 }
7615 /**
7616 * This is used to initiate an attribute confirmation request
7617 * @param {string} attributeName User attribute that needs confirmation.
7618 * @param {object} callback Result callback map.
7619 * @param {onFailure} callback.onFailure Called on any error.
7620 * @param {inputVerificationCode} callback.inputVerificationCode Called on success.
7621 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7622 * @returns {void}
7623 */
7624 ;
7625
7626 _proto.getAttributeVerificationCode = function getAttributeVerificationCode(attributeName, callback, clientMetadata) {
7627 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7628 return callback.onFailure(new Error('User is not authenticated'));
7629 }
7630
7631 this.client.request('GetUserAttributeVerificationCode', {
7632 AttributeName: attributeName,
7633 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7634 ClientMetadata: clientMetadata
7635 }, function (err, data) {
7636 if (err) {
7637 return callback.onFailure(err);
7638 }
7639
7640 if (typeof callback.inputVerificationCode === 'function') {
7641 return callback.inputVerificationCode(data);
7642 }
7643
7644 return callback.onSuccess('SUCCESS');
7645 });
7646 return undefined;
7647 }
7648 /**
7649 * This is used to confirm an attribute using a confirmation code
7650 * @param {string} attributeName Attribute being confirmed.
7651 * @param {string} confirmationCode Code entered by user.
7652 * @param {object} callback Result callback map.
7653 * @param {onFailure} callback.onFailure Called on any error.
7654 * @param {onSuccess<string>} callback.onSuccess Called on success.
7655 * @returns {void}
7656 */
7657 ;
7658
7659 _proto.verifyAttribute = function verifyAttribute(attributeName, confirmationCode, callback) {
7660 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7661 return callback.onFailure(new Error('User is not authenticated'));
7662 }
7663
7664 this.client.request('VerifyUserAttribute', {
7665 AttributeName: attributeName,
7666 Code: confirmationCode,
7667 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7668 }, function (err) {
7669 if (err) {
7670 return callback.onFailure(err);
7671 }
7672
7673 return callback.onSuccess('SUCCESS');
7674 });
7675 return undefined;
7676 }
7677 /**
7678 * This is used to get the device information using the current device key
7679 * @param {object} callback Result callback map.
7680 * @param {onFailure} callback.onFailure Called on any error.
7681 * @param {onSuccess<*>} callback.onSuccess Called on success with device data.
7682 * @returns {void}
7683 */
7684 ;
7685
7686 _proto.getDevice = function getDevice(callback) {
7687 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7688 return callback.onFailure(new Error('User is not authenticated'));
7689 }
7690
7691 this.client.request('GetDevice', {
7692 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7693 DeviceKey: this.deviceKey
7694 }, function (err, data) {
7695 if (err) {
7696 return callback.onFailure(err);
7697 }
7698
7699 return callback.onSuccess(data);
7700 });
7701 return undefined;
7702 }
7703 /**
7704 * This is used to forget a specific device
7705 * @param {string} deviceKey Device key.
7706 * @param {object} callback Result callback map.
7707 * @param {onFailure} callback.onFailure Called on any error.
7708 * @param {onSuccess<string>} callback.onSuccess Called on success.
7709 * @returns {void}
7710 */
7711 ;
7712
7713 _proto.forgetSpecificDevice = function forgetSpecificDevice(deviceKey, callback) {
7714 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7715 return callback.onFailure(new Error('User is not authenticated'));
7716 }
7717
7718 this.client.request('ForgetDevice', {
7719 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7720 DeviceKey: deviceKey
7721 }, function (err) {
7722 if (err) {
7723 return callback.onFailure(err);
7724 }
7725
7726 return callback.onSuccess('SUCCESS');
7727 });
7728 return undefined;
7729 }
7730 /**
7731 * This is used to forget the current device
7732 * @param {object} callback Result callback map.
7733 * @param {onFailure} callback.onFailure Called on any error.
7734 * @param {onSuccess<string>} callback.onSuccess Called on success.
7735 * @returns {void}
7736 */
7737 ;
7738
7739 _proto.forgetDevice = function forgetDevice(callback) {
7740 var _this16 = this;
7741
7742 this.forgetSpecificDevice(this.deviceKey, {
7743 onFailure: callback.onFailure,
7744 onSuccess: function onSuccess(result) {
7745 _this16.deviceKey = null;
7746 _this16.deviceGroupKey = null;
7747 _this16.randomPassword = null;
7748
7749 _this16.clearCachedDeviceKeyAndPassword();
7750
7751 return callback.onSuccess(result);
7752 }
7753 });
7754 }
7755 /**
7756 * This is used to set the device status as remembered
7757 * @param {object} callback Result callback map.
7758 * @param {onFailure} callback.onFailure Called on any error.
7759 * @param {onSuccess<string>} callback.onSuccess Called on success.
7760 * @returns {void}
7761 */
7762 ;
7763
7764 _proto.setDeviceStatusRemembered = function setDeviceStatusRemembered(callback) {
7765 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7766 return callback.onFailure(new Error('User is not authenticated'));
7767 }
7768
7769 this.client.request('UpdateDeviceStatus', {
7770 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7771 DeviceKey: this.deviceKey,
7772 DeviceRememberedStatus: 'remembered'
7773 }, function (err) {
7774 if (err) {
7775 return callback.onFailure(err);
7776 }
7777
7778 return callback.onSuccess('SUCCESS');
7779 });
7780 return undefined;
7781 }
7782 /**
7783 * This is used to set the device status as not remembered
7784 * @param {object} callback Result callback map.
7785 * @param {onFailure} callback.onFailure Called on any error.
7786 * @param {onSuccess<string>} callback.onSuccess Called on success.
7787 * @returns {void}
7788 */
7789 ;
7790
7791 _proto.setDeviceStatusNotRemembered = function setDeviceStatusNotRemembered(callback) {
7792 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7793 return callback.onFailure(new Error('User is not authenticated'));
7794 }
7795
7796 this.client.request('UpdateDeviceStatus', {
7797 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7798 DeviceKey: this.deviceKey,
7799 DeviceRememberedStatus: 'not_remembered'
7800 }, function (err) {
7801 if (err) {
7802 return callback.onFailure(err);
7803 }
7804
7805 return callback.onSuccess('SUCCESS');
7806 });
7807 return undefined;
7808 }
7809 /**
7810 * This is used to list all devices for a user
7811 *
7812 * @param {int} limit the number of devices returned in a call
7813 * @param {string | null} paginationToken the pagination token in case any was returned before
7814 * @param {object} callback Result callback map.
7815 * @param {onFailure} callback.onFailure Called on any error.
7816 * @param {onSuccess<*>} callback.onSuccess Called on success with device list.
7817 * @returns {void}
7818 */
7819 ;
7820
7821 _proto.listDevices = function listDevices(limit, paginationToken, callback) {
7822 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7823 return callback.onFailure(new Error('User is not authenticated'));
7824 }
7825
7826 var requestParams = {
7827 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7828 Limit: limit
7829 };
7830
7831 if (paginationToken) {
7832 requestParams.PaginationToken = paginationToken;
7833 }
7834
7835 this.client.request('ListDevices', requestParams, function (err, data) {
7836 if (err) {
7837 return callback.onFailure(err);
7838 }
7839
7840 return callback.onSuccess(data);
7841 });
7842 return undefined;
7843 }
7844 /**
7845 * This is used to globally revoke all tokens issued to a user
7846 * @param {object} callback Result callback map.
7847 * @param {onFailure} callback.onFailure Called on any error.
7848 * @param {onSuccess<string>} callback.onSuccess Called on success.
7849 * @returns {void}
7850 */
7851 ;
7852
7853 _proto.globalSignOut = function globalSignOut(callback) {
7854 var _this17 = this;
7855
7856 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7857 return callback.onFailure(new Error('User is not authenticated'));
7858 }
7859
7860 this.client.request('GlobalSignOut', {
7861 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7862 }, function (err) {
7863 if (err) {
7864 return callback.onFailure(err);
7865 }
7866
7867 _this17.clearCachedUser();
7868
7869 return callback.onSuccess('SUCCESS');
7870 });
7871 return undefined;
7872 }
7873 /**
7874 * This is used for the user to signOut of the application and clear the cached tokens.
7875 * @returns {void}
7876 */
7877 ;
7878
7879 _proto.signOut = function signOut(revokeTokenCallback) {
7880 var _this18 = this; // If tokens won't be revoked, we just clean the client data.
7881
7882
7883 if (!revokeTokenCallback || typeof revokeTokenCallback !== 'function') {
7884 this.cleanClientData();
7885 return;
7886 }
7887
7888 this.getSession(function (error, _session) {
7889 if (error) {
7890 return revokeTokenCallback(error);
7891 }
7892
7893 _this18.revokeTokens(function (err) {
7894 _this18.cleanClientData();
7895
7896 revokeTokenCallback(err);
7897 });
7898 });
7899 };
7900
7901 _proto.revokeTokens = function revokeTokens(revokeTokenCallback) {
7902 if (revokeTokenCallback === void 0) {
7903 revokeTokenCallback = function revokeTokenCallback() {};
7904 }
7905
7906 if (typeof revokeTokenCallback !== 'function') {
7907 throw new Error('Invalid revokeTokenCallback. It should be a function.');
7908 }
7909
7910 var tokensToBeRevoked = [];
7911
7912 if (!this.signInUserSession) {
7913 var error = new Error('User is not authenticated');
7914 return revokeTokenCallback(error);
7915 }
7916
7917 if (!this.signInUserSession.getAccessToken()) {
7918 var _error = new Error('No Access token available');
7919
7920 return revokeTokenCallback(_error);
7921 }
7922
7923 var refreshToken = this.signInUserSession.getRefreshToken().getToken();
7924 var accessToken = this.signInUserSession.getAccessToken();
7925
7926 if (this.isSessionRevocable(accessToken)) {
7927 if (refreshToken) {
7928 return this.revokeToken({
7929 token: refreshToken,
7930 callback: revokeTokenCallback
7931 });
7932 }
7933 }
7934
7935 revokeTokenCallback();
7936 };
7937
7938 _proto.isSessionRevocable = function isSessionRevocable(token) {
7939 if (token && typeof token.decodePayload === 'function') {
7940 try {
7941 var _token$decodePayload = token.decodePayload(),
7942 origin_jti = _token$decodePayload.origin_jti;
7943
7944 return !!origin_jti;
7945 } catch (err) {// Nothing to do, token doesnt have origin_jti claim
7946 }
7947 }
7948
7949 return false;
7950 };
7951
7952 _proto.cleanClientData = function cleanClientData() {
7953 this.signInUserSession = null;
7954 this.clearCachedUser();
7955 };
7956
7957 _proto.revokeToken = function revokeToken(_ref2) {
7958 var token = _ref2.token,
7959 callback = _ref2.callback;
7960 this.client.requestWithRetry('RevokeToken', {
7961 Token: token,
7962 ClientId: this.pool.getClientId()
7963 }, function (err) {
7964 if (err) {
7965 return callback(err);
7966 }
7967
7968 callback();
7969 });
7970 }
7971 /**
7972 * This is used by a user trying to select a given MFA
7973 * @param {string} answerChallenge the mfa the user wants
7974 * @param {nodeCallback<string>} callback Called on success or error.
7975 * @returns {void}
7976 */
7977 ;
7978
7979 _proto.sendMFASelectionAnswer = function sendMFASelectionAnswer(answerChallenge, callback) {
7980 var _this19 = this;
7981
7982 var challengeResponses = {};
7983 challengeResponses.USERNAME = this.username;
7984 challengeResponses.ANSWER = answerChallenge;
7985 var jsonReq = {
7986 ChallengeName: 'SELECT_MFA_TYPE',
7987 ChallengeResponses: challengeResponses,
7988 ClientId: this.pool.getClientId(),
7989 Session: this.Session
7990 };
7991
7992 if (this.getUserContextData()) {
7993 jsonReq.UserContextData = this.getUserContextData();
7994 }
7995
7996 this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
7997 if (err) {
7998 return callback.onFailure(err);
7999 }
8000
8001 _this19.Session = data.Session;
8002
8003 if (answerChallenge === 'SMS_MFA') {
8004 return callback.mfaRequired(data.ChallengeName, data.ChallengeParameters);
8005 }
8006
8007 if (answerChallenge === 'SOFTWARE_TOKEN_MFA') {
8008 return callback.totpRequired(data.ChallengeName, data.ChallengeParameters);
8009 }
8010
8011 return undefined;
8012 });
8013 }
8014 /**
8015 * This returns the user context data for advanced security feature.
8016 * @returns {string} the user context data from CognitoUserPool
8017 */
8018 ;
8019
8020 _proto.getUserContextData = function getUserContextData() {
8021 var pool = this.pool;
8022 return pool.getUserContextData(this.username);
8023 }
8024 /**
8025 * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA
8026 * @param {nodeCallback<string>} callback Called on success or error.
8027 * @returns {void}
8028 */
8029 ;
8030
8031 _proto.associateSoftwareToken = function associateSoftwareToken(callback) {
8032 var _this20 = this;
8033
8034 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
8035 this.client.request('AssociateSoftwareToken', {
8036 Session: this.Session
8037 }, function (err, data) {
8038 if (err) {
8039 return callback.onFailure(err);
8040 }
8041
8042 _this20.Session = data.Session;
8043 return callback.associateSecretCode(data.SecretCode);
8044 });
8045 } else {
8046 this.client.request('AssociateSoftwareToken', {
8047 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
8048 }, function (err, data) {
8049 if (err) {
8050 return callback.onFailure(err);
8051 }
8052
8053 return callback.associateSecretCode(data.SecretCode);
8054 });
8055 }
8056 }
8057 /**
8058 * This is used by an authenticated or a user trying to authenticate to verify a TOTP MFA
8059 * @param {string} totpCode The MFA code entered by the user.
8060 * @param {string} friendlyDeviceName The device name we are assigning to the device.
8061 * @param {nodeCallback<string>} callback Called on success or error.
8062 * @returns {void}
8063 */
8064 ;
8065
8066 _proto.verifySoftwareToken = function verifySoftwareToken(totpCode, friendlyDeviceName, callback) {
8067 var _this21 = this;
8068
8069 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
8070 this.client.request('VerifySoftwareToken', {
8071 Session: this.Session,
8072 UserCode: totpCode,
8073 FriendlyDeviceName: friendlyDeviceName
8074 }, function (err, data) {
8075 if (err) {
8076 return callback.onFailure(err);
8077 }
8078
8079 _this21.Session = data.Session;
8080 var challengeResponses = {};
8081 challengeResponses.USERNAME = _this21.username;
8082 var jsonReq = {
8083 ChallengeName: 'MFA_SETUP',
8084 ClientId: _this21.pool.getClientId(),
8085 ChallengeResponses: challengeResponses,
8086 Session: _this21.Session
8087 };
8088
8089 if (_this21.getUserContextData()) {
8090 jsonReq.UserContextData = _this21.getUserContextData();
8091 }
8092
8093 _this21.client.request('RespondToAuthChallenge', jsonReq, function (errRespond, dataRespond) {
8094 if (errRespond) {
8095 return callback.onFailure(errRespond);
8096 }
8097
8098 _this21.signInUserSession = _this21.getCognitoUserSession(dataRespond.AuthenticationResult);
8099
8100 _this21.cacheTokens();
8101
8102 return callback.onSuccess(_this21.signInUserSession);
8103 });
8104
8105 return undefined;
8106 });
8107 } else {
8108 this.client.request('VerifySoftwareToken', {
8109 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
8110 UserCode: totpCode,
8111 FriendlyDeviceName: friendlyDeviceName
8112 }, function (err, data) {
8113 if (err) {
8114 return callback.onFailure(err);
8115 }
8116
8117 return callback.onSuccess(data);
8118 });
8119 }
8120 };
8121
8122 return CognitoUser;
8123}();
8124
8125
8126
8127/***/ }),
8128
8129/***/ "../amazon-cognito-identity-js/es/CognitoUserAttribute.js":
8130/*!****************************************************************!*\
8131 !*** ../amazon-cognito-identity-js/es/CognitoUserAttribute.js ***!
8132 \****************************************************************/
8133/*! exports provided: default */
8134/***/ (function(module, __webpack_exports__, __webpack_require__) {
8135
8136"use strict";
8137__webpack_require__.r(__webpack_exports__);
8138/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoUserAttribute; });
8139/*!
8140 * Copyright 2016 Amazon.com,
8141 * Inc. or its affiliates. All Rights Reserved.
8142 *
8143 * Licensed under the Amazon Software License (the "License").
8144 * You may not use this file except in compliance with the
8145 * License. A copy of the License is located at
8146 *
8147 * http://aws.amazon.com/asl/
8148 *
8149 * or in the "license" file accompanying this file. This file is
8150 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8151 * CONDITIONS OF ANY KIND, express or implied. See the License
8152 * for the specific language governing permissions and
8153 * limitations under the License.
8154 */
8155
8156/** @class */
8157var CognitoUserAttribute = /*#__PURE__*/function () {
8158 /**
8159 * Constructs a new CognitoUserAttribute object
8160 * @param {string=} Name The record's name
8161 * @param {string=} Value The record's value
8162 */
8163 function CognitoUserAttribute(_temp) {
8164 var _ref = _temp === void 0 ? {} : _temp,
8165 Name = _ref.Name,
8166 Value = _ref.Value;
8167
8168 this.Name = Name || '';
8169 this.Value = Value || '';
8170 }
8171 /**
8172 * @returns {string} the record's value.
8173 */
8174
8175
8176 var _proto = CognitoUserAttribute.prototype;
8177
8178 _proto.getValue = function getValue() {
8179 return this.Value;
8180 }
8181 /**
8182 * Sets the record's value.
8183 * @param {string} value The new value.
8184 * @returns {CognitoUserAttribute} The record for method chaining.
8185 */
8186 ;
8187
8188 _proto.setValue = function setValue(value) {
8189 this.Value = value;
8190 return this;
8191 }
8192 /**
8193 * @returns {string} the record's name.
8194 */
8195 ;
8196
8197 _proto.getName = function getName() {
8198 return this.Name;
8199 }
8200 /**
8201 * Sets the record's name
8202 * @param {string} name The new name.
8203 * @returns {CognitoUserAttribute} The record for method chaining.
8204 */
8205 ;
8206
8207 _proto.setName = function setName(name) {
8208 this.Name = name;
8209 return this;
8210 }
8211 /**
8212 * @returns {string} a string representation of the record.
8213 */
8214 ;
8215
8216 _proto.toString = function toString() {
8217 return JSON.stringify(this);
8218 }
8219 /**
8220 * @returns {object} a flat object representing the record.
8221 */
8222 ;
8223
8224 _proto.toJSON = function toJSON() {
8225 return {
8226 Name: this.Name,
8227 Value: this.Value
8228 };
8229 };
8230
8231 return CognitoUserAttribute;
8232}();
8233
8234
8235
8236/***/ }),
8237
8238/***/ "../amazon-cognito-identity-js/es/CognitoUserPool.js":
8239/*!***********************************************************!*\
8240 !*** ../amazon-cognito-identity-js/es/CognitoUserPool.js ***!
8241 \***********************************************************/
8242/*! exports provided: default */
8243/***/ (function(module, __webpack_exports__, __webpack_require__) {
8244
8245"use strict";
8246__webpack_require__.r(__webpack_exports__);
8247/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoUserPool; });
8248/* harmony import */ var _Client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Client */ "../amazon-cognito-identity-js/es/Client.js");
8249/* harmony import */ var _CognitoUser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CognitoUser */ "../amazon-cognito-identity-js/es/CognitoUser.js");
8250/* harmony import */ var _StorageHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./StorageHelper */ "../amazon-cognito-identity-js/es/StorageHelper.js");
8251/*!
8252 * Copyright 2016 Amazon.com,
8253 * Inc. or its affiliates. All Rights Reserved.
8254 *
8255 * Licensed under the Amazon Software License (the "License").
8256 * You may not use this file except in compliance with the
8257 * License. A copy of the License is located at
8258 *
8259 * http://aws.amazon.com/asl/
8260 *
8261 * or in the "license" file accompanying this file. This file is
8262 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8263 * CONDITIONS OF ANY KIND, express or implied. See the License
8264 * for the specific language governing permissions and
8265 * limitations under the License.
8266 */
8267
8268
8269
8270var USER_POOL_ID_MAX_LENGTH = 55;
8271/** @class */
8272
8273var CognitoUserPool = /*#__PURE__*/function () {
8274 /**
8275 * Constructs a new CognitoUserPool object
8276 * @param {object} data Creation options.
8277 * @param {string} data.UserPoolId Cognito user pool id.
8278 * @param {string} data.ClientId User pool application client id.
8279 * @param {string} data.endpoint Optional custom service endpoint.
8280 * @param {object} data.fetchOptions Optional options for fetch API.
8281 * (only credentials option is supported)
8282 * @param {object} data.Storage Optional storage object.
8283 * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional:
8284 * boolean flag indicating if the data collection is enabled
8285 * to support cognito advanced security features. By default, this
8286 * flag is set to true.
8287 */
8288 function CognitoUserPool(data, wrapRefreshSessionCallback) {
8289 var _ref = data || {},
8290 UserPoolId = _ref.UserPoolId,
8291 ClientId = _ref.ClientId,
8292 endpoint = _ref.endpoint,
8293 fetchOptions = _ref.fetchOptions,
8294 AdvancedSecurityDataCollectionFlag = _ref.AdvancedSecurityDataCollectionFlag;
8295
8296 if (!UserPoolId || !ClientId) {
8297 throw new Error('Both UserPoolId and ClientId are required.');
8298 }
8299
8300 if (UserPoolId.length > USER_POOL_ID_MAX_LENGTH || !/^[\w-]+_[0-9a-zA-Z]+$/.test(UserPoolId)) {
8301 throw new Error('Invalid UserPoolId format.');
8302 }
8303
8304 var region = UserPoolId.split('_')[0];
8305 this.userPoolId = UserPoolId;
8306 this.clientId = ClientId;
8307 this.client = new _Client__WEBPACK_IMPORTED_MODULE_0__["default"](region, endpoint, fetchOptions);
8308 /**
8309 * By default, AdvancedSecurityDataCollectionFlag is set to true,
8310 * if no input value is provided.
8311 */
8312
8313 this.advancedSecurityDataCollectionFlag = AdvancedSecurityDataCollectionFlag !== false;
8314 this.storage = data.Storage || new _StorageHelper__WEBPACK_IMPORTED_MODULE_2__["default"]().getStorage();
8315
8316 if (wrapRefreshSessionCallback) {
8317 this.wrapRefreshSessionCallback = wrapRefreshSessionCallback;
8318 }
8319 }
8320 /**
8321 * @returns {string} the user pool id
8322 */
8323
8324
8325 var _proto = CognitoUserPool.prototype;
8326
8327 _proto.getUserPoolId = function getUserPoolId() {
8328 return this.userPoolId;
8329 }
8330 /**
8331 * @returns {string} the client id
8332 */
8333 ;
8334
8335 _proto.getClientId = function getClientId() {
8336 return this.clientId;
8337 }
8338 /**
8339 * @typedef {object} SignUpResult
8340 * @property {CognitoUser} user New user.
8341 * @property {bool} userConfirmed If the user is already confirmed.
8342 */
8343
8344 /**
8345 * method for signing up a user
8346 * @param {string} username User's username.
8347 * @param {string} password Plain-text initial password entered by user.
8348 * @param {(AttributeArg[])=} userAttributes New user attributes.
8349 * @param {(AttributeArg[])=} validationData Application metadata.
8350 * @param {(AttributeArg[])=} clientMetadata Client metadata.
8351 * @param {nodeCallback<SignUpResult>} callback Called on error or with the new user.
8352 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
8353 * @returns {void}
8354 */
8355 ;
8356
8357 _proto.signUp = function signUp(username, password, userAttributes, validationData, callback, clientMetadata) {
8358 var _this = this;
8359
8360 var jsonReq = {
8361 ClientId: this.clientId,
8362 Username: username,
8363 Password: password,
8364 UserAttributes: userAttributes,
8365 ValidationData: validationData,
8366 ClientMetadata: clientMetadata
8367 };
8368
8369 if (this.getUserContextData(username)) {
8370 jsonReq.UserContextData = this.getUserContextData(username);
8371 }
8372
8373 this.client.request('SignUp', jsonReq, function (err, data) {
8374 if (err) {
8375 return callback(err, null);
8376 }
8377
8378 var cognitoUser = {
8379 Username: username,
8380 Pool: _this,
8381 Storage: _this.storage
8382 };
8383 var returnData = {
8384 user: new _CognitoUser__WEBPACK_IMPORTED_MODULE_1__["default"](cognitoUser),
8385 userConfirmed: data.UserConfirmed,
8386 userSub: data.UserSub,
8387 codeDeliveryDetails: data.CodeDeliveryDetails
8388 };
8389 return callback(null, returnData);
8390 });
8391 }
8392 /**
8393 * method for getting the current user of the application from the local storage
8394 *
8395 * @returns {CognitoUser} the user retrieved from storage
8396 */
8397 ;
8398
8399 _proto.getCurrentUser = function getCurrentUser() {
8400 var lastUserKey = "CognitoIdentityServiceProvider." + this.clientId + ".LastAuthUser";
8401 var lastAuthUser = this.storage.getItem(lastUserKey);
8402
8403 if (lastAuthUser) {
8404 var cognitoUser = {
8405 Username: lastAuthUser,
8406 Pool: this,
8407 Storage: this.storage
8408 };
8409 return new _CognitoUser__WEBPACK_IMPORTED_MODULE_1__["default"](cognitoUser);
8410 }
8411
8412 return null;
8413 }
8414 /**
8415 * This method returns the encoded data string used for cognito advanced security feature.
8416 * This would be generated only when developer has included the JS used for collecting the
8417 * data on their client. Please refer to documentation to know more about using AdvancedSecurity
8418 * features
8419 * @param {string} username the username for the context data
8420 * @returns {string} the user context data
8421 **/
8422 ;
8423
8424 _proto.getUserContextData = function getUserContextData(username) {
8425 if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') {
8426 return undefined;
8427 }
8428 /* eslint-disable */
8429
8430
8431 var amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData;
8432 /* eslint-enable */
8433
8434 if (this.advancedSecurityDataCollectionFlag) {
8435 var advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData(username, this.userPoolId, this.clientId);
8436
8437 if (advancedSecurityData) {
8438 var userContextData = {
8439 EncodedData: advancedSecurityData
8440 };
8441 return userContextData;
8442 }
8443 }
8444
8445 return {};
8446 };
8447
8448 return CognitoUserPool;
8449}();
8450
8451
8452
8453/***/ }),
8454
8455/***/ "../amazon-cognito-identity-js/es/CognitoUserSession.js":
8456/*!**************************************************************!*\
8457 !*** ../amazon-cognito-identity-js/es/CognitoUserSession.js ***!
8458 \**************************************************************/
8459/*! exports provided: default */
8460/***/ (function(module, __webpack_exports__, __webpack_require__) {
8461
8462"use strict";
8463__webpack_require__.r(__webpack_exports__);
8464/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoUserSession; });
8465/*!
8466 * Copyright 2016 Amazon.com,
8467 * Inc. or its affiliates. All Rights Reserved.
8468 *
8469 * Licensed under the Amazon Software License (the "License").
8470 * You may not use this file except in compliance with the
8471 * License. A copy of the License is located at
8472 *
8473 * http://aws.amazon.com/asl/
8474 *
8475 * or in the "license" file accompanying this file. This file is
8476 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8477 * CONDITIONS OF ANY KIND, express or implied. See the License
8478 * for the specific language governing permissions and
8479 * limitations under the License.
8480 */
8481
8482/** @class */
8483var CognitoUserSession = /*#__PURE__*/function () {
8484 /**
8485 * Constructs a new CognitoUserSession object
8486 * @param {CognitoIdToken} IdToken The session's Id token.
8487 * @param {CognitoRefreshToken=} RefreshToken The session's refresh token.
8488 * @param {CognitoAccessToken} AccessToken The session's access token.
8489 * @param {int} ClockDrift The saved computer's clock drift or undefined to force calculation.
8490 */
8491 function CognitoUserSession(_temp) {
8492 var _ref = _temp === void 0 ? {} : _temp,
8493 IdToken = _ref.IdToken,
8494 RefreshToken = _ref.RefreshToken,
8495 AccessToken = _ref.AccessToken,
8496 ClockDrift = _ref.ClockDrift;
8497
8498 if (AccessToken == null || IdToken == null) {
8499 throw new Error('Id token and Access Token must be present.');
8500 }
8501
8502 this.idToken = IdToken;
8503 this.refreshToken = RefreshToken;
8504 this.accessToken = AccessToken;
8505 this.clockDrift = ClockDrift === undefined ? this.calculateClockDrift() : ClockDrift;
8506 }
8507 /**
8508 * @returns {CognitoIdToken} the session's Id token
8509 */
8510
8511
8512 var _proto = CognitoUserSession.prototype;
8513
8514 _proto.getIdToken = function getIdToken() {
8515 return this.idToken;
8516 }
8517 /**
8518 * @returns {CognitoRefreshToken} the session's refresh token
8519 */
8520 ;
8521
8522 _proto.getRefreshToken = function getRefreshToken() {
8523 return this.refreshToken;
8524 }
8525 /**
8526 * @returns {CognitoAccessToken} the session's access token
8527 */
8528 ;
8529
8530 _proto.getAccessToken = function getAccessToken() {
8531 return this.accessToken;
8532 }
8533 /**
8534 * @returns {int} the session's clock drift
8535 */
8536 ;
8537
8538 _proto.getClockDrift = function getClockDrift() {
8539 return this.clockDrift;
8540 }
8541 /**
8542 * @returns {int} the computer's clock drift
8543 */
8544 ;
8545
8546 _proto.calculateClockDrift = function calculateClockDrift() {
8547 var now = Math.floor(new Date() / 1000);
8548 var iat = Math.min(this.accessToken.getIssuedAt(), this.idToken.getIssuedAt());
8549 return now - iat;
8550 }
8551 /**
8552 * Checks to see if the session is still valid based on session expiry information found
8553 * in tokens and the current time (adjusted with clock drift)
8554 * @returns {boolean} if the session is still valid
8555 */
8556 ;
8557
8558 _proto.isValid = function isValid() {
8559 var now = Math.floor(new Date() / 1000);
8560 var adjusted = now - this.clockDrift;
8561 return adjusted < this.accessToken.getExpiration() && adjusted < this.idToken.getExpiration();
8562 };
8563
8564 return CognitoUserSession;
8565}();
8566
8567
8568
8569/***/ }),
8570
8571/***/ "../amazon-cognito-identity-js/es/CookieStorage.js":
8572/*!*********************************************************!*\
8573 !*** ../amazon-cognito-identity-js/es/CookieStorage.js ***!
8574 \*********************************************************/
8575/*! exports provided: default */
8576/***/ (function(module, __webpack_exports__, __webpack_require__) {
8577
8578"use strict";
8579__webpack_require__.r(__webpack_exports__);
8580/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CookieStorage; });
8581/* harmony import */ var js_cookie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! js-cookie */ "../../node_modules/js-cookie/src/js.cookie.js");
8582/* harmony import */ var js_cookie__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(js_cookie__WEBPACK_IMPORTED_MODULE_0__);
8583
8584/** @class */
8585
8586var CookieStorage = /*#__PURE__*/function () {
8587 /**
8588 * Constructs a new CookieStorage object
8589 * @param {object} data Creation options.
8590 * @param {string} data.domain Cookies domain (mandatory).
8591 * @param {string} data.path Cookies path (default: '/')
8592 * @param {integer} data.expires Cookie expiration (in days, default: 365)
8593 * @param {boolean} data.secure Cookie secure flag (default: true)
8594 * @param {string} data.sameSite Cookie request behaviour (default: null)
8595 */
8596 function CookieStorage(data) {
8597 if (data.domain) {
8598 this.domain = data.domain;
8599 } else {
8600 throw new Error('The domain of cookieStorage can not be undefined.');
8601 }
8602
8603 if (data.path) {
8604 this.path = data.path;
8605 } else {
8606 this.path = '/';
8607 }
8608
8609 if (Object.prototype.hasOwnProperty.call(data, 'expires')) {
8610 this.expires = data.expires;
8611 } else {
8612 this.expires = 365;
8613 }
8614
8615 if (Object.prototype.hasOwnProperty.call(data, 'secure')) {
8616 this.secure = data.secure;
8617 } else {
8618 this.secure = true;
8619 }
8620
8621 if (Object.prototype.hasOwnProperty.call(data, 'sameSite')) {
8622 if (!['strict', 'lax', 'none'].includes(data.sameSite)) {
8623 throw new Error('The sameSite value of cookieStorage must be "lax", "strict" or "none".');
8624 }
8625
8626 if (data.sameSite === 'none' && !this.secure) {
8627 throw new Error('sameSite = None requires the Secure attribute in latest browser versions.');
8628 }
8629
8630 this.sameSite = data.sameSite;
8631 } else {
8632 this.sameSite = null;
8633 }
8634 }
8635 /**
8636 * This is used to set a specific item in storage
8637 * @param {string} key - the key for the item
8638 * @param {object} value - the value
8639 * @returns {string} value that was set
8640 */
8641
8642
8643 var _proto = CookieStorage.prototype;
8644
8645 _proto.setItem = function setItem(key, value) {
8646 var options = {
8647 path: this.path,
8648 expires: this.expires,
8649 domain: this.domain,
8650 secure: this.secure
8651 };
8652
8653 if (this.sameSite) {
8654 options.sameSite = this.sameSite;
8655 }
8656
8657 js_cookie__WEBPACK_IMPORTED_MODULE_0__["set"](key, value, options);
8658 return js_cookie__WEBPACK_IMPORTED_MODULE_0__["get"](key);
8659 }
8660 /**
8661 * This is used to get a specific key from storage
8662 * @param {string} key - the key for the item
8663 * This is used to clear the storage
8664 * @returns {string} the data item
8665 */
8666 ;
8667
8668 _proto.getItem = function getItem(key) {
8669 return js_cookie__WEBPACK_IMPORTED_MODULE_0__["get"](key);
8670 }
8671 /**
8672 * This is used to remove an item from storage
8673 * @param {string} key - the key being set
8674 * @returns {string} value - value that was deleted
8675 */
8676 ;
8677
8678 _proto.removeItem = function removeItem(key) {
8679 var options = {
8680 path: this.path,
8681 expires: this.expires,
8682 domain: this.domain,
8683 secure: this.secure
8684 };
8685
8686 if (this.sameSite) {
8687 options.sameSite = this.sameSite;
8688 }
8689
8690 return js_cookie__WEBPACK_IMPORTED_MODULE_0__["remove"](key, options);
8691 }
8692 /**
8693 * This is used to clear the storage of optional
8694 * items that were previously set
8695 * @returns {} an empty object
8696 */
8697 ;
8698
8699 _proto.clear = function clear() {
8700 var cookies = js_cookie__WEBPACK_IMPORTED_MODULE_0__["get"]();
8701 var numKeys = Object.keys(cookies).length;
8702
8703 for (var index = 0; index < numKeys; ++index) {
8704 this.removeItem(Object.keys(cookies)[index]);
8705 }
8706
8707 return {};
8708 };
8709
8710 return CookieStorage;
8711}();
8712
8713
8714
8715/***/ }),
8716
8717/***/ "../amazon-cognito-identity-js/es/DateHelper.js":
8718/*!******************************************************!*\
8719 !*** ../amazon-cognito-identity-js/es/DateHelper.js ***!
8720 \******************************************************/
8721/*! exports provided: default */
8722/***/ (function(module, __webpack_exports__, __webpack_require__) {
8723
8724"use strict";
8725__webpack_require__.r(__webpack_exports__);
8726/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return DateHelper; });
8727/*!
8728 * Copyright 2016 Amazon.com,
8729 * Inc. or its affiliates. All Rights Reserved.
8730 *
8731 * Licensed under the Amazon Software License (the "License").
8732 * You may not use this file except in compliance with the
8733 * License. A copy of the License is located at
8734 *
8735 * http://aws.amazon.com/asl/
8736 *
8737 * or in the "license" file accompanying this file. This file is
8738 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8739 * CONDITIONS OF ANY KIND, express or implied. See the License
8740 * for the specific language governing permissions and
8741 * limitations under the License.
8742 */
8743var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
8744var weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
8745/** @class */
8746
8747var DateHelper = /*#__PURE__*/function () {
8748 function DateHelper() {}
8749
8750 var _proto = DateHelper.prototype;
8751 /**
8752 * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format.
8753 */
8754
8755 _proto.getNowString = function getNowString() {
8756 var now = new Date();
8757 var weekDay = weekNames[now.getUTCDay()];
8758 var month = monthNames[now.getUTCMonth()];
8759 var day = now.getUTCDate();
8760 var hours = now.getUTCHours();
8761
8762 if (hours < 10) {
8763 hours = "0" + hours;
8764 }
8765
8766 var minutes = now.getUTCMinutes();
8767
8768 if (minutes < 10) {
8769 minutes = "0" + minutes;
8770 }
8771
8772 var seconds = now.getUTCSeconds();
8773
8774 if (seconds < 10) {
8775 seconds = "0" + seconds;
8776 }
8777
8778 var year = now.getUTCFullYear(); // ddd MMM D HH:mm:ss UTC YYYY
8779
8780 var dateNow = weekDay + " " + month + " " + day + " " + hours + ":" + minutes + ":" + seconds + " UTC " + year;
8781 return dateNow;
8782 };
8783
8784 return DateHelper;
8785}();
8786
8787
8788
8789/***/ }),
8790
8791/***/ "../amazon-cognito-identity-js/es/Platform/index.js":
8792/*!**********************************************************!*\
8793 !*** ../amazon-cognito-identity-js/es/Platform/index.js ***!
8794 \**********************************************************/
8795/*! exports provided: Platform, getUserAgent, default */
8796/***/ (function(module, __webpack_exports__, __webpack_require__) {
8797
8798"use strict";
8799__webpack_require__.r(__webpack_exports__);
8800/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Platform", function() { return Platform; });
8801/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUserAgent", function() { return getUserAgent; });
8802/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./version */ "../amazon-cognito-identity-js/es/Platform/version.js");
8803/*
8804 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
8805 *
8806 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
8807 * the License. A copy of the License is located at
8808 *
8809 * http://aws.amazon.com/apache2.0/
8810 *
8811 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8812 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
8813 * and limitations under the License.
8814 */
8815
8816var BASE_USER_AGENT = "aws-amplify/" + _version__WEBPACK_IMPORTED_MODULE_0__["version"];
8817var Platform = {
8818 userAgent: BASE_USER_AGENT + " js",
8819 product: '',
8820 navigator: null,
8821 isReactNative: false
8822};
8823
8824if (typeof navigator !== 'undefined' && navigator.product) {
8825 Platform.product = navigator.product || '';
8826 Platform.navigator = navigator || null;
8827
8828 switch (navigator.product) {
8829 case 'ReactNative':
8830 Platform.userAgent = BASE_USER_AGENT + " react-native";
8831 Platform.isReactNative = true;
8832 break;
8833
8834 default:
8835 Platform.userAgent = BASE_USER_AGENT + " js";
8836 Platform.isReactNative = false;
8837 break;
8838 }
8839}
8840
8841var getUserAgent = function getUserAgent() {
8842 return Platform.userAgent;
8843};
8844/**
8845 * @deprecated use named import
8846 */
8847
8848/* harmony default export */ __webpack_exports__["default"] = (Platform);
8849
8850/***/ }),
8851
8852/***/ "../amazon-cognito-identity-js/es/Platform/version.js":
8853/*!************************************************************!*\
8854 !*** ../amazon-cognito-identity-js/es/Platform/version.js ***!
8855 \************************************************************/
8856/*! exports provided: version */
8857/***/ (function(module, __webpack_exports__, __webpack_require__) {
8858
8859"use strict";
8860__webpack_require__.r(__webpack_exports__);
8861/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
8862// generated by genversion
8863var version = '5.0.4';
8864
8865/***/ }),
8866
8867/***/ "../amazon-cognito-identity-js/es/StorageHelper.js":
8868/*!*********************************************************!*\
8869 !*** ../amazon-cognito-identity-js/es/StorageHelper.js ***!
8870 \*********************************************************/
8871/*! exports provided: MemoryStorage, default */
8872/***/ (function(module, __webpack_exports__, __webpack_require__) {
8873
8874"use strict";
8875__webpack_require__.r(__webpack_exports__);
8876/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MemoryStorage", function() { return MemoryStorage; });
8877/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StorageHelper; });
8878/*!
8879 * Copyright 2016 Amazon.com,
8880 * Inc. or its affiliates. All Rights Reserved.
8881 *
8882 * Licensed under the Amazon Software License (the "License").
8883 * You may not use this file except in compliance with the
8884 * License. A copy of the License is located at
8885 *
8886 * http://aws.amazon.com/asl/
8887 *
8888 * or in the "license" file accompanying this file. This file is
8889 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8890 * CONDITIONS OF ANY KIND, express or implied. See the License
8891 * for the specific language governing permissions and
8892 * limitations under the License.
8893 */
8894var dataMemory = {};
8895/** @class */
8896
8897var MemoryStorage = /*#__PURE__*/function () {
8898 function MemoryStorage() {}
8899 /**
8900 * This is used to set a specific item in storage
8901 * @param {string} key - the key for the item
8902 * @param {object} value - the value
8903 * @returns {string} value that was set
8904 */
8905
8906
8907 MemoryStorage.setItem = function setItem(key, value) {
8908 dataMemory[key] = value;
8909 return dataMemory[key];
8910 }
8911 /**
8912 * This is used to get a specific key from storage
8913 * @param {string} key - the key for the item
8914 * This is used to clear the storage
8915 * @returns {string} the data item
8916 */
8917 ;
8918
8919 MemoryStorage.getItem = function getItem(key) {
8920 return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined;
8921 }
8922 /**
8923 * This is used to remove an item from storage
8924 * @param {string} key - the key being set
8925 * @returns {boolean} return true
8926 */
8927 ;
8928
8929 MemoryStorage.removeItem = function removeItem(key) {
8930 return delete dataMemory[key];
8931 }
8932 /**
8933 * This is used to clear the storage
8934 * @returns {string} nothing
8935 */
8936 ;
8937
8938 MemoryStorage.clear = function clear() {
8939 dataMemory = {};
8940 return dataMemory;
8941 };
8942
8943 return MemoryStorage;
8944}();
8945/** @class */
8946
8947var StorageHelper = /*#__PURE__*/function () {
8948 /**
8949 * This is used to get a storage object
8950 * @returns {object} the storage
8951 */
8952 function StorageHelper() {
8953 try {
8954 this.storageWindow = window.localStorage;
8955 this.storageWindow.setItem('aws.cognito.test-ls', 1);
8956 this.storageWindow.removeItem('aws.cognito.test-ls');
8957 } catch (exception) {
8958 this.storageWindow = MemoryStorage;
8959 }
8960 }
8961 /**
8962 * This is used to return the storage
8963 * @returns {object} the storage
8964 */
8965
8966
8967 var _proto = StorageHelper.prototype;
8968
8969 _proto.getStorage = function getStorage() {
8970 return this.storageWindow;
8971 };
8972
8973 return StorageHelper;
8974}();
8975
8976
8977
8978/***/ }),
8979
8980/***/ "../amazon-cognito-identity-js/es/UserAgent.js":
8981/*!*****************************************************!*\
8982 !*** ../amazon-cognito-identity-js/es/UserAgent.js ***!
8983 \*****************************************************/
8984/*! exports provided: appendToCognitoUserAgent, default */
8985/***/ (function(module, __webpack_exports__, __webpack_require__) {
8986
8987"use strict";
8988__webpack_require__.r(__webpack_exports__);
8989/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendToCognitoUserAgent", function() { return appendToCognitoUserAgent; });
8990/* harmony import */ var _Platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Platform */ "../amazon-cognito-identity-js/es/Platform/index.js");
8991 // constructor
8992
8993function UserAgent() {} // public
8994
8995
8996UserAgent.prototype.userAgent = Object(_Platform__WEBPACK_IMPORTED_MODULE_0__["getUserAgent"])();
8997var appendToCognitoUserAgent = function appendToCognitoUserAgent(content) {
8998 if (!content) {
8999 return;
9000 }
9001
9002 if (UserAgent.prototype.userAgent && !UserAgent.prototype.userAgent.includes(content)) {
9003 UserAgent.prototype.userAgent = UserAgent.prototype.userAgent.concat(' ', content);
9004 }
9005
9006 if (!UserAgent.prototype.userAgent || UserAgent.prototype.userAgent === '') {
9007 UserAgent.prototype.userAgent = content;
9008 }
9009}; // class for defining the amzn user-agent
9010
9011/* harmony default export */ __webpack_exports__["default"] = (UserAgent);
9012
9013/***/ }),
9014
9015/***/ "../amazon-cognito-identity-js/es/index.js":
9016/*!*************************************************!*\
9017 !*** ../amazon-cognito-identity-js/es/index.js ***!
9018 \*************************************************/
9019/*! exports provided: AuthenticationDetails, AuthenticationHelper, CognitoAccessToken, CognitoIdToken, CognitoRefreshToken, CognitoUser, CognitoUserAttribute, CognitoUserPool, CognitoUserSession, CookieStorage, DateHelper, appendToCognitoUserAgent, WordArray */
9020/***/ (function(module, __webpack_exports__, __webpack_require__) {
9021
9022"use strict";
9023__webpack_require__.r(__webpack_exports__);
9024/* harmony import */ var _AuthenticationDetails__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AuthenticationDetails */ "../amazon-cognito-identity-js/es/AuthenticationDetails.js");
9025/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthenticationDetails", function() { return _AuthenticationDetails__WEBPACK_IMPORTED_MODULE_0__["default"]; });
9026
9027/* harmony import */ var _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AuthenticationHelper */ "../amazon-cognito-identity-js/es/AuthenticationHelper.js");
9028/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthenticationHelper", function() { return _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_1__["default"]; });
9029
9030/* harmony import */ var _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CognitoAccessToken */ "../amazon-cognito-identity-js/es/CognitoAccessToken.js");
9031/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoAccessToken", function() { return _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_2__["default"]; });
9032
9033/* harmony import */ var _CognitoIdToken__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CognitoIdToken */ "../amazon-cognito-identity-js/es/CognitoIdToken.js");
9034/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoIdToken", function() { return _CognitoIdToken__WEBPACK_IMPORTED_MODULE_3__["default"]; });
9035
9036/* harmony import */ var _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CognitoRefreshToken */ "../amazon-cognito-identity-js/es/CognitoRefreshToken.js");
9037/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoRefreshToken", function() { return _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_4__["default"]; });
9038
9039/* harmony import */ var _CognitoUser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CognitoUser */ "../amazon-cognito-identity-js/es/CognitoUser.js");
9040/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUser", function() { return _CognitoUser__WEBPACK_IMPORTED_MODULE_5__["default"]; });
9041
9042/* harmony import */ var _CognitoUserAttribute__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./CognitoUserAttribute */ "../amazon-cognito-identity-js/es/CognitoUserAttribute.js");
9043/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUserAttribute", function() { return _CognitoUserAttribute__WEBPACK_IMPORTED_MODULE_6__["default"]; });
9044
9045/* harmony import */ var _CognitoUserPool__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CognitoUserPool */ "../amazon-cognito-identity-js/es/CognitoUserPool.js");
9046/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUserPool", function() { return _CognitoUserPool__WEBPACK_IMPORTED_MODULE_7__["default"]; });
9047
9048/* harmony import */ var _CognitoUserSession__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./CognitoUserSession */ "../amazon-cognito-identity-js/es/CognitoUserSession.js");
9049/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUserSession", function() { return _CognitoUserSession__WEBPACK_IMPORTED_MODULE_8__["default"]; });
9050
9051/* harmony import */ var _CookieStorage__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./CookieStorage */ "../amazon-cognito-identity-js/es/CookieStorage.js");
9052/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CookieStorage", function() { return _CookieStorage__WEBPACK_IMPORTED_MODULE_9__["default"]; });
9053
9054/* harmony import */ var _DateHelper__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./DateHelper */ "../amazon-cognito-identity-js/es/DateHelper.js");
9055/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DateHelper", function() { return _DateHelper__WEBPACK_IMPORTED_MODULE_10__["default"]; });
9056
9057/* harmony import */ var _UserAgent__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./UserAgent */ "../amazon-cognito-identity-js/es/UserAgent.js");
9058/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "appendToCognitoUserAgent", function() { return _UserAgent__WEBPACK_IMPORTED_MODULE_11__["appendToCognitoUserAgent"]; });
9059
9060/* harmony import */ var _utils_WordArray__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/WordArray */ "../amazon-cognito-identity-js/es/utils/WordArray.js");
9061/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WordArray", function() { return _utils_WordArray__WEBPACK_IMPORTED_MODULE_12__["default"]; });
9062
9063/*!
9064 * Copyright 2016 Amazon.com,
9065 * Inc. or its affiliates. All Rights Reserved.
9066 *
9067 * Licensed under the Amazon Software License (the "License").
9068 * You may not use this file except in compliance with the
9069 * License. A copy of the License is located at
9070 *
9071 * http://aws.amazon.com/asl/
9072 *
9073 * or in the "license" file accompanying this file. This file is
9074 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
9075 * CONDITIONS OF ANY KIND, express or implied. See the License
9076 * for the specific language governing permissions and
9077 * limitations under the License.
9078 */
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093/***/ }),
9094
9095/***/ "../amazon-cognito-identity-js/es/utils/WordArray.js":
9096/*!***********************************************************!*\
9097 !*** ../amazon-cognito-identity-js/es/utils/WordArray.js ***!
9098 \***********************************************************/
9099/*! exports provided: default */
9100/***/ (function(module, __webpack_exports__, __webpack_require__) {
9101
9102"use strict";
9103__webpack_require__.r(__webpack_exports__);
9104/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WordArray; });
9105/* harmony import */ var _cryptoSecureRandomInt__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./cryptoSecureRandomInt */ "../amazon-cognito-identity-js/es/utils/cryptoSecureRandomInt.js");
9106
9107/**
9108 * Hex encoding strategy.
9109 * Converts a word array to a hex string.
9110 * @param {WordArray} wordArray The word array.
9111 * @return {string} The hex string.
9112 * @static
9113 */
9114
9115function hexStringify(wordArray) {
9116 // Shortcuts
9117 var words = wordArray.words;
9118 var sigBytes = wordArray.sigBytes; // Convert
9119
9120 var hexChars = [];
9121
9122 for (var i = 0; i < sigBytes; i++) {
9123 var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
9124 hexChars.push((bite >>> 4).toString(16));
9125 hexChars.push((bite & 0x0f).toString(16));
9126 }
9127
9128 return hexChars.join('');
9129}
9130
9131var WordArray = /*#__PURE__*/function () {
9132 function WordArray(words, sigBytes) {
9133 words = this.words = words || [];
9134
9135 if (sigBytes != undefined) {
9136 this.sigBytes = sigBytes;
9137 } else {
9138 this.sigBytes = words.length * 4;
9139 }
9140 }
9141
9142 var _proto = WordArray.prototype;
9143
9144 _proto.random = function random(nBytes) {
9145 var words = [];
9146
9147 for (var i = 0; i < nBytes; i += 4) {
9148 words.push(Object(_cryptoSecureRandomInt__WEBPACK_IMPORTED_MODULE_0__["default"])());
9149 }
9150
9151 return new WordArray(words, nBytes);
9152 };
9153
9154 _proto.toString = function toString() {
9155 return hexStringify(this);
9156 };
9157
9158 return WordArray;
9159}();
9160
9161
9162
9163/***/ }),
9164
9165/***/ "../amazon-cognito-identity-js/es/utils/cryptoSecureRandomInt.js":
9166/*!***********************************************************************!*\
9167 !*** ../amazon-cognito-identity-js/es/utils/cryptoSecureRandomInt.js ***!
9168 \***********************************************************************/
9169/*! exports provided: default */
9170/***/ (function(module, __webpack_exports__, __webpack_require__) {
9171
9172"use strict";
9173__webpack_require__.r(__webpack_exports__);
9174/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return cryptoSecureRandomInt; });
9175var crypto; // Native crypto from window (Browser)
9176
9177if (typeof window !== 'undefined' && window.crypto) {
9178 crypto = window.crypto;
9179} // Native (experimental IE 11) crypto from window (Browser)
9180
9181
9182if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
9183 crypto = window.msCrypto;
9184} // Native crypto from global (NodeJS)
9185
9186
9187if (!crypto && typeof global !== 'undefined' && global.crypto) {
9188 crypto = global.crypto;
9189} // Native crypto import via require (NodeJS)
9190
9191
9192if (!crypto && "function" === 'function') {
9193 try {
9194 crypto = __webpack_require__(/*! crypto */ 1);
9195 } catch (err) {}
9196}
9197/*
9198 * Cryptographically secure pseudorandom number generator
9199 * As Math.random() is cryptographically not safe to use
9200 */
9201
9202
9203function cryptoSecureRandomInt() {
9204 if (crypto) {
9205 // Use getRandomValues method (Browser)
9206 if (typeof crypto.getRandomValues === 'function') {
9207 try {
9208 return crypto.getRandomValues(new Uint32Array(1))[0];
9209 } catch (err) {}
9210 } // Use randomBytes method (NodeJS)
9211
9212
9213 if (typeof crypto.randomBytes === 'function') {
9214 try {
9215 return crypto.randomBytes(4).readInt32LE();
9216 } catch (err) {}
9217 }
9218 }
9219
9220 throw new Error('Native crypto module could not be used to get secure random number.');
9221}
9222/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
9223
9224/***/ }),
9225
9226/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js":
9227/*!********************************************************************!*\
9228 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/core.js ***!
9229 \********************************************************************/
9230/*! no static exports found */
9231/***/ (function(module, exports, __webpack_require__) {
9232
9233/* WEBPACK VAR INJECTION */(function(global) {;(function (root, factory) {
9234 if (true) {
9235 // CommonJS
9236 module.exports = exports = factory();
9237 }
9238 else {}
9239}(this, function () {
9240
9241 /*globals window, global, require*/
9242
9243 /**
9244 * CryptoJS core components.
9245 */
9246 var CryptoJS = CryptoJS || (function (Math, undefined) {
9247
9248 var crypto;
9249
9250 // Native crypto from window (Browser)
9251 if (typeof window !== 'undefined' && window.crypto) {
9252 crypto = window.crypto;
9253 }
9254
9255 // Native crypto in web worker (Browser)
9256 if (typeof self !== 'undefined' && self.crypto) {
9257 crypto = self.crypto;
9258 }
9259
9260 // Native crypto from worker
9261 if (typeof globalThis !== 'undefined' && globalThis.crypto) {
9262 crypto = globalThis.crypto;
9263 }
9264
9265 // Native (experimental IE 11) crypto from window (Browser)
9266 if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
9267 crypto = window.msCrypto;
9268 }
9269
9270 // Native crypto from global (NodeJS)
9271 if (!crypto && typeof global !== 'undefined' && global.crypto) {
9272 crypto = global.crypto;
9273 }
9274
9275 // Native crypto import via require (NodeJS)
9276 if (!crypto && "function" === 'function') {
9277 try {
9278 crypto = __webpack_require__(/*! crypto */ 0);
9279 } catch (err) {}
9280 }
9281
9282 /*
9283 * Cryptographically secure pseudorandom number generator
9284 *
9285 * As Math.random() is cryptographically not safe to use
9286 */
9287 var cryptoSecureRandomInt = function () {
9288 if (crypto) {
9289 // Use getRandomValues method (Browser)
9290 if (typeof crypto.getRandomValues === 'function') {
9291 try {
9292 return crypto.getRandomValues(new Uint32Array(1))[0];
9293 } catch (err) {}
9294 }
9295
9296 // Use randomBytes method (NodeJS)
9297 if (typeof crypto.randomBytes === 'function') {
9298 try {
9299 return crypto.randomBytes(4).readInt32LE();
9300 } catch (err) {}
9301 }
9302 }
9303
9304 throw new Error('Native crypto module could not be used to get secure random number.');
9305 };
9306
9307 /*
9308 * Local polyfill of Object.create
9309
9310 */
9311 var create = Object.create || (function () {
9312 function F() {}
9313
9314 return function (obj) {
9315 var subtype;
9316
9317 F.prototype = obj;
9318
9319 subtype = new F();
9320
9321 F.prototype = null;
9322
9323 return subtype;
9324 };
9325 }());
9326
9327 /**
9328 * CryptoJS namespace.
9329 */
9330 var C = {};
9331
9332 /**
9333 * Library namespace.
9334 */
9335 var C_lib = C.lib = {};
9336
9337 /**
9338 * Base object for prototypal inheritance.
9339 */
9340 var Base = C_lib.Base = (function () {
9341
9342
9343 return {
9344 /**
9345 * Creates a new object that inherits from this object.
9346 *
9347 * @param {Object} overrides Properties to copy into the new object.
9348 *
9349 * @return {Object} The new object.
9350 *
9351 * @static
9352 *
9353 * @example
9354 *
9355 * var MyType = CryptoJS.lib.Base.extend({
9356 * field: 'value',
9357 *
9358 * method: function () {
9359 * }
9360 * });
9361 */
9362 extend: function (overrides) {
9363 // Spawn
9364 var subtype = create(this);
9365
9366 // Augment
9367 if (overrides) {
9368 subtype.mixIn(overrides);
9369 }
9370
9371 // Create default initializer
9372 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
9373 subtype.init = function () {
9374 subtype.$super.init.apply(this, arguments);
9375 };
9376 }
9377
9378 // Initializer's prototype is the subtype object
9379 subtype.init.prototype = subtype;
9380
9381 // Reference supertype
9382 subtype.$super = this;
9383
9384 return subtype;
9385 },
9386
9387 /**
9388 * Extends this object and runs the init method.
9389 * Arguments to create() will be passed to init().
9390 *
9391 * @return {Object} The new object.
9392 *
9393 * @static
9394 *
9395 * @example
9396 *
9397 * var instance = MyType.create();
9398 */
9399 create: function () {
9400 var instance = this.extend();
9401 instance.init.apply(instance, arguments);
9402
9403 return instance;
9404 },
9405
9406 /**
9407 * Initializes a newly created object.
9408 * Override this method to add some logic when your objects are created.
9409 *
9410 * @example
9411 *
9412 * var MyType = CryptoJS.lib.Base.extend({
9413 * init: function () {
9414 * // ...
9415 * }
9416 * });
9417 */
9418 init: function () {
9419 },
9420
9421 /**
9422 * Copies properties into this object.
9423 *
9424 * @param {Object} properties The properties to mix in.
9425 *
9426 * @example
9427 *
9428 * MyType.mixIn({
9429 * field: 'value'
9430 * });
9431 */
9432 mixIn: function (properties) {
9433 for (var propertyName in properties) {
9434 if (properties.hasOwnProperty(propertyName)) {
9435 this[propertyName] = properties[propertyName];
9436 }
9437 }
9438
9439 // IE won't copy toString using the loop above
9440 if (properties.hasOwnProperty('toString')) {
9441 this.toString = properties.toString;
9442 }
9443 },
9444
9445 /**
9446 * Creates a copy of this object.
9447 *
9448 * @return {Object} The clone.
9449 *
9450 * @example
9451 *
9452 * var clone = instance.clone();
9453 */
9454 clone: function () {
9455 return this.init.prototype.extend(this);
9456 }
9457 };
9458 }());
9459
9460 /**
9461 * An array of 32-bit words.
9462 *
9463 * @property {Array} words The array of 32-bit words.
9464 * @property {number} sigBytes The number of significant bytes in this word array.
9465 */
9466 var WordArray = C_lib.WordArray = Base.extend({
9467 /**
9468 * Initializes a newly created word array.
9469 *
9470 * @param {Array} words (Optional) An array of 32-bit words.
9471 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
9472 *
9473 * @example
9474 *
9475 * var wordArray = CryptoJS.lib.WordArray.create();
9476 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
9477 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
9478 */
9479 init: function (words, sigBytes) {
9480 words = this.words = words || [];
9481
9482 if (sigBytes != undefined) {
9483 this.sigBytes = sigBytes;
9484 } else {
9485 this.sigBytes = words.length * 4;
9486 }
9487 },
9488
9489 /**
9490 * Converts this word array to a string.
9491 *
9492 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
9493 *
9494 * @return {string} The stringified word array.
9495 *
9496 * @example
9497 *
9498 * var string = wordArray + '';
9499 * var string = wordArray.toString();
9500 * var string = wordArray.toString(CryptoJS.enc.Utf8);
9501 */
9502 toString: function (encoder) {
9503 return (encoder || Hex).stringify(this);
9504 },
9505
9506 /**
9507 * Concatenates a word array to this word array.
9508 *
9509 * @param {WordArray} wordArray The word array to append.
9510 *
9511 * @return {WordArray} This word array.
9512 *
9513 * @example
9514 *
9515 * wordArray1.concat(wordArray2);
9516 */
9517 concat: function (wordArray) {
9518 // Shortcuts
9519 var thisWords = this.words;
9520 var thatWords = wordArray.words;
9521 var thisSigBytes = this.sigBytes;
9522 var thatSigBytes = wordArray.sigBytes;
9523
9524 // Clamp excess bits
9525 this.clamp();
9526
9527 // Concat
9528 if (thisSigBytes % 4) {
9529 // Copy one byte at a time
9530 for (var i = 0; i < thatSigBytes; i++) {
9531 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
9532 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
9533 }
9534 } else {
9535 // Copy one word at a time
9536 for (var j = 0; j < thatSigBytes; j += 4) {
9537 thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
9538 }
9539 }
9540 this.sigBytes += thatSigBytes;
9541
9542 // Chainable
9543 return this;
9544 },
9545
9546 /**
9547 * Removes insignificant bits.
9548 *
9549 * @example
9550 *
9551 * wordArray.clamp();
9552 */
9553 clamp: function () {
9554 // Shortcuts
9555 var words = this.words;
9556 var sigBytes = this.sigBytes;
9557
9558 // Clamp
9559 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
9560 words.length = Math.ceil(sigBytes / 4);
9561 },
9562
9563 /**
9564 * Creates a copy of this word array.
9565 *
9566 * @return {WordArray} The clone.
9567 *
9568 * @example
9569 *
9570 * var clone = wordArray.clone();
9571 */
9572 clone: function () {
9573 var clone = Base.clone.call(this);
9574 clone.words = this.words.slice(0);
9575
9576 return clone;
9577 },
9578
9579 /**
9580 * Creates a word array filled with random bytes.
9581 *
9582 * @param {number} nBytes The number of random bytes to generate.
9583 *
9584 * @return {WordArray} The random word array.
9585 *
9586 * @static
9587 *
9588 * @example
9589 *
9590 * var wordArray = CryptoJS.lib.WordArray.random(16);
9591 */
9592 random: function (nBytes) {
9593 var words = [];
9594
9595 for (var i = 0; i < nBytes; i += 4) {
9596 words.push(cryptoSecureRandomInt());
9597 }
9598
9599 return new WordArray.init(words, nBytes);
9600 }
9601 });
9602
9603 /**
9604 * Encoder namespace.
9605 */
9606 var C_enc = C.enc = {};
9607
9608 /**
9609 * Hex encoding strategy.
9610 */
9611 var Hex = C_enc.Hex = {
9612 /**
9613 * Converts a word array to a hex string.
9614 *
9615 * @param {WordArray} wordArray The word array.
9616 *
9617 * @return {string} The hex string.
9618 *
9619 * @static
9620 *
9621 * @example
9622 *
9623 * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
9624 */
9625 stringify: function (wordArray) {
9626 // Shortcuts
9627 var words = wordArray.words;
9628 var sigBytes = wordArray.sigBytes;
9629
9630 // Convert
9631 var hexChars = [];
9632 for (var i = 0; i < sigBytes; i++) {
9633 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
9634 hexChars.push((bite >>> 4).toString(16));
9635 hexChars.push((bite & 0x0f).toString(16));
9636 }
9637
9638 return hexChars.join('');
9639 },
9640
9641 /**
9642 * Converts a hex string to a word array.
9643 *
9644 * @param {string} hexStr The hex string.
9645 *
9646 * @return {WordArray} The word array.
9647 *
9648 * @static
9649 *
9650 * @example
9651 *
9652 * var wordArray = CryptoJS.enc.Hex.parse(hexString);
9653 */
9654 parse: function (hexStr) {
9655 // Shortcut
9656 var hexStrLength = hexStr.length;
9657
9658 // Convert
9659 var words = [];
9660 for (var i = 0; i < hexStrLength; i += 2) {
9661 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
9662 }
9663
9664 return new WordArray.init(words, hexStrLength / 2);
9665 }
9666 };
9667
9668 /**
9669 * Latin1 encoding strategy.
9670 */
9671 var Latin1 = C_enc.Latin1 = {
9672 /**
9673 * Converts a word array to a Latin1 string.
9674 *
9675 * @param {WordArray} wordArray The word array.
9676 *
9677 * @return {string} The Latin1 string.
9678 *
9679 * @static
9680 *
9681 * @example
9682 *
9683 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
9684 */
9685 stringify: function (wordArray) {
9686 // Shortcuts
9687 var words = wordArray.words;
9688 var sigBytes = wordArray.sigBytes;
9689
9690 // Convert
9691 var latin1Chars = [];
9692 for (var i = 0; i < sigBytes; i++) {
9693 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
9694 latin1Chars.push(String.fromCharCode(bite));
9695 }
9696
9697 return latin1Chars.join('');
9698 },
9699
9700 /**
9701 * Converts a Latin1 string to a word array.
9702 *
9703 * @param {string} latin1Str The Latin1 string.
9704 *
9705 * @return {WordArray} The word array.
9706 *
9707 * @static
9708 *
9709 * @example
9710 *
9711 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
9712 */
9713 parse: function (latin1Str) {
9714 // Shortcut
9715 var latin1StrLength = latin1Str.length;
9716
9717 // Convert
9718 var words = [];
9719 for (var i = 0; i < latin1StrLength; i++) {
9720 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
9721 }
9722
9723 return new WordArray.init(words, latin1StrLength);
9724 }
9725 };
9726
9727 /**
9728 * UTF-8 encoding strategy.
9729 */
9730 var Utf8 = C_enc.Utf8 = {
9731 /**
9732 * Converts a word array to a UTF-8 string.
9733 *
9734 * @param {WordArray} wordArray The word array.
9735 *
9736 * @return {string} The UTF-8 string.
9737 *
9738 * @static
9739 *
9740 * @example
9741 *
9742 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
9743 */
9744 stringify: function (wordArray) {
9745 try {
9746 return decodeURIComponent(escape(Latin1.stringify(wordArray)));
9747 } catch (e) {
9748 throw new Error('Malformed UTF-8 data');
9749 }
9750 },
9751
9752 /**
9753 * Converts a UTF-8 string to a word array.
9754 *
9755 * @param {string} utf8Str The UTF-8 string.
9756 *
9757 * @return {WordArray} The word array.
9758 *
9759 * @static
9760 *
9761 * @example
9762 *
9763 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
9764 */
9765 parse: function (utf8Str) {
9766 return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
9767 }
9768 };
9769
9770 /**
9771 * Abstract buffered block algorithm template.
9772 *
9773 * The property blockSize must be implemented in a concrete subtype.
9774 *
9775 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
9776 */
9777 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
9778 /**
9779 * Resets this block algorithm's data buffer to its initial state.
9780 *
9781 * @example
9782 *
9783 * bufferedBlockAlgorithm.reset();
9784 */
9785 reset: function () {
9786 // Initial values
9787 this._data = new WordArray.init();
9788 this._nDataBytes = 0;
9789 },
9790
9791 /**
9792 * Adds new data to this block algorithm's buffer.
9793 *
9794 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
9795 *
9796 * @example
9797 *
9798 * bufferedBlockAlgorithm._append('data');
9799 * bufferedBlockAlgorithm._append(wordArray);
9800 */
9801 _append: function (data) {
9802 // Convert string to WordArray, else assume WordArray already
9803 if (typeof data == 'string') {
9804 data = Utf8.parse(data);
9805 }
9806
9807 // Append
9808 this._data.concat(data);
9809 this._nDataBytes += data.sigBytes;
9810 },
9811
9812 /**
9813 * Processes available data blocks.
9814 *
9815 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
9816 *
9817 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
9818 *
9819 * @return {WordArray} The processed data.
9820 *
9821 * @example
9822 *
9823 * var processedData = bufferedBlockAlgorithm._process();
9824 * var processedData = bufferedBlockAlgorithm._process(!!'flush');
9825 */
9826 _process: function (doFlush) {
9827 var processedWords;
9828
9829 // Shortcuts
9830 var data = this._data;
9831 var dataWords = data.words;
9832 var dataSigBytes = data.sigBytes;
9833 var blockSize = this.blockSize;
9834 var blockSizeBytes = blockSize * 4;
9835
9836 // Count blocks ready
9837 var nBlocksReady = dataSigBytes / blockSizeBytes;
9838 if (doFlush) {
9839 // Round up to include partial blocks
9840 nBlocksReady = Math.ceil(nBlocksReady);
9841 } else {
9842 // Round down to include only full blocks,
9843 // less the number of blocks that must remain in the buffer
9844 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
9845 }
9846
9847 // Count words ready
9848 var nWordsReady = nBlocksReady * blockSize;
9849
9850 // Count bytes ready
9851 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
9852
9853 // Process blocks
9854 if (nWordsReady) {
9855 for (var offset = 0; offset < nWordsReady; offset += blockSize) {
9856 // Perform concrete-algorithm logic
9857 this._doProcessBlock(dataWords, offset);
9858 }
9859
9860 // Remove processed words
9861 processedWords = dataWords.splice(0, nWordsReady);
9862 data.sigBytes -= nBytesReady;
9863 }
9864
9865 // Return processed words
9866 return new WordArray.init(processedWords, nBytesReady);
9867 },
9868
9869 /**
9870 * Creates a copy of this object.
9871 *
9872 * @return {Object} The clone.
9873 *
9874 * @example
9875 *
9876 * var clone = bufferedBlockAlgorithm.clone();
9877 */
9878 clone: function () {
9879 var clone = Base.clone.call(this);
9880 clone._data = this._data.clone();
9881
9882 return clone;
9883 },
9884
9885 _minBufferSize: 0
9886 });
9887
9888 /**
9889 * Abstract hasher template.
9890 *
9891 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
9892 */
9893 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
9894 /**
9895 * Configuration options.
9896 */
9897 cfg: Base.extend(),
9898
9899 /**
9900 * Initializes a newly created hasher.
9901 *
9902 * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
9903 *
9904 * @example
9905 *
9906 * var hasher = CryptoJS.algo.SHA256.create();
9907 */
9908 init: function (cfg) {
9909 // Apply config defaults
9910 this.cfg = this.cfg.extend(cfg);
9911
9912 // Set initial values
9913 this.reset();
9914 },
9915
9916 /**
9917 * Resets this hasher to its initial state.
9918 *
9919 * @example
9920 *
9921 * hasher.reset();
9922 */
9923 reset: function () {
9924 // Reset data buffer
9925 BufferedBlockAlgorithm.reset.call(this);
9926
9927 // Perform concrete-hasher logic
9928 this._doReset();
9929 },
9930
9931 /**
9932 * Updates this hasher with a message.
9933 *
9934 * @param {WordArray|string} messageUpdate The message to append.
9935 *
9936 * @return {Hasher} This hasher.
9937 *
9938 * @example
9939 *
9940 * hasher.update('message');
9941 * hasher.update(wordArray);
9942 */
9943 update: function (messageUpdate) {
9944 // Append
9945 this._append(messageUpdate);
9946
9947 // Update the hash
9948 this._process();
9949
9950 // Chainable
9951 return this;
9952 },
9953
9954 /**
9955 * Finalizes the hash computation.
9956 * Note that the finalize operation is effectively a destructive, read-once operation.
9957 *
9958 * @param {WordArray|string} messageUpdate (Optional) A final message update.
9959 *
9960 * @return {WordArray} The hash.
9961 *
9962 * @example
9963 *
9964 * var hash = hasher.finalize();
9965 * var hash = hasher.finalize('message');
9966 * var hash = hasher.finalize(wordArray);
9967 */
9968 finalize: function (messageUpdate) {
9969 // Final message update
9970 if (messageUpdate) {
9971 this._append(messageUpdate);
9972 }
9973
9974 // Perform concrete-hasher logic
9975 var hash = this._doFinalize();
9976
9977 return hash;
9978 },
9979
9980 blockSize: 512/32,
9981
9982 /**
9983 * Creates a shortcut function to a hasher's object interface.
9984 *
9985 * @param {Hasher} hasher The hasher to create a helper for.
9986 *
9987 * @return {Function} The shortcut function.
9988 *
9989 * @static
9990 *
9991 * @example
9992 *
9993 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
9994 */
9995 _createHelper: function (hasher) {
9996 return function (message, cfg) {
9997 return new hasher.init(cfg).finalize(message);
9998 };
9999 },
10000
10001 /**
10002 * Creates a shortcut function to the HMAC's object interface.
10003 *
10004 * @param {Hasher} hasher The hasher to use in this HMAC helper.
10005 *
10006 * @return {Function} The shortcut function.
10007 *
10008 * @static
10009 *
10010 * @example
10011 *
10012 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
10013 */
10014 _createHmacHelper: function (hasher) {
10015 return function (message, key) {
10016 return new C_algo.HMAC.init(hasher, key).finalize(message);
10017 };
10018 }
10019 });
10020
10021 /**
10022 * Algorithm namespace.
10023 */
10024 var C_algo = C.algo = {};
10025
10026 return C;
10027 }(Math));
10028
10029
10030 return CryptoJS;
10031
10032}));
10033/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
10034
10035/***/ }),
10036
10037/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/enc-base64.js":
10038/*!**************************************************************************!*\
10039 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/enc-base64.js ***!
10040 \**************************************************************************/
10041/*! no static exports found */
10042/***/ (function(module, exports, __webpack_require__) {
10043
10044;(function (root, factory) {
10045 if (true) {
10046 // CommonJS
10047 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"));
10048 }
10049 else {}
10050}(this, function (CryptoJS) {
10051
10052 (function () {
10053 // Shortcuts
10054 var C = CryptoJS;
10055 var C_lib = C.lib;
10056 var WordArray = C_lib.WordArray;
10057 var C_enc = C.enc;
10058
10059 /**
10060 * Base64 encoding strategy.
10061 */
10062 var Base64 = C_enc.Base64 = {
10063 /**
10064 * Converts a word array to a Base64 string.
10065 *
10066 * @param {WordArray} wordArray The word array.
10067 *
10068 * @return {string} The Base64 string.
10069 *
10070 * @static
10071 *
10072 * @example
10073 *
10074 * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
10075 */
10076 stringify: function (wordArray) {
10077 // Shortcuts
10078 var words = wordArray.words;
10079 var sigBytes = wordArray.sigBytes;
10080 var map = this._map;
10081
10082 // Clamp excess bits
10083 wordArray.clamp();
10084
10085 // Convert
10086 var base64Chars = [];
10087 for (var i = 0; i < sigBytes; i += 3) {
10088 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
10089 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
10090 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
10091
10092 var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
10093
10094 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
10095 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
10096 }
10097 }
10098
10099 // Add padding
10100 var paddingChar = map.charAt(64);
10101 if (paddingChar) {
10102 while (base64Chars.length % 4) {
10103 base64Chars.push(paddingChar);
10104 }
10105 }
10106
10107 return base64Chars.join('');
10108 },
10109
10110 /**
10111 * Converts a Base64 string to a word array.
10112 *
10113 * @param {string} base64Str The Base64 string.
10114 *
10115 * @return {WordArray} The word array.
10116 *
10117 * @static
10118 *
10119 * @example
10120 *
10121 * var wordArray = CryptoJS.enc.Base64.parse(base64String);
10122 */
10123 parse: function (base64Str) {
10124 // Shortcuts
10125 var base64StrLength = base64Str.length;
10126 var map = this._map;
10127 var reverseMap = this._reverseMap;
10128
10129 if (!reverseMap) {
10130 reverseMap = this._reverseMap = [];
10131 for (var j = 0; j < map.length; j++) {
10132 reverseMap[map.charCodeAt(j)] = j;
10133 }
10134 }
10135
10136 // Ignore padding
10137 var paddingChar = map.charAt(64);
10138 if (paddingChar) {
10139 var paddingIndex = base64Str.indexOf(paddingChar);
10140 if (paddingIndex !== -1) {
10141 base64StrLength = paddingIndex;
10142 }
10143 }
10144
10145 // Convert
10146 return parseLoop(base64Str, base64StrLength, reverseMap);
10147
10148 },
10149
10150 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
10151 };
10152
10153 function parseLoop(base64Str, base64StrLength, reverseMap) {
10154 var words = [];
10155 var nBytes = 0;
10156 for (var i = 0; i < base64StrLength; i++) {
10157 if (i % 4) {
10158 var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
10159 var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
10160 var bitsCombined = bits1 | bits2;
10161 words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
10162 nBytes++;
10163 }
10164 }
10165 return WordArray.create(words, nBytes);
10166 }
10167 }());
10168
10169
10170 return CryptoJS.enc.Base64;
10171
10172}));
10173
10174/***/ }),
10175
10176/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/hmac-sha256.js":
10177/*!***************************************************************************!*\
10178 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/hmac-sha256.js ***!
10179 \***************************************************************************/
10180/*! no static exports found */
10181/***/ (function(module, exports, __webpack_require__) {
10182
10183;(function (root, factory, undef) {
10184 if (true) {
10185 // CommonJS
10186 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"), __webpack_require__(/*! ./sha256 */ "../amazon-cognito-identity-js/node_modules/crypto-js/sha256.js"), __webpack_require__(/*! ./hmac */ "../amazon-cognito-identity-js/node_modules/crypto-js/hmac.js"));
10187 }
10188 else {}
10189}(this, function (CryptoJS) {
10190
10191 return CryptoJS.HmacSHA256;
10192
10193}));
10194
10195/***/ }),
10196
10197/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/hmac.js":
10198/*!********************************************************************!*\
10199 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/hmac.js ***!
10200 \********************************************************************/
10201/*! no static exports found */
10202/***/ (function(module, exports, __webpack_require__) {
10203
10204;(function (root, factory) {
10205 if (true) {
10206 // CommonJS
10207 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"));
10208 }
10209 else {}
10210}(this, function (CryptoJS) {
10211
10212 (function () {
10213 // Shortcuts
10214 var C = CryptoJS;
10215 var C_lib = C.lib;
10216 var Base = C_lib.Base;
10217 var C_enc = C.enc;
10218 var Utf8 = C_enc.Utf8;
10219 var C_algo = C.algo;
10220
10221 /**
10222 * HMAC algorithm.
10223 */
10224 var HMAC = C_algo.HMAC = Base.extend({
10225 /**
10226 * Initializes a newly created HMAC.
10227 *
10228 * @param {Hasher} hasher The hash algorithm to use.
10229 * @param {WordArray|string} key The secret key.
10230 *
10231 * @example
10232 *
10233 * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
10234 */
10235 init: function (hasher, key) {
10236 // Init hasher
10237 hasher = this._hasher = new hasher.init();
10238
10239 // Convert string to WordArray, else assume WordArray already
10240 if (typeof key == 'string') {
10241 key = Utf8.parse(key);
10242 }
10243
10244 // Shortcuts
10245 var hasherBlockSize = hasher.blockSize;
10246 var hasherBlockSizeBytes = hasherBlockSize * 4;
10247
10248 // Allow arbitrary length keys
10249 if (key.sigBytes > hasherBlockSizeBytes) {
10250 key = hasher.finalize(key);
10251 }
10252
10253 // Clamp excess bits
10254 key.clamp();
10255
10256 // Clone key for inner and outer pads
10257 var oKey = this._oKey = key.clone();
10258 var iKey = this._iKey = key.clone();
10259
10260 // Shortcuts
10261 var oKeyWords = oKey.words;
10262 var iKeyWords = iKey.words;
10263
10264 // XOR keys with pad constants
10265 for (var i = 0; i < hasherBlockSize; i++) {
10266 oKeyWords[i] ^= 0x5c5c5c5c;
10267 iKeyWords[i] ^= 0x36363636;
10268 }
10269 oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
10270
10271 // Set initial values
10272 this.reset();
10273 },
10274
10275 /**
10276 * Resets this HMAC to its initial state.
10277 *
10278 * @example
10279 *
10280 * hmacHasher.reset();
10281 */
10282 reset: function () {
10283 // Shortcut
10284 var hasher = this._hasher;
10285
10286 // Reset
10287 hasher.reset();
10288 hasher.update(this._iKey);
10289 },
10290
10291 /**
10292 * Updates this HMAC with a message.
10293 *
10294 * @param {WordArray|string} messageUpdate The message to append.
10295 *
10296 * @return {HMAC} This HMAC instance.
10297 *
10298 * @example
10299 *
10300 * hmacHasher.update('message');
10301 * hmacHasher.update(wordArray);
10302 */
10303 update: function (messageUpdate) {
10304 this._hasher.update(messageUpdate);
10305
10306 // Chainable
10307 return this;
10308 },
10309
10310 /**
10311 * Finalizes the HMAC computation.
10312 * Note that the finalize operation is effectively a destructive, read-once operation.
10313 *
10314 * @param {WordArray|string} messageUpdate (Optional) A final message update.
10315 *
10316 * @return {WordArray} The HMAC.
10317 *
10318 * @example
10319 *
10320 * var hmac = hmacHasher.finalize();
10321 * var hmac = hmacHasher.finalize('message');
10322 * var hmac = hmacHasher.finalize(wordArray);
10323 */
10324 finalize: function (messageUpdate) {
10325 // Shortcut
10326 var hasher = this._hasher;
10327
10328 // Compute HMAC
10329 var innerHash = hasher.finalize(messageUpdate);
10330 hasher.reset();
10331 var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
10332
10333 return hmac;
10334 }
10335 });
10336 }());
10337
10338
10339}));
10340
10341/***/ }),
10342
10343/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/lib-typedarrays.js":
10344/*!*******************************************************************************!*\
10345 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/lib-typedarrays.js ***!
10346 \*******************************************************************************/
10347/*! no static exports found */
10348/***/ (function(module, exports, __webpack_require__) {
10349
10350;(function (root, factory) {
10351 if (true) {
10352 // CommonJS
10353 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"));
10354 }
10355 else {}
10356}(this, function (CryptoJS) {
10357
10358 (function () {
10359 // Check if typed arrays are supported
10360 if (typeof ArrayBuffer != 'function') {
10361 return;
10362 }
10363
10364 // Shortcuts
10365 var C = CryptoJS;
10366 var C_lib = C.lib;
10367 var WordArray = C_lib.WordArray;
10368
10369 // Reference original init
10370 var superInit = WordArray.init;
10371
10372 // Augment WordArray.init to handle typed arrays
10373 var subInit = WordArray.init = function (typedArray) {
10374 // Convert buffers to uint8
10375 if (typedArray instanceof ArrayBuffer) {
10376 typedArray = new Uint8Array(typedArray);
10377 }
10378
10379 // Convert other array views to uint8
10380 if (
10381 typedArray instanceof Int8Array ||
10382 (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
10383 typedArray instanceof Int16Array ||
10384 typedArray instanceof Uint16Array ||
10385 typedArray instanceof Int32Array ||
10386 typedArray instanceof Uint32Array ||
10387 typedArray instanceof Float32Array ||
10388 typedArray instanceof Float64Array
10389 ) {
10390 typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
10391 }
10392
10393 // Handle Uint8Array
10394 if (typedArray instanceof Uint8Array) {
10395 // Shortcut
10396 var typedArrayByteLength = typedArray.byteLength;
10397
10398 // Extract bytes
10399 var words = [];
10400 for (var i = 0; i < typedArrayByteLength; i++) {
10401 words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
10402 }
10403
10404 // Initialize this word array
10405 superInit.call(this, words, typedArrayByteLength);
10406 } else {
10407 // Else call normal init
10408 superInit.apply(this, arguments);
10409 }
10410 };
10411
10412 subInit.prototype = WordArray;
10413 }());
10414
10415
10416 return CryptoJS.lib.WordArray;
10417
10418}));
10419
10420/***/ }),
10421
10422/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/sha256.js":
10423/*!**********************************************************************!*\
10424 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/sha256.js ***!
10425 \**********************************************************************/
10426/*! no static exports found */
10427/***/ (function(module, exports, __webpack_require__) {
10428
10429;(function (root, factory) {
10430 if (true) {
10431 // CommonJS
10432 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"));
10433 }
10434 else {}
10435}(this, function (CryptoJS) {
10436
10437 (function (Math) {
10438 // Shortcuts
10439 var C = CryptoJS;
10440 var C_lib = C.lib;
10441 var WordArray = C_lib.WordArray;
10442 var Hasher = C_lib.Hasher;
10443 var C_algo = C.algo;
10444
10445 // Initialization and round constants tables
10446 var H = [];
10447 var K = [];
10448
10449 // Compute constants
10450 (function () {
10451 function isPrime(n) {
10452 var sqrtN = Math.sqrt(n);
10453 for (var factor = 2; factor <= sqrtN; factor++) {
10454 if (!(n % factor)) {
10455 return false;
10456 }
10457 }
10458
10459 return true;
10460 }
10461
10462 function getFractionalBits(n) {
10463 return ((n - (n | 0)) * 0x100000000) | 0;
10464 }
10465
10466 var n = 2;
10467 var nPrime = 0;
10468 while (nPrime < 64) {
10469 if (isPrime(n)) {
10470 if (nPrime < 8) {
10471 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
10472 }
10473 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
10474
10475 nPrime++;
10476 }
10477
10478 n++;
10479 }
10480 }());
10481
10482 // Reusable object
10483 var W = [];
10484
10485 /**
10486 * SHA-256 hash algorithm.
10487 */
10488 var SHA256 = C_algo.SHA256 = Hasher.extend({
10489 _doReset: function () {
10490 this._hash = new WordArray.init(H.slice(0));
10491 },
10492
10493 _doProcessBlock: function (M, offset) {
10494 // Shortcut
10495 var H = this._hash.words;
10496
10497 // Working variables
10498 var a = H[0];
10499 var b = H[1];
10500 var c = H[2];
10501 var d = H[3];
10502 var e = H[4];
10503 var f = H[5];
10504 var g = H[6];
10505 var h = H[7];
10506
10507 // Computation
10508 for (var i = 0; i < 64; i++) {
10509 if (i < 16) {
10510 W[i] = M[offset + i] | 0;
10511 } else {
10512 var gamma0x = W[i - 15];
10513 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
10514 ((gamma0x << 14) | (gamma0x >>> 18)) ^
10515 (gamma0x >>> 3);
10516
10517 var gamma1x = W[i - 2];
10518 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
10519 ((gamma1x << 13) | (gamma1x >>> 19)) ^
10520 (gamma1x >>> 10);
10521
10522 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
10523 }
10524
10525 var ch = (e & f) ^ (~e & g);
10526 var maj = (a & b) ^ (a & c) ^ (b & c);
10527
10528 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
10529 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
10530
10531 var t1 = h + sigma1 + ch + K[i] + W[i];
10532 var t2 = sigma0 + maj;
10533
10534 h = g;
10535 g = f;
10536 f = e;
10537 e = (d + t1) | 0;
10538 d = c;
10539 c = b;
10540 b = a;
10541 a = (t1 + t2) | 0;
10542 }
10543
10544 // Intermediate hash value
10545 H[0] = (H[0] + a) | 0;
10546 H[1] = (H[1] + b) | 0;
10547 H[2] = (H[2] + c) | 0;
10548 H[3] = (H[3] + d) | 0;
10549 H[4] = (H[4] + e) | 0;
10550 H[5] = (H[5] + f) | 0;
10551 H[6] = (H[6] + g) | 0;
10552 H[7] = (H[7] + h) | 0;
10553 },
10554
10555 _doFinalize: function () {
10556 // Shortcuts
10557 var data = this._data;
10558 var dataWords = data.words;
10559
10560 var nBitsTotal = this._nDataBytes * 8;
10561 var nBitsLeft = data.sigBytes * 8;
10562
10563 // Add padding
10564 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
10565 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
10566 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
10567 data.sigBytes = dataWords.length * 4;
10568
10569 // Hash final blocks
10570 this._process();
10571
10572 // Return final computed hash
10573 return this._hash;
10574 },
10575
10576 clone: function () {
10577 var clone = Hasher.clone.call(this);
10578 clone._hash = this._hash.clone();
10579
10580 return clone;
10581 }
10582 });
10583
10584 /**
10585 * Shortcut function to the hasher's object interface.
10586 *
10587 * @param {WordArray|string} message The message to hash.
10588 *
10589 * @return {WordArray} The hash.
10590 *
10591 * @static
10592 *
10593 * @example
10594 *
10595 * var hash = CryptoJS.SHA256('message');
10596 * var hash = CryptoJS.SHA256(wordArray);
10597 */
10598 C.SHA256 = Hasher._createHelper(SHA256);
10599
10600 /**
10601 * Shortcut function to the HMAC's object interface.
10602 *
10603 * @param {WordArray|string} message The message to hash.
10604 * @param {WordArray|string} key The secret key.
10605 *
10606 * @return {WordArray} The HMAC.
10607 *
10608 * @static
10609 *
10610 * @example
10611 *
10612 * var hmac = CryptoJS.HmacSHA256(message, key);
10613 */
10614 C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
10615 }(Math));
10616
10617
10618 return CryptoJS.SHA256;
10619
10620}));
10621
10622/***/ }),
10623
10624/***/ "./lib-esm/Auth.js":
10625/*!*************************!*\
10626 !*** ./lib-esm/Auth.js ***!
10627 \*************************/
10628/*! exports provided: AuthClass, Auth */
10629/***/ (function(module, __webpack_exports__, __webpack_require__) {
10630
10631"use strict";
10632__webpack_require__.r(__webpack_exports__);
10633/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthClass", function() { return AuthClass; });
10634/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Auth", function() { return Auth; });
10635/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types */ "./lib-esm/types/index.js");
10636/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
10637/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__);
10638/* harmony import */ var amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! amazon-cognito-identity-js */ "../amazon-cognito-identity-js/es/index.js");
10639/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! url */ "../../node_modules/url/url.js");
10640/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_3__);
10641/* harmony import */ var _OAuth_OAuth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./OAuth/OAuth */ "./lib-esm/OAuth/OAuth.js");
10642/* harmony import */ var _urlListener__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./urlListener */ "./lib-esm/urlListener.js");
10643/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Errors */ "./lib-esm/Errors.js");
10644/* harmony import */ var _types_Auth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types/Auth */ "./lib-esm/types/Auth.js");
10645function _typeof(obj) {
10646 "@babel/helpers - typeof";
10647
10648 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
10649 return typeof obj;
10650 } : function (obj) {
10651 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
10652 }, _typeof(obj);
10653}
10654/*
10655 * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
10656 *
10657 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
10658 * the License. A copy of the License is located at
10659 *
10660 * http://aws.amazon.com/apache2.0/
10661 *
10662 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
10663 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
10664 * and limitations under the License.
10665 */
10666
10667
10668var __assign = undefined && undefined.__assign || function () {
10669 __assign = Object.assign || function (t) {
10670 for (var s, i = 1, n = arguments.length; i < n; i++) {
10671 s = arguments[i];
10672
10673 for (var p in s) {
10674 if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
10675 }
10676 }
10677
10678 return t;
10679 };
10680
10681 return __assign.apply(this, arguments);
10682};
10683
10684var __awaiter = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) {
10685 function adopt(value) {
10686 return value instanceof P ? value : new P(function (resolve) {
10687 resolve(value);
10688 });
10689 }
10690
10691 return new (P || (P = Promise))(function (resolve, reject) {
10692 function fulfilled(value) {
10693 try {
10694 step(generator.next(value));
10695 } catch (e) {
10696 reject(e);
10697 }
10698 }
10699
10700 function rejected(value) {
10701 try {
10702 step(generator["throw"](value));
10703 } catch (e) {
10704 reject(e);
10705 }
10706 }
10707
10708 function step(result) {
10709 result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
10710 }
10711
10712 step((generator = generator.apply(thisArg, _arguments || [])).next());
10713 });
10714};
10715
10716var __generator = undefined && undefined.__generator || function (thisArg, body) {
10717 var _ = {
10718 label: 0,
10719 sent: function sent() {
10720 if (t[0] & 1) throw t[1];
10721 return t[1];
10722 },
10723 trys: [],
10724 ops: []
10725 },
10726 f,
10727 y,
10728 t,
10729 g;
10730 return g = {
10731 next: verb(0),
10732 "throw": verb(1),
10733 "return": verb(2)
10734 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
10735 return this;
10736 }), g;
10737
10738 function verb(n) {
10739 return function (v) {
10740 return step([n, v]);
10741 };
10742 }
10743
10744 function step(op) {
10745 if (f) throw new TypeError("Generator is already executing.");
10746
10747 while (_) {
10748 try {
10749 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
10750 if (y = 0, t) op = [op[0] & 2, t.value];
10751
10752 switch (op[0]) {
10753 case 0:
10754 case 1:
10755 t = op;
10756 break;
10757
10758 case 4:
10759 _.label++;
10760 return {
10761 value: op[1],
10762 done: false
10763 };
10764
10765 case 5:
10766 _.label++;
10767 y = op[1];
10768 op = [0];
10769 continue;
10770
10771 case 7:
10772 op = _.ops.pop();
10773
10774 _.trys.pop();
10775
10776 continue;
10777
10778 default:
10779 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
10780 _ = 0;
10781 continue;
10782 }
10783
10784 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
10785 _.label = op[1];
10786 break;
10787 }
10788
10789 if (op[0] === 6 && _.label < t[1]) {
10790 _.label = t[1];
10791 t = op;
10792 break;
10793 }
10794
10795 if (t && _.label < t[2]) {
10796 _.label = t[2];
10797
10798 _.ops.push(op);
10799
10800 break;
10801 }
10802
10803 if (t[2]) _.ops.pop();
10804
10805 _.trys.pop();
10806
10807 continue;
10808 }
10809
10810 op = body.call(thisArg, _);
10811 } catch (e) {
10812 op = [6, e];
10813 y = 0;
10814 } finally {
10815 f = t = 0;
10816 }
10817 }
10818
10819 if (op[0] & 5) throw op[1];
10820 return {
10821 value: op[0] ? op[1] : void 0,
10822 done: true
10823 };
10824 }
10825};
10826
10827var __read = undefined && undefined.__read || function (o, n) {
10828 var m = typeof Symbol === "function" && o[Symbol.iterator];
10829 if (!m) return o;
10830 var i = m.call(o),
10831 r,
10832 ar = [],
10833 e;
10834
10835 try {
10836 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
10837 ar.push(r.value);
10838 }
10839 } catch (error) {
10840 e = {
10841 error: error
10842 };
10843 } finally {
10844 try {
10845 if (r && !r.done && (m = i["return"])) m.call(i);
10846 } finally {
10847 if (e) throw e.error;
10848 }
10849 }
10850
10851 return ar;
10852};
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["ConsoleLogger"]('AuthClass');
10863var USER_ADMIN_SCOPE = 'aws.cognito.signin.user.admin'; // 10 sec, following this guide https://www.nngroup.com/articles/response-times-3-important-limits/
10864
10865var OAUTH_FLOW_MS_TIMEOUT = 10 * 1000;
10866var AMPLIFY_SYMBOL = typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function' ? Symbol["for"]('amplify_default') : '@@amplify_default';
10867
10868var dispatchAuthEvent = function dispatchAuthEvent(event, data, message) {
10869 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].dispatch('auth', {
10870 event: event,
10871 data: data,
10872 message: message
10873 }, 'Auth', AMPLIFY_SYMBOL);
10874}; // Cognito Documentation for max device
10875// tslint:disable-next-line:max-line-length
10876// https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html#API_ListDevices_RequestSyntax
10877
10878
10879var MAX_DEVICES = 60;
10880/**
10881 * Provide authentication steps
10882 */
10883
10884var AuthClass =
10885/** @class */
10886function () {
10887 /**
10888 * Initialize Auth with AWS configurations
10889 * @param {Object} config - Configuration of the Auth
10890 */
10891 function AuthClass(config) {
10892 var _this = this;
10893
10894 this.userPool = null;
10895 this.user = null;
10896 this.oAuthFlowInProgress = false;
10897 this.Credentials = _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Credentials"];
10898
10899 this.wrapRefreshSessionCallback = function (callback) {
10900 var wrapped = function wrapped(error, data) {
10901 if (data) {
10902 dispatchAuthEvent('tokenRefresh', undefined, "New token retrieved");
10903 } else {
10904 dispatchAuthEvent('tokenRefresh_failure', error, "Failed to retrieve new token");
10905 }
10906
10907 return callback(error, data);
10908 };
10909
10910 return wrapped;
10911 }; // prettier-ignore
10912
10913
10914 this.configure(config);
10915 this.currentCredentials = this.currentCredentials.bind(this);
10916 this.currentUserCredentials = this.currentUserCredentials.bind(this);
10917 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].listen('auth', function (_a) {
10918 var payload = _a.payload;
10919 var event = payload.event;
10920
10921 switch (event) {
10922 case 'signIn':
10923 _this._storage.setItem('amplify-signin-with-hostedUI', 'false');
10924
10925 break;
10926
10927 case 'signOut':
10928 _this._storage.removeItem('amplify-signin-with-hostedUI');
10929
10930 break;
10931
10932 case 'cognitoHostedUI':
10933 _this._storage.setItem('amplify-signin-with-hostedUI', 'true');
10934
10935 break;
10936 }
10937 });
10938 }
10939
10940 AuthClass.prototype.getModuleName = function () {
10941 return 'Auth';
10942 };
10943
10944 AuthClass.prototype.configure = function (config) {
10945 var _this = this;
10946
10947 if (!config) return this._config || {};
10948 logger.debug('configure Auth');
10949 var conf = Object.assign({}, this._config, _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Parser"].parseMobilehubConfig(config).Auth, config);
10950 this._config = conf;
10951 var _a = this._config,
10952 userPoolId = _a.userPoolId,
10953 userPoolWebClientId = _a.userPoolWebClientId,
10954 cookieStorage = _a.cookieStorage,
10955 oauth = _a.oauth,
10956 region = _a.region,
10957 identityPoolId = _a.identityPoolId,
10958 mandatorySignIn = _a.mandatorySignIn,
10959 refreshHandlers = _a.refreshHandlers,
10960 identityPoolRegion = _a.identityPoolRegion,
10961 clientMetadata = _a.clientMetadata,
10962 endpoint = _a.endpoint;
10963
10964 if (!this._config.storage) {
10965 // backward compatability
10966 if (cookieStorage) this._storage = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CookieStorage"](cookieStorage);else {
10967 this._storage = config.ssr ? new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["UniversalStorage"]() : new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["StorageHelper"]().getStorage();
10968 }
10969 } else {
10970 if (!this._isValidAuthStorage(this._config.storage)) {
10971 logger.error('The storage in the Auth config is not valid!');
10972 throw new Error('Empty storage object');
10973 }
10974
10975 this._storage = this._config.storage;
10976 }
10977
10978 this._storageSync = Promise.resolve();
10979
10980 if (typeof this._storage['sync'] === 'function') {
10981 this._storageSync = this._storage['sync']();
10982 }
10983
10984 if (userPoolId) {
10985 var userPoolData = {
10986 UserPoolId: userPoolId,
10987 ClientId: userPoolWebClientId,
10988 endpoint: endpoint
10989 };
10990 userPoolData.Storage = this._storage;
10991 this.userPool = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserPool"](userPoolData, this.wrapRefreshSessionCallback);
10992 }
10993
10994 this.Credentials.configure({
10995 mandatorySignIn: mandatorySignIn,
10996 region: identityPoolRegion || region,
10997 userPoolId: userPoolId,
10998 identityPoolId: identityPoolId,
10999 refreshHandlers: refreshHandlers,
11000 storage: this._storage
11001 }); // initialize cognitoauth client if hosted ui options provided
11002 // to keep backward compatibility:
11003
11004 var cognitoHostedUIConfig = oauth ? Object(_types__WEBPACK_IMPORTED_MODULE_0__["isCognitoHostedOpts"])(this._config.oauth) ? oauth : oauth.awsCognito : undefined;
11005
11006 if (cognitoHostedUIConfig) {
11007 var cognitoAuthParams = Object.assign({
11008 cognitoClientId: userPoolWebClientId,
11009 UserPoolId: userPoolId,
11010 domain: cognitoHostedUIConfig['domain'],
11011 scopes: cognitoHostedUIConfig['scope'],
11012 redirectSignIn: cognitoHostedUIConfig['redirectSignIn'],
11013 redirectSignOut: cognitoHostedUIConfig['redirectSignOut'],
11014 responseType: cognitoHostedUIConfig['responseType'],
11015 Storage: this._storage,
11016 urlOpener: cognitoHostedUIConfig['urlOpener'],
11017 clientMetadata: clientMetadata
11018 }, cognitoHostedUIConfig['options']);
11019 this._oAuthHandler = new _OAuth_OAuth__WEBPACK_IMPORTED_MODULE_4__["default"]({
11020 scopes: cognitoAuthParams.scopes,
11021 config: cognitoAuthParams,
11022 cognitoClientId: cognitoAuthParams.cognitoClientId
11023 }); // **NOTE** - Remove this in a future major release as it is a breaking change
11024 // Prevents _handleAuthResponse from being called multiple times in Expo
11025 // See https://github.com/aws-amplify/amplify-js/issues/4388
11026
11027 var usedResponseUrls_1 = {};
11028 Object(_urlListener__WEBPACK_IMPORTED_MODULE_5__["default"])(function (_a) {
11029 var url = _a.url;
11030
11031 if (usedResponseUrls_1[url]) {
11032 return;
11033 }
11034
11035 usedResponseUrls_1[url] = true;
11036
11037 _this._handleAuthResponse(url);
11038 });
11039 }
11040
11041 dispatchAuthEvent('configured', null, "The Auth category has been configured successfully");
11042 return this._config;
11043 };
11044 /**
11045 * Sign up with username, password and other attributes like phone, email
11046 * @param {String | object} params - The user attributes used for signin
11047 * @param {String[]} restOfAttrs - for the backward compatability
11048 * @return - A promise resolves callback data if success
11049 */
11050
11051
11052 AuthClass.prototype.signUp = function (params) {
11053 var _this = this;
11054
11055 var restOfAttrs = [];
11056
11057 for (var _i = 1; _i < arguments.length; _i++) {
11058 restOfAttrs[_i - 1] = arguments[_i];
11059 }
11060
11061 if (!this.userPool) {
11062 return this.rejectNoUserPool();
11063 }
11064
11065 var username = null;
11066 var password = null;
11067 var attributes = [];
11068 var validationData = null;
11069 var clientMetadata;
11070
11071 if (params && typeof params === 'string') {
11072 username = params;
11073 password = restOfAttrs ? restOfAttrs[0] : null;
11074 var email = restOfAttrs ? restOfAttrs[1] : null;
11075 var phone_number = restOfAttrs ? restOfAttrs[2] : null;
11076 if (email) attributes.push(new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"]({
11077 Name: 'email',
11078 Value: email
11079 }));
11080 if (phone_number) attributes.push(new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"]({
11081 Name: 'phone_number',
11082 Value: phone_number
11083 }));
11084 } else if (params && _typeof(params) === 'object') {
11085 username = params['username'];
11086 password = params['password'];
11087
11088 if (params && params.clientMetadata) {
11089 clientMetadata = params.clientMetadata;
11090 } else if (this._config.clientMetadata) {
11091 clientMetadata = this._config.clientMetadata;
11092 }
11093
11094 var attrs_1 = params['attributes'];
11095
11096 if (attrs_1) {
11097 Object.keys(attrs_1).map(function (key) {
11098 attributes.push(new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"]({
11099 Name: key,
11100 Value: attrs_1[key]
11101 }));
11102 });
11103 }
11104
11105 var validationDataObject_1 = params['validationData'];
11106
11107 if (validationDataObject_1) {
11108 validationData = [];
11109 Object.keys(validationDataObject_1).map(function (key) {
11110 validationData.push(new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"]({
11111 Name: key,
11112 Value: validationDataObject_1[key]
11113 }));
11114 });
11115 }
11116 } else {
11117 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].SignUpError);
11118 }
11119
11120 if (!username) {
11121 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
11122 }
11123
11124 if (!password) {
11125 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyPassword);
11126 }
11127
11128 logger.debug('signUp attrs:', attributes);
11129 logger.debug('signUp validation data:', validationData);
11130 return new Promise(function (resolve, reject) {
11131 _this.userPool.signUp(username, password, attributes, validationData, function (err, data) {
11132 if (err) {
11133 dispatchAuthEvent('signUp_failure', err, username + " failed to signup");
11134 reject(err);
11135 } else {
11136 dispatchAuthEvent('signUp', data, username + " has signed up successfully");
11137 resolve(data);
11138 }
11139 }, clientMetadata);
11140 });
11141 };
11142 /**
11143 * Send the verification code to confirm sign up
11144 * @param {String} username - The username to be confirmed
11145 * @param {String} code - The verification code
11146 * @param {ConfirmSignUpOptions} options - other options for confirm signup
11147 * @return - A promise resolves callback data if success
11148 */
11149
11150
11151 AuthClass.prototype.confirmSignUp = function (username, code, options) {
11152 if (!this.userPool) {
11153 return this.rejectNoUserPool();
11154 }
11155
11156 if (!username) {
11157 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
11158 }
11159
11160 if (!code) {
11161 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyCode);
11162 }
11163
11164 var user = this.createCognitoUser(username);
11165 var forceAliasCreation = options && typeof options.forceAliasCreation === 'boolean' ? options.forceAliasCreation : true;
11166 var clientMetadata;
11167
11168 if (options && options.clientMetadata) {
11169 clientMetadata = options.clientMetadata;
11170 } else if (this._config.clientMetadata) {
11171 clientMetadata = this._config.clientMetadata;
11172 }
11173
11174 return new Promise(function (resolve, reject) {
11175 user.confirmRegistration(code, forceAliasCreation, function (err, data) {
11176 if (err) {
11177 reject(err);
11178 } else {
11179 resolve(data);
11180 }
11181 }, clientMetadata);
11182 });
11183 };
11184 /**
11185 * Resend the verification code
11186 * @param {String} username - The username to be confirmed
11187 * @param {ClientMetadata} clientMetadata - Metadata to be passed to Cognito Lambda triggers
11188 * @return - A promise resolves code delivery details if successful
11189 */
11190
11191
11192 AuthClass.prototype.resendSignUp = function (username, clientMetadata) {
11193 if (clientMetadata === void 0) {
11194 clientMetadata = this._config.clientMetadata;
11195 }
11196
11197 if (!this.userPool) {
11198 return this.rejectNoUserPool();
11199 }
11200
11201 if (!username) {
11202 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
11203 }
11204
11205 var user = this.createCognitoUser(username);
11206 return new Promise(function (resolve, reject) {
11207 user.resendConfirmationCode(function (err, data) {
11208 if (err) {
11209 reject(err);
11210 } else {
11211 resolve(data);
11212 }
11213 }, clientMetadata);
11214 });
11215 };
11216 /**
11217 * Sign in
11218 * @param {String | SignInOpts} usernameOrSignInOpts - The username to be signed in or the sign in options
11219 * @param {String} password - The password of the username
11220 * @return - A promise resolves the CognitoUser
11221 */
11222
11223
11224 AuthClass.prototype.signIn = function (usernameOrSignInOpts, pw, clientMetadata) {
11225 if (clientMetadata === void 0) {
11226 clientMetadata = this._config.clientMetadata;
11227 }
11228
11229 if (!this.userPool) {
11230 return this.rejectNoUserPool();
11231 }
11232
11233 var username = null;
11234 var password = null;
11235 var validationData = {}; // for backward compatibility
11236
11237 if (typeof usernameOrSignInOpts === 'string') {
11238 username = usernameOrSignInOpts;
11239 password = pw;
11240 } else if (Object(_types__WEBPACK_IMPORTED_MODULE_0__["isUsernamePasswordOpts"])(usernameOrSignInOpts)) {
11241 if (typeof pw !== 'undefined') {
11242 logger.warn('The password should be defined under the first parameter object!');
11243 }
11244
11245 username = usernameOrSignInOpts.username;
11246 password = usernameOrSignInOpts.password;
11247 validationData = usernameOrSignInOpts.validationData;
11248 } else {
11249 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].InvalidUsername);
11250 }
11251
11252 if (!username) {
11253 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
11254 }
11255
11256 var authDetails = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["AuthenticationDetails"]({
11257 Username: username,
11258 Password: password,
11259 ValidationData: validationData,
11260 ClientMetadata: clientMetadata
11261 });
11262
11263 if (password) {
11264 return this.signInWithPassword(authDetails);
11265 } else {
11266 return this.signInWithoutPassword(authDetails);
11267 }
11268 };
11269 /**
11270 * Return an object with the authentication callbacks
11271 * @param {CognitoUser} user - the cognito user object
11272 * @param {} resolve - function called when resolving the current step
11273 * @param {} reject - function called when rejecting the current step
11274 * @return - an object with the callback methods for user authentication
11275 */
11276
11277
11278 AuthClass.prototype.authCallbacks = function (user, resolve, reject) {
11279 var _this = this;
11280
11281 var that = this;
11282 return {
11283 onSuccess: function onSuccess(session) {
11284 return __awaiter(_this, void 0, void 0, function () {
11285 var cred, e_1, currentUser, e_2;
11286 return __generator(this, function (_a) {
11287 switch (_a.label) {
11288 case 0:
11289 logger.debug(session);
11290 delete user['challengeName'];
11291 delete user['challengeParam'];
11292 _a.label = 1;
11293
11294 case 1:
11295 _a.trys.push([1, 4, 5, 9]);
11296
11297 return [4
11298 /*yield*/
11299 , this.Credentials.clear()];
11300
11301 case 2:
11302 _a.sent();
11303
11304 return [4
11305 /*yield*/
11306 , this.Credentials.set(session, 'session')];
11307
11308 case 3:
11309 cred = _a.sent();
11310 logger.debug('succeed to get cognito credentials', cred);
11311 return [3
11312 /*break*/
11313 , 9];
11314
11315 case 4:
11316 e_1 = _a.sent();
11317 logger.debug('cannot get cognito credentials', e_1);
11318 return [3
11319 /*break*/
11320 , 9];
11321
11322 case 5:
11323 _a.trys.push([5, 7,, 8]);
11324
11325 return [4
11326 /*yield*/
11327 , this.currentUserPoolUser()];
11328
11329 case 6:
11330 currentUser = _a.sent();
11331 that.user = currentUser;
11332 dispatchAuthEvent('signIn', currentUser, "A user " + user.getUsername() + " has been signed in");
11333 resolve(currentUser);
11334 return [3
11335 /*break*/
11336 , 8];
11337
11338 case 7:
11339 e_2 = _a.sent();
11340 logger.error('Failed to get the signed in user', e_2);
11341 reject(e_2);
11342 return [3
11343 /*break*/
11344 , 8];
11345
11346 case 8:
11347 return [7
11348 /*endfinally*/
11349 ];
11350
11351 case 9:
11352 return [2
11353 /*return*/
11354 ];
11355 }
11356 });
11357 });
11358 },
11359 onFailure: function onFailure(err) {
11360 logger.debug('signIn failure', err);
11361 dispatchAuthEvent('signIn_failure', err, user.getUsername() + " failed to signin");
11362 reject(err);
11363 },
11364 customChallenge: function customChallenge(challengeParam) {
11365 logger.debug('signIn custom challenge answer required');
11366 user['challengeName'] = 'CUSTOM_CHALLENGE';
11367 user['challengeParam'] = challengeParam;
11368 resolve(user);
11369 },
11370 mfaRequired: function mfaRequired(challengeName, challengeParam) {
11371 logger.debug('signIn MFA required');
11372 user['challengeName'] = challengeName;
11373 user['challengeParam'] = challengeParam;
11374 resolve(user);
11375 },
11376 mfaSetup: function mfaSetup(challengeName, challengeParam) {
11377 logger.debug('signIn mfa setup', challengeName);
11378 user['challengeName'] = challengeName;
11379 user['challengeParam'] = challengeParam;
11380 resolve(user);
11381 },
11382 newPasswordRequired: function newPasswordRequired(userAttributes, requiredAttributes) {
11383 logger.debug('signIn new password');
11384 user['challengeName'] = 'NEW_PASSWORD_REQUIRED';
11385 user['challengeParam'] = {
11386 userAttributes: userAttributes,
11387 requiredAttributes: requiredAttributes
11388 };
11389 resolve(user);
11390 },
11391 totpRequired: function totpRequired(challengeName, challengeParam) {
11392 logger.debug('signIn totpRequired');
11393 user['challengeName'] = challengeName;
11394 user['challengeParam'] = challengeParam;
11395 resolve(user);
11396 },
11397 selectMFAType: function selectMFAType(challengeName, challengeParam) {
11398 logger.debug('signIn selectMFAType', challengeName);
11399 user['challengeName'] = challengeName;
11400 user['challengeParam'] = challengeParam;
11401 resolve(user);
11402 }
11403 };
11404 };
11405 /**
11406 * Sign in with a password
11407 * @private
11408 * @param {AuthenticationDetails} authDetails - the user sign in data
11409 * @return - A promise resolves the CognitoUser object if success or mfa required
11410 */
11411
11412
11413 AuthClass.prototype.signInWithPassword = function (authDetails) {
11414 var _this = this;
11415
11416 if (this.pendingSignIn) {
11417 throw new Error('Pending sign-in attempt already in progress');
11418 }
11419
11420 var user = this.createCognitoUser(authDetails.getUsername());
11421 this.pendingSignIn = new Promise(function (resolve, reject) {
11422 user.authenticateUser(authDetails, _this.authCallbacks(user, function (value) {
11423 _this.pendingSignIn = null;
11424 resolve(value);
11425 }, function (error) {
11426 _this.pendingSignIn = null;
11427 reject(error);
11428 }));
11429 });
11430 return this.pendingSignIn;
11431 };
11432 /**
11433 * Sign in without a password
11434 * @private
11435 * @param {AuthenticationDetails} authDetails - the user sign in data
11436 * @return - A promise resolves the CognitoUser object if success or mfa required
11437 */
11438
11439
11440 AuthClass.prototype.signInWithoutPassword = function (authDetails) {
11441 var _this = this;
11442
11443 var user = this.createCognitoUser(authDetails.getUsername());
11444 user.setAuthenticationFlowType('CUSTOM_AUTH');
11445 return new Promise(function (resolve, reject) {
11446 user.initiateAuth(authDetails, _this.authCallbacks(user, resolve, reject));
11447 });
11448 };
11449 /**
11450 * This was previously used by an authenticated user to get MFAOptions,
11451 * but no longer returns a meaningful response. Refer to the documentation for
11452 * how to setup and use MFA: https://docs.amplify.aws/lib/auth/mfa/q/platform/js
11453 * @deprecated
11454 * @param {CognitoUser} user - the current user
11455 * @return - A promise resolves the current preferred mfa option if success
11456 */
11457
11458
11459 AuthClass.prototype.getMFAOptions = function (user) {
11460 return new Promise(function (res, rej) {
11461 user.getMFAOptions(function (err, mfaOptions) {
11462 if (err) {
11463 logger.debug('get MFA Options failed', err);
11464 rej(err);
11465 return;
11466 }
11467
11468 logger.debug('get MFA options success', mfaOptions);
11469 res(mfaOptions);
11470 return;
11471 });
11472 });
11473 };
11474 /**
11475 * get preferred mfa method
11476 * @param {CognitoUser} user - the current cognito user
11477 * @param {GetPreferredMFAOpts} params - options for getting the current user preferred MFA
11478 */
11479
11480
11481 AuthClass.prototype.getPreferredMFA = function (user, params) {
11482 var _this = this;
11483
11484 var that = this;
11485 return new Promise(function (res, rej) {
11486 var clientMetadata = _this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
11487
11488 var bypassCache = params ? params.bypassCache : false;
11489 user.getUserData(function (err, data) {
11490 if (err) {
11491 logger.debug('getting preferred mfa failed', err);
11492 rej(err);
11493 return;
11494 }
11495
11496 var mfaType = that._getMfaTypeFromUserData(data);
11497
11498 if (!mfaType) {
11499 rej('invalid MFA Type');
11500 return;
11501 } else {
11502 res(mfaType);
11503 return;
11504 }
11505 }, {
11506 bypassCache: bypassCache,
11507 clientMetadata: clientMetadata
11508 });
11509 });
11510 };
11511
11512 AuthClass.prototype._getMfaTypeFromUserData = function (data) {
11513 var ret = null;
11514 var preferredMFA = data.PreferredMfaSetting; // if the user has used Auth.setPreferredMFA() to setup the mfa type
11515 // then the "PreferredMfaSetting" would exist in the response
11516
11517 if (preferredMFA) {
11518 ret = preferredMFA;
11519 } else {
11520 // if mfaList exists but empty, then its noMFA
11521 var mfaList = data.UserMFASettingList;
11522
11523 if (!mfaList) {
11524 // if SMS was enabled by using Auth.enableSMS(),
11525 // the response would contain MFAOptions
11526 // as for now Cognito only supports for SMS, so we will say it is 'SMS_MFA'
11527 // if it does not exist, then it should be NOMFA
11528 var MFAOptions = data.MFAOptions;
11529
11530 if (MFAOptions) {
11531 ret = 'SMS_MFA';
11532 } else {
11533 ret = 'NOMFA';
11534 }
11535 } else if (mfaList.length === 0) {
11536 ret = 'NOMFA';
11537 } else {
11538 logger.debug('invalid case for getPreferredMFA', data);
11539 }
11540 }
11541
11542 return ret;
11543 };
11544
11545 AuthClass.prototype._getUserData = function (user, params) {
11546 return new Promise(function (res, rej) {
11547 user.getUserData(function (err, data) {
11548 if (err) {
11549 logger.debug('getting user data failed', err);
11550 rej(err);
11551 return;
11552 } else {
11553 res(data);
11554 return;
11555 }
11556 }, params);
11557 });
11558 };
11559 /**
11560 * set preferred MFA method
11561 * @param {CognitoUser} user - the current Cognito user
11562 * @param {string} mfaMethod - preferred mfa method
11563 * @return - A promise resolve if success
11564 */
11565
11566
11567 AuthClass.prototype.setPreferredMFA = function (user, mfaMethod) {
11568 return __awaiter(this, void 0, void 0, function () {
11569 var clientMetadata, userData, smsMfaSettings, totpMfaSettings, _a, mfaList, currentMFAType, that;
11570
11571 return __generator(this, function (_b) {
11572 switch (_b.label) {
11573 case 0:
11574 clientMetadata = this._config.clientMetadata;
11575 return [4
11576 /*yield*/
11577 , this._getUserData(user, {
11578 bypassCache: true,
11579 clientMetadata: clientMetadata
11580 })];
11581
11582 case 1:
11583 userData = _b.sent();
11584 smsMfaSettings = null;
11585 totpMfaSettings = null;
11586 _a = mfaMethod;
11587
11588 switch (_a) {
11589 case 'TOTP':
11590 return [3
11591 /*break*/
11592 , 2];
11593
11594 case 'SOFTWARE_TOKEN_MFA':
11595 return [3
11596 /*break*/
11597 , 2];
11598
11599 case 'SMS':
11600 return [3
11601 /*break*/
11602 , 3];
11603
11604 case 'SMS_MFA':
11605 return [3
11606 /*break*/
11607 , 3];
11608
11609 case 'NOMFA':
11610 return [3
11611 /*break*/
11612 , 4];
11613 }
11614
11615 return [3
11616 /*break*/
11617 , 6];
11618
11619 case 2:
11620 totpMfaSettings = {
11621 PreferredMfa: true,
11622 Enabled: true
11623 };
11624 return [3
11625 /*break*/
11626 , 7];
11627
11628 case 3:
11629 smsMfaSettings = {
11630 PreferredMfa: true,
11631 Enabled: true
11632 };
11633 return [3
11634 /*break*/
11635 , 7];
11636
11637 case 4:
11638 mfaList = userData['UserMFASettingList'];
11639 return [4
11640 /*yield*/
11641 , this._getMfaTypeFromUserData(userData)];
11642
11643 case 5:
11644 currentMFAType = _b.sent();
11645
11646 if (currentMFAType === 'NOMFA') {
11647 return [2
11648 /*return*/
11649 , Promise.resolve('No change for mfa type')];
11650 } else if (currentMFAType === 'SMS_MFA') {
11651 smsMfaSettings = {
11652 PreferredMfa: false,
11653 Enabled: false
11654 };
11655 } else if (currentMFAType === 'SOFTWARE_TOKEN_MFA') {
11656 totpMfaSettings = {
11657 PreferredMfa: false,
11658 Enabled: false
11659 };
11660 } else {
11661 return [2
11662 /*return*/
11663 , this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].InvalidMFA)];
11664 } // if there is a UserMFASettingList in the response
11665 // we need to disable every mfa type in that list
11666
11667
11668 if (mfaList && mfaList.length !== 0) {
11669 // to disable SMS or TOTP if exists in that list
11670 mfaList.forEach(function (mfaType) {
11671 if (mfaType === 'SMS_MFA') {
11672 smsMfaSettings = {
11673 PreferredMfa: false,
11674 Enabled: false
11675 };
11676 } else if (mfaType === 'SOFTWARE_TOKEN_MFA') {
11677 totpMfaSettings = {
11678 PreferredMfa: false,
11679 Enabled: false
11680 };
11681 }
11682 });
11683 }
11684
11685 return [3
11686 /*break*/
11687 , 7];
11688
11689 case 6:
11690 logger.debug('no validmfa method provided');
11691 return [2
11692 /*return*/
11693 , this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NoMFA)];
11694
11695 case 7:
11696 that = this;
11697 return [2
11698 /*return*/
11699 , new Promise(function (res, rej) {
11700 user.setUserMfaPreference(smsMfaSettings, totpMfaSettings, function (err, result) {
11701 if (err) {
11702 logger.debug('Set user mfa preference error', err);
11703 return rej(err);
11704 }
11705
11706 logger.debug('Set user mfa success', result);
11707 logger.debug('Caching the latest user data into local'); // cache the latest result into user data
11708
11709 user.getUserData(function (err, data) {
11710 if (err) {
11711 logger.debug('getting user data failed', err);
11712 return rej(err);
11713 } else {
11714 return res(result);
11715 }
11716 }, {
11717 bypassCache: true,
11718 clientMetadata: clientMetadata
11719 });
11720 });
11721 })];
11722 }
11723 });
11724 });
11725 };
11726 /**
11727 * disable SMS
11728 * @deprecated
11729 * @param {CognitoUser} user - the current user
11730 * @return - A promise resolves is success
11731 */
11732
11733
11734 AuthClass.prototype.disableSMS = function (user) {
11735 return new Promise(function (res, rej) {
11736 user.disableMFA(function (err, data) {
11737 if (err) {
11738 logger.debug('disable mfa failed', err);
11739 rej(err);
11740 return;
11741 }
11742
11743 logger.debug('disable mfa succeed', data);
11744 res(data);
11745 return;
11746 });
11747 });
11748 };
11749 /**
11750 * enable SMS
11751 * @deprecated
11752 * @param {CognitoUser} user - the current user
11753 * @return - A promise resolves is success
11754 */
11755
11756
11757 AuthClass.prototype.enableSMS = function (user) {
11758 return new Promise(function (res, rej) {
11759 user.enableMFA(function (err, data) {
11760 if (err) {
11761 logger.debug('enable mfa failed', err);
11762 rej(err);
11763 return;
11764 }
11765
11766 logger.debug('enable mfa succeed', data);
11767 res(data);
11768 return;
11769 });
11770 });
11771 };
11772 /**
11773 * Setup TOTP
11774 * @param {CognitoUser} user - the current user
11775 * @return - A promise resolves with the secret code if success
11776 */
11777
11778
11779 AuthClass.prototype.setupTOTP = function (user) {
11780 return new Promise(function (res, rej) {
11781 user.associateSoftwareToken({
11782 onFailure: function onFailure(err) {
11783 logger.debug('associateSoftwareToken failed', err);
11784 rej(err);
11785 return;
11786 },
11787 associateSecretCode: function associateSecretCode(secretCode) {
11788 logger.debug('associateSoftwareToken sucess', secretCode);
11789 res(secretCode);
11790 return;
11791 }
11792 });
11793 });
11794 };
11795 /**
11796 * verify TOTP setup
11797 * @param {CognitoUser} user - the current user
11798 * @param {string} challengeAnswer - challenge answer
11799 * @return - A promise resolves is success
11800 */
11801
11802
11803 AuthClass.prototype.verifyTotpToken = function (user, challengeAnswer) {
11804 logger.debug('verification totp token', user, challengeAnswer);
11805 return new Promise(function (res, rej) {
11806 user.verifySoftwareToken(challengeAnswer, 'My TOTP device', {
11807 onFailure: function onFailure(err) {
11808 logger.debug('verifyTotpToken failed', err);
11809 rej(err);
11810 return;
11811 },
11812 onSuccess: function onSuccess(data) {
11813 dispatchAuthEvent('signIn', user, "A user " + user.getUsername() + " has been signed in");
11814 logger.debug('verifyTotpToken success', data);
11815 res(data);
11816 return;
11817 }
11818 });
11819 });
11820 };
11821 /**
11822 * Send MFA code to confirm sign in
11823 * @param {Object} user - The CognitoUser object
11824 * @param {String} code - The confirmation code
11825 */
11826
11827
11828 AuthClass.prototype.confirmSignIn = function (user, code, mfaType, clientMetadata) {
11829 var _this = this;
11830
11831 if (clientMetadata === void 0) {
11832 clientMetadata = this._config.clientMetadata;
11833 }
11834
11835 if (!code) {
11836 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyCode);
11837 }
11838
11839 var that = this;
11840 return new Promise(function (resolve, reject) {
11841 user.sendMFACode(code, {
11842 onSuccess: function onSuccess(session) {
11843 return __awaiter(_this, void 0, void 0, function () {
11844 var cred, e_3;
11845 return __generator(this, function (_a) {
11846 switch (_a.label) {
11847 case 0:
11848 logger.debug(session);
11849 _a.label = 1;
11850
11851 case 1:
11852 _a.trys.push([1, 4, 5, 6]);
11853
11854 return [4
11855 /*yield*/
11856 , this.Credentials.clear()];
11857
11858 case 2:
11859 _a.sent();
11860
11861 return [4
11862 /*yield*/
11863 , this.Credentials.set(session, 'session')];
11864
11865 case 3:
11866 cred = _a.sent();
11867 logger.debug('succeed to get cognito credentials', cred);
11868 return [3
11869 /*break*/
11870 , 6];
11871
11872 case 4:
11873 e_3 = _a.sent();
11874 logger.debug('cannot get cognito credentials', e_3);
11875 return [3
11876 /*break*/
11877 , 6];
11878
11879 case 5:
11880 that.user = user;
11881 dispatchAuthEvent('signIn', user, "A user " + user.getUsername() + " has been signed in");
11882 resolve(user);
11883 return [7
11884 /*endfinally*/
11885 ];
11886
11887 case 6:
11888 return [2
11889 /*return*/
11890 ];
11891 }
11892 });
11893 });
11894 },
11895 onFailure: function onFailure(err) {
11896 logger.debug('confirm signIn failure', err);
11897 reject(err);
11898 }
11899 }, mfaType, clientMetadata);
11900 });
11901 };
11902
11903 AuthClass.prototype.completeNewPassword = function (user, password, requiredAttributes, clientMetadata) {
11904 var _this = this;
11905
11906 if (requiredAttributes === void 0) {
11907 requiredAttributes = {};
11908 }
11909
11910 if (clientMetadata === void 0) {
11911 clientMetadata = this._config.clientMetadata;
11912 }
11913
11914 if (!password) {
11915 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyPassword);
11916 }
11917
11918 var that = this;
11919 return new Promise(function (resolve, reject) {
11920 user.completeNewPasswordChallenge(password, requiredAttributes, {
11921 onSuccess: function onSuccess(session) {
11922 return __awaiter(_this, void 0, void 0, function () {
11923 var cred, e_4;
11924 return __generator(this, function (_a) {
11925 switch (_a.label) {
11926 case 0:
11927 logger.debug(session);
11928 _a.label = 1;
11929
11930 case 1:
11931 _a.trys.push([1, 4, 5, 6]);
11932
11933 return [4
11934 /*yield*/
11935 , this.Credentials.clear()];
11936
11937 case 2:
11938 _a.sent();
11939
11940 return [4
11941 /*yield*/
11942 , this.Credentials.set(session, 'session')];
11943
11944 case 3:
11945 cred = _a.sent();
11946 logger.debug('succeed to get cognito credentials', cred);
11947 return [3
11948 /*break*/
11949 , 6];
11950
11951 case 4:
11952 e_4 = _a.sent();
11953 logger.debug('cannot get cognito credentials', e_4);
11954 return [3
11955 /*break*/
11956 , 6];
11957
11958 case 5:
11959 that.user = user;
11960 dispatchAuthEvent('signIn', user, "A user " + user.getUsername() + " has been signed in");
11961 resolve(user);
11962 return [7
11963 /*endfinally*/
11964 ];
11965
11966 case 6:
11967 return [2
11968 /*return*/
11969 ];
11970 }
11971 });
11972 });
11973 },
11974 onFailure: function onFailure(err) {
11975 logger.debug('completeNewPassword failure', err);
11976 dispatchAuthEvent('completeNewPassword_failure', err, _this.user + " failed to complete the new password flow");
11977 reject(err);
11978 },
11979 mfaRequired: function mfaRequired(challengeName, challengeParam) {
11980 logger.debug('signIn MFA required');
11981 user['challengeName'] = challengeName;
11982 user['challengeParam'] = challengeParam;
11983 resolve(user);
11984 },
11985 mfaSetup: function mfaSetup(challengeName, challengeParam) {
11986 logger.debug('signIn mfa setup', challengeName);
11987 user['challengeName'] = challengeName;
11988 user['challengeParam'] = challengeParam;
11989 resolve(user);
11990 },
11991 totpRequired: function totpRequired(challengeName, challengeParam) {
11992 logger.debug('signIn mfa setup', challengeName);
11993 user['challengeName'] = challengeName;
11994 user['challengeParam'] = challengeParam;
11995 resolve(user);
11996 }
11997 }, clientMetadata);
11998 });
11999 };
12000 /**
12001 * Send the answer to a custom challenge
12002 * @param {CognitoUser} user - The CognitoUser object
12003 * @param {String} challengeResponses - The confirmation code
12004 */
12005
12006
12007 AuthClass.prototype.sendCustomChallengeAnswer = function (user, challengeResponses, clientMetadata) {
12008 var _this = this;
12009
12010 if (clientMetadata === void 0) {
12011 clientMetadata = this._config.clientMetadata;
12012 }
12013
12014 if (!this.userPool) {
12015 return this.rejectNoUserPool();
12016 }
12017
12018 if (!challengeResponses) {
12019 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyChallengeResponse);
12020 }
12021
12022 var that = this;
12023 return new Promise(function (resolve, reject) {
12024 user.sendCustomChallengeAnswer(challengeResponses, _this.authCallbacks(user, resolve, reject), clientMetadata);
12025 });
12026 };
12027 /**
12028 * Delete an authenticated users' attributes
12029 * @param {CognitoUser} - The currently logged in user object
12030 * @return {Promise}
12031 **/
12032
12033
12034 AuthClass.prototype.deleteUserAttributes = function (user, attributeNames) {
12035 var that = this;
12036 return new Promise(function (resolve, reject) {
12037 that.userSession(user).then(function (session) {
12038 user.deleteAttributes(attributeNames, function (err, result) {
12039 if (err) {
12040 return reject(err);
12041 } else {
12042 return resolve(result);
12043 }
12044 });
12045 });
12046 });
12047 };
12048 /**
12049 * Update an authenticated users' attributes
12050 * @param {CognitoUser} - The currently logged in user object
12051 * @return {Promise}
12052 **/
12053
12054
12055 AuthClass.prototype.updateUserAttributes = function (user, attributes, clientMetadata) {
12056 if (clientMetadata === void 0) {
12057 clientMetadata = this._config.clientMetadata;
12058 }
12059
12060 var attributeList = [];
12061 var that = this;
12062 return new Promise(function (resolve, reject) {
12063 that.userSession(user).then(function (session) {
12064 for (var key in attributes) {
12065 if (key !== 'sub' && key.indexOf('_verified') < 0) {
12066 var attr = {
12067 Name: key,
12068 Value: attributes[key]
12069 };
12070 attributeList.push(attr);
12071 }
12072 }
12073
12074 user.updateAttributes(attributeList, function (err, result) {
12075 if (err) {
12076 return reject(err);
12077 } else {
12078 return resolve(result);
12079 }
12080 }, clientMetadata);
12081 });
12082 });
12083 };
12084 /**
12085 * Return user attributes
12086 * @param {Object} user - The CognitoUser object
12087 * @return - A promise resolves to user attributes if success
12088 */
12089
12090
12091 AuthClass.prototype.userAttributes = function (user) {
12092 var _this = this;
12093
12094 return new Promise(function (resolve, reject) {
12095 _this.userSession(user).then(function (session) {
12096 user.getUserAttributes(function (err, attributes) {
12097 if (err) {
12098 reject(err);
12099 } else {
12100 resolve(attributes);
12101 }
12102 });
12103 });
12104 });
12105 };
12106
12107 AuthClass.prototype.verifiedContact = function (user) {
12108 var that = this;
12109 return this.userAttributes(user).then(function (attributes) {
12110 var attrs = that.attributesToObject(attributes);
12111 var unverified = {};
12112 var verified = {};
12113
12114 if (attrs['email']) {
12115 if (attrs['email_verified']) {
12116 verified['email'] = attrs['email'];
12117 } else {
12118 unverified['email'] = attrs['email'];
12119 }
12120 }
12121
12122 if (attrs['phone_number']) {
12123 if (attrs['phone_number_verified']) {
12124 verified['phone_number'] = attrs['phone_number'];
12125 } else {
12126 unverified['phone_number'] = attrs['phone_number'];
12127 }
12128 }
12129
12130 return {
12131 verified: verified,
12132 unverified: unverified
12133 };
12134 });
12135 };
12136 /**
12137 * Get current authenticated user
12138 * @return - A promise resolves to current authenticated CognitoUser if success
12139 */
12140
12141
12142 AuthClass.prototype.currentUserPoolUser = function (params) {
12143 var _this = this;
12144
12145 if (!this.userPool) {
12146 return this.rejectNoUserPool();
12147 }
12148
12149 return new Promise(function (res, rej) {
12150 _this._storageSync.then(function () {
12151 return __awaiter(_this, void 0, void 0, function () {
12152 var user, clientMetadata;
12153
12154 var _this = this;
12155
12156 return __generator(this, function (_a) {
12157 switch (_a.label) {
12158 case 0:
12159 if (!this.isOAuthInProgress()) return [3
12160 /*break*/
12161 , 2];
12162 logger.debug('OAuth signIn in progress, waiting for resolution...');
12163 return [4
12164 /*yield*/
12165 , new Promise(function (res) {
12166 var timeoutId = setTimeout(function () {
12167 logger.debug('OAuth signIn in progress timeout');
12168 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].remove('auth', hostedUISignCallback);
12169 res();
12170 }, OAUTH_FLOW_MS_TIMEOUT);
12171 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].listen('auth', hostedUISignCallback);
12172
12173 function hostedUISignCallback(_a) {
12174 var payload = _a.payload;
12175 var event = payload.event;
12176
12177 if (event === 'cognitoHostedUI' || event === 'cognitoHostedUI_failure') {
12178 logger.debug("OAuth signIn resolved: " + event);
12179 clearTimeout(timeoutId);
12180 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].remove('auth', hostedUISignCallback);
12181 res();
12182 }
12183 }
12184 })];
12185
12186 case 1:
12187 _a.sent();
12188
12189 _a.label = 2;
12190
12191 case 2:
12192 user = this.userPool.getCurrentUser();
12193
12194 if (!user) {
12195 logger.debug('Failed to get user from user pool');
12196 rej('No current user');
12197 return [2
12198 /*return*/
12199 ];
12200 }
12201
12202 clientMetadata = this._config.clientMetadata; // refresh the session if the session expired.
12203
12204 user.getSession(function (err, session) {
12205 return __awaiter(_this, void 0, void 0, function () {
12206 var bypassCache, clientMetadata, _a, scope;
12207
12208 var _this = this;
12209
12210 return __generator(this, function (_b) {
12211 switch (_b.label) {
12212 case 0:
12213 if (err) {
12214 logger.debug('Failed to get the user session', err);
12215 rej(err);
12216 return [2
12217 /*return*/
12218 ];
12219 }
12220
12221 bypassCache = params ? params.bypassCache : false;
12222 if (!bypassCache) return [3
12223 /*break*/
12224 , 2];
12225 return [4
12226 /*yield*/
12227 , this.Credentials.clear()];
12228
12229 case 1:
12230 _b.sent();
12231
12232 _b.label = 2;
12233
12234 case 2:
12235 clientMetadata = this._config.clientMetadata;
12236 _a = session.getAccessToken().decodePayload().scope, scope = _a === void 0 ? '' : _a;
12237
12238 if (scope.split(' ').includes(USER_ADMIN_SCOPE)) {
12239 user.getUserData(function (err, data) {
12240 if (err) {
12241 logger.debug('getting user data failed', err); // Make sure the user is still valid
12242
12243 if (err.message === 'User is disabled.' || err.message === 'User does not exist.' || err.message === 'Access Token has been revoked' // Session revoked by another app
12244 ) {
12245 rej(err);
12246 } else {
12247 // the error may also be thrown when lack of permissions to get user info etc
12248 // in that case we just bypass the error
12249 res(user);
12250 }
12251
12252 return;
12253 }
12254
12255 var preferredMFA = data.PreferredMfaSetting || 'NOMFA';
12256 var attributeList = [];
12257
12258 for (var i = 0; i < data.UserAttributes.length; i++) {
12259 var attribute = {
12260 Name: data.UserAttributes[i].Name,
12261 Value: data.UserAttributes[i].Value
12262 };
12263 var userAttribute = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"](attribute);
12264 attributeList.push(userAttribute);
12265 }
12266
12267 var attributes = _this.attributesToObject(attributeList);
12268
12269 Object.assign(user, {
12270 attributes: attributes,
12271 preferredMFA: preferredMFA
12272 });
12273 return res(user);
12274 }, {
12275 bypassCache: bypassCache,
12276 clientMetadata: clientMetadata
12277 });
12278 } else {
12279 logger.debug("Unable to get the user data because the " + USER_ADMIN_SCOPE + " " + "is not in the scopes of the access token");
12280 return [2
12281 /*return*/
12282 , res(user)];
12283 }
12284
12285 return [2
12286 /*return*/
12287 ];
12288 }
12289 });
12290 });
12291 }, {
12292 clientMetadata: clientMetadata
12293 });
12294 return [2
12295 /*return*/
12296 ];
12297 }
12298 });
12299 });
12300 })["catch"](function (e) {
12301 logger.debug('Failed to sync cache info into memory', e);
12302 return rej(e);
12303 });
12304 });
12305 };
12306
12307 AuthClass.prototype.isOAuthInProgress = function () {
12308 return this.oAuthFlowInProgress;
12309 };
12310 /**
12311 * Get current authenticated user
12312 * @param {CurrentUserOpts} - options for getting the current user
12313 * @return - A promise resolves to current authenticated CognitoUser if success
12314 */
12315
12316
12317 AuthClass.prototype.currentAuthenticatedUser = function (params) {
12318 return __awaiter(this, void 0, void 0, function () {
12319 var federatedUser, e_5, federatedInfo, user, e_6;
12320 return __generator(this, function (_a) {
12321 switch (_a.label) {
12322 case 0:
12323 logger.debug('getting current authenticated user');
12324 federatedUser = null;
12325 _a.label = 1;
12326
12327 case 1:
12328 _a.trys.push([1, 3,, 4]);
12329
12330 return [4
12331 /*yield*/
12332 , this._storageSync];
12333
12334 case 2:
12335 _a.sent();
12336
12337 return [3
12338 /*break*/
12339 , 4];
12340
12341 case 3:
12342 e_5 = _a.sent();
12343 logger.debug('Failed to sync cache info into memory', e_5);
12344 throw e_5;
12345
12346 case 4:
12347 try {
12348 federatedInfo = JSON.parse(this._storage.getItem('aws-amplify-federatedInfo'));
12349
12350 if (federatedInfo) {
12351 federatedUser = __assign(__assign({}, federatedInfo.user), {
12352 token: federatedInfo.token
12353 });
12354 }
12355 } catch (e) {
12356 logger.debug('cannot load federated user from auth storage');
12357 }
12358
12359 if (!federatedUser) return [3
12360 /*break*/
12361 , 5];
12362 this.user = federatedUser;
12363 logger.debug('get current authenticated federated user', this.user);
12364 return [2
12365 /*return*/
12366 , this.user];
12367
12368 case 5:
12369 logger.debug('get current authenticated userpool user');
12370 user = null;
12371 _a.label = 6;
12372
12373 case 6:
12374 _a.trys.push([6, 8,, 9]);
12375
12376 return [4
12377 /*yield*/
12378 , this.currentUserPoolUser(params)];
12379
12380 case 7:
12381 user = _a.sent();
12382 return [3
12383 /*break*/
12384 , 9];
12385
12386 case 8:
12387 e_6 = _a.sent();
12388
12389 if (e_6 === 'No userPool') {
12390 logger.error('Cannot get the current user because the user pool is missing. ' + 'Please make sure the Auth module is configured with a valid Cognito User Pool ID');
12391 }
12392
12393 logger.debug('The user is not authenticated by the error', e_6);
12394 return [2
12395 /*return*/
12396 , Promise.reject('The user is not authenticated')];
12397
12398 case 9:
12399 this.user = user;
12400 return [2
12401 /*return*/
12402 , this.user];
12403 }
12404 });
12405 });
12406 };
12407 /**
12408 * Get current user's session
12409 * @return - A promise resolves to session object if success
12410 */
12411
12412
12413 AuthClass.prototype.currentSession = function () {
12414 var that = this;
12415 logger.debug('Getting current session'); // Purposely not calling the reject method here because we don't need a console error
12416
12417 if (!this.userPool) {
12418 return Promise.reject();
12419 }
12420
12421 return new Promise(function (res, rej) {
12422 that.currentUserPoolUser().then(function (user) {
12423 that.userSession(user).then(function (session) {
12424 res(session);
12425 return;
12426 })["catch"](function (e) {
12427 logger.debug('Failed to get the current session', e);
12428 rej(e);
12429 return;
12430 });
12431 })["catch"](function (e) {
12432 logger.debug('Failed to get the current user', e);
12433 rej(e);
12434 return;
12435 });
12436 });
12437 };
12438 /**
12439 * Get the corresponding user session
12440 * @param {Object} user - The CognitoUser object
12441 * @return - A promise resolves to the session
12442 */
12443
12444
12445 AuthClass.prototype.userSession = function (user) {
12446 if (!user) {
12447 logger.debug('the user is null');
12448 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NoUserSession);
12449 }
12450
12451 var clientMetadata = this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
12452
12453 return new Promise(function (resolve, reject) {
12454 logger.debug('Getting the session from this user:', user);
12455 user.getSession(function (err, session) {
12456 if (err) {
12457 logger.debug('Failed to get the session from user', user);
12458 reject(err);
12459 return;
12460 } else {
12461 logger.debug('Succeed to get the user session', session);
12462 resolve(session);
12463 return;
12464 }
12465 }, {
12466 clientMetadata: clientMetadata
12467 });
12468 });
12469 };
12470 /**
12471 * Get authenticated credentials of current user.
12472 * @return - A promise resolves to be current user's credentials
12473 */
12474
12475
12476 AuthClass.prototype.currentUserCredentials = function () {
12477 return __awaiter(this, void 0, void 0, function () {
12478 var e_7, federatedInfo;
12479
12480 var _this = this;
12481
12482 return __generator(this, function (_a) {
12483 switch (_a.label) {
12484 case 0:
12485 logger.debug('Getting current user credentials');
12486 _a.label = 1;
12487
12488 case 1:
12489 _a.trys.push([1, 3,, 4]);
12490
12491 return [4
12492 /*yield*/
12493 , this._storageSync];
12494
12495 case 2:
12496 _a.sent();
12497
12498 return [3
12499 /*break*/
12500 , 4];
12501
12502 case 3:
12503 e_7 = _a.sent();
12504 logger.debug('Failed to sync cache info into memory', e_7);
12505 throw e_7;
12506
12507 case 4:
12508 federatedInfo = null;
12509
12510 try {
12511 federatedInfo = JSON.parse(this._storage.getItem('aws-amplify-federatedInfo'));
12512 } catch (e) {
12513 logger.debug('failed to get or parse item aws-amplify-federatedInfo', e);
12514 }
12515
12516 if (federatedInfo) {
12517 // refresh the jwt token here if necessary
12518 return [2
12519 /*return*/
12520 , this.Credentials.refreshFederatedToken(federatedInfo)];
12521 } else {
12522 return [2
12523 /*return*/
12524 , this.currentSession().then(function (session) {
12525 logger.debug('getting session success', session);
12526 return _this.Credentials.set(session, 'session');
12527 })["catch"](function (error) {
12528 logger.debug('getting session failed', error);
12529 return _this.Credentials.set(null, 'guest');
12530 })];
12531 }
12532
12533 return [2
12534 /*return*/
12535 ];
12536 }
12537 });
12538 });
12539 };
12540
12541 AuthClass.prototype.currentCredentials = function () {
12542 logger.debug('getting current credentials');
12543 return this.Credentials.get();
12544 };
12545 /**
12546 * Initiate an attribute confirmation request
12547 * @param {Object} user - The CognitoUser
12548 * @param {Object} attr - The attributes to be verified
12549 * @return - A promise resolves to callback data if success
12550 */
12551
12552
12553 AuthClass.prototype.verifyUserAttribute = function (user, attr, clientMetadata) {
12554 if (clientMetadata === void 0) {
12555 clientMetadata = this._config.clientMetadata;
12556 }
12557
12558 return new Promise(function (resolve, reject) {
12559 user.getAttributeVerificationCode(attr, {
12560 onSuccess: function onSuccess(success) {
12561 return resolve(success);
12562 },
12563 onFailure: function onFailure(err) {
12564 return reject(err);
12565 }
12566 }, clientMetadata);
12567 });
12568 };
12569 /**
12570 * Confirm an attribute using a confirmation code
12571 * @param {Object} user - The CognitoUser
12572 * @param {Object} attr - The attribute to be verified
12573 * @param {String} code - The confirmation code
12574 * @return - A promise resolves to callback data if success
12575 */
12576
12577
12578 AuthClass.prototype.verifyUserAttributeSubmit = function (user, attr, code) {
12579 if (!code) {
12580 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyCode);
12581 }
12582
12583 return new Promise(function (resolve, reject) {
12584 user.verifyAttribute(attr, code, {
12585 onSuccess: function onSuccess(data) {
12586 resolve(data);
12587 return;
12588 },
12589 onFailure: function onFailure(err) {
12590 reject(err);
12591 return;
12592 }
12593 });
12594 });
12595 };
12596
12597 AuthClass.prototype.verifyCurrentUserAttribute = function (attr) {
12598 var that = this;
12599 return that.currentUserPoolUser().then(function (user) {
12600 return that.verifyUserAttribute(user, attr);
12601 });
12602 };
12603 /**
12604 * Confirm current user's attribute using a confirmation code
12605 * @param {Object} attr - The attribute to be verified
12606 * @param {String} code - The confirmation code
12607 * @return - A promise resolves to callback data if success
12608 */
12609
12610
12611 AuthClass.prototype.verifyCurrentUserAttributeSubmit = function (attr, code) {
12612 var that = this;
12613 return that.currentUserPoolUser().then(function (user) {
12614 return that.verifyUserAttributeSubmit(user, attr, code);
12615 });
12616 };
12617
12618 AuthClass.prototype.cognitoIdentitySignOut = function (opts, user) {
12619 return __awaiter(this, void 0, void 0, function () {
12620 var e_8, isSignedInHostedUI;
12621
12622 var _this = this;
12623
12624 return __generator(this, function (_a) {
12625 switch (_a.label) {
12626 case 0:
12627 _a.trys.push([0, 2,, 3]);
12628
12629 return [4
12630 /*yield*/
12631 , this._storageSync];
12632
12633 case 1:
12634 _a.sent();
12635
12636 return [3
12637 /*break*/
12638 , 3];
12639
12640 case 2:
12641 e_8 = _a.sent();
12642 logger.debug('Failed to sync cache info into memory', e_8);
12643 throw e_8;
12644
12645 case 3:
12646 isSignedInHostedUI = this._oAuthHandler && this._storage.getItem('amplify-signin-with-hostedUI') === 'true';
12647 return [2
12648 /*return*/
12649 , new Promise(function (res, rej) {
12650 if (opts && opts.global) {
12651 logger.debug('user global sign out', user); // in order to use global signout
12652 // we must validate the user as an authenticated user by using getSession
12653
12654 var clientMetadata = _this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
12655
12656 user.getSession(function (err, result) {
12657 if (err) {
12658 logger.debug('failed to get the user session', err);
12659 return rej(err);
12660 }
12661
12662 user.globalSignOut({
12663 onSuccess: function onSuccess(data) {
12664 logger.debug('global sign out success');
12665
12666 if (isSignedInHostedUI) {
12667 _this.oAuthSignOutRedirect(res, rej);
12668 } else {
12669 return res();
12670 }
12671 },
12672 onFailure: function onFailure(err) {
12673 logger.debug('global sign out failed', err);
12674 return rej(err);
12675 }
12676 });
12677 }, {
12678 clientMetadata: clientMetadata
12679 });
12680 } else {
12681 logger.debug('user sign out', user);
12682 user.signOut(function () {
12683 if (isSignedInHostedUI) {
12684 _this.oAuthSignOutRedirect(res, rej);
12685 } else {
12686 return res();
12687 }
12688 });
12689 }
12690 })];
12691 }
12692 });
12693 });
12694 };
12695
12696 AuthClass.prototype.oAuthSignOutRedirect = function (resolve, reject) {
12697 var isBrowser = _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["JS"].browserOrNode().isBrowser;
12698
12699 if (isBrowser) {
12700 this.oAuthSignOutRedirectOrReject(reject);
12701 } else {
12702 this.oAuthSignOutAndResolve(resolve);
12703 }
12704 };
12705
12706 AuthClass.prototype.oAuthSignOutAndResolve = function (resolve) {
12707 this._oAuthHandler.signOut();
12708
12709 resolve();
12710 };
12711
12712 AuthClass.prototype.oAuthSignOutRedirectOrReject = function (reject) {
12713 this._oAuthHandler.signOut(); // this method redirects url
12714 // App should be redirected to another url otherwise it will reject
12715
12716
12717 setTimeout(function () {
12718 return reject('Signout timeout fail');
12719 }, 3000);
12720 };
12721 /**
12722 * Sign out method
12723 * @
12724 * @return - A promise resolved if success
12725 */
12726
12727
12728 AuthClass.prototype.signOut = function (opts) {
12729 return __awaiter(this, void 0, void 0, function () {
12730 var e_9, user;
12731 return __generator(this, function (_a) {
12732 switch (_a.label) {
12733 case 0:
12734 _a.trys.push([0, 2,, 3]);
12735
12736 return [4
12737 /*yield*/
12738 , this.cleanCachedItems()];
12739
12740 case 1:
12741 _a.sent();
12742
12743 return [3
12744 /*break*/
12745 , 3];
12746
12747 case 2:
12748 e_9 = _a.sent();
12749 logger.debug('failed to clear cached items');
12750 return [3
12751 /*break*/
12752 , 3];
12753
12754 case 3:
12755 if (!this.userPool) return [3
12756 /*break*/
12757 , 7];
12758 user = this.userPool.getCurrentUser();
12759 if (!user) return [3
12760 /*break*/
12761 , 5];
12762 return [4
12763 /*yield*/
12764 , this.cognitoIdentitySignOut(opts, user)];
12765
12766 case 4:
12767 _a.sent();
12768
12769 return [3
12770 /*break*/
12771 , 6];
12772
12773 case 5:
12774 logger.debug('no current Cognito user');
12775 _a.label = 6;
12776
12777 case 6:
12778 return [3
12779 /*break*/
12780 , 8];
12781
12782 case 7:
12783 logger.debug('no Congito User pool');
12784 _a.label = 8;
12785
12786 case 8:
12787 /**
12788 * Note for future refactor - no reliable way to get username with
12789 * Cognito User Pools vs Identity when federating with Social Providers
12790 * This is why we need a well structured session object that can be inspected
12791 * and information passed back in the message below for Hub dispatch
12792 */
12793 dispatchAuthEvent('signOut', this.user, "A user has been signed out");
12794 this.user = null;
12795 return [2
12796 /*return*/
12797 ];
12798 }
12799 });
12800 });
12801 };
12802
12803 AuthClass.prototype.cleanCachedItems = function () {
12804 return __awaiter(this, void 0, void 0, function () {
12805 return __generator(this, function (_a) {
12806 switch (_a.label) {
12807 case 0:
12808 // clear cognito cached item
12809 return [4
12810 /*yield*/
12811 , this.Credentials.clear()];
12812
12813 case 1:
12814 // clear cognito cached item
12815 _a.sent();
12816
12817 return [2
12818 /*return*/
12819 ];
12820 }
12821 });
12822 });
12823 };
12824 /**
12825 * Change a password for an authenticated user
12826 * @param {Object} user - The CognitoUser object
12827 * @param {String} oldPassword - the current password
12828 * @param {String} newPassword - the requested new password
12829 * @return - A promise resolves if success
12830 */
12831
12832
12833 AuthClass.prototype.changePassword = function (user, oldPassword, newPassword, clientMetadata) {
12834 var _this = this;
12835
12836 if (clientMetadata === void 0) {
12837 clientMetadata = this._config.clientMetadata;
12838 }
12839
12840 return new Promise(function (resolve, reject) {
12841 _this.userSession(user).then(function (session) {
12842 user.changePassword(oldPassword, newPassword, function (err, data) {
12843 if (err) {
12844 logger.debug('change password failure', err);
12845 return reject(err);
12846 } else {
12847 return resolve(data);
12848 }
12849 }, clientMetadata);
12850 });
12851 });
12852 };
12853 /**
12854 * Initiate a forgot password request
12855 * @param {String} username - the username to change password
12856 * @return - A promise resolves if success
12857 */
12858
12859
12860 AuthClass.prototype.forgotPassword = function (username, clientMetadata) {
12861 if (clientMetadata === void 0) {
12862 clientMetadata = this._config.clientMetadata;
12863 }
12864
12865 if (!this.userPool) {
12866 return this.rejectNoUserPool();
12867 }
12868
12869 if (!username) {
12870 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
12871 }
12872
12873 var user = this.createCognitoUser(username);
12874 return new Promise(function (resolve, reject) {
12875 user.forgotPassword({
12876 onSuccess: function onSuccess() {
12877 resolve();
12878 return;
12879 },
12880 onFailure: function onFailure(err) {
12881 logger.debug('forgot password failure', err);
12882 dispatchAuthEvent('forgotPassword_failure', err, username + " forgotPassword failed");
12883 reject(err);
12884 return;
12885 },
12886 inputVerificationCode: function inputVerificationCode(data) {
12887 dispatchAuthEvent('forgotPassword', user, username + " has initiated forgot password flow");
12888 resolve(data);
12889 return;
12890 }
12891 }, clientMetadata);
12892 });
12893 };
12894 /**
12895 * Confirm a new password using a confirmation Code
12896 * @param {String} username - The username
12897 * @param {String} code - The confirmation code
12898 * @param {String} password - The new password
12899 * @return - A promise that resolves if success
12900 */
12901
12902
12903 AuthClass.prototype.forgotPasswordSubmit = function (username, code, password, clientMetadata) {
12904 if (clientMetadata === void 0) {
12905 clientMetadata = this._config.clientMetadata;
12906 }
12907
12908 if (!this.userPool) {
12909 return this.rejectNoUserPool();
12910 }
12911
12912 if (!username) {
12913 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
12914 }
12915
12916 if (!code) {
12917 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyCode);
12918 }
12919
12920 if (!password) {
12921 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyPassword);
12922 }
12923
12924 var user = this.createCognitoUser(username);
12925 return new Promise(function (resolve, reject) {
12926 user.confirmPassword(code, password, {
12927 onSuccess: function onSuccess(success) {
12928 dispatchAuthEvent('forgotPasswordSubmit', user, username + " forgotPasswordSubmit successful");
12929 resolve(success);
12930 return;
12931 },
12932 onFailure: function onFailure(err) {
12933 dispatchAuthEvent('forgotPasswordSubmit_failure', err, username + " forgotPasswordSubmit failed");
12934 reject(err);
12935 return;
12936 }
12937 }, clientMetadata);
12938 });
12939 };
12940 /**
12941 * Get user information
12942 * @async
12943 * @return {Object }- current User's information
12944 */
12945
12946
12947 AuthClass.prototype.currentUserInfo = function () {
12948 return __awaiter(this, void 0, void 0, function () {
12949 var source, user, attributes, userAttrs, credentials, e_10, info, err_1, user;
12950 return __generator(this, function (_a) {
12951 switch (_a.label) {
12952 case 0:
12953 source = this.Credentials.getCredSource();
12954 if (!(!source || source === 'aws' || source === 'userPool')) return [3
12955 /*break*/
12956 , 9];
12957 return [4
12958 /*yield*/
12959 , this.currentUserPoolUser()["catch"](function (err) {
12960 return logger.error(err);
12961 })];
12962
12963 case 1:
12964 user = _a.sent();
12965
12966 if (!user) {
12967 return [2
12968 /*return*/
12969 , null];
12970 }
12971
12972 _a.label = 2;
12973
12974 case 2:
12975 _a.trys.push([2, 8,, 9]);
12976
12977 return [4
12978 /*yield*/
12979 , this.userAttributes(user)];
12980
12981 case 3:
12982 attributes = _a.sent();
12983 userAttrs = this.attributesToObject(attributes);
12984 credentials = null;
12985 _a.label = 4;
12986
12987 case 4:
12988 _a.trys.push([4, 6,, 7]);
12989
12990 return [4
12991 /*yield*/
12992 , this.currentCredentials()];
12993
12994 case 5:
12995 credentials = _a.sent();
12996 return [3
12997 /*break*/
12998 , 7];
12999
13000 case 6:
13001 e_10 = _a.sent();
13002 logger.debug('Failed to retrieve credentials while getting current user info', e_10);
13003 return [3
13004 /*break*/
13005 , 7];
13006
13007 case 7:
13008 info = {
13009 id: credentials ? credentials.identityId : undefined,
13010 username: user.getUsername(),
13011 attributes: userAttrs
13012 };
13013 return [2
13014 /*return*/
13015 , info];
13016
13017 case 8:
13018 err_1 = _a.sent();
13019 logger.error('currentUserInfo error', err_1);
13020 return [2
13021 /*return*/
13022 , {}];
13023
13024 case 9:
13025 if (source === 'federated') {
13026 user = this.user;
13027 return [2
13028 /*return*/
13029 , user ? user : {}];
13030 }
13031
13032 return [2
13033 /*return*/
13034 ];
13035 }
13036 });
13037 });
13038 };
13039
13040 AuthClass.prototype.federatedSignIn = function (providerOrOptions, response, user) {
13041 return __awaiter(this, void 0, void 0, function () {
13042 var options, provider, customState, client_id, redirect_uri, provider, loggedInUser, token, identity_id, expires_at, credentials, currentUser;
13043 return __generator(this, function (_a) {
13044 switch (_a.label) {
13045 case 0:
13046 if (!this._config.identityPoolId && !this._config.userPoolId) {
13047 throw new Error("Federation requires either a User Pool or Identity Pool in config");
13048 } // Ensure backwards compatability
13049
13050
13051 if (typeof providerOrOptions === 'undefined') {
13052 if (this._config.identityPoolId && !this._config.userPoolId) {
13053 throw new Error("Federation with Identity Pools requires tokens passed as arguments");
13054 }
13055 }
13056
13057 if (!(Object(_types__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptions"])(providerOrOptions) || Object(_types__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptionsCustom"])(providerOrOptions) || Object(_types__WEBPACK_IMPORTED_MODULE_0__["hasCustomState"])(providerOrOptions) || typeof providerOrOptions === 'undefined')) return [3
13058 /*break*/
13059 , 1];
13060 options = providerOrOptions || {
13061 provider: _types_Auth__WEBPACK_IMPORTED_MODULE_7__["CognitoHostedUIIdentityProvider"].Cognito
13062 };
13063 provider = Object(_types__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptions"])(options) ? options.provider : options.customProvider;
13064 customState = Object(_types__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptions"])(options) ? options.customState : options.customState;
13065
13066 if (this._config.userPoolId) {
13067 client_id = Object(_types__WEBPACK_IMPORTED_MODULE_0__["isCognitoHostedOpts"])(this._config.oauth) ? this._config.userPoolWebClientId : this._config.oauth.clientID;
13068 redirect_uri = Object(_types__WEBPACK_IMPORTED_MODULE_0__["isCognitoHostedOpts"])(this._config.oauth) ? this._config.oauth.redirectSignIn : this._config.oauth.redirectUri;
13069
13070 this._oAuthHandler.oauthSignIn(this._config.oauth.responseType, this._config.oauth.domain, redirect_uri, client_id, provider, customState);
13071 }
13072
13073 return [3
13074 /*break*/
13075 , 4];
13076
13077 case 1:
13078 provider = providerOrOptions; // To check if the user is already logged in
13079
13080 try {
13081 loggedInUser = JSON.stringify(JSON.parse(this._storage.getItem('aws-amplify-federatedInfo')).user);
13082
13083 if (loggedInUser) {
13084 logger.warn("There is already a signed in user: " + loggedInUser + " in your app.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tYou should not call Auth.federatedSignIn method again as it may cause unexpected behavior.");
13085 }
13086 } catch (e) {}
13087
13088 token = response.token, identity_id = response.identity_id, expires_at = response.expires_at;
13089 return [4
13090 /*yield*/
13091 , this.Credentials.set({
13092 provider: provider,
13093 token: token,
13094 identity_id: identity_id,
13095 user: user,
13096 expires_at: expires_at
13097 }, 'federation')];
13098
13099 case 2:
13100 credentials = _a.sent();
13101 return [4
13102 /*yield*/
13103 , this.currentAuthenticatedUser()];
13104
13105 case 3:
13106 currentUser = _a.sent();
13107 dispatchAuthEvent('signIn', currentUser, "A user " + currentUser.username + " has been signed in");
13108 logger.debug('federated sign in credentials', credentials);
13109 return [2
13110 /*return*/
13111 , credentials];
13112
13113 case 4:
13114 return [2
13115 /*return*/
13116 ];
13117 }
13118 });
13119 });
13120 };
13121 /**
13122 * Used to complete the OAuth flow with or without the Cognito Hosted UI
13123 * @param {String} URL - optional parameter for customers to pass in the response URL
13124 */
13125
13126
13127 AuthClass.prototype._handleAuthResponse = function (URL) {
13128 return __awaiter(this, void 0, void 0, function () {
13129 var currentUrl, hasCodeOrError, hasTokenOrError, _a, accessToken, idToken, refreshToken, state, session, credentials, isCustomStateIncluded, currentUser, customState, err_2;
13130
13131 return __generator(this, function (_b) {
13132 switch (_b.label) {
13133 case 0:
13134 if (this.oAuthFlowInProgress) {
13135 logger.debug("Skipping URL " + URL + " current flow in progress");
13136 return [2
13137 /*return*/
13138 ];
13139 }
13140
13141 _b.label = 1;
13142
13143 case 1:
13144 _b.trys.push([1,, 8, 9]);
13145
13146 this.oAuthFlowInProgress = true;
13147
13148 if (!this._config.userPoolId) {
13149 throw new Error("OAuth responses require a User Pool defined in config");
13150 }
13151
13152 dispatchAuthEvent('parsingCallbackUrl', {
13153 url: URL
13154 }, "The callback url is being parsed");
13155 currentUrl = URL || (_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["JS"].browserOrNode().isBrowser ? window.location.href : '');
13156 hasCodeOrError = !!(Object(url__WEBPACK_IMPORTED_MODULE_3__["parse"])(currentUrl).query || '').split('&').map(function (entry) {
13157 return entry.split('=');
13158 }).find(function (_a) {
13159 var _b = __read(_a, 1),
13160 k = _b[0];
13161
13162 return k === 'code' || k === 'error';
13163 });
13164 hasTokenOrError = !!(Object(url__WEBPACK_IMPORTED_MODULE_3__["parse"])(currentUrl).hash || '#').substr(1).split('&').map(function (entry) {
13165 return entry.split('=');
13166 }).find(function (_a) {
13167 var _b = __read(_a, 1),
13168 k = _b[0];
13169
13170 return k === 'access_token' || k === 'error';
13171 });
13172 if (!(hasCodeOrError || hasTokenOrError)) return [3
13173 /*break*/
13174 , 7];
13175
13176 this._storage.setItem('amplify-redirected-from-hosted-ui', 'true');
13177
13178 _b.label = 2;
13179
13180 case 2:
13181 _b.trys.push([2, 6,, 7]);
13182
13183 return [4
13184 /*yield*/
13185 , this._oAuthHandler.handleAuthResponse(currentUrl)];
13186
13187 case 3:
13188 _a = _b.sent(), accessToken = _a.accessToken, idToken = _a.idToken, refreshToken = _a.refreshToken, state = _a.state;
13189 session = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserSession"]({
13190 IdToken: new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoIdToken"]({
13191 IdToken: idToken
13192 }),
13193 RefreshToken: new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoRefreshToken"]({
13194 RefreshToken: refreshToken
13195 }),
13196 AccessToken: new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoAccessToken"]({
13197 AccessToken: accessToken
13198 })
13199 });
13200 credentials = void 0;
13201 if (!this._config.identityPoolId) return [3
13202 /*break*/
13203 , 5];
13204 return [4
13205 /*yield*/
13206 , this.Credentials.set(session, 'session')];
13207
13208 case 4:
13209 credentials = _b.sent();
13210 logger.debug('AWS credentials', credentials);
13211 _b.label = 5;
13212
13213 case 5:
13214 isCustomStateIncluded = /-/.test(state);
13215 currentUser = this.createCognitoUser(session.getIdToken().decodePayload()['cognito:username']); // This calls cacheTokens() in Cognito SDK
13216
13217 currentUser.setSignInUserSession(session);
13218
13219 if (window && typeof window.history !== 'undefined') {
13220 window.history.replaceState({}, null, this._config.oauth.redirectSignIn);
13221 }
13222
13223 dispatchAuthEvent('signIn', currentUser, "A user " + currentUser.getUsername() + " has been signed in");
13224 dispatchAuthEvent('cognitoHostedUI', currentUser, "A user " + currentUser.getUsername() + " has been signed in via Cognito Hosted UI");
13225
13226 if (isCustomStateIncluded) {
13227 customState = state.split('-').splice(1).join('-');
13228 dispatchAuthEvent('customOAuthState', Object(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["urlSafeDecode"])(customState), "State for user " + currentUser.getUsername());
13229 } //#endregion
13230
13231
13232 return [2
13233 /*return*/
13234 , credentials];
13235
13236 case 6:
13237 err_2 = _b.sent();
13238 logger.debug('Error in cognito hosted auth response', err_2); // Just like a successful handling of `?code`, replace the window history to "dispose" of the `code`.
13239 // Otherwise, reloading the page will throw errors as the `code` has already been spent.
13240
13241 if (window && typeof window.history !== 'undefined') {
13242 window.history.replaceState({}, null, this._config.oauth.redirectSignIn);
13243 }
13244
13245 dispatchAuthEvent('signIn_failure', err_2, "The OAuth response flow failed");
13246 dispatchAuthEvent('cognitoHostedUI_failure', err_2, "A failure occurred when returning to the Cognito Hosted UI");
13247 dispatchAuthEvent('customState_failure', err_2, "A failure occurred when returning state");
13248 return [3
13249 /*break*/
13250 , 7];
13251
13252 case 7:
13253 return [3
13254 /*break*/
13255 , 9];
13256
13257 case 8:
13258 this.oAuthFlowInProgress = false;
13259 return [7
13260 /*endfinally*/
13261 ];
13262
13263 case 9:
13264 return [2
13265 /*return*/
13266 ];
13267 }
13268 });
13269 });
13270 };
13271 /**
13272 * Compact version of credentials
13273 * @param {Object} credentials
13274 * @return {Object} - Credentials
13275 */
13276
13277
13278 AuthClass.prototype.essentialCredentials = function (credentials) {
13279 return {
13280 accessKeyId: credentials.accessKeyId,
13281 sessionToken: credentials.sessionToken,
13282 secretAccessKey: credentials.secretAccessKey,
13283 identityId: credentials.identityId,
13284 authenticated: credentials.authenticated
13285 };
13286 };
13287
13288 AuthClass.prototype.attributesToObject = function (attributes) {
13289 var _this = this;
13290
13291 var obj = {};
13292
13293 if (attributes) {
13294 attributes.map(function (attribute) {
13295 if (attribute.Name === 'email_verified' || attribute.Name === 'phone_number_verified') {
13296 obj[attribute.Name] = _this.isTruthyString(attribute.Value) || attribute.Value === true;
13297 } else {
13298 obj[attribute.Name] = attribute.Value;
13299 }
13300 });
13301 }
13302
13303 return obj;
13304 };
13305
13306 AuthClass.prototype.isTruthyString = function (value) {
13307 return typeof value.toLowerCase === 'function' && value.toLowerCase() === 'true';
13308 };
13309
13310 AuthClass.prototype.createCognitoUser = function (username) {
13311 var userData = {
13312 Username: username,
13313 Pool: this.userPool
13314 };
13315 userData.Storage = this._storage;
13316 var authenticationFlowType = this._config.authenticationFlowType;
13317 var user = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUser"](userData);
13318
13319 if (authenticationFlowType) {
13320 user.setAuthenticationFlowType(authenticationFlowType);
13321 }
13322
13323 return user;
13324 };
13325
13326 AuthClass.prototype._isValidAuthStorage = function (obj) {
13327 // We need to check if the obj has the functions of Storage
13328 return !!obj && typeof obj.getItem === 'function' && typeof obj.setItem === 'function' && typeof obj.removeItem === 'function' && typeof obj.clear === 'function';
13329 };
13330
13331 AuthClass.prototype.noUserPoolErrorHandler = function (config) {
13332 if (config) {
13333 if (!config.userPoolId || !config.identityPoolId) {
13334 return _types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].MissingAuthConfig;
13335 }
13336 }
13337
13338 return _types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NoConfig;
13339 };
13340
13341 AuthClass.prototype.rejectAuthError = function (type) {
13342 return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](type));
13343 };
13344
13345 AuthClass.prototype.rejectNoUserPool = function () {
13346 var type = this.noUserPoolErrorHandler(this._config);
13347 return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_6__["NoUserPoolError"](type));
13348 };
13349
13350 AuthClass.prototype.rememberDevice = function () {
13351 return __awaiter(this, void 0, void 0, function () {
13352 var currUser, error_1;
13353 return __generator(this, function (_a) {
13354 switch (_a.label) {
13355 case 0:
13356 _a.trys.push([0, 2,, 3]);
13357
13358 return [4
13359 /*yield*/
13360 , this.currentUserPoolUser()];
13361
13362 case 1:
13363 currUser = _a.sent();
13364 return [3
13365 /*break*/
13366 , 3];
13367
13368 case 2:
13369 error_1 = _a.sent();
13370 logger.debug('The user is not authenticated by the error', error_1);
13371 return [2
13372 /*return*/
13373 , Promise.reject('The user is not authenticated')];
13374
13375 case 3:
13376 currUser.getCachedDeviceKeyAndPassword();
13377 return [2
13378 /*return*/
13379 , new Promise(function (res, rej) {
13380 currUser.setDeviceStatusRemembered({
13381 onSuccess: function onSuccess(data) {
13382 res(data);
13383 },
13384 onFailure: function onFailure(err) {
13385 if (err.code === 'InvalidParameterException') {
13386 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].DeviceConfig));
13387 } else if (err.code === 'NetworkError') {
13388 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NetworkError));
13389 } else {
13390 rej(err);
13391 }
13392 }
13393 });
13394 })];
13395 }
13396 });
13397 });
13398 };
13399
13400 AuthClass.prototype.forgetDevice = function () {
13401 return __awaiter(this, void 0, void 0, function () {
13402 var currUser, error_2;
13403 return __generator(this, function (_a) {
13404 switch (_a.label) {
13405 case 0:
13406 _a.trys.push([0, 2,, 3]);
13407
13408 return [4
13409 /*yield*/
13410 , this.currentUserPoolUser()];
13411
13412 case 1:
13413 currUser = _a.sent();
13414 return [3
13415 /*break*/
13416 , 3];
13417
13418 case 2:
13419 error_2 = _a.sent();
13420 logger.debug('The user is not authenticated by the error', error_2);
13421 return [2
13422 /*return*/
13423 , Promise.reject('The user is not authenticated')];
13424
13425 case 3:
13426 currUser.getCachedDeviceKeyAndPassword();
13427 return [2
13428 /*return*/
13429 , new Promise(function (res, rej) {
13430 currUser.forgetDevice({
13431 onSuccess: function onSuccess(data) {
13432 res(data);
13433 },
13434 onFailure: function onFailure(err) {
13435 if (err.code === 'InvalidParameterException') {
13436 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].DeviceConfig));
13437 } else if (err.code === 'NetworkError') {
13438 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NetworkError));
13439 } else {
13440 rej(err);
13441 }
13442 }
13443 });
13444 })];
13445 }
13446 });
13447 });
13448 };
13449
13450 AuthClass.prototype.fetchDevices = function () {
13451 return __awaiter(this, void 0, void 0, function () {
13452 var currUser, error_3;
13453 return __generator(this, function (_a) {
13454 switch (_a.label) {
13455 case 0:
13456 _a.trys.push([0, 2,, 3]);
13457
13458 return [4
13459 /*yield*/
13460 , this.currentUserPoolUser()];
13461
13462 case 1:
13463 currUser = _a.sent();
13464 return [3
13465 /*break*/
13466 , 3];
13467
13468 case 2:
13469 error_3 = _a.sent();
13470 logger.debug('The user is not authenticated by the error', error_3);
13471 throw new Error('The user is not authenticated');
13472
13473 case 3:
13474 currUser.getCachedDeviceKeyAndPassword();
13475 return [2
13476 /*return*/
13477 , new Promise(function (res, rej) {
13478 var cb = {
13479 onSuccess: function onSuccess(data) {
13480 var deviceList = data.Devices.map(function (device) {
13481 var deviceName = device.DeviceAttributes.find(function (_a) {
13482 var Name = _a.Name;
13483 return Name === 'device_name';
13484 }) || {};
13485 var deviceInfo = {
13486 id: device.DeviceKey,
13487 name: deviceName.Value
13488 };
13489 return deviceInfo;
13490 });
13491 res(deviceList);
13492 },
13493 onFailure: function onFailure(err) {
13494 if (err.code === 'InvalidParameterException') {
13495 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].DeviceConfig));
13496 } else if (err.code === 'NetworkError') {
13497 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NetworkError));
13498 } else {
13499 rej(err);
13500 }
13501 }
13502 };
13503 currUser.listDevices(MAX_DEVICES, null, cb);
13504 })];
13505 }
13506 });
13507 });
13508 };
13509
13510 return AuthClass;
13511}();
13512
13513
13514var Auth = new AuthClass(null);
13515_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Amplify"].register(Auth);
13516
13517/***/ }),
13518
13519/***/ "./lib-esm/Errors.js":
13520/*!***************************!*\
13521 !*** ./lib-esm/Errors.js ***!
13522 \***************************/
13523/*! exports provided: AuthError, NoUserPoolError, authErrorMessages */
13524/***/ (function(module, __webpack_exports__, __webpack_require__) {
13525
13526"use strict";
13527__webpack_require__.r(__webpack_exports__);
13528/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthError", function() { return AuthError; });
13529/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoUserPoolError", function() { return NoUserPoolError; });
13530/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "authErrorMessages", function() { return authErrorMessages; });
13531/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
13532/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__);
13533/* harmony import */ var _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./common/AuthErrorStrings */ "./lib-esm/common/AuthErrorStrings.js");
13534/*
13535 * Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
13536 *
13537 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
13538 * the License. A copy of the License is located at
13539 *
13540 * http://aws.amazon.com/apache2.0/
13541 *
13542 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
13543 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
13544 * and limitations under the License.
13545 */
13546var __extends = undefined && undefined.__extends || function () {
13547 var _extendStatics = function extendStatics(d, b) {
13548 _extendStatics = Object.setPrototypeOf || {
13549 __proto__: []
13550 } instanceof Array && function (d, b) {
13551 d.__proto__ = b;
13552 } || function (d, b) {
13553 for (var p in b) {
13554 if (b.hasOwnProperty(p)) d[p] = b[p];
13555 }
13556 };
13557
13558 return _extendStatics(d, b);
13559 };
13560
13561 return function (d, b) {
13562 _extendStatics(d, b);
13563
13564 function __() {
13565 this.constructor = d;
13566 }
13567
13568 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13569 };
13570}();
13571
13572
13573
13574var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["ConsoleLogger"]('AuthError');
13575
13576var AuthError =
13577/** @class */
13578function (_super) {
13579 __extends(AuthError, _super);
13580
13581 function AuthError(type) {
13582 var _this = this;
13583
13584 var _a = authErrorMessages[type],
13585 message = _a.message,
13586 log = _a.log;
13587 _this = _super.call(this, message) || this; // Hack for making the custom error class work when transpiled to es5
13588 // TODO: Delete the following 2 lines after we change the build target to >= es2015
13589
13590 _this.constructor = AuthError;
13591 Object.setPrototypeOf(_this, AuthError.prototype);
13592 _this.name = 'AuthError';
13593 _this.log = log || message;
13594 logger.error(_this.log);
13595 return _this;
13596 }
13597
13598 return AuthError;
13599}(Error);
13600
13601
13602
13603var NoUserPoolError =
13604/** @class */
13605function (_super) {
13606 __extends(NoUserPoolError, _super);
13607
13608 function NoUserPoolError(type) {
13609 var _this = _super.call(this, type) || this; // Hack for making the custom error class work when transpiled to es5
13610 // TODO: Delete the following 2 lines after we change the build target to >= es2015
13611
13612
13613 _this.constructor = NoUserPoolError;
13614 Object.setPrototypeOf(_this, NoUserPoolError.prototype);
13615 _this.name = 'NoUserPoolError';
13616 return _this;
13617 }
13618
13619 return NoUserPoolError;
13620}(AuthError);
13621
13622
13623var authErrorMessages = {
13624 noConfig: {
13625 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].DEFAULT_MSG,
13626 log: "\n Error: Amplify has not been configured correctly.\n This error is typically caused by one of the following scenarios:\n\n 1. Make sure you're passing the awsconfig object to Amplify.configure() in your app's entry point\n See https://aws-amplify.github.io/docs/js/authentication#configure-your-app for more information\n \n 2. There might be multiple conflicting versions of amplify packages in your node_modules.\n\t\t\t\tRefer to our docs site for help upgrading Amplify packages (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js)\n "
13627 },
13628 missingAuthConfig: {
13629 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].DEFAULT_MSG,
13630 log: "\n Error: Amplify has not been configured correctly. \n The configuration object is missing required auth properties.\n This error is typically caused by one of the following scenarios:\n\n 1. Did you run `amplify push` after adding auth via `amplify add auth`?\n See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information\n\n 2. This could also be caused by multiple conflicting versions of amplify packages, see (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js) for help upgrading Amplify packages.\n "
13631 },
13632 emptyUsername: {
13633 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].EMPTY_USERNAME
13634 },
13635 // TODO: should include a list of valid sign-in types
13636 invalidUsername: {
13637 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].INVALID_USERNAME
13638 },
13639 emptyPassword: {
13640 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].EMPTY_PASSWORD
13641 },
13642 emptyCode: {
13643 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].EMPTY_CODE
13644 },
13645 signUpError: {
13646 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].SIGN_UP_ERROR,
13647 log: 'The first parameter should either be non-null string or object'
13648 },
13649 noMFA: {
13650 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].NO_MFA
13651 },
13652 invalidMFA: {
13653 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].INVALID_MFA
13654 },
13655 emptyChallengeResponse: {
13656 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].EMPTY_CHALLENGE
13657 },
13658 noUserSession: {
13659 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].NO_USER_SESSION
13660 },
13661 deviceConfig: {
13662 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].DEVICE_CONFIG
13663 },
13664 networkError: {
13665 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].NETWORK_ERROR
13666 },
13667 "default": {
13668 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].DEFAULT_MSG
13669 }
13670};
13671
13672/***/ }),
13673
13674/***/ "./lib-esm/OAuth/OAuth.js":
13675/*!********************************!*\
13676 !*** ./lib-esm/OAuth/OAuth.js ***!
13677 \********************************/
13678/*! exports provided: default */
13679/***/ (function(module, __webpack_exports__, __webpack_require__) {
13680
13681"use strict";
13682__webpack_require__.r(__webpack_exports__);
13683/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url */ "../../node_modules/url/url.js");
13684/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_0__);
13685/* harmony import */ var _urlOpener__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./urlOpener */ "./lib-esm/OAuth/urlOpener.js");
13686/* harmony import */ var _oauthStorage__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./oauthStorage */ "./lib-esm/OAuth/oauthStorage.js");
13687/* harmony import */ var _types_Auth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/Auth */ "./lib-esm/types/Auth.js");
13688/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
13689/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__);
13690/* harmony import */ var crypto_js_sha256__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! crypto-js/sha256 */ "./node_modules/crypto-js/sha256.js");
13691/* harmony import */ var crypto_js_sha256__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(crypto_js_sha256__WEBPACK_IMPORTED_MODULE_5__);
13692/* harmony import */ var crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! crypto-js/enc-base64 */ "./node_modules/crypto-js/enc-base64.js");
13693/* harmony import */ var crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_6__);
13694/*
13695 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
13696 *
13697 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
13698 * the License. A copy of the License is located at
13699 *
13700 * http://aws.amazon.com/apache2.0/
13701 *
13702 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
13703 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
13704 * and limitations under the License.
13705 */
13706var __assign = undefined && undefined.__assign || function () {
13707 __assign = Object.assign || function (t) {
13708 for (var s, i = 1, n = arguments.length; i < n; i++) {
13709 s = arguments[i];
13710
13711 for (var p in s) {
13712 if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
13713 }
13714 }
13715
13716 return t;
13717 };
13718
13719 return __assign.apply(this, arguments);
13720};
13721
13722var __awaiter = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) {
13723 function adopt(value) {
13724 return value instanceof P ? value : new P(function (resolve) {
13725 resolve(value);
13726 });
13727 }
13728
13729 return new (P || (P = Promise))(function (resolve, reject) {
13730 function fulfilled(value) {
13731 try {
13732 step(generator.next(value));
13733 } catch (e) {
13734 reject(e);
13735 }
13736 }
13737
13738 function rejected(value) {
13739 try {
13740 step(generator["throw"](value));
13741 } catch (e) {
13742 reject(e);
13743 }
13744 }
13745
13746 function step(result) {
13747 result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
13748 }
13749
13750 step((generator = generator.apply(thisArg, _arguments || [])).next());
13751 });
13752};
13753
13754var __generator = undefined && undefined.__generator || function (thisArg, body) {
13755 var _ = {
13756 label: 0,
13757 sent: function sent() {
13758 if (t[0] & 1) throw t[1];
13759 return t[1];
13760 },
13761 trys: [],
13762 ops: []
13763 },
13764 f,
13765 y,
13766 t,
13767 g;
13768 return g = {
13769 next: verb(0),
13770 "throw": verb(1),
13771 "return": verb(2)
13772 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
13773 return this;
13774 }), g;
13775
13776 function verb(n) {
13777 return function (v) {
13778 return step([n, v]);
13779 };
13780 }
13781
13782 function step(op) {
13783 if (f) throw new TypeError("Generator is already executing.");
13784
13785 while (_) {
13786 try {
13787 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
13788 if (y = 0, t) op = [op[0] & 2, t.value];
13789
13790 switch (op[0]) {
13791 case 0:
13792 case 1:
13793 t = op;
13794 break;
13795
13796 case 4:
13797 _.label++;
13798 return {
13799 value: op[1],
13800 done: false
13801 };
13802
13803 case 5:
13804 _.label++;
13805 y = op[1];
13806 op = [0];
13807 continue;
13808
13809 case 7:
13810 op = _.ops.pop();
13811
13812 _.trys.pop();
13813
13814 continue;
13815
13816 default:
13817 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
13818 _ = 0;
13819 continue;
13820 }
13821
13822 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
13823 _.label = op[1];
13824 break;
13825 }
13826
13827 if (op[0] === 6 && _.label < t[1]) {
13828 _.label = t[1];
13829 t = op;
13830 break;
13831 }
13832
13833 if (t && _.label < t[2]) {
13834 _.label = t[2];
13835
13836 _.ops.push(op);
13837
13838 break;
13839 }
13840
13841 if (t[2]) _.ops.pop();
13842
13843 _.trys.pop();
13844
13845 continue;
13846 }
13847
13848 op = body.call(thisArg, _);
13849 } catch (e) {
13850 op = [6, e];
13851 y = 0;
13852 } finally {
13853 f = t = 0;
13854 }
13855 }
13856
13857 if (op[0] & 5) throw op[1];
13858 return {
13859 value: op[0] ? op[1] : void 0,
13860 done: true
13861 };
13862 }
13863};
13864
13865var __read = undefined && undefined.__read || function (o, n) {
13866 var m = typeof Symbol === "function" && o[Symbol.iterator];
13867 if (!m) return o;
13868 var i = m.call(o),
13869 r,
13870 ar = [],
13871 e;
13872
13873 try {
13874 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
13875 ar.push(r.value);
13876 }
13877 } catch (error) {
13878 e = {
13879 error: error
13880 };
13881 } finally {
13882 try {
13883 if (r && !r.done && (m = i["return"])) m.call(i);
13884 } finally {
13885 if (e) throw e.error;
13886 }
13887 }
13888
13889 return ar;
13890};
13891
13892 // Used for OAuth parsing of Cognito Hosted UI
13893
13894
13895
13896
13897
13898
13899
13900var AMPLIFY_SYMBOL = typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function' ? Symbol["for"]('amplify_default') : '@@amplify_default';
13901
13902var dispatchAuthEvent = function dispatchAuthEvent(event, data, message) {
13903 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__["Hub"].dispatch('auth', {
13904 event: event,
13905 data: data,
13906 message: message
13907 }, 'Auth', AMPLIFY_SYMBOL);
13908};
13909
13910var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__["ConsoleLogger"]('OAuth');
13911
13912var OAuth =
13913/** @class */
13914function () {
13915 function OAuth(_a) {
13916 var config = _a.config,
13917 cognitoClientId = _a.cognitoClientId,
13918 _b = _a.scopes,
13919 scopes = _b === void 0 ? [] : _b;
13920 this._urlOpener = config.urlOpener || _urlOpener__WEBPACK_IMPORTED_MODULE_1__["launchUri"];
13921 this._config = config;
13922 this._cognitoClientId = cognitoClientId;
13923 if (!this.isValidScopes(scopes)) throw Error('scopes must be a String Array');
13924 this._scopes = scopes;
13925 }
13926
13927 OAuth.prototype.isValidScopes = function (scopes) {
13928 return Array.isArray(scopes) && scopes.every(function (scope) {
13929 return typeof scope === 'string';
13930 });
13931 };
13932
13933 OAuth.prototype.oauthSignIn = function (responseType, domain, redirectSignIn, clientId, provider, customState) {
13934 if (responseType === void 0) {
13935 responseType = 'code';
13936 }
13937
13938 if (provider === void 0) {
13939 provider = _types_Auth__WEBPACK_IMPORTED_MODULE_3__["CognitoHostedUIIdentityProvider"].Cognito;
13940 }
13941
13942 var generatedState = this._generateState(32);
13943 /* encodeURIComponent is not URL safe, use urlSafeEncode instead. Cognito
13944 single-encodes/decodes url on first sign in and double-encodes/decodes url
13945 when user already signed in. Using encodeURIComponent, Base32, Base64 add
13946 characters % or = which on further encoding becomes unsafe. '=' create issue
13947 for parsing query params.
13948 Refer: https://github.com/aws-amplify/amplify-js/issues/5218 */
13949
13950
13951 var state = customState ? generatedState + "-" + Object(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__["urlSafeEncode"])(customState) : generatedState;
13952 _oauthStorage__WEBPACK_IMPORTED_MODULE_2__["setState"](state);
13953
13954 var pkce_key = this._generateRandom(128);
13955
13956 _oauthStorage__WEBPACK_IMPORTED_MODULE_2__["setPKCE"](pkce_key);
13957
13958 var code_challenge = this._generateChallenge(pkce_key);
13959
13960 var code_challenge_method = 'S256';
13961
13962 var scopesString = this._scopes.join(' ');
13963
13964 var queryString = Object.entries(__assign(__assign({
13965 redirect_uri: redirectSignIn,
13966 response_type: responseType,
13967 client_id: clientId,
13968 identity_provider: provider,
13969 scope: scopesString,
13970 state: state
13971 }, responseType === 'code' ? {
13972 code_challenge: code_challenge
13973 } : {}), responseType === 'code' ? {
13974 code_challenge_method: code_challenge_method
13975 } : {})).map(function (_a) {
13976 var _b = __read(_a, 2),
13977 k = _b[0],
13978 v = _b[1];
13979
13980 return encodeURIComponent(k) + "=" + encodeURIComponent(v);
13981 }).join('&');
13982 var URL = "https://" + domain + "/oauth2/authorize?" + queryString;
13983 logger.debug("Redirecting to " + URL);
13984
13985 this._urlOpener(URL, redirectSignIn);
13986 };
13987
13988 OAuth.prototype._handleCodeFlow = function (currentUrl) {
13989 return __awaiter(this, void 0, void 0, function () {
13990 var code, currentUrlPathname, redirectSignInPathname, oAuthTokenEndpoint, client_id, redirect_uri, code_verifier, oAuthTokenBody, body, _a, access_token, refresh_token, id_token, error;
13991
13992 return __generator(this, function (_b) {
13993 switch (_b.label) {
13994 case 0:
13995 code = (Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).query || '').split('&').map(function (pairings) {
13996 return pairings.split('=');
13997 }).reduce(function (accum, _a) {
13998 var _b;
13999
14000 var _c = __read(_a, 2),
14001 k = _c[0],
14002 v = _c[1];
14003
14004 return __assign(__assign({}, accum), (_b = {}, _b[k] = v, _b));
14005 }, {
14006 code: undefined
14007 }).code;
14008 currentUrlPathname = Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).pathname || '/';
14009 redirectSignInPathname = Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(this._config.redirectSignIn).pathname || '/';
14010
14011 if (!code || currentUrlPathname !== redirectSignInPathname) {
14012 return [2
14013 /*return*/
14014 ];
14015 }
14016
14017 oAuthTokenEndpoint = 'https://' + this._config.domain + '/oauth2/token';
14018 dispatchAuthEvent('codeFlow', {}, "Retrieving tokens from " + oAuthTokenEndpoint);
14019 client_id = Object(_types_Auth__WEBPACK_IMPORTED_MODULE_3__["isCognitoHostedOpts"])(this._config) ? this._cognitoClientId : this._config.clientID;
14020 redirect_uri = Object(_types_Auth__WEBPACK_IMPORTED_MODULE_3__["isCognitoHostedOpts"])(this._config) ? this._config.redirectSignIn : this._config.redirectUri;
14021 code_verifier = _oauthStorage__WEBPACK_IMPORTED_MODULE_2__["getPKCE"]();
14022 oAuthTokenBody = __assign({
14023 grant_type: 'authorization_code',
14024 code: code,
14025 client_id: client_id,
14026 redirect_uri: redirect_uri
14027 }, code_verifier ? {
14028 code_verifier: code_verifier
14029 } : {});
14030 logger.debug("Calling token endpoint: " + oAuthTokenEndpoint + " with", oAuthTokenBody);
14031 body = Object.entries(oAuthTokenBody).map(function (_a) {
14032 var _b = __read(_a, 2),
14033 k = _b[0],
14034 v = _b[1];
14035
14036 return encodeURIComponent(k) + "=" + encodeURIComponent(v);
14037 }).join('&');
14038 return [4
14039 /*yield*/
14040 , fetch(oAuthTokenEndpoint, {
14041 method: 'POST',
14042 headers: {
14043 'Content-Type': 'application/x-www-form-urlencoded'
14044 },
14045 body: body
14046 })];
14047
14048 case 1:
14049 return [4
14050 /*yield*/
14051 , _b.sent().json()];
14052
14053 case 2:
14054 _a = _b.sent(), access_token = _a.access_token, refresh_token = _a.refresh_token, id_token = _a.id_token, error = _a.error;
14055
14056 if (error) {
14057 throw new Error(error);
14058 }
14059
14060 return [2
14061 /*return*/
14062 , {
14063 accessToken: access_token,
14064 refreshToken: refresh_token,
14065 idToken: id_token
14066 }];
14067 }
14068 });
14069 });
14070 };
14071
14072 OAuth.prototype._handleImplicitFlow = function (currentUrl) {
14073 return __awaiter(this, void 0, void 0, function () {
14074 var _a, id_token, access_token;
14075
14076 return __generator(this, function (_b) {
14077 _a = (Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).hash || '#').substr(1) // Remove # from returned code
14078 .split('&').map(function (pairings) {
14079 return pairings.split('=');
14080 }).reduce(function (accum, _a) {
14081 var _b;
14082
14083 var _c = __read(_a, 2),
14084 k = _c[0],
14085 v = _c[1];
14086
14087 return __assign(__assign({}, accum), (_b = {}, _b[k] = v, _b));
14088 }, {
14089 id_token: undefined,
14090 access_token: undefined
14091 }), id_token = _a.id_token, access_token = _a.access_token;
14092 dispatchAuthEvent('implicitFlow', {}, "Got tokens from " + currentUrl);
14093 logger.debug("Retrieving implicit tokens from " + currentUrl + " with");
14094 return [2
14095 /*return*/
14096 , {
14097 accessToken: access_token,
14098 idToken: id_token,
14099 refreshToken: null
14100 }];
14101 });
14102 });
14103 };
14104
14105 OAuth.prototype.handleAuthResponse = function (currentUrl) {
14106 return __awaiter(this, void 0, void 0, function () {
14107 var urlParams, error, error_description, state, _a, _b, e_1;
14108
14109 return __generator(this, function (_c) {
14110 switch (_c.label) {
14111 case 0:
14112 _c.trys.push([0, 5,, 6]);
14113
14114 urlParams = currentUrl ? __assign(__assign({}, (Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).hash || '#').substr(1).split('&').map(function (entry) {
14115 return entry.split('=');
14116 }).reduce(function (acc, _a) {
14117 var _b = __read(_a, 2),
14118 k = _b[0],
14119 v = _b[1];
14120
14121 return acc[k] = v, acc;
14122 }, {})), (Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).query || '').split('&').map(function (entry) {
14123 return entry.split('=');
14124 }).reduce(function (acc, _a) {
14125 var _b = __read(_a, 2),
14126 k = _b[0],
14127 v = _b[1];
14128
14129 return acc[k] = v, acc;
14130 }, {})) : {};
14131 error = urlParams.error, error_description = urlParams.error_description;
14132
14133 if (error) {
14134 throw new Error(error_description);
14135 }
14136
14137 state = this._validateState(urlParams);
14138 logger.debug("Starting " + this._config.responseType + " flow with " + currentUrl);
14139 if (!(this._config.responseType === 'code')) return [3
14140 /*break*/
14141 , 2];
14142 _a = [{}];
14143 return [4
14144 /*yield*/
14145 , this._handleCodeFlow(currentUrl)];
14146
14147 case 1:
14148 return [2
14149 /*return*/
14150 , __assign.apply(void 0, [__assign.apply(void 0, _a.concat([_c.sent()])), {
14151 state: state
14152 }])];
14153
14154 case 2:
14155 _b = [{}];
14156 return [4
14157 /*yield*/
14158 , this._handleImplicitFlow(currentUrl)];
14159
14160 case 3:
14161 return [2
14162 /*return*/
14163 , __assign.apply(void 0, [__assign.apply(void 0, _b.concat([_c.sent()])), {
14164 state: state
14165 }])];
14166
14167 case 4:
14168 return [3
14169 /*break*/
14170 , 6];
14171
14172 case 5:
14173 e_1 = _c.sent();
14174 logger.error("Error handling auth response.", e_1);
14175 throw e_1;
14176
14177 case 6:
14178 return [2
14179 /*return*/
14180 ];
14181 }
14182 });
14183 });
14184 };
14185
14186 OAuth.prototype._validateState = function (urlParams) {
14187 if (!urlParams) {
14188 return;
14189 }
14190
14191 var savedState = _oauthStorage__WEBPACK_IMPORTED_MODULE_2__["getState"]();
14192 var returnedState = urlParams.state; // This is because savedState only exists if the flow was initiated by Amplify
14193
14194 if (savedState && savedState !== returnedState) {
14195 throw new Error('Invalid state in OAuth flow');
14196 }
14197
14198 return returnedState;
14199 };
14200
14201 OAuth.prototype.signOut = function () {
14202 return __awaiter(this, void 0, void 0, function () {
14203 var oAuthLogoutEndpoint, client_id, signout_uri;
14204 return __generator(this, function (_a) {
14205 oAuthLogoutEndpoint = 'https://' + this._config.domain + '/logout?';
14206 client_id = Object(_types_Auth__WEBPACK_IMPORTED_MODULE_3__["isCognitoHostedOpts"])(this._config) ? this._cognitoClientId : this._config.oauth.clientID;
14207 signout_uri = Object(_types_Auth__WEBPACK_IMPORTED_MODULE_3__["isCognitoHostedOpts"])(this._config) ? this._config.redirectSignOut : this._config.returnTo;
14208 oAuthLogoutEndpoint += Object.entries({
14209 client_id: client_id,
14210 logout_uri: encodeURIComponent(signout_uri)
14211 }).map(function (_a) {
14212 var _b = __read(_a, 2),
14213 k = _b[0],
14214 v = _b[1];
14215
14216 return k + "=" + v;
14217 }).join('&');
14218 dispatchAuthEvent('oAuthSignOut', {
14219 oAuth: 'signOut'
14220 }, "Signing out from " + oAuthLogoutEndpoint);
14221 logger.debug("Signing out from " + oAuthLogoutEndpoint);
14222 return [2
14223 /*return*/
14224 , this._urlOpener(oAuthLogoutEndpoint, signout_uri)];
14225 });
14226 });
14227 };
14228
14229 OAuth.prototype._generateState = function (length) {
14230 var result = '';
14231 var i = length;
14232 var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
14233
14234 for (; i > 0; --i) {
14235 result += chars[Math.round(Math.random() * (chars.length - 1))];
14236 }
14237
14238 return result;
14239 };
14240
14241 OAuth.prototype._generateChallenge = function (code) {
14242 return this._base64URL(crypto_js_sha256__WEBPACK_IMPORTED_MODULE_5___default()(code));
14243 };
14244
14245 OAuth.prototype._base64URL = function (string) {
14246 return string.toString(crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_6___default.a).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
14247 };
14248
14249 OAuth.prototype._generateRandom = function (size) {
14250 var CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
14251 var buffer = new Uint8Array(size);
14252
14253 if (typeof window !== 'undefined' && !!window.crypto) {
14254 window.crypto.getRandomValues(buffer);
14255 } else {
14256 for (var i = 0; i < size; i += 1) {
14257 buffer[i] = Math.random() * CHARSET.length | 0;
14258 }
14259 }
14260
14261 return this._bufferToString(buffer);
14262 };
14263
14264 OAuth.prototype._bufferToString = function (buffer) {
14265 var CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
14266 var state = [];
14267
14268 for (var i = 0; i < buffer.byteLength; i += 1) {
14269 var index = buffer[i] % CHARSET.length;
14270 state.push(CHARSET[index]);
14271 }
14272
14273 return state.join('');
14274 };
14275
14276 return OAuth;
14277}();
14278
14279/* harmony default export */ __webpack_exports__["default"] = (OAuth);
14280
14281/***/ }),
14282
14283/***/ "./lib-esm/OAuth/oauthStorage.js":
14284/*!***************************************!*\
14285 !*** ./lib-esm/OAuth/oauthStorage.js ***!
14286 \***************************************/
14287/*! exports provided: setState, getState, setPKCE, getPKCE, clearAll */
14288/***/ (function(module, __webpack_exports__, __webpack_require__) {
14289
14290"use strict";
14291__webpack_require__.r(__webpack_exports__);
14292/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setState", function() { return setState; });
14293/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getState", function() { return getState; });
14294/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPKCE", function() { return setPKCE; });
14295/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPKCE", function() { return getPKCE; });
14296/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearAll", function() { return clearAll; });
14297/*
14298 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14299 *
14300 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14301 * the License. A copy of the License is located at
14302 *
14303 * http://aws.amazon.com/apache2.0/
14304 *
14305 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14306 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14307 * and limitations under the License.
14308 */
14309var setState = function setState(state) {
14310 window.sessionStorage.setItem('oauth_state', state);
14311};
14312var getState = function getState() {
14313 var oauth_state = window.sessionStorage.getItem('oauth_state');
14314 window.sessionStorage.removeItem('oauth_state');
14315 return oauth_state;
14316};
14317var setPKCE = function setPKCE(private_key) {
14318 window.sessionStorage.setItem('ouath_pkce_key', private_key);
14319};
14320var getPKCE = function getPKCE() {
14321 var ouath_pkce_key = window.sessionStorage.getItem('ouath_pkce_key');
14322 window.sessionStorage.removeItem('ouath_pkce_key');
14323 return ouath_pkce_key;
14324};
14325var clearAll = function clearAll() {
14326 window.sessionStorage.removeItem('ouath_pkce_key');
14327 window.sessionStorage.removeItem('oauth_state');
14328};
14329
14330/***/ }),
14331
14332/***/ "./lib-esm/OAuth/urlOpener.js":
14333/*!************************************!*\
14334 !*** ./lib-esm/OAuth/urlOpener.js ***!
14335 \************************************/
14336/*! exports provided: launchUri */
14337/***/ (function(module, __webpack_exports__, __webpack_require__) {
14338
14339"use strict";
14340__webpack_require__.r(__webpack_exports__);
14341/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "launchUri", function() { return launchUri; });
14342/*
14343 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14344 *
14345 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14346 * the License. A copy of the License is located at
14347 *
14348 * http://aws.amazon.com/apache2.0/
14349 *
14350 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14351 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14352 * and limitations under the License.
14353 */
14354var SELF = '_self';
14355var launchUri = function launchUri(url) {
14356 var windowProxy = window.open(url, SELF);
14357
14358 if (windowProxy) {
14359 return Promise.resolve(windowProxy);
14360 } else {
14361 return Promise.reject();
14362 }
14363};
14364
14365/***/ }),
14366
14367/***/ "./lib-esm/common/AuthErrorStrings.js":
14368/*!********************************************!*\
14369 !*** ./lib-esm/common/AuthErrorStrings.js ***!
14370 \********************************************/
14371/*! exports provided: AuthErrorStrings */
14372/***/ (function(module, __webpack_exports__, __webpack_require__) {
14373
14374"use strict";
14375__webpack_require__.r(__webpack_exports__);
14376/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthErrorStrings", function() { return AuthErrorStrings; });
14377var AuthErrorStrings;
14378
14379(function (AuthErrorStrings) {
14380 AuthErrorStrings["DEFAULT_MSG"] = "Authentication Error";
14381 AuthErrorStrings["EMPTY_EMAIL"] = "Email cannot be empty";
14382 AuthErrorStrings["EMPTY_PHONE"] = "Phone number cannot be empty";
14383 AuthErrorStrings["EMPTY_USERNAME"] = "Username cannot be empty";
14384 AuthErrorStrings["INVALID_USERNAME"] = "The username should either be a string or one of the sign in types";
14385 AuthErrorStrings["EMPTY_PASSWORD"] = "Password cannot be empty";
14386 AuthErrorStrings["EMPTY_CODE"] = "Confirmation code cannot be empty";
14387 AuthErrorStrings["SIGN_UP_ERROR"] = "Error creating account";
14388 AuthErrorStrings["NO_MFA"] = "No valid MFA method provided";
14389 AuthErrorStrings["INVALID_MFA"] = "Invalid MFA type";
14390 AuthErrorStrings["EMPTY_CHALLENGE"] = "Challenge response cannot be empty";
14391 AuthErrorStrings["NO_USER_SESSION"] = "Failed to get the session because the user is empty";
14392 AuthErrorStrings["NETWORK_ERROR"] = "Network Error";
14393 AuthErrorStrings["DEVICE_CONFIG"] = "Device tracking has not been configured in this User Pool";
14394})(AuthErrorStrings || (AuthErrorStrings = {}));
14395
14396/***/ }),
14397
14398/***/ "./lib-esm/index.js":
14399/*!**************************!*\
14400 !*** ./lib-esm/index.js ***!
14401 \**************************/
14402/*! exports provided: default, Auth, CognitoUser, CookieStorage, CognitoHostedUIIdentityProvider, appendToCognitoUserAgent, AuthErrorStrings */
14403/***/ (function(module, __webpack_exports__, __webpack_require__) {
14404
14405"use strict";
14406__webpack_require__.r(__webpack_exports__);
14407/* harmony import */ var _Auth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Auth */ "./lib-esm/Auth.js");
14408/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Auth", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["Auth"]; });
14409
14410/* harmony import */ var _types_Auth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types/Auth */ "./lib-esm/types/Auth.js");
14411/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoHostedUIIdentityProvider", function() { return _types_Auth__WEBPACK_IMPORTED_MODULE_1__["CognitoHostedUIIdentityProvider"]; });
14412
14413/* harmony import */ var amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! amazon-cognito-identity-js */ "../amazon-cognito-identity-js/es/index.js");
14414/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUser", function() { return amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUser"]; });
14415
14416/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CookieStorage", function() { return amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CookieStorage"]; });
14417
14418/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "appendToCognitoUserAgent", function() { return amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["appendToCognitoUserAgent"]; });
14419
14420/* harmony import */ var _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./common/AuthErrorStrings */ "./lib-esm/common/AuthErrorStrings.js");
14421/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthErrorStrings", function() { return _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_3__["AuthErrorStrings"]; });
14422
14423/*
14424 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14425 *
14426 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14427 * the License. A copy of the License is located at
14428 *
14429 * http://aws.amazon.com/apache2.0/
14430 *
14431 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14432 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14433 * and limitations under the License.
14434 */
14435
14436
14437
14438
14439/**
14440 * @deprecated use named import
14441 */
14442
14443/* harmony default export */ __webpack_exports__["default"] = (_Auth__WEBPACK_IMPORTED_MODULE_0__["Auth"]);
14444
14445
14446/***/ }),
14447
14448/***/ "./lib-esm/types/Auth.js":
14449/*!*******************************!*\
14450 !*** ./lib-esm/types/Auth.js ***!
14451 \*******************************/
14452/*! exports provided: CognitoHostedUIIdentityProvider, isFederatedSignInOptions, isFederatedSignInOptionsCustom, hasCustomState, isCognitoHostedOpts, AuthErrorTypes, isUsernamePasswordOpts */
14453/***/ (function(module, __webpack_exports__, __webpack_require__) {
14454
14455"use strict";
14456__webpack_require__.r(__webpack_exports__);
14457/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoHostedUIIdentityProvider", function() { return CognitoHostedUIIdentityProvider; });
14458/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFederatedSignInOptions", function() { return isFederatedSignInOptions; });
14459/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFederatedSignInOptionsCustom", function() { return isFederatedSignInOptionsCustom; });
14460/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasCustomState", function() { return hasCustomState; });
14461/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCognitoHostedOpts", function() { return isCognitoHostedOpts; });
14462/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthErrorTypes", function() { return AuthErrorTypes; });
14463/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isUsernamePasswordOpts", function() { return isUsernamePasswordOpts; });
14464/*
14465 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14466 *
14467 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14468 * the License. A copy of the License is located at
14469 *
14470 * http://aws.amazon.com/apache2.0/
14471 *
14472 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14473 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14474 * and limitations under the License.
14475 */
14476var CognitoHostedUIIdentityProvider;
14477
14478(function (CognitoHostedUIIdentityProvider) {
14479 CognitoHostedUIIdentityProvider["Cognito"] = "COGNITO";
14480 CognitoHostedUIIdentityProvider["Google"] = "Google";
14481 CognitoHostedUIIdentityProvider["Facebook"] = "Facebook";
14482 CognitoHostedUIIdentityProvider["Amazon"] = "LoginWithAmazon";
14483 CognitoHostedUIIdentityProvider["Apple"] = "SignInWithApple";
14484})(CognitoHostedUIIdentityProvider || (CognitoHostedUIIdentityProvider = {}));
14485
14486function isFederatedSignInOptions(obj) {
14487 var keys = ['provider'];
14488 return obj && !!keys.find(function (k) {
14489 return obj.hasOwnProperty(k);
14490 });
14491}
14492function isFederatedSignInOptionsCustom(obj) {
14493 var keys = ['customProvider'];
14494 return obj && !!keys.find(function (k) {
14495 return obj.hasOwnProperty(k);
14496 });
14497}
14498function hasCustomState(obj) {
14499 var keys = ['customState'];
14500 return obj && !!keys.find(function (k) {
14501 return obj.hasOwnProperty(k);
14502 });
14503}
14504function isCognitoHostedOpts(oauth) {
14505 return oauth.redirectSignIn !== undefined;
14506}
14507var AuthErrorTypes;
14508
14509(function (AuthErrorTypes) {
14510 AuthErrorTypes["NoConfig"] = "noConfig";
14511 AuthErrorTypes["MissingAuthConfig"] = "missingAuthConfig";
14512 AuthErrorTypes["EmptyUsername"] = "emptyUsername";
14513 AuthErrorTypes["InvalidUsername"] = "invalidUsername";
14514 AuthErrorTypes["EmptyPassword"] = "emptyPassword";
14515 AuthErrorTypes["EmptyCode"] = "emptyCode";
14516 AuthErrorTypes["SignUpError"] = "signUpError";
14517 AuthErrorTypes["NoMFA"] = "noMFA";
14518 AuthErrorTypes["InvalidMFA"] = "invalidMFA";
14519 AuthErrorTypes["EmptyChallengeResponse"] = "emptyChallengeResponse";
14520 AuthErrorTypes["NoUserSession"] = "noUserSession";
14521 AuthErrorTypes["Default"] = "default";
14522 AuthErrorTypes["DeviceConfig"] = "deviceConfig";
14523 AuthErrorTypes["NetworkError"] = "networkError";
14524})(AuthErrorTypes || (AuthErrorTypes = {}));
14525
14526function isUsernamePasswordOpts(obj) {
14527 return !!obj.username;
14528}
14529
14530/***/ }),
14531
14532/***/ "./lib-esm/types/index.js":
14533/*!********************************!*\
14534 !*** ./lib-esm/types/index.js ***!
14535 \********************************/
14536/*! exports provided: CognitoHostedUIIdentityProvider, isFederatedSignInOptions, isFederatedSignInOptionsCustom, hasCustomState, isCognitoHostedOpts, AuthErrorTypes, isUsernamePasswordOpts */
14537/***/ (function(module, __webpack_exports__, __webpack_require__) {
14538
14539"use strict";
14540__webpack_require__.r(__webpack_exports__);
14541/* harmony import */ var _Auth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Auth */ "./lib-esm/types/Auth.js");
14542/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoHostedUIIdentityProvider", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["CognitoHostedUIIdentityProvider"]; });
14543
14544/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isFederatedSignInOptions", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptions"]; });
14545
14546/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isFederatedSignInOptionsCustom", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptionsCustom"]; });
14547
14548/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasCustomState", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["hasCustomState"]; });
14549
14550/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isCognitoHostedOpts", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["isCognitoHostedOpts"]; });
14551
14552/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthErrorTypes", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["AuthErrorTypes"]; });
14553
14554/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isUsernamePasswordOpts", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["isUsernamePasswordOpts"]; });
14555
14556/*
14557 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14558 *
14559 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14560 * the License. A copy of the License is located at
14561 *
14562 * http://aws.amazon.com/apache2.0/
14563 *
14564 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14565 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14566 * and limitations under the License.
14567 */
14568
14569
14570/***/ }),
14571
14572/***/ "./lib-esm/urlListener.js":
14573/*!********************************!*\
14574 !*** ./lib-esm/urlListener.js ***!
14575 \********************************/
14576/*! exports provided: default */
14577/***/ (function(module, __webpack_exports__, __webpack_require__) {
14578
14579"use strict";
14580__webpack_require__.r(__webpack_exports__);
14581/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
14582/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__);
14583/*
14584 * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14585 *
14586 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14587 * the License. A copy of the License is located at
14588 *
14589 * http://aws.amazon.com/apache2.0/
14590 *
14591 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14592 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14593 * and limitations under the License.
14594 */
14595
14596/* harmony default export */ __webpack_exports__["default"] = (function (callback) {
14597 if (_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["JS"].browserOrNode().isBrowser && window.location) {
14598 var url = window.location.href;
14599 callback({
14600 url: url
14601 });
14602 } else if (_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["JS"].browserOrNode().isNode) {
14603 // continue building on ssr
14604 (function () {}); // noop
14605
14606 } else {
14607 throw new Error('Not supported');
14608 }
14609});
14610
14611/***/ }),
14612
14613/***/ "./node_modules/crypto-js/core.js":
14614/*!****************************************!*\
14615 !*** ./node_modules/crypto-js/core.js ***!
14616 \****************************************/
14617/*! no static exports found */
14618/***/ (function(module, exports, __webpack_require__) {
14619
14620/* WEBPACK VAR INJECTION */(function(global) {;(function (root, factory) {
14621 if (true) {
14622 // CommonJS
14623 module.exports = exports = factory();
14624 }
14625 else {}
14626}(this, function () {
14627
14628 /*globals window, global, require*/
14629
14630 /**
14631 * CryptoJS core components.
14632 */
14633 var CryptoJS = CryptoJS || (function (Math, undefined) {
14634
14635 var crypto;
14636
14637 // Native crypto from window (Browser)
14638 if (typeof window !== 'undefined' && window.crypto) {
14639 crypto = window.crypto;
14640 }
14641
14642 // Native crypto in web worker (Browser)
14643 if (typeof self !== 'undefined' && self.crypto) {
14644 crypto = self.crypto;
14645 }
14646
14647 // Native crypto from worker
14648 if (typeof globalThis !== 'undefined' && globalThis.crypto) {
14649 crypto = globalThis.crypto;
14650 }
14651
14652 // Native (experimental IE 11) crypto from window (Browser)
14653 if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
14654 crypto = window.msCrypto;
14655 }
14656
14657 // Native crypto from global (NodeJS)
14658 if (!crypto && typeof global !== 'undefined' && global.crypto) {
14659 crypto = global.crypto;
14660 }
14661
14662 // Native crypto import via require (NodeJS)
14663 if (!crypto && "function" === 'function') {
14664 try {
14665 crypto = __webpack_require__(/*! crypto */ 2);
14666 } catch (err) {}
14667 }
14668
14669 /*
14670 * Cryptographically secure pseudorandom number generator
14671 *
14672 * As Math.random() is cryptographically not safe to use
14673 */
14674 var cryptoSecureRandomInt = function () {
14675 if (crypto) {
14676 // Use getRandomValues method (Browser)
14677 if (typeof crypto.getRandomValues === 'function') {
14678 try {
14679 return crypto.getRandomValues(new Uint32Array(1))[0];
14680 } catch (err) {}
14681 }
14682
14683 // Use randomBytes method (NodeJS)
14684 if (typeof crypto.randomBytes === 'function') {
14685 try {
14686 return crypto.randomBytes(4).readInt32LE();
14687 } catch (err) {}
14688 }
14689 }
14690
14691 throw new Error('Native crypto module could not be used to get secure random number.');
14692 };
14693
14694 /*
14695 * Local polyfill of Object.create
14696
14697 */
14698 var create = Object.create || (function () {
14699 function F() {}
14700
14701 return function (obj) {
14702 var subtype;
14703
14704 F.prototype = obj;
14705
14706 subtype = new F();
14707
14708 F.prototype = null;
14709
14710 return subtype;
14711 };
14712 }());
14713
14714 /**
14715 * CryptoJS namespace.
14716 */
14717 var C = {};
14718
14719 /**
14720 * Library namespace.
14721 */
14722 var C_lib = C.lib = {};
14723
14724 /**
14725 * Base object for prototypal inheritance.
14726 */
14727 var Base = C_lib.Base = (function () {
14728
14729
14730 return {
14731 /**
14732 * Creates a new object that inherits from this object.
14733 *
14734 * @param {Object} overrides Properties to copy into the new object.
14735 *
14736 * @return {Object} The new object.
14737 *
14738 * @static
14739 *
14740 * @example
14741 *
14742 * var MyType = CryptoJS.lib.Base.extend({
14743 * field: 'value',
14744 *
14745 * method: function () {
14746 * }
14747 * });
14748 */
14749 extend: function (overrides) {
14750 // Spawn
14751 var subtype = create(this);
14752
14753 // Augment
14754 if (overrides) {
14755 subtype.mixIn(overrides);
14756 }
14757
14758 // Create default initializer
14759 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
14760 subtype.init = function () {
14761 subtype.$super.init.apply(this, arguments);
14762 };
14763 }
14764
14765 // Initializer's prototype is the subtype object
14766 subtype.init.prototype = subtype;
14767
14768 // Reference supertype
14769 subtype.$super = this;
14770
14771 return subtype;
14772 },
14773
14774 /**
14775 * Extends this object and runs the init method.
14776 * Arguments to create() will be passed to init().
14777 *
14778 * @return {Object} The new object.
14779 *
14780 * @static
14781 *
14782 * @example
14783 *
14784 * var instance = MyType.create();
14785 */
14786 create: function () {
14787 var instance = this.extend();
14788 instance.init.apply(instance, arguments);
14789
14790 return instance;
14791 },
14792
14793 /**
14794 * Initializes a newly created object.
14795 * Override this method to add some logic when your objects are created.
14796 *
14797 * @example
14798 *
14799 * var MyType = CryptoJS.lib.Base.extend({
14800 * init: function () {
14801 * // ...
14802 * }
14803 * });
14804 */
14805 init: function () {
14806 },
14807
14808 /**
14809 * Copies properties into this object.
14810 *
14811 * @param {Object} properties The properties to mix in.
14812 *
14813 * @example
14814 *
14815 * MyType.mixIn({
14816 * field: 'value'
14817 * });
14818 */
14819 mixIn: function (properties) {
14820 for (var propertyName in properties) {
14821 if (properties.hasOwnProperty(propertyName)) {
14822 this[propertyName] = properties[propertyName];
14823 }
14824 }
14825
14826 // IE won't copy toString using the loop above
14827 if (properties.hasOwnProperty('toString')) {
14828 this.toString = properties.toString;
14829 }
14830 },
14831
14832 /**
14833 * Creates a copy of this object.
14834 *
14835 * @return {Object} The clone.
14836 *
14837 * @example
14838 *
14839 * var clone = instance.clone();
14840 */
14841 clone: function () {
14842 return this.init.prototype.extend(this);
14843 }
14844 };
14845 }());
14846
14847 /**
14848 * An array of 32-bit words.
14849 *
14850 * @property {Array} words The array of 32-bit words.
14851 * @property {number} sigBytes The number of significant bytes in this word array.
14852 */
14853 var WordArray = C_lib.WordArray = Base.extend({
14854 /**
14855 * Initializes a newly created word array.
14856 *
14857 * @param {Array} words (Optional) An array of 32-bit words.
14858 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
14859 *
14860 * @example
14861 *
14862 * var wordArray = CryptoJS.lib.WordArray.create();
14863 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
14864 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
14865 */
14866 init: function (words, sigBytes) {
14867 words = this.words = words || [];
14868
14869 if (sigBytes != undefined) {
14870 this.sigBytes = sigBytes;
14871 } else {
14872 this.sigBytes = words.length * 4;
14873 }
14874 },
14875
14876 /**
14877 * Converts this word array to a string.
14878 *
14879 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
14880 *
14881 * @return {string} The stringified word array.
14882 *
14883 * @example
14884 *
14885 * var string = wordArray + '';
14886 * var string = wordArray.toString();
14887 * var string = wordArray.toString(CryptoJS.enc.Utf8);
14888 */
14889 toString: function (encoder) {
14890 return (encoder || Hex).stringify(this);
14891 },
14892
14893 /**
14894 * Concatenates a word array to this word array.
14895 *
14896 * @param {WordArray} wordArray The word array to append.
14897 *
14898 * @return {WordArray} This word array.
14899 *
14900 * @example
14901 *
14902 * wordArray1.concat(wordArray2);
14903 */
14904 concat: function (wordArray) {
14905 // Shortcuts
14906 var thisWords = this.words;
14907 var thatWords = wordArray.words;
14908 var thisSigBytes = this.sigBytes;
14909 var thatSigBytes = wordArray.sigBytes;
14910
14911 // Clamp excess bits
14912 this.clamp();
14913
14914 // Concat
14915 if (thisSigBytes % 4) {
14916 // Copy one byte at a time
14917 for (var i = 0; i < thatSigBytes; i++) {
14918 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
14919 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
14920 }
14921 } else {
14922 // Copy one word at a time
14923 for (var j = 0; j < thatSigBytes; j += 4) {
14924 thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
14925 }
14926 }
14927 this.sigBytes += thatSigBytes;
14928
14929 // Chainable
14930 return this;
14931 },
14932
14933 /**
14934 * Removes insignificant bits.
14935 *
14936 * @example
14937 *
14938 * wordArray.clamp();
14939 */
14940 clamp: function () {
14941 // Shortcuts
14942 var words = this.words;
14943 var sigBytes = this.sigBytes;
14944
14945 // Clamp
14946 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
14947 words.length = Math.ceil(sigBytes / 4);
14948 },
14949
14950 /**
14951 * Creates a copy of this word array.
14952 *
14953 * @return {WordArray} The clone.
14954 *
14955 * @example
14956 *
14957 * var clone = wordArray.clone();
14958 */
14959 clone: function () {
14960 var clone = Base.clone.call(this);
14961 clone.words = this.words.slice(0);
14962
14963 return clone;
14964 },
14965
14966 /**
14967 * Creates a word array filled with random bytes.
14968 *
14969 * @param {number} nBytes The number of random bytes to generate.
14970 *
14971 * @return {WordArray} The random word array.
14972 *
14973 * @static
14974 *
14975 * @example
14976 *
14977 * var wordArray = CryptoJS.lib.WordArray.random(16);
14978 */
14979 random: function (nBytes) {
14980 var words = [];
14981
14982 for (var i = 0; i < nBytes; i += 4) {
14983 words.push(cryptoSecureRandomInt());
14984 }
14985
14986 return new WordArray.init(words, nBytes);
14987 }
14988 });
14989
14990 /**
14991 * Encoder namespace.
14992 */
14993 var C_enc = C.enc = {};
14994
14995 /**
14996 * Hex encoding strategy.
14997 */
14998 var Hex = C_enc.Hex = {
14999 /**
15000 * Converts a word array to a hex string.
15001 *
15002 * @param {WordArray} wordArray The word array.
15003 *
15004 * @return {string} The hex string.
15005 *
15006 * @static
15007 *
15008 * @example
15009 *
15010 * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
15011 */
15012 stringify: function (wordArray) {
15013 // Shortcuts
15014 var words = wordArray.words;
15015 var sigBytes = wordArray.sigBytes;
15016
15017 // Convert
15018 var hexChars = [];
15019 for (var i = 0; i < sigBytes; i++) {
15020 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
15021 hexChars.push((bite >>> 4).toString(16));
15022 hexChars.push((bite & 0x0f).toString(16));
15023 }
15024
15025 return hexChars.join('');
15026 },
15027
15028 /**
15029 * Converts a hex string to a word array.
15030 *
15031 * @param {string} hexStr The hex string.
15032 *
15033 * @return {WordArray} The word array.
15034 *
15035 * @static
15036 *
15037 * @example
15038 *
15039 * var wordArray = CryptoJS.enc.Hex.parse(hexString);
15040 */
15041 parse: function (hexStr) {
15042 // Shortcut
15043 var hexStrLength = hexStr.length;
15044
15045 // Convert
15046 var words = [];
15047 for (var i = 0; i < hexStrLength; i += 2) {
15048 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
15049 }
15050
15051 return new WordArray.init(words, hexStrLength / 2);
15052 }
15053 };
15054
15055 /**
15056 * Latin1 encoding strategy.
15057 */
15058 var Latin1 = C_enc.Latin1 = {
15059 /**
15060 * Converts a word array to a Latin1 string.
15061 *
15062 * @param {WordArray} wordArray The word array.
15063 *
15064 * @return {string} The Latin1 string.
15065 *
15066 * @static
15067 *
15068 * @example
15069 *
15070 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
15071 */
15072 stringify: function (wordArray) {
15073 // Shortcuts
15074 var words = wordArray.words;
15075 var sigBytes = wordArray.sigBytes;
15076
15077 // Convert
15078 var latin1Chars = [];
15079 for (var i = 0; i < sigBytes; i++) {
15080 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
15081 latin1Chars.push(String.fromCharCode(bite));
15082 }
15083
15084 return latin1Chars.join('');
15085 },
15086
15087 /**
15088 * Converts a Latin1 string to a word array.
15089 *
15090 * @param {string} latin1Str The Latin1 string.
15091 *
15092 * @return {WordArray} The word array.
15093 *
15094 * @static
15095 *
15096 * @example
15097 *
15098 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
15099 */
15100 parse: function (latin1Str) {
15101 // Shortcut
15102 var latin1StrLength = latin1Str.length;
15103
15104 // Convert
15105 var words = [];
15106 for (var i = 0; i < latin1StrLength; i++) {
15107 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
15108 }
15109
15110 return new WordArray.init(words, latin1StrLength);
15111 }
15112 };
15113
15114 /**
15115 * UTF-8 encoding strategy.
15116 */
15117 var Utf8 = C_enc.Utf8 = {
15118 /**
15119 * Converts a word array to a UTF-8 string.
15120 *
15121 * @param {WordArray} wordArray The word array.
15122 *
15123 * @return {string} The UTF-8 string.
15124 *
15125 * @static
15126 *
15127 * @example
15128 *
15129 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
15130 */
15131 stringify: function (wordArray) {
15132 try {
15133 return decodeURIComponent(escape(Latin1.stringify(wordArray)));
15134 } catch (e) {
15135 throw new Error('Malformed UTF-8 data');
15136 }
15137 },
15138
15139 /**
15140 * Converts a UTF-8 string to a word array.
15141 *
15142 * @param {string} utf8Str The UTF-8 string.
15143 *
15144 * @return {WordArray} The word array.
15145 *
15146 * @static
15147 *
15148 * @example
15149 *
15150 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
15151 */
15152 parse: function (utf8Str) {
15153 return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
15154 }
15155 };
15156
15157 /**
15158 * Abstract buffered block algorithm template.
15159 *
15160 * The property blockSize must be implemented in a concrete subtype.
15161 *
15162 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
15163 */
15164 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
15165 /**
15166 * Resets this block algorithm's data buffer to its initial state.
15167 *
15168 * @example
15169 *
15170 * bufferedBlockAlgorithm.reset();
15171 */
15172 reset: function () {
15173 // Initial values
15174 this._data = new WordArray.init();
15175 this._nDataBytes = 0;
15176 },
15177
15178 /**
15179 * Adds new data to this block algorithm's buffer.
15180 *
15181 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
15182 *
15183 * @example
15184 *
15185 * bufferedBlockAlgorithm._append('data');
15186 * bufferedBlockAlgorithm._append(wordArray);
15187 */
15188 _append: function (data) {
15189 // Convert string to WordArray, else assume WordArray already
15190 if (typeof data == 'string') {
15191 data = Utf8.parse(data);
15192 }
15193
15194 // Append
15195 this._data.concat(data);
15196 this._nDataBytes += data.sigBytes;
15197 },
15198
15199 /**
15200 * Processes available data blocks.
15201 *
15202 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
15203 *
15204 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
15205 *
15206 * @return {WordArray} The processed data.
15207 *
15208 * @example
15209 *
15210 * var processedData = bufferedBlockAlgorithm._process();
15211 * var processedData = bufferedBlockAlgorithm._process(!!'flush');
15212 */
15213 _process: function (doFlush) {
15214 var processedWords;
15215
15216 // Shortcuts
15217 var data = this._data;
15218 var dataWords = data.words;
15219 var dataSigBytes = data.sigBytes;
15220 var blockSize = this.blockSize;
15221 var blockSizeBytes = blockSize * 4;
15222
15223 // Count blocks ready
15224 var nBlocksReady = dataSigBytes / blockSizeBytes;
15225 if (doFlush) {
15226 // Round up to include partial blocks
15227 nBlocksReady = Math.ceil(nBlocksReady);
15228 } else {
15229 // Round down to include only full blocks,
15230 // less the number of blocks that must remain in the buffer
15231 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
15232 }
15233
15234 // Count words ready
15235 var nWordsReady = nBlocksReady * blockSize;
15236
15237 // Count bytes ready
15238 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
15239
15240 // Process blocks
15241 if (nWordsReady) {
15242 for (var offset = 0; offset < nWordsReady; offset += blockSize) {
15243 // Perform concrete-algorithm logic
15244 this._doProcessBlock(dataWords, offset);
15245 }
15246
15247 // Remove processed words
15248 processedWords = dataWords.splice(0, nWordsReady);
15249 data.sigBytes -= nBytesReady;
15250 }
15251
15252 // Return processed words
15253 return new WordArray.init(processedWords, nBytesReady);
15254 },
15255
15256 /**
15257 * Creates a copy of this object.
15258 *
15259 * @return {Object} The clone.
15260 *
15261 * @example
15262 *
15263 * var clone = bufferedBlockAlgorithm.clone();
15264 */
15265 clone: function () {
15266 var clone = Base.clone.call(this);
15267 clone._data = this._data.clone();
15268
15269 return clone;
15270 },
15271
15272 _minBufferSize: 0
15273 });
15274
15275 /**
15276 * Abstract hasher template.
15277 *
15278 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
15279 */
15280 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
15281 /**
15282 * Configuration options.
15283 */
15284 cfg: Base.extend(),
15285
15286 /**
15287 * Initializes a newly created hasher.
15288 *
15289 * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
15290 *
15291 * @example
15292 *
15293 * var hasher = CryptoJS.algo.SHA256.create();
15294 */
15295 init: function (cfg) {
15296 // Apply config defaults
15297 this.cfg = this.cfg.extend(cfg);
15298
15299 // Set initial values
15300 this.reset();
15301 },
15302
15303 /**
15304 * Resets this hasher to its initial state.
15305 *
15306 * @example
15307 *
15308 * hasher.reset();
15309 */
15310 reset: function () {
15311 // Reset data buffer
15312 BufferedBlockAlgorithm.reset.call(this);
15313
15314 // Perform concrete-hasher logic
15315 this._doReset();
15316 },
15317
15318 /**
15319 * Updates this hasher with a message.
15320 *
15321 * @param {WordArray|string} messageUpdate The message to append.
15322 *
15323 * @return {Hasher} This hasher.
15324 *
15325 * @example
15326 *
15327 * hasher.update('message');
15328 * hasher.update(wordArray);
15329 */
15330 update: function (messageUpdate) {
15331 // Append
15332 this._append(messageUpdate);
15333
15334 // Update the hash
15335 this._process();
15336
15337 // Chainable
15338 return this;
15339 },
15340
15341 /**
15342 * Finalizes the hash computation.
15343 * Note that the finalize operation is effectively a destructive, read-once operation.
15344 *
15345 * @param {WordArray|string} messageUpdate (Optional) A final message update.
15346 *
15347 * @return {WordArray} The hash.
15348 *
15349 * @example
15350 *
15351 * var hash = hasher.finalize();
15352 * var hash = hasher.finalize('message');
15353 * var hash = hasher.finalize(wordArray);
15354 */
15355 finalize: function (messageUpdate) {
15356 // Final message update
15357 if (messageUpdate) {
15358 this._append(messageUpdate);
15359 }
15360
15361 // Perform concrete-hasher logic
15362 var hash = this._doFinalize();
15363
15364 return hash;
15365 },
15366
15367 blockSize: 512/32,
15368
15369 /**
15370 * Creates a shortcut function to a hasher's object interface.
15371 *
15372 * @param {Hasher} hasher The hasher to create a helper for.
15373 *
15374 * @return {Function} The shortcut function.
15375 *
15376 * @static
15377 *
15378 * @example
15379 *
15380 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
15381 */
15382 _createHelper: function (hasher) {
15383 return function (message, cfg) {
15384 return new hasher.init(cfg).finalize(message);
15385 };
15386 },
15387
15388 /**
15389 * Creates a shortcut function to the HMAC's object interface.
15390 *
15391 * @param {Hasher} hasher The hasher to use in this HMAC helper.
15392 *
15393 * @return {Function} The shortcut function.
15394 *
15395 * @static
15396 *
15397 * @example
15398 *
15399 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
15400 */
15401 _createHmacHelper: function (hasher) {
15402 return function (message, key) {
15403 return new C_algo.HMAC.init(hasher, key).finalize(message);
15404 };
15405 }
15406 });
15407
15408 /**
15409 * Algorithm namespace.
15410 */
15411 var C_algo = C.algo = {};
15412
15413 return C;
15414 }(Math));
15415
15416
15417 return CryptoJS;
15418
15419}));
15420/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
15421
15422/***/ }),
15423
15424/***/ "./node_modules/crypto-js/enc-base64.js":
15425/*!**********************************************!*\
15426 !*** ./node_modules/crypto-js/enc-base64.js ***!
15427 \**********************************************/
15428/*! no static exports found */
15429/***/ (function(module, exports, __webpack_require__) {
15430
15431;(function (root, factory) {
15432 if (true) {
15433 // CommonJS
15434 module.exports = exports = factory(__webpack_require__(/*! ./core */ "./node_modules/crypto-js/core.js"));
15435 }
15436 else {}
15437}(this, function (CryptoJS) {
15438
15439 (function () {
15440 // Shortcuts
15441 var C = CryptoJS;
15442 var C_lib = C.lib;
15443 var WordArray = C_lib.WordArray;
15444 var C_enc = C.enc;
15445
15446 /**
15447 * Base64 encoding strategy.
15448 */
15449 var Base64 = C_enc.Base64 = {
15450 /**
15451 * Converts a word array to a Base64 string.
15452 *
15453 * @param {WordArray} wordArray The word array.
15454 *
15455 * @return {string} The Base64 string.
15456 *
15457 * @static
15458 *
15459 * @example
15460 *
15461 * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
15462 */
15463 stringify: function (wordArray) {
15464 // Shortcuts
15465 var words = wordArray.words;
15466 var sigBytes = wordArray.sigBytes;
15467 var map = this._map;
15468
15469 // Clamp excess bits
15470 wordArray.clamp();
15471
15472 // Convert
15473 var base64Chars = [];
15474 for (var i = 0; i < sigBytes; i += 3) {
15475 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
15476 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
15477 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
15478
15479 var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
15480
15481 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
15482 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
15483 }
15484 }
15485
15486 // Add padding
15487 var paddingChar = map.charAt(64);
15488 if (paddingChar) {
15489 while (base64Chars.length % 4) {
15490 base64Chars.push(paddingChar);
15491 }
15492 }
15493
15494 return base64Chars.join('');
15495 },
15496
15497 /**
15498 * Converts a Base64 string to a word array.
15499 *
15500 * @param {string} base64Str The Base64 string.
15501 *
15502 * @return {WordArray} The word array.
15503 *
15504 * @static
15505 *
15506 * @example
15507 *
15508 * var wordArray = CryptoJS.enc.Base64.parse(base64String);
15509 */
15510 parse: function (base64Str) {
15511 // Shortcuts
15512 var base64StrLength = base64Str.length;
15513 var map = this._map;
15514 var reverseMap = this._reverseMap;
15515
15516 if (!reverseMap) {
15517 reverseMap = this._reverseMap = [];
15518 for (var j = 0; j < map.length; j++) {
15519 reverseMap[map.charCodeAt(j)] = j;
15520 }
15521 }
15522
15523 // Ignore padding
15524 var paddingChar = map.charAt(64);
15525 if (paddingChar) {
15526 var paddingIndex = base64Str.indexOf(paddingChar);
15527 if (paddingIndex !== -1) {
15528 base64StrLength = paddingIndex;
15529 }
15530 }
15531
15532 // Convert
15533 return parseLoop(base64Str, base64StrLength, reverseMap);
15534
15535 },
15536
15537 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
15538 };
15539
15540 function parseLoop(base64Str, base64StrLength, reverseMap) {
15541 var words = [];
15542 var nBytes = 0;
15543 for (var i = 0; i < base64StrLength; i++) {
15544 if (i % 4) {
15545 var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
15546 var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
15547 var bitsCombined = bits1 | bits2;
15548 words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
15549 nBytes++;
15550 }
15551 }
15552 return WordArray.create(words, nBytes);
15553 }
15554 }());
15555
15556
15557 return CryptoJS.enc.Base64;
15558
15559}));
15560
15561/***/ }),
15562
15563/***/ "./node_modules/crypto-js/sha256.js":
15564/*!******************************************!*\
15565 !*** ./node_modules/crypto-js/sha256.js ***!
15566 \******************************************/
15567/*! no static exports found */
15568/***/ (function(module, exports, __webpack_require__) {
15569
15570;(function (root, factory) {
15571 if (true) {
15572 // CommonJS
15573 module.exports = exports = factory(__webpack_require__(/*! ./core */ "./node_modules/crypto-js/core.js"));
15574 }
15575 else {}
15576}(this, function (CryptoJS) {
15577
15578 (function (Math) {
15579 // Shortcuts
15580 var C = CryptoJS;
15581 var C_lib = C.lib;
15582 var WordArray = C_lib.WordArray;
15583 var Hasher = C_lib.Hasher;
15584 var C_algo = C.algo;
15585
15586 // Initialization and round constants tables
15587 var H = [];
15588 var K = [];
15589
15590 // Compute constants
15591 (function () {
15592 function isPrime(n) {
15593 var sqrtN = Math.sqrt(n);
15594 for (var factor = 2; factor <= sqrtN; factor++) {
15595 if (!(n % factor)) {
15596 return false;
15597 }
15598 }
15599
15600 return true;
15601 }
15602
15603 function getFractionalBits(n) {
15604 return ((n - (n | 0)) * 0x100000000) | 0;
15605 }
15606
15607 var n = 2;
15608 var nPrime = 0;
15609 while (nPrime < 64) {
15610 if (isPrime(n)) {
15611 if (nPrime < 8) {
15612 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
15613 }
15614 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
15615
15616 nPrime++;
15617 }
15618
15619 n++;
15620 }
15621 }());
15622
15623 // Reusable object
15624 var W = [];
15625
15626 /**
15627 * SHA-256 hash algorithm.
15628 */
15629 var SHA256 = C_algo.SHA256 = Hasher.extend({
15630 _doReset: function () {
15631 this._hash = new WordArray.init(H.slice(0));
15632 },
15633
15634 _doProcessBlock: function (M, offset) {
15635 // Shortcut
15636 var H = this._hash.words;
15637
15638 // Working variables
15639 var a = H[0];
15640 var b = H[1];
15641 var c = H[2];
15642 var d = H[3];
15643 var e = H[4];
15644 var f = H[5];
15645 var g = H[6];
15646 var h = H[7];
15647
15648 // Computation
15649 for (var i = 0; i < 64; i++) {
15650 if (i < 16) {
15651 W[i] = M[offset + i] | 0;
15652 } else {
15653 var gamma0x = W[i - 15];
15654 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
15655 ((gamma0x << 14) | (gamma0x >>> 18)) ^
15656 (gamma0x >>> 3);
15657
15658 var gamma1x = W[i - 2];
15659 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
15660 ((gamma1x << 13) | (gamma1x >>> 19)) ^
15661 (gamma1x >>> 10);
15662
15663 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
15664 }
15665
15666 var ch = (e & f) ^ (~e & g);
15667 var maj = (a & b) ^ (a & c) ^ (b & c);
15668
15669 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
15670 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
15671
15672 var t1 = h + sigma1 + ch + K[i] + W[i];
15673 var t2 = sigma0 + maj;
15674
15675 h = g;
15676 g = f;
15677 f = e;
15678 e = (d + t1) | 0;
15679 d = c;
15680 c = b;
15681 b = a;
15682 a = (t1 + t2) | 0;
15683 }
15684
15685 // Intermediate hash value
15686 H[0] = (H[0] + a) | 0;
15687 H[1] = (H[1] + b) | 0;
15688 H[2] = (H[2] + c) | 0;
15689 H[3] = (H[3] + d) | 0;
15690 H[4] = (H[4] + e) | 0;
15691 H[5] = (H[5] + f) | 0;
15692 H[6] = (H[6] + g) | 0;
15693 H[7] = (H[7] + h) | 0;
15694 },
15695
15696 _doFinalize: function () {
15697 // Shortcuts
15698 var data = this._data;
15699 var dataWords = data.words;
15700
15701 var nBitsTotal = this._nDataBytes * 8;
15702 var nBitsLeft = data.sigBytes * 8;
15703
15704 // Add padding
15705 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
15706 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
15707 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
15708 data.sigBytes = dataWords.length * 4;
15709
15710 // Hash final blocks
15711 this._process();
15712
15713 // Return final computed hash
15714 return this._hash;
15715 },
15716
15717 clone: function () {
15718 var clone = Hasher.clone.call(this);
15719 clone._hash = this._hash.clone();
15720
15721 return clone;
15722 }
15723 });
15724
15725 /**
15726 * Shortcut function to the hasher's object interface.
15727 *
15728 * @param {WordArray|string} message The message to hash.
15729 *
15730 * @return {WordArray} The hash.
15731 *
15732 * @static
15733 *
15734 * @example
15735 *
15736 * var hash = CryptoJS.SHA256('message');
15737 * var hash = CryptoJS.SHA256(wordArray);
15738 */
15739 C.SHA256 = Hasher._createHelper(SHA256);
15740
15741 /**
15742 * Shortcut function to the HMAC's object interface.
15743 *
15744 * @param {WordArray|string} message The message to hash.
15745 * @param {WordArray|string} key The secret key.
15746 *
15747 * @return {WordArray} The HMAC.
15748 *
15749 * @static
15750 *
15751 * @example
15752 *
15753 * var hmac = CryptoJS.HmacSHA256(message, key);
15754 */
15755 C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
15756 }(Math));
15757
15758
15759 return CryptoJS.SHA256;
15760
15761}));
15762
15763/***/ }),
15764
15765/***/ 0:
15766/*!************************!*\
15767 !*** crypto (ignored) ***!
15768 \************************/
15769/*! no static exports found */
15770/***/ (function(module, exports) {
15771
15772/* (ignored) */
15773
15774/***/ }),
15775
15776/***/ 1:
15777/*!************************!*\
15778 !*** crypto (ignored) ***!
15779 \************************/
15780/*! no static exports found */
15781/***/ (function(module, exports) {
15782
15783/* (ignored) */
15784
15785/***/ }),
15786
15787/***/ 2:
15788/*!************************!*\
15789 !*** crypto (ignored) ***!
15790 \************************/
15791/*! no static exports found */
15792/***/ (function(module, exports) {
15793
15794/* (ignored) */
15795
15796/***/ }),
15797
15798/***/ "@aws-amplify/core":
15799/*!***********************************!*\
15800 !*** external "aws_amplify_core" ***!
15801 \***********************************/
15802/*! no static exports found */
15803/***/ (function(module, exports) {
15804
15805module.exports = __WEBPACK_EXTERNAL_MODULE__aws_amplify_core__;
15806
15807/***/ })
15808
15809/******/ });
15810});
15811//# sourceMappingURL=aws-amplify-auth.js.map
\No newline at end of file