UNPKG

213 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (global.bearer = factory());
5}(this, (function () { 'use strict';
6
7 /*! *****************************************************************************
8 Copyright (c) Microsoft Corporation. All rights reserved.
9 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
10 this file except in compliance with the License. You may obtain a copy of the
11 License at http://www.apache.org/licenses/LICENSE-2.0
12
13 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
15 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
16 MERCHANTABLITY OR NON-INFRINGEMENT.
17
18 See the Apache Version 2.0 License for specific language governing permissions
19 and limitations under the License.
20 ***************************************************************************** */
21
22 function __rest(s, e) {
23 var t = {};
24 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
25 t[p] = s[p];
26 if (s != null && typeof Object.getOwnPropertySymbols === "function")
27 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
28 t[p[i]] = s[p[i]];
29 return t;
30 }
31
32 function __awaiter(thisArg, _arguments, P, generator) {
33 return new (P || (P = Promise))(function (resolve, reject) {
34 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
35 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
36 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
37 step((generator = generator.apply(thisArg, _arguments || [])).next());
38 });
39 }
40
41 /**
42 * Returns a function, that, as long as it continues to be invoked, will not
43 * be triggered. The function will be called after it stops being called for
44 * N milliseconds. If `immediate` is passed, trigger the function on the
45 * leading edge, instead of the trailing. The function also has a property 'clear'
46 * that is a function which will clear the timer to prevent previously scheduled executions.
47 *
48 * @source underscore.js
49 * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
50 * @param {Function} function to wrap
51 * @param {Number} timeout in ms (`100`)
52 * @param {Boolean} whether to execute at the beginning (`false`)
53 * @api public
54 */
55 function debounce(func, wait, immediate){
56 var timeout, args, context, timestamp, result;
57 if (null == wait) wait = 100;
58
59 function later() {
60 var last = Date.now() - timestamp;
61
62 if (last < wait && last >= 0) {
63 timeout = setTimeout(later, wait - last);
64 } else {
65 timeout = null;
66 if (!immediate) {
67 result = func.apply(context, args);
68 context = args = null;
69 }
70 }
71 }
72 var debounced = function(){
73 context = this;
74 args = arguments;
75 timestamp = Date.now();
76 var callNow = immediate && !timeout;
77 if (!timeout) timeout = setTimeout(later, wait);
78 if (callNow) {
79 result = func.apply(context, args);
80 context = args = null;
81 }
82
83 return result;
84 };
85
86 debounced.clear = function() {
87 if (timeout) {
88 clearTimeout(timeout);
89 timeout = null;
90 }
91 };
92
93 debounced.flush = function() {
94 if (timeout) {
95 result = func.apply(context, args);
96 context = args = null;
97
98 clearTimeout(timeout);
99 timeout = null;
100 }
101 };
102
103 return debounced;
104 }
105 // Adds compatibility for ES modules
106 debounce.debounce = debounce;
107
108 var debounce_1 = debounce;
109
110 var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
111
112 function unwrapExports (x) {
113 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
114 }
115
116 function createCommonjsModule(fn, module) {
117 return module = { exports: {} }, fn(module, module.exports), module.exports;
118 }
119
120 var postRobot = createCommonjsModule(function (module, exports) {
121 !function(root, factory) {
122 module.exports = factory();
123 }("undefined" != typeof self ? self : commonjsGlobal, function() {
124 return function(modules) {
125 var installedModules = {};
126 function __webpack_require__(moduleId) {
127 if (installedModules[moduleId]) return installedModules[moduleId].exports;
128 var module = installedModules[moduleId] = {
129 i: moduleId,
130 l: !1,
131 exports: {}
132 };
133 modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
134 module.l = !0;
135 return module.exports;
136 }
137 __webpack_require__.m = modules;
138 __webpack_require__.c = installedModules;
139 __webpack_require__.d = function(exports, name, getter) {
140 __webpack_require__.o(exports, name) || Object.defineProperty(exports, name, {
141 configurable: !1,
142 enumerable: !0,
143 get: getter
144 });
145 };
146 __webpack_require__.n = function(module) {
147 var getter = module && module.__esModule ? function() {
148 return module.default;
149 } : function() {
150 return module;
151 };
152 __webpack_require__.d(getter, "a", getter);
153 return getter;
154 };
155 __webpack_require__.o = function(object, property) {
156 return Object.prototype.hasOwnProperty.call(object, property);
157 };
158 __webpack_require__.p = "";
159 return __webpack_require__(__webpack_require__.s = "./src/index.js");
160 }({
161 "./node_modules/cross-domain-utils/src/constants.js": function(module, __webpack_exports__, __webpack_require__) {
162 __webpack_require__.d(__webpack_exports__, "a", function() {
163 return PROTOCOL;
164 });
165 __webpack_require__.d(__webpack_exports__, "b", function() {
166 return WILDCARD;
167 });
168 var PROTOCOL = {
169 MOCK: "mock:",
170 FILE: "file:",
171 ABOUT: "about:"
172 }, WILDCARD = "*";
173 },
174 "./node_modules/cross-domain-utils/src/index.js": function(module, __webpack_exports__, __webpack_require__) {
175 var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__("./node_modules/cross-domain-utils/src/utils.js");
176 __webpack_require__.d(__webpack_exports__, "getActualDomain", function() {
177 return __WEBPACK_IMPORTED_MODULE_0__utils__.a;
178 });
179 __webpack_require__.d(__webpack_exports__, "getAncestor", function() {
180 return __WEBPACK_IMPORTED_MODULE_0__utils__.b;
181 });
182 __webpack_require__.d(__webpack_exports__, "getDomain", function() {
183 return __WEBPACK_IMPORTED_MODULE_0__utils__.c;
184 });
185 __webpack_require__.d(__webpack_exports__, "getUserAgent", function() {
186 return __WEBPACK_IMPORTED_MODULE_0__utils__.d;
187 });
188 __webpack_require__.d(__webpack_exports__, "isActuallySameDomain", function() {
189 return __WEBPACK_IMPORTED_MODULE_0__utils__.e;
190 });
191 __webpack_require__.d(__webpack_exports__, "isAncestor", function() {
192 return __WEBPACK_IMPORTED_MODULE_0__utils__.f;
193 });
194 __webpack_require__.d(__webpack_exports__, "isIframe", function() {
195 return __WEBPACK_IMPORTED_MODULE_0__utils__.g;
196 });
197 __webpack_require__.d(__webpack_exports__, "isPopup", function() {
198 return __WEBPACK_IMPORTED_MODULE_0__utils__.h;
199 });
200 __webpack_require__.d(__webpack_exports__, "isWindow", function() {
201 return __WEBPACK_IMPORTED_MODULE_0__utils__.i;
202 });
203 __webpack_require__.d(__webpack_exports__, "isWindowClosed", function() {
204 return __WEBPACK_IMPORTED_MODULE_0__utils__.j;
205 });
206 __webpack_require__.d(__webpack_exports__, "matchDomain", function() {
207 return __WEBPACK_IMPORTED_MODULE_0__utils__.k;
208 });
209 __webpack_require__.d(__webpack_exports__, "stringifyDomainPattern", function() {
210 return __WEBPACK_IMPORTED_MODULE_0__utils__.l;
211 });
212 var __WEBPACK_IMPORTED_MODULE_1__types__ = __webpack_require__("./node_modules/cross-domain-utils/src/types.js");
213 __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__types__), __webpack_require__("./node_modules/cross-domain-utils/src/constants.js");
214 },
215 "./node_modules/cross-domain-utils/src/types.js": function(module, exports) {},
216 "./node_modules/cross-domain-utils/src/utils.js": function(module, __webpack_exports__, __webpack_require__) {
217 function isRegex(item) {
218 return "[object RegExp]" === Object.prototype.toString.call(item);
219 }
220 var constants = __webpack_require__("./node_modules/cross-domain-utils/src/constants.js");
221 __webpack_exports__.a = getActualDomain;
222 __webpack_exports__.c = getDomain;
223 __webpack_exports__.e = isActuallySameDomain;
224 __webpack_exports__.j = function(win) {
225 var allowMock = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1];
226 try {
227 if (win === window) return !1;
228 } catch (err) {
229 return !0;
230 }
231 try {
232 if (!win) return !0;
233 } catch (err) {
234 return !0;
235 }
236 try {
237 if (win.closed) return !0;
238 } catch (err) {
239 return !err || err.message !== IE_WIN_ACCESS_ERROR;
240 }
241 if (allowMock && function(win) {
242 if (!isActuallySameDomain(win)) return !1;
243 try {
244 if (win === window) return !0;
245 if (isAboutProtocol(win) && canReadFromWindow(win)) return !0;
246 if (getDomain(window) === getDomain(win)) return !0;
247 } catch (err) {}
248 return !1;
249 }(win)) try {
250 if (win.mockclosed) return !0;
251 } catch (err) {}
252 try {
253 if (!win.parent || !win.top) return !0;
254 } catch (err) {}
255 var iframeIndex = function(collection, item) {
256 for (var i = 0; i < collection.length; i++) try {
257 if (collection[i] === item) return i;
258 } catch (err) {}
259 return -1;
260 }(iframeWindows, win);
261 if (-1 !== iframeIndex) {
262 var frame = iframeFrames[iframeIndex];
263 if (frame && function(frame) {
264 if (!frame.contentWindow) return !0;
265 if (!frame.parentNode) return !0;
266 var doc = frame.ownerDocument;
267 return !(!doc || !doc.documentElement || doc.documentElement.contains(frame));
268 }(frame)) return !0;
269 }
270 return !1;
271 };
272 __webpack_exports__.d = function(win) {
273 return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent;
274 };
275 __webpack_exports__.b = getAncestor;
276 __webpack_exports__.f = function(parent, child) {
277 var actualParent = getAncestor(child);
278 if (actualParent) return actualParent === parent;
279 if (child === parent) return !1;
280 if (function(win) {
281 if (win) {
282 try {
283 if (win.top) return win.top;
284 } catch (err) {}
285 if (getParent(win) === win) return win;
286 try {
287 if (isAncestorParent(window, win) && window.top) return window.top;
288 } catch (err) {}
289 try {
290 if (isAncestorParent(win, window) && window.top) return window.top;
291 } catch (err) {}
292 for (var _i7 = 0, _getAllChildFrames4 = function getAllChildFrames(win) {
293 for (var result = [], _i3 = 0, _getFrames2 = getFrames(win), _length2 = null == _getFrames2 ? 0 : _getFrames2.length; _i3 < _length2; _i3++) {
294 var frame = _getFrames2[_i3];
295 result.push(frame);
296 for (var _i5 = 0, _getAllChildFrames2 = getAllChildFrames(frame), _length4 = null == _getAllChildFrames2 ? 0 : _getAllChildFrames2.length; _i5 < _length4; _i5++) {
297 var childFrame = _getAllChildFrames2[_i5];
298 result.push(childFrame);
299 }
300 }
301 return result;
302 }(win), _length6 = null == _getAllChildFrames4 ? 0 : _getAllChildFrames4.length; _i7 < _length6; _i7++) {
303 var frame = _getAllChildFrames4[_i7];
304 try {
305 if (frame.top) return frame.top;
306 } catch (err) {}
307 if (getParent(frame) === frame) return frame;
308 }
309 }
310 }(child) === child) return !1;
311 for (var _i15 = 0, _getFrames8 = getFrames(parent), _length14 = null == _getFrames8 ? 0 : _getFrames8.length; _i15 < _length14; _i15++) if (_getFrames8[_i15] === child) return !0;
312 return !1;
313 };
314 __webpack_exports__.h = function() {
315 return Boolean(getOpener(window));
316 };
317 __webpack_exports__.g = function() {
318 return Boolean(getParent(window));
319 };
320 __webpack_exports__.k = function matchDomain(pattern, origin) {
321 if ("string" == typeof pattern) {
322 if ("string" == typeof origin) return pattern === constants.b || origin === pattern;
323 if (isRegex(origin)) return !1;
324 if (Array.isArray(origin)) return !1;
325 }
326 return isRegex(pattern) ? isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !isRegex(origin) && pattern.some(function(subpattern) {
327 return matchDomain(subpattern, origin);
328 }));
329 };
330 __webpack_exports__.l = function(pattern) {
331 return Array.isArray(pattern) ? "(" + pattern.join(" | ") + ")" : isRegex(pattern) ? "RegExp(" + pattern.toString() : pattern.toString();
332 };
333 __webpack_exports__.i = function(obj) {
334 try {
335 if (obj === window) return !0;
336 } catch (err) {
337 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
338 }
339 try {
340 if ("[object Window]" === Object.prototype.toString.call(obj)) return !0;
341 } catch (err) {
342 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
343 }
344 try {
345 if (window.Window && obj instanceof window.Window) return !0;
346 } catch (err) {
347 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
348 }
349 try {
350 if (obj && obj.self === obj) return !0;
351 } catch (err) {
352 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
353 }
354 try {
355 if (obj && obj.parent === obj) return !0;
356 } catch (err) {
357 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
358 }
359 try {
360 if (obj && obj.top === obj) return !0;
361 } catch (err) {
362 if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;
363 }
364 try {
365 obj && obj.__cross_domain_utils_window_check__;
366 } catch (err) {
367 return !0;
368 }
369 return !1;
370 };
371 var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n";
372 function isAboutProtocol() {
373 return (arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : window).location.protocol === constants.a.ABOUT;
374 }
375 function getParent(win) {
376 if (win) try {
377 if (win.parent && win.parent !== win) return win.parent;
378 } catch (err) {}
379 }
380 function getOpener(win) {
381 if (win && !getParent(win)) try {
382 return win.opener;
383 } catch (err) {}
384 }
385 function canReadFromWindow(win) {
386 try {
387 win && win.location && win.location.href;
388 return !0;
389 } catch (err) {}
390 return !1;
391 }
392 function getActualDomain(win) {
393 var location = (win = win || window).location;
394 if (!location) throw new Error("Can not read window location");
395 var protocol = location.protocol;
396 if (!protocol) throw new Error("Can not read window protocol");
397 if (protocol === constants.a.FILE) return constants.a.FILE + "//";
398 if (protocol === constants.a.ABOUT) {
399 var parent = getParent(win);
400 return parent && canReadFromWindow(parent) ? getActualDomain(parent) : constants.a.ABOUT + "//";
401 }
402 var host = location.host;
403 if (!host) throw new Error("Can not read window host");
404 return protocol + "//" + host;
405 }
406 function getDomain(win) {
407 var domain = getActualDomain(win = win || window);
408 return domain && win.mockDomain && 0 === win.mockDomain.indexOf(constants.a.MOCK) ? win.mockDomain : domain;
409 }
410 function isActuallySameDomain(win) {
411 try {
412 if (win === window) return !0;
413 } catch (err) {}
414 try {
415 var desc = Object.getOwnPropertyDescriptor(win, "location");
416 if (desc && !1 === desc.enumerable) return !1;
417 } catch (err) {}
418 try {
419 if (isAboutProtocol(win) && canReadFromWindow(win)) return !0;
420 } catch (err) {}
421 try {
422 if (getActualDomain(win) === getActualDomain(window)) return !0;
423 } catch (err) {}
424 return !1;
425 }
426 function isAncestorParent(parent, child) {
427 if (!parent || !child) return !1;
428 var childParent = getParent(child);
429 return childParent ? childParent === parent : -1 !== function(win) {
430 var result = [];
431 try {
432 for (;win.parent !== win; ) {
433 result.push(win.parent);
434 win = win.parent;
435 }
436 } catch (err) {}
437 return result;
438 }(child).indexOf(parent);
439 }
440 function getFrames(win) {
441 var result = [], frames = void 0;
442 try {
443 frames = win.frames;
444 } catch (err) {
445 frames = win;
446 }
447 var len = void 0;
448 try {
449 len = frames.length;
450 } catch (err) {}
451 if (0 === len) return result;
452 if (len) {
453 for (var i = 0; i < len; i++) {
454 var frame = void 0;
455 try {
456 frame = frames[i];
457 } catch (err) {
458 continue;
459 }
460 result.push(frame);
461 }
462 return result;
463 }
464 for (var _i = 0; _i < 100; _i++) {
465 var _frame = void 0;
466 try {
467 _frame = frames[_i];
468 } catch (err) {
469 return result;
470 }
471 if (!_frame) return result;
472 result.push(_frame);
473 }
474 return result;
475 }
476 var iframeWindows = [], iframeFrames = [];
477 function getAncestor(win) {
478 return getOpener(win = win || window) || getParent(win) || void 0;
479 }
480 },
481 "./src/index.js": function(module, __webpack_exports__, __webpack_require__) {
482 Object.defineProperty(__webpack_exports__, "__esModule", {
483 value: !0
484 });
485 __webpack_require__.d({}, "WeakMap", function() {
486 return weakmap_CrossDomainSafeWeakMap;
487 });
488 var src_interface_namespaceObject = {};
489 __webpack_require__.d(src_interface_namespaceObject, "cleanUpWindow", function() {
490 return cleanUpWindow;
491 });
492 __webpack_require__.d(src_interface_namespaceObject, "Promise", function() {
493 return promise_ZalgoPromise;
494 });
495 __webpack_require__.d(src_interface_namespaceObject, "bridge", function() {
496 return bridge;
497 });
498 __webpack_require__.d(src_interface_namespaceObject, "init", function() {
499 return init;
500 });
501 __webpack_require__.d(src_interface_namespaceObject, "parent", function() {
502 return public_parent;
503 });
504 __webpack_require__.d(src_interface_namespaceObject, "send", function() {
505 return _send;
506 });
507 __webpack_require__.d(src_interface_namespaceObject, "request", function() {
508 return request;
509 });
510 __webpack_require__.d(src_interface_namespaceObject, "sendToParent", function() {
511 return sendToParent;
512 });
513 __webpack_require__.d(src_interface_namespaceObject, "client", function() {
514 return client;
515 });
516 __webpack_require__.d(src_interface_namespaceObject, "on", function() {
517 return _on;
518 });
519 __webpack_require__.d(src_interface_namespaceObject, "listen", function() {
520 return listen;
521 });
522 __webpack_require__.d(src_interface_namespaceObject, "once", function() {
523 return server_once;
524 });
525 __webpack_require__.d(src_interface_namespaceObject, "listener", function() {
526 return server_listener;
527 });
528 __webpack_require__.d(src_interface_namespaceObject, "CONFIG", function() {
529 return CONFIG;
530 });
531 __webpack_require__.d(src_interface_namespaceObject, "CONSTANTS", function() {
532 return constants_CONSTANTS;
533 });
534 __webpack_require__.d(src_interface_namespaceObject, "disable", function() {
535 return disable;
536 });
537 var src = __webpack_require__("./node_modules/cross-domain-utils/src/index.js");
538 function safeIndexOf(collection, item) {
539 for (var i = 0; i < collection.length; i++) try {
540 if (collection[i] === item) return i;
541 } catch (err) {}
542 return -1;
543 }
544 var _ALLOWED_POST_MESSAGE, defineProperty = Object.defineProperty, counter = Date.now() % 1e9, weakmap_CrossDomainSafeWeakMap = function() {
545 function CrossDomainSafeWeakMap() {
546 !function(instance, Constructor) {
547 if (!(instance instanceof CrossDomainSafeWeakMap)) throw new TypeError("Cannot call a class as a function");
548 }(this);
549 counter += 1;
550 this.name = "__weakmap_" + (1e9 * Math.random() >>> 0) + "__" + counter;
551 if (function() {
552 if ("undefined" == typeof WeakMap) return !1;
553 if (void 0 === Object.freeze) return !1;
554 try {
555 var testWeakMap = new WeakMap(), testKey = {};
556 Object.freeze(testKey);
557 testWeakMap.set(testKey, "__testvalue__");
558 return "__testvalue__" === testWeakMap.get(testKey);
559 } catch (err) {
560 return !1;
561 }
562 }()) try {
563 this.weakmap = new WeakMap();
564 } catch (err) {}
565 this.keys = [];
566 this.values = [];
567 }
568 CrossDomainSafeWeakMap.prototype._cleanupClosedWindows = function() {
569 for (var weakmap = this.weakmap, keys = this.keys, i = 0; i < keys.length; i++) {
570 var value = keys[i];
571 if (Object(src.isWindow)(value) && Object(src.isWindowClosed)(value)) {
572 if (weakmap) try {
573 weakmap.delete(value);
574 } catch (err) {}
575 keys.splice(i, 1);
576 this.values.splice(i, 1);
577 i -= 1;
578 }
579 }
580 };
581 CrossDomainSafeWeakMap.prototype.isSafeToReadWrite = function(key) {
582 if (Object(src.isWindow)(key)) return !1;
583 try {
584 key && key.self;
585 key && key[this.name];
586 } catch (err) {
587 return !1;
588 }
589 return !0;
590 };
591 CrossDomainSafeWeakMap.prototype.set = function(key, value) {
592 if (!key) throw new Error("WeakMap expected key");
593 var weakmap = this.weakmap;
594 if (weakmap) try {
595 weakmap.set(key, value);
596 } catch (err) {
597 delete this.weakmap;
598 }
599 if (this.isSafeToReadWrite(key)) {
600 var name = this.name, entry = key[name];
601 entry && entry[0] === key ? entry[1] = value : defineProperty(key, name, {
602 value: [ key, value ],
603 writable: !0
604 });
605 } else {
606 this._cleanupClosedWindows();
607 var keys = this.keys, values = this.values, index = safeIndexOf(keys, key);
608 if (-1 === index) {
609 keys.push(key);
610 values.push(value);
611 } else values[index] = value;
612 }
613 };
614 CrossDomainSafeWeakMap.prototype.get = function(key) {
615 if (!key) throw new Error("WeakMap expected key");
616 var weakmap = this.weakmap;
617 if (weakmap) try {
618 if (weakmap.has(key)) return weakmap.get(key);
619 } catch (err) {
620 delete this.weakmap;
621 }
622 if (!this.isSafeToReadWrite(key)) {
623 this._cleanupClosedWindows();
624 var index = safeIndexOf(this.keys, key);
625 if (-1 === index) return;
626 return this.values[index];
627 }
628 var entry = key[this.name];
629 if (entry && entry[0] === key) return entry[1];
630 };
631 CrossDomainSafeWeakMap.prototype.delete = function(key) {
632 if (!key) throw new Error("WeakMap expected key");
633 var weakmap = this.weakmap;
634 if (weakmap) try {
635 weakmap.delete(key);
636 } catch (err) {
637 delete this.weakmap;
638 }
639 if (this.isSafeToReadWrite(key)) {
640 var entry = key[this.name];
641 entry && entry[0] === key && (entry[0] = entry[1] = void 0);
642 } else {
643 this._cleanupClosedWindows();
644 var keys = this.keys, index = safeIndexOf(keys, key);
645 if (-1 !== index) {
646 keys.splice(index, 1);
647 this.values.splice(index, 1);
648 }
649 }
650 };
651 CrossDomainSafeWeakMap.prototype.has = function(key) {
652 if (!key) throw new Error("WeakMap expected key");
653 var weakmap = this.weakmap;
654 if (weakmap) try {
655 if (weakmap.has(key)) return !0;
656 } catch (err) {
657 delete this.weakmap;
658 }
659 if (this.isSafeToReadWrite(key)) {
660 var entry = key[this.name];
661 return !(!entry || entry[0] !== key);
662 }
663 this._cleanupClosedWindows();
664 return -1 !== safeIndexOf(this.keys, key);
665 };
666 CrossDomainSafeWeakMap.prototype.getOrSet = function(key, getter) {
667 if (this.has(key)) return this.get(key);
668 var value = getter();
669 this.set(key, value);
670 return value;
671 };
672 return CrossDomainSafeWeakMap;
673 }(), constants_CONSTANTS = {
674 POST_MESSAGE_TYPE: {
675 REQUEST: "postrobot_message_request",
676 RESPONSE: "postrobot_message_response",
677 ACK: "postrobot_message_ack"
678 },
679 POST_MESSAGE_ACK: {
680 SUCCESS: "success",
681 ERROR: "error"
682 },
683 POST_MESSAGE_NAMES: {
684 METHOD: "postrobot_method",
685 HELLO: "postrobot_ready",
686 OPEN_TUNNEL: "postrobot_open_tunnel"
687 },
688 WINDOW_TYPES: {
689 FULLPAGE: "fullpage",
690 POPUP: "popup",
691 IFRAME: "iframe"
692 },
693 WINDOW_PROPS: {
694 POSTROBOT: "__postRobot__"
695 },
696 SERIALIZATION_TYPES: {
697 METHOD: "postrobot_method",
698 ERROR: "postrobot_error",
699 PROMISE: "postrobot_promise",
700 ZALGO_PROMISE: "postrobot_zalgo_promise",
701 REGEX: "regex"
702 },
703 SEND_STRATEGIES: {
704 POST_MESSAGE: "postrobot_post_message",
705 BRIDGE: "postrobot_bridge",
706 GLOBAL: "postrobot_global"
707 },
708 MOCK_PROTOCOL: "mock:",
709 FILE_PROTOCOL: "file:",
710 BRIDGE_NAME_PREFIX: "__postrobot_bridge__",
711 POSTROBOT_PROXY: "__postrobot_proxy__",
712 WILDCARD: "*"
713 }, POST_MESSAGE_NAMES = {
714 METHOD: "postrobot_method",
715 HELLO: "postrobot_hello",
716 OPEN_TUNNEL: "postrobot_open_tunnel"
717 }, CONFIG = (Object.keys(POST_MESSAGE_NAMES).map(function(key) {
718 return POST_MESSAGE_NAMES[key];
719 }), {
720 ALLOW_POSTMESSAGE_POPUP: !("__ALLOW_POSTMESSAGE_POPUP__" in window) || window.__ALLOW_POSTMESSAGE_POPUP__,
721 BRIDGE_TIMEOUT: 5e3,
722 CHILD_WINDOW_TIMEOUT: 5e3,
723 ACK_TIMEOUT: -1 !== window.navigator.userAgent.match(/MSIE/i) ? 1e4 : 2e3,
724 RES_TIMEOUT: -1,
725 ALLOWED_POST_MESSAGE_METHODS: (_ALLOWED_POST_MESSAGE = {}, _ALLOWED_POST_MESSAGE[constants_CONSTANTS.SEND_STRATEGIES.POST_MESSAGE] = !0,
726 _ALLOWED_POST_MESSAGE[constants_CONSTANTS.SEND_STRATEGIES.BRIDGE] = !0, _ALLOWED_POST_MESSAGE[constants_CONSTANTS.SEND_STRATEGIES.GLOBAL] = !0,
727 _ALLOWED_POST_MESSAGE),
728 ALLOW_SAME_ORIGIN: !1
729 });
730 0 === window.location.href.indexOf(constants_CONSTANTS.FILE_PROTOCOL) && (CONFIG.ALLOW_POSTMESSAGE_POPUP = !0);
731 var _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
732 return typeof obj;
733 } : function(obj) {
734 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
735 };
736 function stringifyError(err) {
737 var level = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1;
738 if (level >= 3) return "stringifyError stack overflow";
739 try {
740 if (!err) return "<unknown error: " + Object.prototype.toString.call(err) + ">";
741 if ("string" == typeof err) return err;
742 if (err instanceof Error) {
743 var stack = err && err.stack, message = err && err.message;
744 if (stack && message) return -1 !== stack.indexOf(message) ? stack : message + "\n" + stack;
745 if (stack) return stack;
746 if (message) return message;
747 }
748 return "function" == typeof err.toString ? err.toString() : Object.prototype.toString.call(err);
749 } catch (newErr) {
750 return "Error while stringifying error: " + stringifyError(newErr, level + 1);
751 }
752 }
753 var once = function(method) {
754 if (!method) return method;
755 var called = !1;
756 return function() {
757 if (!called) {
758 called = !0;
759 return method.apply(this, arguments);
760 }
761 };
762 };
763 function util_noop() {}
764 function uniqueID() {
765 var chars = "0123456789abcdef";
766 return "xxxxxxxxxx".replace(/./g, function() {
767 return chars.charAt(Math.floor(Math.random() * chars.length));
768 });
769 }
770 function replaceObject(item, callback) {
771 var depth = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 1;
772 if (depth >= 100) throw new Error("Self-referential object passed, or object contained too many layers");
773 var newobj = void 0;
774 if ("object" !== (void 0 === item ? "undefined" : _typeof(item)) || null === item || Array.isArray(item)) {
775 if (!Array.isArray(item)) throw new TypeError("Invalid type: " + (void 0 === item ? "undefined" : _typeof(item)));
776 newobj = [];
777 } else newobj = {};
778 !function(item, callback) {
779 Array.isArray(item) ? function(item, callback) {
780 for (var i = 0; i < item.length; i++) callback(item[i], i);
781 }(item, callback) : "object" === (void 0 === item ? "undefined" : _typeof(item)) && null !== item && function(item, callback) {
782 for (var _key in item) item.hasOwnProperty(_key) && callback(item[_key], _key);
783 }(item, callback);
784 }(item, function(childItem, key) {
785 var result = callback(childItem, key);
786 void 0 !== result ? newobj[key] = result : "object" === (void 0 === childItem ? "undefined" : _typeof(childItem)) && null !== childItem ? newobj[key] = replaceObject(childItem, callback, depth + 1) : newobj[key] = childItem;
787 });
788 return newobj;
789 }
790 function isRegex(item) {
791 return "[object RegExp]" === Object.prototype.toString.call(item);
792 }
793 function utils_isPromise(item) {
794 try {
795 if (!item) return !1;
796 if ("undefined" != typeof Promise && item instanceof Promise) return !0;
797 if ("undefined" != typeof window && window.Window && item instanceof window.Window) return !1;
798 if ("undefined" != typeof window && window.constructor && item instanceof window.constructor) return !1;
799 if ("function" == typeof item.then) return !0;
800 } catch (err) {
801 return !1;
802 }
803 return !1;
804 }
805 function getGlobal() {
806 var glob = void 0;
807 if ("undefined" != typeof window) glob = window; else {
808 if ("undefined" == typeof window) throw new TypeError("Can not find global");
809 glob = window;
810 }
811 var zalgoGlobal = glob.__zalgopromise__ = glob.__zalgopromise__ || {};
812 zalgoGlobal.flushPromises = zalgoGlobal.flushPromises || [];
813 zalgoGlobal.activeCount = zalgoGlobal.activeCount || 0;
814 zalgoGlobal.possiblyUnhandledPromiseHandlers = zalgoGlobal.possiblyUnhandledPromiseHandlers || [];
815 zalgoGlobal.dispatchedErrors = zalgoGlobal.dispatchedErrors || [];
816 return zalgoGlobal;
817 }
818 var promise_ZalgoPromise = function() {
819 function ZalgoPromise(handler) {
820 var _this = this;
821 !function(instance, Constructor) {
822 if (!(instance instanceof ZalgoPromise)) throw new TypeError("Cannot call a class as a function");
823 }(this);
824 this.resolved = !1;
825 this.rejected = !1;
826 this.errorHandled = !1;
827 this.handlers = [];
828 if (handler) {
829 var _result = void 0, _error = void 0, resolved = !1, rejected = !1, isAsync = !1;
830 try {
831 handler(function(res) {
832 if (isAsync) _this.resolve(res); else {
833 resolved = !0;
834 _result = res;
835 }
836 }, function(err) {
837 if (isAsync) _this.reject(err); else {
838 rejected = !0;
839 _error = err;
840 }
841 });
842 } catch (err) {
843 this.reject(err);
844 return;
845 }
846 isAsync = !0;
847 resolved ? this.resolve(_result) : rejected && this.reject(_error);
848 }
849 }
850 ZalgoPromise.prototype.resolve = function(result) {
851 if (this.resolved || this.rejected) return this;
852 if (utils_isPromise(result)) throw new Error("Can not resolve promise with another promise");
853 this.resolved = !0;
854 this.value = result;
855 this.dispatch();
856 return this;
857 };
858 ZalgoPromise.prototype.reject = function(error) {
859 var _this2 = this;
860 if (this.resolved || this.rejected) return this;
861 if (utils_isPromise(error)) throw new Error("Can not reject promise with another promise");
862 if (!error) {
863 var _err = error && "function" == typeof error.toString ? error.toString() : Object.prototype.toString.call(error);
864 error = new Error("Expected reject to be called with Error, got " + _err);
865 }
866 this.rejected = !0;
867 this.error = error;
868 this.errorHandled || setTimeout(function() {
869 _this2.errorHandled || function(err, promise) {
870 if (-1 === getGlobal().dispatchedErrors.indexOf(err)) {
871 getGlobal().dispatchedErrors.push(err);
872 setTimeout(function() {
873 throw err;
874 }, 1);
875 for (var j = 0; j < getGlobal().possiblyUnhandledPromiseHandlers.length; j++) getGlobal().possiblyUnhandledPromiseHandlers[j](err, promise);
876 }
877 }(error, _this2);
878 }, 1);
879 this.dispatch();
880 return this;
881 };
882 ZalgoPromise.prototype.asyncReject = function(error) {
883 this.errorHandled = !0;
884 this.reject(error);
885 return this;
886 };
887 ZalgoPromise.prototype.dispatch = function() {
888 var _this3 = this, dispatching = this.dispatching, resolved = this.resolved, rejected = this.rejected, handlers = this.handlers;
889 if (!dispatching && (resolved || rejected)) {
890 this.dispatching = !0;
891 getGlobal().activeCount += 1;
892 for (var _loop = function(i) {
893 var _handlers$i = handlers[i], onSuccess = _handlers$i.onSuccess, onError = _handlers$i.onError, promise = _handlers$i.promise, result = void 0;
894 if (resolved) try {
895 result = onSuccess ? onSuccess(_this3.value) : _this3.value;
896 } catch (err) {
897 promise.reject(err);
898 return "continue";
899 } else if (rejected) {
900 if (!onError) {
901 promise.reject(_this3.error);
902 return "continue";
903 }
904 try {
905 result = onError(_this3.error);
906 } catch (err) {
907 promise.reject(err);
908 return "continue";
909 }
910 }
911 if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {
912 result.resolved ? promise.resolve(result.value) : promise.reject(result.error);
913 result.errorHandled = !0;
914 } else utils_isPromise(result) ? result instanceof ZalgoPromise && (result.resolved || result.rejected) ? result.resolved ? promise.resolve(result.value) : promise.reject(result.error) : result.then(function(res) {
915 promise.resolve(res);
916 }, function(err) {
917 promise.reject(err);
918 }) : promise.resolve(result);
919 }, i = 0; i < handlers.length; i++) _loop(i);
920 handlers.length = 0;
921 this.dispatching = !1;
922 getGlobal().activeCount -= 1;
923 0 === getGlobal().activeCount && ZalgoPromise.flushQueue();
924 }
925 };
926 ZalgoPromise.prototype.then = function(onSuccess, onError) {
927 if (onSuccess && "function" != typeof onSuccess && !onSuccess.call) throw new Error("Promise.then expected a function for success handler");
928 if (onError && "function" != typeof onError && !onError.call) throw new Error("Promise.then expected a function for error handler");
929 var promise = new ZalgoPromise();
930 this.handlers.push({
931 promise: promise,
932 onSuccess: onSuccess,
933 onError: onError
934 });
935 this.errorHandled = !0;
936 this.dispatch();
937 return promise;
938 };
939 ZalgoPromise.prototype.catch = function(onError) {
940 return this.then(void 0, onError);
941 };
942 ZalgoPromise.prototype.finally = function(onFinally) {
943 if (onFinally && "function" != typeof onFinally && !onFinally.call) throw new Error("Promise.finally expected a function");
944 return this.then(function(result) {
945 return ZalgoPromise.try(onFinally).then(function() {
946 return result;
947 });
948 }, function(err) {
949 return ZalgoPromise.try(onFinally).then(function() {
950 throw err;
951 });
952 });
953 };
954 ZalgoPromise.prototype.timeout = function(time, err) {
955 var _this4 = this;
956 if (this.resolved || this.rejected) return this;
957 var timeout = setTimeout(function() {
958 _this4.resolved || _this4.rejected || _this4.reject(err || new Error("Promise timed out after " + time + "ms"));
959 }, time);
960 return this.then(function(result) {
961 clearTimeout(timeout);
962 return result;
963 });
964 };
965 ZalgoPromise.prototype.toPromise = function() {
966 if ("undefined" == typeof Promise) throw new TypeError("Could not find Promise");
967 return Promise.resolve(this);
968 };
969 ZalgoPromise.resolve = function(value) {
970 return value instanceof ZalgoPromise ? value : utils_isPromise(value) ? new ZalgoPromise(function(resolve, reject) {
971 return value.then(resolve, reject);
972 }) : new ZalgoPromise().resolve(value);
973 };
974 ZalgoPromise.reject = function(error) {
975 return new ZalgoPromise().reject(error);
976 };
977 ZalgoPromise.asyncReject = function(error) {
978 return new ZalgoPromise().asyncReject(error);
979 };
980 ZalgoPromise.all = function(promises) {
981 var promise = new ZalgoPromise(), count = promises.length, results = [];
982 if (!count) {
983 promise.resolve(results);
984 return promise;
985 }
986 for (var _loop2 = function(i) {
987 var prom = promises[i];
988 if (prom instanceof ZalgoPromise) {
989 if (prom.resolved) {
990 results[i] = prom.value;
991 count -= 1;
992 return "continue";
993 }
994 } else if (!utils_isPromise(prom)) {
995 results[i] = prom;
996 count -= 1;
997 return "continue";
998 }
999 ZalgoPromise.resolve(prom).then(function(result) {
1000 results[i] = result;
1001 0 == (count -= 1) && promise.resolve(results);
1002 }, function(err) {
1003 promise.reject(err);
1004 });
1005 }, i = 0; i < promises.length; i++) _loop2(i);
1006 0 === count && promise.resolve(results);
1007 return promise;
1008 };
1009 ZalgoPromise.hash = function(promises) {
1010 var result = {};
1011 return ZalgoPromise.all(Object.keys(promises).map(function(key) {
1012 return ZalgoPromise.resolve(promises[key]).then(function(value) {
1013 result[key] = value;
1014 });
1015 })).then(function() {
1016 return result;
1017 });
1018 };
1019 ZalgoPromise.map = function(items, method) {
1020 return ZalgoPromise.all(items.map(method));
1021 };
1022 ZalgoPromise.onPossiblyUnhandledException = function(handler) {
1023 return function(handler) {
1024 getGlobal().possiblyUnhandledPromiseHandlers.push(handler);
1025 return {
1026 cancel: function() {
1027 getGlobal().possiblyUnhandledPromiseHandlers.splice(getGlobal().possiblyUnhandledPromiseHandlers.indexOf(handler), 1);
1028 }
1029 };
1030 }(handler);
1031 };
1032 ZalgoPromise.try = function(method, context, args) {
1033 if (method && "function" != typeof method && !method.call) throw new Error("Promise.try expected a function");
1034 var result = void 0;
1035 try {
1036 result = method.apply(context, args || []);
1037 } catch (err) {
1038 return ZalgoPromise.reject(err);
1039 }
1040 return ZalgoPromise.resolve(result);
1041 };
1042 ZalgoPromise.delay = function(_delay) {
1043 return new ZalgoPromise(function(resolve) {
1044 setTimeout(resolve, _delay);
1045 });
1046 };
1047 ZalgoPromise.isPromise = function(value) {
1048 return !!(value && value instanceof ZalgoPromise) || utils_isPromise(value);
1049 };
1050 ZalgoPromise.flush = function() {
1051 var promise = new ZalgoPromise();
1052 getGlobal().flushPromises.push(promise);
1053 0 === getGlobal().activeCount && ZalgoPromise.flushQueue();
1054 return promise;
1055 };
1056 ZalgoPromise.flushQueue = function() {
1057 var promisesToFlush = getGlobal().flushPromises;
1058 getGlobal().flushPromises = [];
1059 for (var _i2 = 0, _length2 = null == promisesToFlush ? 0 : promisesToFlush.length; _i2 < _length2; _i2++) promisesToFlush[_i2].resolve();
1060 };
1061 return ZalgoPromise;
1062 }(), global = window[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT] = window[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT] || {};
1063 global.registerSelf = function() {};
1064 var serialize__typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
1065 return typeof obj;
1066 } : function(obj) {
1067 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1068 };
1069 global.methods = global.methods || new weakmap_CrossDomainSafeWeakMap();
1070 var listenForMethods = once(function() {
1071 global.on(constants_CONSTANTS.POST_MESSAGE_NAMES.METHOD, {
1072 origin: constants_CONSTANTS.WILDCARD
1073 }, function(_ref) {
1074 var source = _ref.source, origin = _ref.origin, data = _ref.data, methods = global.methods.get(source);
1075 if (!methods) throw new Error("Could not find any methods this window has privileges to call");
1076 var meth = methods[data.id];
1077 if (!meth) throw new Error("Could not find method with id: " + data.id);
1078 if (!Object(src.matchDomain)(meth.domain, origin)) throw new Error("Method domain " + meth.domain + " does not match origin " + origin);
1079 return promise_ZalgoPromise.try(function() {
1080 return meth.method.apply({
1081 source: source,
1082 origin: origin,
1083 data: data
1084 }, data.args);
1085 }).then(function(result) {
1086 return {
1087 result: result,
1088 id: data.id,
1089 name: data.name
1090 };
1091 });
1092 });
1093 });
1094 function isSerialized(item, type) {
1095 return "object" === (void 0 === item ? "undefined" : serialize__typeof(item)) && null !== item && item.__type__ === type;
1096 }
1097 function serializeMethod(destination, domain, method, name) {
1098 var id = uniqueID(), methods = global.methods.get(destination);
1099 if (!methods) {
1100 methods = {};
1101 global.methods.set(destination, methods);
1102 }
1103 methods[id] = {
1104 domain: domain,
1105 method: method
1106 };
1107 return {
1108 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.METHOD,
1109 __id__: id,
1110 __name__: name
1111 };
1112 }
1113 function deserializeMethod(source, origin, obj) {
1114 function wrapper() {
1115 var args = Array.prototype.slice.call(arguments);
1116 return global.send(source, constants_CONSTANTS.POST_MESSAGE_NAMES.METHOD, {
1117 id: obj.__id__,
1118 name: obj.__name__,
1119 args: args
1120 }, {
1121 domain: origin,
1122 timeout: -1
1123 }).then(function(_ref2) {
1124 return _ref2.data.result;
1125 }, function(err) {
1126 throw err;
1127 });
1128 }
1129 wrapper.__name__ = obj.__name__;
1130 wrapper.__xdomain__ = !0;
1131 wrapper.source = source;
1132 wrapper.origin = origin;
1133 return wrapper;
1134 }
1135 function deserializeZalgoPromise(source, origin, prom) {
1136 return new promise_ZalgoPromise(function(resolve, reject) {
1137 return deserializeMethod(source, origin, prom.__then__)(resolve, reject);
1138 });
1139 }
1140 global.readyPromises = global.readyPromises || new weakmap_CrossDomainSafeWeakMap();
1141 function sayHello(win) {
1142 return global.send(win, constants_CONSTANTS.POST_MESSAGE_NAMES.HELLO, {}, {
1143 domain: constants_CONSTANTS.WILDCARD,
1144 timeout: -1
1145 }).then(function(_ref2) {
1146 return {
1147 origin: _ref2.origin
1148 };
1149 });
1150 }
1151 var SEND_MESSAGE_STRATEGIES = {};
1152 SEND_MESSAGE_STRATEGIES[constants_CONSTANTS.SEND_STRATEGIES.POST_MESSAGE] = function(win, serializedMessage, domain) {
1153 (Array.isArray(domain) ? domain : "string" == typeof domain ? [ domain ] : [ constants_CONSTANTS.WILDCARD ]).map(function(dom) {
1154 if (0 === dom.indexOf(constants_CONSTANTS.MOCK_PROTOCOL)) {
1155 if (window.location.protocol === constants_CONSTANTS.FILE_PROTOCOL) return constants_CONSTANTS.WILDCARD;
1156 if (!Object(src.isActuallySameDomain)(win)) throw new Error("Attempting to send messsage to mock domain " + dom + ", but window is actually cross-domain");
1157 return Object(src.getActualDomain)(win);
1158 }
1159 return 0 === dom.indexOf(constants_CONSTANTS.FILE_PROTOCOL) ? constants_CONSTANTS.WILDCARD : dom;
1160 }).forEach(function(dom) {
1161 return win.postMessage(serializedMessage, dom);
1162 });
1163 };
1164 var _extends = Object.assign || function(target) {
1165 for (var i = 1; i < arguments.length; i++) {
1166 var source = arguments[i];
1167 for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
1168 }
1169 return target;
1170 };
1171 function sendMessage(win, message, domain) {
1172 return promise_ZalgoPromise.try(function() {
1173 var _jsonStringify;
1174 message = function(win, message) {
1175 var options = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, id = uniqueID(), type = Object(src.isPopup)() ? constants_CONSTANTS.WINDOW_TYPES.POPUP : Object(src.isIframe)() ? constants_CONSTANTS.WINDOW_TYPES.IFRAME : constants_CONSTANTS.WINDOW_TYPES.FULLPAGE, sourceDomain = Object(src.getDomain)(window);
1176 return _extends({}, message, options, {
1177 sourceDomain: sourceDomain,
1178 id: message.id || id,
1179 windowType: type
1180 });
1181 }(win, message, {
1182 data: function(destination, domain, obj) {
1183 return replaceObject({
1184 obj: message.data
1185 }, function(item, key) {
1186 return "function" == typeof item ? serializeMethod(destination, domain, item, key.toString()) : item instanceof Error ? (err = item,
1187 {
1188 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.ERROR,
1189 __message__: stringifyError(err),
1190 __code__: err.code
1191 }) : window.Promise && item instanceof window.Promise ? function(destination, domain, promise, name) {
1192 return {
1193 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.PROMISE,
1194 __then__: serializeMethod(destination, domain, function(resolve, reject) {
1195 return promise.then(resolve, reject);
1196 }, name + ".then")
1197 };
1198 }(destination, domain, item, key.toString()) : promise_ZalgoPromise.isPromise(item) ? function(destination, domain, promise, name) {
1199 return {
1200 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.ZALGO_PROMISE,
1201 __then__: serializeMethod(destination, domain, function(resolve, reject) {
1202 return promise.then(resolve, reject);
1203 }, name + ".then")
1204 };
1205 }(destination, domain, item, key.toString()) : isRegex(item) ? (regex = item, {
1206 __type__: constants_CONSTANTS.SERIALIZATION_TYPES.REGEX,
1207 __source__: regex.source
1208 }) : void 0;
1209 var err, regex;
1210 }).obj;
1211 }(win, domain),
1212 domain: domain
1213 });
1214 if (win === window && !CONFIG.ALLOW_SAME_ORIGIN) throw new Error("Attemping to send message to self");
1215 if (Object(src.isWindowClosed)(win)) throw new Error("Window is closed");
1216 var messages = [], serializedMessage = function(obj, replacer, indent) {
1217 var objectToJSON = void 0, arrayToJSON = void 0;
1218 try {
1219 if ("{}" !== JSON.stringify({})) {
1220 objectToJSON = Object.prototype.toJSON;
1221 delete Object.prototype.toJSON;
1222 }
1223 if ("{}" !== JSON.stringify({})) throw new Error("Can not correctly serialize JSON objects");
1224 if ("[]" !== JSON.stringify([])) {
1225 arrayToJSON = Array.prototype.toJSON;
1226 delete Array.prototype.toJSON;
1227 }
1228 if ("[]" !== JSON.stringify([])) throw new Error("Can not correctly serialize JSON objects");
1229 } catch (err) {
1230 throw new Error("Can not repair JSON.stringify: " + err.message);
1231 }
1232 var result = JSON.stringify.call(this, obj, null, 2);
1233 try {
1234 objectToJSON && (Object.prototype.toJSON = objectToJSON);
1235 arrayToJSON && (Array.prototype.toJSON = arrayToJSON);
1236 } catch (err) {
1237 throw new Error("Can not repair JSON.stringify: " + err.message);
1238 }
1239 return result;
1240 }(((_jsonStringify = {})[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT] = message,
1241 _jsonStringify));
1242 return promise_ZalgoPromise.map(Object.keys(SEND_MESSAGE_STRATEGIES), function(strategyName) {
1243 return promise_ZalgoPromise.try(function() {
1244 if (!CONFIG.ALLOWED_POST_MESSAGE_METHODS[strategyName]) throw new Error("Strategy disallowed: " + strategyName);
1245 return SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);
1246 }).then(function() {
1247 messages.push(strategyName + ": success");
1248 return !0;
1249 }, function(err) {
1250 messages.push(strategyName + ": " + stringifyError(err) + "\n");
1251 return !1;
1252 });
1253 }).then(function(results) {
1254 var success = results.some(Boolean), status = message.type + " " + message.name + " " + (success ? "success" : "error") + ":\n - " + messages.join("\n - ") + "\n";
1255 if (!success) throw new Error(status);
1256 });
1257 });
1258 }
1259 global.responseListeners = global.responseListeners || {};
1260 global.requestListeners = global.requestListeners || {};
1261 global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new function() {}();
1262 global.erroredResponseListeners = global.erroredResponseListeners || {};
1263 var _RECEIVE_MESSAGE_TYPE, __DOMAIN_REGEX__ = "__domain_regex__";
1264 function getResponseListener(hash) {
1265 return global.responseListeners[hash];
1266 }
1267 function deleteResponseListener(hash) {
1268 delete global.responseListeners[hash];
1269 }
1270 function isResponseListenerErrored(hash) {
1271 return Boolean(global.erroredResponseListeners[hash]);
1272 }
1273 function getRequestListener(_ref) {
1274 var name = _ref.name, win = _ref.win, domain = _ref.domain;
1275 win === constants_CONSTANTS.WILDCARD && (win = null);
1276 domain === constants_CONSTANTS.WILDCARD && (domain = null);
1277 if (!name) throw new Error("Name required to get request listener");
1278 var nameListeners = global.requestListeners[name];
1279 if (nameListeners) for (var _i2 = 0, _ref3 = [ win, global.WINDOW_WILDCARD ], _length2 = null == _ref3 ? 0 : _ref3.length; _i2 < _length2; _i2++) {
1280 var winQualifier = _ref3[_i2], winListeners = winQualifier && nameListeners.get(winQualifier);
1281 if (winListeners) {
1282 if (domain && "string" == typeof domain) {
1283 if (winListeners[domain]) return winListeners[domain];
1284 if (winListeners[__DOMAIN_REGEX__]) for (var _i4 = 0, _winListeners$__DOMAI2 = winListeners[__DOMAIN_REGEX__], _length4 = null == _winListeners$__DOMAI2 ? 0 : _winListeners$__DOMAI2.length; _i4 < _length4; _i4++) {
1285 var _ref5 = _winListeners$__DOMAI2[_i4], regex = _ref5.regex, listener = _ref5.listener;
1286 if (Object(src.matchDomain)(regex, domain)) return listener;
1287 }
1288 }
1289 if (winListeners[constants_CONSTANTS.WILDCARD]) return winListeners[constants_CONSTANTS.WILDCARD];
1290 }
1291 }
1292 }
1293 var types__extends = Object.assign || function(target) {
1294 for (var i = 1; i < arguments.length; i++) {
1295 var source = arguments[i];
1296 for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
1297 }
1298 return target;
1299 }, RECEIVE_MESSAGE_TYPES = ((_RECEIVE_MESSAGE_TYPE = {})[constants_CONSTANTS.POST_MESSAGE_TYPE.ACK] = function(source, origin, message) {
1300 if (!isResponseListenerErrored(message.hash)) {
1301 var options = getResponseListener(message.hash);
1302 if (!options) throw new Error("No handler found for post message ack for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
1303 if (!Object(src.matchDomain)(options.domain, origin)) throw new Error("Ack origin " + origin + " does not match domain " + options.domain.toString());
1304 options.ack = !0;
1305 }
1306 }, _RECEIVE_MESSAGE_TYPE[constants_CONSTANTS.POST_MESSAGE_TYPE.REQUEST] = function(source, origin, message) {
1307 var options = getRequestListener({
1308 name: message.name,
1309 win: source,
1310 domain: origin
1311 });
1312 function respond(data) {
1313 return message.fireAndForget || Object(src.isWindowClosed)(source) ? promise_ZalgoPromise.resolve() : sendMessage(source, types__extends({
1314 target: message.originalSource,
1315 hash: message.hash,
1316 name: message.name
1317 }, data), origin);
1318 }
1319 return promise_ZalgoPromise.all([ respond({
1320 type: constants_CONSTANTS.POST_MESSAGE_TYPE.ACK
1321 }), promise_ZalgoPromise.try(function() {
1322 if (!options) throw new Error("No handler found for post message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
1323 if (!Object(src.matchDomain)(options.domain, origin)) throw new Error("Request origin " + origin + " does not match domain " + options.domain.toString());
1324 var data = message.data;
1325 return options.handler({
1326 source: source,
1327 origin: origin,
1328 data: data
1329 });
1330 }).then(function(data) {
1331 return respond({
1332 type: constants_CONSTANTS.POST_MESSAGE_TYPE.RESPONSE,
1333 ack: constants_CONSTANTS.POST_MESSAGE_ACK.SUCCESS,
1334 data: data
1335 });
1336 }, function(err) {
1337 var error = stringifyError(err).replace(/^Error: /, ""), code = err.code;
1338 return respond({
1339 type: constants_CONSTANTS.POST_MESSAGE_TYPE.RESPONSE,
1340 ack: constants_CONSTANTS.POST_MESSAGE_ACK.ERROR,
1341 error: error,
1342 code: code
1343 });
1344 }) ]).then(util_noop).catch(function(err) {
1345 if (options && options.handleError) return options.handleError(err);
1346 throw err;
1347 });
1348 }, _RECEIVE_MESSAGE_TYPE[constants_CONSTANTS.POST_MESSAGE_TYPE.RESPONSE] = function(source, origin, message) {
1349 if (!isResponseListenerErrored(message.hash)) {
1350 var options = getResponseListener(message.hash);
1351 if (!options) throw new Error("No handler found for post message response for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
1352 if (!Object(src.matchDomain)(options.domain, origin)) throw new Error("Response origin " + origin + " does not match domain " + Object(src.stringifyDomainPattern)(options.domain));
1353 deleteResponseListener(message.hash);
1354 if (message.ack === constants_CONSTANTS.POST_MESSAGE_ACK.ERROR) {
1355 var err = new Error(message.error);
1356 message.code && (err.code = message.code);
1357 return options.respond(err, null);
1358 }
1359 if (message.ack === constants_CONSTANTS.POST_MESSAGE_ACK.SUCCESS) {
1360 var data = message.data || message.response;
1361 return options.respond(null, {
1362 source: source,
1363 origin: origin,
1364 data: data
1365 });
1366 }
1367 }
1368 }, _RECEIVE_MESSAGE_TYPE), receive__typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
1369 return typeof obj;
1370 } : function(obj) {
1371 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1372 };
1373 global.receivedMessages = global.receivedMessages || [];
1374 function receiveMessage(event) {
1375 if (!window || window.closed) throw new Error("Message recieved in closed window");
1376 try {
1377 if (!event.source) return;
1378 } catch (err) {
1379 return;
1380 }
1381 var source = event.source, origin = event.origin, message = function(message) {
1382 var item, parsedMessage = void 0;
1383 try {
1384 parsedMessage = (item = message, JSON.parse(item));
1385 } catch (err) {
1386 return;
1387 }
1388 if (parsedMessage && "object" === (void 0 === parsedMessage ? "undefined" : receive__typeof(parsedMessage)) && null !== parsedMessage && (parsedMessage = parsedMessage[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT]) && "object" === (void 0 === parsedMessage ? "undefined" : receive__typeof(parsedMessage)) && null !== parsedMessage && parsedMessage.type && "string" == typeof parsedMessage.type && RECEIVE_MESSAGE_TYPES[parsedMessage.type]) return parsedMessage;
1389 }(event.data);
1390 if (message) {
1391 if (!message.sourceDomain || "string" != typeof message.sourceDomain) throw new Error("Expected message to have sourceDomain");
1392 0 !== message.sourceDomain.indexOf(constants_CONSTANTS.MOCK_PROTOCOL) && 0 !== message.sourceDomain.indexOf(constants_CONSTANTS.FILE_PROTOCOL) || (origin = message.sourceDomain);
1393 if (-1 === global.receivedMessages.indexOf(message.id)) {
1394 global.receivedMessages.push(message.id);
1395 if (!Object(src.isWindowClosed)(source) || message.fireAndForget) {
1396 message.data && (message.data = function(source, origin, obj) {
1397 return replaceObject({
1398 obj: message.data
1399 }, function(item) {
1400 if ("object" === (void 0 === item ? "undefined" : serialize__typeof(item)) && null !== item) return isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.METHOD) ? deserializeMethod(source, origin, item) : isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.ERROR) ? function(source, origin, obj) {
1401 var err = new Error(obj.__message__);
1402 obj.__code__ && (err.code = obj.__code__);
1403 return err;
1404 }(0, 0, item) : isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.PROMISE) ? function(source, origin, prom) {
1405 return window.Promise ? new window.Promise(function(resolve, reject) {
1406 return deserializeMethod(source, origin, prom.__then__)(resolve, reject);
1407 }) : deserializeZalgoPromise(source, origin, prom);
1408 }(source, origin, item) : isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.ZALGO_PROMISE) ? deserializeZalgoPromise(source, origin, item) : isSerialized(item, constants_CONSTANTS.SERIALIZATION_TYPES.REGEX) ? function(source, origin, item) {
1409 return new RegExp(item.__source__);
1410 }(0, 0, item) : void 0;
1411 }).obj;
1412 }(source, origin));
1413 RECEIVE_MESSAGE_TYPES[message.type](source, origin, message);
1414 }
1415 }
1416 }
1417 }
1418 function messageListener(event) {
1419 try {
1420 event.source;
1421 } catch (err) {
1422 return;
1423 }
1424 receiveMessage({
1425 source: event.source || event.sourceElement,
1426 origin: event.origin || event.originalEvent && event.originalEvent.origin,
1427 data: event.data
1428 });
1429 }
1430 global.receiveMessage = receiveMessage;
1431 global.requestPromises = global.requestPromises || new weakmap_CrossDomainSafeWeakMap();
1432 function request(options) {
1433 return promise_ZalgoPromise.try(function() {
1434 if (!options.name) throw new Error("Expected options.name");
1435 var name = options.name, targetWindow = void 0, domain = void 0;
1436 if ("string" == typeof options.window) {
1437 var el = document.getElementById(options.window);
1438 if (!el) throw new Error("Expected options.window " + Object.prototype.toString.call(options.window) + " to be a valid element id");
1439 if ("iframe" !== el.tagName.toLowerCase()) throw new Error("Expected options.window " + Object.prototype.toString.call(options.window) + " to be an iframe");
1440 if (!el.contentWindow) throw new Error("Iframe must have contentWindow. Make sure it has a src attribute and is in the DOM.");
1441 targetWindow = el.contentWindow;
1442 } else if (options.window instanceof HTMLIFrameElement) {
1443 if ("iframe" !== options.window.tagName.toLowerCase()) throw new Error("Expected options.window " + Object.prototype.toString.call(options.window) + " to be an iframe");
1444 if (options.window && !options.window.contentWindow) throw new Error("Iframe must have contentWindow. Make sure it has a src attribute and is in the DOM.");
1445 options.window && options.window.contentWindow && (targetWindow = options.window.contentWindow);
1446 } else targetWindow = options.window;
1447 if (!targetWindow) throw new Error("Expected options.window to be a window object, iframe, or iframe element id.");
1448 var win = targetWindow;
1449 domain = options.domain || constants_CONSTANTS.WILDCARD;
1450 var hash = options.name + "_" + uniqueID();
1451 if (Object(src.isWindowClosed)(win)) throw new Error("Target window is closed");
1452 var hasResult = !1, requestPromises = global.requestPromises.get(win);
1453 if (!requestPromises) {
1454 requestPromises = [];
1455 global.requestPromises.set(win, requestPromises);
1456 }
1457 var requestPromise = promise_ZalgoPromise.try(function() {
1458 if (Object(src.isAncestor)(window, win)) return function(win) {
1459 var timeout = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 5e3, name = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : "Window", promise = global.readyPromises.get(win);
1460 if (promise) return promise;
1461 promise = new promise_ZalgoPromise();
1462 global.readyPromises.set(win, promise);
1463 -1 !== timeout && setTimeout(function() {
1464 return promise.reject(new Error(name + " did not load after " + timeout + "ms"));
1465 }, timeout);
1466 return promise;
1467 }(win, options.timeout || CONFIG.CHILD_WINDOW_TIMEOUT);
1468 }).then(function() {
1469 var origin = (arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}).origin;
1470 if (isRegex(domain) && !origin) return sayHello(win);
1471 }).then(function() {
1472 var origin = (arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}).origin;
1473 if (isRegex(domain)) {
1474 if (!Object(src.matchDomain)(domain, origin)) throw new Error("Remote window domain " + origin + " does not match regex: " + domain.toString());
1475 domain = origin;
1476 }
1477 if ("string" != typeof domain && !Array.isArray(domain)) throw new TypeError("Expected domain to be a string or array");
1478 var actualDomain = domain;
1479 return new promise_ZalgoPromise(function(resolve, reject) {
1480 var responseListener = void 0;
1481 options.fireAndForget || function(hash, listener) {
1482 global.responseListeners[hash] = listener;
1483 }(hash, responseListener = {
1484 name: name,
1485 window: win,
1486 domain: actualDomain,
1487 respond: function(err, result) {
1488 if (!err) {
1489 hasResult = !0;
1490 requestPromises.splice(requestPromises.indexOf(requestPromise, 1));
1491 }
1492 err ? reject(err) : resolve(result);
1493 }
1494 });
1495 sendMessage(win, {
1496 type: constants_CONSTANTS.POST_MESSAGE_TYPE.REQUEST,
1497 hash: hash,
1498 name: name,
1499 data: options.data,
1500 fireAndForget: options.fireAndForget
1501 }, actualDomain).catch(reject);
1502 if (options.fireAndForget) return resolve();
1503 var ackTimeout = CONFIG.ACK_TIMEOUT, resTimeout = options.timeout || CONFIG.RES_TIMEOUT, cycleTime = 100;
1504 setTimeout(function cycle() {
1505 if (!hasResult) {
1506 if (Object(src.isWindowClosed)(win)) return responseListener.ack ? reject(new Error("Window closed for " + name + " before response")) : reject(new Error("Window closed for " + name + " before ack"));
1507 ackTimeout = Math.max(ackTimeout - cycleTime, 0);
1508 -1 !== resTimeout && (resTimeout = Math.max(resTimeout - cycleTime, 0));
1509 if (responseListener.ack) {
1510 if (-1 === resTimeout) return;
1511 cycleTime = Math.min(resTimeout, 2e3);
1512 } else {
1513 if (0 === ackTimeout) return reject(new Error("No ack for postMessage " + name + " in " + Object(src.getDomain)() + " in " + CONFIG.ACK_TIMEOUT + "ms"));
1514 if (0 === resTimeout) return reject(new Error("No response for postMessage " + name + " in " + Object(src.getDomain)() + " in " + (options.timeout || CONFIG.RES_TIMEOUT) + "ms"));
1515 }
1516 setTimeout(cycle, cycleTime);
1517 }
1518 }, cycleTime);
1519 });
1520 });
1521 requestPromise.catch(function() {
1522 !function(hash) {
1523 global.erroredResponseListeners[hash] = !0;
1524 }(hash);
1525 deleteResponseListener(hash);
1526 });
1527 requestPromises.push(requestPromise);
1528 return requestPromise;
1529 });
1530 }
1531 function _send(window, name, data, options) {
1532 (options = options || {}).window = window;
1533 options.name = name;
1534 options.data = data;
1535 return request(options);
1536 }
1537 function sendToParent(name, data, options) {
1538 var win = Object(src.getAncestor)();
1539 return win ? _send(win, name, data, options) : new promise_ZalgoPromise(function(resolve, reject) {
1540 return reject(new Error("Window does not have a parent"));
1541 });
1542 }
1543 function client() {
1544 var options = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
1545 if (!options.window) throw new Error("Expected options.window");
1546 var win = options.window;
1547 return {
1548 send: function(name, data) {
1549 return _send(win, name, data, options);
1550 }
1551 };
1552 }
1553 global.send = _send;
1554 var server__typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
1555 return typeof obj;
1556 } : function(obj) {
1557 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1558 };
1559 function listen(options) {
1560 if (!options.name) throw new Error("Expected options.name");
1561 if (!options.handler) throw new Error("Expected options.handler");
1562 var name = options.name, win = options.window, domain = options.domain, listenerOptions = {
1563 handler: options.handler,
1564 handleError: options.errorHandler || function(err) {
1565 throw err;
1566 },
1567 window: win,
1568 domain: domain || constants_CONSTANTS.WILDCARD,
1569 name: name
1570 }, requestListener = function addRequestListener(_ref6, listener) {
1571 var name = _ref6.name, win = _ref6.win, domain = _ref6.domain;
1572 if (!name || "string" != typeof name) throw new Error("Name required to add request listener");
1573 if (Array.isArray(win)) {
1574 for (var listenersCollection = [], _i6 = 0, _win2 = win, _length6 = null == _win2 ? 0 : _win2.length; _i6 < _length6; _i6++) {
1575 var item = _win2[_i6];
1576 listenersCollection.push(addRequestListener({
1577 name: name,
1578 domain: domain,
1579 win: item
1580 }, listener));
1581 }
1582 return {
1583 cancel: function() {
1584 for (var _i8 = 0, _length8 = null == listenersCollection ? 0 : listenersCollection.length; _i8 < _length8; _i8++) listenersCollection[_i8].cancel();
1585 }
1586 };
1587 }
1588 if (Array.isArray(domain)) {
1589 for (var _listenersCollection = [], _i10 = 0, _domain2 = domain, _length10 = null == _domain2 ? 0 : _domain2.length; _i10 < _length10; _i10++) {
1590 var _item = _domain2[_i10];
1591 _listenersCollection.push(addRequestListener({
1592 name: name,
1593 win: win,
1594 domain: _item
1595 }, listener));
1596 }
1597 return {
1598 cancel: function() {
1599 for (var _i12 = 0, _length12 = null == _listenersCollection ? 0 : _listenersCollection.length; _i12 < _length12; _i12++) _listenersCollection[_i12].cancel();
1600 }
1601 };
1602 }
1603 var existingListener = getRequestListener({
1604 name: name,
1605 win: win,
1606 domain: domain
1607 });
1608 win && win !== constants_CONSTANTS.WILDCARD || (win = global.WINDOW_WILDCARD);
1609 domain = domain || constants_CONSTANTS.WILDCARD;
1610 if (existingListener) throw win && domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString() + " for " + (win === global.WINDOW_WILDCARD ? "wildcard" : "specified") + " window") : win ? new Error("Request listener already exists for " + name + " for " + (win === global.WINDOW_WILDCARD ? "wildcard" : "specified") + " window") : domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString()) : new Error("Request listener already exists for " + name);
1611 var requestListeners = global.requestListeners, nameListeners = requestListeners[name];
1612 if (!nameListeners) {
1613 nameListeners = new weakmap_CrossDomainSafeWeakMap();
1614 requestListeners[name] = nameListeners;
1615 }
1616 var winListeners = nameListeners.get(win);
1617 if (!winListeners) {
1618 winListeners = {};
1619 nameListeners.set(win, winListeners);
1620 }
1621 var strDomain = domain.toString(), regexListeners = winListeners[__DOMAIN_REGEX__], regexListener = void 0;
1622 if (isRegex(domain)) {
1623 if (!regexListeners) {
1624 regexListeners = [];
1625 winListeners[__DOMAIN_REGEX__] = regexListeners;
1626 }
1627 regexListener = {
1628 regex: domain,
1629 listener: listener
1630 };
1631 regexListeners.push(regexListener);
1632 } else winListeners[strDomain] = listener;
1633 return {
1634 cancel: function() {
1635 if (winListeners) {
1636 delete winListeners[strDomain];
1637 win && 0 === Object.keys(winListeners).length && nameListeners.delete(win);
1638 regexListener && regexListeners.splice(regexListeners.indexOf(regexListener, 1));
1639 }
1640 }
1641 };
1642 }({
1643 name: name,
1644 win: win,
1645 domain: domain
1646 }, listenerOptions);
1647 if (options.once) {
1648 var _handler = listenerOptions.handler;
1649 listenerOptions.handler = once(function() {
1650 requestListener.cancel();
1651 return _handler.apply(this, arguments);
1652 });
1653 }
1654 if (listenerOptions.window && options.errorOnClose) var interval = function(method, time) {
1655 var timeout = void 0;
1656 timeout = setTimeout(function runInterval() {
1657 timeout = setTimeout(runInterval, 50);
1658 (function() {
1659 if (win && "object" === (void 0 === win ? "undefined" : server__typeof(win)) && Object(src.isWindowClosed)(win)) {
1660 interval.cancel();
1661 listenerOptions.handleError(new Error("Post message target window is closed"));
1662 }
1663 }).call();
1664 }, 50);
1665 return {
1666 cancel: function() {
1667 clearTimeout(timeout);
1668 }
1669 };
1670 }();
1671 return {
1672 cancel: function() {
1673 requestListener.cancel();
1674 }
1675 };
1676 }
1677 function _on(name, options, handler) {
1678 if ("function" == typeof options) {
1679 handler = options;
1680 options = {};
1681 }
1682 (options = options || {}).name = name;
1683 options.handler = handler || options.handler;
1684 return listen(options);
1685 }
1686 function server_once(name) {
1687 var options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, handler = arguments[2];
1688 if ("function" == typeof options) {
1689 handler = options;
1690 options = {};
1691 }
1692 options = options || {};
1693 handler = handler || options.handler;
1694 var errorHandler = options.errorHandler, promise = new promise_ZalgoPromise(function(resolve, reject) {
1695 (options = options || {}).name = name;
1696 options.once = !0;
1697 options.handler = function(event) {
1698 resolve(event);
1699 if (handler) return handler(event);
1700 };
1701 options.errorHandler = function(err) {
1702 reject(err);
1703 if (errorHandler) return errorHandler(err);
1704 };
1705 }), onceListener = listen(options);
1706 promise.cancel = onceListener.cancel;
1707 return promise;
1708 }
1709 function server_listener() {
1710 var options = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
1711 return {
1712 on: function(name, handler) {
1713 return _on(name, options, handler);
1714 }
1715 };
1716 }
1717 global.on = _on;
1718 function disable() {
1719 delete window[constants_CONSTANTS.WINDOW_PROPS.POSTROBOT];
1720 window.removeEventListener("message", messageListener);
1721 }
1722 var public_parent = Object(src.getAncestor)();
1723 function cleanUpWindow(win) {
1724 var requestPromises = global.requestPromises.get(win);
1725 if (requestPromises) for (var _i2 = 0, _length2 = null == requestPromises ? 0 : requestPromises.length; _i2 < _length2; _i2++) requestPromises[_i2].reject(new Error("No response from window - cleaned up"));
1726 global.popupWindowsByWin && global.popupWindowsByWin.delete(win);
1727 global.remoteWindows && global.remoteWindows.delete(win);
1728 global.requestPromises.delete(win);
1729 global.methods.delete(win);
1730 global.readyPromises.delete(win);
1731 }
1732 var bridge = null;
1733 function init() {
1734 if (!global.initialized) {
1735 handler = messageListener, (obj = window).addEventListener ? obj.addEventListener("message", handler) : obj.attachEvent("onmessage", handler);
1736 !function() {
1737 handler = function(_ref3) {
1738 var source = _ref3.source, origin = _ref3.origin, promise = global.readyPromises.get(source) || new promise_ZalgoPromise();
1739 promise.resolve({
1740 origin: origin
1741 });
1742 global.readyPromises.set(source, promise);
1743 }, global.on(constants_CONSTANTS.POST_MESSAGE_NAMES.HELLO, {
1744 domain: constants_CONSTANTS.WILDCARD
1745 }, function(_ref) {
1746 var source = _ref.source, origin = _ref.origin;
1747 return handler({
1748 source: source,
1749 origin: origin
1750 });
1751 });
1752 var handler, parent = Object(src.getAncestor)();
1753 parent && sayHello(parent).catch(util_noop);
1754 }();
1755 listenForMethods({
1756 on: _on,
1757 send: _send
1758 });
1759 }
1760 var obj, handler;
1761 global.initialized = !0;
1762 }
1763 init();
1764 __webpack_require__.d(__webpack_exports__, "cleanUpWindow", function() {
1765 return cleanUpWindow;
1766 });
1767 __webpack_require__.d(__webpack_exports__, "Promise", function() {
1768 return promise_ZalgoPromise;
1769 });
1770 __webpack_require__.d(__webpack_exports__, "bridge", function() {
1771 return bridge;
1772 });
1773 __webpack_require__.d(__webpack_exports__, "init", function() {
1774 return init;
1775 });
1776 __webpack_require__.d(__webpack_exports__, "parent", function() {
1777 return public_parent;
1778 });
1779 __webpack_require__.d(__webpack_exports__, "send", function() {
1780 return _send;
1781 });
1782 __webpack_require__.d(__webpack_exports__, "request", function() {
1783 return request;
1784 });
1785 __webpack_require__.d(__webpack_exports__, "sendToParent", function() {
1786 return sendToParent;
1787 });
1788 __webpack_require__.d(__webpack_exports__, "client", function() {
1789 return client;
1790 });
1791 __webpack_require__.d(__webpack_exports__, "on", function() {
1792 return _on;
1793 });
1794 __webpack_require__.d(__webpack_exports__, "listen", function() {
1795 return listen;
1796 });
1797 __webpack_require__.d(__webpack_exports__, "once", function() {
1798 return server_once;
1799 });
1800 __webpack_require__.d(__webpack_exports__, "listener", function() {
1801 return server_listener;
1802 });
1803 __webpack_require__.d(__webpack_exports__, "CONFIG", function() {
1804 return CONFIG;
1805 });
1806 __webpack_require__.d(__webpack_exports__, "CONSTANTS", function() {
1807 return constants_CONSTANTS;
1808 });
1809 __webpack_require__.d(__webpack_exports__, "disable", function() {
1810 return disable;
1811 });
1812 __webpack_exports__.default = src_interface_namespaceObject;
1813 }
1814 });
1815 });
1816
1817 });
1818
1819 unwrapExports(postRobot);
1820 var postRobot_1 = postRobot.postRobot;
1821
1822 var postRobot$2 = createCommonjsModule(function (module) {
1823 /* @flow */
1824
1825 // eslint-disable-next-line import/no-commonjs
1826 module.exports = postRobot;
1827
1828 // eslint-disable-next-line import/no-commonjs
1829 module.exports.default = module.exports;
1830 });
1831
1832 var logger_browser = createCommonjsModule(function (module, exports) {
1833 !function(e,n){module.exports=n();}(commonjsGlobal,function(){var e=1e3,n=60*e,t=60*n,r=24*t,s=7*r,o=365.25*r,a=function(a,i){i=i||{};var u=typeof a;if("string"===u&&a.length>0)return function(a){if((a=String(a)).length>100)return;var c=/^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!c)return;var i=parseFloat(c[1]);switch((c[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o;case"weeks":case"week":case"w":return i*s;case"days":case"day":case"d":return i*r;case"hours":case"hour":case"hrs":case"hr":case"h":return i*t;case"minutes":case"minute":case"mins":case"min":case"m":return i*n;case"seconds":case"second":case"secs":case"sec":case"s":return i*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}(a);if("number"===u&&!1===isNaN(a))return i.long?function(s){var o=Math.abs(s);if(o>=r)return c(s,o,r,"day");if(o>=t)return c(s,o,t,"hour");if(o>=n)return c(s,o,n,"minute");if(o>=e)return c(s,o,e,"second");return s+" ms"}(a):function(s){var o=Math.abs(s);if(o>=r)return Math.round(s/r)+"d";if(o>=t)return Math.round(s/t)+"h";if(o>=n)return Math.round(s/n)+"m";if(o>=e)return Math.round(s/e)+"s";return s+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))};function c(e,n,t,r){var s=n>=1.5*t;return Math.round(e/t)+" "+r+(s?"s":"")}var i,u=function(e){function n(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]}function t(e){let o;function a(...e){if(!a.enabled)return;const n=a,r=Number(new Date),s=r-(o||r);n.diff=s,n.prev=o,n.curr=r,o=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let c=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,s)=>{if("%%"===r)return r;c++;const o=t.formatters[s];if("function"==typeof o){const t=e[c];r=o.call(n,t),e.splice(c,1),c--;}return r}),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e);}return a.namespace=e,a.enabled=t.enabled(e),a.useColors=t.useColors(),a.color=n(e),a.destroy=r,a.extend=s,"function"==typeof t.init&&t.init(a),t.instances.push(a),a}function r(){const e=t.instances.indexOf(this);return -1!==e&&(t.instances.splice(e,1),!0)}function s(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(o),...t.skips.map(o).map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(n=0;n<t.instances.length;n++){const e=t.instances[n];e.enabled=t.enabled(e.namespace);}},t.enabled=function(e){if("*"===e[e.length-1])return !0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return !1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return !0;return !1},t.humanize=a,Object.keys(e).forEach(n=>{t[n]=e[n];}),t.instances=[],t.names=[],t.skips=[],t.formatters={},t.selectColor=n,t.enable(t.load()),t},C=(function(e,n){n.log=function(...e){return "object"==typeof console&&console.log&&console.log(...e)},n.formatArgs=function(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const t="color: "+this.color;n.splice(1,0,t,"color: inherit");let r=0,s=0;n[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(r++,"%c"===e&&(s=r));}),n.splice(s,0,t);},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug");}catch(e){}},n.load=function(){let e;try{e=n.storage.getItem("debug");}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},n.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return !0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return !1;return "undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},n.storage=function(){try{return localStorage}catch(e){}}(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.exports=u(n);const{formatters:t}=e.exports;t.j=function(e){try{return JSON.stringify(e)}catch(e){return "[UnexpectedJSONParseError]: "+e.message}};}(i={exports:{}},i.exports),i.exports);C.log,C.formatArgs,C.save,C.load,C.useColors,C.storage,C.colors;return e=>C(`bearer:${e}`)});
1834 });
1835
1836 var logger = logger_browser('js');
1837
1838 function cleanQuery(params) {
1839 return Object.keys(params).reduce((acc, key) => {
1840 if (params[key]) {
1841 acc[key] = params[key];
1842 }
1843 return acc;
1844 }, {});
1845 }
1846 function formatQuery(params) {
1847 return Object.keys(cleanQuery(params))
1848 .reduce((acc, key) => {
1849 return [...acc, [key, params[key]].join('=')];
1850 }, [])
1851 .join('&');
1852 }
1853
1854 const logger$1 = logger.extend('Bearer');
1855 const prefix = 'bearer';
1856 const DEFAULT_OPTIONS = {
1857 secured: undefined,
1858 integrationHost: 'http://localhost:3000',
1859 domObserver: true,
1860 refreshDebounceDelay: 200
1861 };
1862 class Bearer {
1863 constructor(clientId, options = {}) {
1864 this.clientId = clientId;
1865 this.config = DEFAULT_OPTIONS;
1866 this.registeredIntegrations = {};
1867 // TODO: move to a dedicated file
1868 /**
1869 * `connect` lets you easily retrieve `auth-id` for an integration using OAuth authentication. Before using it, you'll need to generate a `setup-id` with the setup component of your integration
1870 * @argument {string} integration the identifier of the Integration you want to connect to ex: 12345-attach-github-pull-request
1871 * @argument {string} setupId Setup's identifier you received earlier, a Bearer reference containing all required information about auth mechanism
1872 * @argument {Object} options Optional parameters like authId if you already have one
1873 */
1874 this.connect = (integration, setupId, { authId } = {}) => {
1875 const query = formatQuery({
1876 setupId,
1877 authId,
1878 secured: this.config.secured,
1879 clientId: this.clientId
1880 });
1881 const AUTHORIZED_URL = `${this.config.integrationHost}/v2/auth/${integration}?${query}`;
1882 // TODO: get rid of post robot, too heqvy for our needs
1883 const promise = new Promise((resolve, reject) => {
1884 // TODO: use constants
1885 if (this.authorizedListener) {
1886 logger('canceling previous listener');
1887 this.authorizedListener.cancel();
1888 this.rejectedListener.cancel();
1889 }
1890 logger('add authorization listeners');
1891 this.authorizedListener = postRobot$2.on('BEARER_AUTHORIZED', ({ data }) => {
1892 logger('Authorized: %s => %j', integration, data);
1893 resolve(Object.assign({}, data, { integration }));
1894 });
1895 this.rejectedListener = postRobot$2.on('BEARER_REJECTED', ({ data }) => {
1896 logger('Rejected: %s => %j', integration, data);
1897 reject(Object.assign({}, data, { integration }));
1898 });
1899 }).then();
1900 window.open(AUTHORIZED_URL, '', 'resizable,scrollbars,status,centerscreen=yes,width=500,height=600');
1901 return promise;
1902 };
1903 this._jsonRequest = (path, { query = {}, params = {} } = {}) => __awaiter(this, void 0, void 0, function* () {
1904 const url = [this.config.integrationHost, path].join('');
1905 const queryParams = Object.assign({}, query, { clientId: this.clientId, secured: this.config.secured });
1906 const queryString = buildQuery(cleanOptions(queryParams));
1907 logger$1('json request: path %s', path);
1908 return fetch(`${url}?${queryString}`, {
1909 method: 'POST',
1910 body: JSON.stringify(params || {}),
1911 headers: {
1912 'content-type': 'application/json'
1913 },
1914 credentials: 'include'
1915 }).then((response) => __awaiter(this, void 0, void 0, function* () {
1916 if (response.status > 399) {
1917 logger$1('failing request %j', yield response.clone().json());
1918 }
1919 return response;
1920 }));
1921 });
1922 this.invoke = (integrationId, functionName, _a = {}) => __awaiter(this, void 0, void 0, function* () {
1923 var { query = {} } = _a, params = __rest(_a, ["query"]);
1924 const path = `/api/v4/functions/${integrationId}/${functionName}`;
1925 try {
1926 const response = yield this._jsonRequest(path, { query, params });
1927 const payload = yield response.json();
1928 logger$1('successful request %j', payload);
1929 if (!payload.error) {
1930 return payload;
1931 }
1932 else {
1933 throw { error: payload.error };
1934 }
1935 }
1936 catch (error) {
1937 logger$1('invoke failed %j', error, error.message);
1938 throw { error };
1939 }
1940 });
1941 /**
1942 * Retrieve all dom elements starting by bearer- and ask for assets urls if
1943 */
1944 this.loadMissingIntegrations = () => {
1945 const elements = findElements(document.getElementsByTagName('*'));
1946 const requestedElements = elements.filter(t => !this.registeredIntegration(t));
1947 logger$1(this.registeredIntegrations, elements, requestedElements);
1948 this.sendTags(requestedElements);
1949 };
1950 /**
1951 * check wether if an integration is resgistered
1952 */
1953 this.registeredIntegration = (tagName) => {
1954 // NOTE:
1955 // .constructor !== HTMLElement looks weird but it does not work the other way ¯\_(ツ)_/¯
1956 // constructor is supposed to be class extends HTMLElement{}
1957 this.registeredIntegrations[tagName] =
1958 this.registeredIntegrations[tagName] || document.createElement(tagName).constructor !== HTMLElement;
1959 return this.registeredIntegrations[tagName];
1960 };
1961 /**
1962 * load integration asset or wait until dom is loaded
1963 */
1964 this.initialIntegrationLoading = () => {
1965 if (document.readyState === 'complete' || document.readyState === 'interactive') {
1966 this.debounceRefresh();
1967 }
1968 else {
1969 document.addEventListener('DOMContentLoaded', this.debounceRefresh);
1970 }
1971 };
1972 /**
1973 * Register a DOM observer so that we can load integration assets only when we need them
1974 */
1975 this.registerDomObserver = () => {
1976 if ('MutationObserver' in window) {
1977 this.disconnectObserver();
1978 const container = document.documentElement || document.body;
1979 const config = { childList: true, subtree: true };
1980 this.observer = new MutationObserver(this.observerCallback);
1981 this.observer.observe(container, config);
1982 }
1983 };
1984 this.observerCallback = (mutations) => {
1985 for (const mutation of mutations) {
1986 if (mutation.type == 'childList') {
1987 if (mutation.addedNodes.length) {
1988 this.debounceRefresh();
1989 }
1990 }
1991 }
1992 };
1993 /**
1994 * remove dom observer
1995 */
1996 this.disconnectObserver = () => {
1997 if (this.observer) {
1998 this.observer.disconnect();
1999 delete this.observer;
2000 }
2001 };
2002 /**
2003 * retrieve corresponding integration asset url
2004 */
2005 this.sendTags = (tags) => __awaiter(this, void 0, void 0, function* () {
2006 if (!tags.length) {
2007 return Promise.resolve(true);
2008 }
2009 try {
2010 const response = yield fetch(`${this.config.integrationHost}/v1/parse-tags`, {
2011 headers: { 'content-type': 'application/json' },
2012 body: JSON.stringify({ tags, clientId: this.clientId }),
2013 method: 'POST'
2014 });
2015 if (response.status > 299) {
2016 throw new Error(`Error while fetching integration tag names: ${tags}`);
2017 }
2018 const integrations = yield response.json();
2019 integrations.map(integration => {
2020 if (!document.querySelector(`#${getScriptId(integration.uuid)}`)) {
2021 document.body.appendChild(getScriptDOM(this.clientId || '', integration));
2022 }
2023 });
2024 return true;
2025 }
2026 catch (e) {
2027 return false;
2028 }
2029 });
2030 this.config = Object.assign({}, DEFAULT_OPTIONS, cleanOptions(options));
2031 this.secured = this.config.secured;
2032 logger$1('init bearer instance clientId: %s with config: %j', clientId, this.config);
2033 this.debounceRefresh = debounce_1(this.loadMissingIntegrations, this.config.refreshDebounceDelay);
2034 }
2035 }
2036 /**
2037 * Extract/format element tag names given a regexp
2038 * @param elements
2039 * @param filter
2040 */
2041 function findElements(elements, filter = /^bearer-/i) {
2042 return Array.from(elements)
2043 .filter(el => filter.test(el.tagName))
2044 .map(el => el.tagName.toLowerCase());
2045 }
2046 /**
2047 * Return the bearer script id
2048 * @param uuid
2049 */
2050 function getScriptId(uuid) {
2051 return `${prefix}-${uuid}`; // id must start with a letter
2052 }
2053 /**
2054 * create a script tag for a given integration
2055 * @param clientId
2056 * @param integration
2057 */
2058 function getScriptDOM(clientId, integration) {
2059 const s = document.createElement('script');
2060 s.type = 'text/javascript';
2061 s.async = true;
2062 const separator = integration.asset.indexOf('?') > -1 ? '&' : '?';
2063 s.src = [integration.asset, [`clientId=${clientId}`].join('&')].join(separator);
2064 s.id = getScriptId(integration.uuid);
2065 return s;
2066 }
2067 function buildQuery(params) {
2068 function encode(k) {
2069 return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
2070 }
2071 return Object.keys(params)
2072 .map(encode)
2073 .join('&');
2074 }
2075 function cleanOptions(obj) {
2076 return Object.keys(obj).reduce((acc, key) => {
2077 if (obj[key] !== undefined) {
2078 acc[key] = obj[key];
2079 }
2080 return acc;
2081 }, {});
2082 }
2083
2084 var lodash_merge = createCommonjsModule(function (module, exports) {
2085 /**
2086 * Lodash (Custom Build) <https://lodash.com/>
2087 * Build: `lodash modularize exports="npm" -o ./`
2088 * Copyright JS Foundation and other contributors <https://js.foundation/>
2089 * Released under MIT license <https://lodash.com/license>
2090 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
2091 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
2092 */
2093
2094 /** Used as the size to enable large array optimizations. */
2095 var LARGE_ARRAY_SIZE = 200;
2096
2097 /** Used to stand-in for `undefined` hash values. */
2098 var HASH_UNDEFINED = '__lodash_hash_undefined__';
2099
2100 /** Used to detect hot functions by number of calls within a span of milliseconds. */
2101 var HOT_COUNT = 800,
2102 HOT_SPAN = 16;
2103
2104 /** Used as references for various `Number` constants. */
2105 var MAX_SAFE_INTEGER = 9007199254740991;
2106
2107 /** `Object#toString` result references. */
2108 var argsTag = '[object Arguments]',
2109 arrayTag = '[object Array]',
2110 asyncTag = '[object AsyncFunction]',
2111 boolTag = '[object Boolean]',
2112 dateTag = '[object Date]',
2113 errorTag = '[object Error]',
2114 funcTag = '[object Function]',
2115 genTag = '[object GeneratorFunction]',
2116 mapTag = '[object Map]',
2117 numberTag = '[object Number]',
2118 nullTag = '[object Null]',
2119 objectTag = '[object Object]',
2120 proxyTag = '[object Proxy]',
2121 regexpTag = '[object RegExp]',
2122 setTag = '[object Set]',
2123 stringTag = '[object String]',
2124 undefinedTag = '[object Undefined]',
2125 weakMapTag = '[object WeakMap]';
2126
2127 var arrayBufferTag = '[object ArrayBuffer]',
2128 dataViewTag = '[object DataView]',
2129 float32Tag = '[object Float32Array]',
2130 float64Tag = '[object Float64Array]',
2131 int8Tag = '[object Int8Array]',
2132 int16Tag = '[object Int16Array]',
2133 int32Tag = '[object Int32Array]',
2134 uint8Tag = '[object Uint8Array]',
2135 uint8ClampedTag = '[object Uint8ClampedArray]',
2136 uint16Tag = '[object Uint16Array]',
2137 uint32Tag = '[object Uint32Array]';
2138
2139 /**
2140 * Used to match `RegExp`
2141 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
2142 */
2143 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
2144
2145 /** Used to detect host constructors (Safari). */
2146 var reIsHostCtor = /^\[object .+?Constructor\]$/;
2147
2148 /** Used to detect unsigned integer values. */
2149 var reIsUint = /^(?:0|[1-9]\d*)$/;
2150
2151 /** Used to identify `toStringTag` values of typed arrays. */
2152 var typedArrayTags = {};
2153 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
2154 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
2155 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
2156 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
2157 typedArrayTags[uint32Tag] = true;
2158 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
2159 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
2160 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
2161 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
2162 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
2163 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
2164 typedArrayTags[setTag] = typedArrayTags[stringTag] =
2165 typedArrayTags[weakMapTag] = false;
2166
2167 /** Detect free variable `global` from Node.js. */
2168 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
2169
2170 /** Detect free variable `self`. */
2171 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
2172
2173 /** Used as a reference to the global object. */
2174 var root = freeGlobal || freeSelf || Function('return this')();
2175
2176 /** Detect free variable `exports`. */
2177 var freeExports = exports && !exports.nodeType && exports;
2178
2179 /** Detect free variable `module`. */
2180 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
2181
2182 /** Detect the popular CommonJS extension `module.exports`. */
2183 var moduleExports = freeModule && freeModule.exports === freeExports;
2184
2185 /** Detect free variable `process` from Node.js. */
2186 var freeProcess = moduleExports && freeGlobal.process;
2187
2188 /** Used to access faster Node.js helpers. */
2189 var nodeUtil = (function() {
2190 try {
2191 return freeProcess && freeProcess.binding && freeProcess.binding('util');
2192 } catch (e) {}
2193 }());
2194
2195 /* Node.js helper references. */
2196 var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
2197
2198 /**
2199 * A faster alternative to `Function#apply`, this function invokes `func`
2200 * with the `this` binding of `thisArg` and the arguments of `args`.
2201 *
2202 * @private
2203 * @param {Function} func The function to invoke.
2204 * @param {*} thisArg The `this` binding of `func`.
2205 * @param {Array} args The arguments to invoke `func` with.
2206 * @returns {*} Returns the result of `func`.
2207 */
2208 function apply(func, thisArg, args) {
2209 switch (args.length) {
2210 case 0: return func.call(thisArg);
2211 case 1: return func.call(thisArg, args[0]);
2212 case 2: return func.call(thisArg, args[0], args[1]);
2213 case 3: return func.call(thisArg, args[0], args[1], args[2]);
2214 }
2215 return func.apply(thisArg, args);
2216 }
2217
2218 /**
2219 * The base implementation of `_.times` without support for iteratee shorthands
2220 * or max array length checks.
2221 *
2222 * @private
2223 * @param {number} n The number of times to invoke `iteratee`.
2224 * @param {Function} iteratee The function invoked per iteration.
2225 * @returns {Array} Returns the array of results.
2226 */
2227 function baseTimes(n, iteratee) {
2228 var index = -1,
2229 result = Array(n);
2230
2231 while (++index < n) {
2232 result[index] = iteratee(index);
2233 }
2234 return result;
2235 }
2236
2237 /**
2238 * The base implementation of `_.unary` without support for storing metadata.
2239 *
2240 * @private
2241 * @param {Function} func The function to cap arguments for.
2242 * @returns {Function} Returns the new capped function.
2243 */
2244 function baseUnary(func) {
2245 return function(value) {
2246 return func(value);
2247 };
2248 }
2249
2250 /**
2251 * Gets the value at `key` of `object`.
2252 *
2253 * @private
2254 * @param {Object} [object] The object to query.
2255 * @param {string} key The key of the property to get.
2256 * @returns {*} Returns the property value.
2257 */
2258 function getValue(object, key) {
2259 return object == null ? undefined : object[key];
2260 }
2261
2262 /**
2263 * Creates a unary function that invokes `func` with its argument transformed.
2264 *
2265 * @private
2266 * @param {Function} func The function to wrap.
2267 * @param {Function} transform The argument transform.
2268 * @returns {Function} Returns the new function.
2269 */
2270 function overArg(func, transform) {
2271 return function(arg) {
2272 return func(transform(arg));
2273 };
2274 }
2275
2276 /**
2277 * Gets the value at `key`, unless `key` is "__proto__".
2278 *
2279 * @private
2280 * @param {Object} object The object to query.
2281 * @param {string} key The key of the property to get.
2282 * @returns {*} Returns the property value.
2283 */
2284 function safeGet(object, key) {
2285 return key == '__proto__'
2286 ? undefined
2287 : object[key];
2288 }
2289
2290 /** Used for built-in method references. */
2291 var arrayProto = Array.prototype,
2292 funcProto = Function.prototype,
2293 objectProto = Object.prototype;
2294
2295 /** Used to detect overreaching core-js shims. */
2296 var coreJsData = root['__core-js_shared__'];
2297
2298 /** Used to resolve the decompiled source of functions. */
2299 var funcToString = funcProto.toString;
2300
2301 /** Used to check objects for own properties. */
2302 var hasOwnProperty = objectProto.hasOwnProperty;
2303
2304 /** Used to detect methods masquerading as native. */
2305 var maskSrcKey = (function() {
2306 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
2307 return uid ? ('Symbol(src)_1.' + uid) : '';
2308 }());
2309
2310 /**
2311 * Used to resolve the
2312 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
2313 * of values.
2314 */
2315 var nativeObjectToString = objectProto.toString;
2316
2317 /** Used to infer the `Object` constructor. */
2318 var objectCtorString = funcToString.call(Object);
2319
2320 /** Used to detect if a method is native. */
2321 var reIsNative = RegExp('^' +
2322 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
2323 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
2324 );
2325
2326 /** Built-in value references. */
2327 var Buffer = moduleExports ? root.Buffer : undefined,
2328 Symbol = root.Symbol,
2329 Uint8Array = root.Uint8Array,
2330 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
2331 getPrototype = overArg(Object.getPrototypeOf, Object),
2332 objectCreate = Object.create,
2333 propertyIsEnumerable = objectProto.propertyIsEnumerable,
2334 splice = arrayProto.splice,
2335 symToStringTag = Symbol ? Symbol.toStringTag : undefined;
2336
2337 var defineProperty = (function() {
2338 try {
2339 var func = getNative(Object, 'defineProperty');
2340 func({}, '', {});
2341 return func;
2342 } catch (e) {}
2343 }());
2344
2345 /* Built-in method references for those with the same name as other `lodash` methods. */
2346 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
2347 nativeMax = Math.max,
2348 nativeNow = Date.now;
2349
2350 /* Built-in method references that are verified to be native. */
2351 var Map = getNative(root, 'Map'),
2352 nativeCreate = getNative(Object, 'create');
2353
2354 /**
2355 * The base implementation of `_.create` without support for assigning
2356 * properties to the created object.
2357 *
2358 * @private
2359 * @param {Object} proto The object to inherit from.
2360 * @returns {Object} Returns the new object.
2361 */
2362 var baseCreate = (function() {
2363 function object() {}
2364 return function(proto) {
2365 if (!isObject(proto)) {
2366 return {};
2367 }
2368 if (objectCreate) {
2369 return objectCreate(proto);
2370 }
2371 object.prototype = proto;
2372 var result = new object;
2373 object.prototype = undefined;
2374 return result;
2375 };
2376 }());
2377
2378 /**
2379 * Creates a hash object.
2380 *
2381 * @private
2382 * @constructor
2383 * @param {Array} [entries] The key-value pairs to cache.
2384 */
2385 function Hash(entries) {
2386 var index = -1,
2387 length = entries == null ? 0 : entries.length;
2388
2389 this.clear();
2390 while (++index < length) {
2391 var entry = entries[index];
2392 this.set(entry[0], entry[1]);
2393 }
2394 }
2395
2396 /**
2397 * Removes all key-value entries from the hash.
2398 *
2399 * @private
2400 * @name clear
2401 * @memberOf Hash
2402 */
2403 function hashClear() {
2404 this.__data__ = nativeCreate ? nativeCreate(null) : {};
2405 this.size = 0;
2406 }
2407
2408 /**
2409 * Removes `key` and its value from the hash.
2410 *
2411 * @private
2412 * @name delete
2413 * @memberOf Hash
2414 * @param {Object} hash The hash to modify.
2415 * @param {string} key The key of the value to remove.
2416 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2417 */
2418 function hashDelete(key) {
2419 var result = this.has(key) && delete this.__data__[key];
2420 this.size -= result ? 1 : 0;
2421 return result;
2422 }
2423
2424 /**
2425 * Gets the hash value for `key`.
2426 *
2427 * @private
2428 * @name get
2429 * @memberOf Hash
2430 * @param {string} key The key of the value to get.
2431 * @returns {*} Returns the entry value.
2432 */
2433 function hashGet(key) {
2434 var data = this.__data__;
2435 if (nativeCreate) {
2436 var result = data[key];
2437 return result === HASH_UNDEFINED ? undefined : result;
2438 }
2439 return hasOwnProperty.call(data, key) ? data[key] : undefined;
2440 }
2441
2442 /**
2443 * Checks if a hash value for `key` exists.
2444 *
2445 * @private
2446 * @name has
2447 * @memberOf Hash
2448 * @param {string} key The key of the entry to check.
2449 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2450 */
2451 function hashHas(key) {
2452 var data = this.__data__;
2453 return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
2454 }
2455
2456 /**
2457 * Sets the hash `key` to `value`.
2458 *
2459 * @private
2460 * @name set
2461 * @memberOf Hash
2462 * @param {string} key The key of the value to set.
2463 * @param {*} value The value to set.
2464 * @returns {Object} Returns the hash instance.
2465 */
2466 function hashSet(key, value) {
2467 var data = this.__data__;
2468 this.size += this.has(key) ? 0 : 1;
2469 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
2470 return this;
2471 }
2472
2473 // Add methods to `Hash`.
2474 Hash.prototype.clear = hashClear;
2475 Hash.prototype['delete'] = hashDelete;
2476 Hash.prototype.get = hashGet;
2477 Hash.prototype.has = hashHas;
2478 Hash.prototype.set = hashSet;
2479
2480 /**
2481 * Creates an list cache object.
2482 *
2483 * @private
2484 * @constructor
2485 * @param {Array} [entries] The key-value pairs to cache.
2486 */
2487 function ListCache(entries) {
2488 var index = -1,
2489 length = entries == null ? 0 : entries.length;
2490
2491 this.clear();
2492 while (++index < length) {
2493 var entry = entries[index];
2494 this.set(entry[0], entry[1]);
2495 }
2496 }
2497
2498 /**
2499 * Removes all key-value entries from the list cache.
2500 *
2501 * @private
2502 * @name clear
2503 * @memberOf ListCache
2504 */
2505 function listCacheClear() {
2506 this.__data__ = [];
2507 this.size = 0;
2508 }
2509
2510 /**
2511 * Removes `key` and its value from the list cache.
2512 *
2513 * @private
2514 * @name delete
2515 * @memberOf ListCache
2516 * @param {string} key The key of the value to remove.
2517 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2518 */
2519 function listCacheDelete(key) {
2520 var data = this.__data__,
2521 index = assocIndexOf(data, key);
2522
2523 if (index < 0) {
2524 return false;
2525 }
2526 var lastIndex = data.length - 1;
2527 if (index == lastIndex) {
2528 data.pop();
2529 } else {
2530 splice.call(data, index, 1);
2531 }
2532 --this.size;
2533 return true;
2534 }
2535
2536 /**
2537 * Gets the list cache value for `key`.
2538 *
2539 * @private
2540 * @name get
2541 * @memberOf ListCache
2542 * @param {string} key The key of the value to get.
2543 * @returns {*} Returns the entry value.
2544 */
2545 function listCacheGet(key) {
2546 var data = this.__data__,
2547 index = assocIndexOf(data, key);
2548
2549 return index < 0 ? undefined : data[index][1];
2550 }
2551
2552 /**
2553 * Checks if a list cache value for `key` exists.
2554 *
2555 * @private
2556 * @name has
2557 * @memberOf ListCache
2558 * @param {string} key The key of the entry to check.
2559 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2560 */
2561 function listCacheHas(key) {
2562 return assocIndexOf(this.__data__, key) > -1;
2563 }
2564
2565 /**
2566 * Sets the list cache `key` to `value`.
2567 *
2568 * @private
2569 * @name set
2570 * @memberOf ListCache
2571 * @param {string} key The key of the value to set.
2572 * @param {*} value The value to set.
2573 * @returns {Object} Returns the list cache instance.
2574 */
2575 function listCacheSet(key, value) {
2576 var data = this.__data__,
2577 index = assocIndexOf(data, key);
2578
2579 if (index < 0) {
2580 ++this.size;
2581 data.push([key, value]);
2582 } else {
2583 data[index][1] = value;
2584 }
2585 return this;
2586 }
2587
2588 // Add methods to `ListCache`.
2589 ListCache.prototype.clear = listCacheClear;
2590 ListCache.prototype['delete'] = listCacheDelete;
2591 ListCache.prototype.get = listCacheGet;
2592 ListCache.prototype.has = listCacheHas;
2593 ListCache.prototype.set = listCacheSet;
2594
2595 /**
2596 * Creates a map cache object to store key-value pairs.
2597 *
2598 * @private
2599 * @constructor
2600 * @param {Array} [entries] The key-value pairs to cache.
2601 */
2602 function MapCache(entries) {
2603 var index = -1,
2604 length = entries == null ? 0 : entries.length;
2605
2606 this.clear();
2607 while (++index < length) {
2608 var entry = entries[index];
2609 this.set(entry[0], entry[1]);
2610 }
2611 }
2612
2613 /**
2614 * Removes all key-value entries from the map.
2615 *
2616 * @private
2617 * @name clear
2618 * @memberOf MapCache
2619 */
2620 function mapCacheClear() {
2621 this.size = 0;
2622 this.__data__ = {
2623 'hash': new Hash,
2624 'map': new (Map || ListCache),
2625 'string': new Hash
2626 };
2627 }
2628
2629 /**
2630 * Removes `key` and its value from the map.
2631 *
2632 * @private
2633 * @name delete
2634 * @memberOf MapCache
2635 * @param {string} key The key of the value to remove.
2636 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2637 */
2638 function mapCacheDelete(key) {
2639 var result = getMapData(this, key)['delete'](key);
2640 this.size -= result ? 1 : 0;
2641 return result;
2642 }
2643
2644 /**
2645 * Gets the map value for `key`.
2646 *
2647 * @private
2648 * @name get
2649 * @memberOf MapCache
2650 * @param {string} key The key of the value to get.
2651 * @returns {*} Returns the entry value.
2652 */
2653 function mapCacheGet(key) {
2654 return getMapData(this, key).get(key);
2655 }
2656
2657 /**
2658 * Checks if a map value for `key` exists.
2659 *
2660 * @private
2661 * @name has
2662 * @memberOf MapCache
2663 * @param {string} key The key of the entry to check.
2664 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2665 */
2666 function mapCacheHas(key) {
2667 return getMapData(this, key).has(key);
2668 }
2669
2670 /**
2671 * Sets the map `key` to `value`.
2672 *
2673 * @private
2674 * @name set
2675 * @memberOf MapCache
2676 * @param {string} key The key of the value to set.
2677 * @param {*} value The value to set.
2678 * @returns {Object} Returns the map cache instance.
2679 */
2680 function mapCacheSet(key, value) {
2681 var data = getMapData(this, key),
2682 size = data.size;
2683
2684 data.set(key, value);
2685 this.size += data.size == size ? 0 : 1;
2686 return this;
2687 }
2688
2689 // Add methods to `MapCache`.
2690 MapCache.prototype.clear = mapCacheClear;
2691 MapCache.prototype['delete'] = mapCacheDelete;
2692 MapCache.prototype.get = mapCacheGet;
2693 MapCache.prototype.has = mapCacheHas;
2694 MapCache.prototype.set = mapCacheSet;
2695
2696 /**
2697 * Creates a stack cache object to store key-value pairs.
2698 *
2699 * @private
2700 * @constructor
2701 * @param {Array} [entries] The key-value pairs to cache.
2702 */
2703 function Stack(entries) {
2704 var data = this.__data__ = new ListCache(entries);
2705 this.size = data.size;
2706 }
2707
2708 /**
2709 * Removes all key-value entries from the stack.
2710 *
2711 * @private
2712 * @name clear
2713 * @memberOf Stack
2714 */
2715 function stackClear() {
2716 this.__data__ = new ListCache;
2717 this.size = 0;
2718 }
2719
2720 /**
2721 * Removes `key` and its value from the stack.
2722 *
2723 * @private
2724 * @name delete
2725 * @memberOf Stack
2726 * @param {string} key The key of the value to remove.
2727 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2728 */
2729 function stackDelete(key) {
2730 var data = this.__data__,
2731 result = data['delete'](key);
2732
2733 this.size = data.size;
2734 return result;
2735 }
2736
2737 /**
2738 * Gets the stack value for `key`.
2739 *
2740 * @private
2741 * @name get
2742 * @memberOf Stack
2743 * @param {string} key The key of the value to get.
2744 * @returns {*} Returns the entry value.
2745 */
2746 function stackGet(key) {
2747 return this.__data__.get(key);
2748 }
2749
2750 /**
2751 * Checks if a stack value for `key` exists.
2752 *
2753 * @private
2754 * @name has
2755 * @memberOf Stack
2756 * @param {string} key The key of the entry to check.
2757 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2758 */
2759 function stackHas(key) {
2760 return this.__data__.has(key);
2761 }
2762
2763 /**
2764 * Sets the stack `key` to `value`.
2765 *
2766 * @private
2767 * @name set
2768 * @memberOf Stack
2769 * @param {string} key The key of the value to set.
2770 * @param {*} value The value to set.
2771 * @returns {Object} Returns the stack cache instance.
2772 */
2773 function stackSet(key, value) {
2774 var data = this.__data__;
2775 if (data instanceof ListCache) {
2776 var pairs = data.__data__;
2777 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
2778 pairs.push([key, value]);
2779 this.size = ++data.size;
2780 return this;
2781 }
2782 data = this.__data__ = new MapCache(pairs);
2783 }
2784 data.set(key, value);
2785 this.size = data.size;
2786 return this;
2787 }
2788
2789 // Add methods to `Stack`.
2790 Stack.prototype.clear = stackClear;
2791 Stack.prototype['delete'] = stackDelete;
2792 Stack.prototype.get = stackGet;
2793 Stack.prototype.has = stackHas;
2794 Stack.prototype.set = stackSet;
2795
2796 /**
2797 * Creates an array of the enumerable property names of the array-like `value`.
2798 *
2799 * @private
2800 * @param {*} value The value to query.
2801 * @param {boolean} inherited Specify returning inherited property names.
2802 * @returns {Array} Returns the array of property names.
2803 */
2804 function arrayLikeKeys(value, inherited) {
2805 var isArr = isArray(value),
2806 isArg = !isArr && isArguments(value),
2807 isBuff = !isArr && !isArg && isBuffer(value),
2808 isType = !isArr && !isArg && !isBuff && isTypedArray(value),
2809 skipIndexes = isArr || isArg || isBuff || isType,
2810 result = skipIndexes ? baseTimes(value.length, String) : [],
2811 length = result.length;
2812
2813 for (var key in value) {
2814 if ((inherited || hasOwnProperty.call(value, key)) &&
2815 !(skipIndexes && (
2816 // Safari 9 has enumerable `arguments.length` in strict mode.
2817 key == 'length' ||
2818 // Node.js 0.10 has enumerable non-index properties on buffers.
2819 (isBuff && (key == 'offset' || key == 'parent')) ||
2820 // PhantomJS 2 has enumerable non-index properties on typed arrays.
2821 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
2822 // Skip index properties.
2823 isIndex(key, length)
2824 ))) {
2825 result.push(key);
2826 }
2827 }
2828 return result;
2829 }
2830
2831 /**
2832 * This function is like `assignValue` except that it doesn't assign
2833 * `undefined` values.
2834 *
2835 * @private
2836 * @param {Object} object The object to modify.
2837 * @param {string} key The key of the property to assign.
2838 * @param {*} value The value to assign.
2839 */
2840 function assignMergeValue(object, key, value) {
2841 if ((value !== undefined && !eq(object[key], value)) ||
2842 (value === undefined && !(key in object))) {
2843 baseAssignValue(object, key, value);
2844 }
2845 }
2846
2847 /**
2848 * Assigns `value` to `key` of `object` if the existing value is not equivalent
2849 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
2850 * for equality comparisons.
2851 *
2852 * @private
2853 * @param {Object} object The object to modify.
2854 * @param {string} key The key of the property to assign.
2855 * @param {*} value The value to assign.
2856 */
2857 function assignValue(object, key, value) {
2858 var objValue = object[key];
2859 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
2860 (value === undefined && !(key in object))) {
2861 baseAssignValue(object, key, value);
2862 }
2863 }
2864
2865 /**
2866 * Gets the index at which the `key` is found in `array` of key-value pairs.
2867 *
2868 * @private
2869 * @param {Array} array The array to inspect.
2870 * @param {*} key The key to search for.
2871 * @returns {number} Returns the index of the matched value, else `-1`.
2872 */
2873 function assocIndexOf(array, key) {
2874 var length = array.length;
2875 while (length--) {
2876 if (eq(array[length][0], key)) {
2877 return length;
2878 }
2879 }
2880 return -1;
2881 }
2882
2883 /**
2884 * The base implementation of `assignValue` and `assignMergeValue` without
2885 * value checks.
2886 *
2887 * @private
2888 * @param {Object} object The object to modify.
2889 * @param {string} key The key of the property to assign.
2890 * @param {*} value The value to assign.
2891 */
2892 function baseAssignValue(object, key, value) {
2893 if (key == '__proto__' && defineProperty) {
2894 defineProperty(object, key, {
2895 'configurable': true,
2896 'enumerable': true,
2897 'value': value,
2898 'writable': true
2899 });
2900 } else {
2901 object[key] = value;
2902 }
2903 }
2904
2905 /**
2906 * The base implementation of `baseForOwn` which iterates over `object`
2907 * properties returned by `keysFunc` and invokes `iteratee` for each property.
2908 * Iteratee functions may exit iteration early by explicitly returning `false`.
2909 *
2910 * @private
2911 * @param {Object} object The object to iterate over.
2912 * @param {Function} iteratee The function invoked per iteration.
2913 * @param {Function} keysFunc The function to get the keys of `object`.
2914 * @returns {Object} Returns `object`.
2915 */
2916 var baseFor = createBaseFor();
2917
2918 /**
2919 * The base implementation of `getTag` without fallbacks for buggy environments.
2920 *
2921 * @private
2922 * @param {*} value The value to query.
2923 * @returns {string} Returns the `toStringTag`.
2924 */
2925 function baseGetTag(value) {
2926 if (value == null) {
2927 return value === undefined ? undefinedTag : nullTag;
2928 }
2929 return (symToStringTag && symToStringTag in Object(value))
2930 ? getRawTag(value)
2931 : objectToString(value);
2932 }
2933
2934 /**
2935 * The base implementation of `_.isArguments`.
2936 *
2937 * @private
2938 * @param {*} value The value to check.
2939 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
2940 */
2941 function baseIsArguments(value) {
2942 return isObjectLike(value) && baseGetTag(value) == argsTag;
2943 }
2944
2945 /**
2946 * The base implementation of `_.isNative` without bad shim checks.
2947 *
2948 * @private
2949 * @param {*} value The value to check.
2950 * @returns {boolean} Returns `true` if `value` is a native function,
2951 * else `false`.
2952 */
2953 function baseIsNative(value) {
2954 if (!isObject(value) || isMasked(value)) {
2955 return false;
2956 }
2957 var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
2958 return pattern.test(toSource(value));
2959 }
2960
2961 /**
2962 * The base implementation of `_.isTypedArray` without Node.js optimizations.
2963 *
2964 * @private
2965 * @param {*} value The value to check.
2966 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
2967 */
2968 function baseIsTypedArray(value) {
2969 return isObjectLike(value) &&
2970 isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
2971 }
2972
2973 /**
2974 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
2975 *
2976 * @private
2977 * @param {Object} object The object to query.
2978 * @returns {Array} Returns the array of property names.
2979 */
2980 function baseKeysIn(object) {
2981 if (!isObject(object)) {
2982 return nativeKeysIn(object);
2983 }
2984 var isProto = isPrototype(object),
2985 result = [];
2986
2987 for (var key in object) {
2988 if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
2989 result.push(key);
2990 }
2991 }
2992 return result;
2993 }
2994
2995 /**
2996 * The base implementation of `_.merge` without support for multiple sources.
2997 *
2998 * @private
2999 * @param {Object} object The destination object.
3000 * @param {Object} source The source object.
3001 * @param {number} srcIndex The index of `source`.
3002 * @param {Function} [customizer] The function to customize merged values.
3003 * @param {Object} [stack] Tracks traversed source values and their merged
3004 * counterparts.
3005 */
3006 function baseMerge(object, source, srcIndex, customizer, stack) {
3007 if (object === source) {
3008 return;
3009 }
3010 baseFor(source, function(srcValue, key) {
3011 if (isObject(srcValue)) {
3012 stack || (stack = new Stack);
3013 baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
3014 }
3015 else {
3016 var newValue = customizer
3017 ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
3018 : undefined;
3019
3020 if (newValue === undefined) {
3021 newValue = srcValue;
3022 }
3023 assignMergeValue(object, key, newValue);
3024 }
3025 }, keysIn);
3026 }
3027
3028 /**
3029 * A specialized version of `baseMerge` for arrays and objects which performs
3030 * deep merges and tracks traversed objects enabling objects with circular
3031 * references to be merged.
3032 *
3033 * @private
3034 * @param {Object} object The destination object.
3035 * @param {Object} source The source object.
3036 * @param {string} key The key of the value to merge.
3037 * @param {number} srcIndex The index of `source`.
3038 * @param {Function} mergeFunc The function to merge values.
3039 * @param {Function} [customizer] The function to customize assigned values.
3040 * @param {Object} [stack] Tracks traversed source values and their merged
3041 * counterparts.
3042 */
3043 function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
3044 var objValue = safeGet(object, key),
3045 srcValue = safeGet(source, key),
3046 stacked = stack.get(srcValue);
3047
3048 if (stacked) {
3049 assignMergeValue(object, key, stacked);
3050 return;
3051 }
3052 var newValue = customizer
3053 ? customizer(objValue, srcValue, (key + ''), object, source, stack)
3054 : undefined;
3055
3056 var isCommon = newValue === undefined;
3057
3058 if (isCommon) {
3059 var isArr = isArray(srcValue),
3060 isBuff = !isArr && isBuffer(srcValue),
3061 isTyped = !isArr && !isBuff && isTypedArray(srcValue);
3062
3063 newValue = srcValue;
3064 if (isArr || isBuff || isTyped) {
3065 if (isArray(objValue)) {
3066 newValue = objValue;
3067 }
3068 else if (isArrayLikeObject(objValue)) {
3069 newValue = copyArray(objValue);
3070 }
3071 else if (isBuff) {
3072 isCommon = false;
3073 newValue = cloneBuffer(srcValue, true);
3074 }
3075 else if (isTyped) {
3076 isCommon = false;
3077 newValue = cloneTypedArray(srcValue, true);
3078 }
3079 else {
3080 newValue = [];
3081 }
3082 }
3083 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
3084 newValue = objValue;
3085 if (isArguments(objValue)) {
3086 newValue = toPlainObject(objValue);
3087 }
3088 else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
3089 newValue = initCloneObject(srcValue);
3090 }
3091 }
3092 else {
3093 isCommon = false;
3094 }
3095 }
3096 if (isCommon) {
3097 // Recursively merge objects and arrays (susceptible to call stack limits).
3098 stack.set(srcValue, newValue);
3099 mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
3100 stack['delete'](srcValue);
3101 }
3102 assignMergeValue(object, key, newValue);
3103 }
3104
3105 /**
3106 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
3107 *
3108 * @private
3109 * @param {Function} func The function to apply a rest parameter to.
3110 * @param {number} [start=func.length-1] The start position of the rest parameter.
3111 * @returns {Function} Returns the new function.
3112 */
3113 function baseRest(func, start) {
3114 return setToString(overRest(func, start, identity), func + '');
3115 }
3116
3117 /**
3118 * The base implementation of `setToString` without support for hot loop shorting.
3119 *
3120 * @private
3121 * @param {Function} func The function to modify.
3122 * @param {Function} string The `toString` result.
3123 * @returns {Function} Returns `func`.
3124 */
3125 var baseSetToString = !defineProperty ? identity : function(func, string) {
3126 return defineProperty(func, 'toString', {
3127 'configurable': true,
3128 'enumerable': false,
3129 'value': constant(string),
3130 'writable': true
3131 });
3132 };
3133
3134 /**
3135 * Creates a clone of `buffer`.
3136 *
3137 * @private
3138 * @param {Buffer} buffer The buffer to clone.
3139 * @param {boolean} [isDeep] Specify a deep clone.
3140 * @returns {Buffer} Returns the cloned buffer.
3141 */
3142 function cloneBuffer(buffer, isDeep) {
3143 if (isDeep) {
3144 return buffer.slice();
3145 }
3146 var length = buffer.length,
3147 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
3148
3149 buffer.copy(result);
3150 return result;
3151 }
3152
3153 /**
3154 * Creates a clone of `arrayBuffer`.
3155 *
3156 * @private
3157 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
3158 * @returns {ArrayBuffer} Returns the cloned array buffer.
3159 */
3160 function cloneArrayBuffer(arrayBuffer) {
3161 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
3162 new Uint8Array(result).set(new Uint8Array(arrayBuffer));
3163 return result;
3164 }
3165
3166 /**
3167 * Creates a clone of `typedArray`.
3168 *
3169 * @private
3170 * @param {Object} typedArray The typed array to clone.
3171 * @param {boolean} [isDeep] Specify a deep clone.
3172 * @returns {Object} Returns the cloned typed array.
3173 */
3174 function cloneTypedArray(typedArray, isDeep) {
3175 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
3176 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
3177 }
3178
3179 /**
3180 * Copies the values of `source` to `array`.
3181 *
3182 * @private
3183 * @param {Array} source The array to copy values from.
3184 * @param {Array} [array=[]] The array to copy values to.
3185 * @returns {Array} Returns `array`.
3186 */
3187 function copyArray(source, array) {
3188 var index = -1,
3189 length = source.length;
3190
3191 array || (array = Array(length));
3192 while (++index < length) {
3193 array[index] = source[index];
3194 }
3195 return array;
3196 }
3197
3198 /**
3199 * Copies properties of `source` to `object`.
3200 *
3201 * @private
3202 * @param {Object} source The object to copy properties from.
3203 * @param {Array} props The property identifiers to copy.
3204 * @param {Object} [object={}] The object to copy properties to.
3205 * @param {Function} [customizer] The function to customize copied values.
3206 * @returns {Object} Returns `object`.
3207 */
3208 function copyObject(source, props, object, customizer) {
3209 var isNew = !object;
3210 object || (object = {});
3211
3212 var index = -1,
3213 length = props.length;
3214
3215 while (++index < length) {
3216 var key = props[index];
3217
3218 var newValue = customizer
3219 ? customizer(object[key], source[key], key, object, source)
3220 : undefined;
3221
3222 if (newValue === undefined) {
3223 newValue = source[key];
3224 }
3225 if (isNew) {
3226 baseAssignValue(object, key, newValue);
3227 } else {
3228 assignValue(object, key, newValue);
3229 }
3230 }
3231 return object;
3232 }
3233
3234 /**
3235 * Creates a function like `_.assign`.
3236 *
3237 * @private
3238 * @param {Function} assigner The function to assign values.
3239 * @returns {Function} Returns the new assigner function.
3240 */
3241 function createAssigner(assigner) {
3242 return baseRest(function(object, sources) {
3243 var index = -1,
3244 length = sources.length,
3245 customizer = length > 1 ? sources[length - 1] : undefined,
3246 guard = length > 2 ? sources[2] : undefined;
3247
3248 customizer = (assigner.length > 3 && typeof customizer == 'function')
3249 ? (length--, customizer)
3250 : undefined;
3251
3252 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
3253 customizer = length < 3 ? undefined : customizer;
3254 length = 1;
3255 }
3256 object = Object(object);
3257 while (++index < length) {
3258 var source = sources[index];
3259 if (source) {
3260 assigner(object, source, index, customizer);
3261 }
3262 }
3263 return object;
3264 });
3265 }
3266
3267 /**
3268 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
3269 *
3270 * @private
3271 * @param {boolean} [fromRight] Specify iterating from right to left.
3272 * @returns {Function} Returns the new base function.
3273 */
3274 function createBaseFor(fromRight) {
3275 return function(object, iteratee, keysFunc) {
3276 var index = -1,
3277 iterable = Object(object),
3278 props = keysFunc(object),
3279 length = props.length;
3280
3281 while (length--) {
3282 var key = props[fromRight ? length : ++index];
3283 if (iteratee(iterable[key], key, iterable) === false) {
3284 break;
3285 }
3286 }
3287 return object;
3288 };
3289 }
3290
3291 /**
3292 * Gets the data for `map`.
3293 *
3294 * @private
3295 * @param {Object} map The map to query.
3296 * @param {string} key The reference key.
3297 * @returns {*} Returns the map data.
3298 */
3299 function getMapData(map, key) {
3300 var data = map.__data__;
3301 return isKeyable(key)
3302 ? data[typeof key == 'string' ? 'string' : 'hash']
3303 : data.map;
3304 }
3305
3306 /**
3307 * Gets the native function at `key` of `object`.
3308 *
3309 * @private
3310 * @param {Object} object The object to query.
3311 * @param {string} key The key of the method to get.
3312 * @returns {*} Returns the function if it's native, else `undefined`.
3313 */
3314 function getNative(object, key) {
3315 var value = getValue(object, key);
3316 return baseIsNative(value) ? value : undefined;
3317 }
3318
3319 /**
3320 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
3321 *
3322 * @private
3323 * @param {*} value The value to query.
3324 * @returns {string} Returns the raw `toStringTag`.
3325 */
3326 function getRawTag(value) {
3327 var isOwn = hasOwnProperty.call(value, symToStringTag),
3328 tag = value[symToStringTag];
3329
3330 try {
3331 value[symToStringTag] = undefined;
3332 } catch (e) {}
3333
3334 var result = nativeObjectToString.call(value);
3335 {
3336 if (isOwn) {
3337 value[symToStringTag] = tag;
3338 } else {
3339 delete value[symToStringTag];
3340 }
3341 }
3342 return result;
3343 }
3344
3345 /**
3346 * Initializes an object clone.
3347 *
3348 * @private
3349 * @param {Object} object The object to clone.
3350 * @returns {Object} Returns the initialized clone.
3351 */
3352 function initCloneObject(object) {
3353 return (typeof object.constructor == 'function' && !isPrototype(object))
3354 ? baseCreate(getPrototype(object))
3355 : {};
3356 }
3357
3358 /**
3359 * Checks if `value` is a valid array-like index.
3360 *
3361 * @private
3362 * @param {*} value The value to check.
3363 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
3364 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
3365 */
3366 function isIndex(value, length) {
3367 var type = typeof value;
3368 length = length == null ? MAX_SAFE_INTEGER : length;
3369
3370 return !!length &&
3371 (type == 'number' ||
3372 (type != 'symbol' && reIsUint.test(value))) &&
3373 (value > -1 && value % 1 == 0 && value < length);
3374 }
3375
3376 /**
3377 * Checks if the given arguments are from an iteratee call.
3378 *
3379 * @private
3380 * @param {*} value The potential iteratee value argument.
3381 * @param {*} index The potential iteratee index or key argument.
3382 * @param {*} object The potential iteratee object argument.
3383 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
3384 * else `false`.
3385 */
3386 function isIterateeCall(value, index, object) {
3387 if (!isObject(object)) {
3388 return false;
3389 }
3390 var type = typeof index;
3391 if (type == 'number'
3392 ? (isArrayLike(object) && isIndex(index, object.length))
3393 : (type == 'string' && index in object)
3394 ) {
3395 return eq(object[index], value);
3396 }
3397 return false;
3398 }
3399
3400 /**
3401 * Checks if `value` is suitable for use as unique object key.
3402 *
3403 * @private
3404 * @param {*} value The value to check.
3405 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
3406 */
3407 function isKeyable(value) {
3408 var type = typeof value;
3409 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
3410 ? (value !== '__proto__')
3411 : (value === null);
3412 }
3413
3414 /**
3415 * Checks if `func` has its source masked.
3416 *
3417 * @private
3418 * @param {Function} func The function to check.
3419 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
3420 */
3421 function isMasked(func) {
3422 return !!maskSrcKey && (maskSrcKey in func);
3423 }
3424
3425 /**
3426 * Checks if `value` is likely a prototype object.
3427 *
3428 * @private
3429 * @param {*} value The value to check.
3430 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
3431 */
3432 function isPrototype(value) {
3433 var Ctor = value && value.constructor,
3434 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
3435
3436 return value === proto;
3437 }
3438
3439 /**
3440 * This function is like
3441 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
3442 * except that it includes inherited enumerable properties.
3443 *
3444 * @private
3445 * @param {Object} object The object to query.
3446 * @returns {Array} Returns the array of property names.
3447 */
3448 function nativeKeysIn(object) {
3449 var result = [];
3450 if (object != null) {
3451 for (var key in Object(object)) {
3452 result.push(key);
3453 }
3454 }
3455 return result;
3456 }
3457
3458 /**
3459 * Converts `value` to a string using `Object.prototype.toString`.
3460 *
3461 * @private
3462 * @param {*} value The value to convert.
3463 * @returns {string} Returns the converted string.
3464 */
3465 function objectToString(value) {
3466 return nativeObjectToString.call(value);
3467 }
3468
3469 /**
3470 * A specialized version of `baseRest` which transforms the rest array.
3471 *
3472 * @private
3473 * @param {Function} func The function to apply a rest parameter to.
3474 * @param {number} [start=func.length-1] The start position of the rest parameter.
3475 * @param {Function} transform The rest array transform.
3476 * @returns {Function} Returns the new function.
3477 */
3478 function overRest(func, start, transform) {
3479 start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
3480 return function() {
3481 var args = arguments,
3482 index = -1,
3483 length = nativeMax(args.length - start, 0),
3484 array = Array(length);
3485
3486 while (++index < length) {
3487 array[index] = args[start + index];
3488 }
3489 index = -1;
3490 var otherArgs = Array(start + 1);
3491 while (++index < start) {
3492 otherArgs[index] = args[index];
3493 }
3494 otherArgs[start] = transform(array);
3495 return apply(func, this, otherArgs);
3496 };
3497 }
3498
3499 /**
3500 * Sets the `toString` method of `func` to return `string`.
3501 *
3502 * @private
3503 * @param {Function} func The function to modify.
3504 * @param {Function} string The `toString` result.
3505 * @returns {Function} Returns `func`.
3506 */
3507 var setToString = shortOut(baseSetToString);
3508
3509 /**
3510 * Creates a function that'll short out and invoke `identity` instead
3511 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
3512 * milliseconds.
3513 *
3514 * @private
3515 * @param {Function} func The function to restrict.
3516 * @returns {Function} Returns the new shortable function.
3517 */
3518 function shortOut(func) {
3519 var count = 0,
3520 lastCalled = 0;
3521
3522 return function() {
3523 var stamp = nativeNow(),
3524 remaining = HOT_SPAN - (stamp - lastCalled);
3525
3526 lastCalled = stamp;
3527 if (remaining > 0) {
3528 if (++count >= HOT_COUNT) {
3529 return arguments[0];
3530 }
3531 } else {
3532 count = 0;
3533 }
3534 return func.apply(undefined, arguments);
3535 };
3536 }
3537
3538 /**
3539 * Converts `func` to its source code.
3540 *
3541 * @private
3542 * @param {Function} func The function to convert.
3543 * @returns {string} Returns the source code.
3544 */
3545 function toSource(func) {
3546 if (func != null) {
3547 try {
3548 return funcToString.call(func);
3549 } catch (e) {}
3550 try {
3551 return (func + '');
3552 } catch (e) {}
3553 }
3554 return '';
3555 }
3556
3557 /**
3558 * Performs a
3559 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
3560 * comparison between two values to determine if they are equivalent.
3561 *
3562 * @static
3563 * @memberOf _
3564 * @since 4.0.0
3565 * @category Lang
3566 * @param {*} value The value to compare.
3567 * @param {*} other The other value to compare.
3568 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
3569 * @example
3570 *
3571 * var object = { 'a': 1 };
3572 * var other = { 'a': 1 };
3573 *
3574 * _.eq(object, object);
3575 * // => true
3576 *
3577 * _.eq(object, other);
3578 * // => false
3579 *
3580 * _.eq('a', 'a');
3581 * // => true
3582 *
3583 * _.eq('a', Object('a'));
3584 * // => false
3585 *
3586 * _.eq(NaN, NaN);
3587 * // => true
3588 */
3589 function eq(value, other) {
3590 return value === other || (value !== value && other !== other);
3591 }
3592
3593 /**
3594 * Checks if `value` is likely an `arguments` object.
3595 *
3596 * @static
3597 * @memberOf _
3598 * @since 0.1.0
3599 * @category Lang
3600 * @param {*} value The value to check.
3601 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
3602 * else `false`.
3603 * @example
3604 *
3605 * _.isArguments(function() { return arguments; }());
3606 * // => true
3607 *
3608 * _.isArguments([1, 2, 3]);
3609 * // => false
3610 */
3611 var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
3612 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
3613 !propertyIsEnumerable.call(value, 'callee');
3614 };
3615
3616 /**
3617 * Checks if `value` is classified as an `Array` object.
3618 *
3619 * @static
3620 * @memberOf _
3621 * @since 0.1.0
3622 * @category Lang
3623 * @param {*} value The value to check.
3624 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
3625 * @example
3626 *
3627 * _.isArray([1, 2, 3]);
3628 * // => true
3629 *
3630 * _.isArray(document.body.children);
3631 * // => false
3632 *
3633 * _.isArray('abc');
3634 * // => false
3635 *
3636 * _.isArray(_.noop);
3637 * // => false
3638 */
3639 var isArray = Array.isArray;
3640
3641 /**
3642 * Checks if `value` is array-like. A value is considered array-like if it's
3643 * not a function and has a `value.length` that's an integer greater than or
3644 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
3645 *
3646 * @static
3647 * @memberOf _
3648 * @since 4.0.0
3649 * @category Lang
3650 * @param {*} value The value to check.
3651 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
3652 * @example
3653 *
3654 * _.isArrayLike([1, 2, 3]);
3655 * // => true
3656 *
3657 * _.isArrayLike(document.body.children);
3658 * // => true
3659 *
3660 * _.isArrayLike('abc');
3661 * // => true
3662 *
3663 * _.isArrayLike(_.noop);
3664 * // => false
3665 */
3666 function isArrayLike(value) {
3667 return value != null && isLength(value.length) && !isFunction(value);
3668 }
3669
3670 /**
3671 * This method is like `_.isArrayLike` except that it also checks if `value`
3672 * is an object.
3673 *
3674 * @static
3675 * @memberOf _
3676 * @since 4.0.0
3677 * @category Lang
3678 * @param {*} value The value to check.
3679 * @returns {boolean} Returns `true` if `value` is an array-like object,
3680 * else `false`.
3681 * @example
3682 *
3683 * _.isArrayLikeObject([1, 2, 3]);
3684 * // => true
3685 *
3686 * _.isArrayLikeObject(document.body.children);
3687 * // => true
3688 *
3689 * _.isArrayLikeObject('abc');
3690 * // => false
3691 *
3692 * _.isArrayLikeObject(_.noop);
3693 * // => false
3694 */
3695 function isArrayLikeObject(value) {
3696 return isObjectLike(value) && isArrayLike(value);
3697 }
3698
3699 /**
3700 * Checks if `value` is a buffer.
3701 *
3702 * @static
3703 * @memberOf _
3704 * @since 4.3.0
3705 * @category Lang
3706 * @param {*} value The value to check.
3707 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
3708 * @example
3709 *
3710 * _.isBuffer(new Buffer(2));
3711 * // => true
3712 *
3713 * _.isBuffer(new Uint8Array(2));
3714 * // => false
3715 */
3716 var isBuffer = nativeIsBuffer || stubFalse;
3717
3718 /**
3719 * Checks if `value` is classified as a `Function` object.
3720 *
3721 * @static
3722 * @memberOf _
3723 * @since 0.1.0
3724 * @category Lang
3725 * @param {*} value The value to check.
3726 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
3727 * @example
3728 *
3729 * _.isFunction(_);
3730 * // => true
3731 *
3732 * _.isFunction(/abc/);
3733 * // => false
3734 */
3735 function isFunction(value) {
3736 if (!isObject(value)) {
3737 return false;
3738 }
3739 // The use of `Object#toString` avoids issues with the `typeof` operator
3740 // in Safari 9 which returns 'object' for typed arrays and other constructors.
3741 var tag = baseGetTag(value);
3742 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
3743 }
3744
3745 /**
3746 * Checks if `value` is a valid array-like length.
3747 *
3748 * **Note:** This method is loosely based on
3749 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
3750 *
3751 * @static
3752 * @memberOf _
3753 * @since 4.0.0
3754 * @category Lang
3755 * @param {*} value The value to check.
3756 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
3757 * @example
3758 *
3759 * _.isLength(3);
3760 * // => true
3761 *
3762 * _.isLength(Number.MIN_VALUE);
3763 * // => false
3764 *
3765 * _.isLength(Infinity);
3766 * // => false
3767 *
3768 * _.isLength('3');
3769 * // => false
3770 */
3771 function isLength(value) {
3772 return typeof value == 'number' &&
3773 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
3774 }
3775
3776 /**
3777 * Checks if `value` is the
3778 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
3779 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
3780 *
3781 * @static
3782 * @memberOf _
3783 * @since 0.1.0
3784 * @category Lang
3785 * @param {*} value The value to check.
3786 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
3787 * @example
3788 *
3789 * _.isObject({});
3790 * // => true
3791 *
3792 * _.isObject([1, 2, 3]);
3793 * // => true
3794 *
3795 * _.isObject(_.noop);
3796 * // => true
3797 *
3798 * _.isObject(null);
3799 * // => false
3800 */
3801 function isObject(value) {
3802 var type = typeof value;
3803 return value != null && (type == 'object' || type == 'function');
3804 }
3805
3806 /**
3807 * Checks if `value` is object-like. A value is object-like if it's not `null`
3808 * and has a `typeof` result of "object".
3809 *
3810 * @static
3811 * @memberOf _
3812 * @since 4.0.0
3813 * @category Lang
3814 * @param {*} value The value to check.
3815 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
3816 * @example
3817 *
3818 * _.isObjectLike({});
3819 * // => true
3820 *
3821 * _.isObjectLike([1, 2, 3]);
3822 * // => true
3823 *
3824 * _.isObjectLike(_.noop);
3825 * // => false
3826 *
3827 * _.isObjectLike(null);
3828 * // => false
3829 */
3830 function isObjectLike(value) {
3831 return value != null && typeof value == 'object';
3832 }
3833
3834 /**
3835 * Checks if `value` is a plain object, that is, an object created by the
3836 * `Object` constructor or one with a `[[Prototype]]` of `null`.
3837 *
3838 * @static
3839 * @memberOf _
3840 * @since 0.8.0
3841 * @category Lang
3842 * @param {*} value The value to check.
3843 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
3844 * @example
3845 *
3846 * function Foo() {
3847 * this.a = 1;
3848 * }
3849 *
3850 * _.isPlainObject(new Foo);
3851 * // => false
3852 *
3853 * _.isPlainObject([1, 2, 3]);
3854 * // => false
3855 *
3856 * _.isPlainObject({ 'x': 0, 'y': 0 });
3857 * // => true
3858 *
3859 * _.isPlainObject(Object.create(null));
3860 * // => true
3861 */
3862 function isPlainObject(value) {
3863 if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
3864 return false;
3865 }
3866 var proto = getPrototype(value);
3867 if (proto === null) {
3868 return true;
3869 }
3870 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
3871 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
3872 funcToString.call(Ctor) == objectCtorString;
3873 }
3874
3875 /**
3876 * Checks if `value` is classified as a typed array.
3877 *
3878 * @static
3879 * @memberOf _
3880 * @since 3.0.0
3881 * @category Lang
3882 * @param {*} value The value to check.
3883 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
3884 * @example
3885 *
3886 * _.isTypedArray(new Uint8Array);
3887 * // => true
3888 *
3889 * _.isTypedArray([]);
3890 * // => false
3891 */
3892 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
3893
3894 /**
3895 * Converts `value` to a plain object flattening inherited enumerable string
3896 * keyed properties of `value` to own properties of the plain object.
3897 *
3898 * @static
3899 * @memberOf _
3900 * @since 3.0.0
3901 * @category Lang
3902 * @param {*} value The value to convert.
3903 * @returns {Object} Returns the converted plain object.
3904 * @example
3905 *
3906 * function Foo() {
3907 * this.b = 2;
3908 * }
3909 *
3910 * Foo.prototype.c = 3;
3911 *
3912 * _.assign({ 'a': 1 }, new Foo);
3913 * // => { 'a': 1, 'b': 2 }
3914 *
3915 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
3916 * // => { 'a': 1, 'b': 2, 'c': 3 }
3917 */
3918 function toPlainObject(value) {
3919 return copyObject(value, keysIn(value));
3920 }
3921
3922 /**
3923 * Creates an array of the own and inherited enumerable property names of `object`.
3924 *
3925 * **Note:** Non-object values are coerced to objects.
3926 *
3927 * @static
3928 * @memberOf _
3929 * @since 3.0.0
3930 * @category Object
3931 * @param {Object} object The object to query.
3932 * @returns {Array} Returns the array of property names.
3933 * @example
3934 *
3935 * function Foo() {
3936 * this.a = 1;
3937 * this.b = 2;
3938 * }
3939 *
3940 * Foo.prototype.c = 3;
3941 *
3942 * _.keysIn(new Foo);
3943 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
3944 */
3945 function keysIn(object) {
3946 return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
3947 }
3948
3949 /**
3950 * This method is like `_.assign` except that it recursively merges own and
3951 * inherited enumerable string keyed properties of source objects into the
3952 * destination object. Source properties that resolve to `undefined` are
3953 * skipped if a destination value exists. Array and plain object properties
3954 * are merged recursively. Other objects and value types are overridden by
3955 * assignment. Source objects are applied from left to right. Subsequent
3956 * sources overwrite property assignments of previous sources.
3957 *
3958 * **Note:** This method mutates `object`.
3959 *
3960 * @static
3961 * @memberOf _
3962 * @since 0.5.0
3963 * @category Object
3964 * @param {Object} object The destination object.
3965 * @param {...Object} [sources] The source objects.
3966 * @returns {Object} Returns `object`.
3967 * @example
3968 *
3969 * var object = {
3970 * 'a': [{ 'b': 2 }, { 'd': 4 }]
3971 * };
3972 *
3973 * var other = {
3974 * 'a': [{ 'c': 3 }, { 'e': 5 }]
3975 * };
3976 *
3977 * _.merge(object, other);
3978 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
3979 */
3980 var merge = createAssigner(function(object, source, srcIndex) {
3981 baseMerge(object, source, srcIndex);
3982 });
3983
3984 /**
3985 * Creates a function that returns `value`.
3986 *
3987 * @static
3988 * @memberOf _
3989 * @since 2.4.0
3990 * @category Util
3991 * @param {*} value The value to return from the new function.
3992 * @returns {Function} Returns the new constant function.
3993 * @example
3994 *
3995 * var objects = _.times(2, _.constant({ 'a': 1 }));
3996 *
3997 * console.log(objects);
3998 * // => [{ 'a': 1 }, { 'a': 1 }]
3999 *
4000 * console.log(objects[0] === objects[1]);
4001 * // => true
4002 */
4003 function constant(value) {
4004 return function() {
4005 return value;
4006 };
4007 }
4008
4009 /**
4010 * This method returns the first argument it receives.
4011 *
4012 * @static
4013 * @since 0.1.0
4014 * @memberOf _
4015 * @category Util
4016 * @param {*} value Any value.
4017 * @returns {*} Returns `value`.
4018 * @example
4019 *
4020 * var object = { 'a': 1 };
4021 *
4022 * console.log(_.identity(object) === object);
4023 * // => true
4024 */
4025 function identity(value) {
4026 return value;
4027 }
4028
4029 /**
4030 * This method returns `false`.
4031 *
4032 * @static
4033 * @memberOf _
4034 * @since 4.13.0
4035 * @category Util
4036 * @returns {boolean} Returns `false`.
4037 * @example
4038 *
4039 * _.times(2, _.stubFalse);
4040 * // => [false, false]
4041 */
4042 function stubFalse() {
4043 return false;
4044 }
4045
4046 module.exports = merge;
4047 });
4048
4049 /**
4050 * lodash (Custom Build) <https://lodash.com/>
4051 * Build: `lodash modularize exports="npm" -o ./`
4052 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
4053 * Released under MIT license <https://lodash.com/license>
4054 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
4055 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
4056 */
4057
4058 /** Used as the `TypeError` message for "Functions" methods. */
4059 var FUNC_ERROR_TEXT = 'Expected a function';
4060
4061 /** Used to stand-in for `undefined` hash values. */
4062 var HASH_UNDEFINED = '__lodash_hash_undefined__';
4063
4064 /** Used as references for various `Number` constants. */
4065 var INFINITY = 1 / 0;
4066
4067 /** `Object#toString` result references. */
4068 var funcTag = '[object Function]',
4069 genTag = '[object GeneratorFunction]',
4070 symbolTag = '[object Symbol]';
4071
4072 /** Used to match property names within property paths. */
4073 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
4074 reIsPlainProp = /^\w*$/,
4075 reLeadingDot = /^\./,
4076 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
4077
4078 /**
4079 * Used to match `RegExp`
4080 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
4081 */
4082 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
4083
4084 /** Used to match backslashes in property paths. */
4085 var reEscapeChar = /\\(\\)?/g;
4086
4087 /** Used to detect host constructors (Safari). */
4088 var reIsHostCtor = /^\[object .+?Constructor\]$/;
4089
4090 /** Detect free variable `global` from Node.js. */
4091 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
4092
4093 /** Detect free variable `self`. */
4094 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
4095
4096 /** Used as a reference to the global object. */
4097 var root = freeGlobal || freeSelf || Function('return this')();
4098
4099 /**
4100 * Gets the value at `key` of `object`.
4101 *
4102 * @private
4103 * @param {Object} [object] The object to query.
4104 * @param {string} key The key of the property to get.
4105 * @returns {*} Returns the property value.
4106 */
4107 function getValue(object, key) {
4108 return object == null ? undefined : object[key];
4109 }
4110
4111 /**
4112 * Checks if `value` is a host object in IE < 9.
4113 *
4114 * @private
4115 * @param {*} value The value to check.
4116 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
4117 */
4118 function isHostObject(value) {
4119 // Many host objects are `Object` objects that can coerce to strings
4120 // despite having improperly defined `toString` methods.
4121 var result = false;
4122 if (value != null && typeof value.toString != 'function') {
4123 try {
4124 result = !!(value + '');
4125 } catch (e) {}
4126 }
4127 return result;
4128 }
4129
4130 /** Used for built-in method references. */
4131 var arrayProto = Array.prototype,
4132 funcProto = Function.prototype,
4133 objectProto = Object.prototype;
4134
4135 /** Used to detect overreaching core-js shims. */
4136 var coreJsData = root['__core-js_shared__'];
4137
4138 /** Used to detect methods masquerading as native. */
4139 var maskSrcKey = (function() {
4140 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
4141 return uid ? ('Symbol(src)_1.' + uid) : '';
4142 }());
4143
4144 /** Used to resolve the decompiled source of functions. */
4145 var funcToString = funcProto.toString;
4146
4147 /** Used to check objects for own properties. */
4148 var hasOwnProperty = objectProto.hasOwnProperty;
4149
4150 /**
4151 * Used to resolve the
4152 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
4153 * of values.
4154 */
4155 var objectToString = objectProto.toString;
4156
4157 /** Used to detect if a method is native. */
4158 var reIsNative = RegExp('^' +
4159 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
4160 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
4161 );
4162
4163 /** Built-in value references. */
4164 var Symbol$1 = root.Symbol,
4165 splice = arrayProto.splice;
4166
4167 /* Built-in method references that are verified to be native. */
4168 var Map = getNative(root, 'Map'),
4169 nativeCreate = getNative(Object, 'create');
4170
4171 /** Used to convert symbols to primitives and strings. */
4172 var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
4173 symbolToString = symbolProto ? symbolProto.toString : undefined;
4174
4175 /**
4176 * Creates a hash object.
4177 *
4178 * @private
4179 * @constructor
4180 * @param {Array} [entries] The key-value pairs to cache.
4181 */
4182 function Hash(entries) {
4183 var index = -1,
4184 length = entries ? entries.length : 0;
4185
4186 this.clear();
4187 while (++index < length) {
4188 var entry = entries[index];
4189 this.set(entry[0], entry[1]);
4190 }
4191 }
4192
4193 /**
4194 * Removes all key-value entries from the hash.
4195 *
4196 * @private
4197 * @name clear
4198 * @memberOf Hash
4199 */
4200 function hashClear() {
4201 this.__data__ = nativeCreate ? nativeCreate(null) : {};
4202 }
4203
4204 /**
4205 * Removes `key` and its value from the hash.
4206 *
4207 * @private
4208 * @name delete
4209 * @memberOf Hash
4210 * @param {Object} hash The hash to modify.
4211 * @param {string} key The key of the value to remove.
4212 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4213 */
4214 function hashDelete(key) {
4215 return this.has(key) && delete this.__data__[key];
4216 }
4217
4218 /**
4219 * Gets the hash value for `key`.
4220 *
4221 * @private
4222 * @name get
4223 * @memberOf Hash
4224 * @param {string} key The key of the value to get.
4225 * @returns {*} Returns the entry value.
4226 */
4227 function hashGet(key) {
4228 var data = this.__data__;
4229 if (nativeCreate) {
4230 var result = data[key];
4231 return result === HASH_UNDEFINED ? undefined : result;
4232 }
4233 return hasOwnProperty.call(data, key) ? data[key] : undefined;
4234 }
4235
4236 /**
4237 * Checks if a hash value for `key` exists.
4238 *
4239 * @private
4240 * @name has
4241 * @memberOf Hash
4242 * @param {string} key The key of the entry to check.
4243 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4244 */
4245 function hashHas(key) {
4246 var data = this.__data__;
4247 return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
4248 }
4249
4250 /**
4251 * Sets the hash `key` to `value`.
4252 *
4253 * @private
4254 * @name set
4255 * @memberOf Hash
4256 * @param {string} key The key of the value to set.
4257 * @param {*} value The value to set.
4258 * @returns {Object} Returns the hash instance.
4259 */
4260 function hashSet(key, value) {
4261 var data = this.__data__;
4262 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
4263 return this;
4264 }
4265
4266 // Add methods to `Hash`.
4267 Hash.prototype.clear = hashClear;
4268 Hash.prototype['delete'] = hashDelete;
4269 Hash.prototype.get = hashGet;
4270 Hash.prototype.has = hashHas;
4271 Hash.prototype.set = hashSet;
4272
4273 /**
4274 * Creates an list cache object.
4275 *
4276 * @private
4277 * @constructor
4278 * @param {Array} [entries] The key-value pairs to cache.
4279 */
4280 function ListCache(entries) {
4281 var index = -1,
4282 length = entries ? entries.length : 0;
4283
4284 this.clear();
4285 while (++index < length) {
4286 var entry = entries[index];
4287 this.set(entry[0], entry[1]);
4288 }
4289 }
4290
4291 /**
4292 * Removes all key-value entries from the list cache.
4293 *
4294 * @private
4295 * @name clear
4296 * @memberOf ListCache
4297 */
4298 function listCacheClear() {
4299 this.__data__ = [];
4300 }
4301
4302 /**
4303 * Removes `key` and its value from the list cache.
4304 *
4305 * @private
4306 * @name delete
4307 * @memberOf ListCache
4308 * @param {string} key The key of the value to remove.
4309 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4310 */
4311 function listCacheDelete(key) {
4312 var data = this.__data__,
4313 index = assocIndexOf(data, key);
4314
4315 if (index < 0) {
4316 return false;
4317 }
4318 var lastIndex = data.length - 1;
4319 if (index == lastIndex) {
4320 data.pop();
4321 } else {
4322 splice.call(data, index, 1);
4323 }
4324 return true;
4325 }
4326
4327 /**
4328 * Gets the list cache value for `key`.
4329 *
4330 * @private
4331 * @name get
4332 * @memberOf ListCache
4333 * @param {string} key The key of the value to get.
4334 * @returns {*} Returns the entry value.
4335 */
4336 function listCacheGet(key) {
4337 var data = this.__data__,
4338 index = assocIndexOf(data, key);
4339
4340 return index < 0 ? undefined : data[index][1];
4341 }
4342
4343 /**
4344 * Checks if a list cache value for `key` exists.
4345 *
4346 * @private
4347 * @name has
4348 * @memberOf ListCache
4349 * @param {string} key The key of the entry to check.
4350 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4351 */
4352 function listCacheHas(key) {
4353 return assocIndexOf(this.__data__, key) > -1;
4354 }
4355
4356 /**
4357 * Sets the list cache `key` to `value`.
4358 *
4359 * @private
4360 * @name set
4361 * @memberOf ListCache
4362 * @param {string} key The key of the value to set.
4363 * @param {*} value The value to set.
4364 * @returns {Object} Returns the list cache instance.
4365 */
4366 function listCacheSet(key, value) {
4367 var data = this.__data__,
4368 index = assocIndexOf(data, key);
4369
4370 if (index < 0) {
4371 data.push([key, value]);
4372 } else {
4373 data[index][1] = value;
4374 }
4375 return this;
4376 }
4377
4378 // Add methods to `ListCache`.
4379 ListCache.prototype.clear = listCacheClear;
4380 ListCache.prototype['delete'] = listCacheDelete;
4381 ListCache.prototype.get = listCacheGet;
4382 ListCache.prototype.has = listCacheHas;
4383 ListCache.prototype.set = listCacheSet;
4384
4385 /**
4386 * Creates a map cache object to store key-value pairs.
4387 *
4388 * @private
4389 * @constructor
4390 * @param {Array} [entries] The key-value pairs to cache.
4391 */
4392 function MapCache(entries) {
4393 var index = -1,
4394 length = entries ? entries.length : 0;
4395
4396 this.clear();
4397 while (++index < length) {
4398 var entry = entries[index];
4399 this.set(entry[0], entry[1]);
4400 }
4401 }
4402
4403 /**
4404 * Removes all key-value entries from the map.
4405 *
4406 * @private
4407 * @name clear
4408 * @memberOf MapCache
4409 */
4410 function mapCacheClear() {
4411 this.__data__ = {
4412 'hash': new Hash,
4413 'map': new (Map || ListCache),
4414 'string': new Hash
4415 };
4416 }
4417
4418 /**
4419 * Removes `key` and its value from the map.
4420 *
4421 * @private
4422 * @name delete
4423 * @memberOf MapCache
4424 * @param {string} key The key of the value to remove.
4425 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4426 */
4427 function mapCacheDelete(key) {
4428 return getMapData(this, key)['delete'](key);
4429 }
4430
4431 /**
4432 * Gets the map value for `key`.
4433 *
4434 * @private
4435 * @name get
4436 * @memberOf MapCache
4437 * @param {string} key The key of the value to get.
4438 * @returns {*} Returns the entry value.
4439 */
4440 function mapCacheGet(key) {
4441 return getMapData(this, key).get(key);
4442 }
4443
4444 /**
4445 * Checks if a map value for `key` exists.
4446 *
4447 * @private
4448 * @name has
4449 * @memberOf MapCache
4450 * @param {string} key The key of the entry to check.
4451 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4452 */
4453 function mapCacheHas(key) {
4454 return getMapData(this, key).has(key);
4455 }
4456
4457 /**
4458 * Sets the map `key` to `value`.
4459 *
4460 * @private
4461 * @name set
4462 * @memberOf MapCache
4463 * @param {string} key The key of the value to set.
4464 * @param {*} value The value to set.
4465 * @returns {Object} Returns the map cache instance.
4466 */
4467 function mapCacheSet(key, value) {
4468 getMapData(this, key).set(key, value);
4469 return this;
4470 }
4471
4472 // Add methods to `MapCache`.
4473 MapCache.prototype.clear = mapCacheClear;
4474 MapCache.prototype['delete'] = mapCacheDelete;
4475 MapCache.prototype.get = mapCacheGet;
4476 MapCache.prototype.has = mapCacheHas;
4477 MapCache.prototype.set = mapCacheSet;
4478
4479 /**
4480 * Gets the index at which the `key` is found in `array` of key-value pairs.
4481 *
4482 * @private
4483 * @param {Array} array The array to inspect.
4484 * @param {*} key The key to search for.
4485 * @returns {number} Returns the index of the matched value, else `-1`.
4486 */
4487 function assocIndexOf(array, key) {
4488 var length = array.length;
4489 while (length--) {
4490 if (eq(array[length][0], key)) {
4491 return length;
4492 }
4493 }
4494 return -1;
4495 }
4496
4497 /**
4498 * The base implementation of `_.get` without support for default values.
4499 *
4500 * @private
4501 * @param {Object} object The object to query.
4502 * @param {Array|string} path The path of the property to get.
4503 * @returns {*} Returns the resolved value.
4504 */
4505 function baseGet(object, path) {
4506 path = isKey(path, object) ? [path] : castPath(path);
4507
4508 var index = 0,
4509 length = path.length;
4510
4511 while (object != null && index < length) {
4512 object = object[toKey(path[index++])];
4513 }
4514 return (index && index == length) ? object : undefined;
4515 }
4516
4517 /**
4518 * The base implementation of `_.isNative` without bad shim checks.
4519 *
4520 * @private
4521 * @param {*} value The value to check.
4522 * @returns {boolean} Returns `true` if `value` is a native function,
4523 * else `false`.
4524 */
4525 function baseIsNative(value) {
4526 if (!isObject(value) || isMasked(value)) {
4527 return false;
4528 }
4529 var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
4530 return pattern.test(toSource(value));
4531 }
4532
4533 /**
4534 * The base implementation of `_.toString` which doesn't convert nullish
4535 * values to empty strings.
4536 *
4537 * @private
4538 * @param {*} value The value to process.
4539 * @returns {string} Returns the string.
4540 */
4541 function baseToString(value) {
4542 // Exit early for strings to avoid a performance hit in some environments.
4543 if (typeof value == 'string') {
4544 return value;
4545 }
4546 if (isSymbol(value)) {
4547 return symbolToString ? symbolToString.call(value) : '';
4548 }
4549 var result = (value + '');
4550 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
4551 }
4552
4553 /**
4554 * Casts `value` to a path array if it's not one.
4555 *
4556 * @private
4557 * @param {*} value The value to inspect.
4558 * @returns {Array} Returns the cast property path array.
4559 */
4560 function castPath(value) {
4561 return isArray(value) ? value : stringToPath(value);
4562 }
4563
4564 /**
4565 * Gets the data for `map`.
4566 *
4567 * @private
4568 * @param {Object} map The map to query.
4569 * @param {string} key The reference key.
4570 * @returns {*} Returns the map data.
4571 */
4572 function getMapData(map, key) {
4573 var data = map.__data__;
4574 return isKeyable(key)
4575 ? data[typeof key == 'string' ? 'string' : 'hash']
4576 : data.map;
4577 }
4578
4579 /**
4580 * Gets the native function at `key` of `object`.
4581 *
4582 * @private
4583 * @param {Object} object The object to query.
4584 * @param {string} key The key of the method to get.
4585 * @returns {*} Returns the function if it's native, else `undefined`.
4586 */
4587 function getNative(object, key) {
4588 var value = getValue(object, key);
4589 return baseIsNative(value) ? value : undefined;
4590 }
4591
4592 /**
4593 * Checks if `value` is a property name and not a property path.
4594 *
4595 * @private
4596 * @param {*} value The value to check.
4597 * @param {Object} [object] The object to query keys on.
4598 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
4599 */
4600 function isKey(value, object) {
4601 if (isArray(value)) {
4602 return false;
4603 }
4604 var type = typeof value;
4605 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
4606 value == null || isSymbol(value)) {
4607 return true;
4608 }
4609 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
4610 (object != null && value in Object(object));
4611 }
4612
4613 /**
4614 * Checks if `value` is suitable for use as unique object key.
4615 *
4616 * @private
4617 * @param {*} value The value to check.
4618 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
4619 */
4620 function isKeyable(value) {
4621 var type = typeof value;
4622 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
4623 ? (value !== '__proto__')
4624 : (value === null);
4625 }
4626
4627 /**
4628 * Checks if `func` has its source masked.
4629 *
4630 * @private
4631 * @param {Function} func The function to check.
4632 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
4633 */
4634 function isMasked(func) {
4635 return !!maskSrcKey && (maskSrcKey in func);
4636 }
4637
4638 /**
4639 * Converts `string` to a property path array.
4640 *
4641 * @private
4642 * @param {string} string The string to convert.
4643 * @returns {Array} Returns the property path array.
4644 */
4645 var stringToPath = memoize(function(string) {
4646 string = toString(string);
4647
4648 var result = [];
4649 if (reLeadingDot.test(string)) {
4650 result.push('');
4651 }
4652 string.replace(rePropName, function(match, number, quote, string) {
4653 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
4654 });
4655 return result;
4656 });
4657
4658 /**
4659 * Converts `value` to a string key if it's not a string or symbol.
4660 *
4661 * @private
4662 * @param {*} value The value to inspect.
4663 * @returns {string|symbol} Returns the key.
4664 */
4665 function toKey(value) {
4666 if (typeof value == 'string' || isSymbol(value)) {
4667 return value;
4668 }
4669 var result = (value + '');
4670 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
4671 }
4672
4673 /**
4674 * Converts `func` to its source code.
4675 *
4676 * @private
4677 * @param {Function} func The function to process.
4678 * @returns {string} Returns the source code.
4679 */
4680 function toSource(func) {
4681 if (func != null) {
4682 try {
4683 return funcToString.call(func);
4684 } catch (e) {}
4685 try {
4686 return (func + '');
4687 } catch (e) {}
4688 }
4689 return '';
4690 }
4691
4692 /**
4693 * Creates a function that memoizes the result of `func`. If `resolver` is
4694 * provided, it determines the cache key for storing the result based on the
4695 * arguments provided to the memoized function. By default, the first argument
4696 * provided to the memoized function is used as the map cache key. The `func`
4697 * is invoked with the `this` binding of the memoized function.
4698 *
4699 * **Note:** The cache is exposed as the `cache` property on the memoized
4700 * function. Its creation may be customized by replacing the `_.memoize.Cache`
4701 * constructor with one whose instances implement the
4702 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
4703 * method interface of `delete`, `get`, `has`, and `set`.
4704 *
4705 * @static
4706 * @memberOf _
4707 * @since 0.1.0
4708 * @category Function
4709 * @param {Function} func The function to have its output memoized.
4710 * @param {Function} [resolver] The function to resolve the cache key.
4711 * @returns {Function} Returns the new memoized function.
4712 * @example
4713 *
4714 * var object = { 'a': 1, 'b': 2 };
4715 * var other = { 'c': 3, 'd': 4 };
4716 *
4717 * var values = _.memoize(_.values);
4718 * values(object);
4719 * // => [1, 2]
4720 *
4721 * values(other);
4722 * // => [3, 4]
4723 *
4724 * object.a = 2;
4725 * values(object);
4726 * // => [1, 2]
4727 *
4728 * // Modify the result cache.
4729 * values.cache.set(object, ['a', 'b']);
4730 * values(object);
4731 * // => ['a', 'b']
4732 *
4733 * // Replace `_.memoize.Cache`.
4734 * _.memoize.Cache = WeakMap;
4735 */
4736 function memoize(func, resolver) {
4737 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
4738 throw new TypeError(FUNC_ERROR_TEXT);
4739 }
4740 var memoized = function() {
4741 var args = arguments,
4742 key = resolver ? resolver.apply(this, args) : args[0],
4743 cache = memoized.cache;
4744
4745 if (cache.has(key)) {
4746 return cache.get(key);
4747 }
4748 var result = func.apply(this, args);
4749 memoized.cache = cache.set(key, result);
4750 return result;
4751 };
4752 memoized.cache = new (memoize.Cache || MapCache);
4753 return memoized;
4754 }
4755
4756 // Assign cache to `_.memoize`.
4757 memoize.Cache = MapCache;
4758
4759 /**
4760 * Performs a
4761 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
4762 * comparison between two values to determine if they are equivalent.
4763 *
4764 * @static
4765 * @memberOf _
4766 * @since 4.0.0
4767 * @category Lang
4768 * @param {*} value The value to compare.
4769 * @param {*} other The other value to compare.
4770 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
4771 * @example
4772 *
4773 * var object = { 'a': 1 };
4774 * var other = { 'a': 1 };
4775 *
4776 * _.eq(object, object);
4777 * // => true
4778 *
4779 * _.eq(object, other);
4780 * // => false
4781 *
4782 * _.eq('a', 'a');
4783 * // => true
4784 *
4785 * _.eq('a', Object('a'));
4786 * // => false
4787 *
4788 * _.eq(NaN, NaN);
4789 * // => true
4790 */
4791 function eq(value, other) {
4792 return value === other || (value !== value && other !== other);
4793 }
4794
4795 /**
4796 * Checks if `value` is classified as an `Array` object.
4797 *
4798 * @static
4799 * @memberOf _
4800 * @since 0.1.0
4801 * @category Lang
4802 * @param {*} value The value to check.
4803 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
4804 * @example
4805 *
4806 * _.isArray([1, 2, 3]);
4807 * // => true
4808 *
4809 * _.isArray(document.body.children);
4810 * // => false
4811 *
4812 * _.isArray('abc');
4813 * // => false
4814 *
4815 * _.isArray(_.noop);
4816 * // => false
4817 */
4818 var isArray = Array.isArray;
4819
4820 /**
4821 * Checks if `value` is classified as a `Function` object.
4822 *
4823 * @static
4824 * @memberOf _
4825 * @since 0.1.0
4826 * @category Lang
4827 * @param {*} value The value to check.
4828 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
4829 * @example
4830 *
4831 * _.isFunction(_);
4832 * // => true
4833 *
4834 * _.isFunction(/abc/);
4835 * // => false
4836 */
4837 function isFunction(value) {
4838 // The use of `Object#toString` avoids issues with the `typeof` operator
4839 // in Safari 8-9 which returns 'object' for typed array and other constructors.
4840 var tag = isObject(value) ? objectToString.call(value) : '';
4841 return tag == funcTag || tag == genTag;
4842 }
4843
4844 /**
4845 * Checks if `value` is the
4846 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
4847 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
4848 *
4849 * @static
4850 * @memberOf _
4851 * @since 0.1.0
4852 * @category Lang
4853 * @param {*} value The value to check.
4854 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
4855 * @example
4856 *
4857 * _.isObject({});
4858 * // => true
4859 *
4860 * _.isObject([1, 2, 3]);
4861 * // => true
4862 *
4863 * _.isObject(_.noop);
4864 * // => true
4865 *
4866 * _.isObject(null);
4867 * // => false
4868 */
4869 function isObject(value) {
4870 var type = typeof value;
4871 return !!value && (type == 'object' || type == 'function');
4872 }
4873
4874 /**
4875 * Checks if `value` is object-like. A value is object-like if it's not `null`
4876 * and has a `typeof` result of "object".
4877 *
4878 * @static
4879 * @memberOf _
4880 * @since 4.0.0
4881 * @category Lang
4882 * @param {*} value The value to check.
4883 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
4884 * @example
4885 *
4886 * _.isObjectLike({});
4887 * // => true
4888 *
4889 * _.isObjectLike([1, 2, 3]);
4890 * // => true
4891 *
4892 * _.isObjectLike(_.noop);
4893 * // => false
4894 *
4895 * _.isObjectLike(null);
4896 * // => false
4897 */
4898 function isObjectLike(value) {
4899 return !!value && typeof value == 'object';
4900 }
4901
4902 /**
4903 * Checks if `value` is classified as a `Symbol` primitive or object.
4904 *
4905 * @static
4906 * @memberOf _
4907 * @since 4.0.0
4908 * @category Lang
4909 * @param {*} value The value to check.
4910 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
4911 * @example
4912 *
4913 * _.isSymbol(Symbol.iterator);
4914 * // => true
4915 *
4916 * _.isSymbol('abc');
4917 * // => false
4918 */
4919 function isSymbol(value) {
4920 return typeof value == 'symbol' ||
4921 (isObjectLike(value) && objectToString.call(value) == symbolTag);
4922 }
4923
4924 /**
4925 * Converts `value` to a string. An empty string is returned for `null`
4926 * and `undefined` values. The sign of `-0` is preserved.
4927 *
4928 * @static
4929 * @memberOf _
4930 * @since 4.0.0
4931 * @category Lang
4932 * @param {*} value The value to process.
4933 * @returns {string} Returns the string.
4934 * @example
4935 *
4936 * _.toString(null);
4937 * // => ''
4938 *
4939 * _.toString(-0);
4940 * // => '-0'
4941 *
4942 * _.toString([1, 2, 3]);
4943 * // => '1,2,3'
4944 */
4945 function toString(value) {
4946 return value == null ? '' : baseToString(value);
4947 }
4948
4949 /**
4950 * Gets the value at `path` of `object`. If the resolved value is
4951 * `undefined`, the `defaultValue` is returned in its place.
4952 *
4953 * @static
4954 * @memberOf _
4955 * @since 3.7.0
4956 * @category Object
4957 * @param {Object} object The object to query.
4958 * @param {Array|string} path The path of the property to get.
4959 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
4960 * @returns {*} Returns the resolved value.
4961 * @example
4962 *
4963 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
4964 *
4965 * _.get(object, 'a[0].b.c');
4966 * // => 3
4967 *
4968 * _.get(object, ['a', '0', 'b', 'c']);
4969 * // => 3
4970 *
4971 * _.get(object, 'a.b.c', 'default');
4972 * // => 'default'
4973 */
4974 function get(object, path, defaultValue) {
4975 var result = object == null ? undefined : baseGet(object, path);
4976 return result === undefined ? defaultValue : result;
4977 }
4978
4979 var lodash_get = get;
4980
4981 const debug = logger.extend('i18n');
4982 const DEFAULT_LOCALE = 'en';
4983 const LOCALE_CHANGED = 'bearer-locale-changed';
4984 class I18n {
4985 constructor() {
4986 this._locale = DEFAULT_LOCALE;
4987 this._dictionnary = {
4988 [DEFAULT_LOCALE]: {}
4989 };
4990 /**
4991 * load a dictionary (key/value) containing all the translations required by a dictionary
4992 * @argument {string} integration the identifier of the Integration you want to connect to ex: 12345-attach-github-pull-request
4993 * @argument {(Object | Promise<Object>)} dictionary dictionary containing all key/value pairs of the integration
4994 * @argument {{locale: string}} options { locale: 'en'}
4995 */
4996 this.load = (integrationName, dictionnary, { locale = this.locale } = {}) => __awaiter(this, void 0, void 0, function* () {
4997 const result = yield dictionnary;
4998 const newEntries = !!integrationName
4999 ? { [integrationName]: result }
5000 : result;
5001 this._dictionnary[locale] = lodash_merge(lodash_get(this._dictionnary, locale), newEntries);
5002 this.localeChanged();
5003 });
5004 this.get = (integrationName, key, options = {}) => {
5005 const path = [options.locale || this.locale, integrationName, key].filter(m => m).join('.');
5006 debug('lookup key', path);
5007 return lodash_get(this._dictionnary, path);
5008 };
5009 }
5010 localeChanged() {
5011 document.dispatchEvent(new CustomEvent(LOCALE_CHANGED, { detail: { locale: this.locale } }));
5012 }
5013 /**
5014 * set the current locale you want your integrations to use
5015 */
5016 set locale(locale) {
5017 this._locale = locale;
5018 this.localeChanged();
5019 }
5020 get locale() {
5021 return this._locale;
5022 }
5023 }
5024 const i18n = new I18n();
5025
5026 /**
5027 * @param {string} clientId Client ID you'll find within the developer portal > Settings
5028 * @param {Partial<TBearerOptions>} options? Fine tune bearer functionalities
5029 */
5030 // @ts-ignore
5031 const bearer = (clientId, options) => {
5032 bearer.instance = new Bearer(clientId, options);
5033 return bearer.instance;
5034 };
5035 // Handle non instantiated bearer client
5036 Object.defineProperty(bearer, 'instance', {
5037 get: function () {
5038 if (!this._instance) {
5039 logMissingInstance();
5040 this._instance = new Bearer(undefined);
5041 }
5042 return this._instance;
5043 },
5044 set: function (bearerInstance) {
5045 this._instance = bearerInstance;
5046 }
5047 });
5048 bearer.version = '0.112.0';
5049 bearer.i18n = i18n;
5050 // fake the presence of secured
5051 bearer.secured = false;
5052 Object.defineProperty(bearer, 'secured', {
5053 get: function () {
5054 return this.instance && this.instance.secured;
5055 },
5056 set: function (secured) {
5057 this.instance.secured = secured;
5058 }
5059 });
5060 const MISSING_INSTANCE_MEESSAGE = '%c No bearer client has been initialized. please make sure you call bearer("YOUR_CLIENT") before using any component of backend function';
5061 const MISSING_INSTANCE_STYLE = 'font-weight:bold;';
5062 function logMissingInstance() {
5063 if (logger.enabled) {
5064 logger.extend('main')(MISSING_INSTANCE_MEESSAGE, MISSING_INSTANCE_STYLE);
5065 }
5066 else {
5067 console.warn(MISSING_INSTANCE_MEESSAGE, MISSING_INSTANCE_STYLE);
5068 }
5069 }
5070
5071 return bearer;
5072
5073})));
5074//# sourceMappingURL=bearer.development.min.js.map