UNPKG

513 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 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3968 * SPDX-License-Identifier: Apache-2.0
3969 */
3970
3971/** @class */
3972var AuthenticationDetails = /*#__PURE__*/function () {
3973 /**
3974 * Constructs a new AuthenticationDetails object
3975 * @param {object=} data Creation options.
3976 * @param {string} data.Username User being authenticated.
3977 * @param {string} data.Password Plain-text password to authenticate with.
3978 * @param {(AttributeArg[])?} data.ValidationData Application extra metadata.
3979 * @param {(AttributeArg[])?} data.AuthParamaters Authentication paramaters for custom auth.
3980 */
3981 function AuthenticationDetails(data) {
3982 var _ref = data || {},
3983 ValidationData = _ref.ValidationData,
3984 Username = _ref.Username,
3985 Password = _ref.Password,
3986 AuthParameters = _ref.AuthParameters,
3987 ClientMetadata = _ref.ClientMetadata;
3988
3989 this.validationData = ValidationData || {};
3990 this.authParameters = AuthParameters || {};
3991 this.clientMetadata = ClientMetadata || {};
3992 this.username = Username;
3993 this.password = Password;
3994 }
3995 /**
3996 * @returns {string} the record's username
3997 */
3998
3999
4000 var _proto = AuthenticationDetails.prototype;
4001
4002 _proto.getUsername = function getUsername() {
4003 return this.username;
4004 }
4005 /**
4006 * @returns {string} the record's password
4007 */
4008 ;
4009
4010 _proto.getPassword = function getPassword() {
4011 return this.password;
4012 }
4013 /**
4014 * @returns {Array} the record's validationData
4015 */
4016 ;
4017
4018 _proto.getValidationData = function getValidationData() {
4019 return this.validationData;
4020 }
4021 /**
4022 * @returns {Array} the record's authParameters
4023 */
4024 ;
4025
4026 _proto.getAuthParameters = function getAuthParameters() {
4027 return this.authParameters;
4028 }
4029 /**
4030 * @returns {ClientMetadata} the clientMetadata for a Lambda trigger
4031 */
4032 ;
4033
4034 _proto.getClientMetadata = function getClientMetadata() {
4035 return this.clientMetadata;
4036 };
4037
4038 return AuthenticationDetails;
4039}();
4040
4041
4042
4043/***/ }),
4044
4045/***/ "../amazon-cognito-identity-js/es/AuthenticationHelper.js":
4046/*!****************************************************************!*\
4047 !*** ../amazon-cognito-identity-js/es/AuthenticationHelper.js ***!
4048 \****************************************************************/
4049/*! exports provided: default */
4050/***/ (function(module, __webpack_exports__, __webpack_require__) {
4051
4052"use strict";
4053__webpack_require__.r(__webpack_exports__);
4054/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AuthenticationHelper; });
4055/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer */ "../../node_modules/buffer/index.js");
4056/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(buffer__WEBPACK_IMPORTED_MODULE_0__);
4057/* 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");
4058/* harmony import */ var crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(crypto_js_core__WEBPACK_IMPORTED_MODULE_1__);
4059/* 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");
4060/* harmony import */ var crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2__);
4061/* 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");
4062/* harmony import */ var crypto_js_sha256__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(crypto_js_sha256__WEBPACK_IMPORTED_MODULE_3__);
4063/* 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");
4064/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4__);
4065/* harmony import */ var _utils_WordArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/WordArray */ "../amazon-cognito-identity-js/es/utils/WordArray.js");
4066/* harmony import */ var _BigInteger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./BigInteger */ "../amazon-cognito-identity-js/es/BigInteger.js");
4067/*!
4068 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4069 * SPDX-License-Identifier: Apache-2.0
4070 */
4071
4072
4073 // necessary for crypto js
4074
4075
4076
4077
4078/**
4079 * Returns a Buffer with a sequence of random nBytes
4080 *
4081 * @param {number} nBytes
4082 * @returns {Buffer} fixed-length sequence of random bytes
4083 */
4084
4085function randomBytes(nBytes) {
4086 return buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(new _utils_WordArray__WEBPACK_IMPORTED_MODULE_5__["default"]().random(nBytes).toString(), 'hex');
4087}
4088
4089
4090/**
4091 * Tests if a hex string has it most significant bit set (case-insensitive regex)
4092 */
4093
4094var HEX_MSB_REGEX = /^[89a-f]/i;
4095var initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF';
4096var newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.';
4097/** @class */
4098
4099var AuthenticationHelper = /*#__PURE__*/function () {
4100 /**
4101 * Constructs a new AuthenticationHelper object
4102 * @param {string} PoolName Cognito user pool name.
4103 */
4104 function AuthenticationHelper(PoolName) {
4105 this.N = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](initN, 16);
4106 this.g = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"]('2', 16);
4107 this.k = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](this.hexHash("" + this.padHex(this.N) + this.padHex(this.g)), 16);
4108 this.smallAValue = this.generateRandomSmallA();
4109 this.getLargeAValue(function () {});
4110 this.infoBits = buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from('Caldera Derived Key', 'utf8');
4111 this.poolName = PoolName;
4112 }
4113 /**
4114 * @returns {BigInteger} small A, a random number
4115 */
4116
4117
4118 var _proto = AuthenticationHelper.prototype;
4119
4120 _proto.getSmallAValue = function getSmallAValue() {
4121 return this.smallAValue;
4122 }
4123 /**
4124 * @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
4125 * @returns {void}
4126 */
4127 ;
4128
4129 _proto.getLargeAValue = function getLargeAValue(callback) {
4130 var _this = this;
4131
4132 if (this.largeAValue) {
4133 callback(null, this.largeAValue);
4134 } else {
4135 this.calculateA(this.smallAValue, function (err, largeAValue) {
4136 if (err) {
4137 callback(err, null);
4138 }
4139
4140 _this.largeAValue = largeAValue;
4141 callback(null, _this.largeAValue);
4142 });
4143 }
4144 }
4145 /**
4146 * helper function to generate a random big integer
4147 * @returns {BigInteger} a random value.
4148 * @private
4149 */
4150 ;
4151
4152 _proto.generateRandomSmallA = function generateRandomSmallA() {
4153 // This will be interpreted as a postive 128-bit integer
4154 var hexRandom = randomBytes(128).toString('hex');
4155 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)
4156
4157 return randomBigInt;
4158 }
4159 /**
4160 * helper function to generate a random string
4161 * @returns {string} a random value.
4162 * @private
4163 */
4164 ;
4165
4166 _proto.generateRandomString = function generateRandomString() {
4167 return randomBytes(40).toString('base64');
4168 }
4169 /**
4170 * @returns {string} Generated random value included in password hash.
4171 */
4172 ;
4173
4174 _proto.getRandomPassword = function getRandomPassword() {
4175 return this.randomPassword;
4176 }
4177 /**
4178 * @returns {string} Generated random value included in devices hash.
4179 */
4180 ;
4181
4182 _proto.getSaltDevices = function getSaltDevices() {
4183 return this.SaltToHashDevices;
4184 }
4185 /**
4186 * @returns {string} Value used to verify devices.
4187 */
4188 ;
4189
4190 _proto.getVerifierDevices = function getVerifierDevices() {
4191 return this.verifierDevices;
4192 }
4193 /**
4194 * Generate salts and compute verifier.
4195 * @param {string} deviceGroupKey Devices to generate verifier for.
4196 * @param {string} username User to generate verifier for.
4197 * @param {nodeCallback<null>} callback Called with (err, null)
4198 * @returns {void}
4199 */
4200 ;
4201
4202 _proto.generateHashDevice = function generateHashDevice(deviceGroupKey, username, callback) {
4203 var _this2 = this;
4204
4205 this.randomPassword = this.generateRandomString();
4206 var combinedString = "" + deviceGroupKey + username + ":" + this.randomPassword;
4207 var hashedString = this.hash(combinedString);
4208 var hexRandom = randomBytes(16).toString('hex'); // The random hex will be unambiguously represented as a postive integer
4209
4210 this.SaltToHashDevices = this.padHex(new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](hexRandom, 16));
4211 this.g.modPow(new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, function (err, verifierDevicesNotPadded) {
4212 if (err) {
4213 callback(err, null);
4214 }
4215
4216 _this2.verifierDevices = _this2.padHex(verifierDevicesNotPadded);
4217 callback(null, null);
4218 });
4219 }
4220 /**
4221 * Calculate the client's public value A = g^a%N
4222 * with the generated random number a
4223 * @param {BigInteger} a Randomly generated small A.
4224 * @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
4225 * @returns {void}
4226 * @private
4227 */
4228 ;
4229
4230 _proto.calculateA = function calculateA(a, callback) {
4231 var _this3 = this;
4232
4233 this.g.modPow(a, this.N, function (err, A) {
4234 if (err) {
4235 callback(err, null);
4236 }
4237
4238 if (A.mod(_this3.N).equals(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ZERO)) {
4239 callback(new Error('Illegal paramater. A mod N cannot be 0.'), null);
4240 }
4241
4242 callback(null, A);
4243 });
4244 }
4245 /**
4246 * Calculate the client's value U which is the hash of A and B
4247 * @param {BigInteger} A Large A value.
4248 * @param {BigInteger} B Server B value.
4249 * @returns {BigInteger} Computed U value.
4250 * @private
4251 */
4252 ;
4253
4254 _proto.calculateU = function calculateU(A, B) {
4255 this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B));
4256 var finalU = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](this.UHexHash, 16);
4257 return finalU;
4258 }
4259 /**
4260 * Calculate a hash from a bitArray
4261 * @param {Buffer} buf Value to hash.
4262 * @returns {String} Hex-encoded hash.
4263 * @private
4264 */
4265 ;
4266
4267 _proto.hash = function hash(buf) {
4268 var str = buf instanceof buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"] ? crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(buf) : buf;
4269 var hashHex = crypto_js_sha256__WEBPACK_IMPORTED_MODULE_3___default()(str).toString();
4270 return new Array(64 - hashHex.length).join('0') + hashHex;
4271 }
4272 /**
4273 * Calculate a hash from a hex string
4274 * @param {String} hexStr Value to hash.
4275 * @returns {String} Hex-encoded hash.
4276 * @private
4277 */
4278 ;
4279
4280 _proto.hexHash = function hexHash(hexStr) {
4281 return this.hash(buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(hexStr, 'hex'));
4282 }
4283 /**
4284 * Standard hkdf algorithm
4285 * @param {Buffer} ikm Input key material.
4286 * @param {Buffer} salt Salt value.
4287 * @returns {Buffer} Strong key material.
4288 * @private
4289 */
4290 ;
4291
4292 _proto.computehkdf = function computehkdf(ikm, salt) {
4293 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')]));
4294 var ikmWordArray = ikm instanceof buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"] ? crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(ikm) : ikm;
4295 var saltWordArray = salt instanceof buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"] ? crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(salt) : salt;
4296 var prk = crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default()(ikmWordArray, saltWordArray);
4297 var hmac = crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default()(infoBitsWordArray, prk);
4298 return buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(hmac.toString(), 'hex').slice(0, 16);
4299 }
4300 /**
4301 * Calculates the final hkdf based on computed S value, and computed U value and the key
4302 * @param {String} username Username.
4303 * @param {String} password Password.
4304 * @param {BigInteger} serverBValue Server B value.
4305 * @param {BigInteger} salt Generated salt.
4306 * @param {nodeCallback<Buffer>} callback Called with (err, hkdfValue)
4307 * @returns {void}
4308 */
4309 ;
4310
4311 _proto.getPasswordAuthenticationKey = function getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) {
4312 var _this4 = this;
4313
4314 if (serverBValue.mod(this.N).equals(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ZERO)) {
4315 throw new Error('B cannot be zero.');
4316 }
4317
4318 this.UValue = this.calculateU(this.largeAValue, serverBValue);
4319
4320 if (this.UValue.equals(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ZERO)) {
4321 throw new Error('U cannot be zero.');
4322 }
4323
4324 var usernamePassword = "" + this.poolName + username + ":" + password;
4325 var usernamePasswordHash = this.hash(usernamePassword);
4326 var xValue = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](this.hexHash(this.padHex(salt) + usernamePasswordHash), 16);
4327 this.calculateS(xValue, serverBValue, function (err, sValue) {
4328 if (err) {
4329 callback(err, null);
4330 }
4331
4332 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'));
4333
4334 callback(null, hkdf);
4335 });
4336 }
4337 /**
4338 * Calculates the S value used in getPasswordAuthenticationKey
4339 * @param {BigInteger} xValue Salted password hash value.
4340 * @param {BigInteger} serverBValue Server B value.
4341 * @param {nodeCallback<string>} callback Called on success or error.
4342 * @returns {void}
4343 */
4344 ;
4345
4346 _proto.calculateS = function calculateS(xValue, serverBValue, callback) {
4347 var _this5 = this;
4348
4349 this.g.modPow(xValue, this.N, function (err, gModPowXN) {
4350 if (err) {
4351 callback(err, null);
4352 }
4353
4354 var intValue2 = serverBValue.subtract(_this5.k.multiply(gModPowXN));
4355 intValue2.modPow(_this5.smallAValue.add(_this5.UValue.multiply(xValue)), _this5.N, function (err2, result) {
4356 if (err2) {
4357 callback(err2, null);
4358 }
4359
4360 callback(null, result.mod(_this5.N));
4361 });
4362 });
4363 }
4364 /**
4365 * Return constant newPasswordRequiredChallengeUserAttributePrefix
4366 * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value
4367 */
4368 ;
4369
4370 _proto.getNewPasswordRequiredChallengeUserAttributePrefix = function getNewPasswordRequiredChallengeUserAttributePrefix() {
4371 return newPasswordRequiredChallengeUserAttributePrefix;
4372 }
4373 /**
4374 * Returns an unambiguous, even-length hex string of the two's complement encoding of an integer.
4375 *
4376 * It is compatible with the hex encoding of Java's BigInteger's toByteArray(), wich returns a
4377 * byte array containing the two's-complement representation of a BigInteger. The array contains
4378 * the minimum number of bytes required to represent the BigInteger, including at least one sign bit.
4379 *
4380 * Examples showing how ambiguity is avoided by left padding with:
4381 * "00" (for positive values where the most-significant-bit is set)
4382 * "FF" (for negative values where the most-significant-bit is set)
4383 *
4384 * padHex(bigInteger.fromInt(-236)) === "FF14"
4385 * padHex(bigInteger.fromInt(20)) === "14"
4386 *
4387 * padHex(bigInteger.fromInt(-200)) === "FF38"
4388 * padHex(bigInteger.fromInt(56)) === "38"
4389 *
4390 * padHex(bigInteger.fromInt(-20)) === "EC"
4391 * padHex(bigInteger.fromInt(236)) === "00EC"
4392 *
4393 * padHex(bigInteger.fromInt(-56)) === "C8"
4394 * padHex(bigInteger.fromInt(200)) === "00C8"
4395 *
4396 * @param {BigInteger} bigInt Number to encode.
4397 * @returns {String} even-length hex string of the two's complement encoding.
4398 */
4399 ;
4400
4401 _proto.padHex = function padHex(bigInt) {
4402 if (!(bigInt instanceof _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"])) {
4403 throw new Error('Not a BigInteger');
4404 }
4405
4406 var isNegative = bigInt.compareTo(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ZERO) < 0;
4407 /* Get a hex string for abs(bigInt) */
4408
4409 var hexStr = bigInt.abs().toString(16);
4410 /* Pad hex to even length if needed */
4411
4412 hexStr = hexStr.length % 2 !== 0 ? "0" + hexStr : hexStr;
4413 /* Prepend "00" if the most significant bit is set */
4414
4415 hexStr = HEX_MSB_REGEX.test(hexStr) ? "00" + hexStr : hexStr;
4416
4417 if (isNegative) {
4418 /* Flip the bits of the representation */
4419 var invertedNibbles = hexStr.split('').map(function (x) {
4420 var invertedNibble = ~parseInt(x, 16) & 0xf;
4421 return '0123456789ABCDEF'.charAt(invertedNibble);
4422 }).join('');
4423 /* After flipping the bits, add one to get the 2's complement representation */
4424
4425 var flippedBitsBI = new _BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"](invertedNibbles, 16).add(_BigInteger__WEBPACK_IMPORTED_MODULE_6__["default"].ONE);
4426 hexStr = flippedBitsBI.toString(16);
4427 /*
4428 For hex strings starting with 'FF8', 'FF' can be dropped, e.g. 0xFFFF80=0xFF80=0x80=-128
4429 Any sequence of '1' bits on the left can always be substituted with a single '1' bit
4430 without changing the represented value.
4431 This only happens in the case when the input is 80...00
4432 */
4433
4434 if (hexStr.toUpperCase().startsWith('FF8')) {
4435 hexStr = hexStr.substring(2);
4436 }
4437 }
4438
4439 return hexStr;
4440 };
4441
4442 return AuthenticationHelper;
4443}();
4444
4445
4446
4447/***/ }),
4448
4449/***/ "../amazon-cognito-identity-js/es/BigInteger.js":
4450/*!******************************************************!*\
4451 !*** ../amazon-cognito-identity-js/es/BigInteger.js ***!
4452 \******************************************************/
4453/*! exports provided: default */
4454/***/ (function(module, __webpack_exports__, __webpack_require__) {
4455
4456"use strict";
4457__webpack_require__.r(__webpack_exports__);
4458// A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/
4459//
4460// All public methods have been removed except the following:
4461// new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported)
4462// toString (only radix 2, 4, 8, 16 and 32 supported)
4463// negate
4464// abs
4465// compareTo
4466// bitLength
4467// mod
4468// equals
4469// add
4470// subtract
4471// multiply
4472// divide
4473// modPow
4474/* harmony default export */ __webpack_exports__["default"] = (BigInteger);
4475/*
4476 * Copyright (c) 2003-2005 Tom Wu
4477 * All Rights Reserved.
4478 *
4479 * Permission is hereby granted, free of charge, to any person obtaining
4480 * a copy of this software and associated documentation files (the
4481 * "Software"), to deal in the Software without restriction, including
4482 * without limitation the rights to use, copy, modify, merge, publish,
4483 * distribute, sublicense, and/or sell copies of the Software, and to
4484 * permit persons to whom the Software is furnished to do so, subject to
4485 * the following conditions:
4486 *
4487 * The above copyright notice and this permission notice shall be
4488 * included in all copies or substantial portions of the Software.
4489 *
4490 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
4491 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
4492 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
4493 *
4494 * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
4495 * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
4496 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
4497 * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
4498 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
4499 *
4500 * In addition, the following condition applies:
4501 *
4502 * All redistributions must retain an intact copy of this copyright notice
4503 * and disclaimer.
4504 */
4505// (public) Constructor
4506
4507function BigInteger(a, b) {
4508 if (a != null) this.fromString(a, b);
4509} // return new, unset BigInteger
4510
4511
4512function nbi() {
4513 return new BigInteger(null);
4514} // Bits per digit
4515
4516
4517var dbits; // JavaScript engine analysis
4518
4519var canary = 0xdeadbeefcafe;
4520var j_lm = (canary & 0xffffff) == 0xefcafe; // am: Compute w_j += (x*this_i), propagate carries,
4521// c is initial carry, returns final carry.
4522// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
4523// We need to select the fastest one that works in this environment.
4524// am1: use a single mult and divide to get the high bits,
4525// max digit bits should be 26 because
4526// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
4527
4528function am1(i, x, w, j, c, n) {
4529 while (--n >= 0) {
4530 var v = x * this[i++] + w[j] + c;
4531 c = Math.floor(v / 0x4000000);
4532 w[j++] = v & 0x3ffffff;
4533 }
4534
4535 return c;
4536} // am2 avoids a big mult-and-extract completely.
4537// Max digit bits should be <= 30 because we do bitwise ops
4538// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
4539
4540
4541function am2(i, x, w, j, c, n) {
4542 var xl = x & 0x7fff,
4543 xh = x >> 15;
4544
4545 while (--n >= 0) {
4546 var l = this[i] & 0x7fff;
4547 var h = this[i++] >> 15;
4548 var m = xh * l + h * xl;
4549 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
4550 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
4551 w[j++] = l & 0x3fffffff;
4552 }
4553
4554 return c;
4555} // Alternately, set max digit bits to 28 since some
4556// browsers slow down when dealing with 32-bit numbers.
4557
4558
4559function am3(i, x, w, j, c, n) {
4560 var xl = x & 0x3fff,
4561 xh = x >> 14;
4562
4563 while (--n >= 0) {
4564 var l = this[i] & 0x3fff;
4565 var h = this[i++] >> 14;
4566 var m = xh * l + h * xl;
4567 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
4568 c = (l >> 28) + (m >> 14) + xh * h;
4569 w[j++] = l & 0xfffffff;
4570 }
4571
4572 return c;
4573}
4574
4575var inBrowser = typeof navigator !== 'undefined';
4576
4577if (inBrowser && j_lm && navigator.appName == 'Microsoft Internet Explorer') {
4578 BigInteger.prototype.am = am2;
4579 dbits = 30;
4580} else if (inBrowser && j_lm && navigator.appName != 'Netscape') {
4581 BigInteger.prototype.am = am1;
4582 dbits = 26;
4583} else {
4584 // Mozilla/Netscape seems to prefer am3
4585 BigInteger.prototype.am = am3;
4586 dbits = 28;
4587}
4588
4589BigInteger.prototype.DB = dbits;
4590BigInteger.prototype.DM = (1 << dbits) - 1;
4591BigInteger.prototype.DV = 1 << dbits;
4592var BI_FP = 52;
4593BigInteger.prototype.FV = Math.pow(2, BI_FP);
4594BigInteger.prototype.F1 = BI_FP - dbits;
4595BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions
4596
4597var BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz';
4598var BI_RC = new Array();
4599var rr, vv;
4600rr = '0'.charCodeAt(0);
4601
4602for (vv = 0; vv <= 9; ++vv) {
4603 BI_RC[rr++] = vv;
4604}
4605
4606rr = 'a'.charCodeAt(0);
4607
4608for (vv = 10; vv < 36; ++vv) {
4609 BI_RC[rr++] = vv;
4610}
4611
4612rr = 'A'.charCodeAt(0);
4613
4614for (vv = 10; vv < 36; ++vv) {
4615 BI_RC[rr++] = vv;
4616}
4617
4618function int2char(n) {
4619 return BI_RM.charAt(n);
4620}
4621
4622function intAt(s, i) {
4623 var c = BI_RC[s.charCodeAt(i)];
4624 return c == null ? -1 : c;
4625} // (protected) copy this to r
4626
4627
4628function bnpCopyTo(r) {
4629 for (var i = this.t - 1; i >= 0; --i) {
4630 r[i] = this[i];
4631 }
4632
4633 r.t = this.t;
4634 r.s = this.s;
4635} // (protected) set from integer value x, -DV <= x < DV
4636
4637
4638function bnpFromInt(x) {
4639 this.t = 1;
4640 this.s = x < 0 ? -1 : 0;
4641 if (x > 0) this[0] = x;else if (x < -1) this[0] = x + this.DV;else this.t = 0;
4642} // return bigint initialized to value
4643
4644
4645function nbv(i) {
4646 var r = nbi();
4647 r.fromInt(i);
4648 return r;
4649} // (protected) set from string and radix
4650
4651
4652function bnpFromString(s, b) {
4653 var k;
4654 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');
4655 this.t = 0;
4656 this.s = 0;
4657 var i = s.length,
4658 mi = false,
4659 sh = 0;
4660
4661 while (--i >= 0) {
4662 var x = intAt(s, i);
4663
4664 if (x < 0) {
4665 if (s.charAt(i) == '-') mi = true;
4666 continue;
4667 }
4668
4669 mi = false;
4670 if (sh == 0) this[this.t++] = x;else if (sh + k > this.DB) {
4671 this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh;
4672 this[this.t++] = x >> this.DB - sh;
4673 } else this[this.t - 1] |= x << sh;
4674 sh += k;
4675 if (sh >= this.DB) sh -= this.DB;
4676 }
4677
4678 this.clamp();
4679 if (mi) BigInteger.ZERO.subTo(this, this);
4680} // (protected) clamp off excess high words
4681
4682
4683function bnpClamp() {
4684 var c = this.s & this.DM;
4685
4686 while (this.t > 0 && this[this.t - 1] == c) {
4687 --this.t;
4688 }
4689} // (public) return string representation in given radix
4690
4691
4692function bnToString(b) {
4693 if (this.s < 0) return '-' + this.negate().toString(b);
4694 var k;
4695 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');
4696 var km = (1 << k) - 1,
4697 d,
4698 m = false,
4699 r = '',
4700 i = this.t;
4701 var p = this.DB - i * this.DB % k;
4702
4703 if (i-- > 0) {
4704 if (p < this.DB && (d = this[i] >> p) > 0) {
4705 m = true;
4706 r = int2char(d);
4707 }
4708
4709 while (i >= 0) {
4710 if (p < k) {
4711 d = (this[i] & (1 << p) - 1) << k - p;
4712 d |= this[--i] >> (p += this.DB - k);
4713 } else {
4714 d = this[i] >> (p -= k) & km;
4715
4716 if (p <= 0) {
4717 p += this.DB;
4718 --i;
4719 }
4720 }
4721
4722 if (d > 0) m = true;
4723 if (m) r += int2char(d);
4724 }
4725 }
4726
4727 return m ? r : '0';
4728} // (public) -this
4729
4730
4731function bnNegate() {
4732 var r = nbi();
4733 BigInteger.ZERO.subTo(this, r);
4734 return r;
4735} // (public) |this|
4736
4737
4738function bnAbs() {
4739 return this.s < 0 ? this.negate() : this;
4740} // (public) return + if this > a, - if this < a, 0 if equal
4741
4742
4743function bnCompareTo(a) {
4744 var r = this.s - a.s;
4745 if (r != 0) return r;
4746 var i = this.t;
4747 r = i - a.t;
4748 if (r != 0) return this.s < 0 ? -r : r;
4749
4750 while (--i >= 0) {
4751 if ((r = this[i] - a[i]) != 0) return r;
4752 }
4753
4754 return 0;
4755} // returns bit length of the integer x
4756
4757
4758function nbits(x) {
4759 var r = 1,
4760 t;
4761
4762 if ((t = x >>> 16) != 0) {
4763 x = t;
4764 r += 16;
4765 }
4766
4767 if ((t = x >> 8) != 0) {
4768 x = t;
4769 r += 8;
4770 }
4771
4772 if ((t = x >> 4) != 0) {
4773 x = t;
4774 r += 4;
4775 }
4776
4777 if ((t = x >> 2) != 0) {
4778 x = t;
4779 r += 2;
4780 }
4781
4782 if ((t = x >> 1) != 0) {
4783 x = t;
4784 r += 1;
4785 }
4786
4787 return r;
4788} // (public) return the number of bits in "this"
4789
4790
4791function bnBitLength() {
4792 if (this.t <= 0) return 0;
4793 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM);
4794} // (protected) r = this << n*DB
4795
4796
4797function bnpDLShiftTo(n, r) {
4798 var i;
4799
4800 for (i = this.t - 1; i >= 0; --i) {
4801 r[i + n] = this[i];
4802 }
4803
4804 for (i = n - 1; i >= 0; --i) {
4805 r[i] = 0;
4806 }
4807
4808 r.t = this.t + n;
4809 r.s = this.s;
4810} // (protected) r = this >> n*DB
4811
4812
4813function bnpDRShiftTo(n, r) {
4814 for (var i = n; i < this.t; ++i) {
4815 r[i - n] = this[i];
4816 }
4817
4818 r.t = Math.max(this.t - n, 0);
4819 r.s = this.s;
4820} // (protected) r = this << n
4821
4822
4823function bnpLShiftTo(n, r) {
4824 var bs = n % this.DB;
4825 var cbs = this.DB - bs;
4826 var bm = (1 << cbs) - 1;
4827 var ds = Math.floor(n / this.DB),
4828 c = this.s << bs & this.DM,
4829 i;
4830
4831 for (i = this.t - 1; i >= 0; --i) {
4832 r[i + ds + 1] = this[i] >> cbs | c;
4833 c = (this[i] & bm) << bs;
4834 }
4835
4836 for (i = ds - 1; i >= 0; --i) {
4837 r[i] = 0;
4838 }
4839
4840 r[ds] = c;
4841 r.t = this.t + ds + 1;
4842 r.s = this.s;
4843 r.clamp();
4844} // (protected) r = this >> n
4845
4846
4847function bnpRShiftTo(n, r) {
4848 r.s = this.s;
4849 var ds = Math.floor(n / this.DB);
4850
4851 if (ds >= this.t) {
4852 r.t = 0;
4853 return;
4854 }
4855
4856 var bs = n % this.DB;
4857 var cbs = this.DB - bs;
4858 var bm = (1 << bs) - 1;
4859 r[0] = this[ds] >> bs;
4860
4861 for (var i = ds + 1; i < this.t; ++i) {
4862 r[i - ds - 1] |= (this[i] & bm) << cbs;
4863 r[i - ds] = this[i] >> bs;
4864 }
4865
4866 if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs;
4867 r.t = this.t - ds;
4868 r.clamp();
4869} // (protected) r = this - a
4870
4871
4872function bnpSubTo(a, r) {
4873 var i = 0,
4874 c = 0,
4875 m = Math.min(a.t, this.t);
4876
4877 while (i < m) {
4878 c += this[i] - a[i];
4879 r[i++] = c & this.DM;
4880 c >>= this.DB;
4881 }
4882
4883 if (a.t < this.t) {
4884 c -= a.s;
4885
4886 while (i < this.t) {
4887 c += this[i];
4888 r[i++] = c & this.DM;
4889 c >>= this.DB;
4890 }
4891
4892 c += this.s;
4893 } else {
4894 c += this.s;
4895
4896 while (i < a.t) {
4897 c -= a[i];
4898 r[i++] = c & this.DM;
4899 c >>= this.DB;
4900 }
4901
4902 c -= a.s;
4903 }
4904
4905 r.s = c < 0 ? -1 : 0;
4906 if (c < -1) r[i++] = this.DV + c;else if (c > 0) r[i++] = c;
4907 r.t = i;
4908 r.clamp();
4909} // (protected) r = this * a, r != this,a (HAC 14.12)
4910// "this" should be the larger one if appropriate.
4911
4912
4913function bnpMultiplyTo(a, r) {
4914 var x = this.abs(),
4915 y = a.abs();
4916 var i = x.t;
4917 r.t = i + y.t;
4918
4919 while (--i >= 0) {
4920 r[i] = 0;
4921 }
4922
4923 for (i = 0; i < y.t; ++i) {
4924 r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
4925 }
4926
4927 r.s = 0;
4928 r.clamp();
4929 if (this.s != a.s) BigInteger.ZERO.subTo(r, r);
4930} // (protected) r = this^2, r != this (HAC 14.16)
4931
4932
4933function bnpSquareTo(r) {
4934 var x = this.abs();
4935 var i = r.t = 2 * x.t;
4936
4937 while (--i >= 0) {
4938 r[i] = 0;
4939 }
4940
4941 for (i = 0; i < x.t - 1; ++i) {
4942 var c = x.am(i, x[i], r, 2 * i, 0, 1);
4943
4944 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
4945 r[i + x.t] -= x.DV;
4946 r[i + x.t + 1] = 1;
4947 }
4948 }
4949
4950 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
4951 r.s = 0;
4952 r.clamp();
4953} // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
4954// r != q, this != m. q or r may be null.
4955
4956
4957function bnpDivRemTo(m, q, r) {
4958 var pm = m.abs();
4959 if (pm.t <= 0) return;
4960 var pt = this.abs();
4961
4962 if (pt.t < pm.t) {
4963 if (q != null) q.fromInt(0);
4964 if (r != null) this.copyTo(r);
4965 return;
4966 }
4967
4968 if (r == null) r = nbi();
4969 var y = nbi(),
4970 ts = this.s,
4971 ms = m.s;
4972 var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
4973
4974 if (nsh > 0) {
4975 pm.lShiftTo(nsh, y);
4976 pt.lShiftTo(nsh, r);
4977 } else {
4978 pm.copyTo(y);
4979 pt.copyTo(r);
4980 }
4981
4982 var ys = y.t;
4983 var y0 = y[ys - 1];
4984 if (y0 == 0) return;
4985 var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0);
4986 var d1 = this.FV / yt,
4987 d2 = (1 << this.F1) / yt,
4988 e = 1 << this.F2;
4989 var i = r.t,
4990 j = i - ys,
4991 t = q == null ? nbi() : q;
4992 y.dlShiftTo(j, t);
4993
4994 if (r.compareTo(t) >= 0) {
4995 r[r.t++] = 1;
4996 r.subTo(t, r);
4997 }
4998
4999 BigInteger.ONE.dlShiftTo(ys, t);
5000 t.subTo(y, y); // "negative" y so we can replace sub with am later
5001
5002 while (y.t < ys) {
5003 y[y.t++] = 0;
5004 }
5005
5006 while (--j >= 0) {
5007 // Estimate quotient digit
5008 var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
5009
5010 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {
5011 // Try it out
5012 y.dlShiftTo(j, t);
5013 r.subTo(t, r);
5014
5015 while (r[i] < --qd) {
5016 r.subTo(t, r);
5017 }
5018 }
5019 }
5020
5021 if (q != null) {
5022 r.drShiftTo(ys, q);
5023 if (ts != ms) BigInteger.ZERO.subTo(q, q);
5024 }
5025
5026 r.t = ys;
5027 r.clamp();
5028 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
5029
5030 if (ts < 0) BigInteger.ZERO.subTo(r, r);
5031} // (public) this mod a
5032
5033
5034function bnMod(a) {
5035 var r = nbi();
5036 this.abs().divRemTo(a, null, r);
5037 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r);
5038 return r;
5039} // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
5040// justification:
5041// xy == 1 (mod m)
5042// xy = 1+km
5043// xy(2-xy) = (1+km)(1-km)
5044// x[y(2-xy)] = 1-k^2m^2
5045// x[y(2-xy)] == 1 (mod m^2)
5046// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
5047// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
5048// JS multiply "overflows" differently from C/C++, so care is needed here.
5049
5050
5051function bnpInvDigit() {
5052 if (this.t < 1) return 0;
5053 var x = this[0];
5054 if ((x & 1) == 0) return 0;
5055 var y = x & 3; // y == 1/x mod 2^2
5056
5057 y = y * (2 - (x & 0xf) * y) & 0xf; // y == 1/x mod 2^4
5058
5059 y = y * (2 - (x & 0xff) * y) & 0xff; // y == 1/x mod 2^8
5060
5061 y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; // y == 1/x mod 2^16
5062 // last step - calculate inverse mod DV directly;
5063 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
5064
5065 y = y * (2 - x * y % this.DV) % this.DV; // y == 1/x mod 2^dbits
5066 // we really want the negative inverse, and -DV < y < DV
5067
5068 return y > 0 ? this.DV - y : -y;
5069}
5070
5071function bnEquals(a) {
5072 return this.compareTo(a) == 0;
5073} // (protected) r = this + a
5074
5075
5076function bnpAddTo(a, r) {
5077 var i = 0,
5078 c = 0,
5079 m = Math.min(a.t, this.t);
5080
5081 while (i < m) {
5082 c += this[i] + a[i];
5083 r[i++] = c & this.DM;
5084 c >>= this.DB;
5085 }
5086
5087 if (a.t < this.t) {
5088 c += a.s;
5089
5090 while (i < this.t) {
5091 c += this[i];
5092 r[i++] = c & this.DM;
5093 c >>= this.DB;
5094 }
5095
5096 c += this.s;
5097 } else {
5098 c += this.s;
5099
5100 while (i < a.t) {
5101 c += a[i];
5102 r[i++] = c & this.DM;
5103 c >>= this.DB;
5104 }
5105
5106 c += a.s;
5107 }
5108
5109 r.s = c < 0 ? -1 : 0;
5110 if (c > 0) r[i++] = c;else if (c < -1) r[i++] = this.DV + c;
5111 r.t = i;
5112 r.clamp();
5113} // (public) this + a
5114
5115
5116function bnAdd(a) {
5117 var r = nbi();
5118 this.addTo(a, r);
5119 return r;
5120} // (public) this - a
5121
5122
5123function bnSubtract(a) {
5124 var r = nbi();
5125 this.subTo(a, r);
5126 return r;
5127} // (public) this * a
5128
5129
5130function bnMultiply(a) {
5131 var r = nbi();
5132 this.multiplyTo(a, r);
5133 return r;
5134} // (public) this / a
5135
5136
5137function bnDivide(a) {
5138 var r = nbi();
5139 this.divRemTo(a, r, null);
5140 return r;
5141} // Montgomery reduction
5142
5143
5144function Montgomery(m) {
5145 this.m = m;
5146 this.mp = m.invDigit();
5147 this.mpl = this.mp & 0x7fff;
5148 this.mph = this.mp >> 15;
5149 this.um = (1 << m.DB - 15) - 1;
5150 this.mt2 = 2 * m.t;
5151} // xR mod m
5152
5153
5154function montConvert(x) {
5155 var r = nbi();
5156 x.abs().dlShiftTo(this.m.t, r);
5157 r.divRemTo(this.m, null, r);
5158 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r);
5159 return r;
5160} // x/R mod m
5161
5162
5163function montRevert(x) {
5164 var r = nbi();
5165 x.copyTo(r);
5166 this.reduce(r);
5167 return r;
5168} // x = x/R mod m (HAC 14.32)
5169
5170
5171function montReduce(x) {
5172 while (x.t <= this.mt2) {
5173 // pad x so am has enough room later
5174 x[x.t++] = 0;
5175 }
5176
5177 for (var i = 0; i < this.m.t; ++i) {
5178 // faster way of calculating u0 = x[i]*mp mod DV
5179 var j = x[i] & 0x7fff;
5180 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
5181
5182 j = i + this.m.t;
5183 x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry
5184
5185 while (x[j] >= x.DV) {
5186 x[j] -= x.DV;
5187 x[++j]++;
5188 }
5189 }
5190
5191 x.clamp();
5192 x.drShiftTo(this.m.t, x);
5193 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x);
5194} // r = "x^2/R mod m"; x != r
5195
5196
5197function montSqrTo(x, r) {
5198 x.squareTo(r);
5199 this.reduce(r);
5200} // r = "xy/R mod m"; x,y != r
5201
5202
5203function montMulTo(x, y, r) {
5204 x.multiplyTo(y, r);
5205 this.reduce(r);
5206}
5207
5208Montgomery.prototype.convert = montConvert;
5209Montgomery.prototype.revert = montRevert;
5210Montgomery.prototype.reduce = montReduce;
5211Montgomery.prototype.mulTo = montMulTo;
5212Montgomery.prototype.sqrTo = montSqrTo; // (public) this^e % m (HAC 14.85)
5213
5214function bnModPow(e, m, callback) {
5215 var i = e.bitLength(),
5216 k,
5217 r = nbv(1),
5218 z = new Montgomery(m);
5219 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
5220
5221 var g = new Array(),
5222 n = 3,
5223 k1 = k - 1,
5224 km = (1 << k) - 1;
5225 g[1] = z.convert(this);
5226
5227 if (k > 1) {
5228 var g2 = nbi();
5229 z.sqrTo(g[1], g2);
5230
5231 while (n <= km) {
5232 g[n] = nbi();
5233 z.mulTo(g2, g[n - 2], g[n]);
5234 n += 2;
5235 }
5236 }
5237
5238 var j = e.t - 1,
5239 w,
5240 is1 = true,
5241 r2 = nbi(),
5242 t;
5243 i = nbits(e[j]) - 1;
5244
5245 while (j >= 0) {
5246 if (i >= k1) w = e[j] >> i - k1 & km;else {
5247 w = (e[j] & (1 << i + 1) - 1) << k1 - i;
5248 if (j > 0) w |= e[j - 1] >> this.DB + i - k1;
5249 }
5250 n = k;
5251
5252 while ((w & 1) == 0) {
5253 w >>= 1;
5254 --n;
5255 }
5256
5257 if ((i -= n) < 0) {
5258 i += this.DB;
5259 --j;
5260 }
5261
5262 if (is1) {
5263 // ret == 1, don't bother squaring or multiplying it
5264 g[w].copyTo(r);
5265 is1 = false;
5266 } else {
5267 while (n > 1) {
5268 z.sqrTo(r, r2);
5269 z.sqrTo(r2, r);
5270 n -= 2;
5271 }
5272
5273 if (n > 0) z.sqrTo(r, r2);else {
5274 t = r;
5275 r = r2;
5276 r2 = t;
5277 }
5278 z.mulTo(r2, g[w], r);
5279 }
5280
5281 while (j >= 0 && (e[j] & 1 << i) == 0) {
5282 z.sqrTo(r, r2);
5283 t = r;
5284 r = r2;
5285 r2 = t;
5286
5287 if (--i < 0) {
5288 i = this.DB - 1;
5289 --j;
5290 }
5291 }
5292 }
5293
5294 var result = z.revert(r);
5295 callback(null, result);
5296 return result;
5297} // protected
5298
5299
5300BigInteger.prototype.copyTo = bnpCopyTo;
5301BigInteger.prototype.fromInt = bnpFromInt;
5302BigInteger.prototype.fromString = bnpFromString;
5303BigInteger.prototype.clamp = bnpClamp;
5304BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
5305BigInteger.prototype.drShiftTo = bnpDRShiftTo;
5306BigInteger.prototype.lShiftTo = bnpLShiftTo;
5307BigInteger.prototype.rShiftTo = bnpRShiftTo;
5308BigInteger.prototype.subTo = bnpSubTo;
5309BigInteger.prototype.multiplyTo = bnpMultiplyTo;
5310BigInteger.prototype.squareTo = bnpSquareTo;
5311BigInteger.prototype.divRemTo = bnpDivRemTo;
5312BigInteger.prototype.invDigit = bnpInvDigit;
5313BigInteger.prototype.addTo = bnpAddTo; // public
5314
5315BigInteger.prototype.toString = bnToString;
5316BigInteger.prototype.negate = bnNegate;
5317BigInteger.prototype.abs = bnAbs;
5318BigInteger.prototype.compareTo = bnCompareTo;
5319BigInteger.prototype.bitLength = bnBitLength;
5320BigInteger.prototype.mod = bnMod;
5321BigInteger.prototype.equals = bnEquals;
5322BigInteger.prototype.add = bnAdd;
5323BigInteger.prototype.subtract = bnSubtract;
5324BigInteger.prototype.multiply = bnMultiply;
5325BigInteger.prototype.divide = bnDivide;
5326BigInteger.prototype.modPow = bnModPow; // "constants"
5327
5328BigInteger.ZERO = nbv(0);
5329BigInteger.ONE = nbv(1);
5330
5331/***/ }),
5332
5333/***/ "../amazon-cognito-identity-js/es/Client.js":
5334/*!**************************************************!*\
5335 !*** ../amazon-cognito-identity-js/es/Client.js ***!
5336 \**************************************************/
5337/*! exports provided: default */
5338/***/ (function(module, __webpack_exports__, __webpack_require__) {
5339
5340"use strict";
5341__webpack_require__.r(__webpack_exports__);
5342/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Client; });
5343/* harmony import */ var isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! isomorphic-unfetch */ "../../node_modules/isomorphic-unfetch/browser.js");
5344/* harmony import */ var isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_0__);
5345/* harmony import */ var _UserAgent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./UserAgent */ "../amazon-cognito-identity-js/es/UserAgent.js");
5346function _inheritsLoose(subClass, superClass) {
5347 subClass.prototype = Object.create(superClass.prototype);
5348 subClass.prototype.constructor = subClass;
5349
5350 _setPrototypeOf(subClass, superClass);
5351}
5352
5353function _wrapNativeSuper(Class) {
5354 var _cache = typeof Map === "function" ? new Map() : undefined;
5355
5356 _wrapNativeSuper = function _wrapNativeSuper(Class) {
5357 if (Class === null || !_isNativeFunction(Class)) return Class;
5358
5359 if (typeof Class !== "function") {
5360 throw new TypeError("Super expression must either be null or a function");
5361 }
5362
5363 if (typeof _cache !== "undefined") {
5364 if (_cache.has(Class)) return _cache.get(Class);
5365
5366 _cache.set(Class, Wrapper);
5367 }
5368
5369 function Wrapper() {
5370 return _construct(Class, arguments, _getPrototypeOf(this).constructor);
5371 }
5372
5373 Wrapper.prototype = Object.create(Class.prototype, {
5374 constructor: {
5375 value: Wrapper,
5376 enumerable: false,
5377 writable: true,
5378 configurable: true
5379 }
5380 });
5381 return _setPrototypeOf(Wrapper, Class);
5382 };
5383
5384 return _wrapNativeSuper(Class);
5385}
5386
5387function _construct(Parent, args, Class) {
5388 if (_isNativeReflectConstruct()) {
5389 _construct = Reflect.construct;
5390 } else {
5391 _construct = function _construct(Parent, args, Class) {
5392 var a = [null];
5393 a.push.apply(a, args);
5394 var Constructor = Function.bind.apply(Parent, a);
5395 var instance = new Constructor();
5396 if (Class) _setPrototypeOf(instance, Class.prototype);
5397 return instance;
5398 };
5399 }
5400
5401 return _construct.apply(null, arguments);
5402}
5403
5404function _isNativeReflectConstruct() {
5405 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
5406 if (Reflect.construct.sham) return false;
5407 if (typeof Proxy === "function") return true;
5408
5409 try {
5410 Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
5411 return true;
5412 } catch (e) {
5413 return false;
5414 }
5415}
5416
5417function _isNativeFunction(fn) {
5418 return Function.toString.call(fn).indexOf("[native code]") !== -1;
5419}
5420
5421function _setPrototypeOf(o, p) {
5422 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
5423 o.__proto__ = p;
5424 return o;
5425 };
5426
5427 return _setPrototypeOf(o, p);
5428}
5429
5430function _getPrototypeOf(o) {
5431 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
5432 return o.__proto__ || Object.getPrototypeOf(o);
5433 };
5434 return _getPrototypeOf(o);
5435}
5436
5437
5438
5439
5440var CognitoError = /*#__PURE__*/function (_Error) {
5441 _inheritsLoose(CognitoError, _Error);
5442
5443 function CognitoError(message, code, name, statusCode) {
5444 var _this;
5445
5446 _this = _Error.call(this, message) || this;
5447 _this.code = code;
5448 _this.name = name;
5449 _this.statusCode = statusCode;
5450 return _this;
5451 }
5452
5453 return CognitoError;
5454}( /*#__PURE__*/_wrapNativeSuper(Error));
5455/** @class */
5456
5457
5458var Client = /*#__PURE__*/function () {
5459 /**
5460 * Constructs a new AWS Cognito Identity Provider client object
5461 * @param {string} region AWS region
5462 * @param {string} endpoint endpoint
5463 * @param {object} fetchOptions options for fetch API (only credentials is supported)
5464 */
5465 function Client(region, endpoint, fetchOptions) {
5466 this.endpoint = endpoint || "https://cognito-idp." + region + ".amazonaws.com/";
5467
5468 var _ref = fetchOptions || {},
5469 credentials = _ref.credentials;
5470
5471 this.fetchOptions = credentials ? {
5472 credentials: credentials
5473 } : {};
5474 }
5475 /**
5476 * Makes an unauthenticated request on AWS Cognito Identity Provider API
5477 * using fetch
5478 * @param {string} operation API operation
5479 * @param {object} params Input parameters
5480 * @returns Promise<object>
5481 */
5482
5483
5484 var _proto = Client.prototype;
5485
5486 _proto.promisifyRequest = function promisifyRequest(operation, params) {
5487 var _this2 = this;
5488
5489 return new Promise(function (resolve, reject) {
5490 _this2.request(operation, params, function (err, data) {
5491 if (err) {
5492 reject(new CognitoError(err.message, err.code, err.name, err.statusCode));
5493 } else {
5494 resolve(data);
5495 }
5496 });
5497 });
5498 };
5499
5500 _proto.requestWithRetry = function requestWithRetry(operation, params, callback) {
5501 var _this3 = this;
5502
5503 var MAX_DELAY_IN_MILLIS = 5 * 1000;
5504 jitteredExponentialRetry(function (p) {
5505 return new Promise(function (res, rej) {
5506 _this3.request(operation, p, function (error, result) {
5507 if (error) {
5508 rej(error);
5509 } else {
5510 res(result);
5511 }
5512 });
5513 });
5514 }, [params], MAX_DELAY_IN_MILLIS).then(function (result) {
5515 return callback(null, result);
5516 })["catch"](function (error) {
5517 return callback(error);
5518 });
5519 }
5520 /**
5521 * Makes an unauthenticated request on AWS Cognito Identity Provider API
5522 * using fetch
5523 * @param {string} operation API operation
5524 * @param {object} params Input parameters
5525 * @param {function} callback Callback called when a response is returned
5526 * @returns {void}
5527 */
5528 ;
5529
5530 _proto.request = function request(operation, params, callback) {
5531 var headers = {
5532 'Content-Type': 'application/x-amz-json-1.1',
5533 'X-Amz-Target': "AWSCognitoIdentityProviderService." + operation,
5534 'X-Amz-User-Agent': _UserAgent__WEBPACK_IMPORTED_MODULE_1__["default"].prototype.userAgent
5535 };
5536 var options = Object.assign({}, this.fetchOptions, {
5537 headers: headers,
5538 method: 'POST',
5539 mode: 'cors',
5540 cache: 'no-cache',
5541 body: JSON.stringify(params)
5542 });
5543 var response;
5544 var responseJsonData;
5545 fetch(this.endpoint, options).then(function (resp) {
5546 response = resp;
5547 return resp;
5548 }, function (err) {
5549 // If error happens here, the request failed
5550 // if it is TypeError throw network error
5551 if (err instanceof TypeError) {
5552 throw new Error('Network error');
5553 }
5554
5555 throw err;
5556 }).then(function (resp) {
5557 return resp.json()["catch"](function () {
5558 return {};
5559 });
5560 }).then(function (data) {
5561 // return parsed body stream
5562 if (response.ok) return callback(null, data);
5563 responseJsonData = data; // Taken from aws-sdk-js/lib/protocol/json.js
5564 // eslint-disable-next-line no-underscore-dangle
5565
5566 var code = (data.__type || data.code).split('#').pop();
5567 var error = new Error(data.message || data.Message || null);
5568 error.name = code;
5569 error.code = code;
5570 return callback(error);
5571 })["catch"](function (err) {
5572 // first check if we have a service error
5573 if (response && response.headers && response.headers.get('x-amzn-errortype')) {
5574 try {
5575 var code = response.headers.get('x-amzn-errortype').split(':')[0];
5576 var error = new Error(response.status ? response.status.toString() : null);
5577 error.code = code;
5578 error.name = code;
5579 error.statusCode = response.status;
5580 return callback(error);
5581 } catch (ex) {
5582 return callback(err);
5583 } // otherwise check if error is Network error
5584
5585 } else if (err instanceof Error && err.message === 'Network error') {
5586 err.code = 'NetworkError';
5587 }
5588
5589 return callback(err);
5590 });
5591 };
5592
5593 return Client;
5594}();
5595
5596
5597var logger = {
5598 debug: function debug() {// Intentionally blank. This package doesn't have logging
5599 }
5600};
5601/**
5602 * For now, all errors are retryable.
5603 */
5604
5605var NonRetryableError = /*#__PURE__*/function (_Error2) {
5606 _inheritsLoose(NonRetryableError, _Error2);
5607
5608 function NonRetryableError(message) {
5609 var _this4;
5610
5611 _this4 = _Error2.call(this, message) || this;
5612 _this4.nonRetryable = true;
5613 return _this4;
5614 }
5615
5616 return NonRetryableError;
5617}( /*#__PURE__*/_wrapNativeSuper(Error));
5618
5619var isNonRetryableError = function isNonRetryableError(obj) {
5620 var key = 'nonRetryable';
5621 return obj && obj[key];
5622};
5623
5624function retry(functionToRetry, args, delayFn, attempt) {
5625 if (attempt === void 0) {
5626 attempt = 1;
5627 }
5628
5629 if (typeof functionToRetry !== 'function') {
5630 throw Error('functionToRetry must be a function');
5631 }
5632
5633 logger.debug(functionToRetry.name + " attempt #" + attempt + " with args: " + JSON.stringify(args));
5634 return functionToRetry.apply(void 0, args)["catch"](function (err) {
5635 logger.debug("error on " + functionToRetry.name, err);
5636
5637 if (isNonRetryableError(err)) {
5638 logger.debug(functionToRetry.name + " non retryable error", err);
5639 throw err;
5640 }
5641
5642 var retryIn = delayFn(attempt, args, err);
5643 logger.debug(functionToRetry.name + " retrying in " + retryIn + " ms");
5644
5645 if (retryIn !== false) {
5646 return new Promise(function (res) {
5647 return setTimeout(res, retryIn);
5648 }).then(function () {
5649 return retry(functionToRetry, args, delayFn, attempt + 1);
5650 });
5651 } else {
5652 throw err;
5653 }
5654 });
5655}
5656
5657function jitteredBackoff(maxDelayMs) {
5658 var BASE_TIME_MS = 100;
5659 var JITTER_FACTOR = 100;
5660 return function (attempt) {
5661 var delay = Math.pow(2, attempt) * BASE_TIME_MS + JITTER_FACTOR * Math.random();
5662 return delay > maxDelayMs ? false : delay;
5663 };
5664}
5665
5666var MAX_DELAY_MS = 5 * 60 * 1000;
5667
5668function jitteredExponentialRetry(functionToRetry, args, maxDelayMs) {
5669 if (maxDelayMs === void 0) {
5670 maxDelayMs = MAX_DELAY_MS;
5671 }
5672
5673 return retry(functionToRetry, args, jitteredBackoff(maxDelayMs));
5674}
5675
5676;
5677
5678/***/ }),
5679
5680/***/ "../amazon-cognito-identity-js/es/CognitoAccessToken.js":
5681/*!**************************************************************!*\
5682 !*** ../amazon-cognito-identity-js/es/CognitoAccessToken.js ***!
5683 \**************************************************************/
5684/*! exports provided: default */
5685/***/ (function(module, __webpack_exports__, __webpack_require__) {
5686
5687"use strict";
5688__webpack_require__.r(__webpack_exports__);
5689/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoAccessToken; });
5690/* harmony import */ var _CognitoJwtToken__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CognitoJwtToken */ "../amazon-cognito-identity-js/es/CognitoJwtToken.js");
5691function _inheritsLoose(subClass, superClass) {
5692 subClass.prototype = Object.create(superClass.prototype);
5693 subClass.prototype.constructor = subClass;
5694
5695 _setPrototypeOf(subClass, superClass);
5696}
5697
5698function _setPrototypeOf(o, p) {
5699 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
5700 o.__proto__ = p;
5701 return o;
5702 };
5703
5704 return _setPrototypeOf(o, p);
5705}
5706/*!
5707 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5708 * SPDX-License-Identifier: Apache-2.0
5709 */
5710
5711
5712
5713/** @class */
5714
5715var CognitoAccessToken = /*#__PURE__*/function (_CognitoJwtToken) {
5716 _inheritsLoose(CognitoAccessToken, _CognitoJwtToken);
5717 /**
5718 * Constructs a new CognitoAccessToken object
5719 * @param {string=} AccessToken The JWT access token.
5720 */
5721
5722
5723 function CognitoAccessToken(_temp) {
5724 var _ref = _temp === void 0 ? {} : _temp,
5725 AccessToken = _ref.AccessToken;
5726
5727 return _CognitoJwtToken.call(this, AccessToken || '') || this;
5728 }
5729
5730 return CognitoAccessToken;
5731}(_CognitoJwtToken__WEBPACK_IMPORTED_MODULE_0__["default"]);
5732
5733
5734
5735/***/ }),
5736
5737/***/ "../amazon-cognito-identity-js/es/CognitoIdToken.js":
5738/*!**********************************************************!*\
5739 !*** ../amazon-cognito-identity-js/es/CognitoIdToken.js ***!
5740 \**********************************************************/
5741/*! exports provided: default */
5742/***/ (function(module, __webpack_exports__, __webpack_require__) {
5743
5744"use strict";
5745__webpack_require__.r(__webpack_exports__);
5746/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoIdToken; });
5747/* harmony import */ var _CognitoJwtToken__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CognitoJwtToken */ "../amazon-cognito-identity-js/es/CognitoJwtToken.js");
5748function _inheritsLoose(subClass, superClass) {
5749 subClass.prototype = Object.create(superClass.prototype);
5750 subClass.prototype.constructor = subClass;
5751
5752 _setPrototypeOf(subClass, superClass);
5753}
5754
5755function _setPrototypeOf(o, p) {
5756 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
5757 o.__proto__ = p;
5758 return o;
5759 };
5760
5761 return _setPrototypeOf(o, p);
5762}
5763/*!
5764 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5765 * SPDX-License-Identifier: Apache-2.0
5766 */
5767
5768
5769
5770/** @class */
5771
5772var CognitoIdToken = /*#__PURE__*/function (_CognitoJwtToken) {
5773 _inheritsLoose(CognitoIdToken, _CognitoJwtToken);
5774 /**
5775 * Constructs a new CognitoIdToken object
5776 * @param {string=} IdToken The JWT Id token
5777 */
5778
5779
5780 function CognitoIdToken(_temp) {
5781 var _ref = _temp === void 0 ? {} : _temp,
5782 IdToken = _ref.IdToken;
5783
5784 return _CognitoJwtToken.call(this, IdToken || '') || this;
5785 }
5786
5787 return CognitoIdToken;
5788}(_CognitoJwtToken__WEBPACK_IMPORTED_MODULE_0__["default"]);
5789
5790
5791
5792/***/ }),
5793
5794/***/ "../amazon-cognito-identity-js/es/CognitoJwtToken.js":
5795/*!***********************************************************!*\
5796 !*** ../amazon-cognito-identity-js/es/CognitoJwtToken.js ***!
5797 \***********************************************************/
5798/*! exports provided: default */
5799/***/ (function(module, __webpack_exports__, __webpack_require__) {
5800
5801"use strict";
5802__webpack_require__.r(__webpack_exports__);
5803/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoJwtToken; });
5804/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer */ "../../node_modules/buffer/index.js");
5805/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(buffer__WEBPACK_IMPORTED_MODULE_0__);
5806/*!
5807 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5808 * SPDX-License-Identifier: Apache-2.0
5809 */
5810
5811/** @class */
5812
5813var CognitoJwtToken = /*#__PURE__*/function () {
5814 /**
5815 * Constructs a new CognitoJwtToken object
5816 * @param {string=} token The JWT token.
5817 */
5818 function CognitoJwtToken(token) {
5819 // Assign object
5820 this.jwtToken = token || '';
5821 this.payload = this.decodePayload();
5822 }
5823 /**
5824 * @returns {string} the record's token.
5825 */
5826
5827
5828 var _proto = CognitoJwtToken.prototype;
5829
5830 _proto.getJwtToken = function getJwtToken() {
5831 return this.jwtToken;
5832 }
5833 /**
5834 * @returns {int} the token's expiration (exp member).
5835 */
5836 ;
5837
5838 _proto.getExpiration = function getExpiration() {
5839 return this.payload.exp;
5840 }
5841 /**
5842 * @returns {int} the token's "issued at" (iat member).
5843 */
5844 ;
5845
5846 _proto.getIssuedAt = function getIssuedAt() {
5847 return this.payload.iat;
5848 }
5849 /**
5850 * @returns {object} the token's payload.
5851 */
5852 ;
5853
5854 _proto.decodePayload = function decodePayload() {
5855 var payload = this.jwtToken.split('.')[1];
5856
5857 try {
5858 return JSON.parse(buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(payload, 'base64').toString('utf8'));
5859 } catch (err) {
5860 return {};
5861 }
5862 };
5863
5864 return CognitoJwtToken;
5865}();
5866
5867
5868
5869/***/ }),
5870
5871/***/ "../amazon-cognito-identity-js/es/CognitoRefreshToken.js":
5872/*!***************************************************************!*\
5873 !*** ../amazon-cognito-identity-js/es/CognitoRefreshToken.js ***!
5874 \***************************************************************/
5875/*! exports provided: default */
5876/***/ (function(module, __webpack_exports__, __webpack_require__) {
5877
5878"use strict";
5879__webpack_require__.r(__webpack_exports__);
5880/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoRefreshToken; });
5881/*!
5882 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5883 * SPDX-License-Identifier: Apache-2.0
5884 */
5885
5886/** @class */
5887var CognitoRefreshToken = /*#__PURE__*/function () {
5888 /**
5889 * Constructs a new CognitoRefreshToken object
5890 * @param {string=} RefreshToken The JWT refresh token.
5891 */
5892 function CognitoRefreshToken(_temp) {
5893 var _ref = _temp === void 0 ? {} : _temp,
5894 RefreshToken = _ref.RefreshToken; // Assign object
5895
5896
5897 this.token = RefreshToken || '';
5898 }
5899 /**
5900 * @returns {string} the record's token.
5901 */
5902
5903
5904 var _proto = CognitoRefreshToken.prototype;
5905
5906 _proto.getToken = function getToken() {
5907 return this.token;
5908 };
5909
5910 return CognitoRefreshToken;
5911}();
5912
5913
5914
5915/***/ }),
5916
5917/***/ "../amazon-cognito-identity-js/es/CognitoUser.js":
5918/*!*******************************************************!*\
5919 !*** ../amazon-cognito-identity-js/es/CognitoUser.js ***!
5920 \*******************************************************/
5921/*! exports provided: default */
5922/***/ (function(module, __webpack_exports__, __webpack_require__) {
5923
5924"use strict";
5925__webpack_require__.r(__webpack_exports__);
5926/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoUser; });
5927/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer */ "../../node_modules/buffer/index.js");
5928/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(buffer__WEBPACK_IMPORTED_MODULE_0__);
5929/* 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");
5930/* harmony import */ var crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(crypto_js_core__WEBPACK_IMPORTED_MODULE_1__);
5931/* 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");
5932/* harmony import */ var crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(crypto_js_lib_typedarrays__WEBPACK_IMPORTED_MODULE_2__);
5933/* 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");
5934/* harmony import */ var crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3__);
5935/* 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");
5936/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4__);
5937/* harmony import */ var _BigInteger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./BigInteger */ "../amazon-cognito-identity-js/es/BigInteger.js");
5938/* harmony import */ var _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./AuthenticationHelper */ "../amazon-cognito-identity-js/es/AuthenticationHelper.js");
5939/* harmony import */ var _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CognitoAccessToken */ "../amazon-cognito-identity-js/es/CognitoAccessToken.js");
5940/* harmony import */ var _CognitoIdToken__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./CognitoIdToken */ "../amazon-cognito-identity-js/es/CognitoIdToken.js");
5941/* harmony import */ var _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./CognitoRefreshToken */ "../amazon-cognito-identity-js/es/CognitoRefreshToken.js");
5942/* harmony import */ var _CognitoUserSession__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./CognitoUserSession */ "../amazon-cognito-identity-js/es/CognitoUserSession.js");
5943/* harmony import */ var _DateHelper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./DateHelper */ "../amazon-cognito-identity-js/es/DateHelper.js");
5944/* harmony import */ var _CognitoUserAttribute__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./CognitoUserAttribute */ "../amazon-cognito-identity-js/es/CognitoUserAttribute.js");
5945/* harmony import */ var _StorageHelper__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./StorageHelper */ "../amazon-cognito-identity-js/es/StorageHelper.js");
5946/*!
5947 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5948 * SPDX-License-Identifier: Apache-2.0
5949 */
5950
5951
5952 // necessary for crypto js
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965/**
5966 * @callback nodeCallback
5967 * @template T result
5968 * @param {*} err The operation failure reason, or null.
5969 * @param {T} result The operation result.
5970 */
5971
5972/**
5973 * @callback onFailure
5974 * @param {*} err Failure reason.
5975 */
5976
5977/**
5978 * @callback onSuccess
5979 * @template T result
5980 * @param {T} result The operation result.
5981 */
5982
5983/**
5984 * @callback mfaRequired
5985 * @param {*} details MFA challenge details.
5986 */
5987
5988/**
5989 * @callback customChallenge
5990 * @param {*} details Custom challenge details.
5991 */
5992
5993/**
5994 * @callback inputVerificationCode
5995 * @param {*} data Server response.
5996 */
5997
5998/**
5999 * @callback authSuccess
6000 * @param {CognitoUserSession} session The new session.
6001 * @param {bool=} userConfirmationNecessary User must be confirmed.
6002 */
6003
6004var isBrowser = typeof navigator !== 'undefined';
6005var userAgent = isBrowser ? navigator.userAgent : 'nodejs';
6006/** @class */
6007
6008var CognitoUser = /*#__PURE__*/function () {
6009 /**
6010 * Constructs a new CognitoUser object
6011 * @param {object} data Creation options
6012 * @param {string} data.Username The user's username.
6013 * @param {CognitoUserPool} data.Pool Pool containing the user.
6014 * @param {object} data.Storage Optional storage object.
6015 */
6016 function CognitoUser(data) {
6017 if (data == null || data.Username == null || data.Pool == null) {
6018 throw new Error('Username and Pool information are required.');
6019 }
6020
6021 this.username = data.Username || '';
6022 this.pool = data.Pool;
6023 this.Session = null;
6024 this.client = data.Pool.client;
6025 this.signInUserSession = null;
6026 this.authenticationFlowType = 'USER_SRP_AUTH';
6027 this.storage = data.Storage || new _StorageHelper__WEBPACK_IMPORTED_MODULE_13__["default"]().getStorage();
6028 this.keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
6029 this.userDataKey = this.keyPrefix + "." + this.username + ".userData";
6030 }
6031 /**
6032 * Sets the session for this user
6033 * @param {CognitoUserSession} signInUserSession the session
6034 * @returns {void}
6035 */
6036
6037
6038 var _proto = CognitoUser.prototype;
6039
6040 _proto.setSignInUserSession = function setSignInUserSession(signInUserSession) {
6041 this.clearCachedUserData();
6042 this.signInUserSession = signInUserSession;
6043 this.cacheTokens();
6044 }
6045 /**
6046 * @returns {CognitoUserSession} the current session for this user
6047 */
6048 ;
6049
6050 _proto.getSignInUserSession = function getSignInUserSession() {
6051 return this.signInUserSession;
6052 }
6053 /**
6054 * @returns {string} the user's username
6055 */
6056 ;
6057
6058 _proto.getUsername = function getUsername() {
6059 return this.username;
6060 }
6061 /**
6062 * @returns {String} the authentication flow type
6063 */
6064 ;
6065
6066 _proto.getAuthenticationFlowType = function getAuthenticationFlowType() {
6067 return this.authenticationFlowType;
6068 }
6069 /**
6070 * sets authentication flow type
6071 * @param {string} authenticationFlowType New value.
6072 * @returns {void}
6073 */
6074 ;
6075
6076 _proto.setAuthenticationFlowType = function setAuthenticationFlowType(authenticationFlowType) {
6077 this.authenticationFlowType = authenticationFlowType;
6078 }
6079 /**
6080 * This is used for authenticating the user through the custom authentication flow.
6081 * @param {AuthenticationDetails} authDetails Contains the authentication data
6082 * @param {object} callback Result callback map.
6083 * @param {onFailure} callback.onFailure Called on any error.
6084 * @param {customChallenge} callback.customChallenge Custom challenge
6085 * response required to continue.
6086 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6087 * @returns {void}
6088 */
6089 ;
6090
6091 _proto.initiateAuth = function initiateAuth(authDetails, callback) {
6092 var _this = this;
6093
6094 var authParameters = authDetails.getAuthParameters();
6095 authParameters.USERNAME = this.username;
6096 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
6097 var jsonReq = {
6098 AuthFlow: 'CUSTOM_AUTH',
6099 ClientId: this.pool.getClientId(),
6100 AuthParameters: authParameters,
6101 ClientMetadata: clientMetaData
6102 };
6103
6104 if (this.getUserContextData()) {
6105 jsonReq.UserContextData = this.getUserContextData();
6106 }
6107
6108 this.client.request('InitiateAuth', jsonReq, function (err, data) {
6109 if (err) {
6110 return callback.onFailure(err);
6111 }
6112
6113 var challengeName = data.ChallengeName;
6114 var challengeParameters = data.ChallengeParameters;
6115
6116 if (challengeName === 'CUSTOM_CHALLENGE') {
6117 _this.Session = data.Session;
6118 return callback.customChallenge(challengeParameters);
6119 }
6120
6121 _this.signInUserSession = _this.getCognitoUserSession(data.AuthenticationResult);
6122
6123 _this.cacheTokens();
6124
6125 return callback.onSuccess(_this.signInUserSession);
6126 });
6127 }
6128 /**
6129 * This is used for authenticating the user.
6130 * stuff
6131 * @param {AuthenticationDetails} authDetails Contains the authentication data
6132 * @param {object} callback Result callback map.
6133 * @param {onFailure} callback.onFailure Called on any error.
6134 * @param {newPasswordRequired} callback.newPasswordRequired new
6135 * password and any required attributes are required to continue
6136 * @param {mfaRequired} callback.mfaRequired MFA code
6137 * required to continue.
6138 * @param {customChallenge} callback.customChallenge Custom challenge
6139 * response required to continue.
6140 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6141 * @returns {void}
6142 */
6143 ;
6144
6145 _proto.authenticateUser = function authenticateUser(authDetails, callback) {
6146 if (this.authenticationFlowType === 'USER_PASSWORD_AUTH') {
6147 return this.authenticateUserPlainUsernamePassword(authDetails, callback);
6148 } else if (this.authenticationFlowType === 'USER_SRP_AUTH' || this.authenticationFlowType === 'CUSTOM_AUTH') {
6149 return this.authenticateUserDefaultAuth(authDetails, callback);
6150 }
6151
6152 return callback.onFailure(new Error('Authentication flow type is invalid.'));
6153 }
6154 /**
6155 * PRIVATE ONLY: This is an internal only method and should not
6156 * be directly called by the consumers.
6157 * It calls the AuthenticationHelper for SRP related
6158 * stuff
6159 * @param {AuthenticationDetails} authDetails Contains the authentication data
6160 * @param {object} callback Result callback map.
6161 * @param {onFailure} callback.onFailure Called on any error.
6162 * @param {newPasswordRequired} callback.newPasswordRequired new
6163 * password and any required attributes are required to continue
6164 * @param {mfaRequired} callback.mfaRequired MFA code
6165 * required to continue.
6166 * @param {customChallenge} callback.customChallenge Custom challenge
6167 * response required to continue.
6168 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6169 * @returns {void}
6170 */
6171 ;
6172
6173 _proto.authenticateUserDefaultAuth = function authenticateUserDefaultAuth(authDetails, callback) {
6174 var _this2 = this;
6175
6176 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.pool.getUserPoolId().split('_')[1]);
6177 var dateHelper = new _DateHelper__WEBPACK_IMPORTED_MODULE_11__["default"]();
6178 var serverBValue;
6179 var salt;
6180 var authParameters = {};
6181
6182 if (this.deviceKey != null) {
6183 authParameters.DEVICE_KEY = this.deviceKey;
6184 }
6185
6186 authParameters.USERNAME = this.username;
6187 authenticationHelper.getLargeAValue(function (errOnAValue, aValue) {
6188 // getLargeAValue callback start
6189 if (errOnAValue) {
6190 callback.onFailure(errOnAValue);
6191 }
6192
6193 authParameters.SRP_A = aValue.toString(16);
6194
6195 if (_this2.authenticationFlowType === 'CUSTOM_AUTH') {
6196 authParameters.CHALLENGE_NAME = 'SRP_A';
6197 }
6198
6199 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
6200 var jsonReq = {
6201 AuthFlow: _this2.authenticationFlowType,
6202 ClientId: _this2.pool.getClientId(),
6203 AuthParameters: authParameters,
6204 ClientMetadata: clientMetaData
6205 };
6206
6207 if (_this2.getUserContextData(_this2.username)) {
6208 jsonReq.UserContextData = _this2.getUserContextData(_this2.username);
6209 }
6210
6211 _this2.client.request('InitiateAuth', jsonReq, function (err, data) {
6212 if (err) {
6213 return callback.onFailure(err);
6214 }
6215
6216 var challengeParameters = data.ChallengeParameters;
6217 _this2.username = challengeParameters.USER_ID_FOR_SRP;
6218 _this2.userDataKey = _this2.keyPrefix + "." + _this2.username + ".userData";
6219 serverBValue = new _BigInteger__WEBPACK_IMPORTED_MODULE_5__["default"](challengeParameters.SRP_B, 16);
6220 salt = new _BigInteger__WEBPACK_IMPORTED_MODULE_5__["default"](challengeParameters.SALT, 16);
6221
6222 _this2.getCachedDeviceKeyAndPassword();
6223
6224 authenticationHelper.getPasswordAuthenticationKey(_this2.username, authDetails.getPassword(), serverBValue, salt, function (errOnHkdf, hkdf) {
6225 // getPasswordAuthenticationKey callback start
6226 if (errOnHkdf) {
6227 callback.onFailure(errOnHkdf);
6228 }
6229
6230 var dateNow = dateHelper.getNowString();
6231 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')]));
6232 var key = crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(hkdf);
6233 var signatureString = crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3___default.a.stringify(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default()(message, key));
6234 var challengeResponses = {};
6235 challengeResponses.USERNAME = _this2.username;
6236 challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK;
6237 challengeResponses.TIMESTAMP = dateNow;
6238 challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString;
6239
6240 if (_this2.deviceKey != null) {
6241 challengeResponses.DEVICE_KEY = _this2.deviceKey;
6242 }
6243
6244 var respondToAuthChallenge = function respondToAuthChallenge(challenge, challengeCallback) {
6245 return _this2.client.request('RespondToAuthChallenge', challenge, function (errChallenge, dataChallenge) {
6246 if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) {
6247 challengeResponses.DEVICE_KEY = null;
6248 _this2.deviceKey = null;
6249 _this2.randomPassword = null;
6250 _this2.deviceGroupKey = null;
6251
6252 _this2.clearCachedDeviceKeyAndPassword();
6253
6254 return respondToAuthChallenge(challenge, challengeCallback);
6255 }
6256
6257 return challengeCallback(errChallenge, dataChallenge);
6258 });
6259 };
6260
6261 var jsonReqResp = {
6262 ChallengeName: 'PASSWORD_VERIFIER',
6263 ClientId: _this2.pool.getClientId(),
6264 ChallengeResponses: challengeResponses,
6265 Session: data.Session,
6266 ClientMetadata: clientMetaData
6267 };
6268
6269 if (_this2.getUserContextData()) {
6270 jsonReqResp.UserContextData = _this2.getUserContextData();
6271 }
6272
6273 respondToAuthChallenge(jsonReqResp, function (errAuthenticate, dataAuthenticate) {
6274 if (errAuthenticate) {
6275 return callback.onFailure(errAuthenticate);
6276 }
6277
6278 return _this2.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback);
6279 });
6280 return undefined; // getPasswordAuthenticationKey callback end
6281 });
6282 return undefined;
6283 }); // getLargeAValue callback end
6284
6285 });
6286 }
6287 /**
6288 * PRIVATE ONLY: This is an internal only method and should not
6289 * be directly called by the consumers.
6290 * @param {AuthenticationDetails} authDetails Contains the authentication data.
6291 * @param {object} callback Result callback map.
6292 * @param {onFailure} callback.onFailure Called on any error.
6293 * @param {mfaRequired} callback.mfaRequired MFA code
6294 * required to continue.
6295 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6296 * @returns {void}
6297 */
6298 ;
6299
6300 _proto.authenticateUserPlainUsernamePassword = function authenticateUserPlainUsernamePassword(authDetails, callback) {
6301 var _this3 = this;
6302
6303 var authParameters = {};
6304 authParameters.USERNAME = this.username;
6305 authParameters.PASSWORD = authDetails.getPassword();
6306
6307 if (!authParameters.PASSWORD) {
6308 callback.onFailure(new Error('PASSWORD parameter is required'));
6309 return;
6310 }
6311
6312 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.pool.getUserPoolId().split('_')[1]);
6313 this.getCachedDeviceKeyAndPassword();
6314
6315 if (this.deviceKey != null) {
6316 authParameters.DEVICE_KEY = this.deviceKey;
6317 }
6318
6319 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
6320 var jsonReq = {
6321 AuthFlow: 'USER_PASSWORD_AUTH',
6322 ClientId: this.pool.getClientId(),
6323 AuthParameters: authParameters,
6324 ClientMetadata: clientMetaData
6325 };
6326
6327 if (this.getUserContextData(this.username)) {
6328 jsonReq.UserContextData = this.getUserContextData(this.username);
6329 } // USER_PASSWORD_AUTH happens in a single round-trip: client sends userName and password,
6330 // Cognito UserPools verifies password and returns tokens.
6331
6332
6333 this.client.request('InitiateAuth', jsonReq, function (err, authResult) {
6334 if (err) {
6335 return callback.onFailure(err);
6336 }
6337
6338 return _this3.authenticateUserInternal(authResult, authenticationHelper, callback);
6339 });
6340 }
6341 /**
6342 * PRIVATE ONLY: This is an internal only method and should not
6343 * be directly called by the consumers.
6344 * @param {object} dataAuthenticate authentication data
6345 * @param {object} authenticationHelper helper created
6346 * @param {callback} callback passed on from caller
6347 * @returns {void}
6348 */
6349 ;
6350
6351 _proto.authenticateUserInternal = function authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) {
6352 var _this4 = this;
6353
6354 var challengeName = dataAuthenticate.ChallengeName;
6355 var challengeParameters = dataAuthenticate.ChallengeParameters;
6356
6357 if (challengeName === 'SMS_MFA') {
6358 this.Session = dataAuthenticate.Session;
6359 return callback.mfaRequired(challengeName, challengeParameters);
6360 }
6361
6362 if (challengeName === 'SELECT_MFA_TYPE') {
6363 this.Session = dataAuthenticate.Session;
6364 return callback.selectMFAType(challengeName, challengeParameters);
6365 }
6366
6367 if (challengeName === 'MFA_SETUP') {
6368 this.Session = dataAuthenticate.Session;
6369 return callback.mfaSetup(challengeName, challengeParameters);
6370 }
6371
6372 if (challengeName === 'SOFTWARE_TOKEN_MFA') {
6373 this.Session = dataAuthenticate.Session;
6374 return callback.totpRequired(challengeName, challengeParameters);
6375 }
6376
6377 if (challengeName === 'CUSTOM_CHALLENGE') {
6378 this.Session = dataAuthenticate.Session;
6379 return callback.customChallenge(challengeParameters);
6380 }
6381
6382 if (challengeName === 'NEW_PASSWORD_REQUIRED') {
6383 this.Session = dataAuthenticate.Session;
6384 var userAttributes = null;
6385 var rawRequiredAttributes = null;
6386 var requiredAttributes = [];
6387 var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix();
6388
6389 if (challengeParameters) {
6390 userAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.userAttributes);
6391 rawRequiredAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.requiredAttributes);
6392 }
6393
6394 if (rawRequiredAttributes) {
6395 for (var i = 0; i < rawRequiredAttributes.length; i++) {
6396 requiredAttributes[i] = rawRequiredAttributes[i].substr(userAttributesPrefix.length);
6397 }
6398 }
6399
6400 return callback.newPasswordRequired(userAttributes, requiredAttributes);
6401 }
6402
6403 if (challengeName === 'DEVICE_SRP_AUTH') {
6404 this.Session = dataAuthenticate.Session;
6405 this.getDeviceResponse(callback);
6406 return undefined;
6407 }
6408
6409 this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
6410 this.challengeName = challengeName;
6411 this.cacheTokens();
6412 var newDeviceMetadata = dataAuthenticate.AuthenticationResult.NewDeviceMetadata;
6413
6414 if (newDeviceMetadata == null) {
6415 return callback.onSuccess(this.signInUserSession);
6416 }
6417
6418 authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) {
6419 if (errGenHash) {
6420 return callback.onFailure(errGenHash);
6421 }
6422
6423 var deviceSecretVerifierConfig = {
6424 Salt: buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'),
6425 PasswordVerifier: buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64')
6426 };
6427 _this4.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier;
6428 _this4.deviceGroupKey = newDeviceMetadata.DeviceGroupKey;
6429 _this4.randomPassword = authenticationHelper.getRandomPassword();
6430
6431 _this4.client.request('ConfirmDevice', {
6432 DeviceKey: newDeviceMetadata.DeviceKey,
6433 AccessToken: _this4.signInUserSession.getAccessToken().getJwtToken(),
6434 DeviceSecretVerifierConfig: deviceSecretVerifierConfig,
6435 DeviceName: userAgent
6436 }, function (errConfirm, dataConfirm) {
6437 if (errConfirm) {
6438 return callback.onFailure(errConfirm);
6439 }
6440
6441 _this4.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey;
6442
6443 _this4.cacheDeviceKeyAndPassword();
6444
6445 if (dataConfirm.UserConfirmationNecessary === true) {
6446 return callback.onSuccess(_this4.signInUserSession, dataConfirm.UserConfirmationNecessary);
6447 }
6448
6449 return callback.onSuccess(_this4.signInUserSession);
6450 });
6451
6452 return undefined;
6453 });
6454 return undefined;
6455 }
6456 /**
6457 * This method is user to complete the NEW_PASSWORD_REQUIRED challenge.
6458 * Pass the new password with any new user attributes to be updated.
6459 * User attribute keys must be of format userAttributes.<attribute_name>.
6460 * @param {string} newPassword new password for this user
6461 * @param {object} requiredAttributeData map with values for all required attributes
6462 * @param {object} callback Result callback map.
6463 * @param {onFailure} callback.onFailure Called on any error.
6464 * @param {mfaRequired} callback.mfaRequired MFA code required to continue.
6465 * @param {customChallenge} callback.customChallenge Custom challenge
6466 * response required to continue.
6467 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6468 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6469 * @returns {void}
6470 */
6471 ;
6472
6473 _proto.completeNewPasswordChallenge = function completeNewPasswordChallenge(newPassword, requiredAttributeData, callback, clientMetadata) {
6474 var _this5 = this;
6475
6476 if (!newPassword) {
6477 return callback.onFailure(new Error('New password is required.'));
6478 }
6479
6480 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.pool.getUserPoolId().split('_')[1]);
6481 var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix();
6482 var finalUserAttributes = {};
6483
6484 if (requiredAttributeData) {
6485 Object.keys(requiredAttributeData).forEach(function (key) {
6486 finalUserAttributes[userAttributesPrefix + key] = requiredAttributeData[key];
6487 });
6488 }
6489
6490 finalUserAttributes.NEW_PASSWORD = newPassword;
6491 finalUserAttributes.USERNAME = this.username;
6492 var jsonReq = {
6493 ChallengeName: 'NEW_PASSWORD_REQUIRED',
6494 ClientId: this.pool.getClientId(),
6495 ChallengeResponses: finalUserAttributes,
6496 Session: this.Session,
6497 ClientMetadata: clientMetadata
6498 };
6499
6500 if (this.getUserContextData()) {
6501 jsonReq.UserContextData = this.getUserContextData();
6502 }
6503
6504 this.client.request('RespondToAuthChallenge', jsonReq, function (errAuthenticate, dataAuthenticate) {
6505 if (errAuthenticate) {
6506 return callback.onFailure(errAuthenticate);
6507 }
6508
6509 return _this5.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback);
6510 });
6511 return undefined;
6512 }
6513 /**
6514 * This is used to get a session using device authentication. It is called at the end of user
6515 * authentication
6516 *
6517 * @param {object} callback Result callback map.
6518 * @param {onFailure} callback.onFailure Called on any error.
6519 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6520 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6521 * @returns {void}
6522 * @private
6523 */
6524 ;
6525
6526 _proto.getDeviceResponse = function getDeviceResponse(callback, clientMetadata) {
6527 var _this6 = this;
6528
6529 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.deviceGroupKey);
6530 var dateHelper = new _DateHelper__WEBPACK_IMPORTED_MODULE_11__["default"]();
6531 var authParameters = {};
6532 authParameters.USERNAME = this.username;
6533 authParameters.DEVICE_KEY = this.deviceKey;
6534 authenticationHelper.getLargeAValue(function (errAValue, aValue) {
6535 // getLargeAValue callback start
6536 if (errAValue) {
6537 callback.onFailure(errAValue);
6538 }
6539
6540 authParameters.SRP_A = aValue.toString(16);
6541 var jsonReq = {
6542 ChallengeName: 'DEVICE_SRP_AUTH',
6543 ClientId: _this6.pool.getClientId(),
6544 ChallengeResponses: authParameters,
6545 ClientMetadata: clientMetadata,
6546 Session: _this6.Session
6547 };
6548
6549 if (_this6.getUserContextData()) {
6550 jsonReq.UserContextData = _this6.getUserContextData();
6551 }
6552
6553 _this6.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
6554 if (err) {
6555 return callback.onFailure(err);
6556 }
6557
6558 var challengeParameters = data.ChallengeParameters;
6559 var serverBValue = new _BigInteger__WEBPACK_IMPORTED_MODULE_5__["default"](challengeParameters.SRP_B, 16);
6560 var salt = new _BigInteger__WEBPACK_IMPORTED_MODULE_5__["default"](challengeParameters.SALT, 16);
6561 authenticationHelper.getPasswordAuthenticationKey(_this6.deviceKey, _this6.randomPassword, serverBValue, salt, function (errHkdf, hkdf) {
6562 // getPasswordAuthenticationKey callback start
6563 if (errHkdf) {
6564 return callback.onFailure(errHkdf);
6565 }
6566
6567 var dateNow = dateHelper.getNowString();
6568 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')]));
6569 var key = crypto_js_core__WEBPACK_IMPORTED_MODULE_1___default.a.lib.WordArray.create(hkdf);
6570 var signatureString = crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_3___default.a.stringify(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_4___default()(message, key));
6571 var challengeResponses = {};
6572 challengeResponses.USERNAME = _this6.username;
6573 challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK;
6574 challengeResponses.TIMESTAMP = dateNow;
6575 challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString;
6576 challengeResponses.DEVICE_KEY = _this6.deviceKey;
6577 var jsonReqResp = {
6578 ChallengeName: 'DEVICE_PASSWORD_VERIFIER',
6579 ClientId: _this6.pool.getClientId(),
6580 ChallengeResponses: challengeResponses,
6581 Session: data.Session
6582 };
6583
6584 if (_this6.getUserContextData()) {
6585 jsonReqResp.UserContextData = _this6.getUserContextData();
6586 }
6587
6588 _this6.client.request('RespondToAuthChallenge', jsonReqResp, function (errAuthenticate, dataAuthenticate) {
6589 if (errAuthenticate) {
6590 return callback.onFailure(errAuthenticate);
6591 }
6592
6593 _this6.signInUserSession = _this6.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
6594
6595 _this6.cacheTokens();
6596
6597 return callback.onSuccess(_this6.signInUserSession);
6598 });
6599
6600 return undefined; // getPasswordAuthenticationKey callback end
6601 });
6602 return undefined;
6603 }); // getLargeAValue callback end
6604
6605 });
6606 }
6607 /**
6608 * This is used for a certain user to confirm the registration by using a confirmation code
6609 * @param {string} confirmationCode Code entered by user.
6610 * @param {bool} forceAliasCreation Allow migrating from an existing email / phone number.
6611 * @param {nodeCallback<string>} callback Called on success or error.
6612 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6613 * @returns {void}
6614 */
6615 ;
6616
6617 _proto.confirmRegistration = function confirmRegistration(confirmationCode, forceAliasCreation, callback, clientMetadata) {
6618 var jsonReq = {
6619 ClientId: this.pool.getClientId(),
6620 ConfirmationCode: confirmationCode,
6621 Username: this.username,
6622 ForceAliasCreation: forceAliasCreation,
6623 ClientMetadata: clientMetadata
6624 };
6625
6626 if (this.getUserContextData()) {
6627 jsonReq.UserContextData = this.getUserContextData();
6628 }
6629
6630 this.client.request('ConfirmSignUp', jsonReq, function (err) {
6631 if (err) {
6632 return callback(err, null);
6633 }
6634
6635 return callback(null, 'SUCCESS');
6636 });
6637 }
6638 /**
6639 * This is used by the user once he has the responses to a custom challenge
6640 * @param {string} answerChallenge The custom challenge answer.
6641 * @param {object} callback Result callback map.
6642 * @param {onFailure} callback.onFailure Called on any error.
6643 * @param {customChallenge} callback.customChallenge
6644 * Custom challenge response required to continue.
6645 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6646 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6647 * @returns {void}
6648 */
6649 ;
6650
6651 _proto.sendCustomChallengeAnswer = function sendCustomChallengeAnswer(answerChallenge, callback, clientMetadata) {
6652 var _this7 = this;
6653
6654 var challengeResponses = {};
6655 challengeResponses.USERNAME = this.username;
6656 challengeResponses.ANSWER = answerChallenge;
6657 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](this.pool.getUserPoolId().split('_')[1]);
6658 this.getCachedDeviceKeyAndPassword();
6659
6660 if (this.deviceKey != null) {
6661 challengeResponses.DEVICE_KEY = this.deviceKey;
6662 }
6663
6664 var jsonReq = {
6665 ChallengeName: 'CUSTOM_CHALLENGE',
6666 ChallengeResponses: challengeResponses,
6667 ClientId: this.pool.getClientId(),
6668 Session: this.Session,
6669 ClientMetadata: clientMetadata
6670 };
6671
6672 if (this.getUserContextData()) {
6673 jsonReq.UserContextData = this.getUserContextData();
6674 }
6675
6676 this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
6677 if (err) {
6678 return callback.onFailure(err);
6679 }
6680
6681 return _this7.authenticateUserInternal(data, authenticationHelper, callback);
6682 });
6683 }
6684 /**
6685 * This is used by the user once he has an MFA code
6686 * @param {string} confirmationCode The MFA code entered by the user.
6687 * @param {object} callback Result callback map.
6688 * @param {string} mfaType The mfa we are replying to.
6689 * @param {onFailure} callback.onFailure Called on any error.
6690 * @param {authSuccess} callback.onSuccess Called on success with the new session.
6691 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6692 * @returns {void}
6693 */
6694 ;
6695
6696 _proto.sendMFACode = function sendMFACode(confirmationCode, callback, mfaType, clientMetadata) {
6697 var _this8 = this;
6698
6699 var challengeResponses = {};
6700 challengeResponses.USERNAME = this.username;
6701 challengeResponses.SMS_MFA_CODE = confirmationCode;
6702 var mfaTypeSelection = mfaType || 'SMS_MFA';
6703
6704 if (mfaTypeSelection === 'SOFTWARE_TOKEN_MFA') {
6705 challengeResponses.SOFTWARE_TOKEN_MFA_CODE = confirmationCode;
6706 }
6707
6708 if (this.deviceKey != null) {
6709 challengeResponses.DEVICE_KEY = this.deviceKey;
6710 }
6711
6712 var jsonReq = {
6713 ChallengeName: mfaTypeSelection,
6714 ChallengeResponses: challengeResponses,
6715 ClientId: this.pool.getClientId(),
6716 Session: this.Session,
6717 ClientMetadata: clientMetadata
6718 };
6719
6720 if (this.getUserContextData()) {
6721 jsonReq.UserContextData = this.getUserContextData();
6722 }
6723
6724 this.client.request('RespondToAuthChallenge', jsonReq, function (err, dataAuthenticate) {
6725 if (err) {
6726 return callback.onFailure(err);
6727 }
6728
6729 var challengeName = dataAuthenticate.ChallengeName;
6730
6731 if (challengeName === 'DEVICE_SRP_AUTH') {
6732 _this8.getDeviceResponse(callback);
6733
6734 return undefined;
6735 }
6736
6737 _this8.signInUserSession = _this8.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
6738
6739 _this8.cacheTokens();
6740
6741 if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) {
6742 return callback.onSuccess(_this8.signInUserSession);
6743 }
6744
6745 var authenticationHelper = new _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_6__["default"](_this8.pool.getUserPoolId().split('_')[1]);
6746 authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) {
6747 if (errGenHash) {
6748 return callback.onFailure(errGenHash);
6749 }
6750
6751 var deviceSecretVerifierConfig = {
6752 Salt: buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'),
6753 PasswordVerifier: buffer__WEBPACK_IMPORTED_MODULE_0__["Buffer"].from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64')
6754 };
6755 _this8.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier;
6756 _this8.deviceGroupKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey;
6757 _this8.randomPassword = authenticationHelper.getRandomPassword();
6758
6759 _this8.client.request('ConfirmDevice', {
6760 DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey,
6761 AccessToken: _this8.signInUserSession.getAccessToken().getJwtToken(),
6762 DeviceSecretVerifierConfig: deviceSecretVerifierConfig,
6763 DeviceName: userAgent
6764 }, function (errConfirm, dataConfirm) {
6765 if (errConfirm) {
6766 return callback.onFailure(errConfirm);
6767 }
6768
6769 _this8.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey;
6770
6771 _this8.cacheDeviceKeyAndPassword();
6772
6773 if (dataConfirm.UserConfirmationNecessary === true) {
6774 return callback.onSuccess(_this8.signInUserSession, dataConfirm.UserConfirmationNecessary);
6775 }
6776
6777 return callback.onSuccess(_this8.signInUserSession);
6778 });
6779
6780 return undefined;
6781 });
6782 return undefined;
6783 });
6784 }
6785 /**
6786 * This is used by an authenticated user to change the current password
6787 * @param {string} oldUserPassword The current password.
6788 * @param {string} newUserPassword The requested new password.
6789 * @param {nodeCallback<string>} callback Called on success or error.
6790 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6791 * @returns {void}
6792 */
6793 ;
6794
6795 _proto.changePassword = function changePassword(oldUserPassword, newUserPassword, callback, clientMetadata) {
6796 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
6797 return callback(new Error('User is not authenticated'), null);
6798 }
6799
6800 this.client.request('ChangePassword', {
6801 PreviousPassword: oldUserPassword,
6802 ProposedPassword: newUserPassword,
6803 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6804 ClientMetadata: clientMetadata
6805 }, function (err) {
6806 if (err) {
6807 return callback(err, null);
6808 }
6809
6810 return callback(null, 'SUCCESS');
6811 });
6812 return undefined;
6813 }
6814 /**
6815 * This is used by an authenticated user to enable MFA for itself
6816 * @deprecated
6817 * @param {nodeCallback<string>} callback Called on success or error.
6818 * @returns {void}
6819 */
6820 ;
6821
6822 _proto.enableMFA = function enableMFA(callback) {
6823 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6824 return callback(new Error('User is not authenticated'), null);
6825 }
6826
6827 var mfaOptions = [];
6828 var mfaEnabled = {
6829 DeliveryMedium: 'SMS',
6830 AttributeName: 'phone_number'
6831 };
6832 mfaOptions.push(mfaEnabled);
6833 this.client.request('SetUserSettings', {
6834 MFAOptions: mfaOptions,
6835 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6836 }, function (err) {
6837 if (err) {
6838 return callback(err, null);
6839 }
6840
6841 return callback(null, 'SUCCESS');
6842 });
6843 return undefined;
6844 }
6845 /**
6846 * This is used by an authenticated user to enable MFA for itself
6847 * @param {IMfaSettings} smsMfaSettings the sms mfa settings
6848 * @param {IMFASettings} softwareTokenMfaSettings the software token mfa settings
6849 * @param {nodeCallback<string>} callback Called on success or error.
6850 * @returns {void}
6851 */
6852 ;
6853
6854 _proto.setUserMfaPreference = function setUserMfaPreference(smsMfaSettings, softwareTokenMfaSettings, callback) {
6855 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6856 return callback(new Error('User is not authenticated'), null);
6857 }
6858
6859 this.client.request('SetUserMFAPreference', {
6860 SMSMfaSettings: smsMfaSettings,
6861 SoftwareTokenMfaSettings: softwareTokenMfaSettings,
6862 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6863 }, function (err) {
6864 if (err) {
6865 return callback(err, null);
6866 }
6867
6868 return callback(null, 'SUCCESS');
6869 });
6870 return undefined;
6871 }
6872 /**
6873 * This is used by an authenticated user to disable MFA for itself
6874 * @deprecated
6875 * @param {nodeCallback<string>} callback Called on success or error.
6876 * @returns {void}
6877 */
6878 ;
6879
6880 _proto.disableMFA = function disableMFA(callback) {
6881 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6882 return callback(new Error('User is not authenticated'), null);
6883 }
6884
6885 var mfaOptions = [];
6886 this.client.request('SetUserSettings', {
6887 MFAOptions: mfaOptions,
6888 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
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 delete itself
6900 * @param {nodeCallback<string>} callback Called on success or error.
6901 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6902 * @returns {void}
6903 */
6904 ;
6905
6906 _proto.deleteUser = function deleteUser(callback, clientMetadata) {
6907 var _this9 = this;
6908
6909 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6910 return callback(new Error('User is not authenticated'), null);
6911 }
6912
6913 this.client.request('DeleteUser', {
6914 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6915 ClientMetadata: clientMetadata
6916 }, function (err) {
6917 if (err) {
6918 return callback(err, null);
6919 }
6920
6921 _this9.clearCachedUser();
6922
6923 return callback(null, 'SUCCESS');
6924 });
6925 return undefined;
6926 }
6927 /**
6928 * @typedef {CognitoUserAttribute | { Name:string, Value:string }} AttributeArg
6929 */
6930
6931 /**
6932 * This is used by an authenticated user to change a list of attributes
6933 * @param {AttributeArg[]} attributes A list of the new user attributes.
6934 * @param {nodeCallback<string>} callback Called on success or error.
6935 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6936 * @returns {void}
6937 */
6938 ;
6939
6940 _proto.updateAttributes = function updateAttributes(attributes, callback, clientMetadata) {
6941 var _this10 = this;
6942
6943 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6944 return callback(new Error('User is not authenticated'), null);
6945 }
6946
6947 this.client.request('UpdateUserAttributes', {
6948 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6949 UserAttributes: attributes,
6950 ClientMetadata: clientMetadata
6951 }, function (err) {
6952 if (err) {
6953 return callback(err, null);
6954 } // update cached user
6955
6956
6957 return _this10.getUserData(function () {
6958 return callback(null, 'SUCCESS');
6959 }, {
6960 bypassCache: true
6961 });
6962 });
6963 return undefined;
6964 }
6965 /**
6966 * This is used by an authenticated user to get a list of attributes
6967 * @param {nodeCallback<CognitoUserAttribute[]>} callback Called on success or error.
6968 * @returns {void}
6969 */
6970 ;
6971
6972 _proto.getUserAttributes = function getUserAttributes(callback) {
6973 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
6974 return callback(new Error('User is not authenticated'), null);
6975 }
6976
6977 this.client.request('GetUser', {
6978 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6979 }, function (err, userData) {
6980 if (err) {
6981 return callback(err, null);
6982 }
6983
6984 var attributeList = [];
6985
6986 for (var i = 0; i < userData.UserAttributes.length; i++) {
6987 var attribute = {
6988 Name: userData.UserAttributes[i].Name,
6989 Value: userData.UserAttributes[i].Value
6990 };
6991 var userAttribute = new _CognitoUserAttribute__WEBPACK_IMPORTED_MODULE_12__["default"](attribute);
6992 attributeList.push(userAttribute);
6993 }
6994
6995 return callback(null, attributeList);
6996 });
6997 return undefined;
6998 }
6999 /**
7000 * This was previously used by an authenticated user to get MFAOptions,
7001 * but no longer returns a meaningful response. Refer to the documentation for
7002 * how to setup and use MFA: https://docs.amplify.aws/lib/auth/mfa/q/platform/js
7003 * @deprecated
7004 * @param {nodeCallback<MFAOptions>} callback Called on success or error.
7005 * @returns {void}
7006 */
7007 ;
7008
7009 _proto.getMFAOptions = function getMFAOptions(callback) {
7010 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7011 return callback(new Error('User is not authenticated'), null);
7012 }
7013
7014 this.client.request('GetUser', {
7015 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7016 }, function (err, userData) {
7017 if (err) {
7018 return callback(err, null);
7019 }
7020
7021 return callback(null, userData.MFAOptions);
7022 });
7023 return undefined;
7024 }
7025 /**
7026 * PRIVATE ONLY: This is an internal only method and should not
7027 * be directly called by the consumers.
7028 */
7029 ;
7030
7031 _proto.createGetUserRequest = function createGetUserRequest() {
7032 return this.client.promisifyRequest('GetUser', {
7033 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7034 });
7035 }
7036 /**
7037 * PRIVATE ONLY: This is an internal only method and should not
7038 * be directly called by the consumers.
7039 */
7040 ;
7041
7042 _proto.refreshSessionIfPossible = function refreshSessionIfPossible(options) {
7043 var _this11 = this;
7044
7045 if (options === void 0) {
7046 options = {};
7047 } // best effort, if not possible
7048
7049
7050 return new Promise(function (resolve) {
7051 var refresh = _this11.signInUserSession.getRefreshToken();
7052
7053 if (refresh && refresh.getToken()) {
7054 _this11.refreshSession(refresh, resolve, options.clientMetadata);
7055 } else {
7056 resolve();
7057 }
7058 });
7059 }
7060 /**
7061 * @typedef {Object} GetUserDataOptions
7062 * @property {boolean} bypassCache - force getting data from Cognito service
7063 * @property {Record<string, string>} clientMetadata - clientMetadata for getSession
7064 */
7065
7066 /**
7067 * This is used by an authenticated users to get the userData
7068 * @param {nodeCallback<UserData>} callback Called on success or error.
7069 * @param {GetUserDataOptions} params
7070 * @returns {void}
7071 */
7072 ;
7073
7074 _proto.getUserData = function getUserData(callback, params) {
7075 var _this12 = this;
7076
7077 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7078 this.clearCachedUserData();
7079 return callback(new Error('User is not authenticated'), null);
7080 }
7081
7082 var userData = this.getUserDataFromCache();
7083
7084 if (!userData) {
7085 this.fetchUserData().then(function (data) {
7086 callback(null, data);
7087 })["catch"](callback);
7088 return;
7089 }
7090
7091 if (this.isFetchUserDataAndTokenRequired(params)) {
7092 this.fetchUserData().then(function (data) {
7093 return _this12.refreshSessionIfPossible(params).then(function () {
7094 return data;
7095 });
7096 }).then(function (data) {
7097 return callback(null, data);
7098 })["catch"](callback);
7099 return;
7100 }
7101
7102 try {
7103 callback(null, JSON.parse(userData));
7104 return;
7105 } catch (err) {
7106 this.clearCachedUserData();
7107 callback(err, null);
7108 return;
7109 }
7110 }
7111 /**
7112 *
7113 * PRIVATE ONLY: This is an internal only method and should not
7114 * be directly called by the consumers.
7115 */
7116 ;
7117
7118 _proto.getUserDataFromCache = function getUserDataFromCache() {
7119 var userData = this.storage.getItem(this.userDataKey);
7120 return userData;
7121 }
7122 /**
7123 *
7124 * PRIVATE ONLY: This is an internal only method and should not
7125 * be directly called by the consumers.
7126 */
7127 ;
7128
7129 _proto.isFetchUserDataAndTokenRequired = function isFetchUserDataAndTokenRequired(params) {
7130 var _ref = params || {},
7131 _ref$bypassCache = _ref.bypassCache,
7132 bypassCache = _ref$bypassCache === void 0 ? false : _ref$bypassCache;
7133
7134 return bypassCache;
7135 }
7136 /**
7137 *
7138 * PRIVATE ONLY: This is an internal only method and should not
7139 * be directly called by the consumers.
7140 */
7141 ;
7142
7143 _proto.fetchUserData = function fetchUserData() {
7144 var _this13 = this;
7145
7146 return this.createGetUserRequest().then(function (data) {
7147 _this13.cacheUserData(data);
7148
7149 return data;
7150 });
7151 }
7152 /**
7153 * This is used by an authenticated user to delete a list of attributes
7154 * @param {string[]} attributeList Names of the attributes to delete.
7155 * @param {nodeCallback<string>} callback Called on success or error.
7156 * @returns {void}
7157 */
7158 ;
7159
7160 _proto.deleteAttributes = function deleteAttributes(attributeList, callback) {
7161 var _this14 = this;
7162
7163 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7164 return callback(new Error('User is not authenticated'), null);
7165 }
7166
7167 this.client.request('DeleteUserAttributes', {
7168 UserAttributeNames: attributeList,
7169 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7170 }, function (err) {
7171 if (err) {
7172 return callback(err, null);
7173 } // update cached user
7174
7175
7176 return _this14.getUserData(function () {
7177 return callback(null, 'SUCCESS');
7178 }, {
7179 bypassCache: true
7180 });
7181 });
7182 return undefined;
7183 }
7184 /**
7185 * This is used by a user to resend a confirmation code
7186 * @param {nodeCallback<string>} callback Called on success or error.
7187 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7188 * @returns {void}
7189 */
7190 ;
7191
7192 _proto.resendConfirmationCode = function resendConfirmationCode(callback, clientMetadata) {
7193 var jsonReq = {
7194 ClientId: this.pool.getClientId(),
7195 Username: this.username,
7196 ClientMetadata: clientMetadata
7197 };
7198 this.client.request('ResendConfirmationCode', jsonReq, function (err, result) {
7199 if (err) {
7200 return callback(err, null);
7201 }
7202
7203 return callback(null, result);
7204 });
7205 }
7206 /**
7207 * @typedef {Object} GetSessionOptions
7208 * @property {Record<string, string>} clientMetadata - clientMetadata for getSession
7209 */
7210
7211 /**
7212 * This is used to get a session, either from the session object
7213 * or from the local storage, or by using a refresh token
7214 *
7215 * @param {nodeCallback<CognitoUserSession>} callback Called on success or error.
7216 * @param {GetSessionOptions} options
7217 * @returns {void}
7218 */
7219 ;
7220
7221 _proto.getSession = function getSession(callback, options) {
7222 if (options === void 0) {
7223 options = {};
7224 }
7225
7226 if (this.username == null) {
7227 return callback(new Error('Username is null. Cannot retrieve a new session'), null);
7228 }
7229
7230 if (this.signInUserSession != null && this.signInUserSession.isValid()) {
7231 return callback(null, this.signInUserSession);
7232 }
7233
7234 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
7235 var idTokenKey = keyPrefix + ".idToken";
7236 var accessTokenKey = keyPrefix + ".accessToken";
7237 var refreshTokenKey = keyPrefix + ".refreshToken";
7238 var clockDriftKey = keyPrefix + ".clockDrift";
7239
7240 if (this.storage.getItem(idTokenKey)) {
7241 var idToken = new _CognitoIdToken__WEBPACK_IMPORTED_MODULE_8__["default"]({
7242 IdToken: this.storage.getItem(idTokenKey)
7243 });
7244 var accessToken = new _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_7__["default"]({
7245 AccessToken: this.storage.getItem(accessTokenKey)
7246 });
7247 var refreshToken = new _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_9__["default"]({
7248 RefreshToken: this.storage.getItem(refreshTokenKey)
7249 });
7250 var clockDrift = parseInt(this.storage.getItem(clockDriftKey), 0) || 0;
7251 var sessionData = {
7252 IdToken: idToken,
7253 AccessToken: accessToken,
7254 RefreshToken: refreshToken,
7255 ClockDrift: clockDrift
7256 };
7257 var cachedSession = new _CognitoUserSession__WEBPACK_IMPORTED_MODULE_10__["default"](sessionData);
7258
7259 if (cachedSession.isValid()) {
7260 this.signInUserSession = cachedSession;
7261 return callback(null, this.signInUserSession);
7262 }
7263
7264 if (!refreshToken.getToken()) {
7265 return callback(new Error('Cannot retrieve a new session. Please authenticate.'), null);
7266 }
7267
7268 this.refreshSession(refreshToken, callback, options.clientMetadata);
7269 } else {
7270 callback(new Error('Local storage is missing an ID Token, Please authenticate'), null);
7271 }
7272
7273 return undefined;
7274 }
7275 /**
7276 * This uses the refreshToken to retrieve a new session
7277 * @param {CognitoRefreshToken} refreshToken A previous session's refresh token.
7278 * @param {nodeCallback<CognitoUserSession>} callback Called on success or error.
7279 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7280 * @returns {void}
7281 */
7282 ;
7283
7284 _proto.refreshSession = function refreshSession(refreshToken, callback, clientMetadata) {
7285 var _this15 = this;
7286
7287 var wrappedCallback = this.pool.wrapRefreshSessionCallback ? this.pool.wrapRefreshSessionCallback(callback) : callback;
7288 var authParameters = {};
7289 authParameters.REFRESH_TOKEN = refreshToken.getToken();
7290 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
7291 var lastUserKey = keyPrefix + ".LastAuthUser";
7292
7293 if (this.storage.getItem(lastUserKey)) {
7294 this.username = this.storage.getItem(lastUserKey);
7295 var deviceKeyKey = keyPrefix + "." + this.username + ".deviceKey";
7296 this.deviceKey = this.storage.getItem(deviceKeyKey);
7297 authParameters.DEVICE_KEY = this.deviceKey;
7298 }
7299
7300 var jsonReq = {
7301 ClientId: this.pool.getClientId(),
7302 AuthFlow: 'REFRESH_TOKEN_AUTH',
7303 AuthParameters: authParameters,
7304 ClientMetadata: clientMetadata
7305 };
7306
7307 if (this.getUserContextData()) {
7308 jsonReq.UserContextData = this.getUserContextData();
7309 }
7310
7311 this.client.request('InitiateAuth', jsonReq, function (err, authResult) {
7312 if (err) {
7313 if (err.code === 'NotAuthorizedException') {
7314 _this15.clearCachedUser();
7315 }
7316
7317 return wrappedCallback(err, null);
7318 }
7319
7320 if (authResult) {
7321 var authenticationResult = authResult.AuthenticationResult;
7322
7323 if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) {
7324 authenticationResult.RefreshToken = refreshToken.getToken();
7325 }
7326
7327 _this15.signInUserSession = _this15.getCognitoUserSession(authenticationResult);
7328
7329 _this15.cacheTokens();
7330
7331 return wrappedCallback(null, _this15.signInUserSession);
7332 }
7333
7334 return undefined;
7335 });
7336 }
7337 /**
7338 * This is used to save the session tokens to local storage
7339 * @returns {void}
7340 */
7341 ;
7342
7343 _proto.cacheTokens = function cacheTokens() {
7344 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
7345 var idTokenKey = keyPrefix + "." + this.username + ".idToken";
7346 var accessTokenKey = keyPrefix + "." + this.username + ".accessToken";
7347 var refreshTokenKey = keyPrefix + "." + this.username + ".refreshToken";
7348 var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift";
7349 var lastUserKey = keyPrefix + ".LastAuthUser";
7350 this.storage.setItem(idTokenKey, this.signInUserSession.getIdToken().getJwtToken());
7351 this.storage.setItem(accessTokenKey, this.signInUserSession.getAccessToken().getJwtToken());
7352 this.storage.setItem(refreshTokenKey, this.signInUserSession.getRefreshToken().getToken());
7353 this.storage.setItem(clockDriftKey, "" + this.signInUserSession.getClockDrift());
7354 this.storage.setItem(lastUserKey, this.username);
7355 }
7356 /**
7357 * This is to cache user data
7358 */
7359 ;
7360
7361 _proto.cacheUserData = function cacheUserData(userData) {
7362 this.storage.setItem(this.userDataKey, JSON.stringify(userData));
7363 }
7364 /**
7365 * This is to remove cached user data
7366 */
7367 ;
7368
7369 _proto.clearCachedUserData = function clearCachedUserData() {
7370 this.storage.removeItem(this.userDataKey);
7371 };
7372
7373 _proto.clearCachedUser = function clearCachedUser() {
7374 this.clearCachedTokens();
7375 this.clearCachedUserData();
7376 }
7377 /**
7378 * This is used to cache the device key and device group and device password
7379 * @returns {void}
7380 */
7381 ;
7382
7383 _proto.cacheDeviceKeyAndPassword = function cacheDeviceKeyAndPassword() {
7384 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
7385 var deviceKeyKey = keyPrefix + ".deviceKey";
7386 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
7387 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
7388 this.storage.setItem(deviceKeyKey, this.deviceKey);
7389 this.storage.setItem(randomPasswordKey, this.randomPassword);
7390 this.storage.setItem(deviceGroupKeyKey, this.deviceGroupKey);
7391 }
7392 /**
7393 * This is used to get current device key and device group and device password
7394 * @returns {void}
7395 */
7396 ;
7397
7398 _proto.getCachedDeviceKeyAndPassword = function getCachedDeviceKeyAndPassword() {
7399 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
7400 var deviceKeyKey = keyPrefix + ".deviceKey";
7401 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
7402 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
7403
7404 if (this.storage.getItem(deviceKeyKey)) {
7405 this.deviceKey = this.storage.getItem(deviceKeyKey);
7406 this.randomPassword = this.storage.getItem(randomPasswordKey);
7407 this.deviceGroupKey = this.storage.getItem(deviceGroupKeyKey);
7408 }
7409 }
7410 /**
7411 * This is used to clear the device key info from local storage
7412 * @returns {void}
7413 */
7414 ;
7415
7416 _proto.clearCachedDeviceKeyAndPassword = function clearCachedDeviceKeyAndPassword() {
7417 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
7418 var deviceKeyKey = keyPrefix + ".deviceKey";
7419 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
7420 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
7421 this.storage.removeItem(deviceKeyKey);
7422 this.storage.removeItem(randomPasswordKey);
7423 this.storage.removeItem(deviceGroupKeyKey);
7424 }
7425 /**
7426 * This is used to clear the session tokens from local storage
7427 * @returns {void}
7428 */
7429 ;
7430
7431 _proto.clearCachedTokens = function clearCachedTokens() {
7432 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
7433 var idTokenKey = keyPrefix + "." + this.username + ".idToken";
7434 var accessTokenKey = keyPrefix + "." + this.username + ".accessToken";
7435 var refreshTokenKey = keyPrefix + "." + this.username + ".refreshToken";
7436 var lastUserKey = keyPrefix + ".LastAuthUser";
7437 var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift";
7438 this.storage.removeItem(idTokenKey);
7439 this.storage.removeItem(accessTokenKey);
7440 this.storage.removeItem(refreshTokenKey);
7441 this.storage.removeItem(lastUserKey);
7442 this.storage.removeItem(clockDriftKey);
7443 }
7444 /**
7445 * This is used to build a user session from tokens retrieved in the authentication result
7446 * @param {object} authResult Successful auth response from server.
7447 * @returns {CognitoUserSession} The new user session.
7448 * @private
7449 */
7450 ;
7451
7452 _proto.getCognitoUserSession = function getCognitoUserSession(authResult) {
7453 var idToken = new _CognitoIdToken__WEBPACK_IMPORTED_MODULE_8__["default"](authResult);
7454 var accessToken = new _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_7__["default"](authResult);
7455 var refreshToken = new _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_9__["default"](authResult);
7456 var sessionData = {
7457 IdToken: idToken,
7458 AccessToken: accessToken,
7459 RefreshToken: refreshToken
7460 };
7461 return new _CognitoUserSession__WEBPACK_IMPORTED_MODULE_10__["default"](sessionData);
7462 }
7463 /**
7464 * This is used to initiate a forgot password request
7465 * @param {object} callback Result callback map.
7466 * @param {onFailure} callback.onFailure Called on any error.
7467 * @param {inputVerificationCode?} callback.inputVerificationCode
7468 * Optional callback raised instead of onSuccess with response data.
7469 * @param {onSuccess} callback.onSuccess Called on success.
7470 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7471 * @returns {void}
7472 */
7473 ;
7474
7475 _proto.forgotPassword = function forgotPassword(callback, clientMetadata) {
7476 var jsonReq = {
7477 ClientId: this.pool.getClientId(),
7478 Username: this.username,
7479 ClientMetadata: clientMetadata
7480 };
7481
7482 if (this.getUserContextData()) {
7483 jsonReq.UserContextData = this.getUserContextData();
7484 }
7485
7486 this.client.request('ForgotPassword', jsonReq, function (err, data) {
7487 if (err) {
7488 return callback.onFailure(err);
7489 }
7490
7491 if (typeof callback.inputVerificationCode === 'function') {
7492 return callback.inputVerificationCode(data);
7493 }
7494
7495 return callback.onSuccess(data);
7496 });
7497 }
7498 /**
7499 * This is used to confirm a new password using a confirmationCode
7500 * @param {string} confirmationCode Code entered by user.
7501 * @param {string} newPassword Confirm new password.
7502 * @param {object} callback Result callback map.
7503 * @param {onFailure} callback.onFailure Called on any error.
7504 * @param {onSuccess<void>} callback.onSuccess Called on success.
7505 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7506 * @returns {void}
7507 */
7508 ;
7509
7510 _proto.confirmPassword = function confirmPassword(confirmationCode, newPassword, callback, clientMetadata) {
7511 var jsonReq = {
7512 ClientId: this.pool.getClientId(),
7513 Username: this.username,
7514 ConfirmationCode: confirmationCode,
7515 Password: newPassword,
7516 ClientMetadata: clientMetadata
7517 };
7518
7519 if (this.getUserContextData()) {
7520 jsonReq.UserContextData = this.getUserContextData();
7521 }
7522
7523 this.client.request('ConfirmForgotPassword', jsonReq, function (err) {
7524 if (err) {
7525 return callback.onFailure(err);
7526 }
7527
7528 return callback.onSuccess('SUCCESS');
7529 });
7530 }
7531 /**
7532 * This is used to initiate an attribute confirmation request
7533 * @param {string} attributeName User attribute that needs confirmation.
7534 * @param {object} callback Result callback map.
7535 * @param {onFailure} callback.onFailure Called on any error.
7536 * @param {inputVerificationCode} callback.inputVerificationCode Called on success.
7537 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7538 * @returns {void}
7539 */
7540 ;
7541
7542 _proto.getAttributeVerificationCode = function getAttributeVerificationCode(attributeName, callback, clientMetadata) {
7543 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7544 return callback.onFailure(new Error('User is not authenticated'));
7545 }
7546
7547 this.client.request('GetUserAttributeVerificationCode', {
7548 AttributeName: attributeName,
7549 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7550 ClientMetadata: clientMetadata
7551 }, function (err, data) {
7552 if (err) {
7553 return callback.onFailure(err);
7554 }
7555
7556 if (typeof callback.inputVerificationCode === 'function') {
7557 return callback.inputVerificationCode(data);
7558 }
7559
7560 return callback.onSuccess('SUCCESS');
7561 });
7562 return undefined;
7563 }
7564 /**
7565 * This is used to confirm an attribute using a confirmation code
7566 * @param {string} attributeName Attribute being confirmed.
7567 * @param {string} confirmationCode Code entered by user.
7568 * @param {object} callback Result callback map.
7569 * @param {onFailure} callback.onFailure Called on any error.
7570 * @param {onSuccess<string>} callback.onSuccess Called on success.
7571 * @returns {void}
7572 */
7573 ;
7574
7575 _proto.verifyAttribute = function verifyAttribute(attributeName, confirmationCode, callback) {
7576 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7577 return callback.onFailure(new Error('User is not authenticated'));
7578 }
7579
7580 this.client.request('VerifyUserAttribute', {
7581 AttributeName: attributeName,
7582 Code: confirmationCode,
7583 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7584 }, function (err) {
7585 if (err) {
7586 return callback.onFailure(err);
7587 }
7588
7589 return callback.onSuccess('SUCCESS');
7590 });
7591 return undefined;
7592 }
7593 /**
7594 * This is used to get the device information using the current device key
7595 * @param {object} callback Result callback map.
7596 * @param {onFailure} callback.onFailure Called on any error.
7597 * @param {onSuccess<*>} callback.onSuccess Called on success with device data.
7598 * @returns {void}
7599 */
7600 ;
7601
7602 _proto.getDevice = function getDevice(callback) {
7603 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7604 return callback.onFailure(new Error('User is not authenticated'));
7605 }
7606
7607 this.client.request('GetDevice', {
7608 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7609 DeviceKey: this.deviceKey
7610 }, function (err, data) {
7611 if (err) {
7612 return callback.onFailure(err);
7613 }
7614
7615 return callback.onSuccess(data);
7616 });
7617 return undefined;
7618 }
7619 /**
7620 * This is used to forget a specific device
7621 * @param {string} deviceKey Device key.
7622 * @param {object} callback Result callback map.
7623 * @param {onFailure} callback.onFailure Called on any error.
7624 * @param {onSuccess<string>} callback.onSuccess Called on success.
7625 * @returns {void}
7626 */
7627 ;
7628
7629 _proto.forgetSpecificDevice = function forgetSpecificDevice(deviceKey, callback) {
7630 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7631 return callback.onFailure(new Error('User is not authenticated'));
7632 }
7633
7634 this.client.request('ForgetDevice', {
7635 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7636 DeviceKey: deviceKey
7637 }, function (err) {
7638 if (err) {
7639 return callback.onFailure(err);
7640 }
7641
7642 return callback.onSuccess('SUCCESS');
7643 });
7644 return undefined;
7645 }
7646 /**
7647 * This is used to forget the current device
7648 * @param {object} callback Result callback map.
7649 * @param {onFailure} callback.onFailure Called on any error.
7650 * @param {onSuccess<string>} callback.onSuccess Called on success.
7651 * @returns {void}
7652 */
7653 ;
7654
7655 _proto.forgetDevice = function forgetDevice(callback) {
7656 var _this16 = this;
7657
7658 this.forgetSpecificDevice(this.deviceKey, {
7659 onFailure: callback.onFailure,
7660 onSuccess: function onSuccess(result) {
7661 _this16.deviceKey = null;
7662 _this16.deviceGroupKey = null;
7663 _this16.randomPassword = null;
7664
7665 _this16.clearCachedDeviceKeyAndPassword();
7666
7667 return callback.onSuccess(result);
7668 }
7669 });
7670 }
7671 /**
7672 * This is used to set the device status as remembered
7673 * @param {object} callback Result callback map.
7674 * @param {onFailure} callback.onFailure Called on any error.
7675 * @param {onSuccess<string>} callback.onSuccess Called on success.
7676 * @returns {void}
7677 */
7678 ;
7679
7680 _proto.setDeviceStatusRemembered = function setDeviceStatusRemembered(callback) {
7681 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7682 return callback.onFailure(new Error('User is not authenticated'));
7683 }
7684
7685 this.client.request('UpdateDeviceStatus', {
7686 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7687 DeviceKey: this.deviceKey,
7688 DeviceRememberedStatus: 'remembered'
7689 }, function (err) {
7690 if (err) {
7691 return callback.onFailure(err);
7692 }
7693
7694 return callback.onSuccess('SUCCESS');
7695 });
7696 return undefined;
7697 }
7698 /**
7699 * This is used to set the device status as not remembered
7700 * @param {object} callback Result callback map.
7701 * @param {onFailure} callback.onFailure Called on any error.
7702 * @param {onSuccess<string>} callback.onSuccess Called on success.
7703 * @returns {void}
7704 */
7705 ;
7706
7707 _proto.setDeviceStatusNotRemembered = function setDeviceStatusNotRemembered(callback) {
7708 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7709 return callback.onFailure(new Error('User is not authenticated'));
7710 }
7711
7712 this.client.request('UpdateDeviceStatus', {
7713 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7714 DeviceKey: this.deviceKey,
7715 DeviceRememberedStatus: 'not_remembered'
7716 }, function (err) {
7717 if (err) {
7718 return callback.onFailure(err);
7719 }
7720
7721 return callback.onSuccess('SUCCESS');
7722 });
7723 return undefined;
7724 }
7725 /**
7726 * This is used to list all devices for a user
7727 *
7728 * @param {int} limit the number of devices returned in a call
7729 * @param {string | null} paginationToken the pagination token in case any was returned before
7730 * @param {object} callback Result callback map.
7731 * @param {onFailure} callback.onFailure Called on any error.
7732 * @param {onSuccess<*>} callback.onSuccess Called on success with device list.
7733 * @returns {void}
7734 */
7735 ;
7736
7737 _proto.listDevices = function listDevices(limit, paginationToken, callback) {
7738 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7739 return callback.onFailure(new Error('User is not authenticated'));
7740 }
7741
7742 var requestParams = {
7743 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
7744 Limit: limit
7745 };
7746
7747 if (paginationToken) {
7748 requestParams.PaginationToken = paginationToken;
7749 }
7750
7751 this.client.request('ListDevices', requestParams, function (err, data) {
7752 if (err) {
7753 return callback.onFailure(err);
7754 }
7755
7756 return callback.onSuccess(data);
7757 });
7758 return undefined;
7759 }
7760 /**
7761 * This is used to globally revoke all tokens issued to a user
7762 * @param {object} callback Result callback map.
7763 * @param {onFailure} callback.onFailure Called on any error.
7764 * @param {onSuccess<string>} callback.onSuccess Called on success.
7765 * @returns {void}
7766 */
7767 ;
7768
7769 _proto.globalSignOut = function globalSignOut(callback) {
7770 var _this17 = this;
7771
7772 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
7773 return callback.onFailure(new Error('User is not authenticated'));
7774 }
7775
7776 this.client.request('GlobalSignOut', {
7777 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7778 }, function (err) {
7779 if (err) {
7780 return callback.onFailure(err);
7781 }
7782
7783 _this17.clearCachedUser();
7784
7785 return callback.onSuccess('SUCCESS');
7786 });
7787 return undefined;
7788 }
7789 /**
7790 * This is used for the user to signOut of the application and clear the cached tokens.
7791 * @returns {void}
7792 */
7793 ;
7794
7795 _proto.signOut = function signOut(revokeTokenCallback) {
7796 var _this18 = this; // If tokens won't be revoked, we just clean the client data.
7797
7798
7799 if (!revokeTokenCallback || typeof revokeTokenCallback !== 'function') {
7800 this.cleanClientData();
7801 return;
7802 }
7803
7804 this.getSession(function (error, _session) {
7805 if (error) {
7806 return revokeTokenCallback(error);
7807 }
7808
7809 _this18.revokeTokens(function (err) {
7810 _this18.cleanClientData();
7811
7812 revokeTokenCallback(err);
7813 });
7814 });
7815 };
7816
7817 _proto.revokeTokens = function revokeTokens(revokeTokenCallback) {
7818 if (revokeTokenCallback === void 0) {
7819 revokeTokenCallback = function revokeTokenCallback() {};
7820 }
7821
7822 if (typeof revokeTokenCallback !== 'function') {
7823 throw new Error('Invalid revokeTokenCallback. It should be a function.');
7824 }
7825
7826 var tokensToBeRevoked = [];
7827
7828 if (!this.signInUserSession) {
7829 var error = new Error('User is not authenticated');
7830 return revokeTokenCallback(error);
7831 }
7832
7833 if (!this.signInUserSession.getAccessToken()) {
7834 var _error = new Error('No Access token available');
7835
7836 return revokeTokenCallback(_error);
7837 }
7838
7839 var refreshToken = this.signInUserSession.getRefreshToken().getToken();
7840 var accessToken = this.signInUserSession.getAccessToken();
7841
7842 if (this.isSessionRevocable(accessToken)) {
7843 if (refreshToken) {
7844 return this.revokeToken({
7845 token: refreshToken,
7846 callback: revokeTokenCallback
7847 });
7848 }
7849 }
7850
7851 revokeTokenCallback();
7852 };
7853
7854 _proto.isSessionRevocable = function isSessionRevocable(token) {
7855 if (token && typeof token.decodePayload === 'function') {
7856 try {
7857 var _token$decodePayload = token.decodePayload(),
7858 origin_jti = _token$decodePayload.origin_jti;
7859
7860 return !!origin_jti;
7861 } catch (err) {// Nothing to do, token doesnt have origin_jti claim
7862 }
7863 }
7864
7865 return false;
7866 };
7867
7868 _proto.cleanClientData = function cleanClientData() {
7869 this.signInUserSession = null;
7870 this.clearCachedUser();
7871 };
7872
7873 _proto.revokeToken = function revokeToken(_ref2) {
7874 var token = _ref2.token,
7875 callback = _ref2.callback;
7876 this.client.requestWithRetry('RevokeToken', {
7877 Token: token,
7878 ClientId: this.pool.getClientId()
7879 }, function (err) {
7880 if (err) {
7881 return callback(err);
7882 }
7883
7884 callback();
7885 });
7886 }
7887 /**
7888 * This is used by a user trying to select a given MFA
7889 * @param {string} answerChallenge the mfa the user wants
7890 * @param {nodeCallback<string>} callback Called on success or error.
7891 * @returns {void}
7892 */
7893 ;
7894
7895 _proto.sendMFASelectionAnswer = function sendMFASelectionAnswer(answerChallenge, callback) {
7896 var _this19 = this;
7897
7898 var challengeResponses = {};
7899 challengeResponses.USERNAME = this.username;
7900 challengeResponses.ANSWER = answerChallenge;
7901 var jsonReq = {
7902 ChallengeName: 'SELECT_MFA_TYPE',
7903 ChallengeResponses: challengeResponses,
7904 ClientId: this.pool.getClientId(),
7905 Session: this.Session
7906 };
7907
7908 if (this.getUserContextData()) {
7909 jsonReq.UserContextData = this.getUserContextData();
7910 }
7911
7912 this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
7913 if (err) {
7914 return callback.onFailure(err);
7915 }
7916
7917 _this19.Session = data.Session;
7918
7919 if (answerChallenge === 'SMS_MFA') {
7920 return callback.mfaRequired(data.ChallengeName, data.ChallengeParameters);
7921 }
7922
7923 if (answerChallenge === 'SOFTWARE_TOKEN_MFA') {
7924 return callback.totpRequired(data.ChallengeName, data.ChallengeParameters);
7925 }
7926
7927 return undefined;
7928 });
7929 }
7930 /**
7931 * This returns the user context data for advanced security feature.
7932 * @returns {string} the user context data from CognitoUserPool
7933 */
7934 ;
7935
7936 _proto.getUserContextData = function getUserContextData() {
7937 var pool = this.pool;
7938 return pool.getUserContextData(this.username);
7939 }
7940 /**
7941 * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA
7942 * @param {nodeCallback<string>} callback Called on success or error.
7943 * @returns {void}
7944 */
7945 ;
7946
7947 _proto.associateSoftwareToken = function associateSoftwareToken(callback) {
7948 var _this20 = this;
7949
7950 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7951 this.client.request('AssociateSoftwareToken', {
7952 Session: this.Session
7953 }, function (err, data) {
7954 if (err) {
7955 return callback.onFailure(err);
7956 }
7957
7958 _this20.Session = data.Session;
7959 return callback.associateSecretCode(data.SecretCode);
7960 });
7961 } else {
7962 this.client.request('AssociateSoftwareToken', {
7963 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
7964 }, function (err, data) {
7965 if (err) {
7966 return callback.onFailure(err);
7967 }
7968
7969 return callback.associateSecretCode(data.SecretCode);
7970 });
7971 }
7972 }
7973 /**
7974 * This is used by an authenticated or a user trying to authenticate to verify a TOTP MFA
7975 * @param {string} totpCode The MFA code entered by the user.
7976 * @param {string} friendlyDeviceName The device name we are assigning to the device.
7977 * @param {nodeCallback<string>} callback Called on success or error.
7978 * @returns {void}
7979 */
7980 ;
7981
7982 _proto.verifySoftwareToken = function verifySoftwareToken(totpCode, friendlyDeviceName, callback) {
7983 var _this21 = this;
7984
7985 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
7986 this.client.request('VerifySoftwareToken', {
7987 Session: this.Session,
7988 UserCode: totpCode,
7989 FriendlyDeviceName: friendlyDeviceName
7990 }, function (err, data) {
7991 if (err) {
7992 return callback.onFailure(err);
7993 }
7994
7995 _this21.Session = data.Session;
7996 var challengeResponses = {};
7997 challengeResponses.USERNAME = _this21.username;
7998 var jsonReq = {
7999 ChallengeName: 'MFA_SETUP',
8000 ClientId: _this21.pool.getClientId(),
8001 ChallengeResponses: challengeResponses,
8002 Session: _this21.Session
8003 };
8004
8005 if (_this21.getUserContextData()) {
8006 jsonReq.UserContextData = _this21.getUserContextData();
8007 }
8008
8009 _this21.client.request('RespondToAuthChallenge', jsonReq, function (errRespond, dataRespond) {
8010 if (errRespond) {
8011 return callback.onFailure(errRespond);
8012 }
8013
8014 _this21.signInUserSession = _this21.getCognitoUserSession(dataRespond.AuthenticationResult);
8015
8016 _this21.cacheTokens();
8017
8018 return callback.onSuccess(_this21.signInUserSession);
8019 });
8020
8021 return undefined;
8022 });
8023 } else {
8024 this.client.request('VerifySoftwareToken', {
8025 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
8026 UserCode: totpCode,
8027 FriendlyDeviceName: friendlyDeviceName
8028 }, function (err, data) {
8029 if (err) {
8030 return callback.onFailure(err);
8031 }
8032
8033 return callback.onSuccess(data);
8034 });
8035 }
8036 };
8037
8038 return CognitoUser;
8039}();
8040
8041
8042
8043/***/ }),
8044
8045/***/ "../amazon-cognito-identity-js/es/CognitoUserAttribute.js":
8046/*!****************************************************************!*\
8047 !*** ../amazon-cognito-identity-js/es/CognitoUserAttribute.js ***!
8048 \****************************************************************/
8049/*! exports provided: default */
8050/***/ (function(module, __webpack_exports__, __webpack_require__) {
8051
8052"use strict";
8053__webpack_require__.r(__webpack_exports__);
8054/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoUserAttribute; });
8055/*!
8056 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8057 * SPDX-License-Identifier: Apache-2.0
8058 */
8059
8060/** @class */
8061var CognitoUserAttribute = /*#__PURE__*/function () {
8062 /**
8063 * Constructs a new CognitoUserAttribute object
8064 * @param {string=} Name The record's name
8065 * @param {string=} Value The record's value
8066 */
8067 function CognitoUserAttribute(_temp) {
8068 var _ref = _temp === void 0 ? {} : _temp,
8069 Name = _ref.Name,
8070 Value = _ref.Value;
8071
8072 this.Name = Name || '';
8073 this.Value = Value || '';
8074 }
8075 /**
8076 * @returns {string} the record's value.
8077 */
8078
8079
8080 var _proto = CognitoUserAttribute.prototype;
8081
8082 _proto.getValue = function getValue() {
8083 return this.Value;
8084 }
8085 /**
8086 * Sets the record's value.
8087 * @param {string} value The new value.
8088 * @returns {CognitoUserAttribute} The record for method chaining.
8089 */
8090 ;
8091
8092 _proto.setValue = function setValue(value) {
8093 this.Value = value;
8094 return this;
8095 }
8096 /**
8097 * @returns {string} the record's name.
8098 */
8099 ;
8100
8101 _proto.getName = function getName() {
8102 return this.Name;
8103 }
8104 /**
8105 * Sets the record's name
8106 * @param {string} name The new name.
8107 * @returns {CognitoUserAttribute} The record for method chaining.
8108 */
8109 ;
8110
8111 _proto.setName = function setName(name) {
8112 this.Name = name;
8113 return this;
8114 }
8115 /**
8116 * @returns {string} a string representation of the record.
8117 */
8118 ;
8119
8120 _proto.toString = function toString() {
8121 return JSON.stringify(this);
8122 }
8123 /**
8124 * @returns {object} a flat object representing the record.
8125 */
8126 ;
8127
8128 _proto.toJSON = function toJSON() {
8129 return {
8130 Name: this.Name,
8131 Value: this.Value
8132 };
8133 };
8134
8135 return CognitoUserAttribute;
8136}();
8137
8138
8139
8140/***/ }),
8141
8142/***/ "../amazon-cognito-identity-js/es/CognitoUserPool.js":
8143/*!***********************************************************!*\
8144 !*** ../amazon-cognito-identity-js/es/CognitoUserPool.js ***!
8145 \***********************************************************/
8146/*! exports provided: default */
8147/***/ (function(module, __webpack_exports__, __webpack_require__) {
8148
8149"use strict";
8150__webpack_require__.r(__webpack_exports__);
8151/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoUserPool; });
8152/* harmony import */ var _Client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Client */ "../amazon-cognito-identity-js/es/Client.js");
8153/* harmony import */ var _CognitoUser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CognitoUser */ "../amazon-cognito-identity-js/es/CognitoUser.js");
8154/* harmony import */ var _StorageHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./StorageHelper */ "../amazon-cognito-identity-js/es/StorageHelper.js");
8155/*!
8156 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8157 * SPDX-License-Identifier: Apache-2.0
8158 */
8159
8160
8161
8162var USER_POOL_ID_MAX_LENGTH = 55;
8163/** @class */
8164
8165var CognitoUserPool = /*#__PURE__*/function () {
8166 /**
8167 * Constructs a new CognitoUserPool object
8168 * @param {object} data Creation options.
8169 * @param {string} data.UserPoolId Cognito user pool id.
8170 * @param {string} data.ClientId User pool application client id.
8171 * @param {string} data.endpoint Optional custom service endpoint.
8172 * @param {object} data.fetchOptions Optional options for fetch API.
8173 * (only credentials option is supported)
8174 * @param {object} data.Storage Optional storage object.
8175 * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional:
8176 * boolean flag indicating if the data collection is enabled
8177 * to support cognito advanced security features. By default, this
8178 * flag is set to true.
8179 */
8180 function CognitoUserPool(data, wrapRefreshSessionCallback) {
8181 var _ref = data || {},
8182 UserPoolId = _ref.UserPoolId,
8183 ClientId = _ref.ClientId,
8184 endpoint = _ref.endpoint,
8185 fetchOptions = _ref.fetchOptions,
8186 AdvancedSecurityDataCollectionFlag = _ref.AdvancedSecurityDataCollectionFlag;
8187
8188 if (!UserPoolId || !ClientId) {
8189 throw new Error('Both UserPoolId and ClientId are required.');
8190 }
8191
8192 if (UserPoolId.length > USER_POOL_ID_MAX_LENGTH || !/^[\w-]+_[0-9a-zA-Z]+$/.test(UserPoolId)) {
8193 throw new Error('Invalid UserPoolId format.');
8194 }
8195
8196 var region = UserPoolId.split('_')[0];
8197 this.userPoolId = UserPoolId;
8198 this.clientId = ClientId;
8199 this.client = new _Client__WEBPACK_IMPORTED_MODULE_0__["default"](region, endpoint, fetchOptions);
8200 /**
8201 * By default, AdvancedSecurityDataCollectionFlag is set to true,
8202 * if no input value is provided.
8203 */
8204
8205 this.advancedSecurityDataCollectionFlag = AdvancedSecurityDataCollectionFlag !== false;
8206 this.storage = data.Storage || new _StorageHelper__WEBPACK_IMPORTED_MODULE_2__["default"]().getStorage();
8207
8208 if (wrapRefreshSessionCallback) {
8209 this.wrapRefreshSessionCallback = wrapRefreshSessionCallback;
8210 }
8211 }
8212 /**
8213 * @returns {string} the user pool id
8214 */
8215
8216
8217 var _proto = CognitoUserPool.prototype;
8218
8219 _proto.getUserPoolId = function getUserPoolId() {
8220 return this.userPoolId;
8221 }
8222 /**
8223 * @returns {string} the client id
8224 */
8225 ;
8226
8227 _proto.getClientId = function getClientId() {
8228 return this.clientId;
8229 }
8230 /**
8231 * @typedef {object} SignUpResult
8232 * @property {CognitoUser} user New user.
8233 * @property {bool} userConfirmed If the user is already confirmed.
8234 */
8235
8236 /**
8237 * method for signing up a user
8238 * @param {string} username User's username.
8239 * @param {string} password Plain-text initial password entered by user.
8240 * @param {(AttributeArg[])=} userAttributes New user attributes.
8241 * @param {(AttributeArg[])=} validationData Application metadata.
8242 * @param {(AttributeArg[])=} clientMetadata Client metadata.
8243 * @param {nodeCallback<SignUpResult>} callback Called on error or with the new user.
8244 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
8245 * @returns {void}
8246 */
8247 ;
8248
8249 _proto.signUp = function signUp(username, password, userAttributes, validationData, callback, clientMetadata) {
8250 var _this = this;
8251
8252 var jsonReq = {
8253 ClientId: this.clientId,
8254 Username: username,
8255 Password: password,
8256 UserAttributes: userAttributes,
8257 ValidationData: validationData,
8258 ClientMetadata: clientMetadata
8259 };
8260
8261 if (this.getUserContextData(username)) {
8262 jsonReq.UserContextData = this.getUserContextData(username);
8263 }
8264
8265 this.client.request('SignUp', jsonReq, function (err, data) {
8266 if (err) {
8267 return callback(err, null);
8268 }
8269
8270 var cognitoUser = {
8271 Username: username,
8272 Pool: _this,
8273 Storage: _this.storage
8274 };
8275 var returnData = {
8276 user: new _CognitoUser__WEBPACK_IMPORTED_MODULE_1__["default"](cognitoUser),
8277 userConfirmed: data.UserConfirmed,
8278 userSub: data.UserSub,
8279 codeDeliveryDetails: data.CodeDeliveryDetails
8280 };
8281 return callback(null, returnData);
8282 });
8283 }
8284 /**
8285 * method for getting the current user of the application from the local storage
8286 *
8287 * @returns {CognitoUser} the user retrieved from storage
8288 */
8289 ;
8290
8291 _proto.getCurrentUser = function getCurrentUser() {
8292 var lastUserKey = "CognitoIdentityServiceProvider." + this.clientId + ".LastAuthUser";
8293 var lastAuthUser = this.storage.getItem(lastUserKey);
8294
8295 if (lastAuthUser) {
8296 var cognitoUser = {
8297 Username: lastAuthUser,
8298 Pool: this,
8299 Storage: this.storage
8300 };
8301 return new _CognitoUser__WEBPACK_IMPORTED_MODULE_1__["default"](cognitoUser);
8302 }
8303
8304 return null;
8305 }
8306 /**
8307 * This method returns the encoded data string used for cognito advanced security feature.
8308 * This would be generated only when developer has included the JS used for collecting the
8309 * data on their client. Please refer to documentation to know more about using AdvancedSecurity
8310 * features
8311 * @param {string} username the username for the context data
8312 * @returns {string} the user context data
8313 **/
8314 ;
8315
8316 _proto.getUserContextData = function getUserContextData(username) {
8317 if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') {
8318 return undefined;
8319 }
8320 /* eslint-disable */
8321
8322
8323 var amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData;
8324 /* eslint-enable */
8325
8326 if (this.advancedSecurityDataCollectionFlag) {
8327 var advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData(username, this.userPoolId, this.clientId);
8328
8329 if (advancedSecurityData) {
8330 var userContextData = {
8331 EncodedData: advancedSecurityData
8332 };
8333 return userContextData;
8334 }
8335 }
8336
8337 return {};
8338 };
8339
8340 return CognitoUserPool;
8341}();
8342
8343
8344
8345/***/ }),
8346
8347/***/ "../amazon-cognito-identity-js/es/CognitoUserSession.js":
8348/*!**************************************************************!*\
8349 !*** ../amazon-cognito-identity-js/es/CognitoUserSession.js ***!
8350 \**************************************************************/
8351/*! exports provided: default */
8352/***/ (function(module, __webpack_exports__, __webpack_require__) {
8353
8354"use strict";
8355__webpack_require__.r(__webpack_exports__);
8356/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CognitoUserSession; });
8357/*!
8358 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8359 * SPDX-License-Identifier: Apache-2.0
8360 */
8361
8362/** @class */
8363var CognitoUserSession = /*#__PURE__*/function () {
8364 /**
8365 * Constructs a new CognitoUserSession object
8366 * @param {CognitoIdToken} IdToken The session's Id token.
8367 * @param {CognitoRefreshToken=} RefreshToken The session's refresh token.
8368 * @param {CognitoAccessToken} AccessToken The session's access token.
8369 * @param {int} ClockDrift The saved computer's clock drift or undefined to force calculation.
8370 */
8371 function CognitoUserSession(_temp) {
8372 var _ref = _temp === void 0 ? {} : _temp,
8373 IdToken = _ref.IdToken,
8374 RefreshToken = _ref.RefreshToken,
8375 AccessToken = _ref.AccessToken,
8376 ClockDrift = _ref.ClockDrift;
8377
8378 if (AccessToken == null || IdToken == null) {
8379 throw new Error('Id token and Access Token must be present.');
8380 }
8381
8382 this.idToken = IdToken;
8383 this.refreshToken = RefreshToken;
8384 this.accessToken = AccessToken;
8385 this.clockDrift = ClockDrift === undefined ? this.calculateClockDrift() : ClockDrift;
8386 }
8387 /**
8388 * @returns {CognitoIdToken} the session's Id token
8389 */
8390
8391
8392 var _proto = CognitoUserSession.prototype;
8393
8394 _proto.getIdToken = function getIdToken() {
8395 return this.idToken;
8396 }
8397 /**
8398 * @returns {CognitoRefreshToken} the session's refresh token
8399 */
8400 ;
8401
8402 _proto.getRefreshToken = function getRefreshToken() {
8403 return this.refreshToken;
8404 }
8405 /**
8406 * @returns {CognitoAccessToken} the session's access token
8407 */
8408 ;
8409
8410 _proto.getAccessToken = function getAccessToken() {
8411 return this.accessToken;
8412 }
8413 /**
8414 * @returns {int} the session's clock drift
8415 */
8416 ;
8417
8418 _proto.getClockDrift = function getClockDrift() {
8419 return this.clockDrift;
8420 }
8421 /**
8422 * @returns {int} the computer's clock drift
8423 */
8424 ;
8425
8426 _proto.calculateClockDrift = function calculateClockDrift() {
8427 var now = Math.floor(new Date() / 1000);
8428 var iat = Math.min(this.accessToken.getIssuedAt(), this.idToken.getIssuedAt());
8429 return now - iat;
8430 }
8431 /**
8432 * Checks to see if the session is still valid based on session expiry information found
8433 * in tokens and the current time (adjusted with clock drift)
8434 * @returns {boolean} if the session is still valid
8435 */
8436 ;
8437
8438 _proto.isValid = function isValid() {
8439 var now = Math.floor(new Date() / 1000);
8440 var adjusted = now - this.clockDrift;
8441 return adjusted < this.accessToken.getExpiration() && adjusted < this.idToken.getExpiration();
8442 };
8443
8444 return CognitoUserSession;
8445}();
8446
8447
8448
8449/***/ }),
8450
8451/***/ "../amazon-cognito-identity-js/es/CookieStorage.js":
8452/*!*********************************************************!*\
8453 !*** ../amazon-cognito-identity-js/es/CookieStorage.js ***!
8454 \*********************************************************/
8455/*! exports provided: default */
8456/***/ (function(module, __webpack_exports__, __webpack_require__) {
8457
8458"use strict";
8459__webpack_require__.r(__webpack_exports__);
8460/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CookieStorage; });
8461/* harmony import */ var js_cookie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! js-cookie */ "../../node_modules/js-cookie/src/js.cookie.js");
8462/* harmony import */ var js_cookie__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(js_cookie__WEBPACK_IMPORTED_MODULE_0__);
8463
8464/** @class */
8465
8466var CookieStorage = /*#__PURE__*/function () {
8467 /**
8468 * Constructs a new CookieStorage object
8469 * @param {object} data Creation options.
8470 * @param {string} data.domain Cookies domain (mandatory).
8471 * @param {string} data.path Cookies path (default: '/')
8472 * @param {integer} data.expires Cookie expiration (in days, default: 365)
8473 * @param {boolean} data.secure Cookie secure flag (default: true)
8474 * @param {string} data.sameSite Cookie request behaviour (default: null)
8475 */
8476 function CookieStorage(data) {
8477 if (data.domain) {
8478 this.domain = data.domain;
8479 } else {
8480 throw new Error('The domain of cookieStorage can not be undefined.');
8481 }
8482
8483 if (data.path) {
8484 this.path = data.path;
8485 } else {
8486 this.path = '/';
8487 }
8488
8489 if (Object.prototype.hasOwnProperty.call(data, 'expires')) {
8490 this.expires = data.expires;
8491 } else {
8492 this.expires = 365;
8493 }
8494
8495 if (Object.prototype.hasOwnProperty.call(data, 'secure')) {
8496 this.secure = data.secure;
8497 } else {
8498 this.secure = true;
8499 }
8500
8501 if (Object.prototype.hasOwnProperty.call(data, 'sameSite')) {
8502 if (!['strict', 'lax', 'none'].includes(data.sameSite)) {
8503 throw new Error('The sameSite value of cookieStorage must be "lax", "strict" or "none".');
8504 }
8505
8506 if (data.sameSite === 'none' && !this.secure) {
8507 throw new Error('sameSite = None requires the Secure attribute in latest browser versions.');
8508 }
8509
8510 this.sameSite = data.sameSite;
8511 } else {
8512 this.sameSite = null;
8513 }
8514 }
8515 /**
8516 * This is used to set a specific item in storage
8517 * @param {string} key - the key for the item
8518 * @param {object} value - the value
8519 * @returns {string} value that was set
8520 */
8521
8522
8523 var _proto = CookieStorage.prototype;
8524
8525 _proto.setItem = function setItem(key, value) {
8526 var options = {
8527 path: this.path,
8528 expires: this.expires,
8529 domain: this.domain,
8530 secure: this.secure
8531 };
8532
8533 if (this.sameSite) {
8534 options.sameSite = this.sameSite;
8535 }
8536
8537 js_cookie__WEBPACK_IMPORTED_MODULE_0__["set"](key, value, options);
8538 return js_cookie__WEBPACK_IMPORTED_MODULE_0__["get"](key);
8539 }
8540 /**
8541 * This is used to get a specific key from storage
8542 * @param {string} key - the key for the item
8543 * This is used to clear the storage
8544 * @returns {string} the data item
8545 */
8546 ;
8547
8548 _proto.getItem = function getItem(key) {
8549 return js_cookie__WEBPACK_IMPORTED_MODULE_0__["get"](key);
8550 }
8551 /**
8552 * This is used to remove an item from storage
8553 * @param {string} key - the key being set
8554 * @returns {string} value - value that was deleted
8555 */
8556 ;
8557
8558 _proto.removeItem = function removeItem(key) {
8559 var options = {
8560 path: this.path,
8561 expires: this.expires,
8562 domain: this.domain,
8563 secure: this.secure
8564 };
8565
8566 if (this.sameSite) {
8567 options.sameSite = this.sameSite;
8568 }
8569
8570 return js_cookie__WEBPACK_IMPORTED_MODULE_0__["remove"](key, options);
8571 }
8572 /**
8573 * This is used to clear the storage of optional
8574 * items that were previously set
8575 * @returns {} an empty object
8576 */
8577 ;
8578
8579 _proto.clear = function clear() {
8580 var cookies = js_cookie__WEBPACK_IMPORTED_MODULE_0__["get"]();
8581 var numKeys = Object.keys(cookies).length;
8582
8583 for (var index = 0; index < numKeys; ++index) {
8584 this.removeItem(Object.keys(cookies)[index]);
8585 }
8586
8587 return {};
8588 };
8589
8590 return CookieStorage;
8591}();
8592
8593
8594
8595/***/ }),
8596
8597/***/ "../amazon-cognito-identity-js/es/DateHelper.js":
8598/*!******************************************************!*\
8599 !*** ../amazon-cognito-identity-js/es/DateHelper.js ***!
8600 \******************************************************/
8601/*! exports provided: default */
8602/***/ (function(module, __webpack_exports__, __webpack_require__) {
8603
8604"use strict";
8605__webpack_require__.r(__webpack_exports__);
8606/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return DateHelper; });
8607/*!
8608 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8609 * SPDX-License-Identifier: Apache-2.0
8610 */
8611var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
8612var weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
8613/** @class */
8614
8615var DateHelper = /*#__PURE__*/function () {
8616 function DateHelper() {}
8617
8618 var _proto = DateHelper.prototype;
8619 /**
8620 * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format.
8621 */
8622
8623 _proto.getNowString = function getNowString() {
8624 var now = new Date();
8625 var weekDay = weekNames[now.getUTCDay()];
8626 var month = monthNames[now.getUTCMonth()];
8627 var day = now.getUTCDate();
8628 var hours = now.getUTCHours();
8629
8630 if (hours < 10) {
8631 hours = "0" + hours;
8632 }
8633
8634 var minutes = now.getUTCMinutes();
8635
8636 if (minutes < 10) {
8637 minutes = "0" + minutes;
8638 }
8639
8640 var seconds = now.getUTCSeconds();
8641
8642 if (seconds < 10) {
8643 seconds = "0" + seconds;
8644 }
8645
8646 var year = now.getUTCFullYear(); // ddd MMM D HH:mm:ss UTC YYYY
8647
8648 var dateNow = weekDay + " " + month + " " + day + " " + hours + ":" + minutes + ":" + seconds + " UTC " + year;
8649 return dateNow;
8650 };
8651
8652 return DateHelper;
8653}();
8654
8655
8656
8657/***/ }),
8658
8659/***/ "../amazon-cognito-identity-js/es/Platform/index.js":
8660/*!**********************************************************!*\
8661 !*** ../amazon-cognito-identity-js/es/Platform/index.js ***!
8662 \**********************************************************/
8663/*! exports provided: Platform, getUserAgent, default */
8664/***/ (function(module, __webpack_exports__, __webpack_require__) {
8665
8666"use strict";
8667__webpack_require__.r(__webpack_exports__);
8668/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Platform", function() { return Platform; });
8669/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUserAgent", function() { return getUserAgent; });
8670/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./version */ "../amazon-cognito-identity-js/es/Platform/version.js");
8671/*!
8672 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8673 * SPDX-License-Identifier: Apache-2.0
8674 */
8675
8676var BASE_USER_AGENT = "aws-amplify/" + _version__WEBPACK_IMPORTED_MODULE_0__["version"];
8677var Platform = {
8678 userAgent: BASE_USER_AGENT + " js",
8679 product: '',
8680 navigator: null,
8681 isReactNative: false
8682};
8683
8684if (typeof navigator !== 'undefined' && navigator.product) {
8685 Platform.product = navigator.product || '';
8686 Platform.navigator = navigator || null;
8687
8688 switch (navigator.product) {
8689 case 'ReactNative':
8690 Platform.userAgent = BASE_USER_AGENT + " react-native";
8691 Platform.isReactNative = true;
8692 break;
8693
8694 default:
8695 Platform.userAgent = BASE_USER_AGENT + " js";
8696 Platform.isReactNative = false;
8697 break;
8698 }
8699}
8700
8701var getUserAgent = function getUserAgent() {
8702 return Platform.userAgent;
8703};
8704/**
8705 * @deprecated use named import
8706 */
8707
8708/* harmony default export */ __webpack_exports__["default"] = (Platform);
8709
8710/***/ }),
8711
8712/***/ "../amazon-cognito-identity-js/es/Platform/version.js":
8713/*!************************************************************!*\
8714 !*** ../amazon-cognito-identity-js/es/Platform/version.js ***!
8715 \************************************************************/
8716/*! exports provided: version */
8717/***/ (function(module, __webpack_exports__, __webpack_require__) {
8718
8719"use strict";
8720__webpack_require__.r(__webpack_exports__);
8721/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
8722// generated by genversion
8723var version = '5.0.4';
8724
8725/***/ }),
8726
8727/***/ "../amazon-cognito-identity-js/es/StorageHelper.js":
8728/*!*********************************************************!*\
8729 !*** ../amazon-cognito-identity-js/es/StorageHelper.js ***!
8730 \*********************************************************/
8731/*! exports provided: MemoryStorage, default */
8732/***/ (function(module, __webpack_exports__, __webpack_require__) {
8733
8734"use strict";
8735__webpack_require__.r(__webpack_exports__);
8736/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MemoryStorage", function() { return MemoryStorage; });
8737/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StorageHelper; });
8738/*!
8739 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8740 * SPDX-License-Identifier: Apache-2.0
8741 */
8742var dataMemory = {};
8743/** @class */
8744
8745var MemoryStorage = /*#__PURE__*/function () {
8746 function MemoryStorage() {}
8747 /**
8748 * This is used to set a specific item in storage
8749 * @param {string} key - the key for the item
8750 * @param {object} value - the value
8751 * @returns {string} value that was set
8752 */
8753
8754
8755 MemoryStorage.setItem = function setItem(key, value) {
8756 dataMemory[key] = value;
8757 return dataMemory[key];
8758 }
8759 /**
8760 * This is used to get a specific key from storage
8761 * @param {string} key - the key for the item
8762 * This is used to clear the storage
8763 * @returns {string} the data item
8764 */
8765 ;
8766
8767 MemoryStorage.getItem = function getItem(key) {
8768 return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined;
8769 }
8770 /**
8771 * This is used to remove an item from storage
8772 * @param {string} key - the key being set
8773 * @returns {boolean} return true
8774 */
8775 ;
8776
8777 MemoryStorage.removeItem = function removeItem(key) {
8778 return delete dataMemory[key];
8779 }
8780 /**
8781 * This is used to clear the storage
8782 * @returns {string} nothing
8783 */
8784 ;
8785
8786 MemoryStorage.clear = function clear() {
8787 dataMemory = {};
8788 return dataMemory;
8789 };
8790
8791 return MemoryStorage;
8792}();
8793/** @class */
8794
8795var StorageHelper = /*#__PURE__*/function () {
8796 /**
8797 * This is used to get a storage object
8798 * @returns {object} the storage
8799 */
8800 function StorageHelper() {
8801 try {
8802 this.storageWindow = window.localStorage;
8803 this.storageWindow.setItem('aws.cognito.test-ls', 1);
8804 this.storageWindow.removeItem('aws.cognito.test-ls');
8805 } catch (exception) {
8806 this.storageWindow = MemoryStorage;
8807 }
8808 }
8809 /**
8810 * This is used to return the storage
8811 * @returns {object} the storage
8812 */
8813
8814
8815 var _proto = StorageHelper.prototype;
8816
8817 _proto.getStorage = function getStorage() {
8818 return this.storageWindow;
8819 };
8820
8821 return StorageHelper;
8822}();
8823
8824
8825
8826/***/ }),
8827
8828/***/ "../amazon-cognito-identity-js/es/UserAgent.js":
8829/*!*****************************************************!*\
8830 !*** ../amazon-cognito-identity-js/es/UserAgent.js ***!
8831 \*****************************************************/
8832/*! exports provided: appendToCognitoUserAgent, default */
8833/***/ (function(module, __webpack_exports__, __webpack_require__) {
8834
8835"use strict";
8836__webpack_require__.r(__webpack_exports__);
8837/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendToCognitoUserAgent", function() { return appendToCognitoUserAgent; });
8838/* harmony import */ var _Platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Platform */ "../amazon-cognito-identity-js/es/Platform/index.js");
8839 // constructor
8840
8841function UserAgent() {} // public
8842
8843
8844UserAgent.prototype.userAgent = Object(_Platform__WEBPACK_IMPORTED_MODULE_0__["getUserAgent"])();
8845var appendToCognitoUserAgent = function appendToCognitoUserAgent(content) {
8846 if (!content) {
8847 return;
8848 }
8849
8850 if (UserAgent.prototype.userAgent && !UserAgent.prototype.userAgent.includes(content)) {
8851 UserAgent.prototype.userAgent = UserAgent.prototype.userAgent.concat(' ', content);
8852 }
8853
8854 if (!UserAgent.prototype.userAgent || UserAgent.prototype.userAgent === '') {
8855 UserAgent.prototype.userAgent = content;
8856 }
8857}; // class for defining the amzn user-agent
8858
8859/* harmony default export */ __webpack_exports__["default"] = (UserAgent);
8860
8861/***/ }),
8862
8863/***/ "../amazon-cognito-identity-js/es/index.js":
8864/*!*************************************************!*\
8865 !*** ../amazon-cognito-identity-js/es/index.js ***!
8866 \*************************************************/
8867/*! exports provided: AuthenticationDetails, AuthenticationHelper, CognitoAccessToken, CognitoIdToken, CognitoRefreshToken, CognitoUser, CognitoUserAttribute, CognitoUserPool, CognitoUserSession, CookieStorage, DateHelper, appendToCognitoUserAgent, WordArray */
8868/***/ (function(module, __webpack_exports__, __webpack_require__) {
8869
8870"use strict";
8871__webpack_require__.r(__webpack_exports__);
8872/* harmony import */ var _AuthenticationDetails__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AuthenticationDetails */ "../amazon-cognito-identity-js/es/AuthenticationDetails.js");
8873/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthenticationDetails", function() { return _AuthenticationDetails__WEBPACK_IMPORTED_MODULE_0__["default"]; });
8874
8875/* harmony import */ var _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AuthenticationHelper */ "../amazon-cognito-identity-js/es/AuthenticationHelper.js");
8876/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthenticationHelper", function() { return _AuthenticationHelper__WEBPACK_IMPORTED_MODULE_1__["default"]; });
8877
8878/* harmony import */ var _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CognitoAccessToken */ "../amazon-cognito-identity-js/es/CognitoAccessToken.js");
8879/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoAccessToken", function() { return _CognitoAccessToken__WEBPACK_IMPORTED_MODULE_2__["default"]; });
8880
8881/* harmony import */ var _CognitoIdToken__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CognitoIdToken */ "../amazon-cognito-identity-js/es/CognitoIdToken.js");
8882/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoIdToken", function() { return _CognitoIdToken__WEBPACK_IMPORTED_MODULE_3__["default"]; });
8883
8884/* harmony import */ var _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CognitoRefreshToken */ "../amazon-cognito-identity-js/es/CognitoRefreshToken.js");
8885/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoRefreshToken", function() { return _CognitoRefreshToken__WEBPACK_IMPORTED_MODULE_4__["default"]; });
8886
8887/* harmony import */ var _CognitoUser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CognitoUser */ "../amazon-cognito-identity-js/es/CognitoUser.js");
8888/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUser", function() { return _CognitoUser__WEBPACK_IMPORTED_MODULE_5__["default"]; });
8889
8890/* harmony import */ var _CognitoUserAttribute__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./CognitoUserAttribute */ "../amazon-cognito-identity-js/es/CognitoUserAttribute.js");
8891/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUserAttribute", function() { return _CognitoUserAttribute__WEBPACK_IMPORTED_MODULE_6__["default"]; });
8892
8893/* harmony import */ var _CognitoUserPool__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CognitoUserPool */ "../amazon-cognito-identity-js/es/CognitoUserPool.js");
8894/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUserPool", function() { return _CognitoUserPool__WEBPACK_IMPORTED_MODULE_7__["default"]; });
8895
8896/* harmony import */ var _CognitoUserSession__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./CognitoUserSession */ "../amazon-cognito-identity-js/es/CognitoUserSession.js");
8897/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUserSession", function() { return _CognitoUserSession__WEBPACK_IMPORTED_MODULE_8__["default"]; });
8898
8899/* harmony import */ var _CookieStorage__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./CookieStorage */ "../amazon-cognito-identity-js/es/CookieStorage.js");
8900/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CookieStorage", function() { return _CookieStorage__WEBPACK_IMPORTED_MODULE_9__["default"]; });
8901
8902/* harmony import */ var _DateHelper__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./DateHelper */ "../amazon-cognito-identity-js/es/DateHelper.js");
8903/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DateHelper", function() { return _DateHelper__WEBPACK_IMPORTED_MODULE_10__["default"]; });
8904
8905/* harmony import */ var _UserAgent__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./UserAgent */ "../amazon-cognito-identity-js/es/UserAgent.js");
8906/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "appendToCognitoUserAgent", function() { return _UserAgent__WEBPACK_IMPORTED_MODULE_11__["appendToCognitoUserAgent"]; });
8907
8908/* harmony import */ var _utils_WordArray__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/WordArray */ "../amazon-cognito-identity-js/es/utils/WordArray.js");
8909/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WordArray", function() { return _utils_WordArray__WEBPACK_IMPORTED_MODULE_12__["default"]; });
8910
8911/*!
8912 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
8913 * SPDX-License-Identifier: Apache-2.0
8914 */
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929/***/ }),
8930
8931/***/ "../amazon-cognito-identity-js/es/utils/WordArray.js":
8932/*!***********************************************************!*\
8933 !*** ../amazon-cognito-identity-js/es/utils/WordArray.js ***!
8934 \***********************************************************/
8935/*! exports provided: default */
8936/***/ (function(module, __webpack_exports__, __webpack_require__) {
8937
8938"use strict";
8939__webpack_require__.r(__webpack_exports__);
8940/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WordArray; });
8941/* harmony import */ var _cryptoSecureRandomInt__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./cryptoSecureRandomInt */ "../amazon-cognito-identity-js/es/utils/cryptoSecureRandomInt.js");
8942
8943/**
8944 * Hex encoding strategy.
8945 * Converts a word array to a hex string.
8946 * @param {WordArray} wordArray The word array.
8947 * @return {string} The hex string.
8948 * @static
8949 */
8950
8951function hexStringify(wordArray) {
8952 // Shortcuts
8953 var words = wordArray.words;
8954 var sigBytes = wordArray.sigBytes; // Convert
8955
8956 var hexChars = [];
8957
8958 for (var i = 0; i < sigBytes; i++) {
8959 var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
8960 hexChars.push((bite >>> 4).toString(16));
8961 hexChars.push((bite & 0x0f).toString(16));
8962 }
8963
8964 return hexChars.join('');
8965}
8966
8967var WordArray = /*#__PURE__*/function () {
8968 function WordArray(words, sigBytes) {
8969 words = this.words = words || [];
8970
8971 if (sigBytes != undefined) {
8972 this.sigBytes = sigBytes;
8973 } else {
8974 this.sigBytes = words.length * 4;
8975 }
8976 }
8977
8978 var _proto = WordArray.prototype;
8979
8980 _proto.random = function random(nBytes) {
8981 var words = [];
8982
8983 for (var i = 0; i < nBytes; i += 4) {
8984 words.push(Object(_cryptoSecureRandomInt__WEBPACK_IMPORTED_MODULE_0__["default"])());
8985 }
8986
8987 return new WordArray(words, nBytes);
8988 };
8989
8990 _proto.toString = function toString() {
8991 return hexStringify(this);
8992 };
8993
8994 return WordArray;
8995}();
8996
8997
8998
8999/***/ }),
9000
9001/***/ "../amazon-cognito-identity-js/es/utils/cryptoSecureRandomInt.js":
9002/*!***********************************************************************!*\
9003 !*** ../amazon-cognito-identity-js/es/utils/cryptoSecureRandomInt.js ***!
9004 \***********************************************************************/
9005/*! exports provided: default */
9006/***/ (function(module, __webpack_exports__, __webpack_require__) {
9007
9008"use strict";
9009__webpack_require__.r(__webpack_exports__);
9010/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return cryptoSecureRandomInt; });
9011var crypto; // Native crypto from window (Browser)
9012
9013if (typeof window !== 'undefined' && window.crypto) {
9014 crypto = window.crypto;
9015} // Native (experimental IE 11) crypto from window (Browser)
9016
9017
9018if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
9019 crypto = window.msCrypto;
9020} // Native crypto from global (NodeJS)
9021
9022
9023if (!crypto && typeof global !== 'undefined' && global.crypto) {
9024 crypto = global.crypto;
9025} // Native crypto import via require (NodeJS)
9026
9027
9028if (!crypto && "function" === 'function') {
9029 try {
9030 crypto = __webpack_require__(/*! crypto */ 1);
9031 } catch (err) {}
9032}
9033/*
9034 * Cryptographically secure pseudorandom number generator
9035 * As Math.random() is cryptographically not safe to use
9036 */
9037
9038
9039function cryptoSecureRandomInt() {
9040 if (crypto) {
9041 // Use getRandomValues method (Browser)
9042 if (typeof crypto.getRandomValues === 'function') {
9043 try {
9044 return crypto.getRandomValues(new Uint32Array(1))[0];
9045 } catch (err) {}
9046 } // Use randomBytes method (NodeJS)
9047
9048
9049 if (typeof crypto.randomBytes === 'function') {
9050 try {
9051 return crypto.randomBytes(4).readInt32LE();
9052 } catch (err) {}
9053 }
9054 }
9055
9056 throw new Error('Native crypto module could not be used to get secure random number.');
9057}
9058/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
9059
9060/***/ }),
9061
9062/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js":
9063/*!********************************************************************!*\
9064 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/core.js ***!
9065 \********************************************************************/
9066/*! no static exports found */
9067/***/ (function(module, exports, __webpack_require__) {
9068
9069/* WEBPACK VAR INJECTION */(function(global) {;(function (root, factory) {
9070 if (true) {
9071 // CommonJS
9072 module.exports = exports = factory();
9073 }
9074 else {}
9075}(this, function () {
9076
9077 /*globals window, global, require*/
9078
9079 /**
9080 * CryptoJS core components.
9081 */
9082 var CryptoJS = CryptoJS || (function (Math, undefined) {
9083
9084 var crypto;
9085
9086 // Native crypto from window (Browser)
9087 if (typeof window !== 'undefined' && window.crypto) {
9088 crypto = window.crypto;
9089 }
9090
9091 // Native crypto in web worker (Browser)
9092 if (typeof self !== 'undefined' && self.crypto) {
9093 crypto = self.crypto;
9094 }
9095
9096 // Native crypto from worker
9097 if (typeof globalThis !== 'undefined' && globalThis.crypto) {
9098 crypto = globalThis.crypto;
9099 }
9100
9101 // Native (experimental IE 11) crypto from window (Browser)
9102 if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
9103 crypto = window.msCrypto;
9104 }
9105
9106 // Native crypto from global (NodeJS)
9107 if (!crypto && typeof global !== 'undefined' && global.crypto) {
9108 crypto = global.crypto;
9109 }
9110
9111 // Native crypto import via require (NodeJS)
9112 if (!crypto && "function" === 'function') {
9113 try {
9114 crypto = __webpack_require__(/*! crypto */ 0);
9115 } catch (err) {}
9116 }
9117
9118 /*
9119 * Cryptographically secure pseudorandom number generator
9120 *
9121 * As Math.random() is cryptographically not safe to use
9122 */
9123 var cryptoSecureRandomInt = function () {
9124 if (crypto) {
9125 // Use getRandomValues method (Browser)
9126 if (typeof crypto.getRandomValues === 'function') {
9127 try {
9128 return crypto.getRandomValues(new Uint32Array(1))[0];
9129 } catch (err) {}
9130 }
9131
9132 // Use randomBytes method (NodeJS)
9133 if (typeof crypto.randomBytes === 'function') {
9134 try {
9135 return crypto.randomBytes(4).readInt32LE();
9136 } catch (err) {}
9137 }
9138 }
9139
9140 throw new Error('Native crypto module could not be used to get secure random number.');
9141 };
9142
9143 /*
9144 * Local polyfill of Object.create
9145
9146 */
9147 var create = Object.create || (function () {
9148 function F() {}
9149
9150 return function (obj) {
9151 var subtype;
9152
9153 F.prototype = obj;
9154
9155 subtype = new F();
9156
9157 F.prototype = null;
9158
9159 return subtype;
9160 };
9161 }());
9162
9163 /**
9164 * CryptoJS namespace.
9165 */
9166 var C = {};
9167
9168 /**
9169 * Library namespace.
9170 */
9171 var C_lib = C.lib = {};
9172
9173 /**
9174 * Base object for prototypal inheritance.
9175 */
9176 var Base = C_lib.Base = (function () {
9177
9178
9179 return {
9180 /**
9181 * Creates a new object that inherits from this object.
9182 *
9183 * @param {Object} overrides Properties to copy into the new object.
9184 *
9185 * @return {Object} The new object.
9186 *
9187 * @static
9188 *
9189 * @example
9190 *
9191 * var MyType = CryptoJS.lib.Base.extend({
9192 * field: 'value',
9193 *
9194 * method: function () {
9195 * }
9196 * });
9197 */
9198 extend: function (overrides) {
9199 // Spawn
9200 var subtype = create(this);
9201
9202 // Augment
9203 if (overrides) {
9204 subtype.mixIn(overrides);
9205 }
9206
9207 // Create default initializer
9208 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
9209 subtype.init = function () {
9210 subtype.$super.init.apply(this, arguments);
9211 };
9212 }
9213
9214 // Initializer's prototype is the subtype object
9215 subtype.init.prototype = subtype;
9216
9217 // Reference supertype
9218 subtype.$super = this;
9219
9220 return subtype;
9221 },
9222
9223 /**
9224 * Extends this object and runs the init method.
9225 * Arguments to create() will be passed to init().
9226 *
9227 * @return {Object} The new object.
9228 *
9229 * @static
9230 *
9231 * @example
9232 *
9233 * var instance = MyType.create();
9234 */
9235 create: function () {
9236 var instance = this.extend();
9237 instance.init.apply(instance, arguments);
9238
9239 return instance;
9240 },
9241
9242 /**
9243 * Initializes a newly created object.
9244 * Override this method to add some logic when your objects are created.
9245 *
9246 * @example
9247 *
9248 * var MyType = CryptoJS.lib.Base.extend({
9249 * init: function () {
9250 * // ...
9251 * }
9252 * });
9253 */
9254 init: function () {
9255 },
9256
9257 /**
9258 * Copies properties into this object.
9259 *
9260 * @param {Object} properties The properties to mix in.
9261 *
9262 * @example
9263 *
9264 * MyType.mixIn({
9265 * field: 'value'
9266 * });
9267 */
9268 mixIn: function (properties) {
9269 for (var propertyName in properties) {
9270 if (properties.hasOwnProperty(propertyName)) {
9271 this[propertyName] = properties[propertyName];
9272 }
9273 }
9274
9275 // IE won't copy toString using the loop above
9276 if (properties.hasOwnProperty('toString')) {
9277 this.toString = properties.toString;
9278 }
9279 },
9280
9281 /**
9282 * Creates a copy of this object.
9283 *
9284 * @return {Object} The clone.
9285 *
9286 * @example
9287 *
9288 * var clone = instance.clone();
9289 */
9290 clone: function () {
9291 return this.init.prototype.extend(this);
9292 }
9293 };
9294 }());
9295
9296 /**
9297 * An array of 32-bit words.
9298 *
9299 * @property {Array} words The array of 32-bit words.
9300 * @property {number} sigBytes The number of significant bytes in this word array.
9301 */
9302 var WordArray = C_lib.WordArray = Base.extend({
9303 /**
9304 * Initializes a newly created word array.
9305 *
9306 * @param {Array} words (Optional) An array of 32-bit words.
9307 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
9308 *
9309 * @example
9310 *
9311 * var wordArray = CryptoJS.lib.WordArray.create();
9312 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
9313 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
9314 */
9315 init: function (words, sigBytes) {
9316 words = this.words = words || [];
9317
9318 if (sigBytes != undefined) {
9319 this.sigBytes = sigBytes;
9320 } else {
9321 this.sigBytes = words.length * 4;
9322 }
9323 },
9324
9325 /**
9326 * Converts this word array to a string.
9327 *
9328 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
9329 *
9330 * @return {string} The stringified word array.
9331 *
9332 * @example
9333 *
9334 * var string = wordArray + '';
9335 * var string = wordArray.toString();
9336 * var string = wordArray.toString(CryptoJS.enc.Utf8);
9337 */
9338 toString: function (encoder) {
9339 return (encoder || Hex).stringify(this);
9340 },
9341
9342 /**
9343 * Concatenates a word array to this word array.
9344 *
9345 * @param {WordArray} wordArray The word array to append.
9346 *
9347 * @return {WordArray} This word array.
9348 *
9349 * @example
9350 *
9351 * wordArray1.concat(wordArray2);
9352 */
9353 concat: function (wordArray) {
9354 // Shortcuts
9355 var thisWords = this.words;
9356 var thatWords = wordArray.words;
9357 var thisSigBytes = this.sigBytes;
9358 var thatSigBytes = wordArray.sigBytes;
9359
9360 // Clamp excess bits
9361 this.clamp();
9362
9363 // Concat
9364 if (thisSigBytes % 4) {
9365 // Copy one byte at a time
9366 for (var i = 0; i < thatSigBytes; i++) {
9367 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
9368 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
9369 }
9370 } else {
9371 // Copy one word at a time
9372 for (var j = 0; j < thatSigBytes; j += 4) {
9373 thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
9374 }
9375 }
9376 this.sigBytes += thatSigBytes;
9377
9378 // Chainable
9379 return this;
9380 },
9381
9382 /**
9383 * Removes insignificant bits.
9384 *
9385 * @example
9386 *
9387 * wordArray.clamp();
9388 */
9389 clamp: function () {
9390 // Shortcuts
9391 var words = this.words;
9392 var sigBytes = this.sigBytes;
9393
9394 // Clamp
9395 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
9396 words.length = Math.ceil(sigBytes / 4);
9397 },
9398
9399 /**
9400 * Creates a copy of this word array.
9401 *
9402 * @return {WordArray} The clone.
9403 *
9404 * @example
9405 *
9406 * var clone = wordArray.clone();
9407 */
9408 clone: function () {
9409 var clone = Base.clone.call(this);
9410 clone.words = this.words.slice(0);
9411
9412 return clone;
9413 },
9414
9415 /**
9416 * Creates a word array filled with random bytes.
9417 *
9418 * @param {number} nBytes The number of random bytes to generate.
9419 *
9420 * @return {WordArray} The random word array.
9421 *
9422 * @static
9423 *
9424 * @example
9425 *
9426 * var wordArray = CryptoJS.lib.WordArray.random(16);
9427 */
9428 random: function (nBytes) {
9429 var words = [];
9430
9431 for (var i = 0; i < nBytes; i += 4) {
9432 words.push(cryptoSecureRandomInt());
9433 }
9434
9435 return new WordArray.init(words, nBytes);
9436 }
9437 });
9438
9439 /**
9440 * Encoder namespace.
9441 */
9442 var C_enc = C.enc = {};
9443
9444 /**
9445 * Hex encoding strategy.
9446 */
9447 var Hex = C_enc.Hex = {
9448 /**
9449 * Converts a word array to a hex string.
9450 *
9451 * @param {WordArray} wordArray The word array.
9452 *
9453 * @return {string} The hex string.
9454 *
9455 * @static
9456 *
9457 * @example
9458 *
9459 * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
9460 */
9461 stringify: function (wordArray) {
9462 // Shortcuts
9463 var words = wordArray.words;
9464 var sigBytes = wordArray.sigBytes;
9465
9466 // Convert
9467 var hexChars = [];
9468 for (var i = 0; i < sigBytes; i++) {
9469 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
9470 hexChars.push((bite >>> 4).toString(16));
9471 hexChars.push((bite & 0x0f).toString(16));
9472 }
9473
9474 return hexChars.join('');
9475 },
9476
9477 /**
9478 * Converts a hex string to a word array.
9479 *
9480 * @param {string} hexStr The hex string.
9481 *
9482 * @return {WordArray} The word array.
9483 *
9484 * @static
9485 *
9486 * @example
9487 *
9488 * var wordArray = CryptoJS.enc.Hex.parse(hexString);
9489 */
9490 parse: function (hexStr) {
9491 // Shortcut
9492 var hexStrLength = hexStr.length;
9493
9494 // Convert
9495 var words = [];
9496 for (var i = 0; i < hexStrLength; i += 2) {
9497 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
9498 }
9499
9500 return new WordArray.init(words, hexStrLength / 2);
9501 }
9502 };
9503
9504 /**
9505 * Latin1 encoding strategy.
9506 */
9507 var Latin1 = C_enc.Latin1 = {
9508 /**
9509 * Converts a word array to a Latin1 string.
9510 *
9511 * @param {WordArray} wordArray The word array.
9512 *
9513 * @return {string} The Latin1 string.
9514 *
9515 * @static
9516 *
9517 * @example
9518 *
9519 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
9520 */
9521 stringify: function (wordArray) {
9522 // Shortcuts
9523 var words = wordArray.words;
9524 var sigBytes = wordArray.sigBytes;
9525
9526 // Convert
9527 var latin1Chars = [];
9528 for (var i = 0; i < sigBytes; i++) {
9529 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
9530 latin1Chars.push(String.fromCharCode(bite));
9531 }
9532
9533 return latin1Chars.join('');
9534 },
9535
9536 /**
9537 * Converts a Latin1 string to a word array.
9538 *
9539 * @param {string} latin1Str The Latin1 string.
9540 *
9541 * @return {WordArray} The word array.
9542 *
9543 * @static
9544 *
9545 * @example
9546 *
9547 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
9548 */
9549 parse: function (latin1Str) {
9550 // Shortcut
9551 var latin1StrLength = latin1Str.length;
9552
9553 // Convert
9554 var words = [];
9555 for (var i = 0; i < latin1StrLength; i++) {
9556 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
9557 }
9558
9559 return new WordArray.init(words, latin1StrLength);
9560 }
9561 };
9562
9563 /**
9564 * UTF-8 encoding strategy.
9565 */
9566 var Utf8 = C_enc.Utf8 = {
9567 /**
9568 * Converts a word array to a UTF-8 string.
9569 *
9570 * @param {WordArray} wordArray The word array.
9571 *
9572 * @return {string} The UTF-8 string.
9573 *
9574 * @static
9575 *
9576 * @example
9577 *
9578 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
9579 */
9580 stringify: function (wordArray) {
9581 try {
9582 return decodeURIComponent(escape(Latin1.stringify(wordArray)));
9583 } catch (e) {
9584 throw new Error('Malformed UTF-8 data');
9585 }
9586 },
9587
9588 /**
9589 * Converts a UTF-8 string to a word array.
9590 *
9591 * @param {string} utf8Str The UTF-8 string.
9592 *
9593 * @return {WordArray} The word array.
9594 *
9595 * @static
9596 *
9597 * @example
9598 *
9599 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
9600 */
9601 parse: function (utf8Str) {
9602 return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
9603 }
9604 };
9605
9606 /**
9607 * Abstract buffered block algorithm template.
9608 *
9609 * The property blockSize must be implemented in a concrete subtype.
9610 *
9611 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
9612 */
9613 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
9614 /**
9615 * Resets this block algorithm's data buffer to its initial state.
9616 *
9617 * @example
9618 *
9619 * bufferedBlockAlgorithm.reset();
9620 */
9621 reset: function () {
9622 // Initial values
9623 this._data = new WordArray.init();
9624 this._nDataBytes = 0;
9625 },
9626
9627 /**
9628 * Adds new data to this block algorithm's buffer.
9629 *
9630 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
9631 *
9632 * @example
9633 *
9634 * bufferedBlockAlgorithm._append('data');
9635 * bufferedBlockAlgorithm._append(wordArray);
9636 */
9637 _append: function (data) {
9638 // Convert string to WordArray, else assume WordArray already
9639 if (typeof data == 'string') {
9640 data = Utf8.parse(data);
9641 }
9642
9643 // Append
9644 this._data.concat(data);
9645 this._nDataBytes += data.sigBytes;
9646 },
9647
9648 /**
9649 * Processes available data blocks.
9650 *
9651 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
9652 *
9653 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
9654 *
9655 * @return {WordArray} The processed data.
9656 *
9657 * @example
9658 *
9659 * var processedData = bufferedBlockAlgorithm._process();
9660 * var processedData = bufferedBlockAlgorithm._process(!!'flush');
9661 */
9662 _process: function (doFlush) {
9663 var processedWords;
9664
9665 // Shortcuts
9666 var data = this._data;
9667 var dataWords = data.words;
9668 var dataSigBytes = data.sigBytes;
9669 var blockSize = this.blockSize;
9670 var blockSizeBytes = blockSize * 4;
9671
9672 // Count blocks ready
9673 var nBlocksReady = dataSigBytes / blockSizeBytes;
9674 if (doFlush) {
9675 // Round up to include partial blocks
9676 nBlocksReady = Math.ceil(nBlocksReady);
9677 } else {
9678 // Round down to include only full blocks,
9679 // less the number of blocks that must remain in the buffer
9680 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
9681 }
9682
9683 // Count words ready
9684 var nWordsReady = nBlocksReady * blockSize;
9685
9686 // Count bytes ready
9687 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
9688
9689 // Process blocks
9690 if (nWordsReady) {
9691 for (var offset = 0; offset < nWordsReady; offset += blockSize) {
9692 // Perform concrete-algorithm logic
9693 this._doProcessBlock(dataWords, offset);
9694 }
9695
9696 // Remove processed words
9697 processedWords = dataWords.splice(0, nWordsReady);
9698 data.sigBytes -= nBytesReady;
9699 }
9700
9701 // Return processed words
9702 return new WordArray.init(processedWords, nBytesReady);
9703 },
9704
9705 /**
9706 * Creates a copy of this object.
9707 *
9708 * @return {Object} The clone.
9709 *
9710 * @example
9711 *
9712 * var clone = bufferedBlockAlgorithm.clone();
9713 */
9714 clone: function () {
9715 var clone = Base.clone.call(this);
9716 clone._data = this._data.clone();
9717
9718 return clone;
9719 },
9720
9721 _minBufferSize: 0
9722 });
9723
9724 /**
9725 * Abstract hasher template.
9726 *
9727 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
9728 */
9729 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
9730 /**
9731 * Configuration options.
9732 */
9733 cfg: Base.extend(),
9734
9735 /**
9736 * Initializes a newly created hasher.
9737 *
9738 * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
9739 *
9740 * @example
9741 *
9742 * var hasher = CryptoJS.algo.SHA256.create();
9743 */
9744 init: function (cfg) {
9745 // Apply config defaults
9746 this.cfg = this.cfg.extend(cfg);
9747
9748 // Set initial values
9749 this.reset();
9750 },
9751
9752 /**
9753 * Resets this hasher to its initial state.
9754 *
9755 * @example
9756 *
9757 * hasher.reset();
9758 */
9759 reset: function () {
9760 // Reset data buffer
9761 BufferedBlockAlgorithm.reset.call(this);
9762
9763 // Perform concrete-hasher logic
9764 this._doReset();
9765 },
9766
9767 /**
9768 * Updates this hasher with a message.
9769 *
9770 * @param {WordArray|string} messageUpdate The message to append.
9771 *
9772 * @return {Hasher} This hasher.
9773 *
9774 * @example
9775 *
9776 * hasher.update('message');
9777 * hasher.update(wordArray);
9778 */
9779 update: function (messageUpdate) {
9780 // Append
9781 this._append(messageUpdate);
9782
9783 // Update the hash
9784 this._process();
9785
9786 // Chainable
9787 return this;
9788 },
9789
9790 /**
9791 * Finalizes the hash computation.
9792 * Note that the finalize operation is effectively a destructive, read-once operation.
9793 *
9794 * @param {WordArray|string} messageUpdate (Optional) A final message update.
9795 *
9796 * @return {WordArray} The hash.
9797 *
9798 * @example
9799 *
9800 * var hash = hasher.finalize();
9801 * var hash = hasher.finalize('message');
9802 * var hash = hasher.finalize(wordArray);
9803 */
9804 finalize: function (messageUpdate) {
9805 // Final message update
9806 if (messageUpdate) {
9807 this._append(messageUpdate);
9808 }
9809
9810 // Perform concrete-hasher logic
9811 var hash = this._doFinalize();
9812
9813 return hash;
9814 },
9815
9816 blockSize: 512/32,
9817
9818 /**
9819 * Creates a shortcut function to a hasher's object interface.
9820 *
9821 * @param {Hasher} hasher The hasher to create a helper for.
9822 *
9823 * @return {Function} The shortcut function.
9824 *
9825 * @static
9826 *
9827 * @example
9828 *
9829 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
9830 */
9831 _createHelper: function (hasher) {
9832 return function (message, cfg) {
9833 return new hasher.init(cfg).finalize(message);
9834 };
9835 },
9836
9837 /**
9838 * Creates a shortcut function to the HMAC's object interface.
9839 *
9840 * @param {Hasher} hasher The hasher to use in this HMAC helper.
9841 *
9842 * @return {Function} The shortcut function.
9843 *
9844 * @static
9845 *
9846 * @example
9847 *
9848 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
9849 */
9850 _createHmacHelper: function (hasher) {
9851 return function (message, key) {
9852 return new C_algo.HMAC.init(hasher, key).finalize(message);
9853 };
9854 }
9855 });
9856
9857 /**
9858 * Algorithm namespace.
9859 */
9860 var C_algo = C.algo = {};
9861
9862 return C;
9863 }(Math));
9864
9865
9866 return CryptoJS;
9867
9868}));
9869/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
9870
9871/***/ }),
9872
9873/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/enc-base64.js":
9874/*!**************************************************************************!*\
9875 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/enc-base64.js ***!
9876 \**************************************************************************/
9877/*! no static exports found */
9878/***/ (function(module, exports, __webpack_require__) {
9879
9880;(function (root, factory) {
9881 if (true) {
9882 // CommonJS
9883 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"));
9884 }
9885 else {}
9886}(this, function (CryptoJS) {
9887
9888 (function () {
9889 // Shortcuts
9890 var C = CryptoJS;
9891 var C_lib = C.lib;
9892 var WordArray = C_lib.WordArray;
9893 var C_enc = C.enc;
9894
9895 /**
9896 * Base64 encoding strategy.
9897 */
9898 var Base64 = C_enc.Base64 = {
9899 /**
9900 * Converts a word array to a Base64 string.
9901 *
9902 * @param {WordArray} wordArray The word array.
9903 *
9904 * @return {string} The Base64 string.
9905 *
9906 * @static
9907 *
9908 * @example
9909 *
9910 * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
9911 */
9912 stringify: function (wordArray) {
9913 // Shortcuts
9914 var words = wordArray.words;
9915 var sigBytes = wordArray.sigBytes;
9916 var map = this._map;
9917
9918 // Clamp excess bits
9919 wordArray.clamp();
9920
9921 // Convert
9922 var base64Chars = [];
9923 for (var i = 0; i < sigBytes; i += 3) {
9924 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
9925 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
9926 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
9927
9928 var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
9929
9930 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
9931 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
9932 }
9933 }
9934
9935 // Add padding
9936 var paddingChar = map.charAt(64);
9937 if (paddingChar) {
9938 while (base64Chars.length % 4) {
9939 base64Chars.push(paddingChar);
9940 }
9941 }
9942
9943 return base64Chars.join('');
9944 },
9945
9946 /**
9947 * Converts a Base64 string to a word array.
9948 *
9949 * @param {string} base64Str The Base64 string.
9950 *
9951 * @return {WordArray} The word array.
9952 *
9953 * @static
9954 *
9955 * @example
9956 *
9957 * var wordArray = CryptoJS.enc.Base64.parse(base64String);
9958 */
9959 parse: function (base64Str) {
9960 // Shortcuts
9961 var base64StrLength = base64Str.length;
9962 var map = this._map;
9963 var reverseMap = this._reverseMap;
9964
9965 if (!reverseMap) {
9966 reverseMap = this._reverseMap = [];
9967 for (var j = 0; j < map.length; j++) {
9968 reverseMap[map.charCodeAt(j)] = j;
9969 }
9970 }
9971
9972 // Ignore padding
9973 var paddingChar = map.charAt(64);
9974 if (paddingChar) {
9975 var paddingIndex = base64Str.indexOf(paddingChar);
9976 if (paddingIndex !== -1) {
9977 base64StrLength = paddingIndex;
9978 }
9979 }
9980
9981 // Convert
9982 return parseLoop(base64Str, base64StrLength, reverseMap);
9983
9984 },
9985
9986 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
9987 };
9988
9989 function parseLoop(base64Str, base64StrLength, reverseMap) {
9990 var words = [];
9991 var nBytes = 0;
9992 for (var i = 0; i < base64StrLength; i++) {
9993 if (i % 4) {
9994 var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
9995 var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
9996 var bitsCombined = bits1 | bits2;
9997 words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
9998 nBytes++;
9999 }
10000 }
10001 return WordArray.create(words, nBytes);
10002 }
10003 }());
10004
10005
10006 return CryptoJS.enc.Base64;
10007
10008}));
10009
10010/***/ }),
10011
10012/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/hmac-sha256.js":
10013/*!***************************************************************************!*\
10014 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/hmac-sha256.js ***!
10015 \***************************************************************************/
10016/*! no static exports found */
10017/***/ (function(module, exports, __webpack_require__) {
10018
10019;(function (root, factory, undef) {
10020 if (true) {
10021 // CommonJS
10022 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"));
10023 }
10024 else {}
10025}(this, function (CryptoJS) {
10026
10027 return CryptoJS.HmacSHA256;
10028
10029}));
10030
10031/***/ }),
10032
10033/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/hmac.js":
10034/*!********************************************************************!*\
10035 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/hmac.js ***!
10036 \********************************************************************/
10037/*! no static exports found */
10038/***/ (function(module, exports, __webpack_require__) {
10039
10040;(function (root, factory) {
10041 if (true) {
10042 // CommonJS
10043 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"));
10044 }
10045 else {}
10046}(this, function (CryptoJS) {
10047
10048 (function () {
10049 // Shortcuts
10050 var C = CryptoJS;
10051 var C_lib = C.lib;
10052 var Base = C_lib.Base;
10053 var C_enc = C.enc;
10054 var Utf8 = C_enc.Utf8;
10055 var C_algo = C.algo;
10056
10057 /**
10058 * HMAC algorithm.
10059 */
10060 var HMAC = C_algo.HMAC = Base.extend({
10061 /**
10062 * Initializes a newly created HMAC.
10063 *
10064 * @param {Hasher} hasher The hash algorithm to use.
10065 * @param {WordArray|string} key The secret key.
10066 *
10067 * @example
10068 *
10069 * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
10070 */
10071 init: function (hasher, key) {
10072 // Init hasher
10073 hasher = this._hasher = new hasher.init();
10074
10075 // Convert string to WordArray, else assume WordArray already
10076 if (typeof key == 'string') {
10077 key = Utf8.parse(key);
10078 }
10079
10080 // Shortcuts
10081 var hasherBlockSize = hasher.blockSize;
10082 var hasherBlockSizeBytes = hasherBlockSize * 4;
10083
10084 // Allow arbitrary length keys
10085 if (key.sigBytes > hasherBlockSizeBytes) {
10086 key = hasher.finalize(key);
10087 }
10088
10089 // Clamp excess bits
10090 key.clamp();
10091
10092 // Clone key for inner and outer pads
10093 var oKey = this._oKey = key.clone();
10094 var iKey = this._iKey = key.clone();
10095
10096 // Shortcuts
10097 var oKeyWords = oKey.words;
10098 var iKeyWords = iKey.words;
10099
10100 // XOR keys with pad constants
10101 for (var i = 0; i < hasherBlockSize; i++) {
10102 oKeyWords[i] ^= 0x5c5c5c5c;
10103 iKeyWords[i] ^= 0x36363636;
10104 }
10105 oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
10106
10107 // Set initial values
10108 this.reset();
10109 },
10110
10111 /**
10112 * Resets this HMAC to its initial state.
10113 *
10114 * @example
10115 *
10116 * hmacHasher.reset();
10117 */
10118 reset: function () {
10119 // Shortcut
10120 var hasher = this._hasher;
10121
10122 // Reset
10123 hasher.reset();
10124 hasher.update(this._iKey);
10125 },
10126
10127 /**
10128 * Updates this HMAC with a message.
10129 *
10130 * @param {WordArray|string} messageUpdate The message to append.
10131 *
10132 * @return {HMAC} This HMAC instance.
10133 *
10134 * @example
10135 *
10136 * hmacHasher.update('message');
10137 * hmacHasher.update(wordArray);
10138 */
10139 update: function (messageUpdate) {
10140 this._hasher.update(messageUpdate);
10141
10142 // Chainable
10143 return this;
10144 },
10145
10146 /**
10147 * Finalizes the HMAC computation.
10148 * Note that the finalize operation is effectively a destructive, read-once operation.
10149 *
10150 * @param {WordArray|string} messageUpdate (Optional) A final message update.
10151 *
10152 * @return {WordArray} The HMAC.
10153 *
10154 * @example
10155 *
10156 * var hmac = hmacHasher.finalize();
10157 * var hmac = hmacHasher.finalize('message');
10158 * var hmac = hmacHasher.finalize(wordArray);
10159 */
10160 finalize: function (messageUpdate) {
10161 // Shortcut
10162 var hasher = this._hasher;
10163
10164 // Compute HMAC
10165 var innerHash = hasher.finalize(messageUpdate);
10166 hasher.reset();
10167 var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
10168
10169 return hmac;
10170 }
10171 });
10172 }());
10173
10174
10175}));
10176
10177/***/ }),
10178
10179/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/lib-typedarrays.js":
10180/*!*******************************************************************************!*\
10181 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/lib-typedarrays.js ***!
10182 \*******************************************************************************/
10183/*! no static exports found */
10184/***/ (function(module, exports, __webpack_require__) {
10185
10186;(function (root, factory) {
10187 if (true) {
10188 // CommonJS
10189 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"));
10190 }
10191 else {}
10192}(this, function (CryptoJS) {
10193
10194 (function () {
10195 // Check if typed arrays are supported
10196 if (typeof ArrayBuffer != 'function') {
10197 return;
10198 }
10199
10200 // Shortcuts
10201 var C = CryptoJS;
10202 var C_lib = C.lib;
10203 var WordArray = C_lib.WordArray;
10204
10205 // Reference original init
10206 var superInit = WordArray.init;
10207
10208 // Augment WordArray.init to handle typed arrays
10209 var subInit = WordArray.init = function (typedArray) {
10210 // Convert buffers to uint8
10211 if (typedArray instanceof ArrayBuffer) {
10212 typedArray = new Uint8Array(typedArray);
10213 }
10214
10215 // Convert other array views to uint8
10216 if (
10217 typedArray instanceof Int8Array ||
10218 (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
10219 typedArray instanceof Int16Array ||
10220 typedArray instanceof Uint16Array ||
10221 typedArray instanceof Int32Array ||
10222 typedArray instanceof Uint32Array ||
10223 typedArray instanceof Float32Array ||
10224 typedArray instanceof Float64Array
10225 ) {
10226 typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
10227 }
10228
10229 // Handle Uint8Array
10230 if (typedArray instanceof Uint8Array) {
10231 // Shortcut
10232 var typedArrayByteLength = typedArray.byteLength;
10233
10234 // Extract bytes
10235 var words = [];
10236 for (var i = 0; i < typedArrayByteLength; i++) {
10237 words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
10238 }
10239
10240 // Initialize this word array
10241 superInit.call(this, words, typedArrayByteLength);
10242 } else {
10243 // Else call normal init
10244 superInit.apply(this, arguments);
10245 }
10246 };
10247
10248 subInit.prototype = WordArray;
10249 }());
10250
10251
10252 return CryptoJS.lib.WordArray;
10253
10254}));
10255
10256/***/ }),
10257
10258/***/ "../amazon-cognito-identity-js/node_modules/crypto-js/sha256.js":
10259/*!**********************************************************************!*\
10260 !*** ../amazon-cognito-identity-js/node_modules/crypto-js/sha256.js ***!
10261 \**********************************************************************/
10262/*! no static exports found */
10263/***/ (function(module, exports, __webpack_require__) {
10264
10265;(function (root, factory) {
10266 if (true) {
10267 // CommonJS
10268 module.exports = exports = factory(__webpack_require__(/*! ./core */ "../amazon-cognito-identity-js/node_modules/crypto-js/core.js"));
10269 }
10270 else {}
10271}(this, function (CryptoJS) {
10272
10273 (function (Math) {
10274 // Shortcuts
10275 var C = CryptoJS;
10276 var C_lib = C.lib;
10277 var WordArray = C_lib.WordArray;
10278 var Hasher = C_lib.Hasher;
10279 var C_algo = C.algo;
10280
10281 // Initialization and round constants tables
10282 var H = [];
10283 var K = [];
10284
10285 // Compute constants
10286 (function () {
10287 function isPrime(n) {
10288 var sqrtN = Math.sqrt(n);
10289 for (var factor = 2; factor <= sqrtN; factor++) {
10290 if (!(n % factor)) {
10291 return false;
10292 }
10293 }
10294
10295 return true;
10296 }
10297
10298 function getFractionalBits(n) {
10299 return ((n - (n | 0)) * 0x100000000) | 0;
10300 }
10301
10302 var n = 2;
10303 var nPrime = 0;
10304 while (nPrime < 64) {
10305 if (isPrime(n)) {
10306 if (nPrime < 8) {
10307 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
10308 }
10309 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
10310
10311 nPrime++;
10312 }
10313
10314 n++;
10315 }
10316 }());
10317
10318 // Reusable object
10319 var W = [];
10320
10321 /**
10322 * SHA-256 hash algorithm.
10323 */
10324 var SHA256 = C_algo.SHA256 = Hasher.extend({
10325 _doReset: function () {
10326 this._hash = new WordArray.init(H.slice(0));
10327 },
10328
10329 _doProcessBlock: function (M, offset) {
10330 // Shortcut
10331 var H = this._hash.words;
10332
10333 // Working variables
10334 var a = H[0];
10335 var b = H[1];
10336 var c = H[2];
10337 var d = H[3];
10338 var e = H[4];
10339 var f = H[5];
10340 var g = H[6];
10341 var h = H[7];
10342
10343 // Computation
10344 for (var i = 0; i < 64; i++) {
10345 if (i < 16) {
10346 W[i] = M[offset + i] | 0;
10347 } else {
10348 var gamma0x = W[i - 15];
10349 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
10350 ((gamma0x << 14) | (gamma0x >>> 18)) ^
10351 (gamma0x >>> 3);
10352
10353 var gamma1x = W[i - 2];
10354 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
10355 ((gamma1x << 13) | (gamma1x >>> 19)) ^
10356 (gamma1x >>> 10);
10357
10358 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
10359 }
10360
10361 var ch = (e & f) ^ (~e & g);
10362 var maj = (a & b) ^ (a & c) ^ (b & c);
10363
10364 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
10365 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
10366
10367 var t1 = h + sigma1 + ch + K[i] + W[i];
10368 var t2 = sigma0 + maj;
10369
10370 h = g;
10371 g = f;
10372 f = e;
10373 e = (d + t1) | 0;
10374 d = c;
10375 c = b;
10376 b = a;
10377 a = (t1 + t2) | 0;
10378 }
10379
10380 // Intermediate hash value
10381 H[0] = (H[0] + a) | 0;
10382 H[1] = (H[1] + b) | 0;
10383 H[2] = (H[2] + c) | 0;
10384 H[3] = (H[3] + d) | 0;
10385 H[4] = (H[4] + e) | 0;
10386 H[5] = (H[5] + f) | 0;
10387 H[6] = (H[6] + g) | 0;
10388 H[7] = (H[7] + h) | 0;
10389 },
10390
10391 _doFinalize: function () {
10392 // Shortcuts
10393 var data = this._data;
10394 var dataWords = data.words;
10395
10396 var nBitsTotal = this._nDataBytes * 8;
10397 var nBitsLeft = data.sigBytes * 8;
10398
10399 // Add padding
10400 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
10401 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
10402 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
10403 data.sigBytes = dataWords.length * 4;
10404
10405 // Hash final blocks
10406 this._process();
10407
10408 // Return final computed hash
10409 return this._hash;
10410 },
10411
10412 clone: function () {
10413 var clone = Hasher.clone.call(this);
10414 clone._hash = this._hash.clone();
10415
10416 return clone;
10417 }
10418 });
10419
10420 /**
10421 * Shortcut function to the hasher's object interface.
10422 *
10423 * @param {WordArray|string} message The message to hash.
10424 *
10425 * @return {WordArray} The hash.
10426 *
10427 * @static
10428 *
10429 * @example
10430 *
10431 * var hash = CryptoJS.SHA256('message');
10432 * var hash = CryptoJS.SHA256(wordArray);
10433 */
10434 C.SHA256 = Hasher._createHelper(SHA256);
10435
10436 /**
10437 * Shortcut function to the HMAC's object interface.
10438 *
10439 * @param {WordArray|string} message The message to hash.
10440 * @param {WordArray|string} key The secret key.
10441 *
10442 * @return {WordArray} The HMAC.
10443 *
10444 * @static
10445 *
10446 * @example
10447 *
10448 * var hmac = CryptoJS.HmacSHA256(message, key);
10449 */
10450 C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
10451 }(Math));
10452
10453
10454 return CryptoJS.SHA256;
10455
10456}));
10457
10458/***/ }),
10459
10460/***/ "./lib-esm/Auth.js":
10461/*!*************************!*\
10462 !*** ./lib-esm/Auth.js ***!
10463 \*************************/
10464/*! exports provided: AuthClass, Auth */
10465/***/ (function(module, __webpack_exports__, __webpack_require__) {
10466
10467"use strict";
10468__webpack_require__.r(__webpack_exports__);
10469/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthClass", function() { return AuthClass; });
10470/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Auth", function() { return Auth; });
10471/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types */ "./lib-esm/types/index.js");
10472/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
10473/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__);
10474/* harmony import */ var amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! amazon-cognito-identity-js */ "../amazon-cognito-identity-js/es/index.js");
10475/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! url */ "../../node_modules/url/url.js");
10476/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_3__);
10477/* harmony import */ var _OAuth_OAuth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./OAuth/OAuth */ "./lib-esm/OAuth/OAuth.js");
10478/* harmony import */ var _urlListener__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./urlListener */ "./lib-esm/urlListener.js");
10479/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Errors */ "./lib-esm/Errors.js");
10480/* harmony import */ var _types_Auth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types/Auth */ "./lib-esm/types/Auth.js");
10481function _typeof(obj) {
10482 "@babel/helpers - typeof";
10483
10484 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
10485 return typeof obj;
10486 } : function (obj) {
10487 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
10488 }, _typeof(obj);
10489}
10490/*
10491 * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
10492 *
10493 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
10494 * the License. A copy of the License is located at
10495 *
10496 * http://aws.amazon.com/apache2.0/
10497 *
10498 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
10499 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
10500 * and limitations under the License.
10501 */
10502
10503
10504var __assign = undefined && undefined.__assign || function () {
10505 __assign = Object.assign || function (t) {
10506 for (var s, i = 1, n = arguments.length; i < n; i++) {
10507 s = arguments[i];
10508
10509 for (var p in s) {
10510 if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
10511 }
10512 }
10513
10514 return t;
10515 };
10516
10517 return __assign.apply(this, arguments);
10518};
10519
10520var __awaiter = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) {
10521 function adopt(value) {
10522 return value instanceof P ? value : new P(function (resolve) {
10523 resolve(value);
10524 });
10525 }
10526
10527 return new (P || (P = Promise))(function (resolve, reject) {
10528 function fulfilled(value) {
10529 try {
10530 step(generator.next(value));
10531 } catch (e) {
10532 reject(e);
10533 }
10534 }
10535
10536 function rejected(value) {
10537 try {
10538 step(generator["throw"](value));
10539 } catch (e) {
10540 reject(e);
10541 }
10542 }
10543
10544 function step(result) {
10545 result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
10546 }
10547
10548 step((generator = generator.apply(thisArg, _arguments || [])).next());
10549 });
10550};
10551
10552var __generator = undefined && undefined.__generator || function (thisArg, body) {
10553 var _ = {
10554 label: 0,
10555 sent: function sent() {
10556 if (t[0] & 1) throw t[1];
10557 return t[1];
10558 },
10559 trys: [],
10560 ops: []
10561 },
10562 f,
10563 y,
10564 t,
10565 g;
10566 return g = {
10567 next: verb(0),
10568 "throw": verb(1),
10569 "return": verb(2)
10570 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
10571 return this;
10572 }), g;
10573
10574 function verb(n) {
10575 return function (v) {
10576 return step([n, v]);
10577 };
10578 }
10579
10580 function step(op) {
10581 if (f) throw new TypeError("Generator is already executing.");
10582
10583 while (_) {
10584 try {
10585 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;
10586 if (y = 0, t) op = [op[0] & 2, t.value];
10587
10588 switch (op[0]) {
10589 case 0:
10590 case 1:
10591 t = op;
10592 break;
10593
10594 case 4:
10595 _.label++;
10596 return {
10597 value: op[1],
10598 done: false
10599 };
10600
10601 case 5:
10602 _.label++;
10603 y = op[1];
10604 op = [0];
10605 continue;
10606
10607 case 7:
10608 op = _.ops.pop();
10609
10610 _.trys.pop();
10611
10612 continue;
10613
10614 default:
10615 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
10616 _ = 0;
10617 continue;
10618 }
10619
10620 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
10621 _.label = op[1];
10622 break;
10623 }
10624
10625 if (op[0] === 6 && _.label < t[1]) {
10626 _.label = t[1];
10627 t = op;
10628 break;
10629 }
10630
10631 if (t && _.label < t[2]) {
10632 _.label = t[2];
10633
10634 _.ops.push(op);
10635
10636 break;
10637 }
10638
10639 if (t[2]) _.ops.pop();
10640
10641 _.trys.pop();
10642
10643 continue;
10644 }
10645
10646 op = body.call(thisArg, _);
10647 } catch (e) {
10648 op = [6, e];
10649 y = 0;
10650 } finally {
10651 f = t = 0;
10652 }
10653 }
10654
10655 if (op[0] & 5) throw op[1];
10656 return {
10657 value: op[0] ? op[1] : void 0,
10658 done: true
10659 };
10660 }
10661};
10662
10663var __read = undefined && undefined.__read || function (o, n) {
10664 var m = typeof Symbol === "function" && o[Symbol.iterator];
10665 if (!m) return o;
10666 var i = m.call(o),
10667 r,
10668 ar = [],
10669 e;
10670
10671 try {
10672 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
10673 ar.push(r.value);
10674 }
10675 } catch (error) {
10676 e = {
10677 error: error
10678 };
10679 } finally {
10680 try {
10681 if (r && !r.done && (m = i["return"])) m.call(i);
10682 } finally {
10683 if (e) throw e.error;
10684 }
10685 }
10686
10687 return ar;
10688};
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["ConsoleLogger"]('AuthClass');
10699var USER_ADMIN_SCOPE = 'aws.cognito.signin.user.admin'; // 10 sec, following this guide https://www.nngroup.com/articles/response-times-3-important-limits/
10700
10701var OAUTH_FLOW_MS_TIMEOUT = 10 * 1000;
10702var AMPLIFY_SYMBOL = typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function' ? Symbol["for"]('amplify_default') : '@@amplify_default';
10703
10704var dispatchAuthEvent = function dispatchAuthEvent(event, data, message) {
10705 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].dispatch('auth', {
10706 event: event,
10707 data: data,
10708 message: message
10709 }, 'Auth', AMPLIFY_SYMBOL);
10710}; // Cognito Documentation for max device
10711// tslint:disable-next-line:max-line-length
10712// https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html#API_ListDevices_RequestSyntax
10713
10714
10715var MAX_DEVICES = 60;
10716/**
10717 * Provide authentication steps
10718 */
10719
10720var AuthClass =
10721/** @class */
10722function () {
10723 /**
10724 * Initialize Auth with AWS configurations
10725 * @param {Object} config - Configuration of the Auth
10726 */
10727 function AuthClass(config) {
10728 var _this = this;
10729
10730 this.userPool = null;
10731 this.user = null;
10732 this.oAuthFlowInProgress = false;
10733 this.Credentials = _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Credentials"];
10734
10735 this.wrapRefreshSessionCallback = function (callback) {
10736 var wrapped = function wrapped(error, data) {
10737 if (data) {
10738 dispatchAuthEvent('tokenRefresh', undefined, "New token retrieved");
10739 } else {
10740 dispatchAuthEvent('tokenRefresh_failure', error, "Failed to retrieve new token");
10741 }
10742
10743 return callback(error, data);
10744 };
10745
10746 return wrapped;
10747 }; // prettier-ignore
10748
10749
10750 this.configure(config);
10751 this.currentCredentials = this.currentCredentials.bind(this);
10752 this.currentUserCredentials = this.currentUserCredentials.bind(this);
10753 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].listen('auth', function (_a) {
10754 var payload = _a.payload;
10755 var event = payload.event;
10756
10757 switch (event) {
10758 case 'signIn':
10759 _this._storage.setItem('amplify-signin-with-hostedUI', 'false');
10760
10761 break;
10762
10763 case 'signOut':
10764 _this._storage.removeItem('amplify-signin-with-hostedUI');
10765
10766 break;
10767
10768 case 'cognitoHostedUI':
10769 _this._storage.setItem('amplify-signin-with-hostedUI', 'true');
10770
10771 break;
10772 }
10773 });
10774 }
10775
10776 AuthClass.prototype.getModuleName = function () {
10777 return 'Auth';
10778 };
10779
10780 AuthClass.prototype.configure = function (config) {
10781 var _this = this;
10782
10783 if (!config) return this._config || {};
10784 logger.debug('configure Auth');
10785 var conf = Object.assign({}, this._config, _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Parser"].parseMobilehubConfig(config).Auth, config);
10786 this._config = conf;
10787 var _a = this._config,
10788 userPoolId = _a.userPoolId,
10789 userPoolWebClientId = _a.userPoolWebClientId,
10790 cookieStorage = _a.cookieStorage,
10791 oauth = _a.oauth,
10792 region = _a.region,
10793 identityPoolId = _a.identityPoolId,
10794 mandatorySignIn = _a.mandatorySignIn,
10795 refreshHandlers = _a.refreshHandlers,
10796 identityPoolRegion = _a.identityPoolRegion,
10797 clientMetadata = _a.clientMetadata,
10798 endpoint = _a.endpoint;
10799
10800 if (!this._config.storage) {
10801 // backward compatability
10802 if (cookieStorage) this._storage = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CookieStorage"](cookieStorage);else {
10803 this._storage = config.ssr ? new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["UniversalStorage"]() : new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["StorageHelper"]().getStorage();
10804 }
10805 } else {
10806 if (!this._isValidAuthStorage(this._config.storage)) {
10807 logger.error('The storage in the Auth config is not valid!');
10808 throw new Error('Empty storage object');
10809 }
10810
10811 this._storage = this._config.storage;
10812 }
10813
10814 this._storageSync = Promise.resolve();
10815
10816 if (typeof this._storage['sync'] === 'function') {
10817 this._storageSync = this._storage['sync']();
10818 }
10819
10820 if (userPoolId) {
10821 var userPoolData = {
10822 UserPoolId: userPoolId,
10823 ClientId: userPoolWebClientId,
10824 endpoint: endpoint
10825 };
10826 userPoolData.Storage = this._storage;
10827 this.userPool = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserPool"](userPoolData, this.wrapRefreshSessionCallback);
10828 }
10829
10830 this.Credentials.configure({
10831 mandatorySignIn: mandatorySignIn,
10832 region: identityPoolRegion || region,
10833 userPoolId: userPoolId,
10834 identityPoolId: identityPoolId,
10835 refreshHandlers: refreshHandlers,
10836 storage: this._storage
10837 }); // initialize cognitoauth client if hosted ui options provided
10838 // to keep backward compatibility:
10839
10840 var cognitoHostedUIConfig = oauth ? Object(_types__WEBPACK_IMPORTED_MODULE_0__["isCognitoHostedOpts"])(this._config.oauth) ? oauth : oauth.awsCognito : undefined;
10841
10842 if (cognitoHostedUIConfig) {
10843 var cognitoAuthParams = Object.assign({
10844 cognitoClientId: userPoolWebClientId,
10845 UserPoolId: userPoolId,
10846 domain: cognitoHostedUIConfig['domain'],
10847 scopes: cognitoHostedUIConfig['scope'],
10848 redirectSignIn: cognitoHostedUIConfig['redirectSignIn'],
10849 redirectSignOut: cognitoHostedUIConfig['redirectSignOut'],
10850 responseType: cognitoHostedUIConfig['responseType'],
10851 Storage: this._storage,
10852 urlOpener: cognitoHostedUIConfig['urlOpener'],
10853 clientMetadata: clientMetadata
10854 }, cognitoHostedUIConfig['options']);
10855 this._oAuthHandler = new _OAuth_OAuth__WEBPACK_IMPORTED_MODULE_4__["default"]({
10856 scopes: cognitoAuthParams.scopes,
10857 config: cognitoAuthParams,
10858 cognitoClientId: cognitoAuthParams.cognitoClientId
10859 }); // **NOTE** - Remove this in a future major release as it is a breaking change
10860 // Prevents _handleAuthResponse from being called multiple times in Expo
10861 // See https://github.com/aws-amplify/amplify-js/issues/4388
10862
10863 var usedResponseUrls_1 = {};
10864 Object(_urlListener__WEBPACK_IMPORTED_MODULE_5__["default"])(function (_a) {
10865 var url = _a.url;
10866
10867 if (usedResponseUrls_1[url]) {
10868 return;
10869 }
10870
10871 usedResponseUrls_1[url] = true;
10872
10873 _this._handleAuthResponse(url);
10874 });
10875 }
10876
10877 dispatchAuthEvent('configured', null, "The Auth category has been configured successfully");
10878 return this._config;
10879 };
10880 /**
10881 * Sign up with username, password and other attributes like phone, email
10882 * @param {String | object} params - The user attributes used for signin
10883 * @param {String[]} restOfAttrs - for the backward compatability
10884 * @return - A promise resolves callback data if success
10885 */
10886
10887
10888 AuthClass.prototype.signUp = function (params) {
10889 var _this = this;
10890
10891 var restOfAttrs = [];
10892
10893 for (var _i = 1; _i < arguments.length; _i++) {
10894 restOfAttrs[_i - 1] = arguments[_i];
10895 }
10896
10897 if (!this.userPool) {
10898 return this.rejectNoUserPool();
10899 }
10900
10901 var username = null;
10902 var password = null;
10903 var attributes = [];
10904 var validationData = null;
10905 var clientMetadata;
10906
10907 if (params && typeof params === 'string') {
10908 username = params;
10909 password = restOfAttrs ? restOfAttrs[0] : null;
10910 var email = restOfAttrs ? restOfAttrs[1] : null;
10911 var phone_number = restOfAttrs ? restOfAttrs[2] : null;
10912 if (email) attributes.push(new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"]({
10913 Name: 'email',
10914 Value: email
10915 }));
10916 if (phone_number) attributes.push(new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"]({
10917 Name: 'phone_number',
10918 Value: phone_number
10919 }));
10920 } else if (params && _typeof(params) === 'object') {
10921 username = params['username'];
10922 password = params['password'];
10923
10924 if (params && params.clientMetadata) {
10925 clientMetadata = params.clientMetadata;
10926 } else if (this._config.clientMetadata) {
10927 clientMetadata = this._config.clientMetadata;
10928 }
10929
10930 var attrs_1 = params['attributes'];
10931
10932 if (attrs_1) {
10933 Object.keys(attrs_1).map(function (key) {
10934 attributes.push(new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"]({
10935 Name: key,
10936 Value: attrs_1[key]
10937 }));
10938 });
10939 }
10940
10941 var validationDataObject_1 = params['validationData'];
10942
10943 if (validationDataObject_1) {
10944 validationData = [];
10945 Object.keys(validationDataObject_1).map(function (key) {
10946 validationData.push(new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"]({
10947 Name: key,
10948 Value: validationDataObject_1[key]
10949 }));
10950 });
10951 }
10952 } else {
10953 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].SignUpError);
10954 }
10955
10956 if (!username) {
10957 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
10958 }
10959
10960 if (!password) {
10961 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyPassword);
10962 }
10963
10964 logger.debug('signUp attrs:', attributes);
10965 logger.debug('signUp validation data:', validationData);
10966 return new Promise(function (resolve, reject) {
10967 _this.userPool.signUp(username, password, attributes, validationData, function (err, data) {
10968 if (err) {
10969 dispatchAuthEvent('signUp_failure', err, username + " failed to signup");
10970 reject(err);
10971 } else {
10972 dispatchAuthEvent('signUp', data, username + " has signed up successfully");
10973 resolve(data);
10974 }
10975 }, clientMetadata);
10976 });
10977 };
10978 /**
10979 * Send the verification code to confirm sign up
10980 * @param {String} username - The username to be confirmed
10981 * @param {String} code - The verification code
10982 * @param {ConfirmSignUpOptions} options - other options for confirm signup
10983 * @return - A promise resolves callback data if success
10984 */
10985
10986
10987 AuthClass.prototype.confirmSignUp = function (username, code, options) {
10988 if (!this.userPool) {
10989 return this.rejectNoUserPool();
10990 }
10991
10992 if (!username) {
10993 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
10994 }
10995
10996 if (!code) {
10997 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyCode);
10998 }
10999
11000 var user = this.createCognitoUser(username);
11001 var forceAliasCreation = options && typeof options.forceAliasCreation === 'boolean' ? options.forceAliasCreation : true;
11002 var clientMetadata;
11003
11004 if (options && options.clientMetadata) {
11005 clientMetadata = options.clientMetadata;
11006 } else if (this._config.clientMetadata) {
11007 clientMetadata = this._config.clientMetadata;
11008 }
11009
11010 return new Promise(function (resolve, reject) {
11011 user.confirmRegistration(code, forceAliasCreation, function (err, data) {
11012 if (err) {
11013 reject(err);
11014 } else {
11015 resolve(data);
11016 }
11017 }, clientMetadata);
11018 });
11019 };
11020 /**
11021 * Resend the verification code
11022 * @param {String} username - The username to be confirmed
11023 * @param {ClientMetadata} clientMetadata - Metadata to be passed to Cognito Lambda triggers
11024 * @return - A promise resolves code delivery details if successful
11025 */
11026
11027
11028 AuthClass.prototype.resendSignUp = function (username, clientMetadata) {
11029 if (clientMetadata === void 0) {
11030 clientMetadata = this._config.clientMetadata;
11031 }
11032
11033 if (!this.userPool) {
11034 return this.rejectNoUserPool();
11035 }
11036
11037 if (!username) {
11038 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
11039 }
11040
11041 var user = this.createCognitoUser(username);
11042 return new Promise(function (resolve, reject) {
11043 user.resendConfirmationCode(function (err, data) {
11044 if (err) {
11045 reject(err);
11046 } else {
11047 resolve(data);
11048 }
11049 }, clientMetadata);
11050 });
11051 };
11052 /**
11053 * Sign in
11054 * @param {String | SignInOpts} usernameOrSignInOpts - The username to be signed in or the sign in options
11055 * @param {String} password - The password of the username
11056 * @return - A promise resolves the CognitoUser
11057 */
11058
11059
11060 AuthClass.prototype.signIn = function (usernameOrSignInOpts, pw, clientMetadata) {
11061 if (clientMetadata === void 0) {
11062 clientMetadata = this._config.clientMetadata;
11063 }
11064
11065 if (!this.userPool) {
11066 return this.rejectNoUserPool();
11067 }
11068
11069 var username = null;
11070 var password = null;
11071 var validationData = {}; // for backward compatibility
11072
11073 if (typeof usernameOrSignInOpts === 'string') {
11074 username = usernameOrSignInOpts;
11075 password = pw;
11076 } else if (Object(_types__WEBPACK_IMPORTED_MODULE_0__["isUsernamePasswordOpts"])(usernameOrSignInOpts)) {
11077 if (typeof pw !== 'undefined') {
11078 logger.warn('The password should be defined under the first parameter object!');
11079 }
11080
11081 username = usernameOrSignInOpts.username;
11082 password = usernameOrSignInOpts.password;
11083 validationData = usernameOrSignInOpts.validationData;
11084 } else {
11085 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].InvalidUsername);
11086 }
11087
11088 if (!username) {
11089 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
11090 }
11091
11092 var authDetails = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["AuthenticationDetails"]({
11093 Username: username,
11094 Password: password,
11095 ValidationData: validationData,
11096 ClientMetadata: clientMetadata
11097 });
11098
11099 if (password) {
11100 return this.signInWithPassword(authDetails);
11101 } else {
11102 return this.signInWithoutPassword(authDetails);
11103 }
11104 };
11105 /**
11106 * Return an object with the authentication callbacks
11107 * @param {CognitoUser} user - the cognito user object
11108 * @param {} resolve - function called when resolving the current step
11109 * @param {} reject - function called when rejecting the current step
11110 * @return - an object with the callback methods for user authentication
11111 */
11112
11113
11114 AuthClass.prototype.authCallbacks = function (user, resolve, reject) {
11115 var _this = this;
11116
11117 var that = this;
11118 return {
11119 onSuccess: function onSuccess(session) {
11120 return __awaiter(_this, void 0, void 0, function () {
11121 var cred, e_1, currentUser, e_2;
11122 return __generator(this, function (_a) {
11123 switch (_a.label) {
11124 case 0:
11125 logger.debug(session);
11126 delete user['challengeName'];
11127 delete user['challengeParam'];
11128 _a.label = 1;
11129
11130 case 1:
11131 _a.trys.push([1, 4, 5, 9]);
11132
11133 return [4
11134 /*yield*/
11135 , this.Credentials.clear()];
11136
11137 case 2:
11138 _a.sent();
11139
11140 return [4
11141 /*yield*/
11142 , this.Credentials.set(session, 'session')];
11143
11144 case 3:
11145 cred = _a.sent();
11146 logger.debug('succeed to get cognito credentials', cred);
11147 return [3
11148 /*break*/
11149 , 9];
11150
11151 case 4:
11152 e_1 = _a.sent();
11153 logger.debug('cannot get cognito credentials', e_1);
11154 return [3
11155 /*break*/
11156 , 9];
11157
11158 case 5:
11159 _a.trys.push([5, 7,, 8]);
11160
11161 return [4
11162 /*yield*/
11163 , this.currentUserPoolUser()];
11164
11165 case 6:
11166 currentUser = _a.sent();
11167 that.user = currentUser;
11168 dispatchAuthEvent('signIn', currentUser, "A user " + user.getUsername() + " has been signed in");
11169 resolve(currentUser);
11170 return [3
11171 /*break*/
11172 , 8];
11173
11174 case 7:
11175 e_2 = _a.sent();
11176 logger.error('Failed to get the signed in user', e_2);
11177 reject(e_2);
11178 return [3
11179 /*break*/
11180 , 8];
11181
11182 case 8:
11183 return [7
11184 /*endfinally*/
11185 ];
11186
11187 case 9:
11188 return [2
11189 /*return*/
11190 ];
11191 }
11192 });
11193 });
11194 },
11195 onFailure: function onFailure(err) {
11196 logger.debug('signIn failure', err);
11197 dispatchAuthEvent('signIn_failure', err, user.getUsername() + " failed to signin");
11198 reject(err);
11199 },
11200 customChallenge: function customChallenge(challengeParam) {
11201 logger.debug('signIn custom challenge answer required');
11202 user['challengeName'] = 'CUSTOM_CHALLENGE';
11203 user['challengeParam'] = challengeParam;
11204 resolve(user);
11205 },
11206 mfaRequired: function mfaRequired(challengeName, challengeParam) {
11207 logger.debug('signIn MFA required');
11208 user['challengeName'] = challengeName;
11209 user['challengeParam'] = challengeParam;
11210 resolve(user);
11211 },
11212 mfaSetup: function mfaSetup(challengeName, challengeParam) {
11213 logger.debug('signIn mfa setup', challengeName);
11214 user['challengeName'] = challengeName;
11215 user['challengeParam'] = challengeParam;
11216 resolve(user);
11217 },
11218 newPasswordRequired: function newPasswordRequired(userAttributes, requiredAttributes) {
11219 logger.debug('signIn new password');
11220 user['challengeName'] = 'NEW_PASSWORD_REQUIRED';
11221 user['challengeParam'] = {
11222 userAttributes: userAttributes,
11223 requiredAttributes: requiredAttributes
11224 };
11225 resolve(user);
11226 },
11227 totpRequired: function totpRequired(challengeName, challengeParam) {
11228 logger.debug('signIn totpRequired');
11229 user['challengeName'] = challengeName;
11230 user['challengeParam'] = challengeParam;
11231 resolve(user);
11232 },
11233 selectMFAType: function selectMFAType(challengeName, challengeParam) {
11234 logger.debug('signIn selectMFAType', challengeName);
11235 user['challengeName'] = challengeName;
11236 user['challengeParam'] = challengeParam;
11237 resolve(user);
11238 }
11239 };
11240 };
11241 /**
11242 * Sign in with a password
11243 * @private
11244 * @param {AuthenticationDetails} authDetails - the user sign in data
11245 * @return - A promise resolves the CognitoUser object if success or mfa required
11246 */
11247
11248
11249 AuthClass.prototype.signInWithPassword = function (authDetails) {
11250 var _this = this;
11251
11252 if (this.pendingSignIn) {
11253 throw new Error('Pending sign-in attempt already in progress');
11254 }
11255
11256 var user = this.createCognitoUser(authDetails.getUsername());
11257 this.pendingSignIn = new Promise(function (resolve, reject) {
11258 user.authenticateUser(authDetails, _this.authCallbacks(user, function (value) {
11259 _this.pendingSignIn = null;
11260 resolve(value);
11261 }, function (error) {
11262 _this.pendingSignIn = null;
11263 reject(error);
11264 }));
11265 });
11266 return this.pendingSignIn;
11267 };
11268 /**
11269 * Sign in without a password
11270 * @private
11271 * @param {AuthenticationDetails} authDetails - the user sign in data
11272 * @return - A promise resolves the CognitoUser object if success or mfa required
11273 */
11274
11275
11276 AuthClass.prototype.signInWithoutPassword = function (authDetails) {
11277 var _this = this;
11278
11279 var user = this.createCognitoUser(authDetails.getUsername());
11280 user.setAuthenticationFlowType('CUSTOM_AUTH');
11281 return new Promise(function (resolve, reject) {
11282 user.initiateAuth(authDetails, _this.authCallbacks(user, resolve, reject));
11283 });
11284 };
11285 /**
11286 * This was previously used by an authenticated user to get MFAOptions,
11287 * but no longer returns a meaningful response. Refer to the documentation for
11288 * how to setup and use MFA: https://docs.amplify.aws/lib/auth/mfa/q/platform/js
11289 * @deprecated
11290 * @param {CognitoUser} user - the current user
11291 * @return - A promise resolves the current preferred mfa option if success
11292 */
11293
11294
11295 AuthClass.prototype.getMFAOptions = function (user) {
11296 return new Promise(function (res, rej) {
11297 user.getMFAOptions(function (err, mfaOptions) {
11298 if (err) {
11299 logger.debug('get MFA Options failed', err);
11300 rej(err);
11301 return;
11302 }
11303
11304 logger.debug('get MFA options success', mfaOptions);
11305 res(mfaOptions);
11306 return;
11307 });
11308 });
11309 };
11310 /**
11311 * get preferred mfa method
11312 * @param {CognitoUser} user - the current cognito user
11313 * @param {GetPreferredMFAOpts} params - options for getting the current user preferred MFA
11314 */
11315
11316
11317 AuthClass.prototype.getPreferredMFA = function (user, params) {
11318 var _this = this;
11319
11320 var that = this;
11321 return new Promise(function (res, rej) {
11322 var clientMetadata = _this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
11323
11324 var bypassCache = params ? params.bypassCache : false;
11325 user.getUserData(function (err, data) {
11326 return __awaiter(_this, void 0, void 0, function () {
11327 var cleanUpError_1, mfaType;
11328 return __generator(this, function (_a) {
11329 switch (_a.label) {
11330 case 0:
11331 if (!err) return [3
11332 /*break*/
11333 , 5];
11334 logger.debug('getting preferred mfa failed', err);
11335 if (!this.isSessionInvalid(err)) return [3
11336 /*break*/
11337 , 4];
11338 _a.label = 1;
11339
11340 case 1:
11341 _a.trys.push([1, 3,, 4]);
11342
11343 return [4
11344 /*yield*/
11345 , this.cleanUpInvalidSession(user)];
11346
11347 case 2:
11348 _a.sent();
11349
11350 return [3
11351 /*break*/
11352 , 4];
11353
11354 case 3:
11355 cleanUpError_1 = _a.sent();
11356 rej(new Error("Session is invalid due to: " + err.message + " and failed to clean up invalid session: " + cleanUpError_1.message));
11357 return [2
11358 /*return*/
11359 ];
11360
11361 case 4:
11362 rej(err);
11363 return [2
11364 /*return*/
11365 ];
11366
11367 case 5:
11368 mfaType = that._getMfaTypeFromUserData(data);
11369
11370 if (!mfaType) {
11371 rej('invalid MFA Type');
11372 return [2
11373 /*return*/
11374 ];
11375 } else {
11376 res(mfaType);
11377 return [2
11378 /*return*/
11379 ];
11380 }
11381
11382 return [2
11383 /*return*/
11384 ];
11385 }
11386 });
11387 });
11388 }, {
11389 bypassCache: bypassCache,
11390 clientMetadata: clientMetadata
11391 });
11392 });
11393 };
11394
11395 AuthClass.prototype._getMfaTypeFromUserData = function (data) {
11396 var ret = null;
11397 var preferredMFA = data.PreferredMfaSetting; // if the user has used Auth.setPreferredMFA() to setup the mfa type
11398 // then the "PreferredMfaSetting" would exist in the response
11399
11400 if (preferredMFA) {
11401 ret = preferredMFA;
11402 } else {
11403 // if mfaList exists but empty, then its noMFA
11404 var mfaList = data.UserMFASettingList;
11405
11406 if (!mfaList) {
11407 // if SMS was enabled by using Auth.enableSMS(),
11408 // the response would contain MFAOptions
11409 // as for now Cognito only supports for SMS, so we will say it is 'SMS_MFA'
11410 // if it does not exist, then it should be NOMFA
11411 var MFAOptions = data.MFAOptions;
11412
11413 if (MFAOptions) {
11414 ret = 'SMS_MFA';
11415 } else {
11416 ret = 'NOMFA';
11417 }
11418 } else if (mfaList.length === 0) {
11419 ret = 'NOMFA';
11420 } else {
11421 logger.debug('invalid case for getPreferredMFA', data);
11422 }
11423 }
11424
11425 return ret;
11426 };
11427
11428 AuthClass.prototype._getUserData = function (user, params) {
11429 var _this = this;
11430
11431 return new Promise(function (res, rej) {
11432 user.getUserData(function (err, data) {
11433 return __awaiter(_this, void 0, void 0, function () {
11434 var cleanUpError_2;
11435 return __generator(this, function (_a) {
11436 switch (_a.label) {
11437 case 0:
11438 if (!err) return [3
11439 /*break*/
11440 , 5];
11441 logger.debug('getting user data failed', err);
11442 if (!this.isSessionInvalid(err)) return [3
11443 /*break*/
11444 , 4];
11445 _a.label = 1;
11446
11447 case 1:
11448 _a.trys.push([1, 3,, 4]);
11449
11450 return [4
11451 /*yield*/
11452 , this.cleanUpInvalidSession(user)];
11453
11454 case 2:
11455 _a.sent();
11456
11457 return [3
11458 /*break*/
11459 , 4];
11460
11461 case 3:
11462 cleanUpError_2 = _a.sent();
11463 rej(new Error("Session is invalid due to: " + err.message + " and failed to clean up invalid session: " + cleanUpError_2.message));
11464 return [2
11465 /*return*/
11466 ];
11467
11468 case 4:
11469 rej(err);
11470 return [2
11471 /*return*/
11472 ];
11473
11474 case 5:
11475 res(data);
11476 _a.label = 6;
11477
11478 case 6:
11479 return [2
11480 /*return*/
11481 ];
11482 }
11483 });
11484 });
11485 }, params);
11486 });
11487 };
11488 /**
11489 * set preferred MFA method
11490 * @param {CognitoUser} user - the current Cognito user
11491 * @param {string} mfaMethod - preferred mfa method
11492 * @return - A promise resolve if success
11493 */
11494
11495
11496 AuthClass.prototype.setPreferredMFA = function (user, mfaMethod) {
11497 return __awaiter(this, void 0, void 0, function () {
11498 var clientMetadata, userData, smsMfaSettings, totpMfaSettings, _a, mfaList, currentMFAType, that;
11499
11500 var _this = this;
11501
11502 return __generator(this, function (_b) {
11503 switch (_b.label) {
11504 case 0:
11505 clientMetadata = this._config.clientMetadata;
11506 return [4
11507 /*yield*/
11508 , this._getUserData(user, {
11509 bypassCache: true,
11510 clientMetadata: clientMetadata
11511 })];
11512
11513 case 1:
11514 userData = _b.sent();
11515 smsMfaSettings = null;
11516 totpMfaSettings = null;
11517 _a = mfaMethod;
11518
11519 switch (_a) {
11520 case 'TOTP':
11521 return [3
11522 /*break*/
11523 , 2];
11524
11525 case 'SOFTWARE_TOKEN_MFA':
11526 return [3
11527 /*break*/
11528 , 2];
11529
11530 case 'SMS':
11531 return [3
11532 /*break*/
11533 , 3];
11534
11535 case 'SMS_MFA':
11536 return [3
11537 /*break*/
11538 , 3];
11539
11540 case 'NOMFA':
11541 return [3
11542 /*break*/
11543 , 4];
11544 }
11545
11546 return [3
11547 /*break*/
11548 , 6];
11549
11550 case 2:
11551 totpMfaSettings = {
11552 PreferredMfa: true,
11553 Enabled: true
11554 };
11555 return [3
11556 /*break*/
11557 , 7];
11558
11559 case 3:
11560 smsMfaSettings = {
11561 PreferredMfa: true,
11562 Enabled: true
11563 };
11564 return [3
11565 /*break*/
11566 , 7];
11567
11568 case 4:
11569 mfaList = userData['UserMFASettingList'];
11570 return [4
11571 /*yield*/
11572 , this._getMfaTypeFromUserData(userData)];
11573
11574 case 5:
11575 currentMFAType = _b.sent();
11576
11577 if (currentMFAType === 'NOMFA') {
11578 return [2
11579 /*return*/
11580 , Promise.resolve('No change for mfa type')];
11581 } else if (currentMFAType === 'SMS_MFA') {
11582 smsMfaSettings = {
11583 PreferredMfa: false,
11584 Enabled: false
11585 };
11586 } else if (currentMFAType === 'SOFTWARE_TOKEN_MFA') {
11587 totpMfaSettings = {
11588 PreferredMfa: false,
11589 Enabled: false
11590 };
11591 } else {
11592 return [2
11593 /*return*/
11594 , this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].InvalidMFA)];
11595 } // if there is a UserMFASettingList in the response
11596 // we need to disable every mfa type in that list
11597
11598
11599 if (mfaList && mfaList.length !== 0) {
11600 // to disable SMS or TOTP if exists in that list
11601 mfaList.forEach(function (mfaType) {
11602 if (mfaType === 'SMS_MFA') {
11603 smsMfaSettings = {
11604 PreferredMfa: false,
11605 Enabled: false
11606 };
11607 } else if (mfaType === 'SOFTWARE_TOKEN_MFA') {
11608 totpMfaSettings = {
11609 PreferredMfa: false,
11610 Enabled: false
11611 };
11612 }
11613 });
11614 }
11615
11616 return [3
11617 /*break*/
11618 , 7];
11619
11620 case 6:
11621 logger.debug('no validmfa method provided');
11622 return [2
11623 /*return*/
11624 , this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NoMFA)];
11625
11626 case 7:
11627 that = this;
11628 return [2
11629 /*return*/
11630 , new Promise(function (res, rej) {
11631 user.setUserMfaPreference(smsMfaSettings, totpMfaSettings, function (err, result) {
11632 if (err) {
11633 logger.debug('Set user mfa preference error', err);
11634 return rej(err);
11635 }
11636
11637 logger.debug('Set user mfa success', result);
11638 logger.debug('Caching the latest user data into local'); // cache the latest result into user data
11639
11640 user.getUserData(function (err, data) {
11641 return __awaiter(_this, void 0, void 0, function () {
11642 var cleanUpError_3;
11643 return __generator(this, function (_a) {
11644 switch (_a.label) {
11645 case 0:
11646 if (!err) return [3
11647 /*break*/
11648 , 5];
11649 logger.debug('getting user data failed', err);
11650 if (!this.isSessionInvalid(err)) return [3
11651 /*break*/
11652 , 4];
11653 _a.label = 1;
11654
11655 case 1:
11656 _a.trys.push([1, 3,, 4]);
11657
11658 return [4
11659 /*yield*/
11660 , this.cleanUpInvalidSession(user)];
11661
11662 case 2:
11663 _a.sent();
11664
11665 return [3
11666 /*break*/
11667 , 4];
11668
11669 case 3:
11670 cleanUpError_3 = _a.sent();
11671 rej(new Error("Session is invalid due to: " + err.message + " and failed to clean up invalid session: " + cleanUpError_3.message));
11672 return [2
11673 /*return*/
11674 ];
11675
11676 case 4:
11677 return [2
11678 /*return*/
11679 , rej(err)];
11680
11681 case 5:
11682 return [2
11683 /*return*/
11684 , res(result)];
11685 }
11686 });
11687 });
11688 }, {
11689 bypassCache: true,
11690 clientMetadata: clientMetadata
11691 });
11692 });
11693 })];
11694 }
11695 });
11696 });
11697 };
11698 /**
11699 * disable SMS
11700 * @deprecated
11701 * @param {CognitoUser} user - the current user
11702 * @return - A promise resolves is success
11703 */
11704
11705
11706 AuthClass.prototype.disableSMS = function (user) {
11707 return new Promise(function (res, rej) {
11708 user.disableMFA(function (err, data) {
11709 if (err) {
11710 logger.debug('disable mfa failed', err);
11711 rej(err);
11712 return;
11713 }
11714
11715 logger.debug('disable mfa succeed', data);
11716 res(data);
11717 return;
11718 });
11719 });
11720 };
11721 /**
11722 * enable SMS
11723 * @deprecated
11724 * @param {CognitoUser} user - the current user
11725 * @return - A promise resolves is success
11726 */
11727
11728
11729 AuthClass.prototype.enableSMS = function (user) {
11730 return new Promise(function (res, rej) {
11731 user.enableMFA(function (err, data) {
11732 if (err) {
11733 logger.debug('enable mfa failed', err);
11734 rej(err);
11735 return;
11736 }
11737
11738 logger.debug('enable mfa succeed', data);
11739 res(data);
11740 return;
11741 });
11742 });
11743 };
11744 /**
11745 * Setup TOTP
11746 * @param {CognitoUser} user - the current user
11747 * @return - A promise resolves with the secret code if success
11748 */
11749
11750
11751 AuthClass.prototype.setupTOTP = function (user) {
11752 return new Promise(function (res, rej) {
11753 user.associateSoftwareToken({
11754 onFailure: function onFailure(err) {
11755 logger.debug('associateSoftwareToken failed', err);
11756 rej(err);
11757 return;
11758 },
11759 associateSecretCode: function associateSecretCode(secretCode) {
11760 logger.debug('associateSoftwareToken sucess', secretCode);
11761 res(secretCode);
11762 return;
11763 }
11764 });
11765 });
11766 };
11767 /**
11768 * verify TOTP setup
11769 * @param {CognitoUser} user - the current user
11770 * @param {string} challengeAnswer - challenge answer
11771 * @return - A promise resolves is success
11772 */
11773
11774
11775 AuthClass.prototype.verifyTotpToken = function (user, challengeAnswer) {
11776 logger.debug('verification totp token', user, challengeAnswer);
11777 return new Promise(function (res, rej) {
11778 user.verifySoftwareToken(challengeAnswer, 'My TOTP device', {
11779 onFailure: function onFailure(err) {
11780 logger.debug('verifyTotpToken failed', err);
11781 rej(err);
11782 return;
11783 },
11784 onSuccess: function onSuccess(data) {
11785 dispatchAuthEvent('signIn', user, "A user " + user.getUsername() + " has been signed in");
11786 logger.debug('verifyTotpToken success', data);
11787 res(data);
11788 return;
11789 }
11790 });
11791 });
11792 };
11793 /**
11794 * Send MFA code to confirm sign in
11795 * @param {Object} user - The CognitoUser object
11796 * @param {String} code - The confirmation code
11797 */
11798
11799
11800 AuthClass.prototype.confirmSignIn = function (user, code, mfaType, clientMetadata) {
11801 var _this = this;
11802
11803 if (clientMetadata === void 0) {
11804 clientMetadata = this._config.clientMetadata;
11805 }
11806
11807 if (!code) {
11808 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyCode);
11809 }
11810
11811 var that = this;
11812 return new Promise(function (resolve, reject) {
11813 user.sendMFACode(code, {
11814 onSuccess: function onSuccess(session) {
11815 return __awaiter(_this, void 0, void 0, function () {
11816 var cred, e_3;
11817 return __generator(this, function (_a) {
11818 switch (_a.label) {
11819 case 0:
11820 logger.debug(session);
11821 _a.label = 1;
11822
11823 case 1:
11824 _a.trys.push([1, 4, 5, 6]);
11825
11826 return [4
11827 /*yield*/
11828 , this.Credentials.clear()];
11829
11830 case 2:
11831 _a.sent();
11832
11833 return [4
11834 /*yield*/
11835 , this.Credentials.set(session, 'session')];
11836
11837 case 3:
11838 cred = _a.sent();
11839 logger.debug('succeed to get cognito credentials', cred);
11840 return [3
11841 /*break*/
11842 , 6];
11843
11844 case 4:
11845 e_3 = _a.sent();
11846 logger.debug('cannot get cognito credentials', e_3);
11847 return [3
11848 /*break*/
11849 , 6];
11850
11851 case 5:
11852 that.user = user;
11853 dispatchAuthEvent('signIn', user, "A user " + user.getUsername() + " has been signed in");
11854 resolve(user);
11855 return [7
11856 /*endfinally*/
11857 ];
11858
11859 case 6:
11860 return [2
11861 /*return*/
11862 ];
11863 }
11864 });
11865 });
11866 },
11867 onFailure: function onFailure(err) {
11868 logger.debug('confirm signIn failure', err);
11869 reject(err);
11870 }
11871 }, mfaType, clientMetadata);
11872 });
11873 };
11874
11875 AuthClass.prototype.completeNewPassword = function (user, password, requiredAttributes, clientMetadata) {
11876 var _this = this;
11877
11878 if (requiredAttributes === void 0) {
11879 requiredAttributes = {};
11880 }
11881
11882 if (clientMetadata === void 0) {
11883 clientMetadata = this._config.clientMetadata;
11884 }
11885
11886 if (!password) {
11887 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyPassword);
11888 }
11889
11890 var that = this;
11891 return new Promise(function (resolve, reject) {
11892 user.completeNewPasswordChallenge(password, requiredAttributes, {
11893 onSuccess: function onSuccess(session) {
11894 return __awaiter(_this, void 0, void 0, function () {
11895 var cred, e_4;
11896 return __generator(this, function (_a) {
11897 switch (_a.label) {
11898 case 0:
11899 logger.debug(session);
11900 _a.label = 1;
11901
11902 case 1:
11903 _a.trys.push([1, 4, 5, 6]);
11904
11905 return [4
11906 /*yield*/
11907 , this.Credentials.clear()];
11908
11909 case 2:
11910 _a.sent();
11911
11912 return [4
11913 /*yield*/
11914 , this.Credentials.set(session, 'session')];
11915
11916 case 3:
11917 cred = _a.sent();
11918 logger.debug('succeed to get cognito credentials', cred);
11919 return [3
11920 /*break*/
11921 , 6];
11922
11923 case 4:
11924 e_4 = _a.sent();
11925 logger.debug('cannot get cognito credentials', e_4);
11926 return [3
11927 /*break*/
11928 , 6];
11929
11930 case 5:
11931 that.user = user;
11932 dispatchAuthEvent('signIn', user, "A user " + user.getUsername() + " has been signed in");
11933 resolve(user);
11934 return [7
11935 /*endfinally*/
11936 ];
11937
11938 case 6:
11939 return [2
11940 /*return*/
11941 ];
11942 }
11943 });
11944 });
11945 },
11946 onFailure: function onFailure(err) {
11947 logger.debug('completeNewPassword failure', err);
11948 dispatchAuthEvent('completeNewPassword_failure', err, _this.user + " failed to complete the new password flow");
11949 reject(err);
11950 },
11951 mfaRequired: function mfaRequired(challengeName, challengeParam) {
11952 logger.debug('signIn MFA required');
11953 user['challengeName'] = challengeName;
11954 user['challengeParam'] = challengeParam;
11955 resolve(user);
11956 },
11957 mfaSetup: function mfaSetup(challengeName, challengeParam) {
11958 logger.debug('signIn mfa setup', challengeName);
11959 user['challengeName'] = challengeName;
11960 user['challengeParam'] = challengeParam;
11961 resolve(user);
11962 },
11963 totpRequired: function totpRequired(challengeName, challengeParam) {
11964 logger.debug('signIn mfa setup', challengeName);
11965 user['challengeName'] = challengeName;
11966 user['challengeParam'] = challengeParam;
11967 resolve(user);
11968 }
11969 }, clientMetadata);
11970 });
11971 };
11972 /**
11973 * Send the answer to a custom challenge
11974 * @param {CognitoUser} user - The CognitoUser object
11975 * @param {String} challengeResponses - The confirmation code
11976 */
11977
11978
11979 AuthClass.prototype.sendCustomChallengeAnswer = function (user, challengeResponses, clientMetadata) {
11980 var _this = this;
11981
11982 if (clientMetadata === void 0) {
11983 clientMetadata = this._config.clientMetadata;
11984 }
11985
11986 if (!this.userPool) {
11987 return this.rejectNoUserPool();
11988 }
11989
11990 if (!challengeResponses) {
11991 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyChallengeResponse);
11992 }
11993
11994 var that = this;
11995 return new Promise(function (resolve, reject) {
11996 user.sendCustomChallengeAnswer(challengeResponses, _this.authCallbacks(user, resolve, reject), clientMetadata);
11997 });
11998 };
11999 /**
12000 * Delete an authenticated users' attributes
12001 * @param {CognitoUser} - The currently logged in user object
12002 * @return {Promise}
12003 **/
12004
12005
12006 AuthClass.prototype.deleteUserAttributes = function (user, attributeNames) {
12007 var that = this;
12008 return new Promise(function (resolve, reject) {
12009 that.userSession(user).then(function (session) {
12010 user.deleteAttributes(attributeNames, function (err, result) {
12011 if (err) {
12012 return reject(err);
12013 } else {
12014 return resolve(result);
12015 }
12016 });
12017 });
12018 });
12019 };
12020 /**
12021 * Delete the current authenticated user
12022 * @return {Promise}
12023 **/
12024 // TODO: Check return type void
12025
12026
12027 AuthClass.prototype.deleteUser = function () {
12028 return __awaiter(this, void 0, void 0, function () {
12029 var e_5, isSignedInHostedUI;
12030
12031 var _this = this;
12032
12033 return __generator(this, function (_a) {
12034 switch (_a.label) {
12035 case 0:
12036 _a.trys.push([0, 2,, 3]);
12037
12038 return [4
12039 /*yield*/
12040 , this._storageSync];
12041
12042 case 1:
12043 _a.sent();
12044
12045 return [3
12046 /*break*/
12047 , 3];
12048
12049 case 2:
12050 e_5 = _a.sent();
12051 logger.debug('Failed to sync cache info into memory', e_5);
12052 throw new Error(e_5);
12053
12054 case 3:
12055 isSignedInHostedUI = this._oAuthHandler && this._storage.getItem('amplify-signin-with-hostedUI') === 'true';
12056 return [2
12057 /*return*/
12058 , new Promise(function (res, rej) {
12059 return __awaiter(_this, void 0, void 0, function () {
12060 var user_1;
12061
12062 var _this = this;
12063
12064 return __generator(this, function (_a) {
12065 if (this.userPool) {
12066 user_1 = this.userPool.getCurrentUser();
12067
12068 if (!user_1) {
12069 logger.debug('Failed to get user from user pool');
12070 return [2
12071 /*return*/
12072 , rej(new Error('No current user.'))];
12073 } else {
12074 user_1.getSession(function (err, session) {
12075 return __awaiter(_this, void 0, void 0, function () {
12076 var cleanUpError_4;
12077
12078 var _this = this;
12079
12080 return __generator(this, function (_a) {
12081 switch (_a.label) {
12082 case 0:
12083 if (!err) return [3
12084 /*break*/
12085 , 5];
12086 logger.debug('Failed to get the user session', err);
12087 if (!this.isSessionInvalid(err)) return [3
12088 /*break*/
12089 , 4];
12090 _a.label = 1;
12091
12092 case 1:
12093 _a.trys.push([1, 3,, 4]);
12094
12095 return [4
12096 /*yield*/
12097 , this.cleanUpInvalidSession(user_1)];
12098
12099 case 2:
12100 _a.sent();
12101
12102 return [3
12103 /*break*/
12104 , 4];
12105
12106 case 3:
12107 cleanUpError_4 = _a.sent();
12108 rej(new Error("Session is invalid due to: " + err.message + " and failed to clean up invalid session: " + cleanUpError_4.message));
12109 return [2
12110 /*return*/
12111 ];
12112
12113 case 4:
12114 return [2
12115 /*return*/
12116 , rej(err)];
12117
12118 case 5:
12119 user_1.deleteUser(function (err, result) {
12120 if (err) {
12121 rej(err);
12122 } else {
12123 dispatchAuthEvent('userDeleted', result, 'The authenticated user has been deleted.');
12124 user_1.signOut();
12125 _this.user = null;
12126
12127 try {
12128 _this.cleanCachedItems(); // clean aws credentials
12129
12130 } catch (e) {
12131 // TODO: change to rejects in refactor
12132 logger.debug('failed to clear cached items');
12133 }
12134
12135 if (isSignedInHostedUI) {
12136 _this.oAuthSignOutRedirect(res, rej);
12137 } else {
12138 dispatchAuthEvent('signOut', _this.user, "A user has been signed out");
12139 res(result);
12140 }
12141 }
12142 });
12143 _a.label = 6;
12144
12145 case 6:
12146 return [2
12147 /*return*/
12148 ];
12149 }
12150 });
12151 });
12152 });
12153 }
12154 } else {
12155 logger.debug('no Congito User pool');
12156 rej(new Error('Cognito User pool does not exist'));
12157 }
12158
12159 return [2
12160 /*return*/
12161 ];
12162 });
12163 });
12164 })];
12165 }
12166 });
12167 });
12168 };
12169 /**
12170 * Update an authenticated users' attributes
12171 * @param {CognitoUser} - The currently logged in user object
12172 * @return {Promise}
12173 **/
12174
12175
12176 AuthClass.prototype.updateUserAttributes = function (user, attributes, clientMetadata) {
12177 if (clientMetadata === void 0) {
12178 clientMetadata = this._config.clientMetadata;
12179 }
12180
12181 var attributeList = [];
12182 var that = this;
12183 return new Promise(function (resolve, reject) {
12184 that.userSession(user).then(function (session) {
12185 for (var key in attributes) {
12186 if (key !== 'sub' && key.indexOf('_verified') < 0) {
12187 var attr = {
12188 Name: key,
12189 Value: attributes[key]
12190 };
12191 attributeList.push(attr);
12192 }
12193 }
12194
12195 user.updateAttributes(attributeList, function (err, result) {
12196 if (err) {
12197 return reject(err);
12198 } else {
12199 return resolve(result);
12200 }
12201 }, clientMetadata);
12202 });
12203 });
12204 };
12205 /**
12206 * Return user attributes
12207 * @param {Object} user - The CognitoUser object
12208 * @return - A promise resolves to user attributes if success
12209 */
12210
12211
12212 AuthClass.prototype.userAttributes = function (user) {
12213 var _this = this;
12214
12215 return new Promise(function (resolve, reject) {
12216 _this.userSession(user).then(function (session) {
12217 user.getUserAttributes(function (err, attributes) {
12218 if (err) {
12219 reject(err);
12220 } else {
12221 resolve(attributes);
12222 }
12223 });
12224 });
12225 });
12226 };
12227
12228 AuthClass.prototype.verifiedContact = function (user) {
12229 var that = this;
12230 return this.userAttributes(user).then(function (attributes) {
12231 var attrs = that.attributesToObject(attributes);
12232 var unverified = {};
12233 var verified = {};
12234
12235 if (attrs['email']) {
12236 if (attrs['email_verified']) {
12237 verified['email'] = attrs['email'];
12238 } else {
12239 unverified['email'] = attrs['email'];
12240 }
12241 }
12242
12243 if (attrs['phone_number']) {
12244 if (attrs['phone_number_verified']) {
12245 verified['phone_number'] = attrs['phone_number'];
12246 } else {
12247 unverified['phone_number'] = attrs['phone_number'];
12248 }
12249 }
12250
12251 return {
12252 verified: verified,
12253 unverified: unverified
12254 };
12255 });
12256 };
12257
12258 AuthClass.prototype.isErrorWithMessage = function (err) {
12259 return _typeof(err) === 'object' && Object.prototype.hasOwnProperty.call(err, 'message');
12260 }; // Session revoked by another app
12261
12262
12263 AuthClass.prototype.isTokenRevokedError = function (err) {
12264 return this.isErrorWithMessage(err) && err.message === 'Access Token has been revoked';
12265 };
12266
12267 AuthClass.prototype.isRefreshTokenRevokedError = function (err) {
12268 return this.isErrorWithMessage(err) && err.message === 'Refresh Token has been revoked';
12269 };
12270
12271 AuthClass.prototype.isUserDisabledError = function (err) {
12272 return this.isErrorWithMessage(err) && err.message === 'User is disabled.';
12273 };
12274
12275 AuthClass.prototype.isUserDoesNotExistError = function (err) {
12276 return this.isErrorWithMessage(err) && err.message === 'User does not exist.';
12277 };
12278
12279 AuthClass.prototype.isRefreshTokenExpiredError = function (err) {
12280 return this.isErrorWithMessage(err) && err.message === 'Refresh Token has expired';
12281 };
12282
12283 AuthClass.prototype.isSignedInHostedUI = function () {
12284 return this._oAuthHandler && this._storage.getItem('amplify-signin-with-hostedUI') === 'true';
12285 };
12286
12287 AuthClass.prototype.isSessionInvalid = function (err) {
12288 return this.isUserDisabledError(err) || this.isUserDoesNotExistError(err) || this.isTokenRevokedError(err) || this.isRefreshTokenRevokedError(err) || this.isRefreshTokenExpiredError(err);
12289 };
12290
12291 AuthClass.prototype.cleanUpInvalidSession = function (user) {
12292 return __awaiter(this, void 0, void 0, function () {
12293 var e_6;
12294
12295 var _this = this;
12296
12297 return __generator(this, function (_a) {
12298 switch (_a.label) {
12299 case 0:
12300 user.signOut();
12301 this.user = null;
12302 _a.label = 1;
12303
12304 case 1:
12305 _a.trys.push([1, 3,, 4]);
12306
12307 return [4
12308 /*yield*/
12309 , this.cleanCachedItems()];
12310
12311 case 2:
12312 _a.sent(); // clean aws credentials
12313
12314
12315 return [3
12316 /*break*/
12317 , 4];
12318
12319 case 3:
12320 e_6 = _a.sent();
12321 logger.debug('failed to clear cached items');
12322 return [3
12323 /*break*/
12324 , 4];
12325
12326 case 4:
12327 if (this.isSignedInHostedUI()) {
12328 return [2
12329 /*return*/
12330 , new Promise(function (res, rej) {
12331 _this.oAuthSignOutRedirect(res, rej);
12332 })];
12333 } else {
12334 dispatchAuthEvent('signOut', this.user, "A user has been signed out");
12335 }
12336
12337 return [2
12338 /*return*/
12339 ];
12340 }
12341 });
12342 });
12343 };
12344 /**
12345 * Get current authenticated user
12346 * @return - A promise resolves to current authenticated CognitoUser if success
12347 */
12348
12349
12350 AuthClass.prototype.currentUserPoolUser = function (params) {
12351 var _this = this;
12352
12353 if (!this.userPool) {
12354 return this.rejectNoUserPool();
12355 }
12356
12357 return new Promise(function (res, rej) {
12358 _this._storageSync.then(function () {
12359 return __awaiter(_this, void 0, void 0, function () {
12360 var user, clientMetadata;
12361
12362 var _this = this;
12363
12364 return __generator(this, function (_a) {
12365 switch (_a.label) {
12366 case 0:
12367 if (!this.isOAuthInProgress()) return [3
12368 /*break*/
12369 , 2];
12370 logger.debug('OAuth signIn in progress, waiting for resolution...');
12371 return [4
12372 /*yield*/
12373 , new Promise(function (res) {
12374 var timeoutId = setTimeout(function () {
12375 logger.debug('OAuth signIn in progress timeout');
12376 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].remove('auth', hostedUISignCallback);
12377 res();
12378 }, OAUTH_FLOW_MS_TIMEOUT);
12379 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].listen('auth', hostedUISignCallback);
12380
12381 function hostedUISignCallback(_a) {
12382 var payload = _a.payload;
12383 var event = payload.event;
12384
12385 if (event === 'cognitoHostedUI' || event === 'cognitoHostedUI_failure') {
12386 logger.debug("OAuth signIn resolved: " + event);
12387 clearTimeout(timeoutId);
12388 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Hub"].remove('auth', hostedUISignCallback);
12389 res();
12390 }
12391 }
12392 })];
12393
12394 case 1:
12395 _a.sent();
12396
12397 _a.label = 2;
12398
12399 case 2:
12400 user = this.userPool.getCurrentUser();
12401
12402 if (!user) {
12403 logger.debug('Failed to get user from user pool');
12404 rej('No current user');
12405 return [2
12406 /*return*/
12407 ];
12408 }
12409
12410 clientMetadata = this._config.clientMetadata; // refresh the session if the session expired.
12411
12412 user.getSession(function (err, session) {
12413 return __awaiter(_this, void 0, void 0, function () {
12414 var cleanUpError_5, bypassCache, clientMetadata, _a, scope;
12415
12416 var _this = this;
12417
12418 return __generator(this, function (_b) {
12419 switch (_b.label) {
12420 case 0:
12421 if (!err) return [3
12422 /*break*/
12423 , 5];
12424 logger.debug('Failed to get the user session', err);
12425 if (!this.isSessionInvalid(err)) return [3
12426 /*break*/
12427 , 4];
12428 _b.label = 1;
12429
12430 case 1:
12431 _b.trys.push([1, 3,, 4]);
12432
12433 return [4
12434 /*yield*/
12435 , this.cleanUpInvalidSession(user)];
12436
12437 case 2:
12438 _b.sent();
12439
12440 return [3
12441 /*break*/
12442 , 4];
12443
12444 case 3:
12445 cleanUpError_5 = _b.sent();
12446 rej(new Error("Session is invalid due to: " + err.message + " and failed to clean up invalid session: " + cleanUpError_5.message));
12447 return [2
12448 /*return*/
12449 ];
12450
12451 case 4:
12452 rej(err);
12453 return [2
12454 /*return*/
12455 ];
12456
12457 case 5:
12458 bypassCache = params ? params.bypassCache : false;
12459 if (!bypassCache) return [3
12460 /*break*/
12461 , 7];
12462 return [4
12463 /*yield*/
12464 , this.Credentials.clear()];
12465
12466 case 6:
12467 _b.sent();
12468
12469 _b.label = 7;
12470
12471 case 7:
12472 clientMetadata = this._config.clientMetadata;
12473 _a = session.getAccessToken().decodePayload().scope, scope = _a === void 0 ? '' : _a;
12474
12475 if (scope.split(' ').includes(USER_ADMIN_SCOPE)) {
12476 user.getUserData(function (err, data) {
12477 return __awaiter(_this, void 0, void 0, function () {
12478 var cleanUpError_6, preferredMFA, attributeList, i, attribute, userAttribute, attributes;
12479 return __generator(this, function (_a) {
12480 switch (_a.label) {
12481 case 0:
12482 if (!err) return [3
12483 /*break*/
12484 , 7];
12485 logger.debug('getting user data failed', err);
12486 if (!this.isSessionInvalid(err)) return [3
12487 /*break*/
12488 , 5];
12489 _a.label = 1;
12490
12491 case 1:
12492 _a.trys.push([1, 3,, 4]);
12493
12494 return [4
12495 /*yield*/
12496 , this.cleanUpInvalidSession(user)];
12497
12498 case 2:
12499 _a.sent();
12500
12501 return [3
12502 /*break*/
12503 , 4];
12504
12505 case 3:
12506 cleanUpError_6 = _a.sent();
12507 rej(new Error("Session is invalid due to: " + err.message + " and failed to clean up invalid session: " + cleanUpError_6.message));
12508 return [2
12509 /*return*/
12510 ];
12511
12512 case 4:
12513 rej(err);
12514 return [3
12515 /*break*/
12516 , 6];
12517
12518 case 5:
12519 res(user);
12520 _a.label = 6;
12521
12522 case 6:
12523 return [2
12524 /*return*/
12525 ];
12526
12527 case 7:
12528 preferredMFA = data.PreferredMfaSetting || 'NOMFA';
12529 attributeList = [];
12530
12531 for (i = 0; i < data.UserAttributes.length; i++) {
12532 attribute = {
12533 Name: data.UserAttributes[i].Name,
12534 Value: data.UserAttributes[i].Value
12535 };
12536 userAttribute = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserAttribute"](attribute);
12537 attributeList.push(userAttribute);
12538 }
12539
12540 attributes = this.attributesToObject(attributeList);
12541 Object.assign(user, {
12542 attributes: attributes,
12543 preferredMFA: preferredMFA
12544 });
12545 return [2
12546 /*return*/
12547 , res(user)];
12548 }
12549 });
12550 });
12551 }, {
12552 bypassCache: bypassCache,
12553 clientMetadata: clientMetadata
12554 });
12555 } else {
12556 logger.debug("Unable to get the user data because the " + USER_ADMIN_SCOPE + " " + "is not in the scopes of the access token");
12557 return [2
12558 /*return*/
12559 , res(user)];
12560 }
12561
12562 return [2
12563 /*return*/
12564 ];
12565 }
12566 });
12567 });
12568 }, {
12569 clientMetadata: clientMetadata
12570 });
12571 return [2
12572 /*return*/
12573 ];
12574 }
12575 });
12576 });
12577 })["catch"](function (e) {
12578 logger.debug('Failed to sync cache info into memory', e);
12579 return rej(e);
12580 });
12581 });
12582 };
12583
12584 AuthClass.prototype.isOAuthInProgress = function () {
12585 return this.oAuthFlowInProgress;
12586 };
12587 /**
12588 * Get current authenticated user
12589 * @param {CurrentUserOpts} - options for getting the current user
12590 * @return - A promise resolves to current authenticated CognitoUser if success
12591 */
12592
12593
12594 AuthClass.prototype.currentAuthenticatedUser = function (params) {
12595 return __awaiter(this, void 0, void 0, function () {
12596 var federatedUser, e_7, federatedInfo, user, e_8;
12597 return __generator(this, function (_a) {
12598 switch (_a.label) {
12599 case 0:
12600 logger.debug('getting current authenticated user');
12601 federatedUser = null;
12602 _a.label = 1;
12603
12604 case 1:
12605 _a.trys.push([1, 3,, 4]);
12606
12607 return [4
12608 /*yield*/
12609 , this._storageSync];
12610
12611 case 2:
12612 _a.sent();
12613
12614 return [3
12615 /*break*/
12616 , 4];
12617
12618 case 3:
12619 e_7 = _a.sent();
12620 logger.debug('Failed to sync cache info into memory', e_7);
12621 throw e_7;
12622
12623 case 4:
12624 try {
12625 federatedInfo = JSON.parse(this._storage.getItem('aws-amplify-federatedInfo'));
12626
12627 if (federatedInfo) {
12628 federatedUser = __assign(__assign({}, federatedInfo.user), {
12629 token: federatedInfo.token
12630 });
12631 }
12632 } catch (e) {
12633 logger.debug('cannot load federated user from auth storage');
12634 }
12635
12636 if (!federatedUser) return [3
12637 /*break*/
12638 , 5];
12639 this.user = federatedUser;
12640 logger.debug('get current authenticated federated user', this.user);
12641 return [2
12642 /*return*/
12643 , this.user];
12644
12645 case 5:
12646 logger.debug('get current authenticated userpool user');
12647 user = null;
12648 _a.label = 6;
12649
12650 case 6:
12651 _a.trys.push([6, 8,, 9]);
12652
12653 return [4
12654 /*yield*/
12655 , this.currentUserPoolUser(params)];
12656
12657 case 7:
12658 user = _a.sent();
12659 return [3
12660 /*break*/
12661 , 9];
12662
12663 case 8:
12664 e_8 = _a.sent();
12665
12666 if (e_8 === 'No userPool') {
12667 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');
12668 }
12669
12670 logger.debug('The user is not authenticated by the error', e_8);
12671 return [2
12672 /*return*/
12673 , Promise.reject('The user is not authenticated')];
12674
12675 case 9:
12676 this.user = user;
12677 return [2
12678 /*return*/
12679 , this.user];
12680 }
12681 });
12682 });
12683 };
12684 /**
12685 * Get current user's session
12686 * @return - A promise resolves to session object if success
12687 */
12688
12689
12690 AuthClass.prototype.currentSession = function () {
12691 var that = this;
12692 logger.debug('Getting current session'); // Purposely not calling the reject method here because we don't need a console error
12693
12694 if (!this.userPool) {
12695 return this.rejectNoUserPool();
12696 }
12697
12698 return new Promise(function (res, rej) {
12699 that.currentUserPoolUser().then(function (user) {
12700 that.userSession(user).then(function (session) {
12701 res(session);
12702 return;
12703 })["catch"](function (e) {
12704 logger.debug('Failed to get the current session', e);
12705 rej(e);
12706 return;
12707 });
12708 })["catch"](function (e) {
12709 logger.debug('Failed to get the current user', e);
12710 rej(e);
12711 return;
12712 });
12713 });
12714 };
12715 /**
12716 * Get the corresponding user session
12717 * @param {Object} user - The CognitoUser object
12718 * @return - A promise resolves to the session
12719 */
12720
12721
12722 AuthClass.prototype.userSession = function (user) {
12723 var _this = this;
12724
12725 if (!user) {
12726 logger.debug('the user is null');
12727 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NoUserSession);
12728 }
12729
12730 var clientMetadata = this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
12731
12732 return new Promise(function (res, rej) {
12733 logger.debug('Getting the session from this user:', user);
12734 user.getSession(function (err, session) {
12735 return __awaiter(_this, void 0, void 0, function () {
12736 var cleanUpError_7;
12737 return __generator(this, function (_a) {
12738 switch (_a.label) {
12739 case 0:
12740 if (!err) return [3
12741 /*break*/
12742 , 5];
12743 logger.debug('Failed to get the session from user', user);
12744 if (!this.isSessionInvalid(err)) return [3
12745 /*break*/
12746 , 4];
12747 _a.label = 1;
12748
12749 case 1:
12750 _a.trys.push([1, 3,, 4]);
12751
12752 return [4
12753 /*yield*/
12754 , this.cleanUpInvalidSession(user)];
12755
12756 case 2:
12757 _a.sent();
12758
12759 return [3
12760 /*break*/
12761 , 4];
12762
12763 case 3:
12764 cleanUpError_7 = _a.sent();
12765 rej(new Error("Session is invalid due to: " + err.message + " and failed to clean up invalid session: " + cleanUpError_7.message));
12766 return [2
12767 /*return*/
12768 ];
12769
12770 case 4:
12771 rej(err);
12772 return [2
12773 /*return*/
12774 ];
12775
12776 case 5:
12777 logger.debug('Succeed to get the user session', session);
12778 res(session);
12779 return [2
12780 /*return*/
12781 ];
12782 }
12783 });
12784 });
12785 }, {
12786 clientMetadata: clientMetadata
12787 });
12788 });
12789 };
12790 /**
12791 * Get authenticated credentials of current user.
12792 * @return - A promise resolves to be current user's credentials
12793 */
12794
12795
12796 AuthClass.prototype.currentUserCredentials = function () {
12797 return __awaiter(this, void 0, void 0, function () {
12798 var e_9, federatedInfo;
12799
12800 var _this = this;
12801
12802 return __generator(this, function (_a) {
12803 switch (_a.label) {
12804 case 0:
12805 logger.debug('Getting current user credentials');
12806 _a.label = 1;
12807
12808 case 1:
12809 _a.trys.push([1, 3,, 4]);
12810
12811 return [4
12812 /*yield*/
12813 , this._storageSync];
12814
12815 case 2:
12816 _a.sent();
12817
12818 return [3
12819 /*break*/
12820 , 4];
12821
12822 case 3:
12823 e_9 = _a.sent();
12824 logger.debug('Failed to sync cache info into memory', e_9);
12825 throw e_9;
12826
12827 case 4:
12828 federatedInfo = null;
12829
12830 try {
12831 federatedInfo = JSON.parse(this._storage.getItem('aws-amplify-federatedInfo'));
12832 } catch (e) {
12833 logger.debug('failed to get or parse item aws-amplify-federatedInfo', e);
12834 }
12835
12836 if (federatedInfo) {
12837 // refresh the jwt token here if necessary
12838 return [2
12839 /*return*/
12840 , this.Credentials.refreshFederatedToken(federatedInfo)];
12841 } else {
12842 return [2
12843 /*return*/
12844 , this.currentSession().then(function (session) {
12845 logger.debug('getting session success', session);
12846 return _this.Credentials.set(session, 'session');
12847 })["catch"](function () {
12848 logger.debug('getting guest credentials');
12849 return _this.Credentials.set(null, 'guest');
12850 })];
12851 }
12852
12853 return [2
12854 /*return*/
12855 ];
12856 }
12857 });
12858 });
12859 };
12860
12861 AuthClass.prototype.currentCredentials = function () {
12862 logger.debug('getting current credentials');
12863 return this.Credentials.get();
12864 };
12865 /**
12866 * Initiate an attribute confirmation request
12867 * @param {Object} user - The CognitoUser
12868 * @param {Object} attr - The attributes to be verified
12869 * @return - A promise resolves to callback data if success
12870 */
12871
12872
12873 AuthClass.prototype.verifyUserAttribute = function (user, attr, clientMetadata) {
12874 if (clientMetadata === void 0) {
12875 clientMetadata = this._config.clientMetadata;
12876 }
12877
12878 return new Promise(function (resolve, reject) {
12879 user.getAttributeVerificationCode(attr, {
12880 onSuccess: function onSuccess(success) {
12881 return resolve(success);
12882 },
12883 onFailure: function onFailure(err) {
12884 return reject(err);
12885 }
12886 }, clientMetadata);
12887 });
12888 };
12889 /**
12890 * Confirm an attribute using a confirmation code
12891 * @param {Object} user - The CognitoUser
12892 * @param {Object} attr - The attribute to be verified
12893 * @param {String} code - The confirmation code
12894 * @return - A promise resolves to callback data if success
12895 */
12896
12897
12898 AuthClass.prototype.verifyUserAttributeSubmit = function (user, attr, code) {
12899 if (!code) {
12900 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyCode);
12901 }
12902
12903 return new Promise(function (resolve, reject) {
12904 user.verifyAttribute(attr, code, {
12905 onSuccess: function onSuccess(data) {
12906 resolve(data);
12907 return;
12908 },
12909 onFailure: function onFailure(err) {
12910 reject(err);
12911 return;
12912 }
12913 });
12914 });
12915 };
12916
12917 AuthClass.prototype.verifyCurrentUserAttribute = function (attr) {
12918 var that = this;
12919 return that.currentUserPoolUser().then(function (user) {
12920 return that.verifyUserAttribute(user, attr);
12921 });
12922 };
12923 /**
12924 * Confirm current user's attribute using a confirmation code
12925 * @param {Object} attr - The attribute to be verified
12926 * @param {String} code - The confirmation code
12927 * @return - A promise resolves to callback data if success
12928 */
12929
12930
12931 AuthClass.prototype.verifyCurrentUserAttributeSubmit = function (attr, code) {
12932 var that = this;
12933 return that.currentUserPoolUser().then(function (user) {
12934 return that.verifyUserAttributeSubmit(user, attr, code);
12935 });
12936 };
12937
12938 AuthClass.prototype.cognitoIdentitySignOut = function (opts, user) {
12939 return __awaiter(this, void 0, void 0, function () {
12940 var e_10, isSignedInHostedUI;
12941
12942 var _this = this;
12943
12944 return __generator(this, function (_a) {
12945 switch (_a.label) {
12946 case 0:
12947 _a.trys.push([0, 2,, 3]);
12948
12949 return [4
12950 /*yield*/
12951 , this._storageSync];
12952
12953 case 1:
12954 _a.sent();
12955
12956 return [3
12957 /*break*/
12958 , 3];
12959
12960 case 2:
12961 e_10 = _a.sent();
12962 logger.debug('Failed to sync cache info into memory', e_10);
12963 throw e_10;
12964
12965 case 3:
12966 isSignedInHostedUI = this._oAuthHandler && this._storage.getItem('amplify-signin-with-hostedUI') === 'true';
12967 return [2
12968 /*return*/
12969 , new Promise(function (res, rej) {
12970 if (opts && opts.global) {
12971 logger.debug('user global sign out', user); // in order to use global signout
12972 // we must validate the user as an authenticated user by using getSession
12973
12974 var clientMetadata = _this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
12975
12976 user.getSession(function (err, result) {
12977 return __awaiter(_this, void 0, void 0, function () {
12978 var cleanUpError_8;
12979
12980 var _this = this;
12981
12982 return __generator(this, function (_a) {
12983 switch (_a.label) {
12984 case 0:
12985 if (!err) return [3
12986 /*break*/
12987 , 5];
12988 logger.debug('failed to get the user session', err);
12989 if (!this.isSessionInvalid(err)) return [3
12990 /*break*/
12991 , 4];
12992 _a.label = 1;
12993
12994 case 1:
12995 _a.trys.push([1, 3,, 4]);
12996
12997 return [4
12998 /*yield*/
12999 , this.cleanUpInvalidSession(user)];
13000
13001 case 2:
13002 _a.sent();
13003
13004 return [3
13005 /*break*/
13006 , 4];
13007
13008 case 3:
13009 cleanUpError_8 = _a.sent();
13010 rej(new Error("Session is invalid due to: " + err.message + " and failed to clean up invalid session: " + cleanUpError_8.message));
13011 return [2
13012 /*return*/
13013 ];
13014
13015 case 4:
13016 return [2
13017 /*return*/
13018 , rej(err)];
13019
13020 case 5:
13021 user.globalSignOut({
13022 onSuccess: function onSuccess(data) {
13023 logger.debug('global sign out success');
13024
13025 if (isSignedInHostedUI) {
13026 _this.oAuthSignOutRedirect(res, rej);
13027 } else {
13028 return res();
13029 }
13030 },
13031 onFailure: function onFailure(err) {
13032 logger.debug('global sign out failed', err);
13033 return rej(err);
13034 }
13035 });
13036 return [2
13037 /*return*/
13038 ];
13039 }
13040 });
13041 });
13042 }, {
13043 clientMetadata: clientMetadata
13044 });
13045 } else {
13046 logger.debug('user sign out', user);
13047 user.signOut(function () {
13048 if (isSignedInHostedUI) {
13049 _this.oAuthSignOutRedirect(res, rej);
13050 } else {
13051 return res();
13052 }
13053 });
13054 }
13055 })];
13056 }
13057 });
13058 });
13059 };
13060
13061 AuthClass.prototype.oAuthSignOutRedirect = function (resolve, reject) {
13062 var isBrowser = _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["JS"].browserOrNode().isBrowser;
13063
13064 if (isBrowser) {
13065 this.oAuthSignOutRedirectOrReject(reject);
13066 } else {
13067 this.oAuthSignOutAndResolve(resolve);
13068 }
13069 };
13070
13071 AuthClass.prototype.oAuthSignOutAndResolve = function (resolve) {
13072 this._oAuthHandler.signOut();
13073
13074 resolve();
13075 };
13076
13077 AuthClass.prototype.oAuthSignOutRedirectOrReject = function (reject) {
13078 this._oAuthHandler.signOut(); // this method redirects url
13079 // App should be redirected to another url otherwise it will reject
13080
13081
13082 setTimeout(function () {
13083 return reject(Error('Signout timeout fail'));
13084 }, 3000);
13085 };
13086 /**
13087 * Sign out method
13088 * @
13089 * @return - A promise resolved if success
13090 */
13091
13092
13093 AuthClass.prototype.signOut = function (opts) {
13094 return __awaiter(this, void 0, void 0, function () {
13095 var e_11, user;
13096 return __generator(this, function (_a) {
13097 switch (_a.label) {
13098 case 0:
13099 _a.trys.push([0, 2,, 3]);
13100
13101 return [4
13102 /*yield*/
13103 , this.cleanCachedItems()];
13104
13105 case 1:
13106 _a.sent();
13107
13108 return [3
13109 /*break*/
13110 , 3];
13111
13112 case 2:
13113 e_11 = _a.sent();
13114 logger.debug('failed to clear cached items');
13115 return [3
13116 /*break*/
13117 , 3];
13118
13119 case 3:
13120 if (!this.userPool) return [3
13121 /*break*/
13122 , 7];
13123 user = this.userPool.getCurrentUser();
13124 if (!user) return [3
13125 /*break*/
13126 , 5];
13127 return [4
13128 /*yield*/
13129 , this.cognitoIdentitySignOut(opts, user)];
13130
13131 case 4:
13132 _a.sent();
13133
13134 return [3
13135 /*break*/
13136 , 6];
13137
13138 case 5:
13139 logger.debug('no current Cognito user');
13140 _a.label = 6;
13141
13142 case 6:
13143 return [3
13144 /*break*/
13145 , 8];
13146
13147 case 7:
13148 logger.debug('no Cognito User pool');
13149 _a.label = 8;
13150
13151 case 8:
13152 /**
13153 * Note for future refactor - no reliable way to get username with
13154 * Cognito User Pools vs Identity when federating with Social Providers
13155 * This is why we need a well structured session object that can be inspected
13156 * and information passed back in the message below for Hub dispatch
13157 */
13158 dispatchAuthEvent('signOut', this.user, "A user has been signed out");
13159 this.user = null;
13160 return [2
13161 /*return*/
13162 ];
13163 }
13164 });
13165 });
13166 };
13167
13168 AuthClass.prototype.cleanCachedItems = function () {
13169 return __awaiter(this, void 0, void 0, function () {
13170 return __generator(this, function (_a) {
13171 switch (_a.label) {
13172 case 0:
13173 // clear cognito cached item
13174 return [4
13175 /*yield*/
13176 , this.Credentials.clear()];
13177
13178 case 1:
13179 // clear cognito cached item
13180 _a.sent();
13181
13182 return [2
13183 /*return*/
13184 ];
13185 }
13186 });
13187 });
13188 };
13189 /**
13190 * Change a password for an authenticated user
13191 * @param {Object} user - The CognitoUser object
13192 * @param {String} oldPassword - the current password
13193 * @param {String} newPassword - the requested new password
13194 * @return - A promise resolves if success
13195 */
13196
13197
13198 AuthClass.prototype.changePassword = function (user, oldPassword, newPassword, clientMetadata) {
13199 var _this = this;
13200
13201 if (clientMetadata === void 0) {
13202 clientMetadata = this._config.clientMetadata;
13203 }
13204
13205 return new Promise(function (resolve, reject) {
13206 _this.userSession(user).then(function (session) {
13207 user.changePassword(oldPassword, newPassword, function (err, data) {
13208 if (err) {
13209 logger.debug('change password failure', err);
13210 return reject(err);
13211 } else {
13212 return resolve(data);
13213 }
13214 }, clientMetadata);
13215 });
13216 });
13217 };
13218 /**
13219 * Initiate a forgot password request
13220 * @param {String} username - the username to change password
13221 * @return - A promise resolves if success
13222 */
13223
13224
13225 AuthClass.prototype.forgotPassword = function (username, clientMetadata) {
13226 if (clientMetadata === void 0) {
13227 clientMetadata = this._config.clientMetadata;
13228 }
13229
13230 if (!this.userPool) {
13231 return this.rejectNoUserPool();
13232 }
13233
13234 if (!username) {
13235 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
13236 }
13237
13238 var user = this.createCognitoUser(username);
13239 return new Promise(function (resolve, reject) {
13240 user.forgotPassword({
13241 onSuccess: function onSuccess() {
13242 resolve();
13243 return;
13244 },
13245 onFailure: function onFailure(err) {
13246 logger.debug('forgot password failure', err);
13247 dispatchAuthEvent('forgotPassword_failure', err, username + " forgotPassword failed");
13248 reject(err);
13249 return;
13250 },
13251 inputVerificationCode: function inputVerificationCode(data) {
13252 dispatchAuthEvent('forgotPassword', user, username + " has initiated forgot password flow");
13253 resolve(data);
13254 return;
13255 }
13256 }, clientMetadata);
13257 });
13258 };
13259 /**
13260 * Confirm a new password using a confirmation Code
13261 * @param {String} username - The username
13262 * @param {String} code - The confirmation code
13263 * @param {String} password - The new password
13264 * @return - A promise that resolves if success
13265 */
13266
13267
13268 AuthClass.prototype.forgotPasswordSubmit = function (username, code, password, clientMetadata) {
13269 if (clientMetadata === void 0) {
13270 clientMetadata = this._config.clientMetadata;
13271 }
13272
13273 if (!this.userPool) {
13274 return this.rejectNoUserPool();
13275 }
13276
13277 if (!username) {
13278 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyUsername);
13279 }
13280
13281 if (!code) {
13282 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyCode);
13283 }
13284
13285 if (!password) {
13286 return this.rejectAuthError(_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].EmptyPassword);
13287 }
13288
13289 var user = this.createCognitoUser(username);
13290 return new Promise(function (resolve, reject) {
13291 user.confirmPassword(code, password, {
13292 onSuccess: function onSuccess(success) {
13293 dispatchAuthEvent('forgotPasswordSubmit', user, username + " forgotPasswordSubmit successful");
13294 resolve(success);
13295 return;
13296 },
13297 onFailure: function onFailure(err) {
13298 dispatchAuthEvent('forgotPasswordSubmit_failure', err, username + " forgotPasswordSubmit failed");
13299 reject(err);
13300 return;
13301 }
13302 }, clientMetadata);
13303 });
13304 };
13305 /**
13306 * Get user information
13307 * @async
13308 * @return {Object }- current User's information
13309 */
13310
13311
13312 AuthClass.prototype.currentUserInfo = function () {
13313 return __awaiter(this, void 0, void 0, function () {
13314 var source, user, attributes, userAttrs, credentials, e_12, info, err_1, user;
13315 return __generator(this, function (_a) {
13316 switch (_a.label) {
13317 case 0:
13318 source = this.Credentials.getCredSource();
13319 if (!(!source || source === 'aws' || source === 'userPool')) return [3
13320 /*break*/
13321 , 9];
13322 return [4
13323 /*yield*/
13324 , this.currentUserPoolUser()["catch"](function (err) {
13325 return logger.error(err);
13326 })];
13327
13328 case 1:
13329 user = _a.sent();
13330
13331 if (!user) {
13332 return [2
13333 /*return*/
13334 , null];
13335 }
13336
13337 _a.label = 2;
13338
13339 case 2:
13340 _a.trys.push([2, 8,, 9]);
13341
13342 return [4
13343 /*yield*/
13344 , this.userAttributes(user)];
13345
13346 case 3:
13347 attributes = _a.sent();
13348 userAttrs = this.attributesToObject(attributes);
13349 credentials = null;
13350 _a.label = 4;
13351
13352 case 4:
13353 _a.trys.push([4, 6,, 7]);
13354
13355 return [4
13356 /*yield*/
13357 , this.currentCredentials()];
13358
13359 case 5:
13360 credentials = _a.sent();
13361 return [3
13362 /*break*/
13363 , 7];
13364
13365 case 6:
13366 e_12 = _a.sent();
13367 logger.debug('Failed to retrieve credentials while getting current user info', e_12);
13368 return [3
13369 /*break*/
13370 , 7];
13371
13372 case 7:
13373 info = {
13374 id: credentials ? credentials.identityId : undefined,
13375 username: user.getUsername(),
13376 attributes: userAttrs
13377 };
13378 return [2
13379 /*return*/
13380 , info];
13381
13382 case 8:
13383 err_1 = _a.sent();
13384 logger.error('currentUserInfo error', err_1);
13385 return [2
13386 /*return*/
13387 , {}];
13388
13389 case 9:
13390 if (source === 'federated') {
13391 user = this.user;
13392 return [2
13393 /*return*/
13394 , user ? user : {}];
13395 }
13396
13397 return [2
13398 /*return*/
13399 ];
13400 }
13401 });
13402 });
13403 };
13404
13405 AuthClass.prototype.federatedSignIn = function (providerOrOptions, response, user) {
13406 return __awaiter(this, void 0, void 0, function () {
13407 var options, provider, customState, client_id, redirect_uri, provider, loggedInUser, token, identity_id, expires_at, credentials, currentUser;
13408 return __generator(this, function (_a) {
13409 switch (_a.label) {
13410 case 0:
13411 if (!this._config.identityPoolId && !this._config.userPoolId) {
13412 throw new Error("Federation requires either a User Pool or Identity Pool in config");
13413 } // Ensure backwards compatability
13414
13415
13416 if (typeof providerOrOptions === 'undefined') {
13417 if (this._config.identityPoolId && !this._config.userPoolId) {
13418 throw new Error("Federation with Identity Pools requires tokens passed as arguments");
13419 }
13420 }
13421
13422 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
13423 /*break*/
13424 , 1];
13425 options = providerOrOptions || {
13426 provider: _types_Auth__WEBPACK_IMPORTED_MODULE_7__["CognitoHostedUIIdentityProvider"].Cognito
13427 };
13428 provider = Object(_types__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptions"])(options) ? options.provider : options.customProvider;
13429 customState = Object(_types__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptions"])(options) ? options.customState : options.customState;
13430
13431 if (this._config.userPoolId) {
13432 client_id = Object(_types__WEBPACK_IMPORTED_MODULE_0__["isCognitoHostedOpts"])(this._config.oauth) ? this._config.userPoolWebClientId : this._config.oauth.clientID;
13433 redirect_uri = Object(_types__WEBPACK_IMPORTED_MODULE_0__["isCognitoHostedOpts"])(this._config.oauth) ? this._config.oauth.redirectSignIn : this._config.oauth.redirectUri;
13434
13435 this._oAuthHandler.oauthSignIn(this._config.oauth.responseType, this._config.oauth.domain, redirect_uri, client_id, provider, customState);
13436 }
13437
13438 return [3
13439 /*break*/
13440 , 4];
13441
13442 case 1:
13443 provider = providerOrOptions; // To check if the user is already logged in
13444
13445 try {
13446 loggedInUser = JSON.stringify(JSON.parse(this._storage.getItem('aws-amplify-federatedInfo')).user);
13447
13448 if (loggedInUser) {
13449 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.");
13450 }
13451 } catch (e) {}
13452
13453 token = response.token, identity_id = response.identity_id, expires_at = response.expires_at;
13454 return [4
13455 /*yield*/
13456 , this.Credentials.set({
13457 provider: provider,
13458 token: token,
13459 identity_id: identity_id,
13460 user: user,
13461 expires_at: expires_at
13462 }, 'federation')];
13463
13464 case 2:
13465 credentials = _a.sent();
13466 return [4
13467 /*yield*/
13468 , this.currentAuthenticatedUser()];
13469
13470 case 3:
13471 currentUser = _a.sent();
13472 dispatchAuthEvent('signIn', currentUser, "A user " + currentUser.username + " has been signed in");
13473 logger.debug('federated sign in credentials', credentials);
13474 return [2
13475 /*return*/
13476 , credentials];
13477
13478 case 4:
13479 return [2
13480 /*return*/
13481 ];
13482 }
13483 });
13484 });
13485 };
13486 /**
13487 * Used to complete the OAuth flow with or without the Cognito Hosted UI
13488 * @param {String} URL - optional parameter for customers to pass in the response URL
13489 */
13490
13491
13492 AuthClass.prototype._handleAuthResponse = function (URL) {
13493 return __awaiter(this, void 0, void 0, function () {
13494 var currentUrl, hasCodeOrError, hasTokenOrError, _a, accessToken, idToken, refreshToken, state, session, credentials, isCustomStateIncluded, currentUser, customState, err_2;
13495
13496 return __generator(this, function (_b) {
13497 switch (_b.label) {
13498 case 0:
13499 if (this.oAuthFlowInProgress) {
13500 logger.debug("Skipping URL " + URL + " current flow in progress");
13501 return [2
13502 /*return*/
13503 ];
13504 }
13505
13506 _b.label = 1;
13507
13508 case 1:
13509 _b.trys.push([1,, 8, 9]);
13510
13511 this.oAuthFlowInProgress = true;
13512
13513 if (!this._config.userPoolId) {
13514 throw new Error("OAuth responses require a User Pool defined in config");
13515 }
13516
13517 dispatchAuthEvent('parsingCallbackUrl', {
13518 url: URL
13519 }, "The callback url is being parsed");
13520 currentUrl = URL || (_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["JS"].browserOrNode().isBrowser ? window.location.href : '');
13521 hasCodeOrError = !!(Object(url__WEBPACK_IMPORTED_MODULE_3__["parse"])(currentUrl).query || '').split('&').map(function (entry) {
13522 return entry.split('=');
13523 }).find(function (_a) {
13524 var _b = __read(_a, 1),
13525 k = _b[0];
13526
13527 return k === 'code' || k === 'error';
13528 });
13529 hasTokenOrError = !!(Object(url__WEBPACK_IMPORTED_MODULE_3__["parse"])(currentUrl).hash || '#').substr(1).split('&').map(function (entry) {
13530 return entry.split('=');
13531 }).find(function (_a) {
13532 var _b = __read(_a, 1),
13533 k = _b[0];
13534
13535 return k === 'access_token' || k === 'error';
13536 });
13537 if (!(hasCodeOrError || hasTokenOrError)) return [3
13538 /*break*/
13539 , 7];
13540
13541 this._storage.setItem('amplify-redirected-from-hosted-ui', 'true');
13542
13543 _b.label = 2;
13544
13545 case 2:
13546 _b.trys.push([2, 6,, 7]);
13547
13548 return [4
13549 /*yield*/
13550 , this._oAuthHandler.handleAuthResponse(currentUrl)];
13551
13552 case 3:
13553 _a = _b.sent(), accessToken = _a.accessToken, idToken = _a.idToken, refreshToken = _a.refreshToken, state = _a.state;
13554 session = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUserSession"]({
13555 IdToken: new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoIdToken"]({
13556 IdToken: idToken
13557 }),
13558 RefreshToken: new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoRefreshToken"]({
13559 RefreshToken: refreshToken
13560 }),
13561 AccessToken: new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoAccessToken"]({
13562 AccessToken: accessToken
13563 })
13564 });
13565 credentials = void 0;
13566 if (!this._config.identityPoolId) return [3
13567 /*break*/
13568 , 5];
13569 return [4
13570 /*yield*/
13571 , this.Credentials.set(session, 'session')];
13572
13573 case 4:
13574 credentials = _b.sent();
13575 logger.debug('AWS credentials', credentials);
13576 _b.label = 5;
13577
13578 case 5:
13579 isCustomStateIncluded = /-/.test(state);
13580 currentUser = this.createCognitoUser(session.getIdToken().decodePayload()['cognito:username']); // This calls cacheTokens() in Cognito SDK
13581
13582 currentUser.setSignInUserSession(session);
13583
13584 if (window && typeof window.history !== 'undefined') {
13585 window.history.replaceState({}, null, this._config.oauth.redirectSignIn);
13586 }
13587
13588 dispatchAuthEvent('signIn', currentUser, "A user " + currentUser.getUsername() + " has been signed in");
13589 dispatchAuthEvent('cognitoHostedUI', currentUser, "A user " + currentUser.getUsername() + " has been signed in via Cognito Hosted UI");
13590
13591 if (isCustomStateIncluded) {
13592 customState = state.split('-').splice(1).join('-');
13593 dispatchAuthEvent('customOAuthState', Object(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["urlSafeDecode"])(customState), "State for user " + currentUser.getUsername());
13594 } //#endregion
13595
13596
13597 return [2
13598 /*return*/
13599 , credentials];
13600
13601 case 6:
13602 err_2 = _b.sent();
13603 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`.
13604 // Otherwise, reloading the page will throw errors as the `code` has already been spent.
13605
13606 if (window && typeof window.history !== 'undefined') {
13607 window.history.replaceState({}, null, this._config.oauth.redirectSignIn);
13608 }
13609
13610 dispatchAuthEvent('signIn_failure', err_2, "The OAuth response flow failed");
13611 dispatchAuthEvent('cognitoHostedUI_failure', err_2, "A failure occurred when returning to the Cognito Hosted UI");
13612 dispatchAuthEvent('customState_failure', err_2, "A failure occurred when returning state");
13613 return [3
13614 /*break*/
13615 , 7];
13616
13617 case 7:
13618 return [3
13619 /*break*/
13620 , 9];
13621
13622 case 8:
13623 this.oAuthFlowInProgress = false;
13624 return [7
13625 /*endfinally*/
13626 ];
13627
13628 case 9:
13629 return [2
13630 /*return*/
13631 ];
13632 }
13633 });
13634 });
13635 };
13636 /**
13637 * Compact version of credentials
13638 * @param {Object} credentials
13639 * @return {Object} - Credentials
13640 */
13641
13642
13643 AuthClass.prototype.essentialCredentials = function (credentials) {
13644 return {
13645 accessKeyId: credentials.accessKeyId,
13646 sessionToken: credentials.sessionToken,
13647 secretAccessKey: credentials.secretAccessKey,
13648 identityId: credentials.identityId,
13649 authenticated: credentials.authenticated
13650 };
13651 };
13652
13653 AuthClass.prototype.attributesToObject = function (attributes) {
13654 var _this = this;
13655
13656 var obj = {};
13657
13658 if (attributes) {
13659 attributes.map(function (attribute) {
13660 if (attribute.Name === 'email_verified' || attribute.Name === 'phone_number_verified') {
13661 obj[attribute.Name] = _this.isTruthyString(attribute.Value) || attribute.Value === true;
13662 } else {
13663 obj[attribute.Name] = attribute.Value;
13664 }
13665 });
13666 }
13667
13668 return obj;
13669 };
13670
13671 AuthClass.prototype.isTruthyString = function (value) {
13672 return typeof value.toLowerCase === 'function' && value.toLowerCase() === 'true';
13673 };
13674
13675 AuthClass.prototype.createCognitoUser = function (username) {
13676 var userData = {
13677 Username: username,
13678 Pool: this.userPool
13679 };
13680 userData.Storage = this._storage;
13681 var authenticationFlowType = this._config.authenticationFlowType;
13682 var user = new amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUser"](userData);
13683
13684 if (authenticationFlowType) {
13685 user.setAuthenticationFlowType(authenticationFlowType);
13686 }
13687
13688 return user;
13689 };
13690
13691 AuthClass.prototype._isValidAuthStorage = function (obj) {
13692 // We need to check if the obj has the functions of Storage
13693 return !!obj && typeof obj.getItem === 'function' && typeof obj.setItem === 'function' && typeof obj.removeItem === 'function' && typeof obj.clear === 'function';
13694 };
13695
13696 AuthClass.prototype.noUserPoolErrorHandler = function (config) {
13697 if (config) {
13698 if (!config.userPoolId || !config.identityPoolId) {
13699 return _types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].MissingAuthConfig;
13700 }
13701 }
13702
13703 return _types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NoConfig;
13704 };
13705
13706 AuthClass.prototype.rejectAuthError = function (type) {
13707 return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](type));
13708 };
13709
13710 AuthClass.prototype.rejectNoUserPool = function () {
13711 var type = this.noUserPoolErrorHandler(this._config);
13712 return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_6__["NoUserPoolError"](type));
13713 };
13714
13715 AuthClass.prototype.rememberDevice = function () {
13716 return __awaiter(this, void 0, void 0, function () {
13717 var currUser, error_1;
13718 return __generator(this, function (_a) {
13719 switch (_a.label) {
13720 case 0:
13721 _a.trys.push([0, 2,, 3]);
13722
13723 return [4
13724 /*yield*/
13725 , this.currentUserPoolUser()];
13726
13727 case 1:
13728 currUser = _a.sent();
13729 return [3
13730 /*break*/
13731 , 3];
13732
13733 case 2:
13734 error_1 = _a.sent();
13735 logger.debug('The user is not authenticated by the error', error_1);
13736 return [2
13737 /*return*/
13738 , Promise.reject('The user is not authenticated')];
13739
13740 case 3:
13741 currUser.getCachedDeviceKeyAndPassword();
13742 return [2
13743 /*return*/
13744 , new Promise(function (res, rej) {
13745 currUser.setDeviceStatusRemembered({
13746 onSuccess: function onSuccess(data) {
13747 res(data);
13748 },
13749 onFailure: function onFailure(err) {
13750 if (err.code === 'InvalidParameterException') {
13751 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].DeviceConfig));
13752 } else if (err.code === 'NetworkError') {
13753 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NetworkError));
13754 } else {
13755 rej(err);
13756 }
13757 }
13758 });
13759 })];
13760 }
13761 });
13762 });
13763 };
13764
13765 AuthClass.prototype.forgetDevice = function () {
13766 return __awaiter(this, void 0, void 0, function () {
13767 var currUser, error_2;
13768 return __generator(this, function (_a) {
13769 switch (_a.label) {
13770 case 0:
13771 _a.trys.push([0, 2,, 3]);
13772
13773 return [4
13774 /*yield*/
13775 , this.currentUserPoolUser()];
13776
13777 case 1:
13778 currUser = _a.sent();
13779 return [3
13780 /*break*/
13781 , 3];
13782
13783 case 2:
13784 error_2 = _a.sent();
13785 logger.debug('The user is not authenticated by the error', error_2);
13786 return [2
13787 /*return*/
13788 , Promise.reject('The user is not authenticated')];
13789
13790 case 3:
13791 currUser.getCachedDeviceKeyAndPassword();
13792 return [2
13793 /*return*/
13794 , new Promise(function (res, rej) {
13795 currUser.forgetDevice({
13796 onSuccess: function onSuccess(data) {
13797 res(data);
13798 },
13799 onFailure: function onFailure(err) {
13800 if (err.code === 'InvalidParameterException') {
13801 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].DeviceConfig));
13802 } else if (err.code === 'NetworkError') {
13803 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NetworkError));
13804 } else {
13805 rej(err);
13806 }
13807 }
13808 });
13809 })];
13810 }
13811 });
13812 });
13813 };
13814
13815 AuthClass.prototype.fetchDevices = function () {
13816 return __awaiter(this, void 0, void 0, function () {
13817 var currUser, error_3;
13818 return __generator(this, function (_a) {
13819 switch (_a.label) {
13820 case 0:
13821 _a.trys.push([0, 2,, 3]);
13822
13823 return [4
13824 /*yield*/
13825 , this.currentUserPoolUser()];
13826
13827 case 1:
13828 currUser = _a.sent();
13829 return [3
13830 /*break*/
13831 , 3];
13832
13833 case 2:
13834 error_3 = _a.sent();
13835 logger.debug('The user is not authenticated by the error', error_3);
13836 throw new Error('The user is not authenticated');
13837
13838 case 3:
13839 currUser.getCachedDeviceKeyAndPassword();
13840 return [2
13841 /*return*/
13842 , new Promise(function (res, rej) {
13843 var cb = {
13844 onSuccess: function onSuccess(data) {
13845 var deviceList = data.Devices.map(function (device) {
13846 var deviceName = device.DeviceAttributes.find(function (_a) {
13847 var Name = _a.Name;
13848 return Name === 'device_name';
13849 }) || {};
13850 var deviceInfo = {
13851 id: device.DeviceKey,
13852 name: deviceName.Value
13853 };
13854 return deviceInfo;
13855 });
13856 res(deviceList);
13857 },
13858 onFailure: function onFailure(err) {
13859 if (err.code === 'InvalidParameterException') {
13860 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].DeviceConfig));
13861 } else if (err.code === 'NetworkError') {
13862 rej(new _Errors__WEBPACK_IMPORTED_MODULE_6__["AuthError"](_types_Auth__WEBPACK_IMPORTED_MODULE_7__["AuthErrorTypes"].NetworkError));
13863 } else {
13864 rej(err);
13865 }
13866 }
13867 };
13868 currUser.listDevices(MAX_DEVICES, null, cb);
13869 })];
13870 }
13871 });
13872 });
13873 };
13874
13875 return AuthClass;
13876}();
13877
13878
13879var Auth = new AuthClass(null);
13880_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["Amplify"].register(Auth);
13881
13882/***/ }),
13883
13884/***/ "./lib-esm/Errors.js":
13885/*!***************************!*\
13886 !*** ./lib-esm/Errors.js ***!
13887 \***************************/
13888/*! exports provided: AuthError, NoUserPoolError, authErrorMessages */
13889/***/ (function(module, __webpack_exports__, __webpack_require__) {
13890
13891"use strict";
13892__webpack_require__.r(__webpack_exports__);
13893/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthError", function() { return AuthError; });
13894/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoUserPoolError", function() { return NoUserPoolError; });
13895/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "authErrorMessages", function() { return authErrorMessages; });
13896/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
13897/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__);
13898/* harmony import */ var _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./common/AuthErrorStrings */ "./lib-esm/common/AuthErrorStrings.js");
13899/*
13900 * Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
13901 *
13902 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
13903 * the License. A copy of the License is located at
13904 *
13905 * http://aws.amazon.com/apache2.0/
13906 *
13907 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
13908 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
13909 * and limitations under the License.
13910 */
13911var __extends = undefined && undefined.__extends || function () {
13912 var _extendStatics = function extendStatics(d, b) {
13913 _extendStatics = Object.setPrototypeOf || {
13914 __proto__: []
13915 } instanceof Array && function (d, b) {
13916 d.__proto__ = b;
13917 } || function (d, b) {
13918 for (var p in b) {
13919 if (b.hasOwnProperty(p)) d[p] = b[p];
13920 }
13921 };
13922
13923 return _extendStatics(d, b);
13924 };
13925
13926 return function (d, b) {
13927 _extendStatics(d, b);
13928
13929 function __() {
13930 this.constructor = d;
13931 }
13932
13933 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13934 };
13935}();
13936
13937
13938
13939var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["ConsoleLogger"]('AuthError');
13940
13941var AuthError =
13942/** @class */
13943function (_super) {
13944 __extends(AuthError, _super);
13945
13946 function AuthError(type) {
13947 var _this = this;
13948
13949 var _a = authErrorMessages[type],
13950 message = _a.message,
13951 log = _a.log;
13952 _this = _super.call(this, message) || this; // Hack for making the custom error class work when transpiled to es5
13953 // TODO: Delete the following 2 lines after we change the build target to >= es2015
13954
13955 _this.constructor = AuthError;
13956 Object.setPrototypeOf(_this, AuthError.prototype);
13957 _this.name = 'AuthError';
13958 _this.log = log || message;
13959 logger.error(_this.log);
13960 return _this;
13961 }
13962
13963 return AuthError;
13964}(Error);
13965
13966
13967
13968var NoUserPoolError =
13969/** @class */
13970function (_super) {
13971 __extends(NoUserPoolError, _super);
13972
13973 function NoUserPoolError(type) {
13974 var _this = _super.call(this, type) || this; // Hack for making the custom error class work when transpiled to es5
13975 // TODO: Delete the following 2 lines after we change the build target to >= es2015
13976
13977
13978 _this.constructor = NoUserPoolError;
13979 Object.setPrototypeOf(_this, NoUserPoolError.prototype);
13980 _this.name = 'NoUserPoolError';
13981 return _this;
13982 }
13983
13984 return NoUserPoolError;
13985}(AuthError);
13986
13987
13988var authErrorMessages = {
13989 noConfig: {
13990 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].DEFAULT_MSG,
13991 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 "
13992 },
13993 missingAuthConfig: {
13994 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].DEFAULT_MSG,
13995 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 "
13996 },
13997 emptyUsername: {
13998 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].EMPTY_USERNAME
13999 },
14000 // TODO: should include a list of valid sign-in types
14001 invalidUsername: {
14002 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].INVALID_USERNAME
14003 },
14004 emptyPassword: {
14005 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].EMPTY_PASSWORD
14006 },
14007 emptyCode: {
14008 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].EMPTY_CODE
14009 },
14010 signUpError: {
14011 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].SIGN_UP_ERROR,
14012 log: 'The first parameter should either be non-null string or object'
14013 },
14014 noMFA: {
14015 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].NO_MFA
14016 },
14017 invalidMFA: {
14018 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].INVALID_MFA
14019 },
14020 emptyChallengeResponse: {
14021 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].EMPTY_CHALLENGE
14022 },
14023 noUserSession: {
14024 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].NO_USER_SESSION
14025 },
14026 deviceConfig: {
14027 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].DEVICE_CONFIG
14028 },
14029 networkError: {
14030 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].NETWORK_ERROR
14031 },
14032 "default": {
14033 message: _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_1__["AuthErrorStrings"].DEFAULT_MSG
14034 }
14035};
14036
14037/***/ }),
14038
14039/***/ "./lib-esm/OAuth/OAuth.js":
14040/*!********************************!*\
14041 !*** ./lib-esm/OAuth/OAuth.js ***!
14042 \********************************/
14043/*! exports provided: default */
14044/***/ (function(module, __webpack_exports__, __webpack_require__) {
14045
14046"use strict";
14047__webpack_require__.r(__webpack_exports__);
14048/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url */ "../../node_modules/url/url.js");
14049/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_0__);
14050/* harmony import */ var _urlOpener__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./urlOpener */ "./lib-esm/OAuth/urlOpener.js");
14051/* harmony import */ var _oauthStorage__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./oauthStorage */ "./lib-esm/OAuth/oauthStorage.js");
14052/* harmony import */ var _types_Auth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/Auth */ "./lib-esm/types/Auth.js");
14053/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
14054/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__);
14055/* harmony import */ var crypto_js_sha256__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! crypto-js/sha256 */ "./node_modules/crypto-js/sha256.js");
14056/* harmony import */ var crypto_js_sha256__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(crypto_js_sha256__WEBPACK_IMPORTED_MODULE_5__);
14057/* harmony import */ var crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! crypto-js/enc-base64 */ "./node_modules/crypto-js/enc-base64.js");
14058/* harmony import */ var crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_6__);
14059/*
14060 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14061 *
14062 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14063 * the License. A copy of the License is located at
14064 *
14065 * http://aws.amazon.com/apache2.0/
14066 *
14067 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14068 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14069 * and limitations under the License.
14070 */
14071var __assign = undefined && undefined.__assign || function () {
14072 __assign = Object.assign || function (t) {
14073 for (var s, i = 1, n = arguments.length; i < n; i++) {
14074 s = arguments[i];
14075
14076 for (var p in s) {
14077 if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
14078 }
14079 }
14080
14081 return t;
14082 };
14083
14084 return __assign.apply(this, arguments);
14085};
14086
14087var __awaiter = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) {
14088 function adopt(value) {
14089 return value instanceof P ? value : new P(function (resolve) {
14090 resolve(value);
14091 });
14092 }
14093
14094 return new (P || (P = Promise))(function (resolve, reject) {
14095 function fulfilled(value) {
14096 try {
14097 step(generator.next(value));
14098 } catch (e) {
14099 reject(e);
14100 }
14101 }
14102
14103 function rejected(value) {
14104 try {
14105 step(generator["throw"](value));
14106 } catch (e) {
14107 reject(e);
14108 }
14109 }
14110
14111 function step(result) {
14112 result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
14113 }
14114
14115 step((generator = generator.apply(thisArg, _arguments || [])).next());
14116 });
14117};
14118
14119var __generator = undefined && undefined.__generator || function (thisArg, body) {
14120 var _ = {
14121 label: 0,
14122 sent: function sent() {
14123 if (t[0] & 1) throw t[1];
14124 return t[1];
14125 },
14126 trys: [],
14127 ops: []
14128 },
14129 f,
14130 y,
14131 t,
14132 g;
14133 return g = {
14134 next: verb(0),
14135 "throw": verb(1),
14136 "return": verb(2)
14137 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
14138 return this;
14139 }), g;
14140
14141 function verb(n) {
14142 return function (v) {
14143 return step([n, v]);
14144 };
14145 }
14146
14147 function step(op) {
14148 if (f) throw new TypeError("Generator is already executing.");
14149
14150 while (_) {
14151 try {
14152 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;
14153 if (y = 0, t) op = [op[0] & 2, t.value];
14154
14155 switch (op[0]) {
14156 case 0:
14157 case 1:
14158 t = op;
14159 break;
14160
14161 case 4:
14162 _.label++;
14163 return {
14164 value: op[1],
14165 done: false
14166 };
14167
14168 case 5:
14169 _.label++;
14170 y = op[1];
14171 op = [0];
14172 continue;
14173
14174 case 7:
14175 op = _.ops.pop();
14176
14177 _.trys.pop();
14178
14179 continue;
14180
14181 default:
14182 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
14183 _ = 0;
14184 continue;
14185 }
14186
14187 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
14188 _.label = op[1];
14189 break;
14190 }
14191
14192 if (op[0] === 6 && _.label < t[1]) {
14193 _.label = t[1];
14194 t = op;
14195 break;
14196 }
14197
14198 if (t && _.label < t[2]) {
14199 _.label = t[2];
14200
14201 _.ops.push(op);
14202
14203 break;
14204 }
14205
14206 if (t[2]) _.ops.pop();
14207
14208 _.trys.pop();
14209
14210 continue;
14211 }
14212
14213 op = body.call(thisArg, _);
14214 } catch (e) {
14215 op = [6, e];
14216 y = 0;
14217 } finally {
14218 f = t = 0;
14219 }
14220 }
14221
14222 if (op[0] & 5) throw op[1];
14223 return {
14224 value: op[0] ? op[1] : void 0,
14225 done: true
14226 };
14227 }
14228};
14229
14230var __read = undefined && undefined.__read || function (o, n) {
14231 var m = typeof Symbol === "function" && o[Symbol.iterator];
14232 if (!m) return o;
14233 var i = m.call(o),
14234 r,
14235 ar = [],
14236 e;
14237
14238 try {
14239 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
14240 ar.push(r.value);
14241 }
14242 } catch (error) {
14243 e = {
14244 error: error
14245 };
14246 } finally {
14247 try {
14248 if (r && !r.done && (m = i["return"])) m.call(i);
14249 } finally {
14250 if (e) throw e.error;
14251 }
14252 }
14253
14254 return ar;
14255};
14256
14257 // Used for OAuth parsing of Cognito Hosted UI
14258
14259
14260
14261
14262
14263
14264
14265var AMPLIFY_SYMBOL = typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function' ? Symbol["for"]('amplify_default') : '@@amplify_default';
14266
14267var dispatchAuthEvent = function dispatchAuthEvent(event, data, message) {
14268 _aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__["Hub"].dispatch('auth', {
14269 event: event,
14270 data: data,
14271 message: message
14272 }, 'Auth', AMPLIFY_SYMBOL);
14273};
14274
14275var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__["ConsoleLogger"]('OAuth');
14276
14277var OAuth =
14278/** @class */
14279function () {
14280 function OAuth(_a) {
14281 var config = _a.config,
14282 cognitoClientId = _a.cognitoClientId,
14283 _b = _a.scopes,
14284 scopes = _b === void 0 ? [] : _b;
14285 this._urlOpener = config.urlOpener || _urlOpener__WEBPACK_IMPORTED_MODULE_1__["launchUri"];
14286 this._config = config;
14287 this._cognitoClientId = cognitoClientId;
14288 if (!this.isValidScopes(scopes)) throw Error('scopes must be a String Array');
14289 this._scopes = scopes;
14290 }
14291
14292 OAuth.prototype.isValidScopes = function (scopes) {
14293 return Array.isArray(scopes) && scopes.every(function (scope) {
14294 return typeof scope === 'string';
14295 });
14296 };
14297
14298 OAuth.prototype.oauthSignIn = function (responseType, domain, redirectSignIn, clientId, provider, customState) {
14299 if (responseType === void 0) {
14300 responseType = 'code';
14301 }
14302
14303 if (provider === void 0) {
14304 provider = _types_Auth__WEBPACK_IMPORTED_MODULE_3__["CognitoHostedUIIdentityProvider"].Cognito;
14305 }
14306
14307 var generatedState = this._generateState(32);
14308 /* encodeURIComponent is not URL safe, use urlSafeEncode instead. Cognito
14309 single-encodes/decodes url on first sign in and double-encodes/decodes url
14310 when user already signed in. Using encodeURIComponent, Base32, Base64 add
14311 characters % or = which on further encoding becomes unsafe. '=' create issue
14312 for parsing query params.
14313 Refer: https://github.com/aws-amplify/amplify-js/issues/5218 */
14314
14315
14316 var state = customState ? generatedState + "-" + Object(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_4__["urlSafeEncode"])(customState) : generatedState;
14317 _oauthStorage__WEBPACK_IMPORTED_MODULE_2__["setState"](state);
14318
14319 var pkce_key = this._generateRandom(128);
14320
14321 _oauthStorage__WEBPACK_IMPORTED_MODULE_2__["setPKCE"](pkce_key);
14322
14323 var code_challenge = this._generateChallenge(pkce_key);
14324
14325 var code_challenge_method = 'S256';
14326
14327 var scopesString = this._scopes.join(' ');
14328
14329 var queryString = Object.entries(__assign(__assign({
14330 redirect_uri: redirectSignIn,
14331 response_type: responseType,
14332 client_id: clientId,
14333 identity_provider: provider,
14334 scope: scopesString,
14335 state: state
14336 }, responseType === 'code' ? {
14337 code_challenge: code_challenge
14338 } : {}), responseType === 'code' ? {
14339 code_challenge_method: code_challenge_method
14340 } : {})).map(function (_a) {
14341 var _b = __read(_a, 2),
14342 k = _b[0],
14343 v = _b[1];
14344
14345 return encodeURIComponent(k) + "=" + encodeURIComponent(v);
14346 }).join('&');
14347 var URL = "https://" + domain + "/oauth2/authorize?" + queryString;
14348 logger.debug("Redirecting to " + URL);
14349
14350 this._urlOpener(URL, redirectSignIn);
14351 };
14352
14353 OAuth.prototype._handleCodeFlow = function (currentUrl) {
14354 return __awaiter(this, void 0, void 0, function () {
14355 var code, currentUrlPathname, redirectSignInPathname, oAuthTokenEndpoint, client_id, redirect_uri, code_verifier, oAuthTokenBody, body, _a, access_token, refresh_token, id_token, error;
14356
14357 return __generator(this, function (_b) {
14358 switch (_b.label) {
14359 case 0:
14360 code = (Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).query || '').split('&').map(function (pairings) {
14361 return pairings.split('=');
14362 }).reduce(function (accum, _a) {
14363 var _b;
14364
14365 var _c = __read(_a, 2),
14366 k = _c[0],
14367 v = _c[1];
14368
14369 return __assign(__assign({}, accum), (_b = {}, _b[k] = v, _b));
14370 }, {
14371 code: undefined
14372 }).code;
14373 currentUrlPathname = Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).pathname || '/';
14374 redirectSignInPathname = Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(this._config.redirectSignIn).pathname || '/';
14375
14376 if (!code || currentUrlPathname !== redirectSignInPathname) {
14377 return [2
14378 /*return*/
14379 ];
14380 }
14381
14382 oAuthTokenEndpoint = 'https://' + this._config.domain + '/oauth2/token';
14383 dispatchAuthEvent('codeFlow', {}, "Retrieving tokens from " + oAuthTokenEndpoint);
14384 client_id = Object(_types_Auth__WEBPACK_IMPORTED_MODULE_3__["isCognitoHostedOpts"])(this._config) ? this._cognitoClientId : this._config.clientID;
14385 redirect_uri = Object(_types_Auth__WEBPACK_IMPORTED_MODULE_3__["isCognitoHostedOpts"])(this._config) ? this._config.redirectSignIn : this._config.redirectUri;
14386 code_verifier = _oauthStorage__WEBPACK_IMPORTED_MODULE_2__["getPKCE"]();
14387 oAuthTokenBody = __assign({
14388 grant_type: 'authorization_code',
14389 code: code,
14390 client_id: client_id,
14391 redirect_uri: redirect_uri
14392 }, code_verifier ? {
14393 code_verifier: code_verifier
14394 } : {});
14395 logger.debug("Calling token endpoint: " + oAuthTokenEndpoint + " with", oAuthTokenBody);
14396 body = Object.entries(oAuthTokenBody).map(function (_a) {
14397 var _b = __read(_a, 2),
14398 k = _b[0],
14399 v = _b[1];
14400
14401 return encodeURIComponent(k) + "=" + encodeURIComponent(v);
14402 }).join('&');
14403 return [4
14404 /*yield*/
14405 , fetch(oAuthTokenEndpoint, {
14406 method: 'POST',
14407 headers: {
14408 'Content-Type': 'application/x-www-form-urlencoded'
14409 },
14410 body: body
14411 })];
14412
14413 case 1:
14414 return [4
14415 /*yield*/
14416 , _b.sent().json()];
14417
14418 case 2:
14419 _a = _b.sent(), access_token = _a.access_token, refresh_token = _a.refresh_token, id_token = _a.id_token, error = _a.error;
14420
14421 if (error) {
14422 throw new Error(error);
14423 }
14424
14425 return [2
14426 /*return*/
14427 , {
14428 accessToken: access_token,
14429 refreshToken: refresh_token,
14430 idToken: id_token
14431 }];
14432 }
14433 });
14434 });
14435 };
14436
14437 OAuth.prototype._handleImplicitFlow = function (currentUrl) {
14438 return __awaiter(this, void 0, void 0, function () {
14439 var _a, id_token, access_token;
14440
14441 return __generator(this, function (_b) {
14442 _a = (Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).hash || '#').substr(1) // Remove # from returned code
14443 .split('&').map(function (pairings) {
14444 return pairings.split('=');
14445 }).reduce(function (accum, _a) {
14446 var _b;
14447
14448 var _c = __read(_a, 2),
14449 k = _c[0],
14450 v = _c[1];
14451
14452 return __assign(__assign({}, accum), (_b = {}, _b[k] = v, _b));
14453 }, {
14454 id_token: undefined,
14455 access_token: undefined
14456 }), id_token = _a.id_token, access_token = _a.access_token;
14457 dispatchAuthEvent('implicitFlow', {}, "Got tokens from " + currentUrl);
14458 logger.debug("Retrieving implicit tokens from " + currentUrl + " with");
14459 return [2
14460 /*return*/
14461 , {
14462 accessToken: access_token,
14463 idToken: id_token,
14464 refreshToken: null
14465 }];
14466 });
14467 });
14468 };
14469
14470 OAuth.prototype.handleAuthResponse = function (currentUrl) {
14471 return __awaiter(this, void 0, void 0, function () {
14472 var urlParams, error, error_description, state, _a, _b, e_1;
14473
14474 return __generator(this, function (_c) {
14475 switch (_c.label) {
14476 case 0:
14477 _c.trys.push([0, 5,, 6]);
14478
14479 urlParams = currentUrl ? __assign(__assign({}, (Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).hash || '#').substr(1).split('&').map(function (entry) {
14480 return entry.split('=');
14481 }).reduce(function (acc, _a) {
14482 var _b = __read(_a, 2),
14483 k = _b[0],
14484 v = _b[1];
14485
14486 return acc[k] = v, acc;
14487 }, {})), (Object(url__WEBPACK_IMPORTED_MODULE_0__["parse"])(currentUrl).query || '').split('&').map(function (entry) {
14488 return entry.split('=');
14489 }).reduce(function (acc, _a) {
14490 var _b = __read(_a, 2),
14491 k = _b[0],
14492 v = _b[1];
14493
14494 return acc[k] = v, acc;
14495 }, {})) : {};
14496 error = urlParams.error, error_description = urlParams.error_description;
14497
14498 if (error) {
14499 throw new Error(error_description);
14500 }
14501
14502 state = this._validateState(urlParams);
14503 logger.debug("Starting " + this._config.responseType + " flow with " + currentUrl);
14504 if (!(this._config.responseType === 'code')) return [3
14505 /*break*/
14506 , 2];
14507 _a = [{}];
14508 return [4
14509 /*yield*/
14510 , this._handleCodeFlow(currentUrl)];
14511
14512 case 1:
14513 return [2
14514 /*return*/
14515 , __assign.apply(void 0, [__assign.apply(void 0, _a.concat([_c.sent()])), {
14516 state: state
14517 }])];
14518
14519 case 2:
14520 _b = [{}];
14521 return [4
14522 /*yield*/
14523 , this._handleImplicitFlow(currentUrl)];
14524
14525 case 3:
14526 return [2
14527 /*return*/
14528 , __assign.apply(void 0, [__assign.apply(void 0, _b.concat([_c.sent()])), {
14529 state: state
14530 }])];
14531
14532 case 4:
14533 return [3
14534 /*break*/
14535 , 6];
14536
14537 case 5:
14538 e_1 = _c.sent();
14539 logger.error("Error handling auth response.", e_1);
14540 throw e_1;
14541
14542 case 6:
14543 return [2
14544 /*return*/
14545 ];
14546 }
14547 });
14548 });
14549 };
14550
14551 OAuth.prototype._validateState = function (urlParams) {
14552 if (!urlParams) {
14553 return;
14554 }
14555
14556 var savedState = _oauthStorage__WEBPACK_IMPORTED_MODULE_2__["getState"]();
14557 var returnedState = urlParams.state; // This is because savedState only exists if the flow was initiated by Amplify
14558
14559 if (savedState && savedState !== returnedState) {
14560 throw new Error('Invalid state in OAuth flow');
14561 }
14562
14563 return returnedState;
14564 };
14565
14566 OAuth.prototype.signOut = function () {
14567 return __awaiter(this, void 0, void 0, function () {
14568 var oAuthLogoutEndpoint, client_id, signout_uri;
14569 return __generator(this, function (_a) {
14570 oAuthLogoutEndpoint = 'https://' + this._config.domain + '/logout?';
14571 client_id = Object(_types_Auth__WEBPACK_IMPORTED_MODULE_3__["isCognitoHostedOpts"])(this._config) ? this._cognitoClientId : this._config.oauth.clientID;
14572 signout_uri = Object(_types_Auth__WEBPACK_IMPORTED_MODULE_3__["isCognitoHostedOpts"])(this._config) ? this._config.redirectSignOut : this._config.returnTo;
14573 oAuthLogoutEndpoint += Object.entries({
14574 client_id: client_id,
14575 logout_uri: encodeURIComponent(signout_uri)
14576 }).map(function (_a) {
14577 var _b = __read(_a, 2),
14578 k = _b[0],
14579 v = _b[1];
14580
14581 return k + "=" + v;
14582 }).join('&');
14583 dispatchAuthEvent('oAuthSignOut', {
14584 oAuth: 'signOut'
14585 }, "Signing out from " + oAuthLogoutEndpoint);
14586 logger.debug("Signing out from " + oAuthLogoutEndpoint);
14587 return [2
14588 /*return*/
14589 , this._urlOpener(oAuthLogoutEndpoint, signout_uri)];
14590 });
14591 });
14592 };
14593
14594 OAuth.prototype._generateState = function (length) {
14595 var result = '';
14596 var i = length;
14597 var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
14598
14599 for (; i > 0; --i) {
14600 result += chars[Math.round(Math.random() * (chars.length - 1))];
14601 }
14602
14603 return result;
14604 };
14605
14606 OAuth.prototype._generateChallenge = function (code) {
14607 return this._base64URL(crypto_js_sha256__WEBPACK_IMPORTED_MODULE_5___default()(code));
14608 };
14609
14610 OAuth.prototype._base64URL = function (string) {
14611 return string.toString(crypto_js_enc_base64__WEBPACK_IMPORTED_MODULE_6___default.a).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
14612 };
14613
14614 OAuth.prototype._generateRandom = function (size) {
14615 var CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
14616 var buffer = new Uint8Array(size);
14617
14618 if (typeof window !== 'undefined' && !!window.crypto) {
14619 window.crypto.getRandomValues(buffer);
14620 } else {
14621 for (var i = 0; i < size; i += 1) {
14622 buffer[i] = Math.random() * CHARSET.length | 0;
14623 }
14624 }
14625
14626 return this._bufferToString(buffer);
14627 };
14628
14629 OAuth.prototype._bufferToString = function (buffer) {
14630 var CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
14631 var state = [];
14632
14633 for (var i = 0; i < buffer.byteLength; i += 1) {
14634 var index = buffer[i] % CHARSET.length;
14635 state.push(CHARSET[index]);
14636 }
14637
14638 return state.join('');
14639 };
14640
14641 return OAuth;
14642}();
14643
14644/* harmony default export */ __webpack_exports__["default"] = (OAuth);
14645
14646/***/ }),
14647
14648/***/ "./lib-esm/OAuth/oauthStorage.js":
14649/*!***************************************!*\
14650 !*** ./lib-esm/OAuth/oauthStorage.js ***!
14651 \***************************************/
14652/*! exports provided: setState, getState, setPKCE, getPKCE, clearAll */
14653/***/ (function(module, __webpack_exports__, __webpack_require__) {
14654
14655"use strict";
14656__webpack_require__.r(__webpack_exports__);
14657/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setState", function() { return setState; });
14658/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getState", function() { return getState; });
14659/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPKCE", function() { return setPKCE; });
14660/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPKCE", function() { return getPKCE; });
14661/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearAll", function() { return clearAll; });
14662/*
14663 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14664 *
14665 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14666 * the License. A copy of the License is located at
14667 *
14668 * http://aws.amazon.com/apache2.0/
14669 *
14670 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14671 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14672 * and limitations under the License.
14673 */
14674var setState = function setState(state) {
14675 window.sessionStorage.setItem('oauth_state', state);
14676};
14677var getState = function getState() {
14678 var oauth_state = window.sessionStorage.getItem('oauth_state');
14679 window.sessionStorage.removeItem('oauth_state');
14680 return oauth_state;
14681};
14682var setPKCE = function setPKCE(private_key) {
14683 window.sessionStorage.setItem('ouath_pkce_key', private_key);
14684};
14685var getPKCE = function getPKCE() {
14686 var ouath_pkce_key = window.sessionStorage.getItem('ouath_pkce_key');
14687 window.sessionStorage.removeItem('ouath_pkce_key');
14688 return ouath_pkce_key;
14689};
14690var clearAll = function clearAll() {
14691 window.sessionStorage.removeItem('ouath_pkce_key');
14692 window.sessionStorage.removeItem('oauth_state');
14693};
14694
14695/***/ }),
14696
14697/***/ "./lib-esm/OAuth/urlOpener.js":
14698/*!************************************!*\
14699 !*** ./lib-esm/OAuth/urlOpener.js ***!
14700 \************************************/
14701/*! exports provided: launchUri */
14702/***/ (function(module, __webpack_exports__, __webpack_require__) {
14703
14704"use strict";
14705__webpack_require__.r(__webpack_exports__);
14706/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "launchUri", function() { return launchUri; });
14707/*
14708 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14709 *
14710 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14711 * the License. A copy of the License is located at
14712 *
14713 * http://aws.amazon.com/apache2.0/
14714 *
14715 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14716 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14717 * and limitations under the License.
14718 */
14719var SELF = '_self';
14720var launchUri = function launchUri(url) {
14721 var windowProxy = window.open(url, SELF);
14722
14723 if (windowProxy) {
14724 return Promise.resolve(windowProxy);
14725 } else {
14726 return Promise.reject();
14727 }
14728};
14729
14730/***/ }),
14731
14732/***/ "./lib-esm/common/AuthErrorStrings.js":
14733/*!********************************************!*\
14734 !*** ./lib-esm/common/AuthErrorStrings.js ***!
14735 \********************************************/
14736/*! exports provided: AuthErrorStrings */
14737/***/ (function(module, __webpack_exports__, __webpack_require__) {
14738
14739"use strict";
14740__webpack_require__.r(__webpack_exports__);
14741/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthErrorStrings", function() { return AuthErrorStrings; });
14742var AuthErrorStrings;
14743
14744(function (AuthErrorStrings) {
14745 AuthErrorStrings["DEFAULT_MSG"] = "Authentication Error";
14746 AuthErrorStrings["EMPTY_EMAIL"] = "Email cannot be empty";
14747 AuthErrorStrings["EMPTY_PHONE"] = "Phone number cannot be empty";
14748 AuthErrorStrings["EMPTY_USERNAME"] = "Username cannot be empty";
14749 AuthErrorStrings["INVALID_USERNAME"] = "The username should either be a string or one of the sign in types";
14750 AuthErrorStrings["EMPTY_PASSWORD"] = "Password cannot be empty";
14751 AuthErrorStrings["EMPTY_CODE"] = "Confirmation code cannot be empty";
14752 AuthErrorStrings["SIGN_UP_ERROR"] = "Error creating account";
14753 AuthErrorStrings["NO_MFA"] = "No valid MFA method provided";
14754 AuthErrorStrings["INVALID_MFA"] = "Invalid MFA type";
14755 AuthErrorStrings["EMPTY_CHALLENGE"] = "Challenge response cannot be empty";
14756 AuthErrorStrings["NO_USER_SESSION"] = "Failed to get the session because the user is empty";
14757 AuthErrorStrings["NETWORK_ERROR"] = "Network Error";
14758 AuthErrorStrings["DEVICE_CONFIG"] = "Device tracking has not been configured in this User Pool";
14759})(AuthErrorStrings || (AuthErrorStrings = {}));
14760
14761/***/ }),
14762
14763/***/ "./lib-esm/index.js":
14764/*!**************************!*\
14765 !*** ./lib-esm/index.js ***!
14766 \**************************/
14767/*! exports provided: default, Auth, CognitoUser, CookieStorage, CognitoHostedUIIdentityProvider, appendToCognitoUserAgent, AuthErrorStrings, GRAPHQL_AUTH_MODE */
14768/***/ (function(module, __webpack_exports__, __webpack_require__) {
14769
14770"use strict";
14771__webpack_require__.r(__webpack_exports__);
14772/* harmony import */ var _Auth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Auth */ "./lib-esm/Auth.js");
14773/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Auth", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["Auth"]; });
14774
14775/* harmony import */ var _types_Auth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types/Auth */ "./lib-esm/types/Auth.js");
14776/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoHostedUIIdentityProvider", function() { return _types_Auth__WEBPACK_IMPORTED_MODULE_1__["CognitoHostedUIIdentityProvider"]; });
14777
14778/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GRAPHQL_AUTH_MODE", function() { return _types_Auth__WEBPACK_IMPORTED_MODULE_1__["GRAPHQL_AUTH_MODE"]; });
14779
14780/* harmony import */ var amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! amazon-cognito-identity-js */ "../amazon-cognito-identity-js/es/index.js");
14781/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoUser", function() { return amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CognitoUser"]; });
14782
14783/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CookieStorage", function() { return amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["CookieStorage"]; });
14784
14785/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "appendToCognitoUserAgent", function() { return amazon_cognito_identity_js__WEBPACK_IMPORTED_MODULE_2__["appendToCognitoUserAgent"]; });
14786
14787/* harmony import */ var _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./common/AuthErrorStrings */ "./lib-esm/common/AuthErrorStrings.js");
14788/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthErrorStrings", function() { return _common_AuthErrorStrings__WEBPACK_IMPORTED_MODULE_3__["AuthErrorStrings"]; });
14789
14790/*
14791 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14792 *
14793 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14794 * the License. A copy of the License is located at
14795 *
14796 * http://aws.amazon.com/apache2.0/
14797 *
14798 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14799 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14800 * and limitations under the License.
14801 */
14802
14803
14804
14805
14806/**
14807 * @deprecated use named import
14808 */
14809
14810/* harmony default export */ __webpack_exports__["default"] = (_Auth__WEBPACK_IMPORTED_MODULE_0__["Auth"]);
14811
14812
14813/***/ }),
14814
14815/***/ "./lib-esm/types/Auth.js":
14816/*!*******************************!*\
14817 !*** ./lib-esm/types/Auth.js ***!
14818 \*******************************/
14819/*! exports provided: CognitoHostedUIIdentityProvider, isFederatedSignInOptions, isFederatedSignInOptionsCustom, hasCustomState, isCognitoHostedOpts, AuthErrorTypes, isUsernamePasswordOpts, GRAPHQL_AUTH_MODE */
14820/***/ (function(module, __webpack_exports__, __webpack_require__) {
14821
14822"use strict";
14823__webpack_require__.r(__webpack_exports__);
14824/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoHostedUIIdentityProvider", function() { return CognitoHostedUIIdentityProvider; });
14825/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFederatedSignInOptions", function() { return isFederatedSignInOptions; });
14826/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFederatedSignInOptionsCustom", function() { return isFederatedSignInOptionsCustom; });
14827/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasCustomState", function() { return hasCustomState; });
14828/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCognitoHostedOpts", function() { return isCognitoHostedOpts; });
14829/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthErrorTypes", function() { return AuthErrorTypes; });
14830/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isUsernamePasswordOpts", function() { return isUsernamePasswordOpts; });
14831/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GRAPHQL_AUTH_MODE", function() { return GRAPHQL_AUTH_MODE; });
14832/*
14833 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14834 *
14835 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14836 * the License. A copy of the License is located at
14837 *
14838 * http://aws.amazon.com/apache2.0/
14839 *
14840 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14841 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14842 * and limitations under the License.
14843 */
14844var CognitoHostedUIIdentityProvider;
14845
14846(function (CognitoHostedUIIdentityProvider) {
14847 CognitoHostedUIIdentityProvider["Cognito"] = "COGNITO";
14848 CognitoHostedUIIdentityProvider["Google"] = "Google";
14849 CognitoHostedUIIdentityProvider["Facebook"] = "Facebook";
14850 CognitoHostedUIIdentityProvider["Amazon"] = "LoginWithAmazon";
14851 CognitoHostedUIIdentityProvider["Apple"] = "SignInWithApple";
14852})(CognitoHostedUIIdentityProvider || (CognitoHostedUIIdentityProvider = {}));
14853
14854function isFederatedSignInOptions(obj) {
14855 var keys = ['provider'];
14856 return obj && !!keys.find(function (k) {
14857 return obj.hasOwnProperty(k);
14858 });
14859}
14860function isFederatedSignInOptionsCustom(obj) {
14861 var keys = ['customProvider'];
14862 return obj && !!keys.find(function (k) {
14863 return obj.hasOwnProperty(k);
14864 });
14865}
14866function hasCustomState(obj) {
14867 var keys = ['customState'];
14868 return obj && !!keys.find(function (k) {
14869 return obj.hasOwnProperty(k);
14870 });
14871}
14872function isCognitoHostedOpts(oauth) {
14873 return oauth.redirectSignIn !== undefined;
14874}
14875var AuthErrorTypes;
14876
14877(function (AuthErrorTypes) {
14878 AuthErrorTypes["NoConfig"] = "noConfig";
14879 AuthErrorTypes["MissingAuthConfig"] = "missingAuthConfig";
14880 AuthErrorTypes["EmptyUsername"] = "emptyUsername";
14881 AuthErrorTypes["InvalidUsername"] = "invalidUsername";
14882 AuthErrorTypes["EmptyPassword"] = "emptyPassword";
14883 AuthErrorTypes["EmptyCode"] = "emptyCode";
14884 AuthErrorTypes["SignUpError"] = "signUpError";
14885 AuthErrorTypes["NoMFA"] = "noMFA";
14886 AuthErrorTypes["InvalidMFA"] = "invalidMFA";
14887 AuthErrorTypes["EmptyChallengeResponse"] = "emptyChallengeResponse";
14888 AuthErrorTypes["NoUserSession"] = "noUserSession";
14889 AuthErrorTypes["Default"] = "default";
14890 AuthErrorTypes["DeviceConfig"] = "deviceConfig";
14891 AuthErrorTypes["NetworkError"] = "networkError";
14892})(AuthErrorTypes || (AuthErrorTypes = {}));
14893
14894function isUsernamePasswordOpts(obj) {
14895 return !!obj.username;
14896}
14897var GRAPHQL_AUTH_MODE;
14898
14899(function (GRAPHQL_AUTH_MODE) {
14900 GRAPHQL_AUTH_MODE["API_KEY"] = "API_KEY";
14901 GRAPHQL_AUTH_MODE["AWS_IAM"] = "AWS_IAM";
14902 GRAPHQL_AUTH_MODE["OPENID_CONNECT"] = "OPENID_CONNECT";
14903 GRAPHQL_AUTH_MODE["AMAZON_COGNITO_USER_POOLS"] = "AMAZON_COGNITO_USER_POOLS";
14904 GRAPHQL_AUTH_MODE["AWS_LAMBDA"] = "AWS_LAMBDA";
14905})(GRAPHQL_AUTH_MODE || (GRAPHQL_AUTH_MODE = {}));
14906
14907/***/ }),
14908
14909/***/ "./lib-esm/types/index.js":
14910/*!********************************!*\
14911 !*** ./lib-esm/types/index.js ***!
14912 \********************************/
14913/*! exports provided: CognitoHostedUIIdentityProvider, isFederatedSignInOptions, isFederatedSignInOptionsCustom, hasCustomState, isCognitoHostedOpts, AuthErrorTypes, isUsernamePasswordOpts, GRAPHQL_AUTH_MODE */
14914/***/ (function(module, __webpack_exports__, __webpack_require__) {
14915
14916"use strict";
14917__webpack_require__.r(__webpack_exports__);
14918/* harmony import */ var _Auth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Auth */ "./lib-esm/types/Auth.js");
14919/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CognitoHostedUIIdentityProvider", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["CognitoHostedUIIdentityProvider"]; });
14920
14921/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isFederatedSignInOptions", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptions"]; });
14922
14923/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isFederatedSignInOptionsCustom", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["isFederatedSignInOptionsCustom"]; });
14924
14925/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasCustomState", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["hasCustomState"]; });
14926
14927/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isCognitoHostedOpts", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["isCognitoHostedOpts"]; });
14928
14929/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthErrorTypes", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["AuthErrorTypes"]; });
14930
14931/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isUsernamePasswordOpts", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["isUsernamePasswordOpts"]; });
14932
14933/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GRAPHQL_AUTH_MODE", function() { return _Auth__WEBPACK_IMPORTED_MODULE_0__["GRAPHQL_AUTH_MODE"]; });
14934
14935/*
14936 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14937 *
14938 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14939 * the License. A copy of the License is located at
14940 *
14941 * http://aws.amazon.com/apache2.0/
14942 *
14943 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14944 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14945 * and limitations under the License.
14946 */
14947
14948
14949/***/ }),
14950
14951/***/ "./lib-esm/urlListener.js":
14952/*!********************************!*\
14953 !*** ./lib-esm/urlListener.js ***!
14954 \********************************/
14955/*! exports provided: default */
14956/***/ (function(module, __webpack_exports__, __webpack_require__) {
14957
14958"use strict";
14959__webpack_require__.r(__webpack_exports__);
14960/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
14961/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__);
14962/*
14963 * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
14964 *
14965 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
14966 * the License. A copy of the License is located at
14967 *
14968 * http://aws.amazon.com/apache2.0/
14969 *
14970 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14971 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
14972 * and limitations under the License.
14973 */
14974
14975/* harmony default export */ __webpack_exports__["default"] = (function (callback) {
14976 if (_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["JS"].browserOrNode().isBrowser && window.location) {
14977 var url = window.location.href;
14978 callback({
14979 url: url
14980 });
14981 } else if (_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["JS"].browserOrNode().isNode) {
14982 // continue building on ssr
14983 (function () {}); // noop
14984
14985 } else {
14986 throw new Error('Not supported');
14987 }
14988});
14989
14990/***/ }),
14991
14992/***/ "./node_modules/crypto-js/core.js":
14993/*!****************************************!*\
14994 !*** ./node_modules/crypto-js/core.js ***!
14995 \****************************************/
14996/*! no static exports found */
14997/***/ (function(module, exports, __webpack_require__) {
14998
14999/* WEBPACK VAR INJECTION */(function(global) {;(function (root, factory) {
15000 if (true) {
15001 // CommonJS
15002 module.exports = exports = factory();
15003 }
15004 else {}
15005}(this, function () {
15006
15007 /*globals window, global, require*/
15008
15009 /**
15010 * CryptoJS core components.
15011 */
15012 var CryptoJS = CryptoJS || (function (Math, undefined) {
15013
15014 var crypto;
15015
15016 // Native crypto from window (Browser)
15017 if (typeof window !== 'undefined' && window.crypto) {
15018 crypto = window.crypto;
15019 }
15020
15021 // Native crypto in web worker (Browser)
15022 if (typeof self !== 'undefined' && self.crypto) {
15023 crypto = self.crypto;
15024 }
15025
15026 // Native crypto from worker
15027 if (typeof globalThis !== 'undefined' && globalThis.crypto) {
15028 crypto = globalThis.crypto;
15029 }
15030
15031 // Native (experimental IE 11) crypto from window (Browser)
15032 if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
15033 crypto = window.msCrypto;
15034 }
15035
15036 // Native crypto from global (NodeJS)
15037 if (!crypto && typeof global !== 'undefined' && global.crypto) {
15038 crypto = global.crypto;
15039 }
15040
15041 // Native crypto import via require (NodeJS)
15042 if (!crypto && "function" === 'function') {
15043 try {
15044 crypto = __webpack_require__(/*! crypto */ 2);
15045 } catch (err) {}
15046 }
15047
15048 /*
15049 * Cryptographically secure pseudorandom number generator
15050 *
15051 * As Math.random() is cryptographically not safe to use
15052 */
15053 var cryptoSecureRandomInt = function () {
15054 if (crypto) {
15055 // Use getRandomValues method (Browser)
15056 if (typeof crypto.getRandomValues === 'function') {
15057 try {
15058 return crypto.getRandomValues(new Uint32Array(1))[0];
15059 } catch (err) {}
15060 }
15061
15062 // Use randomBytes method (NodeJS)
15063 if (typeof crypto.randomBytes === 'function') {
15064 try {
15065 return crypto.randomBytes(4).readInt32LE();
15066 } catch (err) {}
15067 }
15068 }
15069
15070 throw new Error('Native crypto module could not be used to get secure random number.');
15071 };
15072
15073 /*
15074 * Local polyfill of Object.create
15075
15076 */
15077 var create = Object.create || (function () {
15078 function F() {}
15079
15080 return function (obj) {
15081 var subtype;
15082
15083 F.prototype = obj;
15084
15085 subtype = new F();
15086
15087 F.prototype = null;
15088
15089 return subtype;
15090 };
15091 }());
15092
15093 /**
15094 * CryptoJS namespace.
15095 */
15096 var C = {};
15097
15098 /**
15099 * Library namespace.
15100 */
15101 var C_lib = C.lib = {};
15102
15103 /**
15104 * Base object for prototypal inheritance.
15105 */
15106 var Base = C_lib.Base = (function () {
15107
15108
15109 return {
15110 /**
15111 * Creates a new object that inherits from this object.
15112 *
15113 * @param {Object} overrides Properties to copy into the new object.
15114 *
15115 * @return {Object} The new object.
15116 *
15117 * @static
15118 *
15119 * @example
15120 *
15121 * var MyType = CryptoJS.lib.Base.extend({
15122 * field: 'value',
15123 *
15124 * method: function () {
15125 * }
15126 * });
15127 */
15128 extend: function (overrides) {
15129 // Spawn
15130 var subtype = create(this);
15131
15132 // Augment
15133 if (overrides) {
15134 subtype.mixIn(overrides);
15135 }
15136
15137 // Create default initializer
15138 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
15139 subtype.init = function () {
15140 subtype.$super.init.apply(this, arguments);
15141 };
15142 }
15143
15144 // Initializer's prototype is the subtype object
15145 subtype.init.prototype = subtype;
15146
15147 // Reference supertype
15148 subtype.$super = this;
15149
15150 return subtype;
15151 },
15152
15153 /**
15154 * Extends this object and runs the init method.
15155 * Arguments to create() will be passed to init().
15156 *
15157 * @return {Object} The new object.
15158 *
15159 * @static
15160 *
15161 * @example
15162 *
15163 * var instance = MyType.create();
15164 */
15165 create: function () {
15166 var instance = this.extend();
15167 instance.init.apply(instance, arguments);
15168
15169 return instance;
15170 },
15171
15172 /**
15173 * Initializes a newly created object.
15174 * Override this method to add some logic when your objects are created.
15175 *
15176 * @example
15177 *
15178 * var MyType = CryptoJS.lib.Base.extend({
15179 * init: function () {
15180 * // ...
15181 * }
15182 * });
15183 */
15184 init: function () {
15185 },
15186
15187 /**
15188 * Copies properties into this object.
15189 *
15190 * @param {Object} properties The properties to mix in.
15191 *
15192 * @example
15193 *
15194 * MyType.mixIn({
15195 * field: 'value'
15196 * });
15197 */
15198 mixIn: function (properties) {
15199 for (var propertyName in properties) {
15200 if (properties.hasOwnProperty(propertyName)) {
15201 this[propertyName] = properties[propertyName];
15202 }
15203 }
15204
15205 // IE won't copy toString using the loop above
15206 if (properties.hasOwnProperty('toString')) {
15207 this.toString = properties.toString;
15208 }
15209 },
15210
15211 /**
15212 * Creates a copy of this object.
15213 *
15214 * @return {Object} The clone.
15215 *
15216 * @example
15217 *
15218 * var clone = instance.clone();
15219 */
15220 clone: function () {
15221 return this.init.prototype.extend(this);
15222 }
15223 };
15224 }());
15225
15226 /**
15227 * An array of 32-bit words.
15228 *
15229 * @property {Array} words The array of 32-bit words.
15230 * @property {number} sigBytes The number of significant bytes in this word array.
15231 */
15232 var WordArray = C_lib.WordArray = Base.extend({
15233 /**
15234 * Initializes a newly created word array.
15235 *
15236 * @param {Array} words (Optional) An array of 32-bit words.
15237 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
15238 *
15239 * @example
15240 *
15241 * var wordArray = CryptoJS.lib.WordArray.create();
15242 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
15243 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
15244 */
15245 init: function (words, sigBytes) {
15246 words = this.words = words || [];
15247
15248 if (sigBytes != undefined) {
15249 this.sigBytes = sigBytes;
15250 } else {
15251 this.sigBytes = words.length * 4;
15252 }
15253 },
15254
15255 /**
15256 * Converts this word array to a string.
15257 *
15258 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
15259 *
15260 * @return {string} The stringified word array.
15261 *
15262 * @example
15263 *
15264 * var string = wordArray + '';
15265 * var string = wordArray.toString();
15266 * var string = wordArray.toString(CryptoJS.enc.Utf8);
15267 */
15268 toString: function (encoder) {
15269 return (encoder || Hex).stringify(this);
15270 },
15271
15272 /**
15273 * Concatenates a word array to this word array.
15274 *
15275 * @param {WordArray} wordArray The word array to append.
15276 *
15277 * @return {WordArray} This word array.
15278 *
15279 * @example
15280 *
15281 * wordArray1.concat(wordArray2);
15282 */
15283 concat: function (wordArray) {
15284 // Shortcuts
15285 var thisWords = this.words;
15286 var thatWords = wordArray.words;
15287 var thisSigBytes = this.sigBytes;
15288 var thatSigBytes = wordArray.sigBytes;
15289
15290 // Clamp excess bits
15291 this.clamp();
15292
15293 // Concat
15294 if (thisSigBytes % 4) {
15295 // Copy one byte at a time
15296 for (var i = 0; i < thatSigBytes; i++) {
15297 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
15298 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
15299 }
15300 } else {
15301 // Copy one word at a time
15302 for (var j = 0; j < thatSigBytes; j += 4) {
15303 thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
15304 }
15305 }
15306 this.sigBytes += thatSigBytes;
15307
15308 // Chainable
15309 return this;
15310 },
15311
15312 /**
15313 * Removes insignificant bits.
15314 *
15315 * @example
15316 *
15317 * wordArray.clamp();
15318 */
15319 clamp: function () {
15320 // Shortcuts
15321 var words = this.words;
15322 var sigBytes = this.sigBytes;
15323
15324 // Clamp
15325 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
15326 words.length = Math.ceil(sigBytes / 4);
15327 },
15328
15329 /**
15330 * Creates a copy of this word array.
15331 *
15332 * @return {WordArray} The clone.
15333 *
15334 * @example
15335 *
15336 * var clone = wordArray.clone();
15337 */
15338 clone: function () {
15339 var clone = Base.clone.call(this);
15340 clone.words = this.words.slice(0);
15341
15342 return clone;
15343 },
15344
15345 /**
15346 * Creates a word array filled with random bytes.
15347 *
15348 * @param {number} nBytes The number of random bytes to generate.
15349 *
15350 * @return {WordArray} The random word array.
15351 *
15352 * @static
15353 *
15354 * @example
15355 *
15356 * var wordArray = CryptoJS.lib.WordArray.random(16);
15357 */
15358 random: function (nBytes) {
15359 var words = [];
15360
15361 for (var i = 0; i < nBytes; i += 4) {
15362 words.push(cryptoSecureRandomInt());
15363 }
15364
15365 return new WordArray.init(words, nBytes);
15366 }
15367 });
15368
15369 /**
15370 * Encoder namespace.
15371 */
15372 var C_enc = C.enc = {};
15373
15374 /**
15375 * Hex encoding strategy.
15376 */
15377 var Hex = C_enc.Hex = {
15378 /**
15379 * Converts a word array to a hex string.
15380 *
15381 * @param {WordArray} wordArray The word array.
15382 *
15383 * @return {string} The hex string.
15384 *
15385 * @static
15386 *
15387 * @example
15388 *
15389 * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
15390 */
15391 stringify: function (wordArray) {
15392 // Shortcuts
15393 var words = wordArray.words;
15394 var sigBytes = wordArray.sigBytes;
15395
15396 // Convert
15397 var hexChars = [];
15398 for (var i = 0; i < sigBytes; i++) {
15399 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
15400 hexChars.push((bite >>> 4).toString(16));
15401 hexChars.push((bite & 0x0f).toString(16));
15402 }
15403
15404 return hexChars.join('');
15405 },
15406
15407 /**
15408 * Converts a hex string to a word array.
15409 *
15410 * @param {string} hexStr The hex string.
15411 *
15412 * @return {WordArray} The word array.
15413 *
15414 * @static
15415 *
15416 * @example
15417 *
15418 * var wordArray = CryptoJS.enc.Hex.parse(hexString);
15419 */
15420 parse: function (hexStr) {
15421 // Shortcut
15422 var hexStrLength = hexStr.length;
15423
15424 // Convert
15425 var words = [];
15426 for (var i = 0; i < hexStrLength; i += 2) {
15427 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
15428 }
15429
15430 return new WordArray.init(words, hexStrLength / 2);
15431 }
15432 };
15433
15434 /**
15435 * Latin1 encoding strategy.
15436 */
15437 var Latin1 = C_enc.Latin1 = {
15438 /**
15439 * Converts a word array to a Latin1 string.
15440 *
15441 * @param {WordArray} wordArray The word array.
15442 *
15443 * @return {string} The Latin1 string.
15444 *
15445 * @static
15446 *
15447 * @example
15448 *
15449 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
15450 */
15451 stringify: function (wordArray) {
15452 // Shortcuts
15453 var words = wordArray.words;
15454 var sigBytes = wordArray.sigBytes;
15455
15456 // Convert
15457 var latin1Chars = [];
15458 for (var i = 0; i < sigBytes; i++) {
15459 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
15460 latin1Chars.push(String.fromCharCode(bite));
15461 }
15462
15463 return latin1Chars.join('');
15464 },
15465
15466 /**
15467 * Converts a Latin1 string to a word array.
15468 *
15469 * @param {string} latin1Str The Latin1 string.
15470 *
15471 * @return {WordArray} The word array.
15472 *
15473 * @static
15474 *
15475 * @example
15476 *
15477 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
15478 */
15479 parse: function (latin1Str) {
15480 // Shortcut
15481 var latin1StrLength = latin1Str.length;
15482
15483 // Convert
15484 var words = [];
15485 for (var i = 0; i < latin1StrLength; i++) {
15486 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
15487 }
15488
15489 return new WordArray.init(words, latin1StrLength);
15490 }
15491 };
15492
15493 /**
15494 * UTF-8 encoding strategy.
15495 */
15496 var Utf8 = C_enc.Utf8 = {
15497 /**
15498 * Converts a word array to a UTF-8 string.
15499 *
15500 * @param {WordArray} wordArray The word array.
15501 *
15502 * @return {string} The UTF-8 string.
15503 *
15504 * @static
15505 *
15506 * @example
15507 *
15508 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
15509 */
15510 stringify: function (wordArray) {
15511 try {
15512 return decodeURIComponent(escape(Latin1.stringify(wordArray)));
15513 } catch (e) {
15514 throw new Error('Malformed UTF-8 data');
15515 }
15516 },
15517
15518 /**
15519 * Converts a UTF-8 string to a word array.
15520 *
15521 * @param {string} utf8Str The UTF-8 string.
15522 *
15523 * @return {WordArray} The word array.
15524 *
15525 * @static
15526 *
15527 * @example
15528 *
15529 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
15530 */
15531 parse: function (utf8Str) {
15532 return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
15533 }
15534 };
15535
15536 /**
15537 * Abstract buffered block algorithm template.
15538 *
15539 * The property blockSize must be implemented in a concrete subtype.
15540 *
15541 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
15542 */
15543 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
15544 /**
15545 * Resets this block algorithm's data buffer to its initial state.
15546 *
15547 * @example
15548 *
15549 * bufferedBlockAlgorithm.reset();
15550 */
15551 reset: function () {
15552 // Initial values
15553 this._data = new WordArray.init();
15554 this._nDataBytes = 0;
15555 },
15556
15557 /**
15558 * Adds new data to this block algorithm's buffer.
15559 *
15560 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
15561 *
15562 * @example
15563 *
15564 * bufferedBlockAlgorithm._append('data');
15565 * bufferedBlockAlgorithm._append(wordArray);
15566 */
15567 _append: function (data) {
15568 // Convert string to WordArray, else assume WordArray already
15569 if (typeof data == 'string') {
15570 data = Utf8.parse(data);
15571 }
15572
15573 // Append
15574 this._data.concat(data);
15575 this._nDataBytes += data.sigBytes;
15576 },
15577
15578 /**
15579 * Processes available data blocks.
15580 *
15581 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
15582 *
15583 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
15584 *
15585 * @return {WordArray} The processed data.
15586 *
15587 * @example
15588 *
15589 * var processedData = bufferedBlockAlgorithm._process();
15590 * var processedData = bufferedBlockAlgorithm._process(!!'flush');
15591 */
15592 _process: function (doFlush) {
15593 var processedWords;
15594
15595 // Shortcuts
15596 var data = this._data;
15597 var dataWords = data.words;
15598 var dataSigBytes = data.sigBytes;
15599 var blockSize = this.blockSize;
15600 var blockSizeBytes = blockSize * 4;
15601
15602 // Count blocks ready
15603 var nBlocksReady = dataSigBytes / blockSizeBytes;
15604 if (doFlush) {
15605 // Round up to include partial blocks
15606 nBlocksReady = Math.ceil(nBlocksReady);
15607 } else {
15608 // Round down to include only full blocks,
15609 // less the number of blocks that must remain in the buffer
15610 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
15611 }
15612
15613 // Count words ready
15614 var nWordsReady = nBlocksReady * blockSize;
15615
15616 // Count bytes ready
15617 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
15618
15619 // Process blocks
15620 if (nWordsReady) {
15621 for (var offset = 0; offset < nWordsReady; offset += blockSize) {
15622 // Perform concrete-algorithm logic
15623 this._doProcessBlock(dataWords, offset);
15624 }
15625
15626 // Remove processed words
15627 processedWords = dataWords.splice(0, nWordsReady);
15628 data.sigBytes -= nBytesReady;
15629 }
15630
15631 // Return processed words
15632 return new WordArray.init(processedWords, nBytesReady);
15633 },
15634
15635 /**
15636 * Creates a copy of this object.
15637 *
15638 * @return {Object} The clone.
15639 *
15640 * @example
15641 *
15642 * var clone = bufferedBlockAlgorithm.clone();
15643 */
15644 clone: function () {
15645 var clone = Base.clone.call(this);
15646 clone._data = this._data.clone();
15647
15648 return clone;
15649 },
15650
15651 _minBufferSize: 0
15652 });
15653
15654 /**
15655 * Abstract hasher template.
15656 *
15657 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
15658 */
15659 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
15660 /**
15661 * Configuration options.
15662 */
15663 cfg: Base.extend(),
15664
15665 /**
15666 * Initializes a newly created hasher.
15667 *
15668 * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
15669 *
15670 * @example
15671 *
15672 * var hasher = CryptoJS.algo.SHA256.create();
15673 */
15674 init: function (cfg) {
15675 // Apply config defaults
15676 this.cfg = this.cfg.extend(cfg);
15677
15678 // Set initial values
15679 this.reset();
15680 },
15681
15682 /**
15683 * Resets this hasher to its initial state.
15684 *
15685 * @example
15686 *
15687 * hasher.reset();
15688 */
15689 reset: function () {
15690 // Reset data buffer
15691 BufferedBlockAlgorithm.reset.call(this);
15692
15693 // Perform concrete-hasher logic
15694 this._doReset();
15695 },
15696
15697 /**
15698 * Updates this hasher with a message.
15699 *
15700 * @param {WordArray|string} messageUpdate The message to append.
15701 *
15702 * @return {Hasher} This hasher.
15703 *
15704 * @example
15705 *
15706 * hasher.update('message');
15707 * hasher.update(wordArray);
15708 */
15709 update: function (messageUpdate) {
15710 // Append
15711 this._append(messageUpdate);
15712
15713 // Update the hash
15714 this._process();
15715
15716 // Chainable
15717 return this;
15718 },
15719
15720 /**
15721 * Finalizes the hash computation.
15722 * Note that the finalize operation is effectively a destructive, read-once operation.
15723 *
15724 * @param {WordArray|string} messageUpdate (Optional) A final message update.
15725 *
15726 * @return {WordArray} The hash.
15727 *
15728 * @example
15729 *
15730 * var hash = hasher.finalize();
15731 * var hash = hasher.finalize('message');
15732 * var hash = hasher.finalize(wordArray);
15733 */
15734 finalize: function (messageUpdate) {
15735 // Final message update
15736 if (messageUpdate) {
15737 this._append(messageUpdate);
15738 }
15739
15740 // Perform concrete-hasher logic
15741 var hash = this._doFinalize();
15742
15743 return hash;
15744 },
15745
15746 blockSize: 512/32,
15747
15748 /**
15749 * Creates a shortcut function to a hasher's object interface.
15750 *
15751 * @param {Hasher} hasher The hasher to create a helper for.
15752 *
15753 * @return {Function} The shortcut function.
15754 *
15755 * @static
15756 *
15757 * @example
15758 *
15759 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
15760 */
15761 _createHelper: function (hasher) {
15762 return function (message, cfg) {
15763 return new hasher.init(cfg).finalize(message);
15764 };
15765 },
15766
15767 /**
15768 * Creates a shortcut function to the HMAC's object interface.
15769 *
15770 * @param {Hasher} hasher The hasher to use in this HMAC helper.
15771 *
15772 * @return {Function} The shortcut function.
15773 *
15774 * @static
15775 *
15776 * @example
15777 *
15778 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
15779 */
15780 _createHmacHelper: function (hasher) {
15781 return function (message, key) {
15782 return new C_algo.HMAC.init(hasher, key).finalize(message);
15783 };
15784 }
15785 });
15786
15787 /**
15788 * Algorithm namespace.
15789 */
15790 var C_algo = C.algo = {};
15791
15792 return C;
15793 }(Math));
15794
15795
15796 return CryptoJS;
15797
15798}));
15799/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
15800
15801/***/ }),
15802
15803/***/ "./node_modules/crypto-js/enc-base64.js":
15804/*!**********************************************!*\
15805 !*** ./node_modules/crypto-js/enc-base64.js ***!
15806 \**********************************************/
15807/*! no static exports found */
15808/***/ (function(module, exports, __webpack_require__) {
15809
15810;(function (root, factory) {
15811 if (true) {
15812 // CommonJS
15813 module.exports = exports = factory(__webpack_require__(/*! ./core */ "./node_modules/crypto-js/core.js"));
15814 }
15815 else {}
15816}(this, function (CryptoJS) {
15817
15818 (function () {
15819 // Shortcuts
15820 var C = CryptoJS;
15821 var C_lib = C.lib;
15822 var WordArray = C_lib.WordArray;
15823 var C_enc = C.enc;
15824
15825 /**
15826 * Base64 encoding strategy.
15827 */
15828 var Base64 = C_enc.Base64 = {
15829 /**
15830 * Converts a word array to a Base64 string.
15831 *
15832 * @param {WordArray} wordArray The word array.
15833 *
15834 * @return {string} The Base64 string.
15835 *
15836 * @static
15837 *
15838 * @example
15839 *
15840 * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
15841 */
15842 stringify: function (wordArray) {
15843 // Shortcuts
15844 var words = wordArray.words;
15845 var sigBytes = wordArray.sigBytes;
15846 var map = this._map;
15847
15848 // Clamp excess bits
15849 wordArray.clamp();
15850
15851 // Convert
15852 var base64Chars = [];
15853 for (var i = 0; i < sigBytes; i += 3) {
15854 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
15855 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
15856 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
15857
15858 var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
15859
15860 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
15861 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
15862 }
15863 }
15864
15865 // Add padding
15866 var paddingChar = map.charAt(64);
15867 if (paddingChar) {
15868 while (base64Chars.length % 4) {
15869 base64Chars.push(paddingChar);
15870 }
15871 }
15872
15873 return base64Chars.join('');
15874 },
15875
15876 /**
15877 * Converts a Base64 string to a word array.
15878 *
15879 * @param {string} base64Str The Base64 string.
15880 *
15881 * @return {WordArray} The word array.
15882 *
15883 * @static
15884 *
15885 * @example
15886 *
15887 * var wordArray = CryptoJS.enc.Base64.parse(base64String);
15888 */
15889 parse: function (base64Str) {
15890 // Shortcuts
15891 var base64StrLength = base64Str.length;
15892 var map = this._map;
15893 var reverseMap = this._reverseMap;
15894
15895 if (!reverseMap) {
15896 reverseMap = this._reverseMap = [];
15897 for (var j = 0; j < map.length; j++) {
15898 reverseMap[map.charCodeAt(j)] = j;
15899 }
15900 }
15901
15902 // Ignore padding
15903 var paddingChar = map.charAt(64);
15904 if (paddingChar) {
15905 var paddingIndex = base64Str.indexOf(paddingChar);
15906 if (paddingIndex !== -1) {
15907 base64StrLength = paddingIndex;
15908 }
15909 }
15910
15911 // Convert
15912 return parseLoop(base64Str, base64StrLength, reverseMap);
15913
15914 },
15915
15916 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
15917 };
15918
15919 function parseLoop(base64Str, base64StrLength, reverseMap) {
15920 var words = [];
15921 var nBytes = 0;
15922 for (var i = 0; i < base64StrLength; i++) {
15923 if (i % 4) {
15924 var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
15925 var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
15926 var bitsCombined = bits1 | bits2;
15927 words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
15928 nBytes++;
15929 }
15930 }
15931 return WordArray.create(words, nBytes);
15932 }
15933 }());
15934
15935
15936 return CryptoJS.enc.Base64;
15937
15938}));
15939
15940/***/ }),
15941
15942/***/ "./node_modules/crypto-js/sha256.js":
15943/*!******************************************!*\
15944 !*** ./node_modules/crypto-js/sha256.js ***!
15945 \******************************************/
15946/*! no static exports found */
15947/***/ (function(module, exports, __webpack_require__) {
15948
15949;(function (root, factory) {
15950 if (true) {
15951 // CommonJS
15952 module.exports = exports = factory(__webpack_require__(/*! ./core */ "./node_modules/crypto-js/core.js"));
15953 }
15954 else {}
15955}(this, function (CryptoJS) {
15956
15957 (function (Math) {
15958 // Shortcuts
15959 var C = CryptoJS;
15960 var C_lib = C.lib;
15961 var WordArray = C_lib.WordArray;
15962 var Hasher = C_lib.Hasher;
15963 var C_algo = C.algo;
15964
15965 // Initialization and round constants tables
15966 var H = [];
15967 var K = [];
15968
15969 // Compute constants
15970 (function () {
15971 function isPrime(n) {
15972 var sqrtN = Math.sqrt(n);
15973 for (var factor = 2; factor <= sqrtN; factor++) {
15974 if (!(n % factor)) {
15975 return false;
15976 }
15977 }
15978
15979 return true;
15980 }
15981
15982 function getFractionalBits(n) {
15983 return ((n - (n | 0)) * 0x100000000) | 0;
15984 }
15985
15986 var n = 2;
15987 var nPrime = 0;
15988 while (nPrime < 64) {
15989 if (isPrime(n)) {
15990 if (nPrime < 8) {
15991 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
15992 }
15993 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
15994
15995 nPrime++;
15996 }
15997
15998 n++;
15999 }
16000 }());
16001
16002 // Reusable object
16003 var W = [];
16004
16005 /**
16006 * SHA-256 hash algorithm.
16007 */
16008 var SHA256 = C_algo.SHA256 = Hasher.extend({
16009 _doReset: function () {
16010 this._hash = new WordArray.init(H.slice(0));
16011 },
16012
16013 _doProcessBlock: function (M, offset) {
16014 // Shortcut
16015 var H = this._hash.words;
16016
16017 // Working variables
16018 var a = H[0];
16019 var b = H[1];
16020 var c = H[2];
16021 var d = H[3];
16022 var e = H[4];
16023 var f = H[5];
16024 var g = H[6];
16025 var h = H[7];
16026
16027 // Computation
16028 for (var i = 0; i < 64; i++) {
16029 if (i < 16) {
16030 W[i] = M[offset + i] | 0;
16031 } else {
16032 var gamma0x = W[i - 15];
16033 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
16034 ((gamma0x << 14) | (gamma0x >>> 18)) ^
16035 (gamma0x >>> 3);
16036
16037 var gamma1x = W[i - 2];
16038 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
16039 ((gamma1x << 13) | (gamma1x >>> 19)) ^
16040 (gamma1x >>> 10);
16041
16042 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
16043 }
16044
16045 var ch = (e & f) ^ (~e & g);
16046 var maj = (a & b) ^ (a & c) ^ (b & c);
16047
16048 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
16049 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
16050
16051 var t1 = h + sigma1 + ch + K[i] + W[i];
16052 var t2 = sigma0 + maj;
16053
16054 h = g;
16055 g = f;
16056 f = e;
16057 e = (d + t1) | 0;
16058 d = c;
16059 c = b;
16060 b = a;
16061 a = (t1 + t2) | 0;
16062 }
16063
16064 // Intermediate hash value
16065 H[0] = (H[0] + a) | 0;
16066 H[1] = (H[1] + b) | 0;
16067 H[2] = (H[2] + c) | 0;
16068 H[3] = (H[3] + d) | 0;
16069 H[4] = (H[4] + e) | 0;
16070 H[5] = (H[5] + f) | 0;
16071 H[6] = (H[6] + g) | 0;
16072 H[7] = (H[7] + h) | 0;
16073 },
16074
16075 _doFinalize: function () {
16076 // Shortcuts
16077 var data = this._data;
16078 var dataWords = data.words;
16079
16080 var nBitsTotal = this._nDataBytes * 8;
16081 var nBitsLeft = data.sigBytes * 8;
16082
16083 // Add padding
16084 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
16085 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
16086 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
16087 data.sigBytes = dataWords.length * 4;
16088
16089 // Hash final blocks
16090 this._process();
16091
16092 // Return final computed hash
16093 return this._hash;
16094 },
16095
16096 clone: function () {
16097 var clone = Hasher.clone.call(this);
16098 clone._hash = this._hash.clone();
16099
16100 return clone;
16101 }
16102 });
16103
16104 /**
16105 * Shortcut function to the hasher's object interface.
16106 *
16107 * @param {WordArray|string} message The message to hash.
16108 *
16109 * @return {WordArray} The hash.
16110 *
16111 * @static
16112 *
16113 * @example
16114 *
16115 * var hash = CryptoJS.SHA256('message');
16116 * var hash = CryptoJS.SHA256(wordArray);
16117 */
16118 C.SHA256 = Hasher._createHelper(SHA256);
16119
16120 /**
16121 * Shortcut function to the HMAC's object interface.
16122 *
16123 * @param {WordArray|string} message The message to hash.
16124 * @param {WordArray|string} key The secret key.
16125 *
16126 * @return {WordArray} The HMAC.
16127 *
16128 * @static
16129 *
16130 * @example
16131 *
16132 * var hmac = CryptoJS.HmacSHA256(message, key);
16133 */
16134 C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
16135 }(Math));
16136
16137
16138 return CryptoJS.SHA256;
16139
16140}));
16141
16142/***/ }),
16143
16144/***/ 0:
16145/*!************************!*\
16146 !*** crypto (ignored) ***!
16147 \************************/
16148/*! no static exports found */
16149/***/ (function(module, exports) {
16150
16151/* (ignored) */
16152
16153/***/ }),
16154
16155/***/ 1:
16156/*!************************!*\
16157 !*** crypto (ignored) ***!
16158 \************************/
16159/*! no static exports found */
16160/***/ (function(module, exports) {
16161
16162/* (ignored) */
16163
16164/***/ }),
16165
16166/***/ 2:
16167/*!************************!*\
16168 !*** crypto (ignored) ***!
16169 \************************/
16170/*! no static exports found */
16171/***/ (function(module, exports) {
16172
16173/* (ignored) */
16174
16175/***/ }),
16176
16177/***/ "@aws-amplify/core":
16178/*!***********************************!*\
16179 !*** external "aws_amplify_core" ***!
16180 \***********************************/
16181/*! no static exports found */
16182/***/ (function(module, exports) {
16183
16184module.exports = __WEBPACK_EXTERNAL_MODULE__aws_amplify_core__;
16185
16186/***/ })
16187
16188/******/ });
16189});
16190//# sourceMappingURL=aws-amplify-auth.js.map
\No newline at end of file