From 3ec845a6f05c36d81cd519720b0416b3a505b866 Mon Sep 17 00:00:00 2001 From: artmanque Date: Fri, 25 Feb 2022 14:47:18 +0500 Subject: [PATCH 01/32] fix(react): dont use iframe context constants --- src/drivers/react.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/drivers/react.js b/src/drivers/react.js index 9f26f38c..ca5a15f1 100644 --- a/src/drivers/react.js +++ b/src/drivers/react.js @@ -4,7 +4,6 @@ import { extend, noop } from 'belter/src'; import type { ComponentDriverType } from '../component'; -import { CONTEXT } from '../constants'; declare class ReactClassType {} declare class __ReactComponent {} @@ -42,7 +41,7 @@ export const react : ComponentDriverType<*, ReactLibraryType, typeof ReactClassT // $FlowFixMe const el = ReactDOM.findDOMNode(this); const parent = init(extend({}, this.props)); - parent.render(el, CONTEXT.IFRAME); + parent.render(el); this.setState({ parent }); } From d97a8ee5f70ad5776a9448533ad6d3fe095aa66a Mon Sep 17 00:00:00 2001 From: artmanque Date: Fri, 25 Feb 2022 14:47:32 +0500 Subject: [PATCH 02/32] fix(angular): dont use iframe context constants --- src/drivers/angular.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/drivers/angular.js b/src/drivers/angular.js index 1e1bb6a4..f7101601 100644 --- a/src/drivers/angular.js +++ b/src/drivers/angular.js @@ -3,7 +3,6 @@ import { dasherizeToCamel, replaceObject, noop } from 'belter/src'; import type { ComponentDriverType } from '../component'; -import { CONTEXT } from '../constants'; type AngularModule = {| directive : (string, () => {| @@ -62,7 +61,7 @@ export const angular : ComponentDriverType<*, Angular, AngularModule, *, *> = { }; const instance = init(getProps()); - instance.render($element[0], CONTEXT.IFRAME); + instance.render($element[0]); $scope.$watch(() => { instance.updateProps(getProps()).catch(noop); From a3efdf651549a77ce8a77f01fee450524858fc98 Mon Sep 17 00:00:00 2001 From: artmanque Date: Fri, 25 Feb 2022 14:47:42 +0500 Subject: [PATCH 03/32] fix(angular2): dont use iframe context constants --- src/drivers/angular2.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/drivers/angular2.js b/src/drivers/angular2.js index 7144a4f9..74b19efd 100644 --- a/src/drivers/angular2.js +++ b/src/drivers/angular2.js @@ -4,7 +4,6 @@ import { replaceObject } from 'belter/src'; import type { ComponentDriverType } from '../component'; -import { CONTEXT } from '../constants'; type Angular2Injection = {||}; @@ -82,7 +81,7 @@ export const angular2 : ComponentDriverType<*, Angular2, Angular2Module, *, *> = ngOnInit() { const targetElement = this.elementRef.nativeElement; this.parent = init(this.getProps()); - this.parent.render(targetElement, CONTEXT.IFRAME); + this.parent.render(targetElement); } ngDoCheck() { From afe812979ad900a5da8d1ce6ba0d9464507af3eb Mon Sep 17 00:00:00 2001 From: artmanque Date: Fri, 25 Feb 2022 14:47:50 +0500 Subject: [PATCH 04/32] fix(vue): dont use iframe context constants --- src/drivers/vue.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/drivers/vue.js b/src/drivers/vue.js index 9b7e69d3..12fc17bc 100644 --- a/src/drivers/vue.js +++ b/src/drivers/vue.js @@ -3,7 +3,6 @@ import { noop, dasherizeToCamel } from 'belter/src'; import type { ComponentDriverType } from '../component'; -import { CONTEXT } from '../constants'; type VueComponent = {| render : (Function) => Element, @@ -59,7 +58,7 @@ export const vue : ComponentDriverType<*, VueType, RegisteredVueComponent, *, *> // $FlowFixMe[object-this-reference] this.parent = init({ ...propsToCamelCase(this.$attrs) }); // $FlowFixMe[object-this-reference] - this.parent.render(el, CONTEXT.IFRAME); + this.parent.render(el); }, watch: { From 71b5912d24d17df9b423c9d36349bd6ce3229fee Mon Sep 17 00:00:00 2001 From: artmanque Date: Fri, 25 Feb 2022 14:48:02 +0500 Subject: [PATCH 05/32] fix(vue3): dont use iframe context constants --- src/drivers/vue3.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/drivers/vue3.js b/src/drivers/vue3.js index 94270064..5511ba34 100644 --- a/src/drivers/vue3.js +++ b/src/drivers/vue3.js @@ -2,7 +2,6 @@ import { dasherizeToCamel, noop } from 'belter/src'; import type { ComponentDriverType } from '../component'; -import { CONTEXT } from '../constants'; function propsToCamelCase(props : Object) : Object { return Object.keys(props).reduce((acc, key) => { @@ -34,7 +33,7 @@ export const vue3 : ComponentDriverType<*, *, *, *, *> = { // $FlowFixMe[object-this-reference] this.parent = init({ ...propsToCamelCase(this.$attrs) }); // $FlowFixMe[object-this-reference] - this.parent.render(el, CONTEXT.IFRAME); + this.parent.render(el); }, watch: { From c70e06fc5910c7d32cac1fbebe12566ea70f1150 Mon Sep 17 00:00:00 2001 From: artmanque Date: Fri, 25 Feb 2022 14:48:32 +0500 Subject: [PATCH 06/32] fix: update dist/zoid.frameworks.js --- dist/zoid.frameworks.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/dist/zoid.frameworks.js b/dist/zoid.frameworks.js index 0490eb2c..8a303bad 100644 --- a/dist/zoid.frameworks.js +++ b/dist/zoid.frameworks.js @@ -4886,7 +4886,7 @@ _proto.componentDidMount = function() { var el = ReactDOM.findDOMNode(this); var parent = init(extend({}, this.props)); - parent.render(el, CONTEXT.IFRAME); + parent.render(el); this.setState({ parent: parent }); @@ -4916,7 +4916,7 @@ return acc; }), {})))); var props; - this.parent.render(el, CONTEXT.IFRAME); + this.parent.render(el); }, watch: { $attrs: { @@ -4945,7 +4945,7 @@ return acc; }), {})))); var props; - this.parent.render(el, CONTEXT.IFRAME); + this.parent.render(el); }, watch: { $attrs: { @@ -4983,7 +4983,7 @@ })); }; var instance = init(getProps()); - instance.render($element[0], CONTEXT.IFRAME); + instance.render($element[0]); $scope.$watch((function() { instance.updateProps(getProps()).catch(src_util_noop); })); @@ -5026,7 +5026,7 @@ _proto.ngOnInit = function() { var targetElement = this.elementRef.nativeElement; this.parent = init(this.getProps()); - this.parent.render(targetElement, CONTEXT.IFRAME); + this.parent.render(targetElement); }; _proto.ngDoCheck = function() { if (this.parent && !function(obj1, obj2) { From eb08a0c58ba64d357ef38a9a131fadd28071803c Mon Sep 17 00:00:00 2001 From: artmanque Date: Fri, 25 Feb 2022 14:50:06 +0500 Subject: [PATCH 07/32] fix: remove prepare script temporary --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index d6b89cbf..1de7d1c4 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,6 @@ "clean": "rimraf dist coverage", "reinstall": "rimraf flow-typed && rimraf node_modules && npm install && flow-typed install", "debug": "cross-env NODE_ENV=debug", - "prepare": "husky install", "prerelease": "npm run clean && npm run test && npm run build", "release": "standard-version", "postrelease": "git push && git push --follow-tags && npm publish" From 7a55ed4fd5feb94b37565daa782ab888236c3809 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:21:19 +0500 Subject: [PATCH 08/32] feat(context): context prop | add contextPropType --- src/component/props.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/component/props.js b/src/component/props.js index 849746ab..b8582acd 100644 --- a/src/component/props.js +++ b/src/component/props.js @@ -28,6 +28,7 @@ export type hidePropType = () => ZalgoPromise; export type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise; export type getParentPropType = () => CrossDomainWindowType; export type getParentDomainPropType = () => string; +export type contextPropType = string; export type onDisplayPropType = EventHandlerType; export type onRenderedPropType = EventHandlerType; @@ -52,6 +53,7 @@ export type PropsInputType

= {| timeout? : timeoutPropType, window? : windowPropType, cspNonce? : ?cspNoncePropType, + context? : ?contextPropType, onDisplay? : onDisplayPropType, onRendered? : onRenderedPropType, @@ -70,6 +72,7 @@ export type PropsType

= {| timeout? : timeoutPropType, window? : ?windowPropType, cspNonce? : ?cspNoncePropType, + context? : ?contextPropType, dimensions : CssDimensionsType, onDisplay : onDisplayPropType, @@ -213,6 +216,7 @@ export type BuiltInPropsDefinitionType = {| show : FunctionPropDefinitionType, export : FunctionPropDefinitionType, P, X>, getSiblings : FunctionPropDefinitionType, + context : StringPropDefinitionType, onDisplay : FunctionPropDefinitionType, onRendered : FunctionPropDefinitionType, @@ -274,6 +278,11 @@ export function getBuiltInProps() : BuiltInPropsDefinitionType { required: false }, + context: { + type: PROP_TYPE.STRING, + required: false + }, + onDisplay: { type: PROP_TYPE.FUNCTION, required: false, From be5953e157fe6658d37d407df2798c7e37a467ce Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:22:37 +0500 Subject: [PATCH 09/32] feat: angular driver uses context prop --- src/drivers/angular.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/drivers/angular.js b/src/drivers/angular.js index f7101601..0b2f4718 100644 --- a/src/drivers/angular.js +++ b/src/drivers/angular.js @@ -60,8 +60,9 @@ export const angular : ComponentDriverType<*, Angular, AngularModule, *, *> = { }); }; - const instance = init(getProps()); - instance.render($element[0]); + const props = getProps(); + const instance = init(props); + instance.render($element[0], props.context); $scope.$watch(() => { instance.updateProps(getProps()).catch(noop); From 2041c654afe163983362e830f5b3b1900b54ca7f Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:22:49 +0500 Subject: [PATCH 10/32] feat: angular2 driver uses context prop --- src/drivers/angular2.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/drivers/angular2.js b/src/drivers/angular2.js index 74b19efd..0b12ecf7 100644 --- a/src/drivers/angular2.js +++ b/src/drivers/angular2.js @@ -80,8 +80,9 @@ export const angular2 : ComponentDriverType<*, Angular2, Angular2Module, *, *> = ngOnInit() { const targetElement = this.elementRef.nativeElement; - this.parent = init(this.getProps()); - this.parent.render(targetElement); + const props = this.getProps(); + this.parent = init(props); + this.parent.render(targetElement, props.context); } ngDoCheck() { From 72e6cce2041bf33087ee15be672ba0769fe68512 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:23:00 +0500 Subject: [PATCH 11/32] feat: react driver uses context prop --- src/drivers/react.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/drivers/react.js b/src/drivers/react.js index ca5a15f1..a4e7959d 100644 --- a/src/drivers/react.js +++ b/src/drivers/react.js @@ -41,7 +41,7 @@ export const react : ComponentDriverType<*, ReactLibraryType, typeof ReactClassT // $FlowFixMe const el = ReactDOM.findDOMNode(this); const parent = init(extend({}, this.props)); - parent.render(el); + parent.render(el, this.props.context); this.setState({ parent }); } From 8703b2ced37d89847202487086655f4662e75d26 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:23:13 +0500 Subject: [PATCH 12/32] feat: vue driver uses context prop --- src/drivers/vue.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/drivers/vue.js b/src/drivers/vue.js index 12fc17bc..32650134 100644 --- a/src/drivers/vue.js +++ b/src/drivers/vue.js @@ -58,7 +58,7 @@ export const vue : ComponentDriverType<*, VueType, RegisteredVueComponent, *, *> // $FlowFixMe[object-this-reference] this.parent = init({ ...propsToCamelCase(this.$attrs) }); // $FlowFixMe[object-this-reference] - this.parent.render(el); + this.parent.render(el, this.$attrs.context); }, watch: { From a3396a246a99a92ac7e94c291e9d39f63b2b1939 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:23:29 +0500 Subject: [PATCH 13/32] feat: vue3 driver uses context prop --- src/drivers/vue3.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/drivers/vue3.js b/src/drivers/vue3.js index 5511ba34..69a8cb7e 100644 --- a/src/drivers/vue3.js +++ b/src/drivers/vue3.js @@ -33,7 +33,7 @@ export const vue3 : ComponentDriverType<*, *, *, *, *> = { // $FlowFixMe[object-this-reference] this.parent = init({ ...propsToCamelCase(this.$attrs) }); // $FlowFixMe[object-this-reference] - this.parent.render(el); + this.parent.render(el, this.$attrs.context); }, watch: { From d841cd27e546211fdb303abe10149d34bf26140b Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:25:29 +0500 Subject: [PATCH 14/32] feat: context prop | update build dist dir --- dist/zoid.frame.js | 544 ++++++------------------- dist/zoid.frame.min.js | 2 +- dist/zoid.frame.min.js.map | 2 +- dist/zoid.frameworks.frame.js | 560 ++++++-------------------- dist/zoid.frameworks.frame.min.js | 2 +- dist/zoid.frameworks.frame.min.js.map | 2 +- dist/zoid.frameworks.js | 555 +++++-------------------- dist/zoid.frameworks.min.js | 2 +- dist/zoid.frameworks.min.js.map | 2 +- dist/zoid.js | 539 +++++-------------------- dist/zoid.min.js | 2 +- dist/zoid.min.js.map | 2 +- 12 files changed, 478 insertions(+), 1736 deletions(-) diff --git a/dist/zoid.frame.js b/dist/zoid.frame.js index 1a18a844..8726446e 100644 --- a/dist/zoid.frame.js +++ b/dist/zoid.frame.js @@ -423,6 +423,10 @@ function isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } + var WINDOW_TYPE = { + IFRAME: "iframe", + POPUP: "popup" + }; var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; function getActualProtocol(win) { void 0 === win && (win = window); @@ -646,6 +650,21 @@ } return !1; } + function getFrameByName(win, name) { + var winFrames = getFrames(win); + for (var _i9 = 0; _i9 < winFrames.length; _i9++) { + var childFrame = winFrames[_i9]; + try { + if (isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; + } catch (err) {} + } + try { + if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; + } catch (err) {} + try { + if (-1 !== winFrames.indexOf(win[name])) return win[name]; + } catch (err) {} + } function getAncestor(win) { void 0 === win && (win = window); return getOpener(win = win || window) || utils_getParent(win) || void 0; @@ -657,6 +676,27 @@ } return !1; } + function getDistanceFromTop(win) { + void 0 === win && (win = window); + var distance = 0; + var parent = win; + for (;parent; ) (parent = utils_getParent(parent)) && (distance += 1); + return distance; + } + function isSameTopWindow(win1, win2) { + var top1 = getTop(win1) || win1; + var top2 = getTop(win2) || win2; + try { + if (top1 && top2) return top1 === top2; + } catch (err) {} + var allFrames1 = getAllFramesInWindow(win1); + var allFrames2 = getAllFramesInWindow(win2); + if (anyMatch(allFrames1, allFrames2)) return !0; + var opener1 = getOpener(top1); + var opener2 = getOpener(top2); + return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), + !1; + } function matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; @@ -667,6 +707,29 @@ return matchDomain(subpattern, origin); }))); } + function getDomainFromUrl(url) { + return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : getDomain(); + } + function onCloseWindow(win, callback, delay, maxtime) { + void 0 === delay && (delay = 1e3); + void 0 === maxtime && (maxtime = 1 / 0); + var timeout; + !function check() { + if (isWindowClosed(win)) { + timeout && clearTimeout(timeout); + return callback(); + } + if (maxtime <= 0) clearTimeout(timeout); else { + maxtime -= delay; + timeout = setTimeout(check, delay); + } + }(); + return { + cancel: function() { + timeout && clearTimeout(timeout); + } + }; + } function isWindow(obj) { try { if (obj === window) return !0; @@ -1688,7 +1751,7 @@ })); var windowTypePromise = winPromise.then((function(window) { if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type"); - return getOpener(window) ? "popup" : "iframe"; + return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME; })); windowNamePromise.catch(src_util_noop); windowTypePromise.catch(src_util_noop); @@ -1806,7 +1869,7 @@ }; _proto.isPopup = function() { return this.getType().then((function(type) { - return "popup" === type; + return type === WINDOW_TYPE.POPUP; })); }; _proto.setLocation = function(href, opts) { @@ -2149,20 +2212,7 @@ return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent; }(window).match(/MSIE|rv:11|trident|edge\/12|edge\/13/i)) throw new Error("Global messaging not needed for browser"); if (!isSameDomain(win)) throw new Error("Post message through global disabled between different domain windows"); - if (!1 !== function(win1, win2) { - var top1 = getTop(win1) || win1; - var top2 = getTop(win2) || win2; - try { - if (top1 && top2) return top1 === top2; - } catch (err) {} - var allFrames1 = getAllFramesInWindow(win1); - var allFrames2 = getAllFramesInWindow(win2); - if (anyMatch(allFrames1, allFrames2)) return !0; - var opener1 = getOpener(top1); - var opener2 = getOpener(top2); - return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), - !1; - }(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames"); + if (!1 !== isSameTopWindow(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames"); var foreignGlobal = global_getGlobal(win); if (!foreignGlobal) throw new Error("Can not find postRobot global on foreign window"); foreignGlobal.receiveMessage({ @@ -2600,342 +2650,10 @@ send: send_send }); } - function src_util_isRegex(item) { - return "[object RegExp]" === {}.toString.call(item); - } - function utils_getActualProtocol(win) { - void 0 === win && (win = window); - return win.location.protocol; - } - function utils_getProtocol(win) { - void 0 === win && (win = window); - if (win.mockDomain) { - var protocol = win.mockDomain.split("//")[0]; - if (protocol) return protocol; - } - return utils_getActualProtocol(win); - } - function utils_isAboutProtocol(win) { - void 0 === win && (win = window); - return "about:" === utils_getProtocol(win); - } - function src_utils_getParent(win) { - void 0 === win && (win = window); - if (win) try { - if (win.parent && win.parent !== win) return win.parent; - } catch (err) {} - } - function utils_getOpener(win) { - void 0 === win && (win = window); - if (win && !src_utils_getParent(win)) try { - return win.opener; - } catch (err) {} - } - function utils_canReadFromWindow(win) { - try { - return !0; - } catch (err) {} - return !1; - } - function utils_getActualDomain(win) { - void 0 === win && (win = window); - var location = win.location; - if (!location) throw new Error("Can not read window location"); - var protocol = utils_getActualProtocol(win); - if (!protocol) throw new Error("Can not read window protocol"); - if ("file:" === protocol) return "file://"; - if ("about:" === protocol) { - var parent = src_utils_getParent(win); - return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://"; - } - var host = location.host; - if (!host) throw new Error("Can not read window host"); - return protocol + "//" + host; - } - function utils_getDomain(win) { - void 0 === win && (win = window); - var domain = utils_getActualDomain(win); - return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; - } - function utils_isSameDomain(win) { - if (!function(win) { - try { - if (win === window) return !0; - } catch (err) {} - try { - var desc = Object.getOwnPropertyDescriptor(win, "location"); - if (desc && !1 === desc.enumerable) return !1; - } catch (err) {} - try { - if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; - } catch (err) {} - try { - if (function(win) { - void 0 === win && (win = window); - return "mock:" === utils_getProtocol(win); - }(win) && utils_canReadFromWindow()) return !0; - } catch (err) {} - try { - if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0; - } catch (err) {} - return !1; - }(win)) return !1; - try { - if (win === window) return !0; - if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; - if (utils_getDomain(window) === utils_getDomain(win)) return !0; - } catch (err) {} - return !1; - } - function utils_assertSameDomain(win) { - if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain"); - return win; - } - function utils_isAncestorParent(parent, child) { - if (!parent || !child) return !1; - var childParent = src_utils_getParent(child); - return childParent ? childParent === parent : -1 !== function(win) { - var result = []; - try { - for (;win.parent !== win; ) { - result.push(win.parent); - win = win.parent; - } - } catch (err) {} - return result; - }(child).indexOf(parent); - } - function utils_getFrames(win) { - var result = []; - var frames; - try { - frames = win.frames; - } catch (err) { - frames = win; - } - var len; - try { - len = frames.length; - } catch (err) {} - if (0 === len) return result; - if (len) { - for (var i = 0; i < len; i++) { - var frame = void 0; - try { - frame = frames[i]; - } catch (err) { - continue; - } - result.push(frame); - } - return result; - } - for (var _i = 0; _i < 100; _i++) { - var _frame = void 0; - try { - _frame = frames[_i]; - } catch (err) { - return result; - } - if (!_frame) return result; - result.push(_frame); - } - return result; - } - function utils_getAllChildFrames(win) { - var result = []; - for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) { - var frame = _getFrames2[_i3]; - result.push(frame); - for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); - } - return result; - } - function utils_getTop(win) { - void 0 === win && (win = window); - try { - if (win.top) return win.top; - } catch (err) {} - if (src_utils_getParent(win) === win) return win; - try { - if (utils_isAncestorParent(window, win) && window.top) return window.top; - } catch (err) {} - try { - if (utils_isAncestorParent(win, window) && window.top) return window.top; - } catch (err) {} - for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { - var frame = _getAllChildFrames4[_i7]; - try { - if (frame.top) return frame.top; - } catch (err) {} - if (src_utils_getParent(frame) === frame) return frame; - } - } - function utils_getAllFramesInWindow(win) { - var top = utils_getTop(win); - if (!top) throw new Error("Can not determine top window"); - var result = [].concat(utils_getAllChildFrames(top), [ top ]); - -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win))); - return result; - } - var utils_iframeWindows = []; - var utils_iframeFrames = []; - function utils_isWindowClosed(win, allowMock) { - void 0 === allowMock && (allowMock = !0); - try { - if (win === window) return !1; - } catch (err) { - return !0; - } - try { - if (!win) return !0; - } catch (err) { - return !0; - } - try { - if (win.closed) return !0; - } catch (err) { - return !err || "Call was rejected by callee.\r\n" !== err.message; - } - if (allowMock && utils_isSameDomain(win)) try { - if (win.mockclosed) return !0; - } catch (err) {} - try { - if (!win.parent || !win.top) return !0; - } catch (err) {} - var iframeIndex = function(collection, item) { - for (var i = 0; i < collection.length; i++) try { - if (collection[i] === item) return i; - } catch (err) {} - return -1; - }(utils_iframeWindows, win); - if (-1 !== iframeIndex) { - var frame = utils_iframeFrames[iframeIndex]; - if (frame && function(frame) { - if (!frame.contentWindow) return !0; - if (!frame.parentNode) return !0; - var doc = frame.ownerDocument; - if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { - var parent = frame; - for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; - if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; - } - return !1; - }(frame)) return !0; - } - return !1; - } - function utils_getFrameByName(win, name) { - var winFrames = utils_getFrames(win); - for (var _i9 = 0; _i9 < winFrames.length; _i9++) { - var childFrame = winFrames[_i9]; - try { - if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; - } catch (err) {} - } - try { - if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; - } catch (err) {} - try { - if (-1 !== winFrames.indexOf(win[name])) return win[name]; - } catch (err) {} - } - function utils_getAncestor(win) { - void 0 === win && (win = window); - return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0; - } - function utils_anyMatch(collection1, collection2) { - for (var _i17 = 0; _i17 < collection1.length; _i17++) { - var item1 = collection1[_i17]; - for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; - } - return !1; - } - function utils_getDistanceFromTop(win) { - void 0 === win && (win = window); - var distance = 0; - var parent = win; - for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1); - return distance; - } - function utils_matchDomain(pattern, origin) { - if ("string" == typeof pattern) { - if ("string" == typeof origin) return "*" === pattern || origin === pattern; - if (src_util_isRegex(origin)) return !1; - if (Array.isArray(origin)) return !1; - } - return src_util_isRegex(pattern) ? src_util_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) : !src_util_isRegex(origin) && pattern.some((function(subpattern) { - return utils_matchDomain(subpattern, origin); - }))); - } - function utils_getDomainFromUrl(url) { - return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain(); - } - function utils_onCloseWindow(win, callback, delay, maxtime) { - void 0 === delay && (delay = 1e3); - void 0 === maxtime && (maxtime = 1 / 0); - var timeout; - !function check() { - if (utils_isWindowClosed(win)) { - timeout && clearTimeout(timeout); - return callback(); - } - if (maxtime <= 0) clearTimeout(timeout); else { - maxtime -= delay; - timeout = setTimeout(check, delay); - } - }(); - return { - cancel: function() { - timeout && clearTimeout(timeout); - } - }; - } - function utils_isWindow(obj) { - try { - if (obj === window) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if ("[object Window]" === {}.toString.call(obj)) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (window.Window && obj instanceof window.Window) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.self === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.parent === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.top === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; - } catch (err) { - return !0; - } - try { - if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; - } catch (err) {} - return !1; - } function lib_global_getGlobal(win) { - if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain"); - win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {}); - return win.__zoid_9_0_87__; + if (!isSameDomain(win)) throw new Error("Can not get global for window on different domain"); + win.__zoid_9_0_88__ || (win.__zoid_9_0_88__ = {}); + return win.__zoid_9_0_88__; } function tryGlobal(win, handler) { try { @@ -3046,10 +2764,7 @@ DOTIFY: "dotify", BASE64: "base64" }; - var CONTEXT = { - IFRAME: "iframe", - POPUP: "popup" - }; + var CONTEXT = WINDOW_TYPE; var EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", @@ -3081,7 +2796,7 @@ sender: { win: function(_ref2) { return function(windowRef) { - if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window)); + if ("opener" === windowRef.type) return assertExists("opener", getOpener(window)); if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) { void 0 === n && (n = 1); return function(win, n) { @@ -3089,19 +2804,19 @@ var parent = win; for (var i = 0; i < n; i++) { if (!parent) return; - parent = src_utils_getParent(parent); + parent = utils_getParent(parent); } return parent; - }(win, utils_getDistanceFromTop(win) - n); + }(win, getDistanceFromTop(win) - n); }(window, windowRef.distance)); if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) { var _ret = function() { var uid = windowRef.uid; - var ancestor = utils_getAncestor(window); + var ancestor = getAncestor(window); if (!ancestor) throw new Error("Can not find ancestor window"); - for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { + for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { var frame = _getAllFramesInWindow2[_i2]; - if (utils_isSameDomain(frame)) { + if (isSameDomain(frame)) { var win = tryGlobal(frame, (function(global) { return global.windows && global.windows[uid]; })); @@ -3115,15 +2830,15 @@ } else if ("name" === windowRef.type) { var name = windowRef.name; return assertExists("namedWindow", function(win, name) { - return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) { - var frame = utils_getFrameByName(win, name); + return getFrameByName(win, name) || function findChildFrameByName(win, name) { + var frame = getFrameByName(win, name); if (frame) return frame; - for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) { - var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name); + for (var _i11 = 0, _getFrames4 = getFrames(win); _i11 < _getFrames4.length; _i11++) { + var namedFrame = findChildFrameByName(_getFrames4[_i11], name); if (namedFrame) return namedFrame; } - }(utils_getTop(win) || win, name); - }(assertExists("ancestor", utils_getAncestor(window)), name)); + }(getTop(win) || win, name); + }(assertExists("ancestor", getAncestor(window)), name)); } throw new Error("Unable to find " + windowRef.type + " parent component window"); }(_ref2.metaData.windowRef); @@ -3141,15 +2856,15 @@ } function window_getWindowRef(targetWindow, currentWindow) { void 0 === currentWindow && (currentWindow = window); - if (targetWindow === src_utils_getParent(currentWindow)) return { + if (targetWindow === utils_getParent(currentWindow)) return { type: "parent", - distance: utils_getDistanceFromTop(targetWindow) + distance: getDistanceFromTop(targetWindow) }; - if (targetWindow === utils_getOpener(currentWindow)) return { + if (targetWindow === getOpener(currentWindow)) return { type: "opener" }; - if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) { - var windowName = utils_assertSameDomain(targetWindow).name; + if (isSameDomain(targetWindow) && !(win = targetWindow, win === getTop(win))) { + var windowName = assertSameDomain(targetWindow).name; if (windowName) return { type: "name", name: windowName @@ -3352,7 +3067,7 @@ for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; - prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]); + prop && !1 === prop.sendToChild || prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window)) || (result[key] = props[key]); } return promise_ZalgoPromise.hash(result); }; @@ -3413,7 +3128,7 @@ }) : attributes; }; var getInitialChildDomain = function() { - return utils_getDomainFromUrl(getUrl()); + return getDomainFromUrl(getUrl()); }; var openFrame = function(context, _ref2) { var windowName = _ref2.windowName; @@ -3447,7 +3162,7 @@ return destroyElement(prerenderFrame); })); return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) { - return utils_assertSameDomain(prerenderFrameWindow); + return assertSameDomain(prerenderFrameWindow); })).then((function(win) { return setup_toProxyWindow(win); })); @@ -3471,7 +3186,7 @@ return uid; }; var getWindowRef = function(target, initialChildDomain, context, proxyWin) { - if (initialChildDomain === utils_getDomain(window)) return { + if (initialChildDomain === getDomain(window)) return { type: "global", uid: getCurrentWindowReferenceUID() }; @@ -3479,14 +3194,14 @@ if (props.window) { var actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop"); - if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); + if (getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); } if (context === CONTEXT.POPUP) return { type: "opener" }; if (context === CONTEXT.IFRAME) return { type: "parent", - distance: utils_getDistanceFromTop(window) + distance: getDistanceFromTop(window) }; throw new Error("Can not construct window reference for child"); }; @@ -3521,7 +3236,7 @@ var close = memoize((function(err) { return promise_ZalgoPromise.try((function() { if (closeOverride) { - if (utils_isWindowClosed(closeOverride.__source__)) return; + if (isWindowClosed(closeOverride.__source__)) return; return closeOverride(); } return promise_ZalgoPromise.try((function() { @@ -3569,7 +3284,7 @@ var unloadWindowListener = addEventListener(window, "unload", once((function() { destroy(new Error("Window navigated away")); }))); - var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3); + var closeParentWindowListener = onCloseWindow(parentWin, destroy, 3e3); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) return watchForUnloadOverride(); @@ -3636,14 +3351,14 @@ }) : promise_ZalgoPromise.try((function() { if (prerenderTemplate) { var prerenderWindow = proxyPrerenderWin.getWindow(); - if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) { + if (prerenderWindow && isSameDomain(prerenderWindow) && function(win) { try { if (!win.location.href) return !0; if ("about:blank" === win.location.href) return !0; } catch (err) {} return !1; }(prerenderWindow)) { - var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document; + var doc = (prerenderWindow = assertSameDomain(prerenderWindow)).document; var el = renderTemplate(prerenderTemplate, { context: context, doc: doc @@ -3927,22 +3642,9 @@ var childDomainMatch = domainMatch || getInitialChildDomain(); !function(target, childDomainMatch, container) { if (target !== window) { - if (!function(win1, win2) { - var top1 = utils_getTop(win1) || win1; - var top2 = utils_getTop(win2) || win2; - try { - if (top1 && top2) return top1 === top2; - } catch (err) {} - var allFrames1 = utils_getAllFramesInWindow(win1); - var allFrames2 = utils_getAllFramesInWindow(win2); - if (utils_anyMatch(allFrames1, allFrames2)) return !0; - var opener1 = utils_getOpener(top1); - var opener2 = utils_getOpener(top2); - return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1), - !1; - }(window, target)) throw new Error("Can only renderTo an adjacent frame"); - var origin = utils_getDomain(); - if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); + if (!isSameTopWindow(window, target)) throw new Error("Can only renderTo an adjacent frame"); + var origin = getDomain(); + if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }"); } }(target, childDomainMatch, container); @@ -3969,7 +3671,7 @@ }).then((function(_ref13) { var parentComp = _ref13.data.parent; clean.register((function(err) { - if (!utils_isWindowClosed(target)) return parentComp.destroy(err); + if (!isWindowClosed(target)) return parentComp.destroy(err); })); return parentComp.getDelegateOverrides(); })).catch((function(err) { @@ -4072,7 +3774,7 @@ hashString && (originalUrl = originalUrl + "#" + hashString); return originalUrl; }(function(url) { - if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; + if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; var domain; throw new Error("Mock urls not supported out of test mode"); }(getUrl()), { @@ -4091,7 +3793,7 @@ context: context, tag: tag, childDomainMatch: childDomainMatch, - version: "9_0_87", + version: "9_0_88", props: childProps, exports: (win = proxyWin, { init: function(childExports) { @@ -4122,13 +3824,13 @@ windowRef: getWindowRef(target, initialChildDomain, context, proxyWin) }, sender: { - domain: utils_getDomain(window) + domain: getDomain(window) }, receiver: { win: proxyWin, domain: childDomainMatch }, - passByReference: initialChildDomain === utils_getDomain() + passByReference: initialChildDomain === getDomain() }), serializedData = _crossDomainSerialize.serializedData; clean.register(_crossDomainSerialize.cleanReference); return serializedData; @@ -4375,10 +4077,10 @@ allowDelegate: !0, validate: function(_ref2) { var value = _ref2.value; - if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); - if (utils_isWindow(value)) { - if (utils_isWindowClosed(value)) throw new Error("Window is closed"); - if (!utils_isSameDomain(value)) throw new Error("Window is not same domain"); + if (!isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); + if (isWindow(value)) { + if (isWindowClosed(value)) throw new Error("Window is closed"); + if (!isSameDomain(value)) throw new Error("Window is not same domain"); } }, decorate: function(_ref3) { @@ -4394,6 +4096,10 @@ type: PROP_TYPE.STRING, required: !1 }, + context: { + type: PROP_TYPE.STRING, + required: !1 + }, onDisplay: { type: PROP_TYPE.FUNCTION, required: !1, @@ -4603,7 +4309,7 @@ return !1; }(name)) { var _payload = getInitialParentPayload().payload; - if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0; + if (_payload.tag === tag && matchDomain(_payload.childDomainMatch, getDomain())) return !0; } return !1; }; @@ -4621,7 +4327,7 @@ var props; var exportsPromise = new promise_ZalgoPromise; var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props; - if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87"); + if ("9_0_88" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_88"); var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init; var getParent = function() { return parentComponentWindow; @@ -4653,10 +4359,10 @@ var currentParent = props.parent; void 0 === anyParent && (anyParent = !currentParent); if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child"); - for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { + for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { var win = _getAllFramesInWindow2[_i2]; - if (utils_isSameDomain(win)) { - var xprops = utils_assertSameDomain(win).xprops; + if (isSameDomain(win)) { + var xprops = assertSameDomain(win).xprops; if (xprops && getParent() === xprops.getParent()) { var winParent = xprops.parent; if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) { @@ -4681,7 +4387,7 @@ for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; - if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) { + if (!prop || !prop.sameDomain || origin === getDomain(window) && isSameDomain(parentComponentWindow)) { var value = normalizeChildProp(propsDef, 0, key, props[key], helpers); result[key] = value; prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value); @@ -4718,7 +4424,7 @@ return { init: function() { return promise_ZalgoPromise.try((function() { - utils_isSameDomain(parentComponentWindow) && function(_ref3) { + isSameDomain(parentComponentWindow) && function(_ref3) { var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow; var _crossDomainDeseriali2 = crossDomainDeserialize({ data: parseWindowName(window.name).serializedInitialPayload, @@ -4738,7 +4444,7 @@ }, receiver: { win: window, - domain: utils_getDomain() + domain: getDomain() }, basic: !0 }); @@ -4757,7 +4463,7 @@ } }); !function(allowedParentDomains, domain) { - if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); + if (!matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); }(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); !function() { @@ -4767,7 +4473,7 @@ window.addEventListener("unload", (function() { checkClose.fireAndForget(); })); - utils_onCloseWindow(parentComponentWindow, (function() { + onCloseWindow(parentComponentWindow, (function() { child_destroy(); })); }(); @@ -4868,7 +4574,7 @@ throw err; })); } - if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo"); + if (!isWindow(target)) throw new Error("Must pass window to renderTo"); return function(props, context) { return promise_ZalgoPromise.try((function() { if (props.window) return setup_toProxyWindow(props.window).getType(); @@ -5053,7 +4759,7 @@ var destroyAll = destroyComponents; function component_destroy(err) { destroyAll(); - delete window.__zoid_9_0_87__; + delete window.__zoid_9_0_88__; !function() { !function() { var responseListeners = globalStore("responseListeners"); diff --git a/dist/zoid.frame.min.js b/dist/zoid.frame.min.js index 7d619054..b478b6fa 100644 --- a/dist/zoid.frame.min.js +++ b/dist/zoid.frame.min.js @@ -1,2 +1,2 @@ -!function(n,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("zoid",[],e):"object"==typeof exports?exports.zoid=e():n.zoid=e()}("undefined"!=typeof self?self:this,(function(){return function(n){var e={};function r(t){if(e[t])return e[t].exports;var o=e[t]={i:t,l:!1,exports:{}};return n[t].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=n,r.c=e,r.d=function(n,e,t){r.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:t})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,e){if(1&e&&(n=r(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var t=Object.create(null);if(r.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)r.d(t,o,function(e){return n[e]}.bind(null,o));return t},r.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(e,"a",e),e},r.o=function(n,e){return{}.hasOwnProperty.call(n,e)},r.p="",r(r.s=0)}([function(n,e,r){"use strict";function t(n,e){return(t=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function o(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,t(n,e)}function i(){return(i=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+cn(n,e+1)}}function fn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function sn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function dn(n){return n}function ln(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function hn(n){return[].slice.call(n)}function wn(n){return null!=n}function pn(n){return"[object RegExp]"==={}.toString.call(n)}function vn(n,e,r){if(n.hasOwnProperty(e))return n[e];var t=r();return n[e]=t,t}function mn(n){var e,r=[],t=!1,o={set:function(e,r){return t||(n[e]=r,o.register((function(){delete n[e]}))),r},register:function(n){var o=un((function(){return n(e)}));return t?n(e):r.push(o),{cancel:function(){var n=r.indexOf(o);-1!==n&&r.splice(n,1)}}},all:function(n){e=n;var o=[];for(t=!0;r.length;){var i=r.shift();o.push(i())}return w.all(o).then(an)}};return o}function yn(n,e){if(null==e)throw new Error("Expected "+n+" to be present");return e}tn.clear=function(){rn=en},tn((function(n){if(Object.values)return Object.values(n);var e=[];for(var r in n)n.hasOwnProperty(r)&&e.push(n[r]);return e}));var gn=function(n){function e(e){var r;return(r=n.call(this,e)||this).name=r.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(n){if(void 0===n)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}(r),r.constructor):r.stack=new Error(e).stack,r}return o(e,n),e}(Z(Error));function bn(){var n=document.body;if(!n)throw new Error("Body element not found");return n}function En(){return Boolean(document.body)&&"complete"===document.readyState}function _n(){return Boolean(document.body)&&"interactive"===document.readyState}function xn(n){return encodeURIComponent(n)}function Pn(n){return function(e,r,t){void 0===t&&(t=[]);var o=e.__inline_memoize_cache__=e.__inline_memoize_cache__||{},i=Q(t);return o.hasOwnProperty(i)?o[i]:o[i]=function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var r=0,t=n.split("&");r { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||K();n=we.unwrap(n);var f=r.__name__||r.name||t;return"string"==typeof f&&"function"==typeof f.indexOf&&0===f.indexOf("anonymous::")&&(f=f.replace("anonymous::",t+"::")),we.isProxyWindow(n)?(pe(c,r,f,n,e),n.awaitWindow().then((function(n){pe(c,r,f,n,e)}))):pe(c,r,f,n,e),ae("cross_domain_function",{id:c,name:f})}function ye(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=fe);var r=JSON.stringify(n,(function(n){var r=this[n];if(oe(this))return r;var t=ie(r);if(!t)return r;var o=e[t]||ce[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return ae("cross_domain_zalgo_promise",{then:me(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return me(n,e,r,t,{on:i,send:a})},o.object=function(n){return F(n)||we.isProxyWindow(n)?ae("cross_domain_window",we.serialize(n,{send:a})):n},o))}function ge(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=de),"undefined"!==n)return JSON.parse(n,(function(n,r){if(oe(this))return r;var t,o;if(oe(r)?(t=r.__type__,o=r.__val__):(t=ie(r),o=r),!t)return o;var i=e[t]||se[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new w(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return we.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=ve(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:P()},u);var f=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return we.deserialize(n,{send:i})},o))}var be={};function Ee(n,e,r,t){var o=t.on,i=t.send;return w.try((function(){var t=Kn().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||w.flush().then((function(){if(T(n))throw new Error("Window is closed");var r,a=ye(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(be),c=[],f=0;f1?e-1:0),o=1;o1?r-1:0),i=1;i iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),s.appendChild(r),s.appendChild(t),s.appendChild(d),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(vr.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){zn(t)}),1)})),a.on(vr.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(s.style.width=Hn(e)),"number"==typeof r&&(s.style.height=Hn(r))})),s}}var jr=mn(),Rr=mn();function Ar(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,f=void 0===c?{}:c,s=n.autoResize,d=void 0===s?{}:s,l=n.allowedParentDomains,h=void 0===l?"*":l,w=n.attributes,p=void 0===w?{}:w,v=n.defaultContext,m=void 0===v?pr.IFRAME:v,y=n.containerTemplate,g=void 0===y?Nr:y,b=n.prerenderTemplate,E=void 0===b?null:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,C=void 0===O?{info:an}:O,W=n.exports,D=void 0===W?an:W,S=n.method,N=n.children,j=void 0===N?function(){return{}}:N,R=e.replace(/-/g,"_"),A=i({},{window:{type:hr.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!ir(e)&&!we.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(ir(e)){if(Xe(e))throw new Error("Window is closed");if(!qe(e))throw new Error("Window is not same domain")}},decorate:function(n){return Re(n.value)}},timeout:{type:hr.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:hr.STRING,required:!1},onDisplay:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or,decorate:Cr},onRendered:{type:hr.FUNCTION,required:!1,sendToChild:!1,default:Or,decorate:Cr},onRender:{type:hr.FUNCTION,required:!1,sendToChild:!1,default:Or,decorate:Cr},onClose:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or,decorate:Cr},onDestroy:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or,decorate:Cr},onResize:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or},onFocus:{type:hr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Or},close:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:hr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:hr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:hr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:R,tag:e,url:r,domain:t,bridgeUrl:o,method:S,propsDef:A,dimensions:f,autoResize:d,allowedParentDomains:h,attributes:p,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:C,eligible:P,children:j,exports:"function"==typeof D?D:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=D[o].type,a=e().then((function(n){return n[o]}));r[o]=i===hr.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+wn(n,e+1)}}function pn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function vn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function mn(n){return n}function yn(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function gn(n){return[].slice.call(n)}function bn(n){return null!=n}function En(n){return"[object RegExp]"==={}.toString.call(n)}function _n(n,e,r){if(n.hasOwnProperty(e))return n[e];var t=r();return n[e]=t,t}function xn(n){var e,r=[],t=!1,o={set:function(e,r){return t||(n[e]=r,o.register((function(){delete n[e]}))),r},register:function(n){var o=hn((function(){return n(e)}));return t?n(e):r.push(o),{cancel:function(){var n=r.indexOf(o);-1!==n&&r.splice(n,1)}}},all:function(n){e=n;var o=[];for(t=!0;r.length;){var i=r.shift();o.push(i())}return w.all(o).then(ln)}};return o}function Pn(n,e){if(null==e)throw new Error("Expected "+n+" to be present");return e}sn.clear=function(){fn=cn},sn((function(n){if(Object.values)return Object.values(n);var e=[];for(var r in n)n.hasOwnProperty(r)&&e.push(n[r]);return e}));var On=function(n){function e(e){var r;return(r=n.call(this,e)||this).name=r.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(n){if(void 0===n)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}(r),r.constructor):r.stack=new Error(e).stack,r}return o(e,n),e}(Q(Error));function Cn(){var n=document.body;if(!n)throw new Error("Body element not found");return n}function Wn(){return Boolean(document.body)&&"complete"===document.readyState}function Sn(){return Boolean(document.body)&&"interactive"===document.readyState}function Dn(n){return encodeURIComponent(n)}function Nn(n){return function(e,r,t){void 0===t&&(t=[]);var o=e.__inline_memoize_cache__=e.__inline_memoize_cache__||{},i=an(t);return o.hasOwnProperty(i)?o[i]:o[i]=function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var r=0,t=n.split("&");r { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||on();n=be.unwrap(n);var f=r.__name__||r.name||t;return"string"==typeof f&&"function"==typeof f.indexOf&&0===f.indexOf("anonymous::")&&(f=f.replace("anonymous::",t+"::")),be.isProxyWindow(n)?(Ee(c,r,f,n,e),n.awaitWindow().then((function(n){Ee(c,r,f,n,e)}))):Ee(c,r,f,n,e),le("cross_domain_function",{id:c,name:f})}function Pe(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=pe);var r=JSON.stringify(n,(function(n){var r=this[n];if(se(this))return r;var t=de(r);if(!t)return r;var o=e[t]||we[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return le("cross_domain_zalgo_promise",{then:xe(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return xe(n,e,r,t,{on:i,send:a})},o.object=function(n){return J(n)||be.isProxyWindow(n)?le("cross_domain_window",be.serialize(n,{send:a})):n},o))}function Oe(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=me),"undefined"!==n)return JSON.parse(n,(function(n,r){if(se(this))return r;var t,o;if(se(r)?(t=r.__type__,o=r.__val__):(t=de(r),o=r),!t)return o;var i=e[t]||ve[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new w(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return be.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=_e(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:O()},u);var f=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return be.deserialize(n,{send:i})},o))}var Ce={};function We(n,e,r,t){var o=t.on,i=t.send;return w.try((function(){var t=oe().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||w.flush().then((function(){if(I(n))throw new Error("Window is closed");var r,a=Pe(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(Ce),c=[],f=0;f1?e-1:0),o=1;o1?r-1:0),i=1;i iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),s.appendChild(r),s.appendChild(t),s.appendChild(d),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(Ve.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){Bn(t)}),1)})),a.on(Ve.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(s.style.width=Xn(e)),"number"==typeof r&&(s.style.height=Xn(r))})),s}}var sr=xn(),dr=xn();function lr(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,f=void 0===c?{}:c,s=n.autoResize,d=void 0===s?{}:s,l=n.allowedParentDomains,h=void 0===l?"*":l,w=n.attributes,p=void 0===w?{}:w,v=n.defaultContext,m=void 0===v?Ze.IFRAME:v,y=n.containerTemplate,g=void 0===y?fr:y,b=n.prerenderTemplate,E=void 0===b?null:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,W=void 0===O?{info:ln}:O,S=n.exports,D=void 0===S?ln:S,N=n.method,j=n.children,R=void 0===j?function(){return{}}:j,T=e.replace(/-/g,"_"),A=i({},{window:{type:Ye.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!J(e)&&!be.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(J(e)){if(I(e))throw new Error("Window is closed");if(!C(e))throw new Error("Window is not same domain")}},decorate:function(n){return Fe(n.value)}},timeout:{type:Ye.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:Ye.STRING,required:!1},context:{type:Ye.STRING,required:!1},onDisplay:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or,decorate:ir},onRendered:{type:Ye.FUNCTION,required:!1,sendToChild:!1,default:or,decorate:ir},onRender:{type:Ye.FUNCTION,required:!1,sendToChild:!1,default:or,decorate:ir},onClose:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or,decorate:ir},onDestroy:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or,decorate:ir},onResize:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or},onFocus:{type:Ye.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:or},close:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:Ye.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:Ye.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:Ye.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:T,tag:e,url:r,domain:t,bridgeUrl:o,method:N,propsDef:A,dimensions:f,autoResize:d,allowedParentDomains:h,attributes:p,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:W,eligible:P,children:R,exports:"function"==typeof D?D:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=D[o].type,a=e().then((function(n){return n[o]}));r[o]=i===Ye.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer,\n undefined? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull,\n [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull,\n deserializeUndefined\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer,\n undefined? : PrimitiveDeserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull,\n [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SetLocationOptions = {|\n method? : $Values,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n const getName = () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n });\n\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n\n } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name, 'noopener');\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady : ZalgoPromise = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n // $FlowFixMe[method-unbinding]\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\ntype SendStrategies = {|\n [$Values] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore, getGlobalKey } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n const strDomain = domain.toString();\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n}\n\nexport function handleAck(source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n}\n\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[getGlobalKey()];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n if (isWindowClosed(source)) {\n return;\n }\n\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise = ZalgoPromise & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport { ProxyWindow } from '../serialize/window';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (winOrProxyWin, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n });\n};\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT : number = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from '@krakenjs/cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n\nexport function basicSerialize(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType =\n UIDReferenceType |\n RawReferenceType;\n\nexport function getUIDRefStore(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef(val : T) : ReferenceType {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef(val : T) : ReferenceType {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue(win : CrossDomainWindowType, ref : ReferenceType) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef(win : CrossDomainWindowType, ref : ReferenceType) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType\n|};\n\ntype CrossDomainSerializeOptions = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType\n|};\n\nexport function crossDomainDeserialize({ data, sender, basic = false } : CrossDomainDeserializeOptions) : CrossDomainDeserializedMessage {\n const message : Message = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from '@krakenjs/cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: ('string' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from '@krakenjs/cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = windowName.split('__');\n\n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n\n if (!name) {\n throw new Error(`Expected component name`);\n }\n\n if (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload,\n reference : ReferenceType\n|};\n\nconst parseInitialParentPayload = memoize((windowName : string) : InitialParentPayload => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload() : InitialParentPayload {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType, props : PropsType

, origin : string, helpers : ChildHelpers, isUpdate : boolean = false) : ChildPropsType {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise,\n getSiblings : getSiblingsPropType\n|};\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent = {|\n getProps : () => ChildPropsType,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent(options : NormalizedComponentOptionsType) : ChildComponent {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return getAutoResize().then(({ width, height, element }) => {\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type exportPropType = (X) => ZalgoPromise;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType

,\n export : exportPropType\n|};\n\nexport type PropsInputType

= {|\n parent? : ParentPropType,\n \n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : ?cspNoncePropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

,\n\n ...P\n|};\n\nexport type PropsType

= {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n dimensions : CssDimensionsType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise;\n\nexport type ChildPropsType = {|\n ...PropsType

,\n\n parent? : ParentPropType,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType

,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n // eslint-disable-next-line no-undef\n queryValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P, X> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType = {|\n [string] : MixedPropDefinitionType\n|};\n\nexport type BuiltInPropsDefinitionType = {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n uid : StringPropDefinitionType,\n tag : StringPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n export : FunctionPropDefinitionType, P, X>,\n getSiblings : FunctionPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P, X>\n|};\n\nexport type PropsDefinitionType = {|\n ...BuiltInPropsDefinitionType,\n [ string ] : MixedPropDefinitionType\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = ({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps() : BuiltInPropsDefinitionType {\n return {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback =\n ((string, BooleanPropDefinitionType | void, boolean) => R) &\n ((string, StringPropDefinitionType | void, string) => R) &\n ((string, NumberPropDefinitionType | void, number) => R) &\n ((string, FunctionPropDefinitionType | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType | void, Object) => R);\n\nexport function eachProp(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) : $ReadOnlyArray {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps(propsDef : PropsDefinitionType, existingProps : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps(propsDef : PropsDefinitionType, props : (PropsType

), method : $Values) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType = {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n childDomainMatch : DomainMatcher,\n props : PropsType

,\n exports : ParentExportsType\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise;\n\ntype RenderContainerOptions = {|\n context : $Values,\n proxyFrame : ?ProxyObject,\n proxyPrerenderFrame : ?ProxyObject,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise;\ntype RejectInitPromise = (mixed) => ZalgoPromise;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, RenderContainerOptions) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values|}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState,\n resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values,\n rerender : Rerender\n|};\n\ntype ParentComponent = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise,\n getProps : () => PropsType

,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise,\n getExports : () => X\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions = {|\n uid : string,\n options : NormalizedComponentOptionsType,\n overrides? : ParentDelegateOverrides

,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions) : ParentComponent {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType

= overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return rejectInitPromise(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__${ ZOID }_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getCurrentWindowReferenceUID = () : string => {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childDomain : string, childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin.setName(windowName).then(() => {\n return proxyWin;\n });\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow, context : $Values) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n const exportsPromise : ZalgoPromise = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType

) : ZalgoPromise {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values|} = {}) : ZalgoPromise> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|} = {}) : ZalgoPromise => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|}) : ZalgoPromise => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values|}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, initialChildDomain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType

= getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = ({ target, container, context, rerender } : RenderOptions) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, initialChildDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\n };\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType

) : ?HTMLElement {\n const { width, height } = dimensions;\n\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition = ({|\n getExports : () => ZalgoPromise\n|}) => X;\n\nexport type ExportsDefinition = ExportsConfigDefinition | ExportsMapperDefinition;\n\nexport type ComponentOptionsType = {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values,\n\n props? : UserPropsDefinitionType,\n\n dimensions? : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType

|}) => Attributes,\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values,\n\n propsDef : PropsDefinitionType,\n dimensions : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition\n|};\n\nexport type ZoidComponentInstance = {|\n ...ParentHelpers

,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance,\n render : (container? : ContainerReferenceType, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent = {\n (props? : PropsInputType

| void) : ZoidComponentInstance,\n // eslint-disable-next-line no-undef\n driver : (string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n instances : $ReadOnlyArray>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = () : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions(options : ComponentOptionsType) : NormalizedComponentOptionsType {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop },\n exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component = {|\n init : (props? : PropsInputType

| void) => ZoidComponentInstance,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent\n|};\n\nexport function component(opts : ComponentOptionsType) : Component {\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible,\n children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent => {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : ContainerReferenceType) : ContainerReferenceType => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType

| void) : ZoidComponentInstance => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType

= parent.getProps();\n const parentExport : exportPropType = parent.export;\n\n const childParent : ParentPropType = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, vue3, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L) => D\n|};\n\nexport type ZoidProps

= PropsType

;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = (options : ComponentOptionsType) => ZoidComponent;\n\nexport const create : CreateZoidComponent = (options : ComponentOptionsType) : ZoidComponent => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType

| void) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n};\n\nexport function destroyComponents(err? : mixed) : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://zoid/webpack/universalModuleDefinition","webpack://zoid/webpack/bootstrap","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://zoid/./node_modules/zalgo-promise/src/utils.js","webpack://zoid/./node_modules/zalgo-promise/src/exceptions.js","webpack://zoid/./node_modules/zalgo-promise/src/flush.js","webpack://zoid/./node_modules/zalgo-promise/src/promise.js","webpack://zoid/./node_modules/cross-domain-utils/src/util.js","webpack://zoid/./node_modules/cross-domain-utils/src/constants.js","webpack://zoid/./node_modules/cross-domain-utils/src/utils.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/weakmap.js","webpack://zoid/./node_modules/belter/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/native.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://zoid/./node_modules/belter/src/dom.js","webpack://zoid/./node_modules/belter/src/css.js","webpack://zoid/./node_modules/post-robot/src/global.js","webpack://zoid/./node_modules/belter/src/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/hello.js","webpack://zoid/./node_modules/post-robot/src/conf/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/windows.js","webpack://zoid/./node_modules/universal-serialize/src/common.js","webpack://zoid/./node_modules/universal-serialize/src/constants.js","webpack://zoid/./node_modules/universal-serialize/src/serialize.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/function.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/error.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/promise.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/regex.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/date.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/array.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/object.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/string.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/number.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/boolean.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/null.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/undefined.js","webpack://zoid/./node_modules/universal-serialize/src/deserialize.js","webpack://zoid/./node_modules/post-robot/src/serialize/window.js","webpack://zoid/./node_modules/post-robot/src/bridge/common.js","webpack://zoid/./node_modules/post-robot/src/serialize/function.js","webpack://zoid/./node_modules/post-robot/src/serialize/serialize.js","webpack://zoid/./node_modules/post-robot/src/serialize/promise.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/strategies.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/index.js","webpack://zoid/./node_modules/post-robot/src/drivers/listeners.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/types.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/index.js","webpack://zoid/./node_modules/post-robot/src/public/on.js","webpack://zoid/./node_modules/post-robot/src/lib/compat.js","webpack://zoid/./node_modules/post-robot/src/public/send.js","webpack://zoid/./node_modules/post-robot/src/conf/config.js","webpack://zoid/./node_modules/post-robot/src/setup.js","webpack://zoid/./src/lib/global.js","webpack://zoid/./src/lib/serialize.js","webpack://zoid/./src/constants.js","webpack://zoid/./src/lib/window.js","webpack://zoid/./src/child/props.js","webpack://zoid/./src/child/child.js","webpack://zoid/./src/component/props.js","webpack://zoid/./src/parent/props.js","webpack://zoid/./src/parent/parent.js","webpack://zoid/./node_modules/post-robot/src/clean.js","webpack://zoid/./src/component/templates/container.js","webpack://zoid/./src/component/component.js"],"names":["root","factory","exports","module","define","amd","self","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","hasOwnProperty","p","s","_setPrototypeOf","setPrototypeOf","__proto__","_inheritsLoose","subClass","superClass","prototype","constructor","_extends","assign","target","arguments","length","source","apply","isPromise","item","Promise","window","Window","toString","then","err","flushPromise","dispatchedErrors","possiblyUnhandledPromiseHandlers","activeCount","flushActive","promise","resolve","startActive","endActive","ZalgoPromise","handler","resolved","rejected","errorHandled","error","handlers","dispatching","stack","result","isAsync","res","reject","Error","dispatch","setTimeout","indexOf","push","j","dispatchPossiblyUnhandledError","asyncReject","chain","firstPromise","secondPromise","onSuccess","onError","promiseResult","catch","undefined","finally","onFinally","try","timeout","time","clearTimeout","toPromise","TypeError","lazy","all","promises","count","results","slice","prom","hash","awaitPromises","map","items","method","onPossiblyUnhandledException","cancel","splice","context","args","delay","flush","isRegex","WINDOW_TYPE","IFRAME","POPUP","IE_WIN_ACCESS_ERROR","getActualProtocol","win","location","protocol","getProtocol","mockDomain","split","isAboutProtocol","getParent","parent","getOpener","opener","canReadFromWindow","getActualDomain","PROTOCOL","host","getDomain","domain","isSameDomain","desc","getOwnPropertyDescriptor","isMockProtocol","isActuallySameDomain","assertSameDomain","isAncestorParent","child","childParent","getParents","getFrames","frames","len","frame","getAllChildFrames","getTop","top","getAllFramesInWindow","iframeWindows","iframeFrames","isWindowClosed","allowMock","closed","message","mockclosed","iframeIndex","collection","safeIndexOf","contentWindow","parentNode","doc","ownerDocument","documentElement","contains","isFrameWindowClosed","getFrameByName","winFrames","childFrame","getAncestor","anyMatch","collection1","collection2","item1","getDistanceFromTop","distance","isSameTopWindow","win1","win2","top1","top2","allFrames1","allFrames2","opener1","opener2","matchDomain","pattern","origin","Array","isArray","Boolean","match","JSON","stringify","some","subpattern","getDomainFromUrl","url","join","onCloseWindow","callback","maxtime","Infinity","check","isWindow","obj","__cross_domain_utils_window_check__","getFrameForWindow","frameElement","document","querySelectorAll","closeWindow","isIframe","parentElement","removeChild","close","objectIDs","CrossDomainSafeWeakMap","weakmap","keys","values","Math","random","WeakMap","freeze","testWeakMap","testKey","set","hasNativeWeakMap","_cleanupClosedWindows","delete","isSafeToReadWrite","entry","writable","index","has","getOrSet","_getPrototypeOf","getPrototypeOf","_isNativeReflectConstruct","Reflect","construct","sham","Proxy","Date","e","_construct","Parent","Class","isNativeReflectConstruct","a","instance","Function","_wrapNativeSuper","_cache","Map","Wrapper","configurable","isElement","element","passed","Element","nodeType","style","_","getFunctionName","fn","__name__","displayName","setFunctionName","base64encode","str","btoa","encodeURIComponent","replace","p1","String","fromCharCode","parseInt","Buffer","from","uniqueID","chars","charAt","floor","toISOString","toLowerCase","serializeArgs","subkey","val","uid","getObjectID","getEmptyObject","memoizeGlobalIndex","memoizeGlobalIndexValidFrom","memoize","options","simpleCache","thisCache","thisNamespace","cacheTime","memoizeIndex","memoizedFunction","cache","cacheKey","cacheResult","now","reset","memoizePromise","memoizedPromiseFunction","noop","once","called","stringifyError","level","newErr","extend","identity","safeInterval","loop","arrayFrom","isDefined","cleanup","cleanErr","tasks","cleaned","cleaner","register","task","shift","assertExists","thing","clear","ExtendableError","captureStackTrace","ReferenceError","getBody","body","isDocumentReady","readyState","isDocumentInteractive","urlEncode","parseQuery","queryString","logic","__inline_memoize_cache__","params","pair","decodeURIComponent","inlineMemoize","extendQuery","originalQuery","props","filter","appendChild","container","getElementSafe","id","querySelector","elementReady","el","interval","setInterval","clearInterval","awaitFrameLoadPromises","PopupOpenError","awaitFrameLoad","addEventListener","cleanIframes","linkFrameWindow","awaitFrameWindow","loadedFrame","iframe","tag","styleText","createElement","class","className","setAttribute","attributes","styleSheet","cssText","createTextNode","html","innerHTML","allowTransparency","backgroundColor","border","isIE","navigator","userAgent","hasAttribute","getElement","event","removeEventListener","showElement","setProperty","hideElement","destroyElement","isElementClosed","onResize","width","height","currentWidth","offsetWidth","currentHeight","offsetHeight","canceled","observer","getClientRects","isElementVisible","newWidth","newHeight","ResizeObserver","observe","MutationObserver","childList","subtree","characterData","disconnect","isShadowElement","currentScript","getCurrentScript","getStackTrace","stackDetails","exec","scriptLocation","getElementsByTagName","reverse","script","src","inferCurrentScript","currentUID","toPx","toNum","toCSS","test","getGlobal","globalKey","__POST_ROBOT__","getAttribute","ATTRIBUTES","hashedString","total","charCodeAt","abs","strHashStr","dataset","getObj","globalStore","defStore","store","storeKey","defVal","del","WildCard","getWildcard","global","WINDOW_WILDCARD","windowStore","winStore","getStore","getInstanceID","resolveHelloPromise","helloPromises","existingPromise","newPromise","sayHello","send","instanceID","data","getWindowInstanceID","markWindowKnown","isSerializedType","__type__","determineType","serializeType","type","__val__","SERIALIZER","code","toJSON","defaultSerializers","DESERIALIZER","RegExp","defaultDeserializers","cleanupProxyWindows","idToProxyWindow","shouldClean","getSerializedWindow","winPromise","windowNamePromise","windowTypePromise","getName","getType","focus","isClosed","setLocation","href","opts","form","display","input","submit","submitForm","setName","sameDomain","ProxyWindow","serializedWindow","isProxyWindow","actualWindow","actualWindowPromise","getID","setWindow","isPopup","isPopupPromise","getNamePromise","reopenPromise","open","focusPromise","getWindow","awaitWindow","matchWindow","proxyInstanceID","knownWindowInstanceID","unwrap","serialize","toProxyWindow","deserialize","addMethod","methodStore","proxyWindowMethods","lookupMethod","serializeFunction","destination","on","meth","methodSource","arg","__id__","serializeMessage","serializers","serializer","serializePromise","deserializeMessage","deserializers","parse","deserializer","serializedPromise","deserializePromise","serializedFunction","getDeserializedFunction","crossDomainFunctionWrapper","fireAndForget","__origin__","__source__","deserializeFunction","SEND_MESSAGE_STRATEGIES","sendMessage","domainBuffer","buffer","serializedMessage","strategies","errors","strategyName","getResponseListener","deleteResponseListener","isResponseListenerErrored","getRequestListener","requestListeners","winQualifier","nameListeners","domainListeners","listener","regex","handleRequest","logName","sendResponse","ack","pathname","handleError","handleAck","handleResponse","receiveMessage","receivedMessages","messages","parsedMessage","parseMessages","deserializeMessages","requestListener","addRequestListener","winCandidate","requestListenerPromise","actualWin","listenersCollection","existingListener","strDomain","winNameDomainRegexListeners","winNameDomainRegexListener","winNameListeners","winNameDomainListeners","errorHandler","postMessage","mockUserAgent","getUserAgent","foreignGlobal","winOrProxyWin","domainMatcher","responseTimeout","childTimeout","validateOptions","actualParent","isAncestor","getHelloPromise","awaitWindowHello","targetDomain","actualDomain","normalizedDomain","normalizeDomain","responseListener","addResponseListener","reqPromises","markResponseListenerErrored","totalAckTimeout","isWindowKnown","totalResTimeout","ackTimeout","resTimeout","cancelled","max","tryGlobal","getProxyObject","basicSerialize","getUIDRefStore","references","crossDomainSerialize","metaData","sender","receiver","passByReference","basic","proxyWin","internalSerializeMessage","reference","getRawRef","serializedData","cleanReference","ref","crossDomainDeserialize","atob","base64decode","basicDeserialize","getRefValue","internalDeserializeMessage","PROP_TYPE","STRING","OBJECT","FUNCTION","BOOLEAN","NUMBER","ARRAY","PROP_SERIALIZATION","DOTIFY","BASE64","CONTEXT","EVENT","RENDER","RENDERED","DISPLAY","ERROR","CLOSE","DESTROY","PROPS","RESIZE","FOCUS","buildChildWindowName","serializedPayload","parseWindowName","windowName","zoidcomp","serializedInitialPayload","parseInitialParentPayload","windowRef","getNthParent","ancestor","windows","findChildFrameByName","namedFrame","findFrameByName","getWindowByRef","payload","getInitialParentPayload","getWindowRef","targetWindow","currentWindow","normalizeChildProp","propsDef","helpers","prop","childDecorate","onProps","resize","getParentDomain","show","hide","export","getSiblings","destroy","defaultNoop","decorateOnce","eachProp","serializeProps","propDef","getParam","queryParam","bodyParam","getValue","queryValue","bodyValue","finalParam","finalValue","serialization","dotify","prefix","newobj","every","dotkey","mapProps","parentComponent","triggered","emitter","currentProxyWin","currentProxyContainer","childComponent","currentChildDomain","currentContainer","overrides","parentWin","containerTemplate","prerenderTemplate","dimensions","autoResize","domainMatch","xports","initPromise","handledErrors","clean","state","inputProps","internalState","visible","eventName","handlerList","trigger","triggerOnce","onErrorOverride","getProxyContainerOverride","getProxyContainer","showOverride","hideOverride","closeOverride","renderContainerOverride","renderContainer","getProxyWindowOverride","getProxyWindow","setProxyWinOverride","setProxyWin","openFrameOverride","openFrame","openPrerenderFrameOverride","openPrerenderFrame","prerenderOverride","prerender","openOverride","openPrerenderOverride","openPrerender","watchForUnloadOverride","watchForUnload","getInternalStateOverride","getInternalState","setInternalStateOverride","setInternalState","resolveInitPromise","rejectInitPromise","getPropsForChild","initialChildDomain","sendToChild","newInternalState","windowProp","setState","getUrl","getAttributes","getInitialChildDomain","title","proxyPrerenderFrame","prerenderFrame","prerenderFrameWindow","actualComponentWindow","initChild","childDomain","childExports","proxyFrame","cleanUpWindow","unloadWindowListener","closeParentWindowListener","checkWindowClose","secondIsClosed","exportsPromise","xport","actualExports","renderTemplate","renderer","proxyPrerenderWin","prerenderWindow","isBlankDomain","tagName","children","writeElementToWindow","prerenderResizeListener","proxyContainer","rerender","innerContainer","containerWatcher","sacrificialFrame","sacrificialFrameWin","mutationObservers","elementClosed","mutationElement","mutationObserver","frameWin","watchElementForClose","removeError","getHelpers","updateProps","setProps","newInputProps","existingProps","valueDetermined","alias","default","required","decorate","getDerivedValue","extendProps","newProps","childProps","containerElement","insertShadowSlot","shadowHost","shadowRoot","getShadowRoot","getShadowHost","slotName","slot","slotProvider","init","onRender","onDisplay","onRendered","onClose","onDestroy","onFocus","render","childDomainMatch","checkAllowRender","delegatePromise","delegateProps","propName","allowDelegate","childOverridesPromise","POST_MESSAGE","parentComp","getDelegateOverrides","childOverrides","delegate","watchForUnloadPromise","buildBodyPromise","onRenderPromise","getProxyContainerPromise","getProxyWindowPromise","finalSetPropsPromise","buildUrlPromise","query","originalUrl","originalHash","hashString","extendUrl","normalizeMockUrl","buildWindowNamePromise","version","__ZOID__","checkClose","buildInitialChildPayload","childPayload","buildSerializedChildPayload","openFramePromise","openPrerenderFramePromise","renderContainerPromise","openPromise","openPrerenderPromise","setStatePromise","prerenderPromise","setWindowNamePromise","getMethodPromise","loadUrlPromise","windowUrl","watchForClosePromise","watchForClose","onDisplayPromise","openBridgePromise","runTimeoutPromise","onRenderedPromise","getProps","getExports","defaultContainerTemplate","div","cspNonce","classList","add","remove","cleanInstances","cleanZoid","component","allowDelegateListener","delegateListener","bridgeUrl","allowedParentDomains","defaultContext","validate","eligible","logger","info","xportsDefinition","valuePromise","normalizeOptions","instances","isChild","isChildComponentWindow","registerChild","xprops","components","onPropHandlers","parentComponentWindow","parentDomain","parentExports","initialProps","parentExport","parentResize","parentInit","anyParent","currentParent","winParent","isUpdate","normalizedProps","normalizeChildProps","componentName","updateChildWindowNameWithRef","checkParentDomain","ZOID","eligibility","reason","clone","getDefaultContext","finalContext","getDefaultContainer","newInstance","renderTo","childComponents","childName","Child","childInputProps","parentProps","getChildren","isEligible","driver","driverName","dep","canRenderTo","initialized","sourceElement","originalEvent","messageListener","listenForMessages","initHello","comp","destroyComponents","destroyPromise","destroyAll","responseListeners","cancelResponseListeners"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,OAAQ,GAAIH,GACO,iBAAZC,QACdA,QAAc,KAAID,IAElBD,EAAW,KAAIC,IARjB,CASoB,oBAATK,KAAuBA,KAAOC,MAAO,WAChD,O,YCTE,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V,GAASzV,EAAQ,CAAE0V,SAAQrY,OAAM,SAAArC,OAQ9BmhB,KiC3BP0Z,CAAU,CAAEhc,MAAInE,WYugBpB,IAAMogB,EAAO9D,GAAUlnB,GAEjB+iB,EAAO,SAACvf,GAAD,OAAuCwnB,EAAKjI,KAAKvf,IAC9Duf,EAAKuH,OAAS,SAACl9B,EAAMo9B,GAAP,OAAeQ,EAAKV,OAAOl9B,EAAMo9B,IAC/CzH,EAAKiF,QAAU,kBAAMgD,EAAKhD,WAC1BjF,EAAK0H,YAAc,SAAC/1B,GAAD,OAASs2B,EAAKP,YAAY/1B,IAC7CquB,EAAKgF,UAAYiD,EAAKjD,UAEtB,IAAM7xB,EAAQ80B,EAAK9C,gBAKnB,OAJIhyB,IACApG,OAAOq4B,OAASpF,EAAKoF,OAASjyB,EAAMswB,YAGjCzD,GAGJ,SAASkI,GAAkB/6B,GAK9B,IAAMg7B,EAAiBlE,GAAe9zB,IAAIhD,GAE1C,OADA82B,GAAiBtlB,KACVwpB,EAGJ,IAAMC,GAAaF,GAEnB,SAAStR,GAAQzpB,GAIpB,OAHAi7B,YXriBOr7B,OAAM,gBRWV,WAAmC,IACtC,IAAMs7B,EAAoB3hB,GAAY,qBADA,MAEnB2hB,EAAkBjwB,OAFC,eAEO,CAAxC,IAAM3H,EAAI,KACL6d,EAAW+Z,EAAkB19B,IAAI8F,GACnC6d,IACAA,EAASuD,WAAY,GAEzBwW,EAAkBthB,IAAItW,IOZ1B63B,ILoHMha,EAAW5H,KAAc/b,IAAI,yBAE/B2jB,EAASvd,gB9BvINhE,OAAM,uB+CmjBNm3B,GAAU/zB,IAAIhD,GZniBlB,ILqHGmhB","file":"zoid.frame.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"zoid\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"zoid\"] = factory();\n\telse\n\t\troot[\"zoid\"] = factory();\n})((typeof self !== 'undefined' ? self : this), function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","/* @flow */\n\nexport function isPromise(item : mixed) : boolean {\n try {\n if (!item) {\n return false;\n }\n\n if (typeof Promise !== 'undefined' && item instanceof Promise) {\n return true;\n }\n\n if (typeof window !== 'undefined' && typeof window.Window === 'function' && item instanceof window.Window) {\n return false;\n }\n\n if (typeof window !== 'undefined' && typeof window.constructor === 'function' && item instanceof window.constructor) {\n return false;\n }\n\n const toString = ({}).toString;\n\n if (toString) {\n const name = toString.call(item);\n\n if (name === '[object Window]' || name === '[object global]' || name === '[object DOMWindow]') {\n return false;\n }\n }\n\n if (typeof item.then === 'function') {\n return true;\n }\n } catch (err) {\n return false;\n }\n\n return false;\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nconst dispatchedErrors = [];\nconst possiblyUnhandledPromiseHandlers : Array<(mixed, promise? : ZalgoPromise) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer,\n undefined? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull,\n [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull,\n deserializeUndefined\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer,\n undefined? : PrimitiveDeserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull,\n [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SetLocationOptions = {|\n method? : $Values,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n const getName = () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n });\n\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n\n } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name, 'noopener');\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady : ZalgoPromise = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n // $FlowFixMe[method-unbinding]\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\ntype SendStrategies = {|\n [$Values] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore, getGlobalKey } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n const strDomain = domain.toString();\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n}\n\nexport function handleAck(source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n}\n\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[getGlobalKey()];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n if (isWindowClosed(source)) {\n return;\n }\n\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise = ZalgoPromise & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport { ProxyWindow } from '../serialize/window';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (winOrProxyWin, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n });\n};\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT : number = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n\nexport function basicSerialize(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType =\n UIDReferenceType |\n RawReferenceType;\n\nexport function getUIDRefStore(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef(val : T) : ReferenceType {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef(val : T) : ReferenceType {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue(win : CrossDomainWindowType, ref : ReferenceType) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef(win : CrossDomainWindowType, ref : ReferenceType) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType\n|};\n\ntype CrossDomainSerializeOptions = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType\n|};\n\nexport function crossDomainDeserialize({ data, sender, basic = false } : CrossDomainDeserializeOptions) : CrossDomainDeserializedMessage {\n const message : Message = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from 'cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: ('string' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from 'cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = windowName.split('__');\n\n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n\n if (!name) {\n throw new Error(`Expected component name`);\n }\n\n if (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload,\n reference : ReferenceType\n|};\n\nconst parseInitialParentPayload = memoize((windowName : string) : InitialParentPayload => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload() : InitialParentPayload {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType, props : PropsType

, origin : string, helpers : ChildHelpers, isUpdate : boolean = false) : ChildPropsType {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from 'cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise,\n getSiblings : getSiblingsPropType\n|};\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent = {|\n getProps : () => ChildPropsType,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent(options : NormalizedComponentOptionsType) : ChildComponent {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return getAutoResize().then(({ width, height, element }) => {\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from 'cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type exportPropType = (X) => ZalgoPromise;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\nexport type contextPropType = string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType

,\n export : exportPropType\n|};\n\nexport type PropsInputType

= {|\n parent? : ParentPropType,\n \n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : ?cspNoncePropType,\n context? : ?contextPropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

,\n\n ...P\n|};\n\nexport type PropsType

= {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n context? : ?contextPropType,\n dimensions : CssDimensionsType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise;\n\nexport type ChildPropsType = {|\n ...PropsType

,\n\n parent? : ParentPropType,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType

,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n // eslint-disable-next-line no-undef\n queryValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P, X> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType = {|\n [string] : MixedPropDefinitionType\n|};\n\nexport type BuiltInPropsDefinitionType = {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n uid : StringPropDefinitionType,\n tag : StringPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n export : FunctionPropDefinitionType, P, X>,\n getSiblings : FunctionPropDefinitionType,\n context : StringPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P, X>\n|};\n\nexport type PropsDefinitionType = {|\n ...BuiltInPropsDefinitionType,\n [ string ] : MixedPropDefinitionType\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = ({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps() : BuiltInPropsDefinitionType {\n return {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n context: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback =\n ((string, BooleanPropDefinitionType | void, boolean) => R) &\n ((string, StringPropDefinitionType | void, string) => R) &\n ((string, NumberPropDefinitionType | void, number) => R) &\n ((string, FunctionPropDefinitionType | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType | void, Object) => R);\n\nexport function eachProp(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) : $ReadOnlyArray {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps(propsDef : PropsDefinitionType, existingProps : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps(propsDef : PropsDefinitionType, props : (PropsType

), method : $Values) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType = {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n childDomainMatch : DomainMatcher,\n props : PropsType

,\n exports : ParentExportsType\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise;\n\ntype RenderContainerOptions = {|\n context : $Values,\n proxyFrame : ?ProxyObject,\n proxyPrerenderFrame : ?ProxyObject,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise;\ntype RejectInitPromise = (mixed) => ZalgoPromise;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, RenderContainerOptions) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values|}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState,\n resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values,\n rerender : Rerender\n|};\n\ntype ParentComponent = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise,\n getProps : () => PropsType

,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise,\n getExports : () => X\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions = {|\n uid : string,\n options : NormalizedComponentOptionsType,\n overrides? : ParentDelegateOverrides

,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions) : ParentComponent {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType

= overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return rejectInitPromise(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__${ ZOID }_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getCurrentWindowReferenceUID = () : string => {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childDomain : string, childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin.setName(windowName).then(() => {\n return proxyWin;\n });\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow, context : $Values) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n const exportsPromise : ZalgoPromise = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType

) : ZalgoPromise {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values|} = {}) : ZalgoPromise> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|} = {}) : ZalgoPromise => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|}) : ZalgoPromise => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values|}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, initialChildDomain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType

= getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = ({ target, container, context, rerender } : RenderOptions) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, initialChildDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\n };\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType

) : ?HTMLElement {\n const { width, height } = dimensions;\n\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition = ({|\n getExports : () => ZalgoPromise\n|}) => X;\n\nexport type ExportsDefinition = ExportsConfigDefinition | ExportsMapperDefinition;\n\nexport type ComponentOptionsType = {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values,\n\n props? : UserPropsDefinitionType,\n\n dimensions? : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType

|}) => Attributes,\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values,\n\n propsDef : PropsDefinitionType,\n dimensions : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition\n|};\n\nexport type ZoidComponentInstance = {|\n ...ParentHelpers

,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance,\n render : (container? : ContainerReferenceType, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent = {\n (props? : PropsInputType

| void) : ZoidComponentInstance,\n // eslint-disable-next-line no-undef\n driver : (string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n instances : $ReadOnlyArray>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = () : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions(options : ComponentOptionsType) : NormalizedComponentOptionsType {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop },\n exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component = {|\n init : (props? : PropsInputType

| void) => ZoidComponentInstance,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent\n|};\n\nexport function component(opts : ComponentOptionsType) : Component {\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible,\n children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent => {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : ContainerReferenceType) : ContainerReferenceType => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType

| void) : ZoidComponentInstance => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType

= parent.getProps();\n const parentExport : exportPropType = parent.export;\n\n const childParent : ParentPropType = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, vue3, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L) => D\n|};\n\nexport type ZoidProps

= PropsType

;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = (options : ComponentOptionsType) => ZoidComponent;\n\nexport const create : CreateZoidComponent = (options : ComponentOptionsType) : ZoidComponent => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType

| void) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n};\n\nexport function destroyComponents(err? : mixed) : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/zoid.frameworks.frame.js b/dist/zoid.frameworks.frame.js index 88a78941..84869dc6 100644 --- a/dist/zoid.frameworks.frame.js +++ b/dist/zoid.frameworks.frame.js @@ -423,6 +423,10 @@ function isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } + var WINDOW_TYPE = { + IFRAME: "iframe", + POPUP: "popup" + }; var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; function getActualProtocol(win) { void 0 === win && (win = window); @@ -646,6 +650,21 @@ } return !1; } + function getFrameByName(win, name) { + var winFrames = getFrames(win); + for (var _i9 = 0; _i9 < winFrames.length; _i9++) { + var childFrame = winFrames[_i9]; + try { + if (isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; + } catch (err) {} + } + try { + if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; + } catch (err) {} + try { + if (-1 !== winFrames.indexOf(win[name])) return win[name]; + } catch (err) {} + } function getAncestor(win) { void 0 === win && (win = window); return getOpener(win = win || window) || utils_getParent(win) || void 0; @@ -657,6 +676,27 @@ } return !1; } + function getDistanceFromTop(win) { + void 0 === win && (win = window); + var distance = 0; + var parent = win; + for (;parent; ) (parent = utils_getParent(parent)) && (distance += 1); + return distance; + } + function isSameTopWindow(win1, win2) { + var top1 = getTop(win1) || win1; + var top2 = getTop(win2) || win2; + try { + if (top1 && top2) return top1 === top2; + } catch (err) {} + var allFrames1 = getAllFramesInWindow(win1); + var allFrames2 = getAllFramesInWindow(win2); + if (anyMatch(allFrames1, allFrames2)) return !0; + var opener1 = getOpener(top1); + var opener2 = getOpener(top2); + return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), + !1; + } function matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; @@ -667,6 +707,29 @@ return matchDomain(subpattern, origin); }))); } + function getDomainFromUrl(url) { + return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : getDomain(); + } + function onCloseWindow(win, callback, delay, maxtime) { + void 0 === delay && (delay = 1e3); + void 0 === maxtime && (maxtime = 1 / 0); + var timeout; + !function check() { + if (isWindowClosed(win)) { + timeout && clearTimeout(timeout); + return callback(); + } + if (maxtime <= 0) clearTimeout(timeout); else { + maxtime -= delay; + timeout = setTimeout(check, delay); + } + }(); + return { + cancel: function() { + timeout && clearTimeout(timeout); + } + }; + } function isWindow(obj) { try { if (obj === window) return !0; @@ -1755,7 +1818,7 @@ })); var windowTypePromise = winPromise.then((function(window) { if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type"); - return getOpener(window) ? "popup" : "iframe"; + return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME; })); windowNamePromise.catch(src_util_noop); windowTypePromise.catch(src_util_noop); @@ -1873,7 +1936,7 @@ }; _proto.isPopup = function() { return this.getType().then((function(type) { - return "popup" === type; + return type === WINDOW_TYPE.POPUP; })); }; _proto.setLocation = function(href, opts) { @@ -2216,20 +2279,7 @@ return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent; }(window).match(/MSIE|rv:11|trident|edge\/12|edge\/13/i)) throw new Error("Global messaging not needed for browser"); if (!isSameDomain(win)) throw new Error("Post message through global disabled between different domain windows"); - if (!1 !== function(win1, win2) { - var top1 = getTop(win1) || win1; - var top2 = getTop(win2) || win2; - try { - if (top1 && top2) return top1 === top2; - } catch (err) {} - var allFrames1 = getAllFramesInWindow(win1); - var allFrames2 = getAllFramesInWindow(win2); - if (anyMatch(allFrames1, allFrames2)) return !0; - var opener1 = getOpener(top1); - var opener2 = getOpener(top2); - return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), - !1; - }(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames"); + if (!1 !== isSameTopWindow(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames"); var foreignGlobal = global_getGlobal(win); if (!foreignGlobal) throw new Error("Can not find postRobot global on foreign window"); foreignGlobal.receiveMessage({ @@ -2667,342 +2717,10 @@ send: send_send }); } - function src_util_isRegex(item) { - return "[object RegExp]" === {}.toString.call(item); - } - function utils_getActualProtocol(win) { - void 0 === win && (win = window); - return win.location.protocol; - } - function utils_getProtocol(win) { - void 0 === win && (win = window); - if (win.mockDomain) { - var protocol = win.mockDomain.split("//")[0]; - if (protocol) return protocol; - } - return utils_getActualProtocol(win); - } - function utils_isAboutProtocol(win) { - void 0 === win && (win = window); - return "about:" === utils_getProtocol(win); - } - function src_utils_getParent(win) { - void 0 === win && (win = window); - if (win) try { - if (win.parent && win.parent !== win) return win.parent; - } catch (err) {} - } - function utils_getOpener(win) { - void 0 === win && (win = window); - if (win && !src_utils_getParent(win)) try { - return win.opener; - } catch (err) {} - } - function utils_canReadFromWindow(win) { - try { - return !0; - } catch (err) {} - return !1; - } - function utils_getActualDomain(win) { - void 0 === win && (win = window); - var location = win.location; - if (!location) throw new Error("Can not read window location"); - var protocol = utils_getActualProtocol(win); - if (!protocol) throw new Error("Can not read window protocol"); - if ("file:" === protocol) return "file://"; - if ("about:" === protocol) { - var parent = src_utils_getParent(win); - return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://"; - } - var host = location.host; - if (!host) throw new Error("Can not read window host"); - return protocol + "//" + host; - } - function utils_getDomain(win) { - void 0 === win && (win = window); - var domain = utils_getActualDomain(win); - return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; - } - function utils_isSameDomain(win) { - if (!function(win) { - try { - if (win === window) return !0; - } catch (err) {} - try { - var desc = Object.getOwnPropertyDescriptor(win, "location"); - if (desc && !1 === desc.enumerable) return !1; - } catch (err) {} - try { - if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; - } catch (err) {} - try { - if (function(win) { - void 0 === win && (win = window); - return "mock:" === utils_getProtocol(win); - }(win) && utils_canReadFromWindow()) return !0; - } catch (err) {} - try { - if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0; - } catch (err) {} - return !1; - }(win)) return !1; - try { - if (win === window) return !0; - if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; - if (utils_getDomain(window) === utils_getDomain(win)) return !0; - } catch (err) {} - return !1; - } - function utils_assertSameDomain(win) { - if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain"); - return win; - } - function utils_isAncestorParent(parent, child) { - if (!parent || !child) return !1; - var childParent = src_utils_getParent(child); - return childParent ? childParent === parent : -1 !== function(win) { - var result = []; - try { - for (;win.parent !== win; ) { - result.push(win.parent); - win = win.parent; - } - } catch (err) {} - return result; - }(child).indexOf(parent); - } - function utils_getFrames(win) { - var result = []; - var frames; - try { - frames = win.frames; - } catch (err) { - frames = win; - } - var len; - try { - len = frames.length; - } catch (err) {} - if (0 === len) return result; - if (len) { - for (var i = 0; i < len; i++) { - var frame = void 0; - try { - frame = frames[i]; - } catch (err) { - continue; - } - result.push(frame); - } - return result; - } - for (var _i = 0; _i < 100; _i++) { - var _frame = void 0; - try { - _frame = frames[_i]; - } catch (err) { - return result; - } - if (!_frame) return result; - result.push(_frame); - } - return result; - } - function utils_getAllChildFrames(win) { - var result = []; - for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) { - var frame = _getFrames2[_i3]; - result.push(frame); - for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); - } - return result; - } - function utils_getTop(win) { - void 0 === win && (win = window); - try { - if (win.top) return win.top; - } catch (err) {} - if (src_utils_getParent(win) === win) return win; - try { - if (utils_isAncestorParent(window, win) && window.top) return window.top; - } catch (err) {} - try { - if (utils_isAncestorParent(win, window) && window.top) return window.top; - } catch (err) {} - for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { - var frame = _getAllChildFrames4[_i7]; - try { - if (frame.top) return frame.top; - } catch (err) {} - if (src_utils_getParent(frame) === frame) return frame; - } - } - function utils_getAllFramesInWindow(win) { - var top = utils_getTop(win); - if (!top) throw new Error("Can not determine top window"); - var result = [].concat(utils_getAllChildFrames(top), [ top ]); - -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win))); - return result; - } - var utils_iframeWindows = []; - var utils_iframeFrames = []; - function utils_isWindowClosed(win, allowMock) { - void 0 === allowMock && (allowMock = !0); - try { - if (win === window) return !1; - } catch (err) { - return !0; - } - try { - if (!win) return !0; - } catch (err) { - return !0; - } - try { - if (win.closed) return !0; - } catch (err) { - return !err || "Call was rejected by callee.\r\n" !== err.message; - } - if (allowMock && utils_isSameDomain(win)) try { - if (win.mockclosed) return !0; - } catch (err) {} - try { - if (!win.parent || !win.top) return !0; - } catch (err) {} - var iframeIndex = function(collection, item) { - for (var i = 0; i < collection.length; i++) try { - if (collection[i] === item) return i; - } catch (err) {} - return -1; - }(utils_iframeWindows, win); - if (-1 !== iframeIndex) { - var frame = utils_iframeFrames[iframeIndex]; - if (frame && function(frame) { - if (!frame.contentWindow) return !0; - if (!frame.parentNode) return !0; - var doc = frame.ownerDocument; - if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { - var parent = frame; - for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; - if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; - } - return !1; - }(frame)) return !0; - } - return !1; - } - function utils_getFrameByName(win, name) { - var winFrames = utils_getFrames(win); - for (var _i9 = 0; _i9 < winFrames.length; _i9++) { - var childFrame = winFrames[_i9]; - try { - if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; - } catch (err) {} - } - try { - if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; - } catch (err) {} - try { - if (-1 !== winFrames.indexOf(win[name])) return win[name]; - } catch (err) {} - } - function utils_getAncestor(win) { - void 0 === win && (win = window); - return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0; - } - function utils_anyMatch(collection1, collection2) { - for (var _i17 = 0; _i17 < collection1.length; _i17++) { - var item1 = collection1[_i17]; - for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; - } - return !1; - } - function utils_getDistanceFromTop(win) { - void 0 === win && (win = window); - var distance = 0; - var parent = win; - for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1); - return distance; - } - function utils_matchDomain(pattern, origin) { - if ("string" == typeof pattern) { - if ("string" == typeof origin) return "*" === pattern || origin === pattern; - if (src_util_isRegex(origin)) return !1; - if (Array.isArray(origin)) return !1; - } - return src_util_isRegex(pattern) ? src_util_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) : !src_util_isRegex(origin) && pattern.some((function(subpattern) { - return utils_matchDomain(subpattern, origin); - }))); - } - function utils_getDomainFromUrl(url) { - return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain(); - } - function utils_onCloseWindow(win, callback, delay, maxtime) { - void 0 === delay && (delay = 1e3); - void 0 === maxtime && (maxtime = 1 / 0); - var timeout; - !function check() { - if (utils_isWindowClosed(win)) { - timeout && clearTimeout(timeout); - return callback(); - } - if (maxtime <= 0) clearTimeout(timeout); else { - maxtime -= delay; - timeout = setTimeout(check, delay); - } - }(); - return { - cancel: function() { - timeout && clearTimeout(timeout); - } - }; - } - function utils_isWindow(obj) { - try { - if (obj === window) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if ("[object Window]" === {}.toString.call(obj)) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (window.Window && obj instanceof window.Window) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.self === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.parent === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.top === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; - } catch (err) { - return !0; - } - try { - if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; - } catch (err) {} - return !1; - } function lib_global_getGlobal(win) { - if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain"); - win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {}); - return win.__zoid_9_0_87__; + if (!isSameDomain(win)) throw new Error("Can not get global for window on different domain"); + win.__zoid_9_0_88__ || (win.__zoid_9_0_88__ = {}); + return win.__zoid_9_0_88__; } function tryGlobal(win, handler) { try { @@ -3113,10 +2831,7 @@ DOTIFY: "dotify", BASE64: "base64" }; - var CONTEXT = { - IFRAME: "iframe", - POPUP: "popup" - }; + var CONTEXT = WINDOW_TYPE; var EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", @@ -3148,7 +2863,7 @@ sender: { win: function(_ref2) { return function(windowRef) { - if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window)); + if ("opener" === windowRef.type) return assertExists("opener", getOpener(window)); if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) { void 0 === n && (n = 1); return function(win, n) { @@ -3156,19 +2871,19 @@ var parent = win; for (var i = 0; i < n; i++) { if (!parent) return; - parent = src_utils_getParent(parent); + parent = utils_getParent(parent); } return parent; - }(win, utils_getDistanceFromTop(win) - n); + }(win, getDistanceFromTop(win) - n); }(window, windowRef.distance)); if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) { var _ret = function() { var uid = windowRef.uid; - var ancestor = utils_getAncestor(window); + var ancestor = getAncestor(window); if (!ancestor) throw new Error("Can not find ancestor window"); - for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { + for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { var frame = _getAllFramesInWindow2[_i2]; - if (utils_isSameDomain(frame)) { + if (isSameDomain(frame)) { var win = tryGlobal(frame, (function(global) { return global.windows && global.windows[uid]; })); @@ -3182,15 +2897,15 @@ } else if ("name" === windowRef.type) { var name = windowRef.name; return assertExists("namedWindow", function(win, name) { - return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) { - var frame = utils_getFrameByName(win, name); + return getFrameByName(win, name) || function findChildFrameByName(win, name) { + var frame = getFrameByName(win, name); if (frame) return frame; - for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) { - var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name); + for (var _i11 = 0, _getFrames4 = getFrames(win); _i11 < _getFrames4.length; _i11++) { + var namedFrame = findChildFrameByName(_getFrames4[_i11], name); if (namedFrame) return namedFrame; } - }(utils_getTop(win) || win, name); - }(assertExists("ancestor", utils_getAncestor(window)), name)); + }(getTop(win) || win, name); + }(assertExists("ancestor", getAncestor(window)), name)); } throw new Error("Unable to find " + windowRef.type + " parent component window"); }(_ref2.metaData.windowRef); @@ -3208,15 +2923,15 @@ } function window_getWindowRef(targetWindow, currentWindow) { void 0 === currentWindow && (currentWindow = window); - if (targetWindow === src_utils_getParent(currentWindow)) return { + if (targetWindow === utils_getParent(currentWindow)) return { type: "parent", - distance: utils_getDistanceFromTop(targetWindow) + distance: getDistanceFromTop(targetWindow) }; - if (targetWindow === utils_getOpener(currentWindow)) return { + if (targetWindow === getOpener(currentWindow)) return { type: "opener" }; - if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) { - var windowName = utils_assertSameDomain(targetWindow).name; + if (isSameDomain(targetWindow) && !(win = targetWindow, win === getTop(win))) { + var windowName = assertSameDomain(targetWindow).name; if (windowName) return { type: "name", name: windowName @@ -3419,7 +3134,7 @@ for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; - prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]); + prop && !1 === prop.sendToChild || prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window)) || (result[key] = props[key]); } return promise_ZalgoPromise.hash(result); }; @@ -3480,7 +3195,7 @@ }) : attributes; }; var getInitialChildDomain = function() { - return utils_getDomainFromUrl(getUrl()); + return getDomainFromUrl(getUrl()); }; var openFrame = function(context, _ref2) { var windowName = _ref2.windowName; @@ -3514,7 +3229,7 @@ return destroyElement(prerenderFrame); })); return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) { - return utils_assertSameDomain(prerenderFrameWindow); + return assertSameDomain(prerenderFrameWindow); })).then((function(win) { return setup_toProxyWindow(win); })); @@ -3538,7 +3253,7 @@ return uid; }; var getWindowRef = function(target, initialChildDomain, context, proxyWin) { - if (initialChildDomain === utils_getDomain(window)) return { + if (initialChildDomain === getDomain(window)) return { type: "global", uid: getCurrentWindowReferenceUID() }; @@ -3546,14 +3261,14 @@ if (props.window) { var actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop"); - if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); + if (getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); } if (context === CONTEXT.POPUP) return { type: "opener" }; if (context === CONTEXT.IFRAME) return { type: "parent", - distance: utils_getDistanceFromTop(window) + distance: getDistanceFromTop(window) }; throw new Error("Can not construct window reference for child"); }; @@ -3588,7 +3303,7 @@ var close = memoize((function(err) { return promise_ZalgoPromise.try((function() { if (closeOverride) { - if (utils_isWindowClosed(closeOverride.__source__)) return; + if (isWindowClosed(closeOverride.__source__)) return; return closeOverride(); } return promise_ZalgoPromise.try((function() { @@ -3636,7 +3351,7 @@ var unloadWindowListener = addEventListener(window, "unload", once((function() { destroy(new Error("Window navigated away")); }))); - var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3); + var closeParentWindowListener = onCloseWindow(parentWin, destroy, 3e3); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) return watchForUnloadOverride(); @@ -3703,14 +3418,14 @@ }) : promise_ZalgoPromise.try((function() { if (prerenderTemplate) { var prerenderWindow = proxyPrerenderWin.getWindow(); - if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) { + if (prerenderWindow && isSameDomain(prerenderWindow) && function(win) { try { if (!win.location.href) return !0; if ("about:blank" === win.location.href) return !0; } catch (err) {} return !1; }(prerenderWindow)) { - var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document; + var doc = (prerenderWindow = assertSameDomain(prerenderWindow)).document; var el = renderTemplate(prerenderTemplate, { context: context, doc: doc @@ -3994,22 +3709,9 @@ var childDomainMatch = domainMatch || getInitialChildDomain(); !function(target, childDomainMatch, container) { if (target !== window) { - if (!function(win1, win2) { - var top1 = utils_getTop(win1) || win1; - var top2 = utils_getTop(win2) || win2; - try { - if (top1 && top2) return top1 === top2; - } catch (err) {} - var allFrames1 = utils_getAllFramesInWindow(win1); - var allFrames2 = utils_getAllFramesInWindow(win2); - if (utils_anyMatch(allFrames1, allFrames2)) return !0; - var opener1 = utils_getOpener(top1); - var opener2 = utils_getOpener(top2); - return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1), - !1; - }(window, target)) throw new Error("Can only renderTo an adjacent frame"); - var origin = utils_getDomain(); - if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); + if (!isSameTopWindow(window, target)) throw new Error("Can only renderTo an adjacent frame"); + var origin = getDomain(); + if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }"); } }(target, childDomainMatch, container); @@ -4036,7 +3738,7 @@ }).then((function(_ref13) { var parentComp = _ref13.data.parent; clean.register((function(err) { - if (!utils_isWindowClosed(target)) return parentComp.destroy(err); + if (!isWindowClosed(target)) return parentComp.destroy(err); })); return parentComp.getDelegateOverrides(); })).catch((function(err) { @@ -4139,7 +3841,7 @@ hashString && (originalUrl = originalUrl + "#" + hashString); return originalUrl; }(function(url) { - if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; + if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; var domain; throw new Error("Mock urls not supported out of test mode"); }(getUrl()), { @@ -4158,7 +3860,7 @@ context: context, tag: tag, childDomainMatch: childDomainMatch, - version: "9_0_87", + version: "9_0_88", props: childProps, exports: (win = proxyWin, { init: function(childExports) { @@ -4189,13 +3891,13 @@ windowRef: getWindowRef(target, initialChildDomain, context, proxyWin) }, sender: { - domain: utils_getDomain(window) + domain: getDomain(window) }, receiver: { win: proxyWin, domain: childDomainMatch }, - passByReference: initialChildDomain === utils_getDomain() + passByReference: initialChildDomain === getDomain() }), serializedData = _crossDomainSerialize.serializedData; clean.register(_crossDomainSerialize.cleanReference); return serializedData; @@ -4404,7 +4106,7 @@ _proto.componentDidMount = function() { var el = ReactDOM.findDOMNode(this); var parent = init(extend({}, this.props)); - parent.render(el, CONTEXT.IFRAME); + parent.render(el, this.props.context); this.setState({ parent: parent }); @@ -4434,7 +4136,7 @@ return acc; }), {})))); var props; - this.parent.render(el, CONTEXT.IFRAME); + this.parent.render(el, this.$attrs.context); }, watch: { $attrs: { @@ -4463,7 +4165,7 @@ return acc; }), {})))); var props; - this.parent.render(el, CONTEXT.IFRAME); + this.parent.render(el, this.$attrs.context); }, watch: { $attrs: { @@ -4500,8 +4202,9 @@ } : item; })); }; - var instance = init(getProps()); - instance.render($element[0], CONTEXT.IFRAME); + var props = getProps(); + var instance = init(props); + instance.render($element[0], props.context); $scope.$watch((function() { instance.updateProps(getProps()).catch(src_util_noop); })); @@ -4543,8 +4246,9 @@ }; _proto.ngOnInit = function() { var targetElement = this.elementRef.nativeElement; - this.parent = init(this.getProps()); - this.parent.render(targetElement, CONTEXT.IFRAME); + var props = this.getProps(); + this.parent = init(props); + this.parent.render(targetElement, props.context); }; _proto.ngDoCheck = function() { if (this.parent && !function(obj1, obj2) { @@ -4646,10 +4350,10 @@ allowDelegate: !0, validate: function(_ref2) { var value = _ref2.value; - if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); - if (utils_isWindow(value)) { - if (utils_isWindowClosed(value)) throw new Error("Window is closed"); - if (!utils_isSameDomain(value)) throw new Error("Window is not same domain"); + if (!isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); + if (isWindow(value)) { + if (isWindowClosed(value)) throw new Error("Window is closed"); + if (!isSameDomain(value)) throw new Error("Window is not same domain"); } }, decorate: function(_ref3) { @@ -4665,6 +4369,10 @@ type: PROP_TYPE.STRING, required: !1 }, + context: { + type: PROP_TYPE.STRING, + required: !1 + }, onDisplay: { type: PROP_TYPE.FUNCTION, required: !1, @@ -4875,7 +4583,7 @@ return !1; }(name)) { var _payload = getInitialParentPayload().payload; - if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0; + if (_payload.tag === tag && matchDomain(_payload.childDomainMatch, getDomain())) return !0; } return !1; }; @@ -4893,7 +4601,7 @@ var props; var exportsPromise = new promise_ZalgoPromise; var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props; - if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87"); + if ("9_0_88" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_88"); var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init; var getParent = function() { return parentComponentWindow; @@ -4925,10 +4633,10 @@ var currentParent = props.parent; void 0 === anyParent && (anyParent = !currentParent); if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child"); - for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { + for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { var win = _getAllFramesInWindow2[_i2]; - if (utils_isSameDomain(win)) { - var xprops = utils_assertSameDomain(win).xprops; + if (isSameDomain(win)) { + var xprops = assertSameDomain(win).xprops; if (xprops && getParent() === xprops.getParent()) { var winParent = xprops.parent; if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) { @@ -4953,7 +4661,7 @@ for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; - if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) { + if (!prop || !prop.sameDomain || origin === getDomain(window) && isSameDomain(parentComponentWindow)) { var value = normalizeChildProp(propsDef, 0, key, props[key], helpers); result[key] = value; prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value); @@ -4990,7 +4698,7 @@ return { init: function() { return promise_ZalgoPromise.try((function() { - utils_isSameDomain(parentComponentWindow) && function(_ref3) { + isSameDomain(parentComponentWindow) && function(_ref3) { var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow; var _crossDomainDeseriali2 = crossDomainDeserialize({ data: parseWindowName(window.name).serializedInitialPayload, @@ -5010,7 +4718,7 @@ }, receiver: { win: window, - domain: utils_getDomain() + domain: getDomain() }, basic: !0 }); @@ -5029,7 +4737,7 @@ } }); !function(allowedParentDomains, domain) { - if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); + if (!matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); }(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); !function() { @@ -5039,7 +4747,7 @@ window.addEventListener("unload", (function() { checkClose.fireAndForget(); })); - utils_onCloseWindow(parentComponentWindow, (function() { + onCloseWindow(parentComponentWindow, (function() { child_destroy(); })); }(); @@ -5117,7 +4825,7 @@ throw err; })); } - if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo"); + if (!isWindow(target)) throw new Error("Must pass window to renderTo"); return function(props, context) { return promise_ZalgoPromise.try((function() { if (props.window) return setup_toProxyWindow(props.window).getType(); @@ -5335,7 +5043,7 @@ var destroyAll = destroyComponents; function component_destroy(err) { destroyAll(); - delete window.__zoid_9_0_87__; + delete window.__zoid_9_0_88__; !function() { !function() { var responseListeners = globalStore("responseListeners"); diff --git a/dist/zoid.frameworks.frame.min.js b/dist/zoid.frameworks.frame.min.js index 74cc1aa1..e8ac17f2 100644 --- a/dist/zoid.frameworks.frame.min.js +++ b/dist/zoid.frameworks.frame.min.js @@ -1,2 +1,2 @@ -!function(n,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("zoid",[],e):"object"==typeof exports?exports.zoid=e():n.zoid=e()}("undefined"!=typeof self?self:this,(function(){return function(n){var e={};function r(t){if(e[t])return e[t].exports;var o=e[t]={i:t,l:!1,exports:{}};return n[t].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=n,r.c=e,r.d=function(n,e,t){r.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:t})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,e){if(1&e&&(n=r(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var t=Object.create(null);if(r.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)r.d(t,o,function(e){return n[e]}.bind(null,o));return t},r.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(e,"a",e),e},r.o=function(n,e){return{}.hasOwnProperty.call(n,e)},r.p="",r(r.s=0)}([function(n,e,r){"use strict";function t(n,e){return(t=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function o(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,t(n,e)}function i(){return(i=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+cn(n,e+1)}}function fn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function sn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function dn(n){return n}function ln(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function hn(n){return n.replace(/-([a-z])/g,(function(n){return n[1].toUpperCase()}))}function pn(n,e,r){if(Array.isArray(n)){if("number"!=typeof e)throw new TypeError("Array key must be number")}else if("object"==typeof n&&null!==n&&"string"!=typeof e)throw new TypeError("Object key must be string");Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get:function(){delete n[e];var t=r();return n[e]=t,t},set:function(r){delete n[e],n[e]=r}})}function wn(n){return[].slice.call(n)}function vn(n){return"object"==typeof(e=n)&&null!==e&&"[object Object]"==={}.toString.call(n);var e}function mn(n){if(!vn(n))return!1;var e=n.constructor;if("function"!=typeof e)return!1;var r=e.prototype;return!!vn(r)&&!!r.hasOwnProperty("isPrototypeOf")}function yn(n,e,r){if(void 0===r&&(r=""),Array.isArray(n)){for(var t=n.length,o=[],i=function(t){pn(o,t,(function(){var o=r?r+"."+t:""+t,i=e(n[t],t,o);return(mn(i)||Array.isArray(i))&&(i=yn(i,e,o)),i}))},a=0;a { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||K();n=ge.unwrap(n);var f=r.__name__||r.name||t;return"string"==typeof f&&"function"==typeof f.indexOf&&0===f.indexOf("anonymous::")&&(f=f.replace("anonymous::",t+"::")),ge.isProxyWindow(n)?(be(c,r,f,n,e),n.awaitWindow().then((function(n){be(c,r,f,n,e)}))):be(c,r,f,n,e),de("cross_domain_function",{id:c,name:f})}function xe(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=pe);var r=JSON.stringify(n,(function(n){var r=this[n];if(fe(this))return r;var t=se(r);if(!t)return r;var o=e[t]||he[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return de("cross_domain_zalgo_promise",{then:_e(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return _e(n,e,r,t,{on:i,send:a})},o.object=function(n){return F(n)||ge.isProxyWindow(n)?de("cross_domain_window",ge.serialize(n,{send:a})):n},o))}function Pe(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=ve),"undefined"!==n)return JSON.parse(n,(function(n,r){if(fe(this))return r;var t,o;if(fe(r)?(t=r.__type__,o=r.__val__):(t=se(r),o=r),!t)return o;var i=e[t]||we[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new p(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return ge.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=Ee(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:P()},u);var f=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:f},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return ge.deserialize(n,{send:i})},o))}var Oe={};function Ce(n,e,r,t){var o=t.on,i=t.send;return p.try((function(){var t=te().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||p.flush().then((function(){if(T(n))throw new Error("Window is closed");var r,a=xe(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(Oe),c=[],f=0;f1?e-1:0),o=1;o1?r-1:0),i=1;i",inheritAttrs:!1,mounted:function(){var n,e=this.$el;this.parent=r(i({},(n=this.$attrs,Object.keys(n).reduce((function(e,r){var t=n[r];return"style-object"===r||"styleObject"===r?(e.style=t,e.styleObject=t):r.includes("-")?e[hn(r)]=t:e[r]=t,e}),{})))),this.parent.render(e,br.IFRAME)},watch:{$attrs:{handler:function(){this.parent&&this.$attrs&&this.parent.updateProps(i({},this.$attrs)).catch(an)},deep:!0}}}}},Fr={register:function(n,e,r,t){return t.module(n,[]).directive(hn(n),(function(){for(var n={},t=0,o=Object.keys(e);t",inputs:["props"]})];var d=function(){};return d.annotations=void 0,d.annotations=[new a({declarations:[s],exports:[s]})],d}};function Ur(n){var e=n.uid,r=n.frame,t=n.prerenderFrame,o=n.doc,i=n.props,a=n.event,u=n.dimensions,c=u.width,f=u.height;if(r&&t){var s=o.createElement("div");s.setAttribute("id",e);var d=o.createElement("style");return i.cspNonce&&d.setAttribute("nonce",i.cspNonce),d.appendChild(o.createTextNode("\n #"+e+" {\n display: inline-block;\n position: relative;\n width: "+c+";\n height: "+f+";\n }\n\n #"+e+" > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),s.appendChild(r),s.appendChild(t),s.appendChild(d),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(Er.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){qn(t)}),1)})),a.on(Er.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(s.style.width=Vn(e)),"number"==typeof r&&(s.style.height=Vn(r))})),s}}function Lr(n){var e=n.doc,r=n.props,t=e.createElement("html"),o=e.createElement("body"),i=e.createElement("style"),a=e.createElement("div");return a.classList.add("spinner"),r.cspNonce&&i.setAttribute("nonce",r.cspNonce),t.appendChild(o),o.appendChild(a),o.appendChild(i),i.appendChild(e.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")),t}var qr=_n(),Br=_n();function $r(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,f=void 0===c?{}:c,s=n.autoResize,d=void 0===s?{}:s,l=n.allowedParentDomains,h=void 0===l?"*":l,p=n.attributes,w=void 0===p?{}:p,v=n.defaultContext,m=void 0===v?br.IFRAME:v,y=n.containerTemplate,g=void 0===y?Ur:y,b=n.prerenderTemplate,E=void 0===b?Lr:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,C=void 0===O?{info:an}:O,D=n.exports,W=void 0===D?an:D,S=n.method,j=n.children,N=void 0===j?function(){return{}}:j,A=e.replace(/-/g,"_"),R=i({},{window:{type:yr.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!sr(e)&&!ge.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(sr(e)){if(rr(e))throw new Error("Window is closed");if(!Ye(e))throw new Error("Window is not same domain")}},decorate:function(n){return ze(n.value)}},timeout:{type:yr.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:yr.STRING,required:!1},onDisplay:{type:yr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr,decorate:Nr},onRendered:{type:yr.FUNCTION,required:!1,sendToChild:!1,default:jr,decorate:Nr},onRender:{type:yr.FUNCTION,required:!1,sendToChild:!1,default:jr,decorate:Nr},onClose:{type:yr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr,decorate:Nr},onDestroy:{type:yr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr,decorate:Nr},onResize:{type:yr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr},onFocus:{type:yr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr},close:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:yr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:yr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:yr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:A,tag:e,url:r,domain:t,bridgeUrl:o,method:S,propsDef:R,dimensions:f,autoResize:d,allowedParentDomains:h,attributes:w,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:C,eligible:P,children:N,exports:"function"==typeof W?W:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=W[o].type,a=e().then((function(n){return n[o]}));r[o]=i===yr.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+pn(n,e+1)}}function wn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function vn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function mn(n){return n}function yn(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function gn(n){return n.replace(/-([a-z])/g,(function(n){return n[1].toUpperCase()}))}function bn(n,e,r){if(Array.isArray(n)){if("number"!=typeof e)throw new TypeError("Array key must be number")}else if("object"==typeof n&&null!==n&&"string"!=typeof e)throw new TypeError("Object key must be string");Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get:function(){delete n[e];var t=r();return n[e]=t,t},set:function(r){delete n[e],n[e]=r}})}function En(n){return[].slice.call(n)}function _n(n){return"object"==typeof(e=n)&&null!==e&&"[object Object]"==={}.toString.call(n);var e}function xn(n){if(!_n(n))return!1;var e=n.constructor;if("function"!=typeof e)return!1;var r=e.prototype;return!!_n(r)&&!!r.hasOwnProperty("isPrototypeOf")}function Pn(n,e,r){if(void 0===r&&(r=""),Array.isArray(n)){for(var t=n.length,o=[],i=function(t){bn(o,t,(function(){var o=r?r+"."+t:""+t,i=e(n[t],t,o);return(xn(i)||Array.isArray(i))&&(i=Pn(i,e,o)),i}))},a=0;a { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||on();n=Oe.unwrap(n);var s=r.__name__||r.name||t;return"string"==typeof s&&"function"==typeof s.indexOf&&0===s.indexOf("anonymous::")&&(s=s.replace("anonymous::",t+"::")),Oe.isProxyWindow(n)?(Ce(c,r,s,n,e),n.awaitWindow().then((function(n){Ce(c,r,s,n,e)}))):Ce(c,r,s,n,e),me("cross_domain_function",{id:c,name:s})}function Se(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=be);var r=JSON.stringify(n,(function(n){var r=this[n];if(we(this))return r;var t=ve(r);if(!t)return r;var o=e[t]||ge[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return me("cross_domain_zalgo_promise",{then:We(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return We(n,e,r,t,{on:i,send:a})},o.object=function(n){return B(n)||Oe.isProxyWindow(n)?me("cross_domain_window",Oe.serialize(n,{send:a})):n},o))}function Ne(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=_e),"undefined"!==n)return JSON.parse(n,(function(n,r){if(we(this))return r;var t,o;if(we(r)?(t=r.__type__,o=r.__val__):(t=ve(r),o=r),!t)return o;var i=e[t]||Ee[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new p(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return Oe.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=De(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:O()},u);var s=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:s},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:s},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return Oe.deserialize(n,{send:i})},o))}var je={};function Re(n,e,r,t){var o=t.on,i=t.send;return p.try((function(){var t=se().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||p.flush().then((function(){if(z(n))throw new Error("Window is closed");var r,a=Se(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(je),c=[],s=0;s1?e-1:0),o=1;o1?r-1:0),i=1;i",inheritAttrs:!1,mounted:function(){var n,e=this.$el;this.parent=r(i({},(n=this.$attrs,Object.keys(n).reduce((function(e,r){var t=n[r];return"style-object"===r||"styleObject"===r?(e.style=t,e.styleObject=t):r.includes("-")?e[gn(r)]=t:e[r]=t,e}),{})))),this.parent.render(e,this.$attrs.context)},watch:{$attrs:{handler:function(){this.parent&&this.$attrs&&this.parent.updateProps(i({},this.$attrs)).catch(ln)},deep:!0}}}}},mr={register:function(n,e,r,t){return t.module(n,[]).directive(gn(n),(function(){for(var n={},t=0,o=Object.keys(e);t",inputs:["props"]})];var d=function(){};return d.annotations=void 0,d.annotations=[new a({declarations:[f],exports:[f]})],d}};function gr(n){var e=n.uid,r=n.frame,t=n.prerenderFrame,o=n.doc,i=n.props,a=n.event,u=n.dimensions,c=u.width,s=u.height;if(r&&t){var f=o.createElement("div");f.setAttribute("id",e);var d=o.createElement("style");return i.cspNonce&&d.setAttribute("nonce",i.cspNonce),d.appendChild(o.createTextNode("\n #"+e+" {\n display: inline-block;\n position: relative;\n width: "+c+";\n height: "+s+";\n }\n\n #"+e+" > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),f.appendChild(r),f.appendChild(t),f.appendChild(d),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(nr.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){Zn(t)}),1)})),a.on(nr.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(f.style.width=re(e)),"number"==typeof r&&(f.style.height=re(r))})),f}}function br(n){var e=n.doc,r=n.props,t=e.createElement("html"),o=e.createElement("body"),i=e.createElement("style"),a=e.createElement("div");return a.classList.add("spinner"),r.cspNonce&&i.setAttribute("nonce",r.cspNonce),t.appendChild(o),o.appendChild(a),o.appendChild(i),i.appendChild(e.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")),t}var Er=Wn(),_r=Wn();function xr(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,s=void 0===c?{}:c,f=n.autoResize,d=void 0===f?{}:f,l=n.allowedParentDomains,h=void 0===l?"*":l,p=n.attributes,w=void 0===p?{}:p,v=n.defaultContext,m=void 0===v?Qe.IFRAME:v,y=n.containerTemplate,g=void 0===y?gr:y,b=n.prerenderTemplate,E=void 0===b?br:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,D=void 0===O?{info:ln}:O,W=n.exports,S=void 0===W?ln:W,N=n.method,j=n.children,R=void 0===j?function(){return{}}:j,A=e.replace(/-/g,"_"),T=i({},{window:{type:Xe.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!B(e)&&!Oe.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(B(e)){if(z(e))throw new Error("Window is closed");if(!C(e))throw new Error("Window is not same domain")}},decorate:function(n){return $e(n.value)}},timeout:{type:Xe.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:Xe.STRING,required:!1},context:{type:Xe.STRING,required:!1},onDisplay:{type:Xe.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:sr,decorate:fr},onRendered:{type:Xe.FUNCTION,required:!1,sendToChild:!1,default:sr,decorate:fr},onRender:{type:Xe.FUNCTION,required:!1,sendToChild:!1,default:sr,decorate:fr},onClose:{type:Xe.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:sr,decorate:fr},onDestroy:{type:Xe.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:sr,decorate:fr},onResize:{type:Xe.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:sr},onFocus:{type:Xe.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:sr},close:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:Xe.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:Xe.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:Xe.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:A,tag:e,url:r,domain:t,bridgeUrl:o,method:N,propsDef:T,dimensions:s,autoResize:d,allowedParentDomains:h,attributes:w,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:D,eligible:P,children:R,exports:"function"==typeof S?S:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=S[o].type,a=e().then((function(n){return n[o]}));r[o]=i===Xe.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer,\n undefined? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull,\n [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull,\n deserializeUndefined\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer,\n undefined? : PrimitiveDeserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull,\n [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SetLocationOptions = {|\n method? : $Values,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n const getName = () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n });\n\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n\n } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name, 'noopener');\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady : ZalgoPromise = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n // $FlowFixMe[method-unbinding]\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\ntype SendStrategies = {|\n [$Values] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore, getGlobalKey } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n const strDomain = domain.toString();\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n}\n\nexport function handleAck(source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n}\n\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[getGlobalKey()];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n if (isWindowClosed(source)) {\n return;\n }\n\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise = ZalgoPromise & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport { ProxyWindow } from '../serialize/window';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (winOrProxyWin, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n });\n};\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT : number = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from '@krakenjs/cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n\nexport function basicSerialize(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType =\n UIDReferenceType |\n RawReferenceType;\n\nexport function getUIDRefStore(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef(val : T) : ReferenceType {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef(val : T) : ReferenceType {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue(win : CrossDomainWindowType, ref : ReferenceType) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef(win : CrossDomainWindowType, ref : ReferenceType) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType\n|};\n\ntype CrossDomainSerializeOptions = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType\n|};\n\nexport function crossDomainDeserialize({ data, sender, basic = false } : CrossDomainDeserializeOptions) : CrossDomainDeserializedMessage {\n const message : Message = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from '@krakenjs/cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: ('string' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from '@krakenjs/cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = windowName.split('__');\n\n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n\n if (!name) {\n throw new Error(`Expected component name`);\n }\n\n if (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload,\n reference : ReferenceType\n|};\n\nconst parseInitialParentPayload = memoize((windowName : string) : InitialParentPayload => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload() : InitialParentPayload {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType, props : PropsType

, origin : string, helpers : ChildHelpers, isUpdate : boolean = false) : ChildPropsType {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise,\n getSiblings : getSiblingsPropType\n|};\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent = {|\n getProps : () => ChildPropsType,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent(options : NormalizedComponentOptionsType) : ChildComponent {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return getAutoResize().then(({ width, height, element }) => {\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type exportPropType = (X) => ZalgoPromise;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType

,\n export : exportPropType\n|};\n\nexport type PropsInputType

= {|\n parent? : ParentPropType,\n \n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : ?cspNoncePropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

,\n\n ...P\n|};\n\nexport type PropsType

= {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n dimensions : CssDimensionsType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise;\n\nexport type ChildPropsType = {|\n ...PropsType

,\n\n parent? : ParentPropType,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType

,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n // eslint-disable-next-line no-undef\n queryValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P, X> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType = {|\n [string] : MixedPropDefinitionType\n|};\n\nexport type BuiltInPropsDefinitionType = {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n uid : StringPropDefinitionType,\n tag : StringPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n export : FunctionPropDefinitionType, P, X>,\n getSiblings : FunctionPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P, X>\n|};\n\nexport type PropsDefinitionType = {|\n ...BuiltInPropsDefinitionType,\n [ string ] : MixedPropDefinitionType\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = ({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps() : BuiltInPropsDefinitionType {\n return {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback =\n ((string, BooleanPropDefinitionType | void, boolean) => R) &\n ((string, StringPropDefinitionType | void, string) => R) &\n ((string, NumberPropDefinitionType | void, number) => R) &\n ((string, FunctionPropDefinitionType | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType | void, Object) => R);\n\nexport function eachProp(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) : $ReadOnlyArray {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps(propsDef : PropsDefinitionType, existingProps : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps(propsDef : PropsDefinitionType, props : (PropsType

), method : $Values) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType = {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n childDomainMatch : DomainMatcher,\n props : PropsType

,\n exports : ParentExportsType\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise;\n\ntype RenderContainerOptions = {|\n context : $Values,\n proxyFrame : ?ProxyObject,\n proxyPrerenderFrame : ?ProxyObject,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise;\ntype RejectInitPromise = (mixed) => ZalgoPromise;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, RenderContainerOptions) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values|}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState,\n resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values,\n rerender : Rerender\n|};\n\ntype ParentComponent = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise,\n getProps : () => PropsType

,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise,\n getExports : () => X\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions = {|\n uid : string,\n options : NormalizedComponentOptionsType,\n overrides? : ParentDelegateOverrides

,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions) : ParentComponent {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType

= overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return rejectInitPromise(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__${ ZOID }_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getCurrentWindowReferenceUID = () : string => {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childDomain : string, childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin.setName(windowName).then(() => {\n return proxyWin;\n });\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow, context : $Values) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n const exportsPromise : ZalgoPromise = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType

) : ZalgoPromise {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values|} = {}) : ZalgoPromise> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|} = {}) : ZalgoPromise => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|}) : ZalgoPromise => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values|}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, initialChildDomain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType

= getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = ({ target, container, context, rerender } : RenderOptions) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, initialChildDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\n };\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n/* eslint react/no-deprecated: off, react/no-find-dom-node: off, react/display-name: off, react/no-did-mount-set-state: off, react/destructuring-assignment: off, react/prop-types: off */\n\nimport { extend, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\n// eslint-disable-next-line flowtype/require-exact-type\ndeclare class ReactClassType {}\n\n// eslint-disable-next-line flowtype/require-exact-type\ndeclare class __ReactComponent {}\n\ntype ReactElementType = {|\n\n|};\n\ntype ReactType = {|\n Component : __ReactComponent,\n createClass : ({| render : () => ReactElementType, componentDidMount : () => void, componentDidUpdate : () => void |}) => (typeof ReactClassType),\n createElement : (string, ?{ [string] : mixed }, ...children : $ReadOnlyArray) => ReactElementType\n|};\n\ntype ReactDomType = {|\n findDOMNode : (typeof ReactClassType) => HTMLElement\n|};\n\ntype ReactLibraryType = {|\n React : ReactType,\n ReactDOM : ReactDomType\n|};\n\nexport const react : ComponentDriverType<*, ReactLibraryType, typeof ReactClassType, *, *> = {\n\n register: (tag, propsDef, init, { React, ReactDOM }) => {\n\n // $FlowFixMe\n return class extends React.Component {\n render() : ReactElementType {\n return React.createElement('div', null);\n }\n\n componentDidMount() {\n // $FlowFixMe\n const el = ReactDOM.findDOMNode(this);\n const parent = init(extend({}, this.props));\n parent.render(el, CONTEXT.IFRAME);\n this.setState({ parent });\n }\n\n componentDidUpdate() {\n\n if (this.state && this.state.parent) {\n this.state.parent.updateProps(extend({}, this.props)).catch(noop);\n }\n }\n };\n }\n};\n","/* @flow */\n\nimport { noop, dasherizeToCamel } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\ntype VueComponent = {|\n render : (Function) => Element,\n inheritAttrs : boolean,\n mounted : () => void,\n watch : {|\n $attrs : {|\n deep : boolean,\n handler : () => void\n |}\n |}\n|};\n\ntype RegisteredVueComponent = {|\n \n|};\n\ntype VueType = {|\n component : (string, VueComponent) => RegisteredVueComponent\n|};\n\nfunction propsToCamelCase(props : Object) : Object {\n return Object.keys(props).reduce((acc, key) => {\n const value = props[key];\n // In vue `style` is a reserved prop name\n if (key === 'style-object' || key === 'styleObject') {\n acc.style = value;\n // To keep zoid as generic as possible, passing in the original prop name as well\n acc.styleObject = value;\n } else if (key.includes('-')) {\n acc[dasherizeToCamel(key)] = value;\n } else {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\nexport const vue : ComponentDriverType<*, VueType, RegisteredVueComponent, *, *> = {\n\n register: (tag, propsDef, init, Vue) => {\n\n return Vue.component(tag, {\n render(createElement) : Element {\n return createElement('div');\n },\n\n inheritAttrs: false,\n\n mounted() {\n // $FlowFixMe[object-this-reference]\n const el = this.$el;\n // $FlowFixMe[object-this-reference]\n this.parent = init({ ...propsToCamelCase(this.$attrs) });\n // $FlowFixMe[object-this-reference]\n this.parent.render(el, CONTEXT.IFRAME);\n },\n\n watch: {\n $attrs: {\n handler: function handler() {\n if (this.parent && this.$attrs) {\n this.parent.updateProps({ ...this.$attrs }).catch(noop);\n }\n },\n deep: true\n }\n }\n });\n }\n};\n","/* @flow */\nimport { dasherizeToCamel, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\nfunction propsToCamelCase(props : Object) : Object {\n return Object.keys(props).reduce((acc, key) => {\n const value = props[key];\n // In vue `style` is a reserved prop name\n if (key === 'style-object' || key === 'styleObject') {\n acc.style = value;\n // To keep zoid as generic as possible, passing in the original prop name as well\n acc.styleObject = value;\n } else if (key.includes('-')) {\n acc[dasherizeToCamel(key)] = value;\n } else {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\nexport const vue3 : ComponentDriverType<*, *, *, *, *> = {\n register: (tag, propsDef, init) => {\n return {\n template: `

`,\n\n inheritAttrs: false,\n\n mounted() {\n // $FlowFixMe[object-this-reference]\n const el = this.$el;\n // $FlowFixMe[object-this-reference]\n this.parent = init({ ...propsToCamelCase(this.$attrs) });\n // $FlowFixMe[object-this-reference]\n this.parent.render(el, CONTEXT.IFRAME);\n },\n\n watch: {\n $attrs: {\n handler: function handler() {\n if (this.parent && this.$attrs) {\n this.parent.updateProps({ ...this.$attrs }).catch(noop);\n }\n },\n deep: true\n }\n }\n };\n\n }\n};\n","/* @flow */\n\nimport { dasherizeToCamel, replaceObject, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\ntype AngularModule = {|\n directive : (string, () => {|\n scope : { [string] : '=' | '@' },\n restrict : string,\n controller : $ReadOnlyArray\n |}) => AngularModule\n|};\n\ntype Angular = {|\n module : (string, $ReadOnlyArray) => AngularModule\n|};\n\nexport const angular : ComponentDriverType<*, Angular, AngularModule, *, *> = {\n\n register: (tag, propsDef, init, ng) => {\n\n const module = ng.module(tag, []).directive(dasherizeToCamel(tag), () => {\n\n const scope = {};\n\n for (const key of Object.keys(propsDef)) {\n scope[key] = '=';\n }\n\n scope.props = '=';\n\n return {\n scope,\n\n restrict: 'E',\n\n controller: [ '$scope', '$element', ($scope, $element) => {\n function safeApply() {\n if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {\n try {\n $scope.$apply();\n } catch (err) {\n // pass\n }\n }\n }\n\n const getProps = () => {\n return replaceObject($scope.props, item => {\n if (typeof item === 'function') {\n return function angularWrapped() : mixed {\n // $FlowFixMe\n const result = item.apply(this, arguments);\n safeApply();\n return result;\n };\n }\n return item;\n });\n };\n\n const instance = init(getProps());\n instance.render($element[0], CONTEXT.IFRAME);\n\n $scope.$watch(() => {\n instance.updateProps(getProps()).catch(noop);\n });\n } ]\n };\n });\n\n return module;\n }\n};\n","/* @flow */\n/* eslint new-cap: 0 */\n\nimport { replaceObject } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\ntype Angular2Injection = {||};\n\ntype Angular2Component = {||};\n\ntype Angular2Module = {| annotations : Object, name : string |};\n\ntype Angular2 = {|\n Component : ({| selector : string, template : string, inputs : $ReadOnlyArray |}) => {|\n Class : ({| constructor : $ReadOnlyArray, ngOnInit : () => void, ngDoCheck : () => void |}) => Angular2Component\n |},\n NgModule : ({| declarations : $ReadOnlyArray<*>, exports : $ReadOnlyArray<*> |}) => {|\n Class : ({| constructor : () => void |}) => Angular2Module\n |},\n ElementRef : Angular2Injection,\n NgZone : Angular2Injection,\n Inject : Function\n|};\n\nconst equals = (obj1, obj2) => {\n const checked = {};\n\n for (const key in obj1) {\n if (obj1.hasOwnProperty(key)) {\n checked[key] = true;\n\n if (obj1[key] !== obj2[key]) {\n return false;\n }\n }\n }\n\n for (const key in obj2) {\n if (!checked[key]) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const angular2 : ComponentDriverType<*, Angular2, Angular2Module, *, *> = {\n\n register: (tag, propsDef, init, { Component : AngularComponent, NgModule, ElementRef, NgZone, Inject }) => {\n class ComponentInstance {\n elementRef : Object;\n internalProps : Object;\n parent : Object;\n props : Object;\n zone : Object;\n _props : Object;\n\n static annotations : $ReadOnlyArray<*>;\n static parameters : $ReadOnlyArray<*>;\n\n constructor (elementRef, zone) {\n this._props = {};\n this.elementRef = elementRef;\n this.zone = zone;\n }\n\n getProps () : Object {\n return replaceObject({ ...this.internalProps, ...this.props }, item => {\n if (typeof item === 'function') {\n const { zone } = this;\n return function angular2Wrapped() : void {\n // $FlowFixMe\n return zone.run(() => item.apply(this, arguments));\n };\n }\n return item;\n });\n }\n\n ngOnInit() {\n const targetElement = this.elementRef.nativeElement;\n this.parent = init(this.getProps());\n this.parent.render(targetElement, CONTEXT.IFRAME);\n }\n\n ngDoCheck() {\n if (this.parent && !equals(this._props, this.props)) {\n this._props = { ...this.props };\n this.parent.updateProps(this.getProps());\n }\n }\n }\n\n ComponentInstance.parameters = [\n [ new Inject(ElementRef) ],\n [ new Inject(NgZone) ]\n ];\n\n ComponentInstance.annotations = [\n new AngularComponent({\n selector: tag,\n template: `
`,\n inputs: [ 'props' ]\n })\n ];\n\n class ModuleInstance {\n static annotations : $ReadOnlyArray<*>;\n }\n\n ModuleInstance.annotations = [\n new NgModule({\n declarations: [ ComponentInstance ],\n exports: [ ComponentInstance ]\n })\n ];\n\n return ModuleInstance;\n }\n};\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType

) : ?HTMLElement {\n const { width, height } = dimensions;\n\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { type RenderOptionsType } from '../../parent/parent';\n\nexport function defaultPrerenderTemplate

({ doc, props } : RenderOptionsType

) : ?HTMLElement {\n if (__ZOID__.__DEFAULT_PRERENDER__) {\n const html = doc.createElement('html');\n const body = doc.createElement('body');\n const style = doc.createElement('style');\n const spinner = doc.createElement('div');\n spinner.classList.add('spinner');\n\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n html.appendChild(body);\n body.appendChild(spinner);\n body.appendChild(style);\n style.appendChild(doc.createTextNode(`\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n `));\n\n return html;\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition = ({|\n getExports : () => ZalgoPromise\n|}) => X;\n\nexport type ExportsDefinition = ExportsConfigDefinition | ExportsMapperDefinition;\n\nexport type ComponentOptionsType = {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values,\n\n props? : UserPropsDefinitionType,\n\n dimensions? : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType

|}) => Attributes,\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values,\n\n propsDef : PropsDefinitionType,\n dimensions : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition\n|};\n\nexport type ZoidComponentInstance = {|\n ...ParentHelpers

,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance,\n render : (container? : ContainerReferenceType, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent = {\n (props? : PropsInputType

| void) : ZoidComponentInstance,\n // eslint-disable-next-line no-undef\n driver : (string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n instances : $ReadOnlyArray>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = () : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions(options : ComponentOptionsType) : NormalizedComponentOptionsType {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop },\n exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component = {|\n init : (props? : PropsInputType

| void) => ZoidComponentInstance,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent\n|};\n\nexport function component(opts : ComponentOptionsType) : Component {\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible,\n children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent => {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : ContainerReferenceType) : ContainerReferenceType => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType

| void) : ZoidComponentInstance => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType

= parent.getProps();\n const parentExport : exportPropType = parent.export;\n\n const childParent : ParentPropType = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, vue3, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L) => D\n|};\n\nexport type ZoidProps

= PropsType

;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = (options : ComponentOptionsType) => ZoidComponent;\n\nexport const create : CreateZoidComponent = (options : ComponentOptionsType) : ZoidComponent => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType

| void) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n};\n\nexport function destroyComponents(err? : mixed) : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://zoid/webpack/universalModuleDefinition","webpack://zoid/webpack/bootstrap","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://zoid/./node_modules/zalgo-promise/src/utils.js","webpack://zoid/./node_modules/zalgo-promise/src/exceptions.js","webpack://zoid/./node_modules/zalgo-promise/src/flush.js","webpack://zoid/./node_modules/zalgo-promise/src/promise.js","webpack://zoid/./node_modules/cross-domain-utils/src/util.js","webpack://zoid/./node_modules/cross-domain-utils/src/constants.js","webpack://zoid/./node_modules/cross-domain-utils/src/utils.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/weakmap.js","webpack://zoid/./node_modules/belter/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/native.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://zoid/./node_modules/belter/src/dom.js","webpack://zoid/./node_modules/belter/src/css.js","webpack://zoid/./node_modules/post-robot/src/global.js","webpack://zoid/./node_modules/belter/src/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/hello.js","webpack://zoid/./node_modules/post-robot/src/conf/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/windows.js","webpack://zoid/./node_modules/universal-serialize/src/common.js","webpack://zoid/./node_modules/universal-serialize/src/constants.js","webpack://zoid/./node_modules/universal-serialize/src/serialize.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/function.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/error.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/promise.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/regex.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/date.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/array.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/object.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/string.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/number.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/boolean.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/null.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/undefined.js","webpack://zoid/./node_modules/universal-serialize/src/deserialize.js","webpack://zoid/./node_modules/post-robot/src/serialize/window.js","webpack://zoid/./node_modules/post-robot/src/bridge/common.js","webpack://zoid/./node_modules/post-robot/src/serialize/function.js","webpack://zoid/./node_modules/post-robot/src/serialize/serialize.js","webpack://zoid/./node_modules/post-robot/src/serialize/promise.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/strategies.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/index.js","webpack://zoid/./node_modules/post-robot/src/drivers/listeners.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/types.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/index.js","webpack://zoid/./node_modules/post-robot/src/public/on.js","webpack://zoid/./node_modules/post-robot/src/lib/compat.js","webpack://zoid/./node_modules/post-robot/src/public/send.js","webpack://zoid/./node_modules/post-robot/src/conf/config.js","webpack://zoid/./node_modules/post-robot/src/setup.js","webpack://zoid/./src/lib/global.js","webpack://zoid/./src/lib/serialize.js","webpack://zoid/./src/constants.js","webpack://zoid/./src/lib/window.js","webpack://zoid/./src/child/props.js","webpack://zoid/./src/child/child.js","webpack://zoid/./src/component/props.js","webpack://zoid/./src/parent/props.js","webpack://zoid/./src/parent/parent.js","webpack://zoid/./node_modules/post-robot/src/clean.js","webpack://zoid/./src/drivers/react.js","webpack://zoid/./src/drivers/vue.js","webpack://zoid/./src/drivers/vue3.js","webpack://zoid/./src/drivers/angular.js","webpack://zoid/./src/drivers/angular2.js","webpack://zoid/./src/component/templates/container.js","webpack://zoid/./src/component/templates/component.js","webpack://zoid/./src/component/component.js"],"names":["root","factory","exports","module","define","amd","self","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","hasOwnProperty","p","s","_setPrototypeOf","setPrototypeOf","__proto__","_inheritsLoose","subClass","superClass","prototype","constructor","_extends","assign","target","arguments","length","source","apply","isPromise","item","Promise","window","Window","toString","then","err","flushPromise","dispatchedErrors","possiblyUnhandledPromiseHandlers","activeCount","flushActive","promise","resolve","startActive","endActive","ZalgoPromise","handler","resolved","rejected","errorHandled","error","handlers","dispatching","stack","result","isAsync","res","reject","Error","dispatch","setTimeout","indexOf","push","j","dispatchPossiblyUnhandledError","asyncReject","chain","firstPromise","secondPromise","onSuccess","onError","promiseResult","catch","undefined","finally","onFinally","try","timeout","time","clearTimeout","toPromise","TypeError","lazy","all","promises","count","results","slice","prom","hash","awaitPromises","map","items","method","onPossiblyUnhandledException","cancel","splice","context","args","delay","flush","isRegex","WINDOW_TYPE","IFRAME","POPUP","IE_WIN_ACCESS_ERROR","getActualProtocol","win","location","protocol","getProtocol","mockDomain","split","isAboutProtocol","getParent","parent","getOpener","opener","canReadFromWindow","getActualDomain","PROTOCOL","host","getDomain","domain","isSameDomain","desc","getOwnPropertyDescriptor","isMockProtocol","isActuallySameDomain","assertSameDomain","isAncestorParent","child","childParent","getParents","getFrames","frames","len","frame","getAllChildFrames","getTop","top","getAllFramesInWindow","iframeWindows","iframeFrames","isWindowClosed","allowMock","closed","message","mockclosed","iframeIndex","collection","safeIndexOf","contentWindow","parentNode","doc","ownerDocument","documentElement","contains","isFrameWindowClosed","getFrameByName","winFrames","childFrame","getAncestor","anyMatch","collection1","collection2","item1","getDistanceFromTop","distance","isSameTopWindow","win1","win2","top1","top2","allFrames1","allFrames2","opener1","opener2","matchDomain","pattern","origin","Array","isArray","Boolean","match","JSON","stringify","some","subpattern","getDomainFromUrl","url","join","onCloseWindow","callback","maxtime","Infinity","check","isWindow","obj","__cross_domain_utils_window_check__","getFrameForWindow","frameElement","document","querySelectorAll","closeWindow","isIframe","parentElement","removeChild","close","objectIDs","CrossDomainSafeWeakMap","weakmap","keys","values","Math","random","WeakMap","freeze","testWeakMap","testKey","set","hasNativeWeakMap","_cleanupClosedWindows","delete","isSafeToReadWrite","entry","writable","index","has","getOrSet","_getPrototypeOf","getPrototypeOf","_isNativeReflectConstruct","Reflect","construct","sham","Proxy","Date","e","_construct","Parent","Class","isNativeReflectConstruct","a","instance","Function","_wrapNativeSuper","_cache","Map","Wrapper","configurable","isElement","element","passed","Element","nodeType","style","_","getFunctionName","fn","__name__","displayName","setFunctionName","base64encode","str","btoa","encodeURIComponent","replace","p1","String","fromCharCode","parseInt","Buffer","from","uniqueID","chars","charAt","floor","toISOString","toLowerCase","serializeArgs","subkey","val","uid","getObjectID","getEmptyObject","memoizeGlobalIndex","memoizeGlobalIndexValidFrom","memoize","options","simpleCache","thisCache","thisNamespace","cacheTime","memoizeIndex","memoizedFunction","cache","cacheKey","cacheResult","now","reset","memoizePromise","memoizedPromiseFunction","noop","once","called","stringifyError","level","newErr","extend","identity","safeInterval","loop","dasherizeToCamel","string","g","toUpperCase","defineLazyProp","arrayFrom","isObjectObject","isPlainObject","replaceObject","replacer","fullKey","itemKey","isDefined","cleanup","cleanErr","tasks","cleaned","cleaner","register","task","shift","assertExists","thing","clear","ExtendableError","captureStackTrace","ReferenceError","getBody","body","isDocumentReady","readyState","isDocumentInteractive","urlEncode","parseQuery","queryString","logic","__inline_memoize_cache__","params","pair","decodeURIComponent","inlineMemoize","extendQuery","originalQuery","props","filter","appendChild","container","getElementSafe","id","querySelector","elementReady","el","interval","setInterval","clearInterval","awaitFrameLoadPromises","PopupOpenError","awaitFrameLoad","addEventListener","cleanIframes","linkFrameWindow","awaitFrameWindow","loadedFrame","iframe","tag","styleText","createElement","class","className","setAttribute","attributes","styleSheet","cssText","createTextNode","html","innerHTML","allowTransparency","backgroundColor","border","isIE","navigator","userAgent","hasAttribute","getElement","event","removeEventListener","showElement","setProperty","hideElement","destroyElement","isElementClosed","onResize","width","height","currentWidth","offsetWidth","currentHeight","offsetHeight","canceled","observer","getClientRects","isElementVisible","newWidth","newHeight","ResizeObserver","observe","MutationObserver","childList","subtree","characterData","disconnect","isShadowElement","currentScript","getCurrentScript","getStackTrace","stackDetails","exec","scriptLocation","getElementsByTagName","reverse","script","src","inferCurrentScript","currentUID","toPx","toNum","toCSS","test","getGlobal","globalKey","__POST_ROBOT__","getAttribute","ATTRIBUTES","hashedString","total","charCodeAt","abs","strHashStr","dataset","getObj","globalStore","defStore","store","storeKey","defVal","del","WildCard","getWildcard","global","WINDOW_WILDCARD","windowStore","winStore","getStore","getInstanceID","resolveHelloPromise","helloPromises","existingPromise","newPromise","sayHello","send","instanceID","data","getWindowInstanceID","markWindowKnown","isSerializedType","__type__","determineType","serializeType","type","__val__","SERIALIZER","code","toJSON","defaultSerializers","DESERIALIZER","RegExp","defaultDeserializers","cleanupProxyWindows","idToProxyWindow","shouldClean","getSerializedWindow","winPromise","windowNamePromise","windowTypePromise","getName","getType","focus","isClosed","setLocation","href","opts","form","display","input","submit","submitForm","setName","sameDomain","ProxyWindow","serializedWindow","isProxyWindow","actualWindow","actualWindowPromise","getID","setWindow","isPopup","isPopupPromise","getNamePromise","reopenPromise","open","focusPromise","getWindow","awaitWindow","matchWindow","proxyInstanceID","knownWindowInstanceID","unwrap","serialize","toProxyWindow","deserialize","addMethod","methodStore","proxyWindowMethods","lookupMethod","serializeFunction","destination","on","meth","methodSource","arg","__id__","serializeMessage","serializers","serializer","serializePromise","deserializeMessage","deserializers","parse","deserializer","serializedPromise","deserializePromise","serializedFunction","getDeserializedFunction","crossDomainFunctionWrapper","fireAndForget","__origin__","__source__","deserializeFunction","SEND_MESSAGE_STRATEGIES","sendMessage","domainBuffer","buffer","serializedMessage","strategies","errors","strategyName","getResponseListener","deleteResponseListener","isResponseListenerErrored","getRequestListener","requestListeners","winQualifier","nameListeners","domainListeners","listener","regex","handleRequest","logName","sendResponse","ack","pathname","handleError","handleAck","handleResponse","receiveMessage","receivedMessages","messages","parsedMessage","parseMessages","deserializeMessages","requestListener","addRequestListener","winCandidate","requestListenerPromise","actualWin","listenersCollection","existingListener","strDomain","winNameDomainRegexListeners","winNameDomainRegexListener","winNameListeners","winNameDomainListeners","errorHandler","postMessage","mockUserAgent","getUserAgent","foreignGlobal","winOrProxyWin","domainMatcher","responseTimeout","childTimeout","validateOptions","actualParent","isAncestor","getHelloPromise","awaitWindowHello","targetDomain","actualDomain","normalizedDomain","normalizeDomain","responseListener","addResponseListener","reqPromises","markResponseListenerErrored","totalAckTimeout","isWindowKnown","totalResTimeout","ackTimeout","resTimeout","cancelled","max","tryGlobal","getProxyObject","basicSerialize","getUIDRefStore","references","crossDomainSerialize","metaData","sender","receiver","passByReference","basic","proxyWin","internalSerializeMessage","reference","getRawRef","serializedData","cleanReference","ref","crossDomainDeserialize","atob","base64decode","basicDeserialize","getRefValue","internalDeserializeMessage","PROP_TYPE","STRING","OBJECT","FUNCTION","BOOLEAN","NUMBER","ARRAY","PROP_SERIALIZATION","DOTIFY","BASE64","CONTEXT","EVENT","RENDER","RENDERED","DISPLAY","ERROR","CLOSE","DESTROY","PROPS","RESIZE","FOCUS","buildChildWindowName","serializedPayload","parseWindowName","windowName","zoidcomp","serializedInitialPayload","parseInitialParentPayload","windowRef","getNthParent","ancestor","windows","findChildFrameByName","namedFrame","findFrameByName","getWindowByRef","payload","getInitialParentPayload","getWindowRef","targetWindow","currentWindow","normalizeChildProp","propsDef","helpers","prop","childDecorate","onProps","resize","getParentDomain","show","hide","export","getSiblings","destroy","defaultNoop","decorateOnce","eachProp","serializeProps","propDef","getParam","queryParam","bodyParam","getValue","queryValue","bodyValue","finalParam","finalValue","serialization","dotify","prefix","newobj","every","dotkey","mapProps","parentComponent","triggered","emitter","currentProxyWin","currentProxyContainer","childComponent","currentChildDomain","currentContainer","overrides","parentWin","containerTemplate","prerenderTemplate","dimensions","autoResize","domainMatch","xports","initPromise","handledErrors","clean","state","inputProps","internalState","visible","eventName","handlerList","trigger","triggerOnce","onErrorOverride","getProxyContainerOverride","getProxyContainer","showOverride","hideOverride","closeOverride","renderContainerOverride","renderContainer","getProxyWindowOverride","getProxyWindow","setProxyWinOverride","setProxyWin","openFrameOverride","openFrame","openPrerenderFrameOverride","openPrerenderFrame","prerenderOverride","prerender","openOverride","openPrerenderOverride","openPrerender","watchForUnloadOverride","watchForUnload","getInternalStateOverride","getInternalState","setInternalStateOverride","setInternalState","resolveInitPromise","rejectInitPromise","getPropsForChild","initialChildDomain","sendToChild","newInternalState","windowProp","setState","getUrl","getAttributes","getInitialChildDomain","title","proxyPrerenderFrame","prerenderFrame","prerenderFrameWindow","actualComponentWindow","initChild","childDomain","childExports","proxyFrame","cleanUpWindow","unloadWindowListener","closeParentWindowListener","checkWindowClose","secondIsClosed","exportsPromise","xport","actualExports","renderTemplate","renderer","proxyPrerenderWin","prerenderWindow","isBlankDomain","tagName","children","writeElementToWindow","prerenderResizeListener","proxyContainer","rerender","innerContainer","containerWatcher","sacrificialFrame","sacrificialFrameWin","mutationObservers","elementClosed","mutationElement","mutationObserver","frameWin","watchElementForClose","removeError","getHelpers","updateProps","setProps","newInputProps","existingProps","valueDetermined","alias","default","required","decorate","getDerivedValue","extendProps","newProps","childProps","containerElement","insertShadowSlot","shadowHost","shadowRoot","getShadowRoot","getShadowHost","slotName","slot","slotProvider","init","onRender","onDisplay","onRendered","onClose","onDestroy","onFocus","render","childDomainMatch","checkAllowRender","delegatePromise","delegateProps","propName","allowDelegate","childOverridesPromise","POST_MESSAGE","parentComp","getDelegateOverrides","childOverrides","delegate","watchForUnloadPromise","buildBodyPromise","onRenderPromise","getProxyContainerPromise","getProxyWindowPromise","finalSetPropsPromise","buildUrlPromise","query","originalUrl","originalHash","hashString","extendUrl","normalizeMockUrl","buildWindowNamePromise","version","__ZOID__","checkClose","buildInitialChildPayload","childPayload","buildSerializedChildPayload","openFramePromise","openPrerenderFramePromise","renderContainerPromise","openPromise","openPrerenderPromise","setStatePromise","prerenderPromise","setWindowNamePromise","getMethodPromise","loadUrlPromise","windowUrl","watchForClosePromise","watchForClose","onDisplayPromise","openBridgePromise","runTimeoutPromise","onRenderedPromise","getProps","getExports","react","React","ReactDOM","componentDidMount","findDOMNode","componentDidUpdate","Component","vue","Vue","component","inheritAttrs","mounted","$el","$attrs","reduce","acc","styleObject","includes","watch","deep","vue3","template","angular","ng","directive","scope","restrict","controller","$scope","$element","safeApply","$root","$$phase","$apply","$watch","angular2","AngularComponent","NgModule","ElementRef","NgZone","Inject","ComponentInstance","elementRef","zone","internalProps","_props","run","ngOnInit","targetElement","nativeElement","ngDoCheck","obj1","obj2","checked","equals","annotations","parameters","selector","inputs","ModuleInstance","declarations","defaultContainerTemplate","div","cspNonce","classList","add","remove","defaultPrerenderTemplate","spinner","cleanInstances","cleanZoid","allowDelegateListener","delegateListener","bridgeUrl","allowedParentDomains","defaultContext","validate","eligible","logger","info","xportsDefinition","valuePromise","normalizeOptions","driverCache","instances","isChild","isChildComponentWindow","registerChild","xprops","components","onPropHandlers","parentComponentWindow","parentDomain","parentExports","initialProps","parentExport","parentResize","parentInit","anyParent","currentParent","winParent","isUpdate","normalizedProps","normalizeChildProps","componentName","updateChildWindowNameWithRef","checkParentDomain","ZOID","eligibility","reason","clone","getDefaultContext","finalContext","getDefaultContainer","newInstance","renderTo","childComponents","childName","Child","childInputProps","parentProps","getChildren","isEligible","driver","driverName","dep","drivers","canRenderTo","initialized","sourceElement","originalEvent","messageListener","listenForMessages","initHello","comp","destroyComponents","destroyPromise","destroyAll","responseListeners","cancelResponseListeners"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,OAAQ,GAAIH,GACO,iBAAZC,QACdA,QAAc,KAAID,IAElBD,EAAW,KAAIC,IARjB,CASoB,oBAATK,KAAuBA,KAAOC,MAAO,WAChD,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUR,QAGnC,IAAIC,EAASK,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHV,QAAS,IAUV,OANAW,EAAQH,GAAUI,KAAKX,EAAOD,QAASC,EAAQA,EAAOD,QAASO,GAG/DN,EAAOS,GAAI,EAGJT,EAAOD,QA0Df,OArDAO,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASf,EAASgB,EAAMC,GAC3CV,EAAoBW,EAAElB,EA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e,IACAA,EAASuD,WAAY,GAEzBwa,EAAkBtlB,IAAIjX,IOZ1Bw8B,ILoHMhe,EAAW5H,KAAc1c,IAAI,yBAE/BskB,EAASle,gB9BvINhE,OAAM,uBqDmjBN67B,GAAUz4B,IAAIhD,GlBniBlB,ILqHG8hB","file":"zoid.frameworks.frame.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"zoid\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"zoid\"] = factory();\n\telse\n\t\troot[\"zoid\"] = factory();\n})((typeof self !== 'undefined' ? self : this), function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","/* @flow */\n\nexport function isPromise(item : mixed) : boolean {\n try {\n if (!item) {\n return false;\n }\n\n if (typeof Promise !== 'undefined' && item instanceof Promise) {\n return true;\n }\n\n if (typeof window !== 'undefined' && typeof window.Window === 'function' && item instanceof window.Window) {\n return false;\n }\n\n if (typeof window !== 'undefined' && typeof window.constructor === 'function' && item instanceof window.constructor) {\n return false;\n }\n\n const toString = ({}).toString;\n\n if (toString) {\n const name = toString.call(item);\n\n if (name === '[object Window]' || name === '[object global]' || name === '[object DOMWindow]') {\n return false;\n }\n }\n\n if (typeof item.then === 'function') {\n return true;\n }\n } catch (err) {\n return false;\n }\n\n return false;\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nconst dispatchedErrors = [];\nconst possiblyUnhandledPromiseHandlers : Array<(mixed, promise? : ZalgoPromise) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer,\n undefined? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull,\n [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull,\n deserializeUndefined\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer,\n undefined? : PrimitiveDeserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull,\n [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SetLocationOptions = {|\n method? : $Values,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n const getName = () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n });\n\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n\n } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name, 'noopener');\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady : ZalgoPromise = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n // $FlowFixMe[method-unbinding]\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\ntype SendStrategies = {|\n [$Values] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore, getGlobalKey } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n const strDomain = domain.toString();\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n}\n\nexport function handleAck(source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n}\n\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[getGlobalKey()];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n if (isWindowClosed(source)) {\n return;\n }\n\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise = ZalgoPromise & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport { ProxyWindow } from '../serialize/window';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (winOrProxyWin, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n });\n};\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT : number = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n\nexport function basicSerialize(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType =\n UIDReferenceType |\n RawReferenceType;\n\nexport function getUIDRefStore(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef(val : T) : ReferenceType {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef(val : T) : ReferenceType {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue(win : CrossDomainWindowType, ref : ReferenceType) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef(win : CrossDomainWindowType, ref : ReferenceType) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType\n|};\n\ntype CrossDomainSerializeOptions = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType\n|};\n\nexport function crossDomainDeserialize({ data, sender, basic = false } : CrossDomainDeserializeOptions) : CrossDomainDeserializedMessage {\n const message : Message = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from 'cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: ('string' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from 'cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = windowName.split('__');\n\n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n\n if (!name) {\n throw new Error(`Expected component name`);\n }\n\n if (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload,\n reference : ReferenceType\n|};\n\nconst parseInitialParentPayload = memoize((windowName : string) : InitialParentPayload => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload() : InitialParentPayload {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType, props : PropsType

, origin : string, helpers : ChildHelpers, isUpdate : boolean = false) : ChildPropsType {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from 'cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise,\n getSiblings : getSiblingsPropType\n|};\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent = {|\n getProps : () => ChildPropsType,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent(options : NormalizedComponentOptionsType) : ChildComponent {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return getAutoResize().then(({ width, height, element }) => {\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from 'cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type exportPropType = (X) => ZalgoPromise;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\nexport type contextPropType = string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType

,\n export : exportPropType\n|};\n\nexport type PropsInputType

= {|\n parent? : ParentPropType,\n \n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : ?cspNoncePropType,\n context? : ?contextPropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

,\n\n ...P\n|};\n\nexport type PropsType

= {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n context? : ?contextPropType,\n dimensions : CssDimensionsType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise;\n\nexport type ChildPropsType = {|\n ...PropsType

,\n\n parent? : ParentPropType,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType

,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n // eslint-disable-next-line no-undef\n queryValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P, X> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType = {|\n [string] : MixedPropDefinitionType\n|};\n\nexport type BuiltInPropsDefinitionType = {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n uid : StringPropDefinitionType,\n tag : StringPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n export : FunctionPropDefinitionType, P, X>,\n getSiblings : FunctionPropDefinitionType,\n context : StringPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P, X>\n|};\n\nexport type PropsDefinitionType = {|\n ...BuiltInPropsDefinitionType,\n [ string ] : MixedPropDefinitionType\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = ({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps() : BuiltInPropsDefinitionType {\n return {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n context: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback =\n ((string, BooleanPropDefinitionType | void, boolean) => R) &\n ((string, StringPropDefinitionType | void, string) => R) &\n ((string, NumberPropDefinitionType | void, number) => R) &\n ((string, FunctionPropDefinitionType | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType | void, Object) => R);\n\nexport function eachProp(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) : $ReadOnlyArray {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps(propsDef : PropsDefinitionType, existingProps : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps(propsDef : PropsDefinitionType, props : (PropsType

), method : $Values) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType = {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n childDomainMatch : DomainMatcher,\n props : PropsType

,\n exports : ParentExportsType\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise;\n\ntype RenderContainerOptions = {|\n context : $Values,\n proxyFrame : ?ProxyObject,\n proxyPrerenderFrame : ?ProxyObject,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise;\ntype RejectInitPromise = (mixed) => ZalgoPromise;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, RenderContainerOptions) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values|}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState,\n resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values,\n rerender : Rerender\n|};\n\ntype ParentComponent = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise,\n getProps : () => PropsType

,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise,\n getExports : () => X\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions = {|\n uid : string,\n options : NormalizedComponentOptionsType,\n overrides? : ParentDelegateOverrides

,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions) : ParentComponent {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType

= overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return rejectInitPromise(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__${ ZOID }_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getCurrentWindowReferenceUID = () : string => {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childDomain : string, childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin.setName(windowName).then(() => {\n return proxyWin;\n });\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow, context : $Values) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n const exportsPromise : ZalgoPromise = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType

) : ZalgoPromise {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values|} = {}) : ZalgoPromise> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|} = {}) : ZalgoPromise => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|}) : ZalgoPromise => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values|}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, initialChildDomain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType

= getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = ({ target, container, context, rerender } : RenderOptions) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, initialChildDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\n };\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n/* eslint react/no-deprecated: off, react/no-find-dom-node: off, react/display-name: off, react/no-did-mount-set-state: off, react/destructuring-assignment: off, react/prop-types: off */\n\nimport { extend, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\ndeclare class ReactClassType {}\ndeclare class __ReactComponent {}\n\ntype ReactElementType = {|\n\n|};\n\ntype ReactType = {|\n Component : __ReactComponent,\n createClass : ({| render : () => ReactElementType, componentDidMount : () => void, componentDidUpdate : () => void |}) => (typeof ReactClassType),\n createElement : (string, ?{ [string] : mixed }, ...children : $ReadOnlyArray) => ReactElementType\n|};\n\ntype ReactDomType = {|\n findDOMNode : (typeof ReactClassType) => HTMLElement\n|};\n\ntype ReactLibraryType = {|\n React : ReactType,\n ReactDOM : ReactDomType\n|};\n\nexport const react : ComponentDriverType<*, ReactLibraryType, typeof ReactClassType, *, *> = {\n\n register: (tag, propsDef, init, { React, ReactDOM }) => {\n\n // $FlowFixMe\n return class extends React.Component {\n render() : ReactElementType {\n return React.createElement('div', null);\n }\n\n componentDidMount() {\n // $FlowFixMe\n const el = ReactDOM.findDOMNode(this);\n const parent = init(extend({}, this.props));\n parent.render(el, this.props.context);\n this.setState({ parent });\n }\n\n componentDidUpdate() {\n\n if (this.state && this.state.parent) {\n this.state.parent.updateProps(extend({}, this.props)).catch(noop);\n }\n }\n };\n }\n};\n","/* @flow */\n\nimport { noop, dasherizeToCamel } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\ntype VueComponent = {|\n render : (Function) => Element,\n inheritAttrs : boolean,\n mounted : () => void,\n watch : {|\n $attrs : {|\n deep : boolean,\n handler : () => void\n |}\n |}\n|};\n\ntype RegisteredVueComponent = {|\n \n|};\n\ntype VueType = {|\n component : (string, VueComponent) => RegisteredVueComponent\n|};\n\nfunction propsToCamelCase(props : Object) : Object {\n return Object.keys(props).reduce((acc, key) => {\n const value = props[key];\n // In vue `style` is a reserved prop name\n if (key === 'style-object' || key === 'styleObject') {\n acc.style = value;\n // To keep zoid as generic as possible, passing in the original prop name as well\n acc.styleObject = value;\n } else if (key.includes('-')) {\n acc[dasherizeToCamel(key)] = value;\n } else {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\nexport const vue : ComponentDriverType<*, VueType, RegisteredVueComponent, *, *> = {\n\n register: (tag, propsDef, init, Vue) => {\n\n return Vue.component(tag, {\n render(createElement) : Element {\n return createElement('div');\n },\n\n inheritAttrs: false,\n\n mounted() {\n // $FlowFixMe[object-this-reference]\n const el = this.$el;\n // $FlowFixMe[object-this-reference]\n this.parent = init({ ...propsToCamelCase(this.$attrs) });\n // $FlowFixMe[object-this-reference]\n this.parent.render(el, this.$attrs.context);\n },\n\n watch: {\n $attrs: {\n handler: function handler() {\n if (this.parent && this.$attrs) {\n this.parent.updateProps({ ...this.$attrs }).catch(noop);\n }\n },\n deep: true\n }\n }\n });\n }\n};\n","/* @flow */\nimport { dasherizeToCamel, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\nfunction propsToCamelCase(props : Object) : Object {\n return Object.keys(props).reduce((acc, key) => {\n const value = props[key];\n // In vue `style` is a reserved prop name\n if (key === 'style-object' || key === 'styleObject') {\n acc.style = value;\n // To keep zoid as generic as possible, passing in the original prop name as well\n acc.styleObject = value;\n } else if (key.includes('-')) {\n acc[dasherizeToCamel(key)] = value;\n } else {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\nexport const vue3 : ComponentDriverType<*, *, *, *, *> = {\n register: (tag, propsDef, init) => {\n return {\n template: `

`,\n\n inheritAttrs: false,\n\n mounted() {\n // $FlowFixMe[object-this-reference]\n const el = this.$el;\n // $FlowFixMe[object-this-reference]\n this.parent = init({ ...propsToCamelCase(this.$attrs) });\n // $FlowFixMe[object-this-reference]\n this.parent.render(el, this.$attrs.context);\n },\n\n watch: {\n $attrs: {\n handler: function handler() {\n if (this.parent && this.$attrs) {\n this.parent.updateProps({ ...this.$attrs }).catch(noop);\n }\n },\n deep: true\n }\n }\n };\n\n }\n};\n","/* @flow */\n\nimport { dasherizeToCamel, replaceObject, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\ntype AngularModule = {|\n directive : (string, () => {|\n scope : { [string] : '=' | '@' },\n restrict : string,\n controller : $ReadOnlyArray\n |}) => AngularModule\n|};\n\ntype Angular = {|\n module : (string, $ReadOnlyArray) => AngularModule\n|};\n\nexport const angular : ComponentDriverType<*, Angular, AngularModule, *, *> = {\n\n register: (tag, propsDef, init, ng) => {\n\n const module = ng.module(tag, []).directive(dasherizeToCamel(tag), () => {\n\n const scope = {};\n\n for (const key of Object.keys(propsDef)) {\n scope[key] = '=';\n }\n\n scope.props = '=';\n\n return {\n scope,\n\n restrict: 'E',\n\n controller: [ '$scope', '$element', ($scope, $element) => {\n function safeApply() {\n if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {\n try {\n $scope.$apply();\n } catch (err) {\n // pass\n }\n }\n }\n\n const getProps = () => {\n return replaceObject($scope.props, item => {\n if (typeof item === 'function') {\n return function angularWrapped() : mixed {\n // $FlowFixMe\n const result = item.apply(this, arguments);\n safeApply();\n return result;\n };\n }\n return item;\n });\n };\n\n const props = getProps();\n const instance = init(props);\n instance.render($element[0], props.context);\n\n $scope.$watch(() => {\n instance.updateProps(getProps()).catch(noop);\n });\n } ]\n };\n });\n\n return module;\n }\n};\n","/* @flow */\n/* eslint new-cap: 0 */\n\nimport { replaceObject } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\ntype Angular2Injection = {||};\n\ntype Angular2Component = {||};\n\ntype Angular2Module = {| annotations : Object, name : string |};\n\ntype Angular2 = {|\n Component : ({| selector : string, template : string, inputs : $ReadOnlyArray |}) => {|\n Class : ({| constructor : $ReadOnlyArray, ngOnInit : () => void, ngDoCheck : () => void |}) => Angular2Component\n |},\n NgModule : ({| declarations : $ReadOnlyArray<*>, exports : $ReadOnlyArray<*> |}) => {|\n Class : ({| constructor : () => void |}) => Angular2Module\n |},\n ElementRef : Angular2Injection,\n NgZone : Angular2Injection,\n Inject : Function\n|};\n\nconst equals = (obj1, obj2) => {\n const checked = {};\n\n for (const key in obj1) {\n if (obj1.hasOwnProperty(key)) {\n checked[key] = true;\n\n if (obj1[key] !== obj2[key]) {\n return false;\n }\n }\n }\n\n for (const key in obj2) {\n if (!checked[key]) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const angular2 : ComponentDriverType<*, Angular2, Angular2Module, *, *> = {\n\n register: (tag, propsDef, init, { Component : AngularComponent, NgModule, ElementRef, NgZone, Inject }) => {\n class ComponentInstance {\n elementRef : Object;\n internalProps : Object;\n parent : Object;\n props : Object;\n zone : Object;\n _props : Object;\n\n static annotations : $ReadOnlyArray<*>;\n static parameters : $ReadOnlyArray<*>;\n\n constructor (elementRef, zone) {\n this._props = {};\n this.elementRef = elementRef;\n this.zone = zone;\n }\n\n getProps () : Object {\n return replaceObject({ ...this.internalProps, ...this.props }, item => {\n if (typeof item === 'function') {\n const { zone } = this;\n return function angular2Wrapped() : void {\n // $FlowFixMe\n return zone.run(() => item.apply(this, arguments));\n };\n }\n return item;\n });\n }\n\n ngOnInit() {\n const targetElement = this.elementRef.nativeElement;\n const props = this.getProps();\n this.parent = init(props);\n this.parent.render(targetElement, props.context);\n }\n\n ngDoCheck() {\n if (this.parent && !equals(this._props, this.props)) {\n this._props = { ...this.props };\n this.parent.updateProps(this.getProps());\n }\n }\n }\n\n ComponentInstance.parameters = [\n [ new Inject(ElementRef) ],\n [ new Inject(NgZone) ]\n ];\n\n ComponentInstance.annotations = [\n new AngularComponent({\n selector: tag,\n template: `
`,\n inputs: [ 'props' ]\n })\n ];\n\n class ModuleInstance {\n static annotations : $ReadOnlyArray<*>;\n }\n\n ModuleInstance.annotations = [\n new NgModule({\n declarations: [ ComponentInstance ],\n exports: [ ComponentInstance ]\n })\n ];\n\n return ModuleInstance;\n }\n};\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType

) : ?HTMLElement {\n const { width, height } = dimensions;\n\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { type RenderOptionsType } from '../../parent/parent';\n\nexport function defaultPrerenderTemplate

({ doc, props } : RenderOptionsType

) : ?HTMLElement {\n if (__ZOID__.__DEFAULT_PRERENDER__) {\n const html = doc.createElement('html');\n const body = doc.createElement('body');\n const style = doc.createElement('style');\n const spinner = doc.createElement('div');\n spinner.classList.add('spinner');\n\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n html.appendChild(body);\n body.appendChild(spinner);\n body.appendChild(style);\n style.appendChild(doc.createTextNode(`\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n `));\n\n return html;\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition = ({|\n getExports : () => ZalgoPromise\n|}) => X;\n\nexport type ExportsDefinition = ExportsConfigDefinition | ExportsMapperDefinition;\n\nexport type ComponentOptionsType = {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values,\n\n props? : UserPropsDefinitionType,\n\n dimensions? : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType

|}) => Attributes,\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values,\n\n propsDef : PropsDefinitionType,\n dimensions : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition\n|};\n\nexport type ZoidComponentInstance = {|\n ...ParentHelpers

,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance,\n render : (container? : ContainerReferenceType, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent = {\n (props? : PropsInputType

| void) : ZoidComponentInstance,\n // eslint-disable-next-line no-undef\n driver : (string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n instances : $ReadOnlyArray>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = () : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions(options : ComponentOptionsType) : NormalizedComponentOptionsType {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop },\n exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component = {|\n init : (props? : PropsInputType

| void) => ZoidComponentInstance,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent\n|};\n\nexport function component(opts : ComponentOptionsType) : Component {\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible,\n children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent => {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : ContainerReferenceType) : ContainerReferenceType => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType

| void) : ZoidComponentInstance => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType

= parent.getProps();\n const parentExport : exportPropType = parent.export;\n\n const childParent : ParentPropType = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, vue3, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L) => D\n|};\n\nexport type ZoidProps

= PropsType

;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = (options : ComponentOptionsType) => ZoidComponent;\n\nexport const create : CreateZoidComponent = (options : ComponentOptionsType) : ZoidComponent => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType

| void) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n};\n\nexport function destroyComponents(err? : mixed) : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/zoid.frameworks.js b/dist/zoid.frameworks.js index 8a303bad..91bdbd0a 100644 --- a/dist/zoid.frameworks.js +++ b/dist/zoid.frameworks.js @@ -423,6 +423,10 @@ function isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } + var WINDOW_TYPE = { + IFRAME: "iframe", + POPUP: "popup" + }; var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; function getActualProtocol(win) { void 0 === win && (win = window); @@ -678,6 +682,13 @@ } return !1; } + function getDistanceFromTop(win) { + void 0 === win && (win = window); + var distance = 0; + var parent = win; + for (;parent; ) (parent = utils_getParent(parent)) && (distance += 1); + return distance; + } function isSameTopWindow(win1, win2) { var top1 = getTop(win1) || win1; var top2 = getTop(win2) || win2; @@ -705,6 +716,26 @@ function getDomainFromUrl(url) { return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : getDomain(); } + function onCloseWindow(win, callback, delay, maxtime) { + void 0 === delay && (delay = 1e3); + void 0 === maxtime && (maxtime = 1 / 0); + var timeout; + !function check() { + if (isWindowClosed(win)) { + timeout && clearTimeout(timeout); + return callback(); + } + if (maxtime <= 0) clearTimeout(timeout); else { + maxtime -= delay; + timeout = setTimeout(check, delay); + } + }(); + return { + cancel: function() { + timeout && clearTimeout(timeout); + } + }; + } function isWindow(obj) { try { if (obj === window) return !0; @@ -746,6 +777,11 @@ } catch (err) {} return !1; } + function normalizeMockUrl(url) { + if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; + var domain; + throw new Error("Mock urls not supported out of test mode"); + } function getFrameForWindow(win) { if (isSameDomain(win)) return assertSameDomain(win).frameElement; for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { @@ -1881,11 +1917,7 @@ function setupBridge(_ref) { var on = _ref.on, send = _ref.send, receiveMessage = _ref.receiveMessage; windowOpen = window.open, window.open = function(url, name, options, last) { - var win = windowOpen.call(this, function(url) { - if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; - var domain; - throw new Error("Mock urls not supported out of test mode"); - }(url), name, options, last); + var win = windowOpen.call(this, normalizeMockUrl(url), name, options, last); if (!win) return win; linkWindow({ win: win, @@ -2072,7 +2104,7 @@ })); var windowTypePromise = winPromise.then((function(window) { if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type"); - return getOpener(window) ? "popup" : "iframe"; + return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME; })); windowNamePromise.catch(src_util_noop); windowTypePromise.catch(src_util_noop); @@ -2194,7 +2226,7 @@ }; _proto.isPopup = function() { return this.getType().then((function(type) { - return "popup" === type; + return type === WINDOW_TYPE.POPUP; })); }; _proto.setLocation = function(href, opts) { @@ -3049,347 +3081,10 @@ bridges.reset(); } }; - function src_util_isRegex(item) { - return "[object RegExp]" === {}.toString.call(item); - } - function utils_getActualProtocol(win) { - void 0 === win && (win = window); - return win.location.protocol; - } - function utils_getProtocol(win) { - void 0 === win && (win = window); - if (win.mockDomain) { - var protocol = win.mockDomain.split("//")[0]; - if (protocol) return protocol; - } - return utils_getActualProtocol(win); - } - function utils_isAboutProtocol(win) { - void 0 === win && (win = window); - return "about:" === utils_getProtocol(win); - } - function src_utils_getParent(win) { - void 0 === win && (win = window); - if (win) try { - if (win.parent && win.parent !== win) return win.parent; - } catch (err) {} - } - function utils_getOpener(win) { - void 0 === win && (win = window); - if (win && !src_utils_getParent(win)) try { - return win.opener; - } catch (err) {} - } - function utils_canReadFromWindow(win) { - try { - return !0; - } catch (err) {} - return !1; - } - function utils_getActualDomain(win) { - void 0 === win && (win = window); - var location = win.location; - if (!location) throw new Error("Can not read window location"); - var protocol = utils_getActualProtocol(win); - if (!protocol) throw new Error("Can not read window protocol"); - if ("file:" === protocol) return "file://"; - if ("about:" === protocol) { - var parent = src_utils_getParent(win); - return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://"; - } - var host = location.host; - if (!host) throw new Error("Can not read window host"); - return protocol + "//" + host; - } - function utils_getDomain(win) { - void 0 === win && (win = window); - var domain = utils_getActualDomain(win); - return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; - } - function utils_isSameDomain(win) { - if (!function(win) { - try { - if (win === window) return !0; - } catch (err) {} - try { - var desc = Object.getOwnPropertyDescriptor(win, "location"); - if (desc && !1 === desc.enumerable) return !1; - } catch (err) {} - try { - if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; - } catch (err) {} - try { - if (function(win) { - void 0 === win && (win = window); - return "mock:" === utils_getProtocol(win); - }(win) && utils_canReadFromWindow()) return !0; - } catch (err) {} - try { - if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0; - } catch (err) {} - return !1; - }(win)) return !1; - try { - if (win === window) return !0; - if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; - if (utils_getDomain(window) === utils_getDomain(win)) return !0; - } catch (err) {} - return !1; - } - function utils_assertSameDomain(win) { - if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain"); - return win; - } - function utils_isAncestorParent(parent, child) { - if (!parent || !child) return !1; - var childParent = src_utils_getParent(child); - return childParent ? childParent === parent : -1 !== function(win) { - var result = []; - try { - for (;win.parent !== win; ) { - result.push(win.parent); - win = win.parent; - } - } catch (err) {} - return result; - }(child).indexOf(parent); - } - function utils_getFrames(win) { - var result = []; - var frames; - try { - frames = win.frames; - } catch (err) { - frames = win; - } - var len; - try { - len = frames.length; - } catch (err) {} - if (0 === len) return result; - if (len) { - for (var i = 0; i < len; i++) { - var frame = void 0; - try { - frame = frames[i]; - } catch (err) { - continue; - } - result.push(frame); - } - return result; - } - for (var _i = 0; _i < 100; _i++) { - var _frame = void 0; - try { - _frame = frames[_i]; - } catch (err) { - return result; - } - if (!_frame) return result; - result.push(_frame); - } - return result; - } - function utils_getAllChildFrames(win) { - var result = []; - for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) { - var frame = _getFrames2[_i3]; - result.push(frame); - for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); - } - return result; - } - function utils_getTop(win) { - void 0 === win && (win = window); - try { - if (win.top) return win.top; - } catch (err) {} - if (src_utils_getParent(win) === win) return win; - try { - if (utils_isAncestorParent(window, win) && window.top) return window.top; - } catch (err) {} - try { - if (utils_isAncestorParent(win, window) && window.top) return window.top; - } catch (err) {} - for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { - var frame = _getAllChildFrames4[_i7]; - try { - if (frame.top) return frame.top; - } catch (err) {} - if (src_utils_getParent(frame) === frame) return frame; - } - } - function utils_getAllFramesInWindow(win) { - var top = utils_getTop(win); - if (!top) throw new Error("Can not determine top window"); - var result = [].concat(utils_getAllChildFrames(top), [ top ]); - -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win))); - return result; - } - var utils_iframeWindows = []; - var utils_iframeFrames = []; - function utils_isWindowClosed(win, allowMock) { - void 0 === allowMock && (allowMock = !0); - try { - if (win === window) return !1; - } catch (err) { - return !0; - } - try { - if (!win) return !0; - } catch (err) { - return !0; - } - try { - if (win.closed) return !0; - } catch (err) { - return !err || "Call was rejected by callee.\r\n" !== err.message; - } - if (allowMock && utils_isSameDomain(win)) try { - if (win.mockclosed) return !0; - } catch (err) {} - try { - if (!win.parent || !win.top) return !0; - } catch (err) {} - var iframeIndex = function(collection, item) { - for (var i = 0; i < collection.length; i++) try { - if (collection[i] === item) return i; - } catch (err) {} - return -1; - }(utils_iframeWindows, win); - if (-1 !== iframeIndex) { - var frame = utils_iframeFrames[iframeIndex]; - if (frame && function(frame) { - if (!frame.contentWindow) return !0; - if (!frame.parentNode) return !0; - var doc = frame.ownerDocument; - if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { - var parent = frame; - for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; - if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; - } - return !1; - }(frame)) return !0; - } - return !1; - } - function utils_getFrameByName(win, name) { - var winFrames = utils_getFrames(win); - for (var _i9 = 0; _i9 < winFrames.length; _i9++) { - var childFrame = winFrames[_i9]; - try { - if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; - } catch (err) {} - } - try { - if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; - } catch (err) {} - try { - if (-1 !== winFrames.indexOf(win[name])) return win[name]; - } catch (err) {} - } - function utils_getAncestor(win) { - void 0 === win && (win = window); - return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0; - } - function utils_anyMatch(collection1, collection2) { - for (var _i17 = 0; _i17 < collection1.length; _i17++) { - var item1 = collection1[_i17]; - for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; - } - return !1; - } - function utils_getDistanceFromTop(win) { - void 0 === win && (win = window); - var distance = 0; - var parent = win; - for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1); - return distance; - } - function utils_matchDomain(pattern, origin) { - if ("string" == typeof pattern) { - if ("string" == typeof origin) return "*" === pattern || origin === pattern; - if (src_util_isRegex(origin)) return !1; - if (Array.isArray(origin)) return !1; - } - return src_util_isRegex(pattern) ? src_util_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) : !src_util_isRegex(origin) && pattern.some((function(subpattern) { - return utils_matchDomain(subpattern, origin); - }))); - } - function utils_getDomainFromUrl(url) { - return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain(); - } - function utils_onCloseWindow(win, callback, delay, maxtime) { - void 0 === delay && (delay = 1e3); - void 0 === maxtime && (maxtime = 1 / 0); - var timeout; - !function check() { - if (utils_isWindowClosed(win)) { - timeout && clearTimeout(timeout); - return callback(); - } - if (maxtime <= 0) clearTimeout(timeout); else { - maxtime -= delay; - timeout = setTimeout(check, delay); - } - }(); - return { - cancel: function() { - timeout && clearTimeout(timeout); - } - }; - } - function utils_isWindow(obj) { - try { - if (obj === window) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if ("[object Window]" === {}.toString.call(obj)) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (window.Window && obj instanceof window.Window) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.self === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.parent === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.top === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; - } catch (err) { - return !0; - } - try { - if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; - } catch (err) {} - return !1; - } - function utils_normalizeMockUrl(url) { - if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; - var domain; - throw new Error("Mock urls not supported out of test mode"); - } function lib_global_getGlobal(win) { - if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain"); - win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {}); - return win.__zoid_9_0_87__; + if (!isSameDomain(win)) throw new Error("Can not get global for window on different domain"); + win.__zoid_9_0_88__ || (win.__zoid_9_0_88__ = {}); + return win.__zoid_9_0_88__; } function tryGlobal(win, handler) { try { @@ -3500,10 +3195,7 @@ DOTIFY: "dotify", BASE64: "base64" }; - var CONTEXT = { - IFRAME: "iframe", - POPUP: "popup" - }; + var CONTEXT = WINDOW_TYPE; var EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", @@ -3535,7 +3227,7 @@ sender: { win: function(_ref2) { return function(windowRef) { - if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window)); + if ("opener" === windowRef.type) return assertExists("opener", getOpener(window)); if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) { void 0 === n && (n = 1); return function(win, n) { @@ -3543,19 +3235,19 @@ var parent = win; for (var i = 0; i < n; i++) { if (!parent) return; - parent = src_utils_getParent(parent); + parent = utils_getParent(parent); } return parent; - }(win, utils_getDistanceFromTop(win) - n); + }(win, getDistanceFromTop(win) - n); }(window, windowRef.distance)); if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) { var _ret = function() { var uid = windowRef.uid; - var ancestor = utils_getAncestor(window); + var ancestor = getAncestor(window); if (!ancestor) throw new Error("Can not find ancestor window"); - for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { + for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { var frame = _getAllFramesInWindow2[_i2]; - if (utils_isSameDomain(frame)) { + if (isSameDomain(frame)) { var win = tryGlobal(frame, (function(global) { return global.windows && global.windows[uid]; })); @@ -3569,15 +3261,15 @@ } else if ("name" === windowRef.type) { var name = windowRef.name; return assertExists("namedWindow", function(win, name) { - return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) { - var frame = utils_getFrameByName(win, name); + return getFrameByName(win, name) || function findChildFrameByName(win, name) { + var frame = getFrameByName(win, name); if (frame) return frame; - for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) { - var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name); + for (var _i11 = 0, _getFrames4 = getFrames(win); _i11 < _getFrames4.length; _i11++) { + var namedFrame = findChildFrameByName(_getFrames4[_i11], name); if (namedFrame) return namedFrame; } - }(utils_getTop(win) || win, name); - }(assertExists("ancestor", utils_getAncestor(window)), name)); + }(getTop(win) || win, name); + }(assertExists("ancestor", getAncestor(window)), name)); } throw new Error("Unable to find " + windowRef.type + " parent component window"); }(_ref2.metaData.windowRef); @@ -3595,15 +3287,15 @@ } function window_getWindowRef(targetWindow, currentWindow) { void 0 === currentWindow && (currentWindow = window); - if (targetWindow === src_utils_getParent(currentWindow)) return { + if (targetWindow === utils_getParent(currentWindow)) return { type: "parent", - distance: utils_getDistanceFromTop(targetWindow) + distance: getDistanceFromTop(targetWindow) }; - if (targetWindow === utils_getOpener(currentWindow)) return { + if (targetWindow === getOpener(currentWindow)) return { type: "opener" }; - if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) { - var windowName = utils_assertSameDomain(targetWindow).name; + if (isSameDomain(targetWindow) && !(win = targetWindow, win === getTop(win))) { + var windowName = assertSameDomain(targetWindow).name; if (windowName) return { type: "name", name: windowName @@ -3811,7 +3503,7 @@ for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; - prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]); + prop && !1 === prop.sendToChild || prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window)) || (result[key] = props[key]); } return promise_ZalgoPromise.hash(result); }; @@ -3872,7 +3564,7 @@ }) : attributes; }; var getInitialChildDomain = function() { - return utils_getDomainFromUrl(getUrl()); + return getDomainFromUrl(getUrl()); }; var openFrame = function(context, _ref2) { var windowName = _ref2.windowName; @@ -3906,7 +3598,7 @@ return destroyElement(prerenderFrame); })); return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) { - return utils_assertSameDomain(prerenderFrameWindow); + return assertSameDomain(prerenderFrameWindow); })).then((function(win) { return setup_toProxyWindow(win); })); @@ -3931,7 +3623,7 @@ return uid; }; var getWindowRef = function(target, initialChildDomain, context, proxyWin) { - if (initialChildDomain === utils_getDomain(window)) return { + if (initialChildDomain === getDomain(window)) return { type: "global", uid: getCurrentWindowReferenceUID() }; @@ -3939,14 +3631,14 @@ if (props.window) { var actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop"); - if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); + if (getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); } if (context === CONTEXT.POPUP) return { type: "opener" }; if (context === CONTEXT.IFRAME) return { type: "parent", - distance: utils_getDistanceFromTop(window) + distance: getDistanceFromTop(window) }; throw new Error("Can not construct window reference for child"); }; @@ -3981,7 +3673,7 @@ var close = memoize((function(err) { return promise_ZalgoPromise.try((function() { if (closeOverride) { - if (utils_isWindowClosed(closeOverride.__source__)) return; + if (isWindowClosed(closeOverride.__source__)) return; return closeOverride(); } return promise_ZalgoPromise.try((function() { @@ -4058,27 +3750,7 @@ height: height }, getAttributes().popup)); clean.register((function() { - return function(win) { - if (function(win) { - void 0 === win && (win = window); - return Boolean(src_utils_getParent(win)); - }(win)) { - var frame = function(win) { - if (utils_isSameDomain(win)) return utils_assertSameDomain(win).frameElement; - for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { - var frame = _document$querySelect2[_i21]; - if (frame && frame.contentWindow && frame.contentWindow === win) return frame; - } - }(win); - if (frame && frame.parentElement) { - frame.parentElement.removeChild(frame); - return; - } - } - try { - win.close(); - } catch (err) {} - }(win); + return closeWindow(win); })); clean.register((function() { return cleanUpWindow(win); @@ -4100,7 +3772,7 @@ var unloadWindowListener = addEventListener(window, "unload", once((function() { destroy(new Error("Window navigated away")); }))); - var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3); + var closeParentWindowListener = onCloseWindow(parentWin, destroy, 3e3); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) return watchForUnloadOverride(); @@ -4165,14 +3837,14 @@ }) : promise_ZalgoPromise.try((function() { if (prerenderTemplate) { var prerenderWindow = proxyPrerenderWin.getWindow(); - if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) { + if (prerenderWindow && isSameDomain(prerenderWindow) && function(win) { try { if (!win.location.href) return !0; if ("about:blank" === win.location.href) return !0; } catch (err) {} return !1; }(prerenderWindow)) { - var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document; + var doc = (prerenderWindow = assertSameDomain(prerenderWindow)).document; var el = renderTemplate(prerenderTemplate, { context: context, doc: doc @@ -4456,22 +4128,9 @@ var childDomainMatch = domainMatch || getInitialChildDomain(); !function(target, childDomainMatch, container) { if (target !== window) { - if (!function(win1, win2) { - var top1 = utils_getTop(win1) || win1; - var top2 = utils_getTop(win2) || win2; - try { - if (top1 && top2) return top1 === top2; - } catch (err) {} - var allFrames1 = utils_getAllFramesInWindow(win1); - var allFrames2 = utils_getAllFramesInWindow(win2); - if (utils_anyMatch(allFrames1, allFrames2)) return !0; - var opener1 = utils_getOpener(top1); - var opener2 = utils_getOpener(top2); - return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1), - !1; - }(window, target)) throw new Error("Can only renderTo an adjacent frame"); - var origin = utils_getDomain(); - if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); + if (!isSameTopWindow(window, target)) throw new Error("Can only renderTo an adjacent frame"); + var origin = getDomain(); + if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }"); } }(target, childDomainMatch, container); @@ -4498,7 +4157,7 @@ }).then((function(_ref13) { var parentComp = _ref13.data.parent; clean.register((function(err) { - if (!utils_isWindowClosed(target)) return parentComp.destroy(err); + if (!isWindowClosed(target)) return parentComp.destroy(err); })); return parentComp.getDelegateOverrides(); })).catch((function(err) { @@ -4605,7 +4264,7 @@ queryString && (originalUrl = originalUrl + "?" + queryString); hashString && (originalUrl = originalUrl + "#" + hashString); return originalUrl; - }(utils_normalizeMockUrl(getUrl()), { + }(normalizeMockUrl(getUrl()), { query: query }); })); @@ -4621,7 +4280,7 @@ context: context, tag: tag, childDomainMatch: childDomainMatch, - version: "9_0_87", + version: "9_0_88", props: childProps, exports: (win = proxyWin, { init: function(childExports) { @@ -4652,13 +4311,13 @@ windowRef: getWindowRef(target, initialChildDomain, context, proxyWin) }, sender: { - domain: utils_getDomain(window) + domain: getDomain(window) }, receiver: { win: proxyWin, domain: childDomainMatch }, - passByReference: initialChildDomain === utils_getDomain() + passByReference: initialChildDomain === getDomain() }), serializedData = _crossDomainSerialize.serializedData; clean.register(_crossDomainSerialize.cleanReference); return serializedData; @@ -4789,9 +4448,9 @@ props: props }) : options.bridgeUrl; if (!bridgeUrl) throw new Error("Bridge needed to render " + context); - var bridgeDomain = utils_getDomainFromUrl(bridgeUrl); + var bridgeDomain = getDomainFromUrl(bridgeUrl); src_bridge.linkUrl(win, initialChildDomain); - return src_bridge.openBridge(utils_normalizeMockUrl(bridgeUrl), bridgeDomain); + return src_bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain); } })); }(proxyWin, initialChildDomain, context); @@ -4886,7 +4545,7 @@ _proto.componentDidMount = function() { var el = ReactDOM.findDOMNode(this); var parent = init(extend({}, this.props)); - parent.render(el); + parent.render(el, this.props.context); this.setState({ parent: parent }); @@ -4916,7 +4575,7 @@ return acc; }), {})))); var props; - this.parent.render(el); + this.parent.render(el, this.$attrs.context); }, watch: { $attrs: { @@ -4945,7 +4604,7 @@ return acc; }), {})))); var props; - this.parent.render(el); + this.parent.render(el, this.$attrs.context); }, watch: { $attrs: { @@ -4982,8 +4641,9 @@ } : item; })); }; - var instance = init(getProps()); - instance.render($element[0]); + var props = getProps(); + var instance = init(props); + instance.render($element[0], props.context); $scope.$watch((function() { instance.updateProps(getProps()).catch(src_util_noop); })); @@ -5025,8 +4685,9 @@ }; _proto.ngOnInit = function() { var targetElement = this.elementRef.nativeElement; - this.parent = init(this.getProps()); - this.parent.render(targetElement); + var props = this.getProps(); + this.parent = init(props); + this.parent.render(targetElement, props.context); }; _proto.ngDoCheck = function() { if (this.parent && !function(obj1, obj2) { @@ -5128,10 +4789,10 @@ allowDelegate: !0, validate: function(_ref2) { var value = _ref2.value; - if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); - if (utils_isWindow(value)) { - if (utils_isWindowClosed(value)) throw new Error("Window is closed"); - if (!utils_isSameDomain(value)) throw new Error("Window is not same domain"); + if (!isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); + if (isWindow(value)) { + if (isWindowClosed(value)) throw new Error("Window is closed"); + if (!isSameDomain(value)) throw new Error("Window is not same domain"); } }, decorate: function(_ref3) { @@ -5147,6 +4808,10 @@ type: PROP_TYPE.STRING, required: !1 }, + context: { + type: PROP_TYPE.STRING, + required: !1 + }, onDisplay: { type: PROP_TYPE.FUNCTION, required: !1, @@ -5357,7 +5022,7 @@ return !1; }(name)) { var _payload = getInitialParentPayload().payload; - if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0; + if (_payload.tag === tag && matchDomain(_payload.childDomainMatch, getDomain())) return !0; } return !1; }; @@ -5375,7 +5040,7 @@ var props; var exportsPromise = new promise_ZalgoPromise; var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props; - if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87"); + if ("9_0_88" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_88"); var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init; var getParent = function() { return parentComponentWindow; @@ -5407,10 +5072,10 @@ var currentParent = props.parent; void 0 === anyParent && (anyParent = !currentParent); if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child"); - for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { + for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { var win = _getAllFramesInWindow2[_i2]; - if (utils_isSameDomain(win)) { - var xprops = utils_assertSameDomain(win).xprops; + if (isSameDomain(win)) { + var xprops = assertSameDomain(win).xprops; if (xprops && getParent() === xprops.getParent()) { var winParent = xprops.parent; if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) { @@ -5435,7 +5100,7 @@ for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; - if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) { + if (!prop || !prop.sameDomain || origin === getDomain(window) && isSameDomain(parentComponentWindow)) { var value = normalizeChildProp(propsDef, 0, key, props[key], helpers); result[key] = value; prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value); @@ -5472,7 +5137,7 @@ return { init: function() { return promise_ZalgoPromise.try((function() { - utils_isSameDomain(parentComponentWindow) && function(_ref3) { + isSameDomain(parentComponentWindow) && function(_ref3) { var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow; var _crossDomainDeseriali2 = crossDomainDeserialize({ data: parseWindowName(window.name).serializedInitialPayload, @@ -5492,7 +5157,7 @@ }, receiver: { win: window, - domain: utils_getDomain() + domain: getDomain() }, basic: !0 }); @@ -5511,7 +5176,7 @@ } }); !function(allowedParentDomains, domain) { - if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); + if (!matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); }(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); !function() { @@ -5521,7 +5186,7 @@ window.addEventListener("unload", (function() { checkClose.fireAndForget(); })); - utils_onCloseWindow(parentComponentWindow, (function() { + onCloseWindow(parentComponentWindow, (function() { child_destroy(); })); }(); @@ -5599,7 +5264,7 @@ throw err; })); } - if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo"); + if (!isWindow(target)) throw new Error("Must pass window to renderTo"); return function(props, context) { return promise_ZalgoPromise.try((function() { if (props.window) return setup_toProxyWindow(props.window).getType(); @@ -5823,7 +5488,7 @@ var destroyAll = destroyComponents; function component_destroy(err) { destroyAll(); - delete window.__zoid_9_0_87__; + delete window.__zoid_9_0_88__; !function() { !function() { var responseListeners = globalStore("responseListeners"); diff --git a/dist/zoid.frameworks.min.js b/dist/zoid.frameworks.min.js index f5fe663e..c927997b 100644 --- a/dist/zoid.frameworks.min.js +++ b/dist/zoid.frameworks.min.js @@ -1,2 +1,2 @@ -!function(n,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("zoid",[],e):"object"==typeof exports?exports.zoid=e():n.zoid=e()}("undefined"!=typeof self?self:this,(function(){return function(n){var e={};function r(t){if(e[t])return e[t].exports;var o=e[t]={i:t,l:!1,exports:{}};return n[t].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=n,r.c=e,r.d=function(n,e,t){r.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:t})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,e){if(1&e&&(n=r(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var t=Object.create(null);if(r.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)r.d(t,o,function(e){return n[e]}.bind(null,o));return t},r.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(e,"a",e),e},r.o=function(n,e){return{}.hasOwnProperty.call(n,e)},r.p="",r(r.s=0)}([function(n,e,r){"use strict";function t(n,e){return(t=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function o(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,t(n,e)}function i(){return(i=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+hn(n,e+1)}}function wn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function pn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function vn(n){return n}function mn(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function yn(n){return n.replace(/-([a-z])/g,(function(n){return n[1].toUpperCase()}))}function gn(n,e,r){if(Array.isArray(n)){if("number"!=typeof e)throw new TypeError("Array key must be number")}else if("object"==typeof n&&null!==n&&"string"!=typeof e)throw new TypeError("Object key must be string");Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get:function(){delete n[e];var t=r();return n[e]=t,t},set:function(r){delete n[e],n[e]=r}})}function bn(n){return[].slice.call(n)}function En(n){return"object"==typeof(e=n)&&null!==e&&"[object Object]"==={}.toString.call(n);var e}function _n(n){if(!En(n))return!1;var e=n.constructor;if("function"!=typeof e)return!1;var r=e.prototype;return!!En(r)&&!!r.hasOwnProperty("isPrototypeOf")}function xn(n,e,r){if(void 0===r&&(r=""),Array.isArray(n)){for(var t=n.length,o=[],i=function(t){gn(o,t,(function(){var o=r?r+"."+t:""+t,i=e(n[t],t,o);return(_n(i)||Array.isArray(i))&&(i=xn(i,e,o)),i}))},a=0;a { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||tn();n=Le.unwrap(n);var s=r.__name__||r.name||t;return"string"==typeof s&&"function"==typeof s.indexOf&&0===s.indexOf("anonymous::")&&(s=s.replace("anonymous::",t+"::")),Le.isProxyWindow(n)?(Be(c,r,s,n,e),n.awaitWindow().then((function(n){Be(c,r,s,n,e)}))):Be(c,r,s,n,e),be("cross_domain_function",{id:c,name:s})}function Je(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=xe);var r=JSON.stringify(n,(function(n){var r=this[n];if(ye(this))return r;var t=ge(r);if(!t)return r;var o=e[t]||_e[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return be("cross_domain_zalgo_promise",{then:$e(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return $e(n,e,r,t,{on:i,send:a})},o.object=function(n){return q(n)||Le.isProxyWindow(n)?be("cross_domain_window",Le.serialize(n,{send:a})):n},o))}function He(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=Oe),"undefined"!==n)return JSON.parse(n,(function(n,r){if(ye(this))return r;var t,o;if(ye(r)?(t=r.__type__,o=r.__val__):(t=ge(r),o=r),!t)return o;var i=e[t]||Pe[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new w(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return Le.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=qe(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:P()},u);var s=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:s},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:s},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return Le.deserialize(n,{send:i})},o))}var Ye={};function Ze(n,e,r,t){var o=t.on,i=t.send;return w.try((function(){var t=de().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||w.flush().then((function(){if(k(n))throw new Error("Window is closed");var r,a=Je(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(Ye),c=[],s=0;s1?e-1:0),o=1;o1?r-1:0),i=1;i",inheritAttrs:!1,mounted:function(){var n,e=this.$el;this.parent=r(i({},(n=this.$attrs,Object.keys(n).reduce((function(e,r){var t=n[r];return"style-object"===r||"styleObject"===r?(e.style=t,e.styleObject=t):r.includes("-")?e[yn(r)]=t:e[r]=t,e}),{})))),this.parent.render(e,Jr.IFRAME)},watch:{$attrs:{handler:function(){this.parent&&this.$attrs&&this.parent.updateProps(i({},this.$attrs)).catch(dn)},deep:!0}}}}},st={register:function(n,e,r,t){return t.module(n,[]).directive(yn(n),(function(){for(var n={},t=0,o=Object.keys(e);t",inputs:["props"]})];var d=function(){};return d.annotations=void 0,d.annotations=[new a({declarations:[f],exports:[f]})],d}};function dt(n){var e=n.uid,r=n.frame,t=n.prerenderFrame,o=n.doc,i=n.props,a=n.event,u=n.dimensions,c=u.width,s=u.height;if(r&&t){var f=o.createElement("div");f.setAttribute("id",e);var d=o.createElement("style");return i.cspNonce&&d.setAttribute("nonce",i.cspNonce),d.appendChild(o.createTextNode("\n #"+e+" {\n display: inline-block;\n position: relative;\n width: "+c+";\n height: "+s+";\n }\n\n #"+e+" > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),f.appendChild(r),f.appendChild(t),f.appendChild(d),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(Hr.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){Yn(t)}),1)})),a.on(Hr.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(f.style.width=te(e)),"number"==typeof r&&(f.style.height=te(r))})),f}}function lt(n){var e=n.doc,r=n.props,t=e.createElement("html"),o=e.createElement("body"),i=e.createElement("style"),a=e.createElement("div");return a.classList.add("spinner"),r.cspNonce&&i.setAttribute("nonce",r.cspNonce),t.appendChild(o),o.appendChild(a),o.appendChild(i),i.appendChild(e.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")),t}var ht=Wn(),wt=Wn();function pt(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,s=void 0===c?{}:c,f=n.autoResize,d=void 0===f?{}:f,l=n.allowedParentDomains,h=void 0===l?"*":l,w=n.attributes,p=void 0===w?{}:w,v=n.defaultContext,m=void 0===v?Jr.IFRAME:v,y=n.containerTemplate,g=void 0===y?dt:y,b=n.prerenderTemplate,E=void 0===b?lt:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,C=void 0===O?{info:dn}:O,W=n.exports,S=void 0===W?dn:W,D=n.method,j=n.children,A=void 0===j?function(){return{}}:j,N=e.replace(/-/g,"_"),R=i({},{window:{type:qr.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!kr(e)&&!Le.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(kr(e)){if(Cr(e))throw new Error("Window is closed");if(!mr(e))throw new Error("Window is not same domain")}},decorate:function(n){return ar(n.value)}},timeout:{type:qr.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:qr.STRING,required:!1},onDisplay:{type:qr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:et,decorate:rt},onRendered:{type:qr.FUNCTION,required:!1,sendToChild:!1,default:et,decorate:rt},onRender:{type:qr.FUNCTION,required:!1,sendToChild:!1,default:et,decorate:rt},onClose:{type:qr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:et,decorate:rt},onDestroy:{type:qr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:et,decorate:rt},onResize:{type:qr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:et},onFocus:{type:qr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:et},close:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:qr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:qr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:qr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:N,tag:e,url:r,domain:t,bridgeUrl:o,method:D,propsDef:R,dimensions:s,autoResize:d,allowedParentDomains:h,attributes:p,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:C,eligible:P,children:A,exports:"function"==typeof S?S:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=S[o].type,a=e().then((function(n){return n[o]}));r[o]=i===qr.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+mn(n,e+1)}}function yn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function gn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function bn(n){return n}function En(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function _n(n){return n.replace(/-([a-z])/g,(function(n){return n[1].toUpperCase()}))}function xn(n,e,r){if(Array.isArray(n)){if("number"!=typeof e)throw new TypeError("Array key must be number")}else if("object"==typeof n&&null!==n&&"string"!=typeof e)throw new TypeError("Object key must be string");Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get:function(){delete n[e];var t=r();return n[e]=t,t},set:function(r){delete n[e],n[e]=r}})}function Pn(n){return[].slice.call(n)}function On(n){return"object"==typeof(e=n)&&null!==e&&"[object Object]"==={}.toString.call(n);var e}function Cn(n){if(!On(n))return!1;var e=n.constructor;if("function"!=typeof e)return!1;var r=e.prototype;return!!On(r)&&!!r.hasOwnProperty("isPrototypeOf")}function Wn(n,e,r){if(void 0===r&&(r=""),Array.isArray(n)){for(var t=n.length,o=[],i=function(t){xn(o,t,(function(){var o=r?r+"."+t:""+t,i=e(n[t],t,o);return(Cn(i)||Array.isArray(i))&&(i=Wn(i,e,o)),i}))},a=0;a { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||cn();n=Je.unwrap(n);var s=r.__name__||r.name||t;return"string"==typeof s&&"function"==typeof s.indexOf&&0===s.indexOf("anonymous::")&&(s=s.replace("anonymous::",t+"::")),Je.isProxyWindow(n)?(He(c,r,s,n,e),n.awaitWindow().then((function(n){He(c,r,s,n,e)}))):He(c,r,s,n,e),Pe("cross_domain_function",{id:c,name:s})}function Ge(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=We);var r=JSON.stringify(n,(function(n){var r=this[n];if(_e(this))return r;var t=xe(r);if(!t)return r;var o=e[t]||Ce[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return Pe("cross_domain_zalgo_promise",{then:Ze(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return Ze(n,e,r,t,{on:i,send:a})},o.object=function(n){return H(n)||Je.isProxyWindow(n)?Pe("cross_domain_window",Je.serialize(n,{send:a})):n},o))}function Ve(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=De),"undefined"!==n)return JSON.parse(n,(function(n,r){if(_e(this))return r;var t,o;if(_e(r)?(t=r.__type__,o=r.__val__):(t=xe(r),o=r),!t)return o;var i=e[t]||Se[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new w(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return Je.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=Ye(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:O()},u);var s=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:s},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:s},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return Je.deserialize(n,{send:i})},o))}var Xe={};function Ke(n,e,r,t){var o=t.on,i=t.send;return w.try((function(){var t=pe().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||w.flush().then((function(){if(k(n))throw new Error("Window is closed");var r,a=Ge(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(Xe),c=[],s=0;s1?e-1:0),o=1;o1?r-1:0),i=1;i",inheritAttrs:!1,mounted:function(){var n,e=this.$el;this.parent=r(i({},(n=this.$attrs,Object.keys(n).reduce((function(e,r){var t=n[r];return"style-object"===r||"styleObject"===r?(e.style=t,e.styleObject=t):r.includes("-")?e[_n(r)]=t:e[r]=t,e}),{})))),this.parent.render(e,this.$attrs.context)},watch:{$attrs:{handler:function(){this.parent&&this.$attrs&&this.parent.updateProps(i({},this.$attrs)).catch(pn)},deep:!0}}}}},Mr={register:function(n,e,r,t){return t.module(n,[]).directive(_n(n),(function(){for(var n={},t=0,o=Object.keys(e);t",inputs:["props"]})];var f=function(){};return f.annotations=void 0,f.annotations=[new a({declarations:[d],exports:[d]})],f}};function Lr(n){var e=n.uid,r=n.frame,t=n.prerenderFrame,o=n.doc,i=n.props,a=n.event,u=n.dimensions,c=u.width,s=u.height;if(r&&t){var d=o.createElement("div");d.setAttribute("id",e);var f=o.createElement("style");return i.cspNonce&&f.setAttribute("nonce",i.cspNonce),f.appendChild(o.createTextNode("\n #"+e+" {\n display: inline-block;\n position: relative;\n width: "+c+";\n height: "+s+";\n }\n\n #"+e+" > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),d.appendChild(r),d.appendChild(t),d.appendChild(f),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(_r.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){Xn(t)}),1)})),a.on(_r.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(d.style.width=ue(e)),"number"==typeof r&&(d.style.height=ue(r))})),d}}function qr(n){var e=n.doc,r=n.props,t=e.createElement("html"),o=e.createElement("body"),i=e.createElement("style"),a=e.createElement("div");return a.classList.add("spinner"),r.cspNonce&&i.setAttribute("nonce",r.cspNonce),t.appendChild(o),o.appendChild(a),o.appendChild(i),i.appendChild(e.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")),t}var Br=jn(),$r=jn();function Jr(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,s=void 0===c?{}:c,d=n.autoResize,f=void 0===d?{}:d,l=n.allowedParentDomains,h=void 0===l?"*":l,w=n.attributes,p=void 0===w?{}:w,v=n.defaultContext,m=void 0===v?Er.IFRAME:v,y=n.containerTemplate,g=void 0===y?Lr:y,b=n.prerenderTemplate,E=void 0===b?qr:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,W=void 0===O?{info:pn}:O,S=n.exports,D=void 0===S?pn:S,N=n.method,j=n.children,A=void 0===j?function(){return{}}:j,R=e.replace(/-/g,"_"),T=i({},{window:{type:gr.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!H(e)&&!Je.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(H(e)){if(k(e))throw new Error("Window is closed");if(!C(e))throw new Error("Window is not same domain")}},decorate:function(n){return dr(n.value)}},timeout:{type:gr.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:gr.STRING,required:!1},context:{type:gr.STRING,required:!1},onDisplay:{type:gr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr,decorate:Ar},onRendered:{type:gr.FUNCTION,required:!1,sendToChild:!1,default:jr,decorate:Ar},onRender:{type:gr.FUNCTION,required:!1,sendToChild:!1,default:jr,decorate:Ar},onClose:{type:gr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr,decorate:Ar},onDestroy:{type:gr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr,decorate:Ar},onResize:{type:gr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr},onFocus:{type:gr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:jr},close:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:gr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:gr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:gr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:R,tag:e,url:r,domain:t,bridgeUrl:o,method:N,propsDef:T,dimensions:s,autoResize:f,allowedParentDomains:h,attributes:p,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:W,eligible:P,children:A,exports:"function"==typeof D?D:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=D[o].type,a=e().then((function(n){return n[o]}));r[o]=i===gr.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer,\n undefined? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull,\n [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull,\n deserializeUndefined\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer,\n undefined? : PrimitiveDeserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull,\n [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady : ZalgoPromise = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, getFrameByName, isWindowClosed, getDomainFromUrl, normalizeMockUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { BRIDGE_TIMEOUT, MESSAGE_NAME } from '../conf';\nimport { awaitWindowHello } from '../lib';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { getBridgeName, documentBodyReady, registerRemoteSendMessage, registerRemoteWindow } from './common';\n\ntype WinDetails = {|\n win : CrossDomainWindowType,\n domain? : ?string,\n name? : ?string\n|};\n\nexport function listenForOpenTunnel({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n const popupWindowsByName = globalStore('popupWindowsByName');\n\n on(MESSAGE_NAME.OPEN_TUNNEL, ({ source, origin, data }) => {\n const bridgePromise = globalStore('bridges').get(origin);\n\n if (!bridgePromise) {\n throw new Error(`Can not find bridge promise for domain ${ origin }`);\n }\n\n return bridgePromise.then(bridge => {\n if (source !== bridge) {\n throw new Error(`Message source does not matched registered bridge for domain ${ origin }`);\n }\n\n if (!data.name) {\n throw new Error(`Register window expected to be passed window name`);\n }\n\n if (!data.sendMessage) {\n throw new Error(`Register window expected to be passed sendMessage method`);\n }\n\n if (!popupWindowsByName.has(data.name)) {\n throw new Error(`Window with name ${ data.name } does not exist, or was not opened by this window`);\n }\n\n const getWindowDetails = () : WinDetails => {\n const winDetails = popupWindowsByName.get(data.name);\n // $FlowFixMe\n return winDetails;\n };\n\n if (!getWindowDetails().domain) {\n throw new Error(`We do not have a registered domain for window ${ data.name }`);\n }\n\n if (getWindowDetails().domain !== origin) {\n throw new Error(`Message origin ${ origin } does not matched registered window origin ${ getWindowDetails().domain || 'unknown' }`);\n }\n\n registerRemoteSendMessage(getWindowDetails().win, origin, data.sendMessage);\n\n return {\n sendMessage(message) {\n\n if (!window || window.closed) {\n return;\n }\n\n if (!getWindowDetails()) {\n return;\n }\n\n const domain = getWindowDetails().domain;\n\n if (!domain) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n origin: domain,\n source: getWindowDetails().win\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n };\n });\n });\n}\n\nfunction openBridgeFrame(name : string, url : string) : HTMLIFrameElement {\n\n const iframe = document.createElement(`iframe`);\n\n iframe.setAttribute(`name`, name);\n iframe.setAttribute(`id`, name);\n\n iframe.setAttribute(`style`, `display: none; margin: 0; padding: 0; border: 0px none; overflow: hidden;`);\n iframe.setAttribute(`frameborder`, `0`);\n iframe.setAttribute(`border`, `0`);\n iframe.setAttribute(`scrolling`, `no`);\n iframe.setAttribute(`allowTransparency`, `true`);\n\n iframe.setAttribute(`tabindex`, `-1`);\n iframe.setAttribute(`hidden`, `true`);\n iframe.setAttribute(`title`, ``);\n iframe.setAttribute(`role`, `presentation`);\n\n iframe.src = url;\n\n return iframe;\n}\n\nexport function hasBridge(url : string, domain : string) : boolean {\n const bridges = globalStore('bridges');\n return bridges.has(domain || getDomainFromUrl(url));\n}\n\nexport function openBridge(url : string, domain : string) : ZalgoPromise {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n \n domain = domain || getDomainFromUrl(url);\n \n return bridges.getOrSet(domain, () => ZalgoPromise.try(() => {\n\n if (getDomain() === domain) {\n throw new Error(`Can not open bridge on the same domain as current domain: ${ domain }`);\n }\n\n const name = getBridgeName(domain);\n const frame = getFrameByName(window, name);\n\n if (frame) {\n throw new Error(`Frame with name ${ name } already exists on page`);\n }\n\n const iframe = openBridgeFrame(name, url);\n bridgeFrames.set(domain, iframe);\n\n return documentBodyReady.then(body => {\n\n body.appendChild(iframe);\n const bridge = iframe.contentWindow;\n\n return new ZalgoPromise((resolve, reject) => {\n\n iframe.addEventListener('load', resolve);\n iframe.addEventListener('error', reject);\n\n }).then(() => {\n\n return awaitWindowHello(bridge, BRIDGE_TIMEOUT, `Bridge ${ url }`);\n\n }).then(() => {\n\n return bridge;\n });\n });\n }));\n}\n\nexport function linkWindow({ win, name, domain } : WinDetails) : WinDetails {\n const popupWindowsByName = globalStore('popupWindowsByName');\n const popupWindowsByWin = windowStore('popupWindowsByWin');\n\n for (const winName of popupWindowsByName.keys()) {\n const details = popupWindowsByName.get(winName);\n if (!details || isWindowClosed(details.win)) {\n popupWindowsByName.del(winName);\n }\n }\n\n if (isWindowClosed(win)) {\n return { win, name, domain };\n }\n\n const details = popupWindowsByWin.getOrSet(win, () : WinDetails => {\n if (!name) {\n return { win };\n }\n \n // $FlowFixMe\n return popupWindowsByName.getOrSet(name, () : WinDetails => {\n return { win, name };\n });\n });\n\n if (details.win && details.win !== win) {\n throw new Error(`Different window already linked for window: ${ name || 'undefined' }`);\n }\n\n if (name) {\n details.name = name;\n popupWindowsByName.set(name, details);\n }\n\n if (domain) {\n details.domain = domain;\n registerRemoteWindow(win);\n }\n\n popupWindowsByWin.set(win, details);\n \n return details;\n}\n\nexport function linkUrl(win : CrossDomainWindowType, url : string) {\n linkWindow({ win, domain: getDomainFromUrl(url) });\n}\n\nexport function listenForWindowOpen() {\n const windowOpen = window.open;\n\n window.open = function windowOpenWrapper(url : string, name : string, options : string, last : mixed) : mixed {\n const win = windowOpen.call(this, normalizeMockUrl(url), name, options, last);\n \n if (!win) {\n return win;\n }\n \n linkWindow({ win, name, domain: url ? getDomainFromUrl(url) : null });\n \n return win;\n };\n}\n\nexport function destroyBridges() {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n\n for (const domain of bridgeFrames.keys()) {\n const frame = bridgeFrames.get(domain);\n if (frame && frame.parentNode) {\n frame.parentNode.removeChild(frame);\n }\n }\n bridgeFrames.reset();\n bridges.reset();\n}\n","/* @flow */\n\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { listenForWindowOpen, listenForOpenTunnel } from './parent';\nimport { setupOpenTunnelToParent } from './bridge';\nimport { openTunnelToOpener } from './child';\n\nexport function setupBridge({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n listenForWindowOpen();\n listenForOpenTunnel({ on, send, receiveMessage });\n setupOpenTunnelToParent({ send });\n openTunnelToOpener({ on, send, receiveMessage });\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { getParent, isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { getGlobal, globalStore } from '../global';\nimport type { SendType, ResponseMessageEvent } from '../types';\n\nfunction cleanTunnelWindows() {\n const tunnelWindows = globalStore('tunnelWindows');\n\n for (const key of tunnelWindows.keys()) {\n const tunnelWindow = tunnelWindows[key];\n\n try {\n noop(tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(key);\n continue;\n }\n\n if (isWindowClosed(tunnelWindow.source)) {\n tunnelWindows.del(key);\n }\n }\n}\n\ntype TunnelWindowDataType = {|\n name : string,\n source : CrossDomainWindowType,\n canary : () => void,\n sendMessage : (message : string) => void\n|};\n\nfunction addTunnelWindow({ name, source, canary, sendMessage } : TunnelWindowDataType) : string {\n cleanTunnelWindows();\n const id = uniqueID();\n const tunnelWindows = globalStore('tunnelWindows');\n tunnelWindows.set(id, { name, source, canary, sendMessage });\n return id;\n}\n\nexport function setupOpenTunnelToParent({ send } : {| send : SendType |}) {\n getGlobal(window).openTunnelToParent = function openTunnelToParent({ name, source, canary, sendMessage } : TunnelWindowDataType) : ZalgoPromise {\n\n const tunnelWindows = globalStore('tunnelWindows');\n const parentWindow = getParent(window);\n \n if (!parentWindow) {\n throw new Error(`No parent window found to open tunnel to`);\n }\n \n const id = addTunnelWindow({ name, source, canary, sendMessage });\n \n return send(parentWindow, MESSAGE_NAME.OPEN_TUNNEL, {\n \n name,\n \n sendMessage() {\n \n const tunnelWindow = tunnelWindows.get(id);\n \n try {\n // IE gets antsy if you try to even reference a closed window\n noop(tunnelWindow && tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(id);\n return;\n }\n \n if (!tunnelWindow || !tunnelWindow.source || isWindowClosed(tunnelWindow.source)) {\n return;\n }\n \n try {\n tunnelWindow.canary();\n } catch (err) {\n return;\n }\n \n // $FlowFixMe[object-this-reference]\n tunnelWindow.sendMessage.apply(this, arguments);\n }\n \n }, { domain: WILDCARD });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isSameDomain, getOpener, getDomain, getFrameByName, assertSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { getGlobal, windowStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { needsBridge, registerRemoteWindow, rejectRemoteSendMessage, registerRemoteSendMessage, getBridgeName } from './common';\n\nfunction awaitRemoteBridgeForWindow (win : CrossDomainWindowType) : ZalgoPromise {\n return windowStore('remoteBridgeAwaiters').getOrSet(win, () => {\n return ZalgoPromise.try(() => {\n const frame = getFrameByName(win, getBridgeName(getDomain()));\n\n if (!frame) {\n return;\n }\n\n if (isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n return frame;\n }\n\n return new ZalgoPromise(resolve => {\n\n let interval;\n let timeout; // eslint-disable-line prefer-const\n\n interval = setInterval(() => { // eslint-disable-line prefer-const\n if (frame && isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n clearInterval(interval);\n clearTimeout(timeout);\n return resolve(frame);\n }\n }, 100);\n\n timeout = setTimeout(() => {\n clearInterval(interval);\n return resolve();\n }, 2000);\n });\n });\n });\n}\n\nexport function openTunnelToOpener({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const opener = getOpener(window);\n \n if (!opener || !needsBridge({ win: opener })) {\n return;\n }\n\n registerRemoteWindow(opener);\n\n return awaitRemoteBridgeForWindow(opener).then(bridge => {\n\n if (!bridge) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: no bridge found in opener`));\n }\n\n if (!window.name) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: window does not have a name`));\n }\n\n return getGlobal(assertSameDomain(bridge)).openTunnelToParent({\n\n name: window.name,\n\n source: window,\n\n canary() {\n // pass\n },\n\n sendMessage(message) {\n\n try {\n noop(window);\n } catch (err) {\n return;\n }\n\n if (!window || window.closed) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n // $FlowFixMe[object-this-reference]\n origin: this.origin,\n // $FlowFixMe[object-this-reference]\n source: this.source\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n\n }).then(({ source, origin, data }) => {\n\n if (source !== opener) {\n throw new Error(`Source does not match opener`);\n }\n\n registerRemoteSendMessage(source, origin, data.sendMessage);\n\n }).catch(err => {\n\n rejectRemoteSendMessage(opener, err);\n throw err;\n });\n });\n });\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SetLocationOptions = {|\n method? : $Values,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n const getName = () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n });\n\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n\n } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name, 'noopener');\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n // $FlowFixMe[method-unbinding]\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\ntype SendStrategies = {|\n [$Values] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore, getGlobalKey } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n const strDomain = domain.toString();\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n}\n\nexport function handleAck(source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n}\n\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[getGlobalKey()];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n if (isWindowClosed(source)) {\n return;\n }\n\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise = ZalgoPromise & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport { ProxyWindow } from '../serialize/window';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (winOrProxyWin, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n });\n};\n","/* @flow */\n\nimport { setup } from './setup';\nimport { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge, needsBridgeForBrowser, hasBridge,\n needsBridgeForWin, needsBridgeForDomain, destroyBridges } from './bridge';\n\nexport { ZalgoPromise as Promise } from 'zalgo-promise/src';\n\nexport * from './types';\nexport { ProxyWindow } from './serialize';\nexport { setup, destroy, serializeMessage, deserializeMessage, createProxyWindow, toProxyWindow } from './setup';\nexport { on, once, send } from './public';\nexport { markWindowKnown } from './lib';\nexport { cleanUpWindow } from './clean';\n\n// $FlowFixMe\nexport let bridge;\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n bridge = { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge,\n needsBridgeForBrowser, hasBridge, needsBridgeForWin, needsBridgeForDomain, destroyBridges };\n}\n\nif (__POST_ROBOT__.__AUTO_SETUP__) {\n setup();\n}\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT : number = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from '@krakenjs/cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n\nexport function basicSerialize(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType =\n UIDReferenceType |\n RawReferenceType;\n\nexport function getUIDRefStore(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef(val : T) : ReferenceType {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef(val : T) : ReferenceType {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue(win : CrossDomainWindowType, ref : ReferenceType) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef(win : CrossDomainWindowType, ref : ReferenceType) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType\n|};\n\ntype CrossDomainSerializeOptions = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType\n|};\n\nexport function crossDomainDeserialize({ data, sender, basic = false } : CrossDomainDeserializeOptions) : CrossDomainDeserializedMessage {\n const message : Message = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from '@krakenjs/cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: ('string' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from '@krakenjs/cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = windowName.split('__');\n\n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n\n if (!name) {\n throw new Error(`Expected component name`);\n }\n\n if (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload,\n reference : ReferenceType\n|};\n\nconst parseInitialParentPayload = memoize((windowName : string) : InitialParentPayload => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload() : InitialParentPayload {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType, props : PropsType

, origin : string, helpers : ChildHelpers, isUpdate : boolean = false) : ChildPropsType {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise,\n getSiblings : getSiblingsPropType\n|};\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent = {|\n getProps : () => ChildPropsType,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent(options : NormalizedComponentOptionsType) : ChildComponent {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return getAutoResize().then(({ width, height, element }) => {\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type exportPropType = (X) => ZalgoPromise;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType

,\n export : exportPropType\n|};\n\nexport type PropsInputType

= {|\n parent? : ParentPropType,\n \n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : ?cspNoncePropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

,\n\n ...P\n|};\n\nexport type PropsType

= {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n dimensions : CssDimensionsType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise;\n\nexport type ChildPropsType = {|\n ...PropsType

,\n\n parent? : ParentPropType,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType

,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n // eslint-disable-next-line no-undef\n queryValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P, X> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType = {|\n [string] : MixedPropDefinitionType\n|};\n\nexport type BuiltInPropsDefinitionType = {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n uid : StringPropDefinitionType,\n tag : StringPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n export : FunctionPropDefinitionType, P, X>,\n getSiblings : FunctionPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P, X>\n|};\n\nexport type PropsDefinitionType = {|\n ...BuiltInPropsDefinitionType,\n [ string ] : MixedPropDefinitionType\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = ({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps() : BuiltInPropsDefinitionType {\n return {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback =\n ((string, BooleanPropDefinitionType | void, boolean) => R) &\n ((string, StringPropDefinitionType | void, string) => R) &\n ((string, NumberPropDefinitionType | void, number) => R) &\n ((string, FunctionPropDefinitionType | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType | void, Object) => R);\n\nexport function eachProp(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) : $ReadOnlyArray {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps(propsDef : PropsDefinitionType, existingProps : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps(propsDef : PropsDefinitionType, props : (PropsType

), method : $Values) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType = {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n childDomainMatch : DomainMatcher,\n props : PropsType

,\n exports : ParentExportsType\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise;\n\ntype RenderContainerOptions = {|\n context : $Values,\n proxyFrame : ?ProxyObject,\n proxyPrerenderFrame : ?ProxyObject,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise;\ntype RejectInitPromise = (mixed) => ZalgoPromise;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, RenderContainerOptions) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values|}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState,\n resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values,\n rerender : Rerender\n|};\n\ntype ParentComponent = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise,\n getProps : () => PropsType

,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise,\n getExports : () => X\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions = {|\n uid : string,\n options : NormalizedComponentOptionsType,\n overrides? : ParentDelegateOverrides

,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions) : ParentComponent {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType

= overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return rejectInitPromise(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__${ ZOID }_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getCurrentWindowReferenceUID = () : string => {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childDomain : string, childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin.setName(windowName).then(() => {\n return proxyWin;\n });\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow, context : $Values) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n const exportsPromise : ZalgoPromise = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType

) : ZalgoPromise {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values|} = {}) : ZalgoPromise> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|} = {}) : ZalgoPromise => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|}) : ZalgoPromise => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values|}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, initialChildDomain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType

= getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = ({ target, container, context, rerender } : RenderOptions) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, initialChildDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\n };\n}\n","/* @flow */\n/* eslint react/no-deprecated: off, react/no-find-dom-node: off, react/display-name: off, react/no-did-mount-set-state: off, react/destructuring-assignment: off, react/prop-types: off */\n\nimport { extend, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\n// eslint-disable-next-line flowtype/require-exact-type\ndeclare class ReactClassType {}\n\n// eslint-disable-next-line flowtype/require-exact-type\ndeclare class __ReactComponent {}\n\ntype ReactElementType = {|\n\n|};\n\ntype ReactType = {|\n Component : __ReactComponent,\n createClass : ({| render : () => ReactElementType, componentDidMount : () => void, componentDidUpdate : () => void |}) => (typeof ReactClassType),\n createElement : (string, ?{ [string] : mixed }, ...children : $ReadOnlyArray) => ReactElementType\n|};\n\ntype ReactDomType = {|\n findDOMNode : (typeof ReactClassType) => HTMLElement\n|};\n\ntype ReactLibraryType = {|\n React : ReactType,\n ReactDOM : ReactDomType\n|};\n\nexport const react : ComponentDriverType<*, ReactLibraryType, typeof ReactClassType, *, *> = {\n\n register: (tag, propsDef, init, { React, ReactDOM }) => {\n\n // $FlowFixMe\n return class extends React.Component {\n render() : ReactElementType {\n return React.createElement('div', null);\n }\n\n componentDidMount() {\n // $FlowFixMe\n const el = ReactDOM.findDOMNode(this);\n const parent = init(extend({}, this.props));\n parent.render(el, CONTEXT.IFRAME);\n this.setState({ parent });\n }\n\n componentDidUpdate() {\n\n if (this.state && this.state.parent) {\n this.state.parent.updateProps(extend({}, this.props)).catch(noop);\n }\n }\n };\n }\n};\n","/* @flow */\n\nimport { noop, dasherizeToCamel } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\ntype VueComponent = {|\n render : (Function) => Element,\n inheritAttrs : boolean,\n mounted : () => void,\n watch : {|\n $attrs : {|\n deep : boolean,\n handler : () => void\n |}\n |}\n|};\n\ntype RegisteredVueComponent = {|\n \n|};\n\ntype VueType = {|\n component : (string, VueComponent) => RegisteredVueComponent\n|};\n\nfunction propsToCamelCase(props : Object) : Object {\n return Object.keys(props).reduce((acc, key) => {\n const value = props[key];\n // In vue `style` is a reserved prop name\n if (key === 'style-object' || key === 'styleObject') {\n acc.style = value;\n // To keep zoid as generic as possible, passing in the original prop name as well\n acc.styleObject = value;\n } else if (key.includes('-')) {\n acc[dasherizeToCamel(key)] = value;\n } else {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\nexport const vue : ComponentDriverType<*, VueType, RegisteredVueComponent, *, *> = {\n\n register: (tag, propsDef, init, Vue) => {\n\n return Vue.component(tag, {\n render(createElement) : Element {\n return createElement('div');\n },\n\n inheritAttrs: false,\n\n mounted() {\n // $FlowFixMe[object-this-reference]\n const el = this.$el;\n // $FlowFixMe[object-this-reference]\n this.parent = init({ ...propsToCamelCase(this.$attrs) });\n // $FlowFixMe[object-this-reference]\n this.parent.render(el, CONTEXT.IFRAME);\n },\n\n watch: {\n $attrs: {\n handler: function handler() {\n if (this.parent && this.$attrs) {\n this.parent.updateProps({ ...this.$attrs }).catch(noop);\n }\n },\n deep: true\n }\n }\n });\n }\n};\n","/* @flow */\nimport { dasherizeToCamel, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\nfunction propsToCamelCase(props : Object) : Object {\n return Object.keys(props).reduce((acc, key) => {\n const value = props[key];\n // In vue `style` is a reserved prop name\n if (key === 'style-object' || key === 'styleObject') {\n acc.style = value;\n // To keep zoid as generic as possible, passing in the original prop name as well\n acc.styleObject = value;\n } else if (key.includes('-')) {\n acc[dasherizeToCamel(key)] = value;\n } else {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\nexport const vue3 : ComponentDriverType<*, *, *, *, *> = {\n register: (tag, propsDef, init) => {\n return {\n template: `

`,\n\n inheritAttrs: false,\n\n mounted() {\n // $FlowFixMe[object-this-reference]\n const el = this.$el;\n // $FlowFixMe[object-this-reference]\n this.parent = init({ ...propsToCamelCase(this.$attrs) });\n // $FlowFixMe[object-this-reference]\n this.parent.render(el, CONTEXT.IFRAME);\n },\n\n watch: {\n $attrs: {\n handler: function handler() {\n if (this.parent && this.$attrs) {\n this.parent.updateProps({ ...this.$attrs }).catch(noop);\n }\n },\n deep: true\n }\n }\n };\n\n }\n};\n","/* @flow */\n\nimport { dasherizeToCamel, replaceObject, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\ntype AngularModule = {|\n directive : (string, () => {|\n scope : { [string] : '=' | '@' },\n restrict : string,\n controller : $ReadOnlyArray\n |}) => AngularModule\n|};\n\ntype Angular = {|\n module : (string, $ReadOnlyArray) => AngularModule\n|};\n\nexport const angular : ComponentDriverType<*, Angular, AngularModule, *, *> = {\n\n register: (tag, propsDef, init, ng) => {\n\n const module = ng.module(tag, []).directive(dasherizeToCamel(tag), () => {\n\n const scope = {};\n\n for (const key of Object.keys(propsDef)) {\n scope[key] = '=';\n }\n\n scope.props = '=';\n\n return {\n scope,\n\n restrict: 'E',\n\n controller: [ '$scope', '$element', ($scope, $element) => {\n function safeApply() {\n if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {\n try {\n $scope.$apply();\n } catch (err) {\n // pass\n }\n }\n }\n\n const getProps = () => {\n return replaceObject($scope.props, item => {\n if (typeof item === 'function') {\n return function angularWrapped() : mixed {\n // $FlowFixMe\n const result = item.apply(this, arguments);\n safeApply();\n return result;\n };\n }\n return item;\n });\n };\n\n const instance = init(getProps());\n instance.render($element[0], CONTEXT.IFRAME);\n\n $scope.$watch(() => {\n instance.updateProps(getProps()).catch(noop);\n });\n } ]\n };\n });\n\n return module;\n }\n};\n","/* @flow */\n/* eslint new-cap: 0 */\n\nimport { replaceObject } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\nimport { CONTEXT } from '../constants';\n\ntype Angular2Injection = {||};\n\ntype Angular2Component = {||};\n\ntype Angular2Module = {| annotations : Object, name : string |};\n\ntype Angular2 = {|\n Component : ({| selector : string, template : string, inputs : $ReadOnlyArray |}) => {|\n Class : ({| constructor : $ReadOnlyArray, ngOnInit : () => void, ngDoCheck : () => void |}) => Angular2Component\n |},\n NgModule : ({| declarations : $ReadOnlyArray<*>, exports : $ReadOnlyArray<*> |}) => {|\n Class : ({| constructor : () => void |}) => Angular2Module\n |},\n ElementRef : Angular2Injection,\n NgZone : Angular2Injection,\n Inject : Function\n|};\n\nconst equals = (obj1, obj2) => {\n const checked = {};\n\n for (const key in obj1) {\n if (obj1.hasOwnProperty(key)) {\n checked[key] = true;\n\n if (obj1[key] !== obj2[key]) {\n return false;\n }\n }\n }\n\n for (const key in obj2) {\n if (!checked[key]) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const angular2 : ComponentDriverType<*, Angular2, Angular2Module, *, *> = {\n\n register: (tag, propsDef, init, { Component : AngularComponent, NgModule, ElementRef, NgZone, Inject }) => {\n class ComponentInstance {\n elementRef : Object;\n internalProps : Object;\n parent : Object;\n props : Object;\n zone : Object;\n _props : Object;\n\n static annotations : $ReadOnlyArray<*>;\n static parameters : $ReadOnlyArray<*>;\n\n constructor (elementRef, zone) {\n this._props = {};\n this.elementRef = elementRef;\n this.zone = zone;\n }\n\n getProps () : Object {\n return replaceObject({ ...this.internalProps, ...this.props }, item => {\n if (typeof item === 'function') {\n const { zone } = this;\n return function angular2Wrapped() : void {\n // $FlowFixMe\n return zone.run(() => item.apply(this, arguments));\n };\n }\n return item;\n });\n }\n\n ngOnInit() {\n const targetElement = this.elementRef.nativeElement;\n this.parent = init(this.getProps());\n this.parent.render(targetElement, CONTEXT.IFRAME);\n }\n\n ngDoCheck() {\n if (this.parent && !equals(this._props, this.props)) {\n this._props = { ...this.props };\n this.parent.updateProps(this.getProps());\n }\n }\n }\n\n ComponentInstance.parameters = [\n [ new Inject(ElementRef) ],\n [ new Inject(NgZone) ]\n ];\n\n ComponentInstance.annotations = [\n new AngularComponent({\n selector: tag,\n template: `
`,\n inputs: [ 'props' ]\n })\n ];\n\n class ModuleInstance {\n static annotations : $ReadOnlyArray<*>;\n }\n\n ModuleInstance.annotations = [\n new NgModule({\n declarations: [ ComponentInstance ],\n exports: [ ComponentInstance ]\n })\n ];\n\n return ModuleInstance;\n }\n};\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType

) : ?HTMLElement {\n const { width, height } = dimensions;\n\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { type RenderOptionsType } from '../../parent/parent';\n\nexport function defaultPrerenderTemplate

({ doc, props } : RenderOptionsType

) : ?HTMLElement {\n if (__ZOID__.__DEFAULT_PRERENDER__) {\n const html = doc.createElement('html');\n const body = doc.createElement('body');\n const style = doc.createElement('style');\n const spinner = doc.createElement('div');\n spinner.classList.add('spinner');\n\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n html.appendChild(body);\n body.appendChild(spinner);\n body.appendChild(style);\n style.appendChild(doc.createTextNode(`\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n `));\n\n return html;\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition = ({|\n getExports : () => ZalgoPromise\n|}) => X;\n\nexport type ExportsDefinition = ExportsConfigDefinition | ExportsMapperDefinition;\n\nexport type ComponentOptionsType = {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values,\n\n props? : UserPropsDefinitionType,\n\n dimensions? : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType

|}) => Attributes,\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values,\n\n propsDef : PropsDefinitionType,\n dimensions : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition\n|};\n\nexport type ZoidComponentInstance = {|\n ...ParentHelpers

,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance,\n render : (container? : ContainerReferenceType, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent = {\n (props? : PropsInputType

| void) : ZoidComponentInstance,\n // eslint-disable-next-line no-undef\n driver : (string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n instances : $ReadOnlyArray>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = () : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions(options : ComponentOptionsType) : NormalizedComponentOptionsType {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop },\n exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component = {|\n init : (props? : PropsInputType

| void) => ZoidComponentInstance,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent\n|};\n\nexport function component(opts : ComponentOptionsType) : Component {\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible,\n children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent => {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : ContainerReferenceType) : ContainerReferenceType => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType

| void) : ZoidComponentInstance => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType

= parent.getProps();\n const parentExport : exportPropType = parent.export;\n\n const childParent : ParentPropType = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, vue3, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L) => D\n|};\n\nexport type ZoidProps

= PropsType

;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = (options : ComponentOptionsType) => ZoidComponent;\n\nexport const create : CreateZoidComponent = (options : ComponentOptionsType) : ZoidComponent => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType

| void) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n};\n\nexport function destroyComponents(err? : mixed) : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://zoid/webpack/universalModuleDefinition","webpack://zoid/webpack/bootstrap","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://zoid/./node_modules/zalgo-promise/src/utils.js","webpack://zoid/./node_modules/zalgo-promise/src/exceptions.js","webpack://zoid/./node_modules/zalgo-promise/src/flush.js","webpack://zoid/./node_modules/zalgo-promise/src/promise.js","webpack://zoid/./node_modules/cross-domain-utils/src/util.js","webpack://zoid/./node_modules/cross-domain-utils/src/constants.js","webpack://zoid/./node_modules/cross-domain-utils/src/utils.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/weakmap.js","webpack://zoid/./node_modules/belter/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/native.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://zoid/./node_modules/belter/src/dom.js","webpack://zoid/./node_modules/belter/src/css.js","webpack://zoid/./node_modules/post-robot/src/global.js","webpack://zoid/./node_modules/belter/src/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/hello.js","webpack://zoid/./node_modules/post-robot/src/conf/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/windows.js","webpack://zoid/./node_modules/universal-serialize/src/common.js","webpack://zoid/./node_modules/universal-serialize/src/constants.js","webpack://zoid/./node_modules/universal-serialize/src/serialize.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/function.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/error.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/promise.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/regex.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/date.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/array.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/object.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/string.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/number.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/boolean.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/null.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/undefined.js","webpack://zoid/./node_modules/universal-serialize/src/deserialize.js","webpack://zoid/./node_modules/post-robot/src/bridge/common.js","webpack://zoid/./node_modules/post-robot/src/bridge/parent.js","webpack://zoid/./node_modules/post-robot/src/bridge/setup.js","webpack://zoid/./node_modules/post-robot/src/bridge/bridge.js","webpack://zoid/./node_modules/post-robot/src/bridge/child.js","webpack://zoid/./node_modules/post-robot/src/serialize/window.js","webpack://zoid/./node_modules/post-robot/src/serialize/function.js","webpack://zoid/./node_modules/post-robot/src/serialize/serialize.js","webpack://zoid/./node_modules/post-robot/src/serialize/promise.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/strategies.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/index.js","webpack://zoid/./node_modules/post-robot/src/drivers/listeners.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/types.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/index.js","webpack://zoid/./node_modules/post-robot/src/public/on.js","webpack://zoid/./node_modules/post-robot/src/lib/compat.js","webpack://zoid/./node_modules/post-robot/src/public/send.js","webpack://zoid/./node_modules/post-robot/src/index.js","webpack://zoid/./node_modules/post-robot/src/conf/config.js","webpack://zoid/./node_modules/post-robot/src/setup.js","webpack://zoid/./node_modules/post-robot/src/clean.js","webpack://zoid/./src/lib/global.js","webpack://zoid/./src/lib/serialize.js","webpack://zoid/./src/constants.js","webpack://zoid/./src/lib/window.js","webpack://zoid/./src/child/props.js","webpack://zoid/./src/child/child.js","webpack://zoid/./src/component/props.js","webpack://zoid/./src/parent/props.js","webpack://zoid/./src/parent/parent.js","webpack://zoid/./src/drivers/react.js","webpack://zoid/./src/drivers/vue.js","webpack://zoid/./src/drivers/vue3.js","webpack://zoid/./src/drivers/angular.js","webpack://zoid/./src/drivers/angular2.js","webpack://zoid/./src/component/templates/container.js","webpack://zoid/./src/component/templates/component.js","webpack://zoid/./src/component/component.js"],"names":["root","factory","exports","module","define","amd","self","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","hasOwnProperty","p","s","_setPrototypeOf","setPrototypeOf","__proto__","_inheritsLoose","subClass","superClass","prototype","constructor","_extends","assign","target","arguments","length","source","apply","isPromise","item","Promise","window","Window","toString","then","err","flushPromise","dispatchedErrors","possiblyUnhandledPromiseHandlers","activeCount","flushActive","promise","resolve","startActive","endActive","ZalgoPromise","handler","resolved","rejected","errorHandled","error","handlers","dispatching","stack","result","isAsync","res","reject","Error","dispatch","setTimeout","indexOf","push","j","dispatchPossiblyUnhandledError","asyncReject","chain","firstPromise","secondPromise","onSuccess","onError","promiseResult","catch","undefined","finally","onFinally","try","timeout","time","clearTimeout","toPromise","TypeError","lazy","all","promises","count","results","slice","prom","hash","awaitPromises","map","items","method","onPossiblyUnhandledException","cancel","splice","context","args","delay","flush","isRegex","WINDOW_TYPE","IFRAME","POPUP","IE_WIN_ACCESS_ERROR","getActualProtocol","win","location","protocol","getProtocol","mockDomain","split","isAboutProtocol","getParent","parent","getOpener","opener","canReadFromWindow","getActualDomain","PROTOCOL","host","getDomain","domain","isSameDomain","desc","getOwnPropertyDescriptor","isMockProtocol","isActuallySameDomain","assertSameDomain","isAncestorParent","child","childParent","getParents","getFrames","frames","len","frame","getAllChildFrames","getTop","top","getAllFramesInWindow","iframeWindows","iframeFrames","isWindowClosed","allowMock","closed","message","mockclosed","iframeIndex","collection","safeIndexOf","contentWindow","parentNode","doc","ownerDocument","documentElement","contains","isFrameWindowClosed","getUserAgent","navigator","mockUserAgent","userAgent","getFrameByName","winFrames","childFrame","isOpener","getAncestor","anyMatch","collection1","collection2","item1","getDistanceFromTop","distance","isSameTopWindow","win1","win2","top1","top2","allFrames1","allFrames2","opener1","opener2","matchDomain","pattern","origin","Array","isArray","Boolean","match","JSON","stringify","some","subpattern","getDomainFromUrl","url","join","onCloseWindow","callback","maxtime","Infinity","check","isWindow","obj","__cross_domain_utils_window_check__","normalizeMockUrl","getFrameForWindow","frameElement","document","querySelectorAll","closeWindow","isIframe","parentElement","removeChild","close","objectIDs","CrossDomainSafeWeakMap","weakmap","keys","values","Math","random","WeakMap","freeze","testWeakMap","testKey","set","hasNativeWeakMap","_cleanupClosedWindows","delete","isSafeToReadWrite","entry","writable","index","has","getOrSet","_getPrototypeOf","getPrototypeOf","_isNativeReflectConstruct","Reflect","construct","sham","Proxy","Date","e","_construct","Parent","Class","isNativeReflectConstruct","a","instance","Function","_wrapNativeSuper","_cache","Map","Wrapper","configurable","isElement","element","passed","Element","nodeType","style","_","getFunctionName","fn","__name__","displayName","setFunctionName","base64encode","str","btoa","encodeURIComponent","replace","p1","String","fromCharCode","parseInt","Buffer","from","uniqueID","chars","charAt","floor","toISOString","toLowerCase","serializeArgs","subkey","val","uid","getObjectID","getEmptyObject","memoizeGlobalIndex","memoizeGlobalIndexValidFrom","memoize","options","simpleCache","thisCache","thisNamespace","cacheTime","memoizeIndex","memoizedFunction","cache","cacheKey","cacheResult","now","reset","memoizePromise","memoizedPromiseFunction","noop","once","called","stringifyError","level","newErr","extend","identity","safeInterval","loop","dasherizeToCamel","string","g","toUpperCase","defineLazyProp","arrayFrom","isObjectObject","isPlainObject","replaceObject","replacer","fullKey","itemKey","isDefined","cleanup","cleanErr","tasks","cleaned","cleaner","register","task","shift","assertExists","thing","clear","ExtendableError","captureStackTrace","ReferenceError","getBody","body","isDocumentReady","readyState","isDocumentInteractive","urlEncode","parseQuery","queryString","logic","__inline_memoize_cache__","params","pair","decodeURIComponent","inlineMemoize","extendQuery","originalQuery","props","filter","appendChild","container","getElementSafe","id","querySelector","elementReady","el","interval","setInterval","clearInterval","awaitFrameLoadPromises","PopupOpenError","awaitFrameLoad","addEventListener","cleanIframes","linkFrameWindow","awaitFrameWindow","loadedFrame","iframe","tag","styleText","createElement","class","className","setAttribute","attributes","styleSheet","cssText","createTextNode","html","innerHTML","allowTransparency","backgroundColor","border","isIE","hasAttribute","getElement","event","removeEventListener","showElement","setProperty","hideElement","destroyElement","isElementClosed","onResize","width","height","currentWidth","offsetWidth","currentHeight","offsetHeight","canceled","observer","getClientRects","isElementVisible","newWidth","newHeight","ResizeObserver","observe","MutationObserver","childList","subtree","characterData","disconnect","isShadowElement","currentScript","getCurrentScript","getStackTrace","stackDetails","exec","scriptLocation","getElementsByTagName","reverse","script","src","inferCurrentScript","currentUID","isPerc","test","toNum","toPx","toCSS","normalizeDimension","dim","max","getGlobal","globalKey","__POST_ROBOT__","getAttribute","ATTRIBUTES","hashedString","total","charCodeAt","abs","strHashStr","dataset","getObj","globalStore","defStore","store","storeKey","defVal","del","WildCard","getWildcard","global","WINDOW_WILDCARD","windowStore","winStore","getStore","getInstanceID","resolveHelloPromise","helloPromises","existingPromise","newPromise","sayHello","send","instanceID","data","getWindowInstanceID","awaitWindowHello","getHelloPromise","markWindowKnown","isSerializedType","__type__","determineType","serializeType","type","__val__","SERIALIZER","code","toJSON","defaultSerializers","DESERIALIZER","RegExp","defaultDeserializers","needsBridgeForBrowser","needsBridgeForWin","needsBridgeForDomain","needsBridge","getBridgeName","BRIDGE_NAME_PREFIX","isBridge","documentBodyReady","registerRemoteWindow","findRemoteWindow","remoteWinPromise","registerRemoteSendMessage","sendMessage","remoteWin","remoteDomain","fireAndForget","rejectRemoteSendMessage","linkWindow","popupWindowsByName","popupWindowsByWin","winName","details","setupBridge","windowOpen","on","receiveMessage","open","last","bridgePromise","bridge","getWindowDetails","listenForOpenTunnel","openTunnelToParent","canary","tunnelWindows","parentWindow","cleanTunnelWindows","addTunnelWindow","tunnelWindow","setupOpenTunnelToParent","openTunnelToOpener","cleanupProxyWindows","idToProxyWindow","shouldClean","getSerializedWindow","winPromise","windowNamePromise","windowTypePromise","getName","getType","focus","isClosed","setLocation","href","opts","form","display","input","submit","submitForm","setName","sameDomain","ProxyWindow","serializedWindow","isProxyWindow","actualWindow","actualWindowPromise","getID","setWindow","isPopup","isPopupPromise","getNamePromise","reopenPromise","focusPromise","getWindow","awaitWindow","matchWindow","proxyInstanceID","knownWindowInstanceID","unwrap","serialize","toProxyWindow","deserialize","addMethod","methodStore","proxyWindowMethods","lookupMethod","serializeFunction","destination","meth","methodSource","arg","__id__","serializeMessage","serializers","serializer","serializePromise","deserializeMessage","deserializers","parse","deserializer","serializedPromise","deserializePromise","serializedFunction","getDeserializedFunction","crossDomainFunctionWrapper","__origin__","__source__","deserializeFunction","SEND_MESSAGE_STRATEGIES","domainBuffer","buffer","serializedMessage","strategies","errors","strategyName","getResponseListener","deleteResponseListener","isResponseListenerErrored","getRequestListener","requestListeners","winQualifier","nameListeners","domainListeners","listener","regex","handleRequest","logName","sendResponse","ack","pathname","handleError","handleAck","handleResponse","receivedMessages","messages","parsedMessage","parseMessages","deserializeMessages","requestListener","addRequestListener","winCandidate","requestListenerPromise","actualWin","listenersCollection","existingListener","strDomain","winNameDomainRegexListeners","winNameDomainRegexListener","winNameListeners","winNameDomainListeners","errorHandler","postMessage","messagingChild","messagingParent","sendBridgeMessage","foreignGlobal","winOrProxyWin","domainMatcher","responseTimeout","childTimeout","validateOptions","actualParent","isAncestor","targetDomain","actualDomain","normalizedDomain","normalizeDomain","responseListener","addResponseListener","reqPromises","markResponseListenerErrored","totalAckTimeout","isWindowKnown","totalResTimeout","ackTimeout","resTimeout","cancelled","cleanUpWindow","tryGlobal","getProxyObject","basicSerialize","getUIDRefStore","references","crossDomainSerialize","metaData","sender","receiver","passByReference","basic","proxyWin","internalSerializeMessage","reference","getRawRef","serializedData","cleanReference","ref","crossDomainDeserialize","atob","base64decode","basicDeserialize","getRefValue","internalDeserializeMessage","openBridge","bridges","bridgeFrames","openBridgeFrame","linkUrl","hasBridge","destroyBridges","PROP_TYPE","STRING","OBJECT","FUNCTION","BOOLEAN","NUMBER","ARRAY","PROP_SERIALIZATION","DOTIFY","BASE64","CONTEXT","EVENT","RENDER","RENDERED","DISPLAY","ERROR","CLOSE","DESTROY","PROPS","RESIZE","FOCUS","buildChildWindowName","serializedPayload","parseWindowName","windowName","zoidcomp","serializedInitialPayload","parseInitialParentPayload","windowRef","getNthParent","ancestor","windows","findChildFrameByName","namedFrame","findFrameByName","getWindowByRef","payload","getInitialParentPayload","getWindowRef","targetWindow","currentWindow","normalizeChildProp","propsDef","helpers","prop","childDecorate","onProps","resize","getParentDomain","show","hide","export","getSiblings","destroy","defaultNoop","decorateOnce","eachProp","serializeProps","propDef","getParam","queryParam","bodyParam","getValue","queryValue","bodyValue","finalParam","finalValue","serialization","dotify","prefix","newobj","every","dotkey","mapProps","parentComponent","triggered","emitter","currentProxyWin","currentProxyContainer","childComponent","currentChildDomain","currentContainer","overrides","parentWin","containerTemplate","prerenderTemplate","dimensions","autoResize","domainMatch","xports","initPromise","handledErrors","clean","state","inputProps","internalState","visible","eventName","handlerList","trigger","triggerOnce","onErrorOverride","getProxyContainerOverride","getProxyContainer","showOverride","hideOverride","closeOverride","renderContainerOverride","renderContainer","getProxyWindowOverride","getProxyWindow","setProxyWinOverride","setProxyWin","openFrameOverride","openFrame","openPrerenderFrameOverride","openPrerenderFrame","prerenderOverride","prerender","openOverride","openPrerenderOverride","openPrerender","watchForUnloadOverride","watchForUnload","getInternalStateOverride","getInternalState","setInternalStateOverride","setInternalState","getDimensions","resolveInitPromise","rejectInitPromise","getPropsForChild","initialChildDomain","sendToChild","newInternalState","windowProp","setState","getUrl","getAttributes","getInitialChildDomain","title","proxyPrerenderFrame","prerenderFrame","prerenderFrameWindow","actualComponentWindow","initChild","childDomain","childExports","proxyFrame","outerWidth","closeOnUnload","left","round","screenX","screen","outerHeight","screenY","status","toolbar","menubar","resizable","scrollbars","popup","unloadWindowListener","closeParentWindowListener","checkWindowClose","secondIsClosed","exportsPromise","xport","actualExports","renderTemplate","renderer","proxyPrerenderWin","prerenderWindow","isBlankDomain","tagName","children","writeElementToWindow","prerenderResizeListener","proxyContainer","rerender","innerContainer","containerWatcher","sacrificialFrame","sacrificialFrameWin","mutationObservers","elementClosed","mutationElement","mutationObserver","frameWin","watchElementForClose","removeError","getHelpers","updateProps","setProps","newInputProps","existingProps","valueDetermined","alias","default","required","decorate","getDerivedValue","extendProps","newProps","childProps","containerElement","insertShadowSlot","shadowHost","shadowRoot","getShadowRoot","getShadowHost","slotName","slot","slotProvider","init","onRender","onDisplay","onRendered","onClose","onDestroy","onFocus","render","childDomainMatch","checkAllowRender","delegatePromise","delegateProps","propName","allowDelegate","childOverridesPromise","POST_MESSAGE","parentComp","getDelegateOverrides","childOverrides","delegate","watchForUnloadPromise","buildBodyPromise","onRenderPromise","getProxyContainerPromise","getProxyWindowPromise","finalSetPropsPromise","buildUrlPromise","query","originalUrl","originalHash","hashString","extendUrl","buildWindowNamePromise","version","__ZOID__","checkClose","buildInitialChildPayload","childPayload","buildSerializedChildPayload","openFramePromise","openPrerenderFramePromise","renderContainerPromise","openPromise","openPrerenderPromise","setStatePromise","prerenderPromise","setWindowNamePromise","getMethodPromise","loadUrlPromise","windowUrl","watchForClosePromise","watchForClose","onDisplayPromise","openBridgePromise","bridgeUrl","bridgeDomain","runTimeoutPromise","onRenderedPromise","getProps","getExports","react","React","ReactDOM","componentDidMount","findDOMNode","componentDidUpdate","Component","vue","Vue","component","inheritAttrs","mounted","$el","$attrs","reduce","acc","styleObject","includes","watch","deep","vue3","template","angular","ng","directive","scope","restrict","controller","$scope","$element","safeApply","$root","$$phase","$apply","$watch","angular2","AngularComponent","NgModule","ElementRef","NgZone","Inject","ComponentInstance","elementRef","zone","internalProps","_props","run","ngOnInit","targetElement","nativeElement","ngDoCheck","obj1","obj2","checked","equals","annotations","parameters","selector","inputs","ModuleInstance","declarations","defaultContainerTemplate","div","cspNonce","classList","add","remove","defaultPrerenderTemplate","spinner","cleanInstances","cleanZoid","allowDelegateListener","delegateListener","allowedParentDomains","defaultContext","validate","eligible","logger","info","xportsDefinition","valuePromise","normalizeOptions","driverCache","instances","isChild","isChildComponentWindow","registerChild","xprops","components","onPropHandlers","parentComponentWindow","parentDomain","parentExports","initialProps","parentExport","parentResize","parentInit","anyParent","currentParent","winParent","isUpdate","normalizedProps","normalizeChildProps","componentName","updateChildWindowNameWithRef","checkParentDomain","ZOID","eligibility","reason","clone","getDefaultContext","finalContext","getDefaultContainer","newInstance","renderTo","childComponents","childName","Child","childInputProps","parentProps","getChildren","isEligible","driver","driverName","dep","drivers","canRenderTo","initialized","sourceElement","originalEvent","messageListener","listenForMessages","initHello","comp","destroyComponents","destroyPromise","destroyAll","responseListeners","cancelResponseListeners"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,OAAQ,GAAIH,GACO,iBAAZC,QACdA,QAAc,KAAID,IAElBD,EAAW,KAAIC,IARjB,CASoB,oBAATK,KAAuBA,KAAOC,MAAO,WAChD,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUR,QAGnC,IAAIC,EAASK,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GA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,OAJI56B,IACApG,OAAOihC,OAASnJ,EAAKmJ,OAAS76B,EAAMo1B,YAGjC1D,GAGJ,SAASkM,GAAkB5jC,GAC1B8e,IACAA,GAAOoL,iBAGX,IAAM2Z,EAAiBlE,GAAe38B,IAAIhD,GAE1C,OADA2/B,GAAiBltB,KACVoxB,EAGJ,IAAMC,GAAaF,GAEnB,SAASpW,GAAQxtB,GAIpB,OAHA8jC,YhBriBOlkC,OAAM,gBVWV,WAAmC,IACtC,IAAMmkC,EAAoBrpB,GAAY,qBADA,MAEnBqpB,EAAkBx4B,OAFC,eAEO,CAAxC,IAAMjI,EAAI,KACLuhB,EAAWkf,EAAkBvmC,IAAI8F,GACnCuhB,IACAA,EAASqD,WAAY,GAEzB6b,EAAkBhpB,IAAIzX,IQZ1B0gC,INoHMnf,EAAWnK,KAAcld,IAAI,yBAE/BqnB,EAASjhB,gBlCvINhE,OAAM,uB0DmjBNggC,GAAU58B,IAAIhD,GlBniBlB,INqHG6kB","file":"zoid.frameworks.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"zoid\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"zoid\"] = factory();\n\telse\n\t\troot[\"zoid\"] = factory();\n})((typeof self !== 'undefined' ? self : this), function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","/* @flow */\n\nexport function isPromise(item : mixed) : boolean {\n try {\n if (!item) {\n return false;\n }\n\n if (typeof Promise !== 'undefined' && item instanceof Promise) {\n return true;\n }\n\n if (typeof window !== 'undefined' && typeof window.Window === 'function' && item instanceof window.Window) {\n return false;\n }\n\n if (typeof window !== 'undefined' && typeof window.constructor === 'function' && item instanceof window.constructor) {\n return false;\n }\n\n const toString = ({}).toString;\n\n if (toString) {\n const name = toString.call(item);\n\n if (name === '[object Window]' || name === '[object global]' || name === '[object DOMWindow]') {\n return false;\n }\n }\n\n if (typeof item.then === 'function') {\n return true;\n }\n } catch (err) {\n return false;\n }\n\n return false;\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nconst dispatchedErrors = [];\nconst possiblyUnhandledPromiseHandlers : Array<(mixed, promise? : ZalgoPromise) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer,\n undefined? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull,\n [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull,\n deserializeUndefined\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer,\n undefined? : PrimitiveDeserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull,\n [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady : ZalgoPromise = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, getFrameByName, isWindowClosed, getDomainFromUrl, normalizeMockUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { BRIDGE_TIMEOUT, MESSAGE_NAME } from '../conf';\nimport { awaitWindowHello } from '../lib';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { getBridgeName, documentBodyReady, registerRemoteSendMessage, registerRemoteWindow } from './common';\n\ntype WinDetails = {|\n win : CrossDomainWindowType,\n domain? : ?string,\n name? : ?string\n|};\n\nexport function listenForOpenTunnel({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n const popupWindowsByName = globalStore('popupWindowsByName');\n\n on(MESSAGE_NAME.OPEN_TUNNEL, ({ source, origin, data }) => {\n const bridgePromise = globalStore('bridges').get(origin);\n\n if (!bridgePromise) {\n throw new Error(`Can not find bridge promise for domain ${ origin }`);\n }\n\n return bridgePromise.then(bridge => {\n if (source !== bridge) {\n throw new Error(`Message source does not matched registered bridge for domain ${ origin }`);\n }\n\n if (!data.name) {\n throw new Error(`Register window expected to be passed window name`);\n }\n\n if (!data.sendMessage) {\n throw new Error(`Register window expected to be passed sendMessage method`);\n }\n\n if (!popupWindowsByName.has(data.name)) {\n throw new Error(`Window with name ${ data.name } does not exist, or was not opened by this window`);\n }\n\n const getWindowDetails = () : WinDetails => {\n const winDetails = popupWindowsByName.get(data.name);\n // $FlowFixMe\n return winDetails;\n };\n\n if (!getWindowDetails().domain) {\n throw new Error(`We do not have a registered domain for window ${ data.name }`);\n }\n\n if (getWindowDetails().domain !== origin) {\n throw new Error(`Message origin ${ origin } does not matched registered window origin ${ getWindowDetails().domain || 'unknown' }`);\n }\n\n registerRemoteSendMessage(getWindowDetails().win, origin, data.sendMessage);\n\n return {\n sendMessage(message) {\n\n if (!window || window.closed) {\n return;\n }\n\n if (!getWindowDetails()) {\n return;\n }\n\n const domain = getWindowDetails().domain;\n\n if (!domain) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n origin: domain,\n source: getWindowDetails().win\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n };\n });\n });\n}\n\nfunction openBridgeFrame(name : string, url : string) : HTMLIFrameElement {\n\n const iframe = document.createElement(`iframe`);\n\n iframe.setAttribute(`name`, name);\n iframe.setAttribute(`id`, name);\n\n iframe.setAttribute(`style`, `display: none; margin: 0; padding: 0; border: 0px none; overflow: hidden;`);\n iframe.setAttribute(`frameborder`, `0`);\n iframe.setAttribute(`border`, `0`);\n iframe.setAttribute(`scrolling`, `no`);\n iframe.setAttribute(`allowTransparency`, `true`);\n\n iframe.setAttribute(`tabindex`, `-1`);\n iframe.setAttribute(`hidden`, `true`);\n iframe.setAttribute(`title`, ``);\n iframe.setAttribute(`role`, `presentation`);\n\n iframe.src = url;\n\n return iframe;\n}\n\nexport function hasBridge(url : string, domain : string) : boolean {\n const bridges = globalStore('bridges');\n return bridges.has(domain || getDomainFromUrl(url));\n}\n\nexport function openBridge(url : string, domain : string) : ZalgoPromise {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n \n domain = domain || getDomainFromUrl(url);\n \n return bridges.getOrSet(domain, () => ZalgoPromise.try(() => {\n\n if (getDomain() === domain) {\n throw new Error(`Can not open bridge on the same domain as current domain: ${ domain }`);\n }\n\n const name = getBridgeName(domain);\n const frame = getFrameByName(window, name);\n\n if (frame) {\n throw new Error(`Frame with name ${ name } already exists on page`);\n }\n\n const iframe = openBridgeFrame(name, url);\n bridgeFrames.set(domain, iframe);\n\n return documentBodyReady.then(body => {\n\n body.appendChild(iframe);\n const bridge = iframe.contentWindow;\n\n return new ZalgoPromise((resolve, reject) => {\n\n iframe.addEventListener('load', resolve);\n iframe.addEventListener('error', reject);\n\n }).then(() => {\n\n return awaitWindowHello(bridge, BRIDGE_TIMEOUT, `Bridge ${ url }`);\n\n }).then(() => {\n\n return bridge;\n });\n });\n }));\n}\n\nexport function linkWindow({ win, name, domain } : WinDetails) : WinDetails {\n const popupWindowsByName = globalStore('popupWindowsByName');\n const popupWindowsByWin = windowStore('popupWindowsByWin');\n\n for (const winName of popupWindowsByName.keys()) {\n const details = popupWindowsByName.get(winName);\n if (!details || isWindowClosed(details.win)) {\n popupWindowsByName.del(winName);\n }\n }\n\n if (isWindowClosed(win)) {\n return { win, name, domain };\n }\n\n const details = popupWindowsByWin.getOrSet(win, () : WinDetails => {\n if (!name) {\n return { win };\n }\n \n // $FlowFixMe\n return popupWindowsByName.getOrSet(name, () : WinDetails => {\n return { win, name };\n });\n });\n\n if (details.win && details.win !== win) {\n throw new Error(`Different window already linked for window: ${ name || 'undefined' }`);\n }\n\n if (name) {\n details.name = name;\n popupWindowsByName.set(name, details);\n }\n\n if (domain) {\n details.domain = domain;\n registerRemoteWindow(win);\n }\n\n popupWindowsByWin.set(win, details);\n \n return details;\n}\n\nexport function linkUrl(win : CrossDomainWindowType, url : string) {\n linkWindow({ win, domain: getDomainFromUrl(url) });\n}\n\nexport function listenForWindowOpen() {\n const windowOpen = window.open;\n\n window.open = function windowOpenWrapper(url : string, name : string, options : string, last : mixed) : mixed {\n const win = windowOpen.call(this, normalizeMockUrl(url), name, options, last);\n \n if (!win) {\n return win;\n }\n \n linkWindow({ win, name, domain: url ? getDomainFromUrl(url) : null });\n \n return win;\n };\n}\n\nexport function destroyBridges() {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n\n for (const domain of bridgeFrames.keys()) {\n const frame = bridgeFrames.get(domain);\n if (frame && frame.parentNode) {\n frame.parentNode.removeChild(frame);\n }\n }\n bridgeFrames.reset();\n bridges.reset();\n}\n","/* @flow */\n\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { listenForWindowOpen, listenForOpenTunnel } from './parent';\nimport { setupOpenTunnelToParent } from './bridge';\nimport { openTunnelToOpener } from './child';\n\nexport function setupBridge({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n listenForWindowOpen();\n listenForOpenTunnel({ on, send, receiveMessage });\n setupOpenTunnelToParent({ send });\n openTunnelToOpener({ on, send, receiveMessage });\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { getParent, isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { getGlobal, globalStore } from '../global';\nimport type { SendType, ResponseMessageEvent } from '../types';\n\nfunction cleanTunnelWindows() {\n const tunnelWindows = globalStore('tunnelWindows');\n\n for (const key of tunnelWindows.keys()) {\n const tunnelWindow = tunnelWindows[key];\n\n try {\n noop(tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(key);\n continue;\n }\n\n if (isWindowClosed(tunnelWindow.source)) {\n tunnelWindows.del(key);\n }\n }\n}\n\ntype TunnelWindowDataType = {|\n name : string,\n source : CrossDomainWindowType,\n canary : () => void,\n sendMessage : (message : string) => void\n|};\n\nfunction addTunnelWindow({ name, source, canary, sendMessage } : TunnelWindowDataType) : string {\n cleanTunnelWindows();\n const id = uniqueID();\n const tunnelWindows = globalStore('tunnelWindows');\n tunnelWindows.set(id, { name, source, canary, sendMessage });\n return id;\n}\n\nexport function setupOpenTunnelToParent({ send } : {| send : SendType |}) {\n getGlobal(window).openTunnelToParent = function openTunnelToParent({ name, source, canary, sendMessage } : TunnelWindowDataType) : ZalgoPromise {\n\n const tunnelWindows = globalStore('tunnelWindows');\n const parentWindow = getParent(window);\n \n if (!parentWindow) {\n throw new Error(`No parent window found to open tunnel to`);\n }\n \n const id = addTunnelWindow({ name, source, canary, sendMessage });\n \n return send(parentWindow, MESSAGE_NAME.OPEN_TUNNEL, {\n \n name,\n \n sendMessage() {\n \n const tunnelWindow = tunnelWindows.get(id);\n \n try {\n // IE gets antsy if you try to even reference a closed window\n noop(tunnelWindow && tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(id);\n return;\n }\n \n if (!tunnelWindow || !tunnelWindow.source || isWindowClosed(tunnelWindow.source)) {\n return;\n }\n \n try {\n tunnelWindow.canary();\n } catch (err) {\n return;\n }\n \n // $FlowFixMe[object-this-reference]\n tunnelWindow.sendMessage.apply(this, arguments);\n }\n \n }, { domain: WILDCARD });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isSameDomain, getOpener, getDomain, getFrameByName, assertSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { getGlobal, windowStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { needsBridge, registerRemoteWindow, rejectRemoteSendMessage, registerRemoteSendMessage, getBridgeName } from './common';\n\nfunction awaitRemoteBridgeForWindow (win : CrossDomainWindowType) : ZalgoPromise {\n return windowStore('remoteBridgeAwaiters').getOrSet(win, () => {\n return ZalgoPromise.try(() => {\n const frame = getFrameByName(win, getBridgeName(getDomain()));\n\n if (!frame) {\n return;\n }\n\n if (isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n return frame;\n }\n\n return new ZalgoPromise(resolve => {\n\n let interval;\n let timeout; // eslint-disable-line prefer-const\n\n interval = setInterval(() => { // eslint-disable-line prefer-const\n if (frame && isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n clearInterval(interval);\n clearTimeout(timeout);\n return resolve(frame);\n }\n }, 100);\n\n timeout = setTimeout(() => {\n clearInterval(interval);\n return resolve();\n }, 2000);\n });\n });\n });\n}\n\nexport function openTunnelToOpener({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const opener = getOpener(window);\n \n if (!opener || !needsBridge({ win: opener })) {\n return;\n }\n\n registerRemoteWindow(opener);\n\n return awaitRemoteBridgeForWindow(opener).then(bridge => {\n\n if (!bridge) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: no bridge found in opener`));\n }\n\n if (!window.name) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: window does not have a name`));\n }\n\n return getGlobal(assertSameDomain(bridge)).openTunnelToParent({\n\n name: window.name,\n\n source: window,\n\n canary() {\n // pass\n },\n\n sendMessage(message) {\n\n try {\n noop(window);\n } catch (err) {\n return;\n }\n\n if (!window || window.closed) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n // $FlowFixMe[object-this-reference]\n origin: this.origin,\n // $FlowFixMe[object-this-reference]\n source: this.source\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n\n }).then(({ source, origin, data }) => {\n\n if (source !== opener) {\n throw new Error(`Source does not match opener`);\n }\n\n registerRemoteSendMessage(source, origin, data.sendMessage);\n\n }).catch(err => {\n\n rejectRemoteSendMessage(opener, err);\n throw err;\n });\n });\n });\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SetLocationOptions = {|\n method? : $Values,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n const getName = () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n });\n\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n\n } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name, 'noopener');\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n // $FlowFixMe[method-unbinding]\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\ntype SendStrategies = {|\n [$Values] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore, getGlobalKey } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n const strDomain = domain.toString();\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n}\n\nexport function handleAck(source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n}\n\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[getGlobalKey()];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n if (isWindowClosed(source)) {\n return;\n }\n\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise = ZalgoPromise & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport { ProxyWindow } from '../serialize/window';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (winOrProxyWin, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n });\n};\n","/* @flow */\n\nimport { setup } from './setup';\nimport { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge, needsBridgeForBrowser, hasBridge,\n needsBridgeForWin, needsBridgeForDomain, destroyBridges } from './bridge';\n\nexport { ZalgoPromise as Promise } from 'zalgo-promise/src';\n\nexport * from './types';\nexport { ProxyWindow } from './serialize';\nexport { setup, destroy, serializeMessage, deserializeMessage, createProxyWindow, toProxyWindow } from './setup';\nexport { on, once, send } from './public';\nexport { markWindowKnown } from './lib';\nexport { cleanUpWindow } from './clean';\n\n// $FlowFixMe\nexport let bridge;\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n bridge = { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge,\n needsBridgeForBrowser, hasBridge, needsBridgeForWin, needsBridgeForDomain, destroyBridges };\n}\n\nif (__POST_ROBOT__.__AUTO_SETUP__) {\n setup();\n}\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT : number = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n\nexport function basicSerialize(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType =\n UIDReferenceType |\n RawReferenceType;\n\nexport function getUIDRefStore(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef(val : T) : ReferenceType {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef(val : T) : ReferenceType {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue(win : CrossDomainWindowType, ref : ReferenceType) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef(win : CrossDomainWindowType, ref : ReferenceType) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType\n|};\n\ntype CrossDomainSerializeOptions = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType\n|};\n\nexport function crossDomainDeserialize({ data, sender, basic = false } : CrossDomainDeserializeOptions) : CrossDomainDeserializedMessage {\n const message : Message = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from 'cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: ('string' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from 'cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = windowName.split('__');\n\n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n\n if (!name) {\n throw new Error(`Expected component name`);\n }\n\n if (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload,\n reference : ReferenceType\n|};\n\nconst parseInitialParentPayload = memoize((windowName : string) : InitialParentPayload => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload() : InitialParentPayload {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType, props : PropsType

, origin : string, helpers : ChildHelpers, isUpdate : boolean = false) : ChildPropsType {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from 'cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise,\n getSiblings : getSiblingsPropType\n|};\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent = {|\n getProps : () => ChildPropsType,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent(options : NormalizedComponentOptionsType) : ChildComponent {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return getAutoResize().then(({ width, height, element }) => {\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from 'cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type exportPropType = (X) => ZalgoPromise;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\nexport type contextPropType = string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType

,\n export : exportPropType\n|};\n\nexport type PropsInputType

= {|\n parent? : ParentPropType,\n \n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : ?cspNoncePropType,\n context? : ?contextPropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

,\n\n ...P\n|};\n\nexport type PropsType

= {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n context? : ?contextPropType,\n dimensions : CssDimensionsType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise;\n\nexport type ChildPropsType = {|\n ...PropsType

,\n\n parent? : ParentPropType,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType

,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n // eslint-disable-next-line no-undef\n queryValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P, X> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType = {|\n [string] : MixedPropDefinitionType\n|};\n\nexport type BuiltInPropsDefinitionType = {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n uid : StringPropDefinitionType,\n tag : StringPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n export : FunctionPropDefinitionType, P, X>,\n getSiblings : FunctionPropDefinitionType,\n context : StringPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P, X>\n|};\n\nexport type PropsDefinitionType = {|\n ...BuiltInPropsDefinitionType,\n [ string ] : MixedPropDefinitionType\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = ({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps() : BuiltInPropsDefinitionType {\n return {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n context: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback =\n ((string, BooleanPropDefinitionType | void, boolean) => R) &\n ((string, StringPropDefinitionType | void, string) => R) &\n ((string, NumberPropDefinitionType | void, number) => R) &\n ((string, FunctionPropDefinitionType | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType | void, Object) => R);\n\nexport function eachProp(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) : $ReadOnlyArray {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps(propsDef : PropsDefinitionType, existingProps : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps(propsDef : PropsDefinitionType, props : (PropsType

), method : $Values) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType = {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n childDomainMatch : DomainMatcher,\n props : PropsType

,\n exports : ParentExportsType\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise;\n\ntype RenderContainerOptions = {|\n context : $Values,\n proxyFrame : ?ProxyObject,\n proxyPrerenderFrame : ?ProxyObject,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise;\ntype RejectInitPromise = (mixed) => ZalgoPromise;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, RenderContainerOptions) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values|}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState,\n resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values,\n rerender : Rerender\n|};\n\ntype ParentComponent = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise,\n getProps : () => PropsType

,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise,\n getExports : () => X\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions = {|\n uid : string,\n options : NormalizedComponentOptionsType,\n overrides? : ParentDelegateOverrides

,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions) : ParentComponent {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType

= overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return rejectInitPromise(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__${ ZOID }_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getCurrentWindowReferenceUID = () : string => {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childDomain : string, childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin.setName(windowName).then(() => {\n return proxyWin;\n });\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow, context : $Values) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n const exportsPromise : ZalgoPromise = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType

) : ZalgoPromise {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values|} = {}) : ZalgoPromise> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|} = {}) : ZalgoPromise => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|}) : ZalgoPromise => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values|}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, initialChildDomain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType

= getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = ({ target, container, context, rerender } : RenderOptions) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, initialChildDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\n };\n}\n","/* @flow */\n/* eslint react/no-deprecated: off, react/no-find-dom-node: off, react/display-name: off, react/no-did-mount-set-state: off, react/destructuring-assignment: off, react/prop-types: off */\n\nimport { extend, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\ndeclare class ReactClassType {}\ndeclare class __ReactComponent {}\n\ntype ReactElementType = {|\n\n|};\n\ntype ReactType = {|\n Component : __ReactComponent,\n createClass : ({| render : () => ReactElementType, componentDidMount : () => void, componentDidUpdate : () => void |}) => (typeof ReactClassType),\n createElement : (string, ?{ [string] : mixed }, ...children : $ReadOnlyArray) => ReactElementType\n|};\n\ntype ReactDomType = {|\n findDOMNode : (typeof ReactClassType) => HTMLElement\n|};\n\ntype ReactLibraryType = {|\n React : ReactType,\n ReactDOM : ReactDomType\n|};\n\nexport const react : ComponentDriverType<*, ReactLibraryType, typeof ReactClassType, *, *> = {\n\n register: (tag, propsDef, init, { React, ReactDOM }) => {\n\n // $FlowFixMe\n return class extends React.Component {\n render() : ReactElementType {\n return React.createElement('div', null);\n }\n\n componentDidMount() {\n // $FlowFixMe\n const el = ReactDOM.findDOMNode(this);\n const parent = init(extend({}, this.props));\n parent.render(el, this.props.context);\n this.setState({ parent });\n }\n\n componentDidUpdate() {\n\n if (this.state && this.state.parent) {\n this.state.parent.updateProps(extend({}, this.props)).catch(noop);\n }\n }\n };\n }\n};\n","/* @flow */\n\nimport { noop, dasherizeToCamel } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\ntype VueComponent = {|\n render : (Function) => Element,\n inheritAttrs : boolean,\n mounted : () => void,\n watch : {|\n $attrs : {|\n deep : boolean,\n handler : () => void\n |}\n |}\n|};\n\ntype RegisteredVueComponent = {|\n \n|};\n\ntype VueType = {|\n component : (string, VueComponent) => RegisteredVueComponent\n|};\n\nfunction propsToCamelCase(props : Object) : Object {\n return Object.keys(props).reduce((acc, key) => {\n const value = props[key];\n // In vue `style` is a reserved prop name\n if (key === 'style-object' || key === 'styleObject') {\n acc.style = value;\n // To keep zoid as generic as possible, passing in the original prop name as well\n acc.styleObject = value;\n } else if (key.includes('-')) {\n acc[dasherizeToCamel(key)] = value;\n } else {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\nexport const vue : ComponentDriverType<*, VueType, RegisteredVueComponent, *, *> = {\n\n register: (tag, propsDef, init, Vue) => {\n\n return Vue.component(tag, {\n render(createElement) : Element {\n return createElement('div');\n },\n\n inheritAttrs: false,\n\n mounted() {\n // $FlowFixMe[object-this-reference]\n const el = this.$el;\n // $FlowFixMe[object-this-reference]\n this.parent = init({ ...propsToCamelCase(this.$attrs) });\n // $FlowFixMe[object-this-reference]\n this.parent.render(el, this.$attrs.context);\n },\n\n watch: {\n $attrs: {\n handler: function handler() {\n if (this.parent && this.$attrs) {\n this.parent.updateProps({ ...this.$attrs }).catch(noop);\n }\n },\n deep: true\n }\n }\n });\n }\n};\n","/* @flow */\nimport { dasherizeToCamel, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\nfunction propsToCamelCase(props : Object) : Object {\n return Object.keys(props).reduce((acc, key) => {\n const value = props[key];\n // In vue `style` is a reserved prop name\n if (key === 'style-object' || key === 'styleObject') {\n acc.style = value;\n // To keep zoid as generic as possible, passing in the original prop name as well\n acc.styleObject = value;\n } else if (key.includes('-')) {\n acc[dasherizeToCamel(key)] = value;\n } else {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\nexport const vue3 : ComponentDriverType<*, *, *, *, *> = {\n register: (tag, propsDef, init) => {\n return {\n template: `

`,\n\n inheritAttrs: false,\n\n mounted() {\n // $FlowFixMe[object-this-reference]\n const el = this.$el;\n // $FlowFixMe[object-this-reference]\n this.parent = init({ ...propsToCamelCase(this.$attrs) });\n // $FlowFixMe[object-this-reference]\n this.parent.render(el, this.$attrs.context);\n },\n\n watch: {\n $attrs: {\n handler: function handler() {\n if (this.parent && this.$attrs) {\n this.parent.updateProps({ ...this.$attrs }).catch(noop);\n }\n },\n deep: true\n }\n }\n };\n\n }\n};\n","/* @flow */\n\nimport { dasherizeToCamel, replaceObject, noop } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\ntype AngularModule = {|\n directive : (string, () => {|\n scope : { [string] : '=' | '@' },\n restrict : string,\n controller : $ReadOnlyArray\n |}) => AngularModule\n|};\n\ntype Angular = {|\n module : (string, $ReadOnlyArray) => AngularModule\n|};\n\nexport const angular : ComponentDriverType<*, Angular, AngularModule, *, *> = {\n\n register: (tag, propsDef, init, ng) => {\n\n const module = ng.module(tag, []).directive(dasherizeToCamel(tag), () => {\n\n const scope = {};\n\n for (const key of Object.keys(propsDef)) {\n scope[key] = '=';\n }\n\n scope.props = '=';\n\n return {\n scope,\n\n restrict: 'E',\n\n controller: [ '$scope', '$element', ($scope, $element) => {\n function safeApply() {\n if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {\n try {\n $scope.$apply();\n } catch (err) {\n // pass\n }\n }\n }\n\n const getProps = () => {\n return replaceObject($scope.props, item => {\n if (typeof item === 'function') {\n return function angularWrapped() : mixed {\n // $FlowFixMe\n const result = item.apply(this, arguments);\n safeApply();\n return result;\n };\n }\n return item;\n });\n };\n\n const props = getProps();\n const instance = init(props);\n instance.render($element[0], props.context);\n\n $scope.$watch(() => {\n instance.updateProps(getProps()).catch(noop);\n });\n } ]\n };\n });\n\n return module;\n }\n};\n","/* @flow */\n/* eslint new-cap: 0 */\n\nimport { replaceObject } from 'belter/src';\n\nimport type { ComponentDriverType } from '../component';\n\ntype Angular2Injection = {||};\n\ntype Angular2Component = {||};\n\ntype Angular2Module = {| annotations : Object, name : string |};\n\ntype Angular2 = {|\n Component : ({| selector : string, template : string, inputs : $ReadOnlyArray |}) => {|\n Class : ({| constructor : $ReadOnlyArray, ngOnInit : () => void, ngDoCheck : () => void |}) => Angular2Component\n |},\n NgModule : ({| declarations : $ReadOnlyArray<*>, exports : $ReadOnlyArray<*> |}) => {|\n Class : ({| constructor : () => void |}) => Angular2Module\n |},\n ElementRef : Angular2Injection,\n NgZone : Angular2Injection,\n Inject : Function\n|};\n\nconst equals = (obj1, obj2) => {\n const checked = {};\n\n for (const key in obj1) {\n if (obj1.hasOwnProperty(key)) {\n checked[key] = true;\n\n if (obj1[key] !== obj2[key]) {\n return false;\n }\n }\n }\n\n for (const key in obj2) {\n if (!checked[key]) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const angular2 : ComponentDriverType<*, Angular2, Angular2Module, *, *> = {\n\n register: (tag, propsDef, init, { Component : AngularComponent, NgModule, ElementRef, NgZone, Inject }) => {\n class ComponentInstance {\n elementRef : Object;\n internalProps : Object;\n parent : Object;\n props : Object;\n zone : Object;\n _props : Object;\n\n static annotations : $ReadOnlyArray<*>;\n static parameters : $ReadOnlyArray<*>;\n\n constructor (elementRef, zone) {\n this._props = {};\n this.elementRef = elementRef;\n this.zone = zone;\n }\n\n getProps () : Object {\n return replaceObject({ ...this.internalProps, ...this.props }, item => {\n if (typeof item === 'function') {\n const { zone } = this;\n return function angular2Wrapped() : void {\n // $FlowFixMe\n return zone.run(() => item.apply(this, arguments));\n };\n }\n return item;\n });\n }\n\n ngOnInit() {\n const targetElement = this.elementRef.nativeElement;\n const props = this.getProps();\n this.parent = init(props);\n this.parent.render(targetElement, props.context);\n }\n\n ngDoCheck() {\n if (this.parent && !equals(this._props, this.props)) {\n this._props = { ...this.props };\n this.parent.updateProps(this.getProps());\n }\n }\n }\n\n ComponentInstance.parameters = [\n [ new Inject(ElementRef) ],\n [ new Inject(NgZone) ]\n ];\n\n ComponentInstance.annotations = [\n new AngularComponent({\n selector: tag,\n template: `
`,\n inputs: [ 'props' ]\n })\n ];\n\n class ModuleInstance {\n static annotations : $ReadOnlyArray<*>;\n }\n\n ModuleInstance.annotations = [\n new NgModule({\n declarations: [ ComponentInstance ],\n exports: [ ComponentInstance ]\n })\n ];\n\n return ModuleInstance;\n }\n};\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType

) : ?HTMLElement {\n const { width, height } = dimensions;\n\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { type RenderOptionsType } from '../../parent/parent';\n\nexport function defaultPrerenderTemplate

({ doc, props } : RenderOptionsType

) : ?HTMLElement {\n if (__ZOID__.__DEFAULT_PRERENDER__) {\n const html = doc.createElement('html');\n const body = doc.createElement('body');\n const style = doc.createElement('style');\n const spinner = doc.createElement('div');\n spinner.classList.add('spinner');\n\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n html.appendChild(body);\n body.appendChild(spinner);\n body.appendChild(style);\n style.appendChild(doc.createTextNode(`\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n `));\n\n return html;\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition = ({|\n getExports : () => ZalgoPromise\n|}) => X;\n\nexport type ExportsDefinition = ExportsConfigDefinition | ExportsMapperDefinition;\n\nexport type ComponentOptionsType = {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values,\n\n props? : UserPropsDefinitionType,\n\n dimensions? : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType

|}) => Attributes,\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values,\n\n propsDef : PropsDefinitionType,\n dimensions : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition\n|};\n\nexport type ZoidComponentInstance = {|\n ...ParentHelpers

,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance,\n render : (container? : ContainerReferenceType, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent = {\n (props? : PropsInputType

| void) : ZoidComponentInstance,\n // eslint-disable-next-line no-undef\n driver : (string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n instances : $ReadOnlyArray>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = () : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions(options : ComponentOptionsType) : NormalizedComponentOptionsType {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop },\n exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component = {|\n init : (props? : PropsInputType

| void) => ZoidComponentInstance,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent\n|};\n\nexport function component(opts : ComponentOptionsType) : Component {\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible,\n children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent => {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : ContainerReferenceType) : ContainerReferenceType => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType

| void) : ZoidComponentInstance => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType

= parent.getProps();\n const parentExport : exportPropType = parent.export;\n\n const childParent : ParentPropType = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, vue3, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L) => D\n|};\n\nexport type ZoidProps

= PropsType

;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = (options : ComponentOptionsType) => ZoidComponent;\n\nexport const create : CreateZoidComponent = (options : ComponentOptionsType) : ZoidComponent => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType

| void) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n};\n\nexport function destroyComponents(err? : mixed) : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/zoid.js b/dist/zoid.js index 7df5024d..2e06c5ca 100644 --- a/dist/zoid.js +++ b/dist/zoid.js @@ -423,6 +423,10 @@ function isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } + var WINDOW_TYPE = { + IFRAME: "iframe", + POPUP: "popup" + }; var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; function getActualProtocol(win) { void 0 === win && (win = window); @@ -678,6 +682,13 @@ } return !1; } + function getDistanceFromTop(win) { + void 0 === win && (win = window); + var distance = 0; + var parent = win; + for (;parent; ) (parent = utils_getParent(parent)) && (distance += 1); + return distance; + } function isSameTopWindow(win1, win2) { var top1 = getTop(win1) || win1; var top2 = getTop(win2) || win2; @@ -705,6 +716,26 @@ function getDomainFromUrl(url) { return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : getDomain(); } + function onCloseWindow(win, callback, delay, maxtime) { + void 0 === delay && (delay = 1e3); + void 0 === maxtime && (maxtime = 1 / 0); + var timeout; + !function check() { + if (isWindowClosed(win)) { + timeout && clearTimeout(timeout); + return callback(); + } + if (maxtime <= 0) clearTimeout(timeout); else { + maxtime -= delay; + timeout = setTimeout(check, delay); + } + }(); + return { + cancel: function() { + timeout && clearTimeout(timeout); + } + }; + } function isWindow(obj) { try { if (obj === window) return !0; @@ -746,6 +777,11 @@ } catch (err) {} return !1; } + function normalizeMockUrl(url) { + if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; + var domain; + throw new Error("Mock urls not supported out of test mode"); + } function getFrameForWindow(win) { if (isSameDomain(win)) return assertSameDomain(win).frameElement; for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { @@ -1814,11 +1850,7 @@ function setupBridge(_ref) { var on = _ref.on, send = _ref.send, receiveMessage = _ref.receiveMessage; windowOpen = window.open, window.open = function(url, name, options, last) { - var win = windowOpen.call(this, function(url) { - if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; - var domain; - throw new Error("Mock urls not supported out of test mode"); - }(url), name, options, last); + var win = windowOpen.call(this, normalizeMockUrl(url), name, options, last); if (!win) return win; linkWindow({ win: win, @@ -2005,7 +2037,7 @@ })); var windowTypePromise = winPromise.then((function(window) { if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type"); - return getOpener(window) ? "popup" : "iframe"; + return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME; })); windowNamePromise.catch(src_util_noop); windowTypePromise.catch(src_util_noop); @@ -2127,7 +2159,7 @@ }; _proto.isPopup = function() { return this.getType().then((function(type) { - return "popup" === type; + return type === WINDOW_TYPE.POPUP; })); }; _proto.setLocation = function(href, opts) { @@ -2982,347 +3014,10 @@ bridges.reset(); } }; - function src_util_isRegex(item) { - return "[object RegExp]" === {}.toString.call(item); - } - function utils_getActualProtocol(win) { - void 0 === win && (win = window); - return win.location.protocol; - } - function utils_getProtocol(win) { - void 0 === win && (win = window); - if (win.mockDomain) { - var protocol = win.mockDomain.split("//")[0]; - if (protocol) return protocol; - } - return utils_getActualProtocol(win); - } - function utils_isAboutProtocol(win) { - void 0 === win && (win = window); - return "about:" === utils_getProtocol(win); - } - function src_utils_getParent(win) { - void 0 === win && (win = window); - if (win) try { - if (win.parent && win.parent !== win) return win.parent; - } catch (err) {} - } - function utils_getOpener(win) { - void 0 === win && (win = window); - if (win && !src_utils_getParent(win)) try { - return win.opener; - } catch (err) {} - } - function utils_canReadFromWindow(win) { - try { - return !0; - } catch (err) {} - return !1; - } - function utils_getActualDomain(win) { - void 0 === win && (win = window); - var location = win.location; - if (!location) throw new Error("Can not read window location"); - var protocol = utils_getActualProtocol(win); - if (!protocol) throw new Error("Can not read window protocol"); - if ("file:" === protocol) return "file://"; - if ("about:" === protocol) { - var parent = src_utils_getParent(win); - return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://"; - } - var host = location.host; - if (!host) throw new Error("Can not read window host"); - return protocol + "//" + host; - } - function utils_getDomain(win) { - void 0 === win && (win = window); - var domain = utils_getActualDomain(win); - return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; - } - function utils_isSameDomain(win) { - if (!function(win) { - try { - if (win === window) return !0; - } catch (err) {} - try { - var desc = Object.getOwnPropertyDescriptor(win, "location"); - if (desc && !1 === desc.enumerable) return !1; - } catch (err) {} - try { - if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; - } catch (err) {} - try { - if (function(win) { - void 0 === win && (win = window); - return "mock:" === utils_getProtocol(win); - }(win) && utils_canReadFromWindow()) return !0; - } catch (err) {} - try { - if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0; - } catch (err) {} - return !1; - }(win)) return !1; - try { - if (win === window) return !0; - if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; - if (utils_getDomain(window) === utils_getDomain(win)) return !0; - } catch (err) {} - return !1; - } - function utils_assertSameDomain(win) { - if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain"); - return win; - } - function utils_isAncestorParent(parent, child) { - if (!parent || !child) return !1; - var childParent = src_utils_getParent(child); - return childParent ? childParent === parent : -1 !== function(win) { - var result = []; - try { - for (;win.parent !== win; ) { - result.push(win.parent); - win = win.parent; - } - } catch (err) {} - return result; - }(child).indexOf(parent); - } - function utils_getFrames(win) { - var result = []; - var frames; - try { - frames = win.frames; - } catch (err) { - frames = win; - } - var len; - try { - len = frames.length; - } catch (err) {} - if (0 === len) return result; - if (len) { - for (var i = 0; i < len; i++) { - var frame = void 0; - try { - frame = frames[i]; - } catch (err) { - continue; - } - result.push(frame); - } - return result; - } - for (var _i = 0; _i < 100; _i++) { - var _frame = void 0; - try { - _frame = frames[_i]; - } catch (err) { - return result; - } - if (!_frame) return result; - result.push(_frame); - } - return result; - } - function utils_getAllChildFrames(win) { - var result = []; - for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) { - var frame = _getFrames2[_i3]; - result.push(frame); - for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); - } - return result; - } - function utils_getTop(win) { - void 0 === win && (win = window); - try { - if (win.top) return win.top; - } catch (err) {} - if (src_utils_getParent(win) === win) return win; - try { - if (utils_isAncestorParent(window, win) && window.top) return window.top; - } catch (err) {} - try { - if (utils_isAncestorParent(win, window) && window.top) return window.top; - } catch (err) {} - for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { - var frame = _getAllChildFrames4[_i7]; - try { - if (frame.top) return frame.top; - } catch (err) {} - if (src_utils_getParent(frame) === frame) return frame; - } - } - function utils_getAllFramesInWindow(win) { - var top = utils_getTop(win); - if (!top) throw new Error("Can not determine top window"); - var result = [].concat(utils_getAllChildFrames(top), [ top ]); - -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win))); - return result; - } - var utils_iframeWindows = []; - var utils_iframeFrames = []; - function utils_isWindowClosed(win, allowMock) { - void 0 === allowMock && (allowMock = !0); - try { - if (win === window) return !1; - } catch (err) { - return !0; - } - try { - if (!win) return !0; - } catch (err) { - return !0; - } - try { - if (win.closed) return !0; - } catch (err) { - return !err || "Call was rejected by callee.\r\n" !== err.message; - } - if (allowMock && utils_isSameDomain(win)) try { - if (win.mockclosed) return !0; - } catch (err) {} - try { - if (!win.parent || !win.top) return !0; - } catch (err) {} - var iframeIndex = function(collection, item) { - for (var i = 0; i < collection.length; i++) try { - if (collection[i] === item) return i; - } catch (err) {} - return -1; - }(utils_iframeWindows, win); - if (-1 !== iframeIndex) { - var frame = utils_iframeFrames[iframeIndex]; - if (frame && function(frame) { - if (!frame.contentWindow) return !0; - if (!frame.parentNode) return !0; - var doc = frame.ownerDocument; - if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { - var parent = frame; - for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; - if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; - } - return !1; - }(frame)) return !0; - } - return !1; - } - function utils_getFrameByName(win, name) { - var winFrames = utils_getFrames(win); - for (var _i9 = 0; _i9 < winFrames.length; _i9++) { - var childFrame = winFrames[_i9]; - try { - if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; - } catch (err) {} - } - try { - if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; - } catch (err) {} - try { - if (-1 !== winFrames.indexOf(win[name])) return win[name]; - } catch (err) {} - } - function utils_getAncestor(win) { - void 0 === win && (win = window); - return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0; - } - function utils_anyMatch(collection1, collection2) { - for (var _i17 = 0; _i17 < collection1.length; _i17++) { - var item1 = collection1[_i17]; - for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; - } - return !1; - } - function utils_getDistanceFromTop(win) { - void 0 === win && (win = window); - var distance = 0; - var parent = win; - for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1); - return distance; - } - function utils_matchDomain(pattern, origin) { - if ("string" == typeof pattern) { - if ("string" == typeof origin) return "*" === pattern || origin === pattern; - if (src_util_isRegex(origin)) return !1; - if (Array.isArray(origin)) return !1; - } - return src_util_isRegex(pattern) ? src_util_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) : !src_util_isRegex(origin) && pattern.some((function(subpattern) { - return utils_matchDomain(subpattern, origin); - }))); - } - function utils_getDomainFromUrl(url) { - return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain(); - } - function utils_onCloseWindow(win, callback, delay, maxtime) { - void 0 === delay && (delay = 1e3); - void 0 === maxtime && (maxtime = 1 / 0); - var timeout; - !function check() { - if (utils_isWindowClosed(win)) { - timeout && clearTimeout(timeout); - return callback(); - } - if (maxtime <= 0) clearTimeout(timeout); else { - maxtime -= delay; - timeout = setTimeout(check, delay); - } - }(); - return { - cancel: function() { - timeout && clearTimeout(timeout); - } - }; - } - function utils_isWindow(obj) { - try { - if (obj === window) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if ("[object Window]" === {}.toString.call(obj)) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (window.Window && obj instanceof window.Window) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.self === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.parent === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && obj.top === obj) return !0; - } catch (err) { - if (err && "Call was rejected by callee.\r\n" === err.message) return !0; - } - try { - if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; - } catch (err) { - return !0; - } - try { - if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; - } catch (err) {} - return !1; - } - function utils_normalizeMockUrl(url) { - if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; - var domain; - throw new Error("Mock urls not supported out of test mode"); - } function lib_global_getGlobal(win) { - if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain"); - win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {}); - return win.__zoid_9_0_87__; + if (!isSameDomain(win)) throw new Error("Can not get global for window on different domain"); + win.__zoid_9_0_88__ || (win.__zoid_9_0_88__ = {}); + return win.__zoid_9_0_88__; } function tryGlobal(win, handler) { try { @@ -3433,10 +3128,7 @@ DOTIFY: "dotify", BASE64: "base64" }; - var CONTEXT = { - IFRAME: "iframe", - POPUP: "popup" - }; + var CONTEXT = WINDOW_TYPE; var EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", @@ -3468,7 +3160,7 @@ sender: { win: function(_ref2) { return function(windowRef) { - if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window)); + if ("opener" === windowRef.type) return assertExists("opener", getOpener(window)); if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) { void 0 === n && (n = 1); return function(win, n) { @@ -3476,19 +3168,19 @@ var parent = win; for (var i = 0; i < n; i++) { if (!parent) return; - parent = src_utils_getParent(parent); + parent = utils_getParent(parent); } return parent; - }(win, utils_getDistanceFromTop(win) - n); + }(win, getDistanceFromTop(win) - n); }(window, windowRef.distance)); if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) { var _ret = function() { var uid = windowRef.uid; - var ancestor = utils_getAncestor(window); + var ancestor = getAncestor(window); if (!ancestor) throw new Error("Can not find ancestor window"); - for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { + for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { var frame = _getAllFramesInWindow2[_i2]; - if (utils_isSameDomain(frame)) { + if (isSameDomain(frame)) { var win = tryGlobal(frame, (function(global) { return global.windows && global.windows[uid]; })); @@ -3502,15 +3194,15 @@ } else if ("name" === windowRef.type) { var name = windowRef.name; return assertExists("namedWindow", function(win, name) { - return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) { - var frame = utils_getFrameByName(win, name); + return getFrameByName(win, name) || function findChildFrameByName(win, name) { + var frame = getFrameByName(win, name); if (frame) return frame; - for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) { - var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name); + for (var _i11 = 0, _getFrames4 = getFrames(win); _i11 < _getFrames4.length; _i11++) { + var namedFrame = findChildFrameByName(_getFrames4[_i11], name); if (namedFrame) return namedFrame; } - }(utils_getTop(win) || win, name); - }(assertExists("ancestor", utils_getAncestor(window)), name)); + }(getTop(win) || win, name); + }(assertExists("ancestor", getAncestor(window)), name)); } throw new Error("Unable to find " + windowRef.type + " parent component window"); }(_ref2.metaData.windowRef); @@ -3528,15 +3220,15 @@ } function window_getWindowRef(targetWindow, currentWindow) { void 0 === currentWindow && (currentWindow = window); - if (targetWindow === src_utils_getParent(currentWindow)) return { + if (targetWindow === utils_getParent(currentWindow)) return { type: "parent", - distance: utils_getDistanceFromTop(targetWindow) + distance: getDistanceFromTop(targetWindow) }; - if (targetWindow === utils_getOpener(currentWindow)) return { + if (targetWindow === getOpener(currentWindow)) return { type: "opener" }; - if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) { - var windowName = utils_assertSameDomain(targetWindow).name; + if (isSameDomain(targetWindow) && !(win = targetWindow, win === getTop(win))) { + var windowName = assertSameDomain(targetWindow).name; if (windowName) return { type: "name", name: windowName @@ -3744,7 +3436,7 @@ for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; - prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]); + prop && !1 === prop.sendToChild || prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window)) || (result[key] = props[key]); } return promise_ZalgoPromise.hash(result); }; @@ -3805,7 +3497,7 @@ }) : attributes; }; var getInitialChildDomain = function() { - return utils_getDomainFromUrl(getUrl()); + return getDomainFromUrl(getUrl()); }; var openFrame = function(context, _ref2) { var windowName = _ref2.windowName; @@ -3839,7 +3531,7 @@ return destroyElement(prerenderFrame); })); return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) { - return utils_assertSameDomain(prerenderFrameWindow); + return assertSameDomain(prerenderFrameWindow); })).then((function(win) { return setup_toProxyWindow(win); })); @@ -3864,7 +3556,7 @@ return uid; }; var getWindowRef = function(target, initialChildDomain, context, proxyWin) { - if (initialChildDomain === utils_getDomain(window)) return { + if (initialChildDomain === getDomain(window)) return { type: "global", uid: getCurrentWindowReferenceUID() }; @@ -3872,14 +3564,14 @@ if (props.window) { var actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop"); - if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); + if (getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); } if (context === CONTEXT.POPUP) return { type: "opener" }; if (context === CONTEXT.IFRAME) return { type: "parent", - distance: utils_getDistanceFromTop(window) + distance: getDistanceFromTop(window) }; throw new Error("Can not construct window reference for child"); }; @@ -3914,7 +3606,7 @@ var close = memoize((function(err) { return promise_ZalgoPromise.try((function() { if (closeOverride) { - if (utils_isWindowClosed(closeOverride.__source__)) return; + if (isWindowClosed(closeOverride.__source__)) return; return closeOverride(); } return promise_ZalgoPromise.try((function() { @@ -3991,27 +3683,7 @@ height: height }, getAttributes().popup)); clean.register((function() { - return function(win) { - if (function(win) { - void 0 === win && (win = window); - return Boolean(src_utils_getParent(win)); - }(win)) { - var frame = function(win) { - if (utils_isSameDomain(win)) return utils_assertSameDomain(win).frameElement; - for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { - var frame = _document$querySelect2[_i21]; - if (frame && frame.contentWindow && frame.contentWindow === win) return frame; - } - }(win); - if (frame && frame.parentElement) { - frame.parentElement.removeChild(frame); - return; - } - } - try { - win.close(); - } catch (err) {} - }(win); + return closeWindow(win); })); clean.register((function() { return cleanUpWindow(win); @@ -4033,7 +3705,7 @@ var unloadWindowListener = addEventListener(window, "unload", once((function() { destroy(new Error("Window navigated away")); }))); - var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3); + var closeParentWindowListener = onCloseWindow(parentWin, destroy, 3e3); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) return watchForUnloadOverride(); @@ -4098,14 +3770,14 @@ }) : promise_ZalgoPromise.try((function() { if (prerenderTemplate) { var prerenderWindow = proxyPrerenderWin.getWindow(); - if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) { + if (prerenderWindow && isSameDomain(prerenderWindow) && function(win) { try { if (!win.location.href) return !0; if ("about:blank" === win.location.href) return !0; } catch (err) {} return !1; }(prerenderWindow)) { - var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document; + var doc = (prerenderWindow = assertSameDomain(prerenderWindow)).document; var el = renderTemplate(prerenderTemplate, { context: context, doc: doc @@ -4389,22 +4061,9 @@ var childDomainMatch = domainMatch || getInitialChildDomain(); !function(target, childDomainMatch, container) { if (target !== window) { - if (!function(win1, win2) { - var top1 = utils_getTop(win1) || win1; - var top2 = utils_getTop(win2) || win2; - try { - if (top1 && top2) return top1 === top2; - } catch (err) {} - var allFrames1 = utils_getAllFramesInWindow(win1); - var allFrames2 = utils_getAllFramesInWindow(win2); - if (utils_anyMatch(allFrames1, allFrames2)) return !0; - var opener1 = utils_getOpener(top1); - var opener2 = utils_getOpener(top2); - return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1), - !1; - }(window, target)) throw new Error("Can only renderTo an adjacent frame"); - var origin = utils_getDomain(); - if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); + if (!isSameTopWindow(window, target)) throw new Error("Can only renderTo an adjacent frame"); + var origin = getDomain(); + if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }"); } }(target, childDomainMatch, container); @@ -4431,7 +4090,7 @@ }).then((function(_ref13) { var parentComp = _ref13.data.parent; clean.register((function(err) { - if (!utils_isWindowClosed(target)) return parentComp.destroy(err); + if (!isWindowClosed(target)) return parentComp.destroy(err); })); return parentComp.getDelegateOverrides(); })).catch((function(err) { @@ -4538,7 +4197,7 @@ queryString && (originalUrl = originalUrl + "?" + queryString); hashString && (originalUrl = originalUrl + "#" + hashString); return originalUrl; - }(utils_normalizeMockUrl(getUrl()), { + }(normalizeMockUrl(getUrl()), { query: query }); })); @@ -4554,7 +4213,7 @@ context: context, tag: tag, childDomainMatch: childDomainMatch, - version: "9_0_87", + version: "9_0_88", props: childProps, exports: (win = proxyWin, { init: function(childExports) { @@ -4585,13 +4244,13 @@ windowRef: getWindowRef(target, initialChildDomain, context, proxyWin) }, sender: { - domain: utils_getDomain(window) + domain: getDomain(window) }, receiver: { win: proxyWin, domain: childDomainMatch }, - passByReference: initialChildDomain === utils_getDomain() + passByReference: initialChildDomain === getDomain() }), serializedData = _crossDomainSerialize.serializedData; clean.register(_crossDomainSerialize.cleanReference); return serializedData; @@ -4722,9 +4381,9 @@ props: props }) : options.bridgeUrl; if (!bridgeUrl) throw new Error("Bridge needed to render " + context); - var bridgeDomain = utils_getDomainFromUrl(bridgeUrl); + var bridgeDomain = getDomainFromUrl(bridgeUrl); src_bridge.linkUrl(win, initialChildDomain); - return src_bridge.openBridge(utils_normalizeMockUrl(bridgeUrl), bridgeDomain); + return src_bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain); } })); }(proxyWin, initialChildDomain, context); @@ -4871,10 +4530,10 @@ allowDelegate: !0, validate: function(_ref2) { var value = _ref2.value; - if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); - if (utils_isWindow(value)) { - if (utils_isWindowClosed(value)) throw new Error("Window is closed"); - if (!utils_isSameDomain(value)) throw new Error("Window is not same domain"); + if (!isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); + if (isWindow(value)) { + if (isWindowClosed(value)) throw new Error("Window is closed"); + if (!isSameDomain(value)) throw new Error("Window is not same domain"); } }, decorate: function(_ref3) { @@ -4890,6 +4549,10 @@ type: PROP_TYPE.STRING, required: !1 }, + context: { + type: PROP_TYPE.STRING, + required: !1 + }, onDisplay: { type: PROP_TYPE.FUNCTION, required: !1, @@ -5099,7 +4762,7 @@ return !1; }(name)) { var _payload = getInitialParentPayload().payload; - if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0; + if (_payload.tag === tag && matchDomain(_payload.childDomainMatch, getDomain())) return !0; } return !1; }; @@ -5117,7 +4780,7 @@ var props; var exportsPromise = new promise_ZalgoPromise; var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props; - if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87"); + if ("9_0_88" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_88"); var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init; var getParent = function() { return parentComponentWindow; @@ -5149,10 +4812,10 @@ var currentParent = props.parent; void 0 === anyParent && (anyParent = !currentParent); if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child"); - for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { + for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { var win = _getAllFramesInWindow2[_i2]; - if (utils_isSameDomain(win)) { - var xprops = utils_assertSameDomain(win).xprops; + if (isSameDomain(win)) { + var xprops = assertSameDomain(win).xprops; if (xprops && getParent() === xprops.getParent()) { var winParent = xprops.parent; if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) { @@ -5177,7 +4840,7 @@ for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; - if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) { + if (!prop || !prop.sameDomain || origin === getDomain(window) && isSameDomain(parentComponentWindow)) { var value = normalizeChildProp(propsDef, 0, key, props[key], helpers); result[key] = value; prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value); @@ -5214,7 +4877,7 @@ return { init: function() { return promise_ZalgoPromise.try((function() { - utils_isSameDomain(parentComponentWindow) && function(_ref3) { + isSameDomain(parentComponentWindow) && function(_ref3) { var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow; var _crossDomainDeseriali2 = crossDomainDeserialize({ data: parseWindowName(window.name).serializedInitialPayload, @@ -5234,7 +4897,7 @@ }, receiver: { win: window, - domain: utils_getDomain() + domain: getDomain() }, basic: !0 }); @@ -5253,7 +4916,7 @@ } }); !function(allowedParentDomains, domain) { - if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); + if (!matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); }(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); !function() { @@ -5263,7 +4926,7 @@ window.addEventListener("unload", (function() { checkClose.fireAndForget(); })); - utils_onCloseWindow(parentComponentWindow, (function() { + onCloseWindow(parentComponentWindow, (function() { child_destroy(); })); }(); @@ -5364,7 +5027,7 @@ throw err; })); } - if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo"); + if (!isWindow(target)) throw new Error("Must pass window to renderTo"); return function(props, context) { return promise_ZalgoPromise.try((function() { if (props.window) return setup_toProxyWindow(props.window).getType(); @@ -5555,7 +5218,7 @@ var destroyAll = destroyComponents; function component_destroy(err) { destroyAll(); - delete window.__zoid_9_0_87__; + delete window.__zoid_9_0_88__; !function() { !function() { var responseListeners = globalStore("responseListeners"); diff --git a/dist/zoid.min.js b/dist/zoid.min.js index be41860d..d74471f9 100644 --- a/dist/zoid.min.js +++ b/dist/zoid.min.js @@ -1,2 +1,2 @@ -!function(n,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("zoid",[],e):"object"==typeof exports?exports.zoid=e():n.zoid=e()}("undefined"!=typeof self?self:this,(function(){return function(n){var e={};function r(t){if(e[t])return e[t].exports;var o=e[t]={i:t,l:!1,exports:{}};return n[t].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=n,r.c=e,r.d=function(n,e,t){r.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:t})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,e){if(1&e&&(n=r(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var t=Object.create(null);if(r.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)r.d(t,o,function(e){return n[e]}.bind(null,o));return t},r.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(e,"a",e),e},r.o=function(n,e){return{}.hasOwnProperty.call(n,e)},r.p="",r(r.s=0)}([function(n,e,r){"use strict";function t(n,e){return(t=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function o(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,t(n,e)}function i(){return(i=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+wn(n,e+1)}}function hn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function pn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function vn(n){return n}function mn(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function yn(n){return[].slice.call(n)}function gn(n){return null!=n}function bn(n){return"[object RegExp]"==={}.toString.call(n)}function En(n,e,r){if(n.hasOwnProperty(e))return n[e];var t=r();return n[e]=t,t}function _n(n){var e,r=[],t=!1,o={set:function(e,r){return t||(n[e]=r,o.register((function(){delete n[e]}))),r},register:function(n){var o=ln((function(){return n(e)}));return t?n(e):r.push(o),{cancel:function(){var n=r.indexOf(o);-1!==n&&r.splice(n,1)}}},all:function(n){e=n;var o=[];for(t=!0;r.length;){var i=r.shift();o.push(i())}return h.all(o).then(sn)}};return o}function xn(n,e){if(null==e)throw new Error("Expected "+n+" to be present");return e}dn.clear=function(){cn=un},dn((function(n){if(Object.values)return Object.values(n);var e=[];for(var r in n)n.hasOwnProperty(r)&&e.push(n[r]);return e}));var Pn=function(n){function e(e){var r;return(r=n.call(this,e)||this).name=r.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(n){if(void 0===n)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}(r),r.constructor):r.stack=new Error(e).stack,r}return o(e,n),e}(K(Error));function On(){var n=document.body;if(!n)throw new Error("Body element not found");return n}function Cn(){return Boolean(document.body)&&"complete"===document.readyState}function Wn(){return Boolean(document.body)&&"interactive"===document.readyState}function Sn(n){return encodeURIComponent(n)}function Dn(n){return function(e,r,t){void 0===t&&(t=[]);var o=e.__inline_memoize_cache__=e.__inline_memoize_cache__||{},i=on(t);return o.hasOwnProperty(i)?o[i]:o[i]=function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var r=0,t=n.split("&");r { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||tn();n=Ie.unwrap(n);var d=r.__name__||r.name||t;return"string"==typeof d&&"function"==typeof d.indexOf&&0===d.indexOf("anonymous::")&&(d=d.replace("anonymous::",t+"::")),Ie.isProxyWindow(n)?(ze(c,r,d,n,e),n.awaitWindow().then((function(n){ze(c,r,d,n,e)}))):ze(c,r,d,n,e),pe("cross_domain_function",{id:c,name:d})}function Ue(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=ye);var r=JSON.stringify(n,(function(n){var r=this[n];if(we(this))return r;var t=he(r);if(!t)return r;var o=e[t]||me[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return pe("cross_domain_zalgo_promise",{then:Me(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return Me(n,e,r,t,{on:i,send:a})},o.object=function(n){return q(n)||Ie.isProxyWindow(n)?pe("cross_domain_window",Ie.serialize(n,{send:a})):n},o))}function Le(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=be),"undefined"!==n)return JSON.parse(n,(function(n,r){if(we(this))return r;var t,o;if(we(r)?(t=r.__type__,o=r.__val__):(t=he(r),o=r),!t)return o;var i=e[t]||ge[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new h(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return Ie.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=Fe(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:P()},u);var d=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:d},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:d},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return Ie.deserialize(n,{send:i})},o))}var Be={};function qe(n,e,r,t){var o=t.on,i=t.send;return h.try((function(){var t=ae().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||h.flush().then((function(){if(T(n))throw new Error("Window is closed");var r,a=Ue(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(Be),c=[],d=0;d1?e-1:0),o=1;o1?r-1:0),i=1;i iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),f.appendChild(r),f.appendChild(t),f.appendChild(s),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(Lr.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){Bn(t)}),1)})),a.on(Lr.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(f.style.width=Kn(e)),"number"==typeof r&&(f.style.height=Kn(r))})),f}}function rt(n){var e=n.doc,r=n.props,t=e.createElement("html"),o=e.createElement("body"),i=e.createElement("style"),a=e.createElement("div");return a.classList.add("spinner"),r.cspNonce&&i.setAttribute("nonce",r.cspNonce),t.appendChild(o),o.appendChild(a),o.appendChild(i),i.appendChild(e.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")),t}var tt=_n(),ot=_n();function it(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,d=void 0===c?{}:c,f=n.autoResize,s=void 0===f?{}:f,l=n.allowedParentDomains,w=void 0===l?"*":l,h=n.attributes,p=void 0===h?{}:h,v=n.defaultContext,m=void 0===v?Ur.IFRAME:v,y=n.containerTemplate,g=void 0===y?et:y,b=n.prerenderTemplate,E=void 0===b?rt:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,C=void 0===O?{info:sn}:O,W=n.exports,S=void 0===W?sn:W,D=n.method,N=n.children,j=void 0===N?function(){return{}}:N,A=e.replace(/-/g,"_"),k=i({},{window:{type:Fr.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!Dr(e)&&!Ie.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(Dr(e)){if(Er(e))throw new Error("Window is closed");if(!lr(e))throw new Error("Window is not same domain")}},decorate:function(n){return er(n.value)}},timeout:{type:Fr.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:Fr.STRING,required:!1},onDisplay:{type:Fr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Xr,decorate:$r},onRendered:{type:Fr.FUNCTION,required:!1,sendToChild:!1,default:Xr,decorate:$r},onRender:{type:Fr.FUNCTION,required:!1,sendToChild:!1,default:Xr,decorate:$r},onClose:{type:Fr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Xr,decorate:$r},onDestroy:{type:Fr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Xr,decorate:$r},onResize:{type:Fr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Xr},onFocus:{type:Fr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Xr},close:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:Fr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:Fr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:Fr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:A,tag:e,url:r,domain:t,bridgeUrl:o,method:D,propsDef:k,dimensions:d,autoResize:s,allowedParentDomains:w,attributes:p,defaultContext:m,containerTemplate:g,prerenderTemplate:E,validate:_,logger:C,eligible:P,children:j,exports:"function"==typeof S?S:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=S[o].type,a=e().then((function(n){return n[o]}));r[o]=i===Fr.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,r=0;r=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var r=n&&n.stack,t=n&&n.message;if(r&&t)return-1!==r.indexOf(t)?r:t+"\n"+r;if(r)return r;if(t)return t}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+vn(n,e+1)}}function yn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function gn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function bn(n){return n}function En(n,e){var r;return function t(){r=setTimeout((function(){n(),t()}),e)}(),{cancel:function(){clearTimeout(r)}}}function _n(n){return[].slice.call(n)}function xn(n){return null!=n}function Pn(n){return"[object RegExp]"==={}.toString.call(n)}function On(n,e,r){if(n.hasOwnProperty(e))return n[e];var t=r();return n[e]=t,t}function Cn(n){var e,r=[],t=!1,o={set:function(e,r){return t||(n[e]=r,o.register((function(){delete n[e]}))),r},register:function(n){var o=mn((function(){return n(e)}));return t?n(e):r.push(o),{cancel:function(){var n=r.indexOf(o);-1!==n&&r.splice(n,1)}}},all:function(n){e=n;var o=[];for(t=!0;r.length;){var i=r.shift();o.push(i())}return w.all(o).then(pn)}};return o}function Wn(n,e){if(null==e)throw new Error("Expected "+n+" to be present");return e}hn.clear=function(){ln=fn},hn((function(n){if(Object.values)return Object.values(n);var e=[];for(var r in n)n.hasOwnProperty(r)&&e.push(n[r]);return e}));var Sn=function(n){function e(e){var r;return(r=n.call(this,e)||this).name=r.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(n){if(void 0===n)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}(r),r.constructor):r.stack=new Error(e).stack,r}return o(e,n),e}(rn(Error));function Dn(){var n=document.body;if(!n)throw new Error("Body element not found");return n}function Nn(){return Boolean(document.body)&&"complete"===document.readyState}function An(){return Boolean(document.body)&&"interactive"===document.readyState}function Tn(n){return encodeURIComponent(n)}function jn(n){return function(e,r,t){void 0===t&&(t=[]);var o=e.__inline_memoize_cache__=e.__inline_memoize_cache__||{},i=sn(t);return o.hasOwnProperty(i)?o[i]:o[i]=function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var r=0,t=n.split("&");r { ... }":"<"+typeof n+">"})).join(", ")+") failed\n\n")+n.stack),n}))})).then((function(n){return{result:n,id:o,name:i}}))}))}));var c=r.__id__||cn();n=Ue.unwrap(n);var s=r.__name__||r.name||t;return"string"==typeof s&&"function"==typeof s.indexOf&&0===s.indexOf("anonymous::")&&(s=s.replace("anonymous::",t+"::")),Ue.isProxyWindow(n)?(Le(c,r,s,n,e),n.awaitWindow().then((function(n){Le(c,r,s,n,e)}))):Le(c,r,s,n,e),ge("cross_domain_function",{id:c,name:s})}function Je(n,e,r,t){var o,i=t.on,a=t.send;return function(n,e){void 0===e&&(e=_e);var r=JSON.stringify(n,(function(n){var r=this[n];if(ve(this))return r;var t=ye(r);if(!t)return r;var o=e[t]||Ee[t];return o?o(r,n):r}));return void 0===r?"undefined":r}(r,((o={}).promise=function(r,t){return function(n,e,r,t,o){return ge("cross_domain_zalgo_promise",{then:Be(n,e,(function(n,e){return r.then(n,e)}),t,{on:o.on,send:o.send})})}(n,e,r,t,{on:i,send:a})},o.function=function(r,t){return Be(n,e,r,t,{on:i,send:a})},o.object=function(n){return Y(n)||Ue.isProxyWindow(n)?ge("cross_domain_window",Ue.serialize(n,{send:a})):n},o))}function He(n,e,r,t){var o,i=t.send;return function(n,e){if(void 0===e&&(e=Pe),"undefined"!==n)return JSON.parse(n,(function(n,r){if(ve(this))return r;var t,o;if(ve(r)?(t=r.__type__,o=r.__val__):(t=ye(r),o=r),!t)return o;var i=e[t]||xe[t];return i?i(o,n):o}))}(r,((o={}).cross_domain_zalgo_promise=function(n){return function(n,e,r){return new w(r.then)}(0,0,n)},o.cross_domain_function=function(r){return function(n,e,r,t){var o=r.id,i=r.name,a=t.send,u=function(r){function t(){var u=arguments;return Ue.toProxyWindow(n,{send:a}).awaitWindow().then((function(n){var c=qe(n,o);if(c&&c.val!==t)return c.val.apply({source:window,origin:O()},u);var s=[].slice.call(u);return r.fireAndForget?a(n,"postrobot_method",{id:o,name:i,args:s},{domain:e,fireAndForget:!0}):a(n,"postrobot_method",{id:o,name:i,args:s},{domain:e,fireAndForget:!1}).then((function(n){return n.data.result}))})).catch((function(n){throw n}))}return void 0===r&&(r={}),t.__name__=i,t.__origin__=e,t.__source__=n,t.__id__=o,t.origin=e,t},c=u();return c.fireAndForget=u({fireAndForget:!0}),c}(n,e,r,{send:i})},o.cross_domain_window=function(n){return Ue.deserialize(n,{send:i})},o))}var Ye={};function Ze(n,e,r,t){var o=t.on,i=t.send;return w.try((function(){var t=de().getOrSet(n,(function(){return{}}));return t.buffer=t.buffer||[],t.buffer.push(r),t.flush=t.flush||w.flush().then((function(){if(k(n))throw new Error("Window is closed");var r,a=Je(n,e,((r={}).__post_robot_10_0_46__=t.buffer||[],r),{on:o,send:i});delete t.buffer;for(var u=Object.keys(Ye),c=[],s=0;s1?e-1:0),o=1;o1?r-1:0),i=1;i iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #"+e+" > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #"+e+" > iframe.zoid-visible {\n opacity: 1;\n }\n ")),d.appendChild(r),d.appendChild(t),d.appendChild(f),t.classList.add("zoid-visible"),r.classList.add("zoid-invisible"),a.on(vr.RENDERED,(function(){t.classList.remove("zoid-visible"),t.classList.add("zoid-invisible"),r.classList.remove("zoid-invisible"),r.classList.add("zoid-visible"),setTimeout((function(){Yn(t)}),1)})),a.on(vr.RESIZE,(function(n){var e=n.width,r=n.height;"number"==typeof e&&(d.style.width=re(e)),"number"==typeof r&&(d.style.height=re(r))})),d}}function Tr(n){var e=n.doc,r=n.props,t=e.createElement("html"),o=e.createElement("body"),i=e.createElement("style"),a=e.createElement("div");return a.classList.add("spinner"),r.cspNonce&&i.setAttribute("nonce",r.cspNonce),t.appendChild(o),o.appendChild(a),o.appendChild(i),i.appendChild(e.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")),t}var jr=Cn(),Rr=Cn();function kr(n){var e,r,t=function(n){var e=n.tag,r=n.url,t=n.domain,o=n.bridgeUrl,a=n.props,u=void 0===a?{}:a,c=n.dimensions,s=void 0===c?{}:c,d=n.autoResize,f=void 0===d?{}:d,l=n.allowedParentDomains,h=void 0===l?"*":l,w=n.attributes,p=void 0===w?{}:w,m=n.defaultContext,v=void 0===m?mr.IFRAME:m,y=n.containerTemplate,g=void 0===y?Ar:y,b=n.prerenderTemplate,E=void 0===b?Tr:b,_=n.validate,x=n.eligible,P=void 0===x?function(){return{eligible:!0}}:x,O=n.logger,W=void 0===O?{info:pn}:O,S=n.exports,D=void 0===S?pn:S,N=n.method,A=n.children,T=void 0===A?function(){return{}}:A,j=e.replace(/-/g,"_"),R=i({},{window:{type:wr.OBJECT,sendToChild:!1,required:!1,allowDelegate:!0,validate:function(n){var e=n.value;if(!Y(e)&&!Ue.isProxyWindow(e))throw new Error("Expected Window or ProxyWindow");if(Y(e)){if(k(e))throw new Error("Window is closed");if(!C(e))throw new Error("Window is not same domain")}},decorate:function(n){return ir(n.value)}},timeout:{type:wr.NUMBER,required:!1,sendToChild:!1},cspNonce:{type:wr.STRING,required:!1},context:{type:wr.STRING,required:!1},onDisplay:{type:wr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Cr,decorate:Wr},onRendered:{type:wr.FUNCTION,required:!1,sendToChild:!1,default:Cr,decorate:Wr},onRender:{type:wr.FUNCTION,required:!1,sendToChild:!1,default:Cr,decorate:Wr},onClose:{type:wr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Cr,decorate:Wr},onDestroy:{type:wr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Cr,decorate:Wr},onResize:{type:wr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Cr},onFocus:{type:wr.FUNCTION,required:!1,sendToChild:!1,allowDelegate:!0,default:Cr},close:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.close}},focus:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.focus}},resize:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.resize}},uid:{type:wr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.uid}},tag:{type:wr.STRING,required:!1,sendToChild:!1,childDecorate:function(n){return n.tag}},getParent:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParent}},getParentDomain:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getParentDomain}},show:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.show}},hide:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.hide}},export:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.export}},onError:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onError}},onProps:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.onProps}},getSiblings:{type:wr.FUNCTION,required:!1,sendToChild:!1,childDecorate:function(n){return n.getSiblings}}},u);if(!g)throw new Error("Container template required");return{name:j,tag:e,url:r,domain:t,bridgeUrl:o,method:N,propsDef:R,dimensions:s,autoResize:f,allowedParentDomains:h,attributes:p,defaultContext:v,containerTemplate:g,prerenderTemplate:E,validate:_,logger:W,eligible:P,children:T,exports:"function"==typeof D?D:function(n){for(var e=n.getExports,r={},t=function(n,t){var o=t[n],i=D[o].type,a=e().then((function(n){return n[o]}));r[o]=i===wr.FUNCTION?function(){for(var n=arguments.length,e=new Array(n),r=0;r) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer,\n undefined? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull,\n [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull,\n deserializeUndefined\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer,\n undefined? : PrimitiveDeserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull,\n [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady : ZalgoPromise = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, getFrameByName, isWindowClosed, getDomainFromUrl, normalizeMockUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { BRIDGE_TIMEOUT, MESSAGE_NAME } from '../conf';\nimport { awaitWindowHello } from '../lib';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { getBridgeName, documentBodyReady, registerRemoteSendMessage, registerRemoteWindow } from './common';\n\ntype WinDetails = {|\n win : CrossDomainWindowType,\n domain? : ?string,\n name? : ?string\n|};\n\nexport function listenForOpenTunnel({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n const popupWindowsByName = globalStore('popupWindowsByName');\n\n on(MESSAGE_NAME.OPEN_TUNNEL, ({ source, origin, data }) => {\n const bridgePromise = globalStore('bridges').get(origin);\n\n if (!bridgePromise) {\n throw new Error(`Can not find bridge promise for domain ${ origin }`);\n }\n\n return bridgePromise.then(bridge => {\n if (source !== bridge) {\n throw new Error(`Message source does not matched registered bridge for domain ${ origin }`);\n }\n\n if (!data.name) {\n throw new Error(`Register window expected to be passed window name`);\n }\n\n if (!data.sendMessage) {\n throw new Error(`Register window expected to be passed sendMessage method`);\n }\n\n if (!popupWindowsByName.has(data.name)) {\n throw new Error(`Window with name ${ data.name } does not exist, or was not opened by this window`);\n }\n\n const getWindowDetails = () : WinDetails => {\n const winDetails = popupWindowsByName.get(data.name);\n // $FlowFixMe\n return winDetails;\n };\n\n if (!getWindowDetails().domain) {\n throw new Error(`We do not have a registered domain for window ${ data.name }`);\n }\n\n if (getWindowDetails().domain !== origin) {\n throw new Error(`Message origin ${ origin } does not matched registered window origin ${ getWindowDetails().domain || 'unknown' }`);\n }\n\n registerRemoteSendMessage(getWindowDetails().win, origin, data.sendMessage);\n\n return {\n sendMessage(message) {\n\n if (!window || window.closed) {\n return;\n }\n\n if (!getWindowDetails()) {\n return;\n }\n\n const domain = getWindowDetails().domain;\n\n if (!domain) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n origin: domain,\n source: getWindowDetails().win\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n };\n });\n });\n}\n\nfunction openBridgeFrame(name : string, url : string) : HTMLIFrameElement {\n\n const iframe = document.createElement(`iframe`);\n\n iframe.setAttribute(`name`, name);\n iframe.setAttribute(`id`, name);\n\n iframe.setAttribute(`style`, `display: none; margin: 0; padding: 0; border: 0px none; overflow: hidden;`);\n iframe.setAttribute(`frameborder`, `0`);\n iframe.setAttribute(`border`, `0`);\n iframe.setAttribute(`scrolling`, `no`);\n iframe.setAttribute(`allowTransparency`, `true`);\n\n iframe.setAttribute(`tabindex`, `-1`);\n iframe.setAttribute(`hidden`, `true`);\n iframe.setAttribute(`title`, ``);\n iframe.setAttribute(`role`, `presentation`);\n\n iframe.src = url;\n\n return iframe;\n}\n\nexport function hasBridge(url : string, domain : string) : boolean {\n const bridges = globalStore('bridges');\n return bridges.has(domain || getDomainFromUrl(url));\n}\n\nexport function openBridge(url : string, domain : string) : ZalgoPromise {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n \n domain = domain || getDomainFromUrl(url);\n \n return bridges.getOrSet(domain, () => ZalgoPromise.try(() => {\n\n if (getDomain() === domain) {\n throw new Error(`Can not open bridge on the same domain as current domain: ${ domain }`);\n }\n\n const name = getBridgeName(domain);\n const frame = getFrameByName(window, name);\n\n if (frame) {\n throw new Error(`Frame with name ${ name } already exists on page`);\n }\n\n const iframe = openBridgeFrame(name, url);\n bridgeFrames.set(domain, iframe);\n\n return documentBodyReady.then(body => {\n\n body.appendChild(iframe);\n const bridge = iframe.contentWindow;\n\n return new ZalgoPromise((resolve, reject) => {\n\n iframe.addEventListener('load', resolve);\n iframe.addEventListener('error', reject);\n\n }).then(() => {\n\n return awaitWindowHello(bridge, BRIDGE_TIMEOUT, `Bridge ${ url }`);\n\n }).then(() => {\n\n return bridge;\n });\n });\n }));\n}\n\nexport function linkWindow({ win, name, domain } : WinDetails) : WinDetails {\n const popupWindowsByName = globalStore('popupWindowsByName');\n const popupWindowsByWin = windowStore('popupWindowsByWin');\n\n for (const winName of popupWindowsByName.keys()) {\n const details = popupWindowsByName.get(winName);\n if (!details || isWindowClosed(details.win)) {\n popupWindowsByName.del(winName);\n }\n }\n\n if (isWindowClosed(win)) {\n return { win, name, domain };\n }\n\n const details = popupWindowsByWin.getOrSet(win, () : WinDetails => {\n if (!name) {\n return { win };\n }\n \n // $FlowFixMe\n return popupWindowsByName.getOrSet(name, () : WinDetails => {\n return { win, name };\n });\n });\n\n if (details.win && details.win !== win) {\n throw new Error(`Different window already linked for window: ${ name || 'undefined' }`);\n }\n\n if (name) {\n details.name = name;\n popupWindowsByName.set(name, details);\n }\n\n if (domain) {\n details.domain = domain;\n registerRemoteWindow(win);\n }\n\n popupWindowsByWin.set(win, details);\n \n return details;\n}\n\nexport function linkUrl(win : CrossDomainWindowType, url : string) {\n linkWindow({ win, domain: getDomainFromUrl(url) });\n}\n\nexport function listenForWindowOpen() {\n const windowOpen = window.open;\n\n window.open = function windowOpenWrapper(url : string, name : string, options : string, last : mixed) : mixed {\n const win = windowOpen.call(this, normalizeMockUrl(url), name, options, last);\n \n if (!win) {\n return win;\n }\n \n linkWindow({ win, name, domain: url ? getDomainFromUrl(url) : null });\n \n return win;\n };\n}\n\nexport function destroyBridges() {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n\n for (const domain of bridgeFrames.keys()) {\n const frame = bridgeFrames.get(domain);\n if (frame && frame.parentNode) {\n frame.parentNode.removeChild(frame);\n }\n }\n bridgeFrames.reset();\n bridges.reset();\n}\n","/* @flow */\n\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { listenForWindowOpen, listenForOpenTunnel } from './parent';\nimport { setupOpenTunnelToParent } from './bridge';\nimport { openTunnelToOpener } from './child';\n\nexport function setupBridge({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n listenForWindowOpen();\n listenForOpenTunnel({ on, send, receiveMessage });\n setupOpenTunnelToParent({ send });\n openTunnelToOpener({ on, send, receiveMessage });\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { getParent, isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { getGlobal, globalStore } from '../global';\nimport type { SendType, ResponseMessageEvent } from '../types';\n\nfunction cleanTunnelWindows() {\n const tunnelWindows = globalStore('tunnelWindows');\n\n for (const key of tunnelWindows.keys()) {\n const tunnelWindow = tunnelWindows[key];\n\n try {\n noop(tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(key);\n continue;\n }\n\n if (isWindowClosed(tunnelWindow.source)) {\n tunnelWindows.del(key);\n }\n }\n}\n\ntype TunnelWindowDataType = {|\n name : string,\n source : CrossDomainWindowType,\n canary : () => void,\n sendMessage : (message : string) => void\n|};\n\nfunction addTunnelWindow({ name, source, canary, sendMessage } : TunnelWindowDataType) : string {\n cleanTunnelWindows();\n const id = uniqueID();\n const tunnelWindows = globalStore('tunnelWindows');\n tunnelWindows.set(id, { name, source, canary, sendMessage });\n return id;\n}\n\nexport function setupOpenTunnelToParent({ send } : {| send : SendType |}) {\n getGlobal(window).openTunnelToParent = function openTunnelToParent({ name, source, canary, sendMessage } : TunnelWindowDataType) : ZalgoPromise {\n\n const tunnelWindows = globalStore('tunnelWindows');\n const parentWindow = getParent(window);\n \n if (!parentWindow) {\n throw new Error(`No parent window found to open tunnel to`);\n }\n \n const id = addTunnelWindow({ name, source, canary, sendMessage });\n \n return send(parentWindow, MESSAGE_NAME.OPEN_TUNNEL, {\n \n name,\n \n sendMessage() {\n \n const tunnelWindow = tunnelWindows.get(id);\n \n try {\n // IE gets antsy if you try to even reference a closed window\n noop(tunnelWindow && tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(id);\n return;\n }\n \n if (!tunnelWindow || !tunnelWindow.source || isWindowClosed(tunnelWindow.source)) {\n return;\n }\n \n try {\n tunnelWindow.canary();\n } catch (err) {\n return;\n }\n \n // $FlowFixMe[object-this-reference]\n tunnelWindow.sendMessage.apply(this, arguments);\n }\n \n }, { domain: WILDCARD });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isSameDomain, getOpener, getDomain, getFrameByName, assertSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { getGlobal, windowStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { needsBridge, registerRemoteWindow, rejectRemoteSendMessage, registerRemoteSendMessage, getBridgeName } from './common';\n\nfunction awaitRemoteBridgeForWindow (win : CrossDomainWindowType) : ZalgoPromise {\n return windowStore('remoteBridgeAwaiters').getOrSet(win, () => {\n return ZalgoPromise.try(() => {\n const frame = getFrameByName(win, getBridgeName(getDomain()));\n\n if (!frame) {\n return;\n }\n\n if (isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n return frame;\n }\n\n return new ZalgoPromise(resolve => {\n\n let interval;\n let timeout; // eslint-disable-line prefer-const\n\n interval = setInterval(() => { // eslint-disable-line prefer-const\n if (frame && isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n clearInterval(interval);\n clearTimeout(timeout);\n return resolve(frame);\n }\n }, 100);\n\n timeout = setTimeout(() => {\n clearInterval(interval);\n return resolve();\n }, 2000);\n });\n });\n });\n}\n\nexport function openTunnelToOpener({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const opener = getOpener(window);\n \n if (!opener || !needsBridge({ win: opener })) {\n return;\n }\n\n registerRemoteWindow(opener);\n\n return awaitRemoteBridgeForWindow(opener).then(bridge => {\n\n if (!bridge) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: no bridge found in opener`));\n }\n\n if (!window.name) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: window does not have a name`));\n }\n\n return getGlobal(assertSameDomain(bridge)).openTunnelToParent({\n\n name: window.name,\n\n source: window,\n\n canary() {\n // pass\n },\n\n sendMessage(message) {\n\n try {\n noop(window);\n } catch (err) {\n return;\n }\n\n if (!window || window.closed) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n // $FlowFixMe[object-this-reference]\n origin: this.origin,\n // $FlowFixMe[object-this-reference]\n source: this.source\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n\n }).then(({ source, origin, data }) => {\n\n if (source !== opener) {\n throw new Error(`Source does not match opener`);\n }\n\n registerRemoteSendMessage(source, origin, data.sendMessage);\n\n }).catch(err => {\n\n rejectRemoteSendMessage(opener, err);\n throw err;\n });\n });\n });\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SetLocationOptions = {|\n method? : $Values,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n const getName = () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n });\n\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n\n } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name, 'noopener');\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n // $FlowFixMe[method-unbinding]\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\ntype SendStrategies = {|\n [$Values] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore, getGlobalKey } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n const strDomain = domain.toString();\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n}\n\nexport function handleAck(source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n}\n\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[getGlobalKey()];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n if (isWindowClosed(source)) {\n return;\n }\n\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise = ZalgoPromise & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport { ProxyWindow } from '../serialize/window';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (winOrProxyWin, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n });\n};\n","/* @flow */\n\nimport { setup } from './setup';\nimport { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge, needsBridgeForBrowser, hasBridge,\n needsBridgeForWin, needsBridgeForDomain, destroyBridges } from './bridge';\n\nexport { ZalgoPromise as Promise } from 'zalgo-promise/src';\n\nexport * from './types';\nexport { ProxyWindow } from './serialize';\nexport { setup, destroy, serializeMessage, deserializeMessage, createProxyWindow, toProxyWindow } from './setup';\nexport { on, once, send } from './public';\nexport { markWindowKnown } from './lib';\nexport { cleanUpWindow } from './clean';\n\n// $FlowFixMe\nexport let bridge;\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n bridge = { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge,\n needsBridgeForBrowser, hasBridge, needsBridgeForWin, needsBridgeForDomain, destroyBridges };\n}\n\nif (__POST_ROBOT__.__AUTO_SETUP__) {\n setup();\n}\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT : number = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from '@krakenjs/cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n\nexport function basicSerialize(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType =\n UIDReferenceType |\n RawReferenceType;\n\nexport function getUIDRefStore(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef(val : T) : ReferenceType {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef(val : T) : ReferenceType {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue(win : CrossDomainWindowType, ref : ReferenceType) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef(win : CrossDomainWindowType, ref : ReferenceType) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType\n|};\n\ntype CrossDomainSerializeOptions = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType\n|};\n\nexport function crossDomainDeserialize({ data, sender, basic = false } : CrossDomainDeserializeOptions) : CrossDomainDeserializedMessage {\n const message : Message = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from '@krakenjs/cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: ('string' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from '@krakenjs/cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = windowName.split('__');\n\n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n\n if (!name) {\n throw new Error(`Expected component name`);\n }\n\n if (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload,\n reference : ReferenceType\n|};\n\nconst parseInitialParentPayload = memoize((windowName : string) : InitialParentPayload => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload() : InitialParentPayload {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType, props : PropsType

, origin : string, helpers : ChildHelpers, isUpdate : boolean = false) : ChildPropsType {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise,\n getSiblings : getSiblingsPropType\n|};\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent = {|\n getProps : () => ChildPropsType,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent(options : NormalizedComponentOptionsType) : ChildComponent {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return getAutoResize().then(({ width, height, element }) => {\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from '@krakenjs/cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type exportPropType = (X) => ZalgoPromise;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType

,\n export : exportPropType\n|};\n\nexport type PropsInputType

= {|\n parent? : ParentPropType,\n \n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : ?cspNoncePropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

,\n\n ...P\n|};\n\nexport type PropsType

= {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n dimensions : CssDimensionsType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise;\n\nexport type ChildPropsType = {|\n ...PropsType

,\n\n parent? : ParentPropType,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType

,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n // eslint-disable-next-line no-undef\n queryValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P, X> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType = {|\n [string] : MixedPropDefinitionType\n|};\n\nexport type BuiltInPropsDefinitionType = {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n uid : StringPropDefinitionType,\n tag : StringPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n export : FunctionPropDefinitionType, P, X>,\n getSiblings : FunctionPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P, X>\n|};\n\nexport type PropsDefinitionType = {|\n ...BuiltInPropsDefinitionType,\n [ string ] : MixedPropDefinitionType\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = ({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps() : BuiltInPropsDefinitionType {\n return {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback =\n ((string, BooleanPropDefinitionType | void, boolean) => R) &\n ((string, StringPropDefinitionType | void, string) => R) &\n ((string, NumberPropDefinitionType | void, number) => R) &\n ((string, FunctionPropDefinitionType | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType | void, Object) => R);\n\nexport function eachProp(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) : $ReadOnlyArray {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps(propsDef : PropsDefinitionType, existingProps : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps(propsDef : PropsDefinitionType, props : (PropsType

), method : $Values) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType = {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n childDomainMatch : DomainMatcher,\n props : PropsType

,\n exports : ParentExportsType\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise;\n\ntype RenderContainerOptions = {|\n context : $Values,\n proxyFrame : ?ProxyObject,\n proxyPrerenderFrame : ?ProxyObject,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise;\ntype RejectInitPromise = (mixed) => ZalgoPromise;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, RenderContainerOptions) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values|}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState,\n resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values,\n rerender : Rerender\n|};\n\ntype ParentComponent = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise,\n getProps : () => PropsType

,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise,\n getExports : () => X\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions = {|\n uid : string,\n options : NormalizedComponentOptionsType,\n overrides? : ParentDelegateOverrides

,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions) : ParentComponent {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType

= overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return rejectInitPromise(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__${ ZOID }_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getCurrentWindowReferenceUID = () : string => {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childDomain : string, childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin.setName(windowName).then(() => {\n return proxyWin;\n });\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow, context : $Values) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n const exportsPromise : ZalgoPromise = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType

) : ZalgoPromise {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values|} = {}) : ZalgoPromise> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|} = {}) : ZalgoPromise => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|}) : ZalgoPromise => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values|}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, initialChildDomain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType

= getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = ({ target, container, context, rerender } : RenderOptions) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, initialChildDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\n };\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType

) : ?HTMLElement {\n const { width, height } = dimensions;\n\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { type RenderOptionsType } from '../../parent/parent';\n\nexport function defaultPrerenderTemplate

({ doc, props } : RenderOptionsType

) : ?HTMLElement {\n if (__ZOID__.__DEFAULT_PRERENDER__) {\n const html = doc.createElement('html');\n const body = doc.createElement('body');\n const style = doc.createElement('style');\n const spinner = doc.createElement('div');\n spinner.classList.add('spinner');\n\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n html.appendChild(body);\n body.appendChild(spinner);\n body.appendChild(style);\n style.appendChild(doc.createTextNode(`\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n `));\n\n return html;\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from '@krakenjs/cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition = ({|\n getExports : () => ZalgoPromise\n|}) => X;\n\nexport type ExportsDefinition = ExportsConfigDefinition | ExportsMapperDefinition;\n\nexport type ComponentOptionsType = {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values,\n\n props? : UserPropsDefinitionType,\n\n dimensions? : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType

|}) => Attributes,\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values,\n\n propsDef : PropsDefinitionType,\n dimensions : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition\n|};\n\nexport type ZoidComponentInstance = {|\n ...ParentHelpers

,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance,\n render : (container? : ContainerReferenceType, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent = {\n (props? : PropsInputType

| void) : ZoidComponentInstance,\n // eslint-disable-next-line no-undef\n driver : (string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n instances : $ReadOnlyArray>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = () : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions(options : ComponentOptionsType) : NormalizedComponentOptionsType {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop },\n exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component = {|\n init : (props? : PropsInputType

| void) => ZoidComponentInstance,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent\n|};\n\nexport function component(opts : ComponentOptionsType) : Component {\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible,\n children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent => {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : ContainerReferenceType) : ContainerReferenceType => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType

| void) : ZoidComponentInstance => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType

= parent.getProps();\n const parentExport : exportPropType = parent.export;\n\n const childParent : ParentPropType = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, vue3, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L) => D\n|};\n\nexport type ZoidProps

= PropsType

;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = (options : ComponentOptionsType) => ZoidComponent;\n\nexport const create : CreateZoidComponent = (options : ComponentOptionsType) : ZoidComponent => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType

| void) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n};\n\nexport function destroyComponents(err? : mixed) : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://zoid/webpack/universalModuleDefinition","webpack://zoid/webpack/bootstrap","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://zoid/./node_modules/zalgo-promise/src/utils.js","webpack://zoid/./node_modules/zalgo-promise/src/exceptions.js","webpack://zoid/./node_modules/zalgo-promise/src/flush.js","webpack://zoid/./node_modules/zalgo-promise/src/promise.js","webpack://zoid/./node_modules/cross-domain-utils/src/util.js","webpack://zoid/./node_modules/cross-domain-utils/src/constants.js","webpack://zoid/./node_modules/cross-domain-utils/src/utils.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/weakmap.js","webpack://zoid/./node_modules/belter/src/util.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/native.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://zoid/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://zoid/./node_modules/belter/src/dom.js","webpack://zoid/./node_modules/belter/src/css.js","webpack://zoid/./node_modules/post-robot/src/global.js","webpack://zoid/./node_modules/belter/src/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/hello.js","webpack://zoid/./node_modules/post-robot/src/conf/constants.js","webpack://zoid/./node_modules/post-robot/src/lib/windows.js","webpack://zoid/./node_modules/universal-serialize/src/common.js","webpack://zoid/./node_modules/universal-serialize/src/constants.js","webpack://zoid/./node_modules/universal-serialize/src/serialize.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/function.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/error.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/promise.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/regex.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/date.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/array.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/object.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/string.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/number.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/boolean.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/null.js","webpack://zoid/./node_modules/universal-serialize/src/serializers/undefined.js","webpack://zoid/./node_modules/universal-serialize/src/deserialize.js","webpack://zoid/./node_modules/post-robot/src/bridge/common.js","webpack://zoid/./node_modules/post-robot/src/bridge/parent.js","webpack://zoid/./node_modules/post-robot/src/bridge/setup.js","webpack://zoid/./node_modules/post-robot/src/bridge/bridge.js","webpack://zoid/./node_modules/post-robot/src/bridge/child.js","webpack://zoid/./node_modules/post-robot/src/serialize/window.js","webpack://zoid/./node_modules/post-robot/src/serialize/function.js","webpack://zoid/./node_modules/post-robot/src/serialize/serialize.js","webpack://zoid/./node_modules/post-robot/src/serialize/promise.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/strategies.js","webpack://zoid/./node_modules/post-robot/src/drivers/send/index.js","webpack://zoid/./node_modules/post-robot/src/drivers/listeners.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/types.js","webpack://zoid/./node_modules/post-robot/src/drivers/receive/index.js","webpack://zoid/./node_modules/post-robot/src/public/on.js","webpack://zoid/./node_modules/post-robot/src/lib/compat.js","webpack://zoid/./node_modules/post-robot/src/public/send.js","webpack://zoid/./node_modules/post-robot/src/index.js","webpack://zoid/./node_modules/post-robot/src/conf/config.js","webpack://zoid/./node_modules/post-robot/src/setup.js","webpack://zoid/./node_modules/post-robot/src/clean.js","webpack://zoid/./src/lib/global.js","webpack://zoid/./src/lib/serialize.js","webpack://zoid/./src/constants.js","webpack://zoid/./src/lib/window.js","webpack://zoid/./src/child/props.js","webpack://zoid/./src/child/child.js","webpack://zoid/./src/component/props.js","webpack://zoid/./src/parent/props.js","webpack://zoid/./src/parent/parent.js","webpack://zoid/./src/component/templates/container.js","webpack://zoid/./src/component/templates/component.js","webpack://zoid/./src/component/component.js"],"names":["root","factory","exports","module","define","amd","self","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","hasOwnProperty","p","s","_setPrototypeOf","setPrototypeOf","__proto__","_inheritsLoose","subClass","superClass","prototype","constructor","_extends","assign","target","arguments","length","source","apply","isPromise","item","Promise","window","Window","toString","then","err","flushPromise","dispatchedErrors","possiblyUnhandledPromiseHandlers","activeCount","flushActive","promise","resolve","startActive","endActive","ZalgoPromise","handler","resolved","rejected","errorHandled","error","handlers","dispatching","stack","result","isAsync","res","reject","Error","dispatch","setTimeout","indexOf","push","j","dispatchPossiblyUnhandledError","asyncReject","chain","firstPromise","secondPromise","onSuccess","onError","promiseResult","catch","undefined","finally","onFinally","try","timeout","time","clearTimeout","toPromise","TypeError","lazy","all","promises","count","results","slice","prom","hash","awaitPromises","map","items","method","onPossiblyUnhandledException","cancel","splice","context","args","delay","flush","isRegex","WINDOW_TYPE","IFRAME","POPUP","IE_WIN_ACCESS_ERROR","getActualProtocol","win","location","protocol","getProtocol","mockDomain","split","isAboutProtocol","getParent","parent","getOpener","opener","canReadFromWindow","getActualDomain","PROTOCOL","host","getDomain","domain","isSameDomain","desc","getOwnPropertyDescriptor","isMockProtocol","isActuallySameDomain","assertSameDomain","isAncestorParent","child","childParent","getParents","getFrames","frames","len","frame","getAllChildFrames","getTop","top","getAllFramesInWindow","iframeWindows","iframeFrames","isWindowClosed","allowMock","closed","message","mockclosed","iframeIndex","collection","safeIndexOf","contentWindow","parentNode","doc","ownerDocument","documentElement","contains","isFrameWindowClosed","getUserAgent","navigator","mockUserAgent","userAgent","getFrameByName","winFrames","childFrame","isOpener","getAncestor","anyMatch","collection1","collection2","item1","getDistanceFromTop","distance","isSameTopWindow","win1","win2","top1","top2","allFrames1","allFrames2","opener1","opener2","matchDomain","pattern","origin","Array","isArray","Boolean","match","JSON","stringify","some","subpattern","getDomainFromUrl","url","join","onCloseWindow","callback","maxtime","Infinity","check","isWindow","obj","__cross_domain_utils_window_check__","normalizeMockUrl","getFrameForWindow","frameElement","document","querySelectorAll","closeWindow","isIframe","parentElement","removeChild","close","objectIDs","CrossDomainSafeWeakMap","weakmap","keys","values","Math","random","WeakMap","freeze","testWeakMap","testKey","set","hasNativeWeakMap","_cleanupClosedWindows","delete","isSafeToReadWrite","entry","writable","index","has","getOrSet","_getPrototypeOf","getPrototypeOf","_isNativeReflectConstruct","Reflect","construct","sham","Proxy","Date","e","_construct","Parent","Class","isNativeReflectConstruct","a","instance","Function","_wrapNativeSuper","_cache","Map","Wrapper","configurable","isElement","element","passed","Element","nodeType","style","_","getFunctionName","fn","__name__","displayName","setFunctionName","base64encode","str","btoa","encodeURIComponent","replace","p1","String","fromCharCode","parseInt","Buffer","from","uniqueID","chars","charAt","floor","toISOString","toLowerCase","serializeArgs","subkey","val","uid","getObjectID","getEmptyObject","memoizeGlobalIndex","memoizeGlobalIndexValidFrom","memoize","options","simpleCache","thisCache","thisNamespace","cacheTime","memoizeIndex","memoizedFunction","cache","cacheKey","cacheResult","now","reset","memoizePromise","memoizedPromiseFunction","noop","once","called","stringifyError","level","newErr","extend","identity","safeInterval","loop","arrayFrom","isDefined","cleanup","cleanErr","tasks","cleaned","cleaner","register","task","shift","assertExists","thing","clear","ExtendableError","captureStackTrace","ReferenceError","getBody","body","isDocumentReady","readyState","isDocumentInteractive","urlEncode","parseQuery","queryString","logic","__inline_memoize_cache__","params","pair","decodeURIComponent","inlineMemoize","extendQuery","originalQuery","props","filter","appendChild","container","getElementSafe","id","querySelector","elementReady","el","interval","setInterval","clearInterval","awaitFrameLoadPromises","PopupOpenError","awaitFrameLoad","addEventListener","cleanIframes","linkFrameWindow","awaitFrameWindow","loadedFrame","iframe","tag","styleText","createElement","class","className","setAttribute","attributes","styleSheet","cssText","createTextNode","html","innerHTML","allowTransparency","backgroundColor","border","isIE","hasAttribute","getElement","event","removeEventListener","showElement","setProperty","hideElement","destroyElement","isElementClosed","onResize","width","height","currentWidth","offsetWidth","currentHeight","offsetHeight","canceled","observer","getClientRects","isElementVisible","newWidth","newHeight","ResizeObserver","observe","MutationObserver","childList","subtree","characterData","disconnect","isShadowElement","currentScript","getCurrentScript","getStackTrace","stackDetails","exec","scriptLocation","getElementsByTagName","reverse","script","src","inferCurrentScript","currentUID","isPerc","test","toNum","toPx","toCSS","normalizeDimension","dim","max","getGlobal","globalKey","__POST_ROBOT__","getAttribute","ATTRIBUTES","hashedString","total","charCodeAt","abs","strHashStr","dataset","getObj","globalStore","defStore","store","storeKey","defVal","del","WildCard","getWildcard","global","WINDOW_WILDCARD","windowStore","winStore","getStore","getInstanceID","resolveHelloPromise","helloPromises","existingPromise","newPromise","sayHello","send","instanceID","data","getWindowInstanceID","awaitWindowHello","getHelloPromise","markWindowKnown","isSerializedType","__type__","determineType","serializeType","type","__val__","SERIALIZER","code","toJSON","defaultSerializers","DESERIALIZER","RegExp","defaultDeserializers","needsBridgeForBrowser","needsBridgeForWin","needsBridgeForDomain","needsBridge","getBridgeName","BRIDGE_NAME_PREFIX","isBridge","documentBodyReady","registerRemoteWindow","findRemoteWindow","remoteWinPromise","registerRemoteSendMessage","sendMessage","remoteWin","remoteDomain","fireAndForget","rejectRemoteSendMessage","linkWindow","popupWindowsByName","popupWindowsByWin","winName","details","setupBridge","windowOpen","on","receiveMessage","open","last","bridgePromise","bridge","getWindowDetails","listenForOpenTunnel","openTunnelToParent","canary","tunnelWindows","parentWindow","cleanTunnelWindows","addTunnelWindow","tunnelWindow","setupOpenTunnelToParent","openTunnelToOpener","cleanupProxyWindows","idToProxyWindow","shouldClean","getSerializedWindow","winPromise","windowNamePromise","windowTypePromise","getName","getType","focus","isClosed","setLocation","href","opts","form","display","input","submit","submitForm","setName","sameDomain","ProxyWindow","serializedWindow","isProxyWindow","actualWindow","actualWindowPromise","getID","setWindow","isPopup","isPopupPromise","getNamePromise","reopenPromise","focusPromise","getWindow","awaitWindow","matchWindow","proxyInstanceID","knownWindowInstanceID","unwrap","serialize","toProxyWindow","deserialize","addMethod","methodStore","proxyWindowMethods","lookupMethod","serializeFunction","destination","meth","methodSource","arg","__id__","serializeMessage","serializers","serializer","serializePromise","deserializeMessage","deserializers","parse","deserializer","serializedPromise","deserializePromise","serializedFunction","getDeserializedFunction","crossDomainFunctionWrapper","__origin__","__source__","deserializeFunction","SEND_MESSAGE_STRATEGIES","domainBuffer","buffer","serializedMessage","strategies","errors","strategyName","getResponseListener","deleteResponseListener","isResponseListenerErrored","getRequestListener","requestListeners","winQualifier","nameListeners","domainListeners","listener","regex","handleRequest","logName","sendResponse","ack","pathname","handleError","handleAck","handleResponse","receivedMessages","messages","parsedMessage","parseMessages","deserializeMessages","requestListener","addRequestListener","winCandidate","requestListenerPromise","actualWin","listenersCollection","existingListener","strDomain","winNameDomainRegexListeners","winNameDomainRegexListener","winNameListeners","winNameDomainListeners","errorHandler","postMessage","messagingChild","messagingParent","sendBridgeMessage","foreignGlobal","winOrProxyWin","domainMatcher","responseTimeout","childTimeout","validateOptions","actualParent","isAncestor","targetDomain","actualDomain","normalizedDomain","normalizeDomain","responseListener","addResponseListener","reqPromises","markResponseListenerErrored","totalAckTimeout","isWindowKnown","totalResTimeout","ackTimeout","resTimeout","cancelled","cleanUpWindow","tryGlobal","getProxyObject","basicSerialize","getUIDRefStore","references","crossDomainSerialize","metaData","sender","receiver","passByReference","basic","proxyWin","internalSerializeMessage","reference","getRawRef","serializedData","cleanReference","ref","crossDomainDeserialize","atob","base64decode","basicDeserialize","getRefValue","internalDeserializeMessage","openBridge","bridges","bridgeFrames","openBridgeFrame","linkUrl","hasBridge","destroyBridges","PROP_TYPE","STRING","OBJECT","FUNCTION","BOOLEAN","NUMBER","ARRAY","PROP_SERIALIZATION","DOTIFY","BASE64","CONTEXT","EVENT","RENDER","RENDERED","DISPLAY","ERROR","CLOSE","DESTROY","PROPS","RESIZE","FOCUS","buildChildWindowName","serializedPayload","parseWindowName","windowName","zoidcomp","serializedInitialPayload","parseInitialParentPayload","windowRef","getNthParent","ancestor","windows","findChildFrameByName","namedFrame","findFrameByName","getWindowByRef","payload","getInitialParentPayload","getWindowRef","targetWindow","currentWindow","normalizeChildProp","propsDef","helpers","prop","childDecorate","onProps","resize","getParentDomain","show","hide","export","getSiblings","destroy","defaultNoop","decorateOnce","eachProp","serializeProps","propDef","getParam","queryParam","bodyParam","getValue","queryValue","bodyValue","finalParam","finalValue","serialization","dotify","prefix","newobj","every","dotkey","mapProps","parentComponent","triggered","emitter","currentProxyWin","currentProxyContainer","childComponent","currentChildDomain","currentContainer","overrides","parentWin","containerTemplate","prerenderTemplate","dimensions","autoResize","domainMatch","xports","initPromise","handledErrors","clean","state","inputProps","internalState","visible","eventName","handlerList","trigger","triggerOnce","onErrorOverride","getProxyContainerOverride","getProxyContainer","showOverride","hideOverride","closeOverride","renderContainerOverride","renderContainer","getProxyWindowOverride","getProxyWindow","setProxyWinOverride","setProxyWin","openFrameOverride","openFrame","openPrerenderFrameOverride","openPrerenderFrame","prerenderOverride","prerender","openOverride","openPrerenderOverride","openPrerender","watchForUnloadOverride","watchForUnload","getInternalStateOverride","getInternalState","setInternalStateOverride","setInternalState","getDimensions","resolveInitPromise","rejectInitPromise","getPropsForChild","initialChildDomain","sendToChild","newInternalState","windowProp","setState","getUrl","getAttributes","getInitialChildDomain","title","proxyPrerenderFrame","prerenderFrame","prerenderFrameWindow","actualComponentWindow","initChild","childDomain","childExports","proxyFrame","outerWidth","closeOnUnload","left","round","screenX","screen","outerHeight","screenY","status","toolbar","menubar","resizable","scrollbars","popup","unloadWindowListener","closeParentWindowListener","checkWindowClose","secondIsClosed","exportsPromise","xport","actualExports","renderTemplate","renderer","proxyPrerenderWin","prerenderWindow","isBlankDomain","tagName","children","writeElementToWindow","prerenderResizeListener","proxyContainer","rerender","innerContainer","containerWatcher","sacrificialFrame","sacrificialFrameWin","mutationObservers","elementClosed","mutationElement","mutationObserver","frameWin","watchElementForClose","removeError","getHelpers","updateProps","setProps","newInputProps","existingProps","valueDetermined","alias","default","required","decorate","getDerivedValue","extendProps","newProps","childProps","containerElement","insertShadowSlot","shadowHost","shadowRoot","getShadowRoot","getShadowHost","slotName","slot","slotProvider","init","onRender","onDisplay","onRendered","onClose","onDestroy","onFocus","render","childDomainMatch","checkAllowRender","delegatePromise","delegateProps","propName","allowDelegate","childOverridesPromise","POST_MESSAGE","parentComp","getDelegateOverrides","childOverrides","delegate","watchForUnloadPromise","buildBodyPromise","onRenderPromise","getProxyContainerPromise","getProxyWindowPromise","finalSetPropsPromise","buildUrlPromise","query","originalUrl","originalHash","hashString","extendUrl","buildWindowNamePromise","version","__ZOID__","checkClose","buildInitialChildPayload","childPayload","buildSerializedChildPayload","openFramePromise","openPrerenderFramePromise","renderContainerPromise","openPromise","openPrerenderPromise","setStatePromise","prerenderPromise","setWindowNamePromise","getMethodPromise","loadUrlPromise","windowUrl","watchForClosePromise","watchForClose","onDisplayPromise","openBridgePromise","bridgeUrl","bridgeDomain","runTimeoutPromise","onRenderedPromise","getProps","getExports","defaultContainerTemplate","div","cspNonce","classList","add","remove","defaultPrerenderTemplate","spinner","cleanInstances","cleanZoid","component","allowDelegateListener","delegateListener","allowedParentDomains","defaultContext","validate","eligible","logger","info","xportsDefinition","valuePromise","normalizeOptions","instances","isChild","isChildComponentWindow","registerChild","xprops","components","onPropHandlers","parentComponentWindow","parentDomain","parentExports","initialProps","parentExport","parentResize","parentInit","anyParent","currentParent","winParent","isUpdate","normalizedProps","normalizeChildProps","componentName","updateChildWindowNameWithRef","checkParentDomain","ZOID","eligibility","reason","clone","getDefaultContext","finalContext","getDefaultContainer","newInstance","renderTo","childComponents","childName","Child","childInputProps","parentProps","getChildren","isEligible","driver","driverName","dep","canRenderTo","initialized","sourceElement","originalEvent","messageListener","listenForMessages","initHello","comp","destroyComponents","destroyPromise","destroyAll","responseListeners","cancelResponseListeners"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,OAAQ,GAAIH,GACO,iBAAZC,QACdA,QAAc,KAAID,IAElBD,EAAW,KAAIC,IARjB,CASoB,oBAATK,KAAuBA,KAAOC,MAAO,WAChD,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUR,QAGnC,IAAIC,EAASK,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHV,QAAS,IAUV,OANAW,EAAQH,GAAUI,KAAKX,EAAOD,QAASC,EAAQA,EAAOD,QAASO,GAG/DN,EAAOS,GAAI,EAGJT,EAAOD,QA0Df,OArDAO,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASf,EAASgB,EAAMC,GAC3CV,EAAoBW,EAAElB,EAASgB,IAClCG,OAAOC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,OAD0C,EAAb8D,SAEpD,CAAE6R,WAAYP,SAsBf5V,EAASoD,IAUf,OATIpD,GACAiW,GAASjW,EAAQ,CAAEkW,SAAQ7Y,OAAM,SAAArC,OAQ9BkkB,KsC3BP+a,CAAU,CAAEnhB,MAAI5C,WaugBpB,IAAMgkB,EAAO7D,GAAUjrB,GAEjB2mB,EAAO,SAACnjB,GAAD,OAAuCsrB,EAAKnI,KAAKnjB,IAC9DmjB,EAAKyH,OAAS,SAACthC,EAAMwhC,GAAP,OAAeQ,EAAKV,OAAOthC,EAAMwhC,IAC/C3H,EAAKmF,QAAU,kBAAMgD,EAAKhD,WAC1BnF,EAAK4H,YAAc,SAACn6B,GAAD,OAAS06B,EAAKP,YAAYn6B,IAC7CuyB,EAAKkF,UAAYiD,EAAKjD,UAEtB,IAAMj2B,EAAQk5B,EAAK9C,gBAKnB,OAJIp2B,IACApG,OAAOy8B,OAAStF,EAAKsF,OAASr2B,EAAMy0B,YAGjC1D,GAGJ,SAASoI,GAAkBn/B,GAC1Bme,IACAA,GAAOoL,iBAGX,IAAM6V,EAAiBjE,GAAen4B,IAAIhD,GAE1C,OADAm7B,GAAiBrpB,KACVstB,EAGJ,IAAMC,GAAaF,GAEnB,SAAStS,GAAQ7sB,GAIpB,OAHAq/B,YXriBOz/B,OAAM,gBVWV,WAAmC,IACtC,IAAM0/B,EAAoBvlB,GAAY,qBADA,MAEnBulB,EAAkB/zB,OAFC,eAEO,CAAxC,IAAMjI,EAAI,KACL4gB,EAAWob,EAAkB9hC,IAAI8F,GACnC4gB,IACAA,EAASqD,WAAY,GAEzB+X,EAAkBllB,IAAI9W,IQZ1Bi8B,INoHMrb,EAAWnK,KAAcvc,IAAI,yBAE/B0mB,EAAStgB,gBlCvINhE,OAAM,uBqDmjBNw7B,GAAUp4B,IAAIhD,GbniBlB,INqHGkkB","file":"zoid.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"zoid\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"zoid\"] = factory();\n\telse\n\t\troot[\"zoid\"] = factory();\n})((typeof self !== 'undefined' ? self : this), function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","/* @flow */\n\nexport function isPromise(item : mixed) : boolean {\n try {\n if (!item) {\n return false;\n }\n\n if (typeof Promise !== 'undefined' && item instanceof Promise) {\n return true;\n }\n\n if (typeof window !== 'undefined' && typeof window.Window === 'function' && item instanceof window.Window) {\n return false;\n }\n\n if (typeof window !== 'undefined' && typeof window.constructor === 'function' && item instanceof window.constructor) {\n return false;\n }\n\n const toString = ({}).toString;\n\n if (toString) {\n const name = toString.call(item);\n\n if (name === '[object Window]' || name === '[object global]' || name === '[object DOMWindow]') {\n return false;\n }\n }\n\n if (typeof item.then === 'function') {\n return true;\n }\n } catch (err) {\n return false;\n }\n\n return false;\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nconst dispatchedErrors = [];\nconst possiblyUnhandledPromiseHandlers : Array<(mixed, promise? : ZalgoPromise) => void> = [];\n\nexport function dispatchPossiblyUnhandledError(err : mixed, promise : ZalgoPromise) {\n\n if (dispatchedErrors.indexOf(err) !== -1) {\n return;\n }\n\n dispatchedErrors.push(err);\n\n setTimeout(() => {\n if (__DEBUG__) {\n // $FlowFixMe\n throw new Error(`${ err.stack || err.toString() }\\n\\nFrom promise:\\n\\n${ promise.stack }`);\n }\n\n throw err;\n }, 1);\n\n for (let j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {\n // $FlowFixMe\n possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n}\n\nexport function onPossiblyUnhandledException(handler : (mixed, promise? : ZalgoPromise) => void) : {| cancel : () => void |} {\n possiblyUnhandledPromiseHandlers.push(handler);\n\n return {\n cancel() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n}\n","/* @flow */\n\nimport type { ZalgoPromise } from './promise';\n\nlet activeCount = 0;\nlet flushPromise;\n\nfunction flushActive() {\n if (!activeCount && flushPromise) {\n const promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n}\n\nexport function startActive() {\n activeCount += 1;\n}\n\nexport function endActive() {\n activeCount -= 1;\n flushActive();\n}\n\nexport function awaitActive(Zalgo : Class>) : ZalgoPromise { // eslint-disable-line no-undef\n const promise = flushPromise = flushPromise || new Zalgo();\n flushActive();\n return promise;\n}\n","/* @flow */\n\nimport { isPromise } from './utils';\nimport { onPossiblyUnhandledException, dispatchPossiblyUnhandledError } from './exceptions';\nimport { startActive, endActive, awaitActive } from './flush';\n\nexport class ZalgoPromise {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\n // eslint-disable-next-line flowtype/no-mutable-array\n handlers : Array<{|\n promise : ZalgoPromise<*>,\n onSuccess : void | (result : R) => mixed,\n onError : void | (error : mixed) => mixed\n |}>\n dispatching : boolean\n stack : string\n\n constructor(handler : ?(resolve : (result : R) => void, reject : (error : mixed) => void) => void) {\n\n this.resolved = false;\n this.rejected = false;\n this.errorHandled = false;\n\n this.handlers = [];\n\n if (handler) {\n\n let result;\n let error;\n let resolved = false;\n let rejected = false;\n let isAsync = false;\n\n startActive();\n\n try {\n handler(res => {\n if (isAsync) {\n this.resolve(res);\n } else {\n resolved = true;\n result = res;\n }\n\n }, err => {\n if (isAsync) {\n this.reject(err);\n } else {\n rejected = true;\n error = err;\n }\n });\n\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n\n endActive();\n\n isAsync = true;\n\n if (resolved) {\n // $FlowFixMe\n this.resolve(result);\n } else if (rejected) {\n this.reject(error);\n }\n }\n\n if (__DEBUG__) {\n try {\n throw new Error(`ZalgoPromise`);\n } catch (err) {\n this.stack = err.stack;\n }\n }\n }\n\n resolve(result : R) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(result)) {\n throw new Error('Can not resolve promise with another promise');\n }\n\n this.resolved = true;\n this.value = result;\n this.dispatch();\n\n return this;\n }\n\n reject(error : mixed) : ZalgoPromise {\n if (this.resolved || this.rejected) {\n return this;\n }\n\n if (isPromise(error)) {\n throw new Error('Can not reject promise with another promise');\n }\n\n if (!error) {\n // $FlowFixMe\n const err = (error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error));\n error = new Error(`Expected reject to be called with Error, got ${ err }`);\n }\n\n this.rejected = true;\n this.error = error;\n\n if (!this.errorHandled) {\n setTimeout(() => {\n if (!this.errorHandled) {\n dispatchPossiblyUnhandledError(error, this);\n }\n }, 1);\n }\n\n this.dispatch();\n\n return this;\n }\n\n asyncReject(error : mixed) : ZalgoPromise {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n const { dispatching, resolved, rejected, handlers } = this;\n\n if (dispatching) {\n return;\n }\n\n if (!resolved && !rejected) {\n return;\n }\n\n this.dispatching = true;\n startActive();\n\n const chain = (firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n secondPromise.resolve(res);\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < handlers.length; i++) {\n\n const { onSuccess, onError, promise } = handlers[i];\n\n let result;\n\n if (resolved) {\n\n try {\n result = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n }\n\n } else if (rejected) {\n\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n\n try {\n result = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n const promiseResult : ZalgoPromise<*> = result;\n\n if (promiseResult.resolved) {\n promise.resolve(promiseResult.value);\n } else {\n promise.reject(promiseResult.error);\n }\n\n promiseResult.errorHandled = true;\n\n } else if (isPromise(result)) {\n\n if (result instanceof ZalgoPromise && (result.resolved || result.rejected)) {\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n } else {\n // $FlowFixMe\n chain(result, promise);\n }\n\n } else {\n\n promise.resolve(result);\n }\n }\n\n handlers.length = 0;\n this.dispatching = false;\n endActive();\n }\n\n then(onSuccess : void | (result : R) => (ZalgoPromise | Y), onError : void | (error : mixed) => (ZalgoPromise | Y)) : ZalgoPromise {\n\n if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {\n throw new Error('Promise.then expected a function for success handler');\n }\n\n if (onError && typeof onError !== 'function' && !onError.call) {\n throw new Error('Promise.then expected a function for error handler');\n }\n\n const promise = new ZalgoPromise();\n\n this.handlers.push({\n promise,\n onSuccess,\n onError\n });\n\n this.errorHandled = true;\n\n this.dispatch();\n\n return promise;\n }\n\n catch(onError : (error : mixed) => ZalgoPromise | Y) : ZalgoPromise {\n // $FlowFixMe incompatible-call\n const resultPromise : ZalgoPromise = this.then(undefined, onError);\n return resultPromise;\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise {\n\n if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {\n throw new Error('Promise.finally expected a function');\n }\n\n return this.then((result) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n return result;\n });\n }, (err) => {\n return ZalgoPromise.try(onFinally)\n .then(() => {\n throw err;\n });\n });\n }\n\n timeout(time : number, err : ?Error) : ZalgoPromise {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n const timeout = setTimeout(() => {\n\n if (this.resolved || this.rejected) {\n return;\n }\n\n this.reject(err || new Error(`Promise timed out after ${ time }ms`));\n\n }, time);\n\n return this.then(result => {\n clearTimeout(timeout);\n return result;\n });\n }\n\n // $FlowFixMe\n toPromise() : Promise {\n // $FlowFixMe\n if (typeof Promise === 'undefined') {\n throw new TypeError(`Could not find Promise`);\n }\n // $FlowFixMe\n return Promise.resolve(this); // eslint-disable-line compat/compat\n }\n\n lazy() : ZalgoPromise {\n this.errorHandled = true;\n return this;\n }\n\n static resolve(value : ZalgoPromise | Y) : ZalgoPromise {\n\n if (value instanceof ZalgoPromise) {\n // $FlowFixMe incompatible-type-arg\n const result : ZalgoPromise = value;\n return result;\n }\n\n if (isPromise(value)) {\n // $FlowFixMe\n return new ZalgoPromise((resolve, reject) => value.then(resolve, reject));\n }\n\n return new ZalgoPromise().resolve(value);\n }\n\n static reject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all>(promises : X) : ZalgoPromise<$TupleMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n\n const promise = new ZalgoPromise();\n let count = promises.length;\n // eslint-disable-next-line no-undef\n const results = ([] : $TupleMap(ZalgoPromise | Y) => Y>).slice();\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n const chain = (i : number, firstPromise : ZalgoPromise, secondPromise : ZalgoPromise) => {\n return firstPromise.then(res => {\n results[i] = res;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n secondPromise.reject(err);\n });\n };\n\n for (let i = 0; i < promises.length; i++) {\n const prom = promises[i];\n\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash(promises : O) : ZalgoPromise<$ObjMap(ZalgoPromise | Y) => Y>> { // eslint-disable-line no-undef\n const result = {};\n const awaitPromises = [];\n\n for (const key in promises) {\n if (promises.hasOwnProperty(key)) {\n const value = promises[key];\n\n if (isPromise(value)) {\n awaitPromises.push(value.then(res => {\n result[key] = res;\n }));\n } else {\n result[key] = value;\n }\n }\n }\n \n return ZalgoPromise.all(awaitPromises).then(() => result);\n }\n\n static map(items : $ReadOnlyArray, method : (T) => (ZalgoPromise | X)) : ZalgoPromise<$ReadOnlyArray> {\n // $FlowFixMe\n return ZalgoPromise.all(items.map(method));\n }\n\n static onPossiblyUnhandledException(handler : (err : mixed) => void) : {| cancel : () => void |} {\n return onPossiblyUnhandledException(handler);\n }\n\n static try>(method : (...args : $ReadOnlyArray) => (ZalgoPromise | Y), context? : C, args? : A) : ZalgoPromise {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result : ZalgoPromise | Y;\n\n startActive();\n \n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n // $FlowFixMe incompatible-call\n const resultPromise = ZalgoPromise.resolve(result);\n\n return resultPromise;\n }\n\n static delay(delay : number) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n setTimeout(resolve, delay);\n });\n }\n\n static isPromise(value : mixed) : boolean {\n\n if (value && value instanceof ZalgoPromise) {\n return true;\n }\n\n return isPromise(value);\n }\n\n static flush() : ZalgoPromise {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe method-unbinding\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nexport const PROTOCOL = {\n MOCK: ('mock:' : 'mock:'),\n FILE: ('file:' : 'file:'),\n ABOUT: ('about:' : 'about:')\n};\n\nexport const WILDCARD = '*';\n\nexport const WINDOW_TYPE = {\n IFRAME: ('iframe' : 'iframe'),\n POPUP: ('popup' : 'popup')\n};\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isRegex, noop } from './util';\nimport type { CrossDomainWindowType, SameDomainWindowType, DomainMatcher } from './types';\nimport { PROTOCOL, WILDCARD } from './constants';\n\nconst IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function getActualProtocol(win : SameDomainWindowType = window) : ?string {\n return win.location.protocol;\n}\n\nexport function getProtocol(win : SameDomainWindowType = window) : ?string {\n if (win.mockDomain) {\n const protocol = win.mockDomain.split('//')[0];\n\n if (protocol) {\n return protocol;\n }\n }\n\n return getActualProtocol(win);\n}\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.ABOUT;\n}\n\nexport function isMockProtocol(win : SameDomainWindowType = window) : boolean {\n return getProtocol(win) === PROTOCOL.MOCK;\n}\n\nexport function getParent(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n try {\n if (win.parent && win.parent !== win) {\n return win.parent;\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function getOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\n\n // Make sure we're not actually an iframe which has had window.open() called on us\n if (getParent(win)) {\n return;\n }\n\n try {\n return win.opener;\n } catch (err) {\n // pass\n }\n}\n\nexport function canReadFromWindow(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n noop(win && win.location && win.location.href);\n return true;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getActualDomain(win? : SameDomainWindowType = window) : string {\n\n const location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n const protocol = getActualProtocol(win);\n\n if (!protocol) {\n throw new Error(`Can not read window protocol`);\n }\n\n if (protocol === PROTOCOL.FILE) {\n return `${ PROTOCOL.FILE }//`;\n }\n\n if (protocol === PROTOCOL.ABOUT) {\n\n const parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n const host = location.host;\n\n if (!host) {\n throw new Error(`Can not read window host`);\n }\n\n return `${ protocol }//${ host }`;\n}\n\nexport function getDomain(win? : SameDomainWindowType = window) : string {\n\n const domain = getActualDomain(win);\n\n if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {\n return win.mockDomain;\n }\n\n return domain;\n}\n\nexport function isBlankDomain(win : CrossDomainWindowType) : boolean {\n try {\n // $FlowFixMe\n if (!win.location.href) {\n return true;\n }\n\n if (win.location.href === 'about:blank') {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isActuallySameDomain(win : CrossDomainWindowType) : boolean {\n\n try {\n if (win === window) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n const desc = Object.getOwnPropertyDescriptor(win, 'location');\n\n if (desc && desc.enumerable === false) {\n return false;\n }\n\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (isMockProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n try {\n // $FlowFixMe\n if (getActualDomain(win) === getActualDomain(window)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : boolean {\n\n if (!isActuallySameDomain(win)) {\n return false;\n }\n\n try {\n if (win === window) {\n return true;\n }\n \n // $FlowFixMe\n if (isAboutProtocol(win) && canReadFromWindow(win)) {\n return true;\n }\n\n // $FlowFixMe\n if (getDomain(window) === getDomain(win)) {\n return true;\n }\n\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\n\nexport function assertSameDomain(win : CrossDomainWindowType | SameDomainWindowType) : SameDomainWindowType {\n if (!isSameDomain(win)) {\n throw new Error(`Expected window to be same domain`);\n }\n\n // $FlowFixMe\n return win;\n}\n\nexport function getParents(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n try {\n\n while (win.parent !== win) {\n result.push(win.parent);\n win = win.parent;\n }\n\n } catch (err) {\n // pass\n }\n\n return result;\n}\n\nexport function isAncestorParent(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n if (!parent || !child) {\n return false;\n }\n\n const childParent = getParent(child);\n\n if (childParent) {\n return childParent === parent;\n }\n\n if (getParents(child).indexOf(parent) !== -1) {\n return true;\n }\n\n return false;\n}\n\nexport function getFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n let frames;\n\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n\n let len;\n\n try {\n len = frames.length;\n } catch (err) {\n // pass\n }\n\n if (len === 0) {\n return result;\n }\n\n if (len) {\n for (let i = 0; i < len; i++) {\n\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n\n result.push(frame);\n }\n\n return result;\n }\n\n for (let i = 0; i < 100; i++) {\n let frame;\n\n try {\n frame = frames[i];\n } catch (err) {\n return result;\n }\n\n if (!frame) {\n return result;\n }\n\n result.push(frame);\n }\n\n return result;\n}\n\n\nexport function getAllChildFrames(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const result = [];\n\n for (const frame of getFrames(win)) {\n result.push(frame);\n\n for (const childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n\n try {\n if (win.top) {\n return win.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(win) === win) {\n return win;\n }\n\n try {\n if (isAncestorParent(window, win) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (isAncestorParent(win, window) && window.top) {\n return window.top;\n }\n } catch (err) {\n // pass\n }\n\n for (const frame of getAllChildFrames(win)) {\n try {\n if (frame.top) {\n return frame.top;\n }\n } catch (err) {\n // pass\n }\n\n if (getParent(frame) === frame) {\n return frame;\n }\n }\n}\n\nexport function getNextOpener(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n return getOpener(getTop(win) || win);\n}\n\nexport function getUltimateTop(win? : CrossDomainWindowType = window) : CrossDomainWindowType {\n const opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : $ReadOnlyArray {\n const top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n let result = [ ...getAllChildFrames(top), top ];\n\n // Win may be in shadow dom\n if (result.indexOf(win) === -1) {\n result = [ ...result, win, ...getAllChildFrames(win) ];\n }\n\n return result;\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray {\n const frames = getAllFramesInWindow(win);\n const opener = getNextOpener(win);\n\n if (opener) {\n return [ ...getAllWindows(opener), ...frames ];\n } else {\n return frames;\n }\n}\n\nexport function isTop(win : CrossDomainWindowType) : boolean {\n return win === getTop(win);\n}\n\nexport function isFrameWindowClosed(frame : HTMLIFrameElement) : boolean {\n\n if (!frame.contentWindow) {\n return true;\n }\n\n if (!frame.parentNode) {\n return true;\n }\n\n const doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n let parent = frame;\n\n while (parent.parentNode && parent.parentNode !== parent) {\n parent = parent.parentNode;\n }\n\n // $FlowFixMe\n if (!parent.host || !doc.documentElement.contains(parent.host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\nconst iframeWindows = [];\nconst iframeFrames = [];\n\nexport function isWindowClosed(win : CrossDomainWindowType, allowMock : boolean = true) : boolean {\n\n try {\n if (win === window) {\n return false;\n }\n } catch (err) {\n return true;\n }\n\n try {\n if (!win) {\n return true;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (win.closed) {\n return true;\n }\n\n } catch (err) {\n\n // I love you so much IE\n\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return false;\n }\n\n return true;\n }\n\n\n if (allowMock && isSameDomain(win)) {\n try {\n // $FlowFixMe\n if (win.mockclosed) {\n return true;\n }\n } catch (err) {\n // pass\n }\n }\n\n // Mobile safari\n\n try {\n if (!win.parent || !win.top) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n // Yes, this actually happens in IE. win === win errors out when the window\n // is from an iframe, and the iframe was removed from the page.\n\n try {\n noop(win === win); // eslint-disable-line no-self-compare\n } catch (err) {\n return true;\n }\n\n // IE orphaned frame\n\n const iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n const frame = iframeFrames[iframeIndex];\n\n if (frame && isFrameWindowClosed(frame)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction cleanIframes() {\n for (let i = 0; i < iframeWindows.length; i++) {\n let closed = false;\n\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {\n // pass\n }\n\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n}\n\nexport function linkFrameWindow(frame : HTMLIFrameElement) {\n\n cleanIframes();\n\n if (frame && frame.contentWindow) {\n try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {\n // pass\n }\n }\n}\n\nexport function getUserAgent(win : ?SameDomainWindowType) : string {\n win = win || window;\n return win.navigator.mockUserAgent || win.navigator.userAgent;\n}\n\n\nexport function getFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const winFrames = getFrames(win);\n\n for (const childFrame of winFrames) {\n try {\n // $FlowFixMe\n if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {\n return childFrame;\n }\n } catch (err) {\n // pass\n }\n }\n\n try {\n // $FlowFixMe\n if (winFrames.indexOf(win.frames[name]) !== -1) {\n // $FlowFixMe\n return win.frames[name];\n }\n } catch (err) {\n // pass\n }\n\n try {\n if (winFrames.indexOf(win[name]) !== -1) {\n return win[name];\n }\n } catch (err) {\n // pass\n }\n}\n\nexport function findChildFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (const childFrame of getFrames(win)) {\n const namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n const frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n const top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n const frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (const childFrame of getFrames(win)) {\n if (childFrame === frame) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isOpener(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n return parent === getOpener(child);\n}\n\nexport function getAncestor(win? : CrossDomainWindowType = window) : ?CrossDomainWindowType {\n win = win || window;\n\n const opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n const parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : $ReadOnlyArray {\n\n const results = [];\n\n let ancestor = win;\n\n while (ancestor) {\n ancestor = getAncestor(ancestor);\n if (ancestor) {\n results.push(ancestor);\n }\n }\n\n return results;\n}\n\n\nexport function isAncestor(parent : CrossDomainWindowType, child : CrossDomainWindowType) : boolean {\n\n const actualParent = getAncestor(child);\n\n if (actualParent) {\n if (actualParent === parent) {\n return true;\n }\n\n return false;\n }\n\n if (child === parent) {\n return false;\n }\n\n if (getTop(child) === child) {\n return false;\n }\n\n for (const frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getOpener(win));\n}\n\nexport function isIframe(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(getParent(win));\n}\n\nexport function isFullpage(win? : CrossDomainWindowType = window) : boolean {\n return Boolean(!isIframe(win) && !isPopup(win));\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (const item1 of collection1) {\n for (const item2 of collection2) {\n if (item1 === item2) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function getDistanceFromTop(win : CrossDomainWindowType = window) : number {\n let distance = 0;\n let parent = win;\n\n while (parent) {\n parent = getParent(parent);\n if (parent) {\n distance += 1;\n }\n }\n\n return distance;\n}\n\nexport function getNthParent(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n let parent = win;\n\n for (let i = 0; i < n; i++) {\n if (!parent) {\n return;\n }\n\n parent = getParent(parent);\n }\n\n return parent;\n}\n\nexport function getNthParentFromTop(win : CrossDomainWindowType, n : number = 1) : ?CrossDomainWindowType {\n return getNthParent(win, getDistanceFromTop(win) - n);\n}\n\nexport function isSameTopWindow(win1 : CrossDomainWindowType, win2 : CrossDomainWindowType) : boolean {\n\n const top1 = getTop(win1) || win1;\n const top2 = getTop(win2) || win2;\n\n try {\n if (top1 && top2) {\n if (top1 === top2) {\n return true;\n }\n\n return false;\n }\n } catch (err) {\n // pass\n }\n\n const allFrames1 = getAllFramesInWindow(win1);\n const allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n const opener1 = getOpener(top1);\n const opener2 = getOpener(top2);\n\n if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {\n return false;\n }\n\n if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {\n return false;\n }\n\n return false;\n}\n\nexport function matchDomain(pattern : DomainMatcher, origin : DomainMatcher) : boolean {\n\n if (typeof pattern === 'string') {\n\n if (typeof origin === 'string') {\n return pattern === WILDCARD || origin === pattern;\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n }\n\n if (isRegex(pattern)) {\n\n if (isRegex(origin)) {\n return pattern.toString() === origin.toString();\n }\n\n if (Array.isArray(origin)) {\n return false;\n }\n\n // $FlowFixMe\n return Boolean(origin.match(pattern));\n }\n\n if (Array.isArray(pattern)) {\n\n if (Array.isArray(origin)) {\n return JSON.stringify(pattern) === JSON.stringify(origin);\n }\n\n if (isRegex(origin)) {\n return false;\n }\n\n return pattern.some(subpattern => matchDomain(subpattern, origin));\n }\n\n return false;\n}\n\nexport function stringifyDomainPattern(pattern : DomainMatcher) : string {\n if (Array.isArray(pattern)) {\n return `(${ pattern.join(' | ') })`;\n } else if (isRegex(pattern)) {\n return `RegExp(${ pattern.toString() })`;\n } else {\n return pattern.toString();\n }\n}\n\nexport function getDomainFromUrl(url : string) : string {\n\n let domain;\n\n if (url.match(/^(https?|mock|file):\\/\\//)) {\n domain = url;\n } else {\n return getDomain();\n }\n\n domain = domain.split('/').slice(0, 3).join('/');\n\n return domain;\n}\n\nexport function onCloseWindow(win : CrossDomainWindowType, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} {\n\n let timeout;\n\n const check = () => {\n\n if (isWindowClosed(win)) {\n\n if (timeout) {\n clearTimeout(timeout);\n }\n\n return callback();\n }\n\n if (maxtime <= 0) {\n clearTimeout(timeout);\n } else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n };\n\n check();\n\n return {\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n// eslint-disable-next-line complexity\nexport function isWindow(obj : Object) : boolean {\n\n try {\n if (obj === window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(obj) === '[object Window]') {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (window.Window && obj instanceof window.Window) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.self === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.parent === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (obj && obj.top === obj) {\n return true;\n }\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) {\n return true;\n }\n }\n\n try {\n if (noop(obj === obj) === '__unlikely_value__') { // eslint-disable-line no-self-compare\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {\n return false;\n }\n\n } catch (err) {\n return true;\n }\n\n try {\n if ('postMessage' in obj && 'self' in obj && 'location' in obj) {\n return true;\n }\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined' && typeof window.location !== 'undefined');\n}\n\nexport function isCurrentDomain(domain : string) : boolean {\n if (!isBrowser()) {\n return false;\n }\n\n return (getDomain() === domain);\n}\n\nexport function isMockDomain(domain : string) : boolean {\n return domain.indexOf(PROTOCOL.MOCK) === 0;\n}\n\nexport function normalizeMockUrl(url : string) : string {\n if (!isMockDomain(getDomainFromUrl(url))) {\n return url;\n }\n\n if (!__TEST__) {\n throw new Error(`Mock urls not supported out of test mode`);\n }\n\n return url.replace(/^mock:\\/\\/[^/]+/, getActualDomain(window));\n}\n\nexport function getFrameForWindow(win : CrossDomainWindowType) : ?HTMLElement {\n if (isSameDomain(win)) {\n return assertSameDomain(win).frameElement;\n }\n\n for (const frame of document.querySelectorAll('iframe')) {\n if (frame && frame.contentWindow && frame.contentWindow === win) {\n return frame;\n }\n }\n}\n\nexport function closeWindow(win : CrossDomainWindowType) {\n if (isIframe(win)) {\n const frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf(collection : $ReadOnlyArray, item : T) : number {\n for (let i = 0; i < collection.length; i++) {\n\n try {\n if (collection[i] === item) {\n return i;\n }\n } catch (err) {\n // pass\n }\n }\n\n return -1;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n","/* @flow */\n\nimport { isWindow, isWindowClosed } from 'cross-domain-utils/src';\n\nimport { hasNativeWeakMap } from './native';\nimport { noop, safeIndexOf } from './util';\n\nexport class CrossDomainSafeWeakMap {\n\n name : string\n weakmap : ?WeakMap\n // eslint-disable-next-line flowtype/no-mutable-array\n keys : Array\n // eslint-disable-next-line flowtype/no-mutable-array\n values : Array\n\n constructor() {\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__`;\n\n if (hasNativeWeakMap()) {\n try {\n this.weakmap = new WeakMap();\n } catch (err) {\n // pass\n }\n }\n\n this.keys = [];\n this.values = [];\n }\n\n _cleanupClosedWindows() {\n\n const weakmap = this.weakmap;\n const keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n const value = keys[i];\n\n if (isWindow(value) && isWindowClosed(value)) {\n\n if (weakmap) {\n try {\n weakmap.delete(value);\n } catch (err) {\n // pass\n }\n }\n\n keys.splice(i, 1);\n this.values.splice(i, 1);\n\n i -= 1;\n }\n }\n }\n\n isSafeToReadWrite(key : K) : boolean {\n\n if (isWindow(key)) {\n return false;\n }\n\n try {\n noop(key && key.self);\n noop(key && key[this.name]);\n } catch (err) {\n return false;\n }\n\n return true;\n }\n\n set(key : K, value : V) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const name = this.name;\n const entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: true\n });\n }\n\n return;\n\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const values = this.values;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n keys.push(key);\n values.push(value);\n } else {\n values[index] = value;\n }\n }\n\n get(key : K) : V | void {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return weakmap.get(key);\n }\n \n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return entry[1];\n }\n\n return;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index === -1) {\n return;\n }\n\n return this.values[index];\n }\n\n delete(key : K) {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n entry[0] = entry[1] = undefined;\n }\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const keys = this.keys;\n const index = safeIndexOf(keys, key);\n\n if (index !== -1) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n }\n\n has(key : K) : boolean {\n\n if (!key) {\n throw new Error(`WeakMap expected key`);\n }\n\n const weakmap = this.weakmap;\n\n if (weakmap) {\n try {\n if (weakmap.has(key)) {\n return true;\n }\n } catch (err) {\n delete this.weakmap;\n }\n }\n\n if (this.isSafeToReadWrite(key)) {\n try {\n const entry = key[this.name];\n\n if (entry && entry[0] === key) {\n return true;\n }\n\n return false;\n } catch (err) {\n // pass\n }\n }\n\n this._cleanupClosedWindows();\n\n const index = safeIndexOf(this.keys, key);\n return index !== -1;\n }\n\n getOrSet(key : K, getter : () => V) : V {\n if (this.has(key)) {\n // $FlowFixMe\n return this.get(key);\n }\n\n const value = getter();\n this.set(key, value);\n return value;\n }\n}\n","\n/* @flow */\n/* eslint max-lines: 0 */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport type { CancelableType } from './types';\n\nexport function isElement(element : mixed) : boolean {\n let passed = false;\n\n try {\n if (element instanceof window.Element) {\n passed = true;\n } else if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n passed = true;\n }\n } catch (_) {\n // we don't have an element\n }\n\n return passed;\n}\n\nexport function getFunctionName (fn : T) : string {\n return fn.name || fn.__name__ || fn.displayName || 'anonymous';\n}\n\nexport function setFunctionName (fn : T, name : string) : T {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {\n // pass\n }\n\n fn.__name__ = fn.displayName = name;\n return fn;\n}\n\nexport function base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (m, p1) => {\n return String.fromCharCode(parseInt(p1, 16));\n })).replace(/[=]/g, '');\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64').replace(/[=]/g, '');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof atob === 'function') {\n // $FlowFixMe[method-unbinding]\n return decodeURIComponent(Array.prototype.map.call(atob(str), c => {\n // eslint-disable-next-line prefer-template\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n }\n\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf8');\n }\n\n throw new Error(`Can not find window.atob or Buffer`);\n}\n\nexport function uniqueID() : string {\n\n const chars = '0123456789abcdef';\n\n const randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n const timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `uid_${ randomID }_${ timeID }`;\n}\n\nexport function getGlobal() : Object {\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof __GLOBAL__ !== 'undefined') {\n return __GLOBAL__;\n }\n throw new Error(`No global found`);\n}\n\nlet objectIDs;\n\nexport function getObjectID(obj : Object) : string {\n\n objectIDs = objectIDs || new WeakMap();\n\n if (obj === null || obj === undefined || (typeof obj !== 'object' && typeof obj !== 'function')) {\n throw new Error(`Invalid object`);\n }\n\n let uid = objectIDs.get(obj);\n\n if (!uid) {\n uid = `${ typeof obj }:${ uniqueID() }`;\n objectIDs.set(obj, uid);\n }\n\n return uid;\n}\n\nfunction serializeArgs(args : $ReadOnlyArray) : string {\n try {\n // $FlowFixMe[method-unbinding]\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n\n // Treat each distinct function as unique for purposes of memoization\n // e.g. even if someFunction.stringify() is the same, we may use a different memoize cache\n // if the actual function is different.\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n\n // By default JSON.stringify(domElement) returns '{}'. This ensures that stays true even for non-standard\n // elements (e.g. React-rendered dom elements) with custom properties\n if (isElement(val)) {\n return {};\n }\n\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\nexport function getEmptyObject() : {||} {\n // $FlowFixMe\n return {};\n}\n\ntype MemoizeOptions = {|\n name? : string,\n time? : number,\n thisNamespace? : boolean\n|};\n\nconst getDefaultMemoizeOptions = () : MemoizeOptions => {\n // $FlowFixMe\n return {};\n};\n\nexport type Memoized = F & {| reset : () => void |};\n\nlet memoizeGlobalIndex = 0;\nlet memoizeGlobalIndexValidFrom = 0;\n\nexport function memoize(method : F, options? : MemoizeOptions = getDefaultMemoizeOptions()) : Memoized {\n const { thisNamespace = false, time: cacheTime } = options;\n\n let simpleCache;\n let thisCache;\n\n let memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n\n const memoizedFunction = function memoizedFunction(...args) : mixed {\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n\n let cache;\n\n if (thisNamespace) {\n thisCache = thisCache || new WeakMap();\n cache = thisCache.getOrSet(this, getEmptyObject);\n } else {\n cache = simpleCache = simpleCache || {};\n }\n\n let cacheKey;\n\n try {\n cacheKey = serializeArgs(args);\n } catch {\n return method.apply(this, arguments);\n }\n\n let cacheResult = cache[cacheKey];\n\n if (cacheResult && cacheTime && (Date.now() - cacheResult.time) < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n\n if (cacheResult) {\n return cacheResult.value;\n }\n\n const time = Date.now();\n const value = method.apply(this, arguments);\n\n cache[cacheKey] = { time, value };\n\n return value;\n };\n\n memoizedFunction.reset = () => {\n simpleCache = null;\n thisCache = null;\n };\n\n // $FlowFixMe\n const result : F = memoizedFunction;\n\n return setFunctionName(result, `${ options.name || getFunctionName(method) }::memoized`);\n}\n\nmemoize.clear = () => {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n};\n\nexport function promiseIdentity(item : ZalgoPromise | T) : ZalgoPromise {\n // $FlowFixMe\n return ZalgoPromise.resolve(item);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise(method : (...args : $ReadOnlyArray) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : $ReadOnlyArray) : ZalgoPromise {\n const key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = ZalgoPromise.try(() => method.apply(this, arguments))\n .finally(() => {\n delete cache[key];\n });\n\n return cache[key];\n }\n\n memoizedPromiseFunction.reset = () => {\n cache = {};\n };\n\n return setFunctionName(memoizedPromiseFunction, `${ getFunctionName(method) }::promiseMemoized`);\n}\n\ntype PromisifyOptions = {|\n name ? : string\n|};\n\nconst getDefaultPromisifyOptions = () : PromisifyOptions => {\n // $FlowFixMe\n return {};\n};\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify(method : (...args : $ReadOnlyArray) => R, options : PromisifyOptions = getDefaultPromisifyOptions()) : ((...args : $ReadOnlyArray) => ZalgoPromise) {\n function promisifiedFunction() : ZalgoPromise {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return setFunctionName(promisifiedFunction, `${ getFunctionName(method) }::promisified`);\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize(method : (...args : $ReadOnlyArray) => R, logic : (...args : $ReadOnlyArray) => R, args : $ReadOnlyArray = []) : R {\n // $FlowFixMe\n const cache : {| [string] : R |} = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n const key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n const result = cache[key] = logic(...args);\n\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : $ReadOnlyArray) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n const onceFunction = function() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\n\n return setFunctionName(onceFunction, `${ getFunctionName(method) }::once`);\n}\n\nexport function hashStr(str : string) : number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);\n }\n return Math.floor(Math.pow(Math.sqrt(hash), 5));\n}\n\nexport function strHashStr(str : string) : string {\n let hash = '';\n\n for (let i = 0; i < str.length; i++) {\n let total = (str[i].charCodeAt(0) * i);\n\n if (str[i + 1]) {\n total += (str[i + 1].charCodeAt(0) * (i - 1));\n }\n\n hash += String.fromCharCode(97 + (Math.abs(total) % 26));\n }\n\n return hash;\n}\n\nexport function match(str : string, pattern : RegExp) : ?string {\n const regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey(obj : Object, key : string) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n\n let value = obj[key];\n\n if (value) {\n return resolve(value);\n }\n\n delete obj[key];\n\n Object.defineProperty(obj, key, {\n\n configurable: true,\n\n set(item) {\n value = item;\n\n if (value) {\n resolve(value);\n }\n },\n\n get() : T {\n return value;\n }\n });\n });\n}\n\nexport function stringifyError(err : mixed, level : number = 1) : string {\n\n if (level >= 3) {\n return 'stringifyError stack overflow';\n }\n\n try {\n if (!err) {\n // $FlowFixMe[method-unbinding]\n return ``;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n const stack = err && err.stack;\n const message = err && err.message;\n\n if (stack && message) {\n if (stack.indexOf(message) !== -1) {\n return stack;\n } else {\n return `${ message }\\n${ stack }`;\n }\n } else if (stack) {\n return stack;\n } else if (message) {\n return message;\n }\n }\n\n if (err && err.toString && typeof err.toString === 'function') {\n // $FlowFixMe\n return err.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(err);\n\n } catch (newErr) {\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n // $FlowFixMe[method-unbinding]\n const defaultMessage = ``;\n\n if (!err) {\n return defaultMessage;\n }\n\n if (err instanceof Error) {\n return err.message || defaultMessage;\n }\n\n if (typeof err.message === 'string') {\n return err.message || defaultMessage;\n }\n\n return defaultMessage;\n}\n\nexport function stringify(item : mixed) : string {\n if (typeof item === 'string') {\n return item;\n }\n\n if (item && item.toString && typeof item.toString === 'function') {\n // $FlowFixMe\n return item.toString();\n }\n\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n const index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n const original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n // $FlowFixMe[method-unbinding]\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend(obj : T, source : Object) : T {\n if (!source) {\n return obj;\n }\n\n if (Object.assign) {\n return Object.assign(obj, source);\n }\n\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values(obj : { [string] : T }) : $ReadOnlyArray {\n if (Object.values) {\n // $FlowFixMe\n return Object.values(obj);\n }\n\n const result : Array = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n // $FlowFixMe[escaped-generic]\n result.push(obj[key]);\n }\n }\n\n // $FlowFixMe\n return result;\n}\n\n// eslint-disable-next-line no-undef\nexport const memoizedValues : ({ [string] : T }) => $ReadOnlyArray = memoize(values);\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : $ReadOnlyArray) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : $ReadOnlyArray) : number {\n return Math.max(...args);\n}\n\nexport function roundUp(num : number, nearest : number) : number {\n const remainder = num % nearest;\n return remainder\n ? (num - remainder) + nearest\n : num;\n}\n\nexport function regexMap(str : string, regexp : RegExp, handler : () => T) : $ReadOnlyArray {\n const results = [];\n\n // $FlowFixMe\n str.replace(regexp, function regexMapMatcher(item) {\n results.push(handler ? handler.apply(null, arguments) : item);\n });\n\n // $FlowFixMe\n return results;\n}\n\nexport function svgToBase64(svg : string) : string {\n return `data:image/svg+xml;base64,${ base64encode(svg) }`;\n}\n\nexport function objFilter(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n const result = {};\n\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {\n continue;\n }\n\n result[key] = obj[key];\n }\n\n return result;\n}\n\nexport function identity (item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : $ReadOnlyArray {\n const result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce(method : () => ZalgoPromise | T, delay : number = 50) : () => ZalgoPromise {\n\n let promise;\n let timeout;\n\n const promiseDebounced = function() : ZalgoPromise {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n const localPromise = promise = promise || new ZalgoPromise();\n\n timeout = setTimeout(() => {\n promise = null;\n timeout = null;\n\n ZalgoPromise.try(method).then(\n result => { localPromise.resolve(result); },\n err => { localPromise.reject(err); }\n );\n }, delay);\n\n return localPromise;\n };\n\n return setFunctionName(promiseDebounced, `${ getFunctionName(method) }::promiseDebounced`);\n}\n\nexport function safeInterval(method : Function, time : number) : {| cancel : () => void |} {\n\n let timeout;\n\n function loop() {\n timeout = setTimeout(() => {\n method();\n loop();\n }, time);\n }\n\n loop();\n\n return {\n cancel() {\n clearTimeout(timeout);\n }\n };\n}\n\nexport function isInteger(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+$/));\n}\n\nexport function isFloat(str : string) : boolean {\n return Boolean(str.match(/^[0-9]+\\.[0-9]+$/));\n}\n\nexport function serializePrimitive(value : string | number | boolean) : string {\n return value.toString();\n}\n\nexport function deserializePrimitive(value : string) : string | number | boolean {\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n } else if (isInteger(value)) {\n return parseInt(value, 10);\n } else if (isFloat(value)) {\n return parseFloat(value);\n } else {\n return value;\n }\n}\n\nexport function dotify(obj : Object, prefix : string = '', newobj : Object = {}) : { [string] : string } {\n prefix = prefix ? `${ prefix }.` : prefix;\n for (const key in obj) {\n if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {\n continue;\n } else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(val => typeof val !== 'object')) {\n newobj[`${ prefix }${ key }[]`] = obj[key].join(',');\n } else if (obj[key] && typeof obj[key] === 'object') {\n newobj = dotify(obj[key], `${ prefix }${ key }`, newobj);\n } else {\n newobj[`${ prefix }${ key }`] = serializePrimitive(obj[key]);\n }\n }\n return newobj;\n}\n\nexport function undotify(obj : { [string] : string }) : Object {\n\n const result = {};\n\n for (let key in obj) {\n if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {\n continue;\n }\n\n let value = obj[key];\n\n if (key.match(/^.+\\[\\]$/)) {\n key = key.slice(0, -2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n const parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const isLast = (i + 1 === parts.length);\n const isIndex = !isLast && isInteger(parts[i + 1]);\n\n if (part === 'constructor' || part === 'prototype' || part === '__proto__') {\n throw new Error(`Disallowed key: ${ part }`);\n }\n\n if (isLast) {\n // $FlowFixMe\n keyResult[part] = value;\n } else {\n // $FlowFixMe\n keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});\n }\n }\n }\n\n return result;\n}\n\nexport type EventEmitterType = {|\n on : (eventName : string, handler : Function) => CancelableType,\n once : (eventName : string, handler : Function) => CancelableType,\n trigger : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray) => ZalgoPromise,\n reset : () => void\n|};\n\nexport function eventEmitter() : EventEmitterType {\n const triggered = {};\n let handlers = {};\n\n const emitter = {\n\n on(eventName : string, handler : Function) : CancelableType {\n const handlerList = handlers[eventName] = handlers[eventName] || [];\n\n handlerList.push(handler);\n\n let cancelled = false;\n\n return {\n cancel() {\n if (!cancelled) {\n cancelled = true;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n\n }\n };\n },\n\n once(eventName : string, handler : Function) : CancelableType {\n\n const listener = emitter.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n const handlerList = handlers[eventName];\n const promises = [];\n\n if (handlerList) {\n for (const handler of handlerList) {\n promises.push(ZalgoPromise.try(() => handler(...args)));\n }\n }\n\n return ZalgoPromise.all(promises).then(noop);\n },\n\n triggerOnce(eventName : string, ...args : $ReadOnlyArray) : ZalgoPromise {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return emitter.trigger(eventName, ...args);\n },\n\n reset() {\n handlers = {};\n }\n };\n\n return emitter;\n}\n\nexport function camelToDasherize(string : string) : string {\n return string.replace(/([A-Z])/g, (g) => {\n return `-${ g.toLowerCase() }`;\n });\n}\n\nexport function dasherizeToCamel(string : string) : string {\n return string.replace(/-([a-z])/g, (g) => {\n return g[1].toUpperCase();\n });\n}\n\nexport function capitalizeFirstLetter(string : string) : string {\n return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();\n}\n\nexport function get(item : Object, path : string, def : mixed) : mixed {\n\n if (!path) {\n return def;\n }\n\n const pathParts = path.split('.');\n\n // Loop through each section of our key path\n\n for (let i = 0; i < pathParts.length; i++) {\n\n // If we have an object, we can get the key\n if (typeof item === 'object' && item !== null) {\n item = item[pathParts[i]];\n\n // Otherwise, we should return the default (undefined if not provided)\n } else {\n return def;\n }\n }\n\n // If our final result is undefined, we should return the default\n\n return item === undefined ? def : item;\n}\n\nexport function safeTimeout(method : Function, time : number) {\n\n const interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp(obj : Object | $ReadOnlyArray, key : string | number, getter : () => T) {\n if (Array.isArray(obj)) {\n if (typeof key !== 'number') {\n throw new TypeError(`Array key must be number`);\n }\n } else if (typeof obj === 'object' && obj !== null) {\n if (typeof key !== 'string') {\n throw new TypeError(`Object key must be string`);\n }\n }\n\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => {\n // $FlowFixMe\n delete obj[key];\n const value = getter();\n // $FlowFixMe\n obj[key] = value;\n return value;\n },\n set: (value : T) => {\n // $FlowFixMe\n delete obj[key];\n // $FlowFixMe\n obj[key] = value;\n }\n });\n}\n\nexport function arrayFrom(item : Iterable) : $ReadOnlyArray { // eslint-disable-line no-undef\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(item);\n}\n\nexport function isObject(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null);\n}\n\nexport function isObjectObject(obj : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isPlainObject(obj : mixed) : boolean {\n if (!isObjectObject(obj)) {\n return false;\n }\n\n // $FlowFixMe\n const constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n const prototype = constructor.prototype;\n\n if (!isObjectObject(prototype)) {\n return false;\n }\n\n if (!prototype.hasOwnProperty('isPrototypeOf')) {\n return false;\n }\n\n return true;\n}\n\nexport function replaceObject | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n const length = item.length;\n const result : Array = [];\n\n for (let i = 0; i < length; i++) {\n\n\n defineLazyProp(result, i, () => {\n const itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n const el = item[i];\n\n let child = replacer(el, i, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else if (isPlainObject(item)) {\n const result = {};\n\n for (const key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n const itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n const el = item[key];\n\n let child = replacer(el, key, itemKey);\n\n if (isPlainObject(child) || Array.isArray(child)) {\n // $FlowFixMe\n child = replaceObject(child, replacer, itemKey);\n }\n\n return child;\n });\n }\n\n // $FlowFixMe\n return result;\n } else {\n throw new Error(`Pass an object or array`);\n }\n}\n\n\nexport function copyProp(source : Object, target : Object, name : string, def : mixed) {\n if (source.hasOwnProperty(name)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, name);\n // $FlowFixMe\n Object.defineProperty(target, name, descriptor);\n\n } else {\n target[name] = def;\n }\n}\n\ntype RegexResultType = {|\n text : string,\n groups : $ReadOnlyArray,\n start : number,\n end : number,\n length : number,\n replace : (text : string) => string\n|};\n\nexport function regex(pattern : string | RegExp, string : string, start : number = 0) : ?RegexResultType {\n\n if (typeof pattern === 'string') {\n // eslint-disable-next-line security/detect-non-literal-regexp\n pattern = new RegExp(pattern);\n }\n\n const result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n const index : number = result.index;\n const regmatch = result[0];\n\n return {\n text: regmatch,\n groups: result.slice(1),\n start: start + index,\n end: start + index + regmatch.length,\n length: regmatch.length,\n\n replace(text : string) : string {\n\n if (!regmatch) {\n return '';\n }\n\n return `${ regmatch.slice(0, start + index) }${ text }${ regmatch.slice(index + regmatch.length) }`;\n }\n };\n}\n\nexport function regexAll(pattern : string | RegExp, string : string) : $ReadOnlyArray {\n\n const matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const regmatch = regex(pattern, string, start);\n\n if (!regmatch) {\n break;\n }\n\n matches.push(regmatch);\n start = match.end;\n }\n\n return matches;\n}\n\nexport function isDefined(value : ?mixed) : boolean {\n return value !== null && value !== undefined;\n}\n\nexport function cycle(method : Function) : ZalgoPromise {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce(method : (...args : $ReadOnlyArray) => T, time : number = 100) : (...args : $ReadOnlyArray) => void {\n\n let timeout;\n\n const debounceWrapper = function() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n\n return setFunctionName(debounceWrapper, `${ getFunctionName(method) }::debounced`);\n}\n\nexport function isRegex(item : mixed) : boolean {\n // $FlowFixMe[method-unbinding]\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoize : FunctionProxy<*> = (method : (arg : any) => R) : ((...args : $ReadOnlyArray) => R) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoized(arg : any) : R {\n return weakmap.getOrSet(arg, () => method.call(this, arg));\n };\n};\n\ntype FunctionPromiseProxy) => ZalgoPromise> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport const weakMapMemoizePromise : FunctionPromiseProxy<*, *> = (method : (arg : any) => ZalgoPromise) : ((...args : $ReadOnlyArray) => ZalgoPromise) => {\n\n const weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n }));\n };\n};\n\nexport function getOrSet(obj : O, key : string, getter : () => T) : T {\n if (obj.hasOwnProperty(key)) {\n return obj[key];\n }\n\n const val = getter();\n obj[key] = val;\n return val;\n}\n\nexport type CleanupType = {|\n set : (string, T) => T, // eslint-disable-line no-undef\n register : (Function) => {| cancel : () => void |},\n all : (err? : mixed) => ZalgoPromise\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n let cleanErr;\n\n const cleaner = {\n set(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) : {| cancel : () => void |} {\n const task = once(() => method(cleanErr));\n\n if (cleaned) {\n method(cleanErr);\n } else {\n tasks.push(task);\n }\n\n return {\n cancel: () => {\n const index = tasks.indexOf(task);\n if (index !== -1) {\n tasks.splice(index, 1);\n }\n }\n };\n },\n\n all(err? : mixed) : ZalgoPromise {\n cleanErr = err;\n\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.shift();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n\n return cleaner;\n}\n\nexport function tryCatch(fn : () => T) : {| result : T, error : void |} | {| result : void, error : mixed |} {\n let result;\n let error;\n\n try {\n result = fn();\n } catch (err) {\n error = err;\n }\n\n // $FlowFixMe\n return { result, error };\n}\n\n// eslint-disable-next-line flowtype/no-mutable-array\nexport function removeFromArray>(arr : T, item : X) {\n const index = arr.indexOf(item);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n}\n\nexport function assertExists(name : string, thing : void | null | T) : T {\n if (thing === null || typeof thing === 'undefined') {\n throw new Error(`Expected ${ name } to be present`);\n }\n\n return thing;\n}\n\nexport function unique(arr : $ReadOnlyArray) : $ReadOnlyArray {\n const result = {};\n for (const item of arr) {\n result[item] = true;\n }\n return Object.keys(result);\n}\n\nexport const constHas = (constant : T, value : X) : boolean => {\n return memoizedValues(constant).indexOf(value) !== -1;\n};\n\nexport function dedupeErrors(handler : (mixed) => T) : (mixed) => (T | void) {\n const seenErrors = [];\n const seenStringifiedErrors = {};\n\n return (err) => {\n if (seenErrors.indexOf(err) !== -1) {\n return;\n }\n\n seenErrors.push(err);\n\n const stringifiedError = stringifyError(err);\n if (seenStringifiedErrors[stringifiedError]) {\n return;\n }\n\n seenStringifiedErrors[stringifiedError] = true;\n return handler(err);\n };\n}\n\nexport class ExtendableError extends Error {\n constructor(message : string) {\n super(message);\n // eslint-disable-next-line unicorn/custom-error-definition\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error(message)).stack;\n }\n }\n}\n","/* @flow */\n\nexport function hasNativeWeakMap() : boolean {\n\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n if (typeof Object.freeze === 'undefined') {\n return false;\n }\n\n try {\n\n const testWeakMap = new WeakMap();\n const testKey = {};\n const testValue = '__testvalue__';\n\n Object.freeze(testKey);\n\n testWeakMap.set(testKey, testValue);\n\n if (testWeakMap.get(testKey) === testValue) {\n return true;\n }\n\n return false;\n\n } catch (err) {\n\n return false;\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* @flow */\n/* eslint max-lines: off */\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed, assertSameDomain,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { isElement, inlineMemoize, memoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom, ExtendableError, strHashStr } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES, ATTRIBUTES, UID_HASH_LENGTH } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function getBody() : HTMLBodyElement {\n // eslint-disable-next-line compat/compat\n const body = document.body;\n\n if (!body) {\n throw new Error(`Body element not found`);\n }\n\n return body;\n}\n\nexport function isDocumentReady() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'complete');\n}\n\nexport function isDocumentInteractive() : boolean {\n // eslint-disable-next-line compat/compat\n return Boolean(document.body) && (document.readyState === 'interactive');\n}\n\nexport function urlEncode(str : string) : string {\n return encodeURIComponent(str);\n}\n\nexport function waitForWindowReady() : ZalgoPromise {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\ntype WaitForDocumentReady = () => ZalgoPromise;\n\nexport const waitForDocumentReady : WaitForDocumentReady = memoize(() => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady() || isDocumentInteractive()) {\n return resolve();\n }\n\n const interval = setInterval(() => {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n});\n\nexport function waitForDocumentBody() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (document.body) {\n return document.body;\n }\n\n return waitForDocumentReady().then(() => {\n if (document.body) {\n return document.body;\n }\n\n throw new Error('Document ready but document.body not present');\n });\n });\n}\n\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n const params = {};\n\n if (!queryString) {\n return params;\n }\n\n if (queryString.indexOf('=') === -1) {\n return params;\n }\n\n for (let pair of queryString.split('&')) {\n pair = pair.split('=');\n\n if (pair[0] && pair[1]) {\n params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n }\n }\n\n return params;\n }, [ queryString ]);\n}\n\n\nexport function getQueryParam(name : string) : string {\n return parseQuery(window.location.search.slice(1))[name];\n}\n\nexport function urlWillRedirectPage(url : string) : boolean {\n\n if (url.indexOf('#') === -1) {\n return true;\n }\n\n if (url.indexOf('#') === 0) {\n return false;\n }\n\n if (url.split('#')[0] === window.location.href.split('#')[0]) {\n return false;\n }\n\n return true;\n}\n\nexport type Query = {\n [ string ] : boolean | string\n};\n\nexport function formatQuery(obj : Query = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string' || typeof obj[key] === 'boolean';\n }).map(key => {\n const val = obj[key];\n\n if (typeof val !== 'string' && typeof val !== 'boolean') {\n throw new TypeError(`Invalid type for query`);\n }\n\n return `${ urlEncode(key) }=${ urlEncode(val.toString()) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : Query = {}) : string {\n\n if (!props || !Object.keys(props).length) {\n return originalQuery;\n }\n\n return formatQuery({\n ...parseQuery(originalQuery),\n ...props\n });\n}\n\nexport function extendUrl(url : string, options : {| query? : Query, hash? : Query |}) : string {\n\n const query = options.query || {};\n const hash = options.hash || {};\n\n let originalUrl;\n let originalQuery;\n let originalHash;\n\n [ originalUrl, originalHash ] = url.split('#');\n [ originalUrl, originalQuery ] = originalUrl.split('?');\n\n const queryString = extendQuery(originalQuery, query);\n const hashString = extendQuery(originalHash, hash);\n\n if (queryString) {\n originalUrl = `${ originalUrl }?${ queryString }`;\n }\n\n if (hashString) {\n originalUrl = `${ originalUrl }#${ hashString }`;\n }\n\n return originalUrl;\n}\n\nexport function redirect(url : string, win : CrossDomainWindowType = window) : ZalgoPromise {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n const meta = document.querySelector('meta[name=viewport]');\n\n if (isDevice() && window.screen.width < 660 && !meta) {\n return false;\n }\n\n return true;\n}\n\nexport function isElementVisible(el : HTMLElement) : boolean {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n}\n\nexport function getPerformance() : ?Performance {\n return inlineMemoize(getPerformance, () : ?Performance => {\n const performance = window.performance;\n\n if (\n performance &&\n performance.now &&\n performance.timing &&\n performance.timing.connectEnd &&\n performance.timing.navigationStart &&\n (Math.abs(performance.now() - Date.now()) > 1000) &&\n (performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart)) > 0\n ) {\n return performance;\n }\n });\n}\n\nexport function enablePerformance() : boolean {\n return Boolean(getPerformance());\n}\n\nexport function getPageRenderTime() : ZalgoPromise {\n return waitForDocumentReady().then(() => {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n const timing = performance.timing;\n\n if (timing.connectEnd && timing.domInteractive) {\n return timing.domInteractive - timing.connectEnd;\n }\n });\n}\n\nexport function htmlEncode(html : string = '') : string {\n return html.toString()\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/\\//g, '/');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined') && window.location !== undefined;\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : $ReadOnlyArray {\n // $FlowFixMe[method-unbinding]\n return Array.prototype.slice.call(doc.querySelectorAll(selector));\n}\n\nexport function onClick(element : HTMLElement, handler : (Event) => void) {\n element.addEventListener('touchstart', noop);\n element.addEventListener('click', handler);\n element.addEventListener('keypress', (event : Event) => {\n // $FlowFixMe\n if (event.keyCode === KEY_CODES.ENTER || event.keyCode === KEY_CODES.SPACE) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path, reverse = false } : {| host? : string, path : string, reverse? : boolean |}) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n const url = `${ host }${ path }`;\n // $FlowFixMe[method-unbinding]\n const scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n if (reverse) {\n scripts.reverse();\n }\n\n for (const script of scripts) {\n if (!script.src) {\n continue;\n }\n\n const src = script.src.replace(/^https?:\\/\\//, '').split('?')[0];\n\n if (src === url) {\n return script;\n }\n }\n }, [ path ]);\n}\n\nexport function isLocalStorageEnabled() : boolean {\n return inlineMemoize(isLocalStorageEnabled, () => {\n try {\n if (typeof window === 'undefined') {\n return false;\n }\n\n if (window.localStorage) {\n const value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n const result = window.localStorage.getItem('__test__localStorage__');\n window.localStorage.removeItem('__test__localStorage__');\n if (value === result) {\n return true;\n }\n }\n } catch (err) {\n // pass\n }\n return false;\n });\n}\n\nexport function getBrowserLocales() : $ReadOnlyArray<{| country? : string, lang : string |}> {\n const nav = window.navigator;\n\n const locales = nav.languages\n ? [ ...nav.languages ]\n : [];\n\n if (nav.language) {\n locales.push(nav.language);\n }\n\n if (nav.userLanguage) {\n locales.push(nav.userLanguage);\n }\n\n return locales.map(locale => {\n\n if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {\n const [ lang, country ] = locale.split(/[-_]/);\n return { country, lang };\n }\n\n if (locale && locale.match(/^[a-z]{2}$/)) {\n return { lang: locale };\n }\n\n return null;\n\n }).filter(Boolean);\n}\n\n\nexport function appendChild(container : HTMLElement, child : HTMLElement | Text) {\n container.appendChild(child);\n}\n\nexport function getElementSafe(id : ElementRefType, doc : Document | HTMLElement = document) : ?HTMLElement {\n\n if (isElement(id)) {\n // $FlowFixMe\n return id;\n }\n\n if (typeof id === 'string') {\n return doc.querySelector(id);\n }\n}\n\nexport function getElement(id : ElementRefType, doc : Document | HTMLElement = document) : HTMLElement {\n\n const element = getElementSafe(id, doc);\n\n if (element) {\n return element;\n }\n\n throw new Error(`Can not find element: ${ stringify(id) }`);\n}\n\nexport function elementReady(id : ElementRefType) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const name = stringify(id);\n let el = getElementSafe(id);\n\n if (el) {\n return resolve(el);\n }\n\n if (isDocumentReady()) {\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n\n const interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n resolve(el);\n clearInterval(interval);\n return;\n }\n\n if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(`Document is ready and element ${ name } does not exist`));\n }\n }, 10);\n });\n}\n\n// eslint-disable-next-line unicorn/custom-error-definition\nexport class PopupOpenError extends ExtendableError {}\n\ntype PopupOptions = {|\n name? : string,\n width? : number,\n height? : number,\n top? : number,\n left? : number,\n status? : 0 | 1,\n resizable? : 0 | 1,\n toolbar? : 0 | 1,\n menubar? : 0 | 1,\n scrollbars? : 0 | 1,\n closeOnUnload? : 0 | 1\n|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n const { closeOnUnload = 1, name = '', width, height } = options;\n\n let top = 0;\n let left = 0;\n\n if (width) {\n if (window.outerWidth) {\n left = Math.round((window.outerWidth - width) / 2) + window.screenX;\n } else if (window.screen.width) {\n left = Math.round((window.screen.width - width) / 2);\n }\n }\n\n if (height) {\n if (window.outerHeight) {\n top = Math.round((window.outerHeight - height) / 2) + window.screenY;\n } else if (window.screen.height) {\n top = Math.round((window.screen.height - height) / 2);\n }\n }\n\n delete options.closeOnUnload;\n delete options.name;\n\n if (width && height) {\n // $FlowFixMe\n options = {\n top,\n left,\n width,\n height,\n status: 1,\n toolbar: 0,\n menubar: 0,\n resizable: 1,\n scrollbars: 1,\n ...options\n };\n }\n\n // eslint-disable-next-line array-callback-return\n const params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key] !== null && options[key] !== undefined) {\n return `${ key }=${ stringify(options[key]) }`;\n }\n }).filter(Boolean).join(',');\n\n let win;\n\n try {\n win = window.open(url, name, params);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n const err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n if (closeOnUnload) {\n window.addEventListener('unload', () => win.close());\n }\n\n return win;\n}\n\n\nexport function writeToWindow(win : SameDomainWindowType, html : string) {\n try {\n win.document.open();\n win.document.write(html);\n win.document.close();\n } catch (err) {\n try {\n win.location = `javascript: document.open(); document.write(${ JSON.stringify(html) }); document.close();`;\n } catch (err2) {\n // pass\n }\n }\n}\n\nexport function writeElementToWindow(win : SameDomainWindowType, el : HTMLElement) {\n\n const tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n const documentElement = win.document.documentElement;\n\n for (const child of arrayFrom(documentElement.children)) {\n documentElement.removeChild(child);\n }\n\n for (const child of arrayFrom(el.children)) {\n documentElement.appendChild(child);\n }\n}\n\nexport function setStyle(el : HTMLElement, styleText : string, doc : Document = window.document) {\n // $FlowFixMe\n if (el.styleSheet) {\n // $FlowFixMe\n el.styleSheet.cssText = styleText;\n } else {\n el.appendChild(doc.createTextNode(styleText));\n }\n}\n\nexport type ElementOptionsType = {|\n style? : { [ string ] : string },\n id? : string,\n class? : ?$ReadOnlyArray,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n|};\n\nlet awaitFrameLoadPromises : WeakMap>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n const promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n const promise = new ZalgoPromise((resolve, reject) => {\n frame.addEventListener('load', () => {\n linkFrameWindow(frame);\n resolve(frame);\n });\n\n frame.addEventListener('error', (err : Event) => {\n if (frame.contentWindow) {\n resolve(frame);\n } else {\n reject(err);\n }\n });\n });\n\n awaitFrameLoadPromises.set(frame, promise);\n\n return promise;\n}\n\nexport function awaitFrameWindow(frame : HTMLIFrameElement) : ZalgoPromise {\n return awaitFrameLoad(frame).then(loadedFrame => {\n\n if (!loadedFrame.contentWindow) {\n throw new Error(`Could not find window in iframe`);\n }\n\n return loadedFrame.contentWindow;\n });\n}\n\nconst getDefaultCreateElementOptions = () : ElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function createElement(tag : string = 'div', options : ElementOptionsType = getDefaultCreateElementOptions(), container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n const element = document.createElement(tag);\n\n if (options.style) {\n extend(element.style, options.style);\n }\n\n if (options.class) {\n element.className = options.class.join(' ');\n }\n\n if (options.id) {\n element.setAttribute('id', options.id);\n }\n\n if (options.attributes) {\n for (const key of Object.keys(options.attributes)) {\n element.setAttribute(key, options.attributes[key]);\n }\n }\n\n if (options.styleSheet) {\n setStyle(element, options.styleSheet);\n }\n\n if (container) {\n appendChild(container, element);\n }\n\n if (options.html) {\n if (tag === 'iframe') {\n // $FlowFixMe\n if (!container || !element.contentWindow) {\n throw new Error(`Iframe html can not be written unless container provided and iframe in DOM`);\n }\n\n // $FlowFixMe\n writeToWindow(element.contentWindow, options.html);\n\n } else {\n element.innerHTML = options.html;\n }\n }\n\n return element;\n}\n\ntype StringMap = {|\n [ string ] : string\n|};\n\nexport type IframeElementOptionsType = {|\n style? : StringMap,\n class? : ?$ReadOnlyArray,\n attributes? : StringMap,\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n|};\n\nconst getDefaultIframeOptions = () : IframeElementOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultStringMap = () : StringMap => {\n // $FlowFixMe\n return {};\n};\n\nexport function iframe(options : IframeElementOptionsType = getDefaultIframeOptions(), container : ?HTMLElement) : HTMLIFrameElement {\n\n const attributes = options.attributes || getDefaultStringMap();\n const style = options.style || getDefaultStringMap();\n\n // $FlowFixMe\n const newAttributes = {\n allowTransparency: 'true',\n ...attributes\n };\n\n // $FlowFixMe\n const newStyle = {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n };\n\n const frame = createElement('iframe', {\n attributes: newAttributes,\n style: newStyle,\n html: options.html,\n class: options.class\n });\n\n const isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n\n if (!frame.hasAttribute('id')) {\n frame.setAttribute('id', uniqueID());\n }\n\n // $FlowFixMe\n awaitFrameLoad(frame);\n\n if (container) {\n const el = getElement(container);\n el.appendChild(frame);\n }\n\n if (options.url || isIE) {\n frame.setAttribute('src', options.url || 'about:blank');\n }\n\n // $FlowFixMe\n return frame;\n}\n\nexport function addEventListener(obj : HTMLElement, event : string, handler : (event : Event) => void) : CancelableType {\n obj.addEventListener(event, handler);\n return {\n cancel() {\n obj.removeEventListener(event, handler);\n }\n };\n}\n\nexport function bindEvents(element : HTMLElement, eventNames : $ReadOnlyArray, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (const eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (const eventName of eventNames) {\n element.removeEventListener(eventName, handler);\n }\n })\n };\n}\n\nconst VENDOR_PREFIXES = [ 'webkit', 'moz', 'ms', 'o' ];\n\nexport function setVendorCSS(element : HTMLElement, name : string, value : string) {\n\n // $FlowFixMe\n element.style[name] = value;\n\n const capitalizedName = capitalizeFirstLetter(name);\n\n for (const prefix of VENDOR_PREFIXES) {\n // $FlowFixMe\n element.style[`${ prefix }${ capitalizedName }`] = value;\n }\n}\n\nconst ANIMATION_START_EVENTS = [ 'animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart' ];\nconst ANIMATION_END_EVENTS = [ 'animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd' ];\n\nexport function animate(element : ElementRefType, name : string, clean : (Function) => void, timeout : number = 1000) : ZalgoPromise {\n return new ZalgoPromise((resolve, reject) => {\n\n const el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n // eslint-disable-next-line prefer-const\n let startTimeout;\n let endTimeout;\n // eslint-disable-next-line prefer-const\n let startEvent;\n // eslint-disable-next-line prefer-const\n let endEvent;\n\n function cleanUp() {\n clearTimeout(startTimeout);\n clearTimeout(endTimeout);\n startEvent.cancel();\n endEvent.cancel();\n }\n\n startEvent = bindEvents(el, ANIMATION_START_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n clearTimeout(startTimeout);\n\n event.stopPropagation();\n\n startEvent.cancel();\n hasStarted = true;\n\n endTimeout = setTimeout(() => {\n cleanUp();\n resolve();\n }, timeout);\n });\n\n endEvent = bindEvents(el, ANIMATION_END_EVENTS, event => {\n\n // $FlowFixMe\n if (event.target !== el || event.animationName !== name) {\n return;\n }\n\n cleanUp();\n\n // $FlowFixMe\n if (typeof event.animationName === 'string' && event.animationName !== name) {\n return reject(`Expected animation name to be ${ name }, found ${ event.animationName }`);\n }\n\n return resolve();\n });\n\n setVendorCSS(el, 'animationName', name);\n\n startTimeout = setTimeout(() => {\n if (!hasStarted) {\n cleanUp();\n return resolve();\n }\n }, 200);\n\n if (clean) {\n clean(cleanUp);\n }\n });\n}\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', 'hidden', 'important');\n}\n\n\nexport function showElement(element : HTMLElement) {\n element.style.setProperty('display', '');\n}\n\nexport function hideElement(element : HTMLElement) {\n element.style.setProperty('display', 'none', 'important');\n}\n\nexport function destroyElement(element : HTMLElement) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n}\n\nexport function showAndAnimate(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n const animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise {\n return animate(element, name, clean).then(() => {\n hideElement(element);\n });\n}\n\nexport function addClass(element : HTMLElement, name : string) {\n element.classList.add(name);\n}\n\nexport function removeClass(element : HTMLElement, name : string) {\n element.classList.remove(name);\n}\n\nexport function isElementClosed(el : HTMLElement) : boolean {\n if (!el || !el.parentNode || !el.ownerDocument || !el.ownerDocument.documentElement || !el.ownerDocument.documentElement.contains(el)) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let cancelled = false;\n const mutationObservers = [];\n // eslint-disable-next-line prefer-const\n let interval;\n // eslint-disable-next-line prefer-const\n let sacrificialFrame;\n let sacrificialFrameWin;\n\n const cancel = () => {\n cancelled = true;\n for (const observer of mutationObservers) {\n observer.disconnect();\n }\n if (interval) {\n interval.cancel();\n }\n if (sacrificialFrameWin) {\n // eslint-disable-next-line no-use-before-define\n sacrificialFrameWin.removeEventListener('unload', elementClosed);\n }\n if (sacrificialFrame) {\n destroyElement(sacrificialFrame);\n }\n };\n\n const elementClosed = () => {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n\n if (isElementClosed(element)) {\n elementClosed();\n return { cancel };\n }\n\n // Strategy 1: Mutation observer\n\n if (window.MutationObserver) {\n let mutationElement = element.parentElement;\n while (mutationElement) {\n const mutationObserver = new window.MutationObserver(() => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n });\n\n mutationObserver.observe(mutationElement, { childList: true });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n\n // Strategy 2: Sacrificial iframe\n\n sacrificialFrame = document.createElement('iframe');\n sacrificialFrame.setAttribute('name', `__detect_close_${ uniqueID() }__`);\n sacrificialFrame.style.display = 'none';\n awaitFrameWindow(sacrificialFrame).then(frameWin => {\n sacrificialFrameWin = assertSameDomain(frameWin);\n sacrificialFrameWin.addEventListener('unload', elementClosed);\n });\n element.appendChild(sacrificialFrame);\n\n // Strategy 3: Poller\n\n const check = () => {\n if (isElementClosed(element)) {\n elementClosed();\n }\n };\n interval = safeInterval(check, 1000);\n\n return { cancel };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (const script of querySelectorAll('script', el)) {\n const parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n const newScript = doc.createElement('script');\n newScript.text = script.textContent;\n parentNode.replaceChild(newScript, script);\n }\n}\n\ntype OnResizeOptions = {|\n width? : boolean,\n height? : boolean,\n interval? : number,\n win? : SameDomainWindowType\n|};\n\nexport function onResize(el : HTMLElement, handler : ({| width : number, height : number |}) => void, { width = true, height = true, interval = 100, win = window } : OnResizeOptions = {}) : {| cancel : () => void |} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n let canceled = false;\n\n handler({ width: currentWidth, height: currentHeight });\n\n const check = () => {\n if (canceled || !isElementVisible(el)) {\n return;\n }\n\n const newWidth = el.offsetWidth;\n const newHeight = el.offsetHeight;\n\n if ((width && newWidth !== currentWidth) || (height && newHeight !== currentHeight)) {\n handler({ width: newWidth, height: newHeight });\n }\n\n currentWidth = newWidth;\n currentHeight = newHeight;\n };\n\n let observer;\n let timeout;\n\n win.addEventListener('resize', check);\n\n if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\n timeout = safeInterval(check, interval * 10);\n\n } else if (typeof win.MutationObserver !== 'undefined') {\n observer = new win.MutationObserver(check);\n observer.observe(el, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: false\n });\n timeout = safeInterval(check, interval * 10);\n } else {\n timeout = safeInterval(check, interval);\n }\n\n return {\n cancel: () => {\n canceled = true;\n observer.disconnect();\n window.removeEventListener('resize', check);\n timeout.cancel();\n }\n };\n}\n\nexport function getResourceLoadTime(url : string) : ?number {\n const performance = getPerformance();\n\n if (!performance) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n if (typeof performance.getEntries !== 'function') {\n return;\n }\n\n const entries = performance.getEntries();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n\n if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {\n return Math.floor(entry.duration);\n }\n }\n}\n\nexport function isShadowElement(element : Node) : boolean {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n return element.toString() === '[object ShadowRoot]';\n}\n\nexport function getShadowRoot(element : Node) : ?Node {\n while (element.parentNode) {\n element = element.parentNode;\n }\n\n if (isShadowElement(element)) {\n return element;\n }\n}\n\nexport function getShadowHost(element : Node) : ?HTMLElement {\n const shadowRoot = getShadowRoot(element);\n\n // $FlowFixMe\n if (shadowRoot && shadowRoot.host) {\n // $FlowFixMe\n return shadowRoot.host;\n }\n}\n\n\nexport function insertShadowSlot(element : HTMLElement) : HTMLElement {\n const shadowHost = getShadowHost(element);\n\n if (!shadowHost) {\n throw new Error(`Element is not in shadow dom`);\n }\n\n const slotName = `shadow-slot-${ uniqueID() }`;\n const slot = document.createElement('slot');\n slot.setAttribute('name', slotName);\n element.appendChild(slot);\n\n const slotProvider = document.createElement('div');\n slotProvider.setAttribute('slot', slotName);\n shadowHost.appendChild(slotProvider);\n\n if (isShadowElement(shadowHost)) {\n return insertShadowSlot(slotProvider);\n }\n\n return slotProvider;\n}\n\nexport function preventClickFocus(el : HTMLElement) {\n const onFocus = (event : Event) => {\n el.removeEventListener('focus', onFocus);\n event.preventDefault();\n el.blur();\n return false;\n };\n\n el.addEventListener('mousedown', () => {\n el.addEventListener('focus', onFocus);\n setTimeout(() => {\n el.removeEventListener('focus', onFocus);\n }, 1);\n });\n}\n\nexport function getStackTrace() : string {\n try {\n throw new Error('_');\n }\n catch (err) {\n return err.stack || '';\n }\n}\n\nfunction inferCurrentScript() : ?HTMLScriptElement {\n try {\n const stack = getStackTrace();\n const stackDetails = (/.*at [^(]*\\((.*):(.+):(.+)\\)$/ig).exec(stack);\n const scriptLocation = stackDetails && stackDetails[1];\n\n if (!scriptLocation) {\n return;\n }\n\n // $FlowFixMe[method-unbinding]\n for (const script of Array.prototype.slice.call(document.getElementsByTagName('script')).reverse()) {\n if (script.src && script.src === scriptLocation) {\n return script;\n }\n }\n\n } catch (err) {\n // pass\n }\n}\n\n// eslint-disable-next-line compat/compat\nlet currentScript = typeof document !== 'undefined' ? document.currentScript : null;\n\ntype GetCurrentScript = () => HTMLScriptElement;\n\nexport const getCurrentScript : GetCurrentScript = memoize(() => {\n if (currentScript) {\n return currentScript;\n }\n\n currentScript = inferCurrentScript();\n\n if (currentScript) {\n return currentScript;\n }\n\n throw new Error('Can not determine current script');\n});\n\nconst currentUID = uniqueID();\n\ntype GetCurrentScriptUID = () => string;\n\nexport const getCurrentScriptUID : GetCurrentScriptUID = memoize(() => {\n let script;\n\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n\n let uid = script.getAttribute(ATTRIBUTES.UID);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n uid = script.getAttribute(`${ ATTRIBUTES.UID }-auto`);\n\n if (uid && typeof uid === 'string') {\n return uid;\n }\n\n if (script.src) {\n\n const { src, dataset } = script;\n const stringToHash = JSON.stringify({ src, dataset });\n const hashedString = strHashStr(stringToHash);\n const hashResult = hashedString.slice(hashedString.length - UID_HASH_LENGTH);\n\n uid = `uid_${ hashResult }`;\n } else {\n uid = uniqueID();\n }\n\n script.setAttribute(`${ ATTRIBUTES.UID }-auto`, uid);\n\n return uid;\n});\n\ntype SubmitFormOptions = {|\n url : string,\n target : string,\n body? : {| [string] : string | boolean |},\n method? : string\n|};\n\nexport function submitForm({ url, target, body, method = 'post' } : SubmitFormOptions) {\n const form = document.createElement('form');\n form.setAttribute('target', target);\n form.setAttribute('method', method);\n form.setAttribute('action', url);\n form.style.display = 'none';\n\n if (body) {\n for (const key of Object.keys(body)) {\n const input = document.createElement('input');\n input.setAttribute('name', key);\n input.setAttribute('value', body[key]?.toString());\n form.appendChild(input);\n }\n }\n\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n}\n","/* @flow */\n\nexport function isPerc(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+%$/).test(str);\n}\n\nexport function isPx(str : string) : boolean {\n return typeof str === 'string' && (/^[0-9]+px$/).test(str);\n}\n\nexport function toNum(val : string | number) : number {\n\n if (typeof val === 'number') {\n return val;\n }\n\n const match = val.match(/^([0-9]+)(px|%)$/);\n\n if (!match) {\n throw new Error(`Could not match css value from ${ val }`);\n }\n\n return parseInt(match[1], 10);\n}\n\nexport function toPx(val : number | string) : string {\n return `${ toNum(val) }px`;\n}\n\nexport function toCSS(val : number | string) : string {\n\n if (typeof val === 'number') {\n return toPx(val);\n }\n\n return isPerc(val) ? val : toPx(val);\n}\n\nexport function percOf(num : number, perc : string) : number {\n return parseInt(num * toNum(perc) / 100, 10);\n}\n\nexport function normalizeDimension(dim : string | number, max : number) : number {\n if (typeof dim === 'number') {\n return dim;\n } else if (isPerc(dim)) {\n return percOf(max, dim);\n } else if (isPx(dim)) {\n return toNum(dim);\n } else {\n throw new Error(`Can not normalize dimension: ${ dim }`);\n }\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet, getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__POST_ROBOT__.__SCRIPT_NAMESPACE__) {\n return `${ __POST_ROBOT__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __POST_ROBOT__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n const globalKey = getGlobalKey();\n\n if (win !== window) {\n return win[globalKey];\n }\n const global : Object = win[globalKey] = win[globalKey] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore = {|\n get : ((string, T) => T) & ((string, void) => T | void),\n set : (string, T) => T,\n has : (string) => boolean,\n del : (string) => void,\n getOrSet : GetOrSet,\n reset : () => void,\n keys : () => $ReadOnlyArray\n|};\n\nexport function globalStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore {\n return getOrSet(getGlobal(), key, () => {\n let store = defStore();\n\n return {\n has: (storeKey) => {\n return store.hasOwnProperty(storeKey);\n },\n get: (storeKey, defVal) => {\n // $FlowFixMe\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: (storeKey, val) => {\n store[storeKey] = val;\n return val;\n },\n del: (storeKey) => {\n delete store[storeKey];\n },\n getOrSet: (storeKey, getter) => {\n // $FlowFixMe\n return getOrSet(store, storeKey, getter);\n },\n reset: () => {\n store = defStore();\n },\n keys: () => {\n return Object.keys(store);\n }\n };\n });\n}\n\nexport class WildCard {}\n\nexport function getWildcard() : WildCard {\n const global = getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();\n return global.WINDOW_WILDCARD;\n}\n\ntype WindowStore = {|\n get : ((CrossDomainWindowType | WildCard, T) => T) & ((CrossDomainWindowType | WildCard, void) => T | void),\n set : (CrossDomainWindowType | WildCard, T) => T,\n has : (CrossDomainWindowType | WildCard) => boolean,\n del : (CrossDomainWindowType | WildCard) => void,\n getOrSet : (CrossDomainWindowType | WildCard, () => T) => T\n|};\n\nexport function windowStore(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore {\n return globalStore('windowStore').getOrSet(key, () => {\n const winStore = new WeakMap();\n\n const getStore = (win : CrossDomainWindowType | WildCard) : ObjectGetter => {\n return winStore.getOrSet(win, defStore);\n };\n \n return {\n has: (win) => {\n const store = getStore(win);\n return store.hasOwnProperty(key);\n },\n get: (win, defVal) => {\n const store = getStore(win);\n // $FlowFixMe\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: (win, val) => {\n const store = getStore(win);\n store[key] = val;\n return val;\n },\n del: (win) => {\n const store = getStore(win);\n delete store[key];\n },\n getOrSet: (win, getter) => {\n const store = getStore(win);\n return getOrSet(store, key, getter);\n }\n };\n });\n}\n","/* @flow */\n\nexport const KEY_CODES = {\n ENTER: 13,\n SPACE: 32\n};\n\nexport const ATTRIBUTES = {\n UID: 'data-uid'\n};\n\nexport const UID_HASH_LENGTH = 30;\n","/* @flow */\n\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore, getGlobal } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nfunction getInstanceID() : string {\n return globalStore('instance').getOrSet('instanceID', uniqueID);\n}\n\nfunction getHelloPromise(win : CrossDomainWindowType) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction resolveHelloPromise(win : CrossDomainWindowType, { domain }) : ZalgoPromise<{| domain : string |}> {\n const helloPromises = windowStore('helloPromises');\n const existingPromise = helloPromises.get(win);\n if (existingPromise) {\n existingPromise.resolve({ domain });\n }\n const newPromise = ZalgoPromise.resolve({ domain });\n helloPromises.set(win, newPromise);\n return newPromise;\n}\n\nfunction listenForHello({ on } : {| on : OnType |}) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n resolveHelloPromise(source, { domain: origin });\n return { instanceID: getInstanceID() };\n });\n}\n\nexport function sayHello(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise<{| win : CrossDomainWindowType, domain : string, instanceID : string |}> {\n return send(win, MESSAGE_NAME.HELLO, { instanceID: getInstanceID() }, { domain: WILDCARD, timeout: -1 })\n .then(({ origin, data: { instanceID } }) => {\n resolveHelloPromise(win, { domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return windowStore('windowInstanceIDPromises').getOrSet(win, () => {\n return sayHello(win, { send }).then(({ instanceID }) => instanceID);\n });\n}\n\nexport function initHello({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('helloListener', () => {\n const listener = listenForHello({ on });\n\n const parent = getAncestor();\n if (parent) {\n sayHello(parent, { send }).catch(err => {\n // $FlowFixMe\n if (__TEST__ && getGlobal(parent)) {\n throw err;\n }\n });\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{| domain : string |}> {\n let promise = getHelloPromise(win);\n\n if (timeout !== -1) {\n promise = promise.timeout(timeout, new Error(`${ name } did not load after ${ timeout }ms`));\n }\n\n return promise;\n}\n","/* @flow */\n\nexport const MESSAGE_TYPE = {\n REQUEST: ('postrobot_message_request' : 'postrobot_message_request'),\n RESPONSE: ('postrobot_message_response' : 'postrobot_message_response'),\n ACK: ('postrobot_message_ack' : 'postrobot_message_ack')\n};\n\nexport const MESSAGE_ACK = {\n SUCCESS: ('success' : 'success'),\n ERROR: ('error' : 'error')\n};\n\nexport const MESSAGE_NAME = {\n METHOD: ('postrobot_method' : 'postrobot_method'),\n HELLO: ('postrobot_hello' : 'postrobot_hello'),\n OPEN_TUNNEL: ('postrobot_open_tunnel' : 'postrobot_open_tunnel')\n};\n\nexport const SEND_STRATEGY = {\n POST_MESSAGE: ('postrobot_post_message' : 'postrobot_post_message'),\n BRIDGE: ('postrobot_bridge' : 'postrobot_bridge'),\n GLOBAL: ('postrobot_global' : 'postrobot_global')\n};\n\nexport const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';\nexport const POSTROBOT_PROXY = '__postrobot_proxy__';\n\nexport const WILDCARD = '*';\n\nexport const SERIALIZATION_TYPE = {\n CROSS_DOMAIN_ZALGO_PROMISE: ('cross_domain_zalgo_promise' : 'cross_domain_zalgo_promise'),\n CROSS_DOMAIN_FUNCTION: ('cross_domain_function' : 'cross_domain_function'),\n CROSS_DOMAIN_WINDOW: ('cross_domain_window' : 'cross_domain_window')\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { windowStore } from '../global';\n\nexport function markWindowKnown(win : CrossDomainWindowType) {\n const knownWindows = windowStore('knownWindows');\n knownWindows.set(win, true);\n}\n\nexport function isWindowKnown(win : CrossDomainWindowType) : boolean {\n const knownWindows = windowStore('knownWindows');\n return knownWindows.get(win, false);\n}\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { CustomSerializedType } from './types';\n\nexport function isSerializedType(item : mixed) : boolean {\n return (typeof item === 'object' && item !== null && typeof item.__type__ === 'string');\n}\n\nexport function determineType(val : mixed) : $Values | void {\n if (typeof val === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n if (val === null) {\n return TYPE.NULL;\n }\n\n if (Array.isArray(val)) {\n return TYPE.ARRAY;\n }\n\n if (typeof val === 'function') {\n return TYPE.FUNCTION;\n }\n\n if (typeof val === 'object') {\n\n if (val instanceof Error) {\n return TYPE.ERROR;\n }\n\n if (typeof val.then === 'function') {\n return TYPE.PROMISE;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\n // $FlowFixMe method-unbinding\n if (Object.prototype.toString.call(val) === '[object Date]') {\n return TYPE.DATE;\n }\n\n return TYPE.OBJECT;\n }\n\n if (typeof val === 'string') {\n return TYPE.STRING;\n }\n\n if (typeof val === 'number') {\n return TYPE.NUMBER;\n }\n\n if (typeof val === 'boolean') {\n return TYPE.BOOLEAN;\n }\n}\n\nexport function serializeType(type : T, val : V) : CustomSerializedType {\n return {\n __type__: type,\n __val__: val\n };\n}\n","/* @flow */\n\nexport const TYPE = {\n FUNCTION: ('function' : 'function'),\n ERROR: ('error' : 'error'),\n PROMISE: ('promise' : 'promise'),\n REGEX: ('regex' : 'regex'),\n DATE: ('date' : 'date'),\n ARRAY: ('array' : 'array'),\n OBJECT: ('object' : 'object'),\n STRING: ('string' : 'string'),\n NUMBER: ('number' : 'number'),\n BOOLEAN: ('boolean' : 'boolean'),\n NULL: ('null' : 'null'),\n UNDEFINED: ('undefined' : 'undefined')\n};\n","/* @flow */\n\nimport { TYPE } from './constants';\nimport type { Thenable, CustomSerializedType, NativeSerializedType } from './types';\nimport { determineType, isSerializedType } from './common';\nimport {\n serializeFunction,\n serializeError, type SerializedError,\n serializePromise,\n serializeRegex, type SerializedRegex,\n serializeDate, type SerializedDate,\n serializeArray,\n serializeObject,\n serializeString,\n serializeNumber,\n serializeBoolean,\n serializeNull,\n serializeUndefined\n} from './serializers';\n\ntype NativeSerializer> = (value : V, key : string) => NativeSerializedType;\ntype CustomSerializer = (value : V, key : string) => CustomSerializedType;\ntype PrimitiveSerializer = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer = CustomSerializer | PrimitiveSerializer;\ntype NativeOrCustomOrPrimitiveSerializer = NativeSerializer | CustomOrPrimitiveSerializer;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer,\n error? : NativeOrCustomOrPrimitiveSerializer,\n promise? : CustomOrPrimitiveSerializer,\n regex? : NativeOrCustomOrPrimitiveSerializer,\n date? : NativeOrCustomOrPrimitiveSerializer,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer,\n string? : CustomOrPrimitiveSerializer,\n number? : CustomOrPrimitiveSerializer,\n boolean? : CustomOrPrimitiveSerializer,\n null? : CustomOrPrimitiveSerializer,\n undefined? : CustomOrPrimitiveSerializer\n|};\n\nconst SERIALIZER : Serializers = {\n [ TYPE.FUNCTION ]: serializeFunction,\n [ TYPE.ERROR ]: serializeError,\n [ TYPE.PROMISE ]: serializePromise,\n [ TYPE.REGEX ]: serializeRegex,\n [ TYPE.DATE ]: serializeDate,\n [ TYPE.ARRAY ]: serializeArray,\n [ TYPE.OBJECT ]: serializeObject,\n [ TYPE.STRING ]: serializeString,\n [ TYPE.NUMBER ]: serializeNumber,\n [ TYPE.BOOLEAN ]: serializeBoolean,\n [ TYPE.NULL ]: serializeNull,\n [ TYPE.UNDEFINED ]: serializeUndefined\n};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize(obj : T, serializers : Serializers = defaultSerializers) : string {\n\n function replacer(key) : ?mixed {\n const val = this[key];\n\n if (isSerializedType(this)) {\n return val;\n }\n \n const type = determineType(val);\n\n if (!type) {\n return val;\n }\n\n // $FlowFixMe\n const serializer = serializers[type] || SERIALIZER[type];\n\n if (!serializer) {\n return val;\n }\n\n return serializer(val, key);\n }\n\n const result = JSON.stringify(obj, replacer);\n\n if (typeof result === 'undefined') {\n return TYPE.UNDEFINED;\n }\n\n return result;\n}\n","/* @flow */\n\nexport type SerializedFunction = void;\n\nexport function serializeFunction() : SerializedFunction {\n // pass\n}\n\nexport function deserializeFunction() {\n throw new Error(`Function serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nimport { serializeObject } from './object';\n\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void,\n data : mixed\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code, data } : Error) : NativeSerializedType {\n return serializeType(TYPE.ERROR, { message, stack, code, data });\n}\n\nexport function deserializeError({ message, stack, code, data } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n\n if (data) {\n // $FlowFixMe\n error.data = serializeObject(data);\n }\n\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nimport type { Thenable } from '../types';\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() : Thenable {\n throw new Error(`Promise serialization is not implemented; nothing to deserialize`);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedRegex = string;\n\nexport function serializeRegex(val : RegExp) : NativeSerializedType {\n return serializeType(TYPE.REGEX, val.source);\n}\n\nexport function deserializeRegex(val : string) : RegExp {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp(val);\n}\n","/* @flow */\n\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\nimport type { NativeSerializedType } from '../types';\n\nexport type SerializedDate = string;\n\nexport function serializeDate(val : Date) : NativeSerializedType {\n return serializeType(TYPE.DATE, val.toJSON());\n}\n\nexport function deserializeDate(val : string) : Date {\n return new Date(val);\n}\n","/* @flow */\n\nexport type SerializedArray = $ReadOnlyArray;\n\nexport function serializeArray(val : $ReadOnlyArray) : SerializedArray {\n return val;\n}\n\nexport function deserializeArray(val : SerializedArray) : $ReadOnlyArray {\n return val;\n}\n","/* @flow */\n\nexport type SerializedObject = Object;\n\nexport function serializeObject(val : Object) : SerializedObject {\n return val;\n}\n\nexport function deserializeObject(val : SerializedObject) : Object {\n return val;\n}\n","/* @flow */\n\nexport type SerializedString = string;\n\nexport function serializeString(val : string) : SerializedString {\n return val;\n}\n\nexport function deserializeString(val : SerializedString) : string {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNumber = number;\n\nexport function serializeNumber(val : number) : SerializedNumber {\n return val;\n}\n\nexport function deserializeNumber(val : SerializedNumber) : number {\n return val;\n}\n","/* @flow */\n\nexport type SerializedBoolean = boolean;\n\nexport function serializeBoolean(val : boolean) : SerializedBoolean {\n return val;\n}\n\nexport function deserializeBoolean(val : SerializedBoolean) : boolean {\n return val;\n}\n","/* @flow */\n\nexport type SerializedNull = null;\n\nexport function serializeNull(val : null) : SerializedNull {\n return val;\n}\n\nexport function deserializeNull(val : SerializedNull) : null {\n return val;\n}\n","/* @flow */\n\nimport type { NativeSerializedType } from '../types';\nimport { serializeType } from '../common';\nimport { TYPE } from '../constants';\n\nexport type SerializedUndefined = void;\n\nexport function serializeUndefined(val : void) : NativeSerializedType {\n return serializeType(TYPE.UNDEFINED, val);\n}\n\nexport function deserializeUndefined() : void {\n // pass\n}\n","/* @flow */\n\nimport type { Thenable } from './types';\nimport { TYPE } from './constants';\nimport { determineType, isSerializedType } from './common';\nimport {\n deserializeFunction,\n deserializeError, type SerializedError,\n deserializePromise,\n deserializeRegex, type SerializedRegex,\n deserializeDate, type SerializedDate,\n deserializeArray,\n deserializeObject,\n deserializeString,\n deserializeNumber,\n deserializeBoolean,\n deserializeNull,\n deserializeUndefined\n} from './serializers';\n\ntype Deserializer = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer,\n error? : Deserializer,\n promise? : Deserializer,\n regex? : Deserializer,\n date? : Deserializer,\n array? : PrimitiveDeserializer<$ReadOnlyArray>,\n object? : PrimitiveDeserializer,\n string? : PrimitiveDeserializer,\n number? : PrimitiveDeserializer,\n boolean? : PrimitiveDeserializer,\n null? : PrimitiveDeserializer,\n [string] : Deserializer,\n undefined? : PrimitiveDeserializer\n};\n\n// $FlowFixMe\nconst DESERIALIZER : Deserializers = {\n [ TYPE.FUNCTION ]: deserializeFunction,\n [ TYPE.ERROR ]: deserializeError,\n [ TYPE.PROMISE ]: deserializePromise,\n [ TYPE.REGEX ]: deserializeRegex,\n [ TYPE.DATE ]: deserializeDate,\n [ TYPE.ARRAY ]: deserializeArray,\n [ TYPE.OBJECT ]: deserializeObject,\n [ TYPE.STRING ]: deserializeString,\n [ TYPE.NUMBER ]: deserializeNumber,\n [ TYPE.BOOLEAN ]: deserializeBoolean,\n [ TYPE.NULL ]: deserializeNull,\n [ TYPE.UNDEFINED ]: deserializeUndefined\n};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize(str : string, deserializers : Deserializers = defaultDeserializers) : T {\n if (str === TYPE.UNDEFINED) {\n // $FlowFixMe\n return;\n }\n\n function replacer(key, val) : ?mixed {\n if (isSerializedType(this)) {\n return val;\n }\n\n let type;\n let value;\n\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n\n if (!type) {\n return value;\n }\n\n // $FlowFixMe\n const deserializer = deserializers[type] || DESERIALIZER[type];\n\n if (!deserializer) {\n return value;\n }\n\n return deserializer(value, key);\n }\n\n return JSON.parse(str, replacer);\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isSameDomain, isOpener, isSameTopWindow, matchDomain, getUserAgent, getDomainFromUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { BRIDGE_NAME_PREFIX } from '../conf';\nimport { windowStore } from '../global';\n\nexport function needsBridgeForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForWin(win : CrossDomainWindowType) : boolean {\n\n if (!isSameTopWindow(window, win)) {\n return true;\n }\n\n return false;\n}\n\nexport function needsBridgeForDomain(domain : ?string, win : ?CrossDomainWindowType) : boolean {\n\n if (domain) {\n if (getDomain() !== getDomainFromUrl(domain)) {\n return true;\n }\n } else if (win) {\n if (!isSameDomain(win)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function needsBridge({ win, domain } : {| win? : CrossDomainWindowType, domain? : string |}) : boolean {\n\n if (!needsBridgeForBrowser()) {\n return false;\n }\n\n if (domain && !needsBridgeForDomain(domain, win)) {\n return false;\n }\n\n if (win && !needsBridgeForWin(win)) {\n return false;\n }\n\n return true;\n}\n\nexport function getBridgeName(domain : string) : string {\n\n domain = domain || getDomainFromUrl(domain);\n\n const sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');\n\n const id = `${ BRIDGE_NAME_PREFIX }_${ sanitizedDomain }`;\n\n return id;\n}\n\nexport function isBridge() : boolean {\n return Boolean(window.name && window.name === getBridgeName(getDomain()));\n}\n\nexport const documentBodyReady : ZalgoPromise = new ZalgoPromise(resolve => {\n\n if (window.document && window.document.body) {\n return resolve(window.document.body);\n }\n\n const interval = setInterval(() => {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }, 10);\n});\n\nexport function registerRemoteWindow(win : CrossDomainWindowType) {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n remoteWindowPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nexport function findRemoteWindow(win : CrossDomainWindowType) : ZalgoPromise<(remoteWin : CrossDomainWindowType, message : string, remoteDomain : string) => void> {\n const remoteWindowPromises = windowStore('remoteWindowPromises');\n const remoteWinPromise = remoteWindowPromises.get(win);\n\n if (!remoteWinPromise) {\n throw new Error(`Remote window promise not found`);\n }\n\n return remoteWinPromise;\n}\n\ntype SendMessageType = {|\n (string) : void,\n fireAndForget : (string) => void\n|};\n\nexport function registerRemoteSendMessage(win : CrossDomainWindowType, domain : string, sendMessage : SendMessageType) {\n const sendMessageWrapper = (remoteWin : CrossDomainWindowType, remoteDomain : string, message : string) => {\n if (remoteWin !== win) {\n throw new Error(`Remote window does not match window`);\n }\n\n if (!matchDomain(remoteDomain, domain)) {\n throw new Error(`Remote domain ${ remoteDomain } does not match domain ${ domain }`);\n }\n\n sendMessage.fireAndForget(message);\n };\n\n findRemoteWindow(win).resolve(sendMessageWrapper);\n}\n\nexport function rejectRemoteSendMessage(win : CrossDomainWindowType, err : Error) {\n findRemoteWindow(win).reject(err).catch(noop);\n}\n\nexport function sendBridgeMessage(win : CrossDomainWindowType, domain : string, message : string) : ZalgoPromise {\n\n const messagingChild = isOpener(window, win);\n const messagingParent = isOpener(win, window);\n\n if (!messagingChild && !messagingParent) {\n throw new Error(`Can only send messages to and from parent and popup windows`);\n }\n\n return findRemoteWindow(win).then(sendMessage => {\n return sendMessage(win, domain, message);\n });\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, getFrameByName, isWindowClosed, getDomainFromUrl, normalizeMockUrl, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport { BRIDGE_TIMEOUT, MESSAGE_NAME } from '../conf';\nimport { awaitWindowHello } from '../lib';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { getBridgeName, documentBodyReady, registerRemoteSendMessage, registerRemoteWindow } from './common';\n\ntype WinDetails = {|\n win : CrossDomainWindowType,\n domain? : ?string,\n name? : ?string\n|};\n\nexport function listenForOpenTunnel({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n const popupWindowsByName = globalStore('popupWindowsByName');\n\n on(MESSAGE_NAME.OPEN_TUNNEL, ({ source, origin, data }) => {\n const bridgePromise = globalStore('bridges').get(origin);\n\n if (!bridgePromise) {\n throw new Error(`Can not find bridge promise for domain ${ origin }`);\n }\n\n return bridgePromise.then(bridge => {\n if (source !== bridge) {\n throw new Error(`Message source does not matched registered bridge for domain ${ origin }`);\n }\n\n if (!data.name) {\n throw new Error(`Register window expected to be passed window name`);\n }\n\n if (!data.sendMessage) {\n throw new Error(`Register window expected to be passed sendMessage method`);\n }\n\n if (!popupWindowsByName.has(data.name)) {\n throw new Error(`Window with name ${ data.name } does not exist, or was not opened by this window`);\n }\n\n const getWindowDetails = () : WinDetails => {\n const winDetails = popupWindowsByName.get(data.name);\n // $FlowFixMe\n return winDetails;\n };\n\n if (!getWindowDetails().domain) {\n throw new Error(`We do not have a registered domain for window ${ data.name }`);\n }\n\n if (getWindowDetails().domain !== origin) {\n throw new Error(`Message origin ${ origin } does not matched registered window origin ${ getWindowDetails().domain || 'unknown' }`);\n }\n\n registerRemoteSendMessage(getWindowDetails().win, origin, data.sendMessage);\n\n return {\n sendMessage(message) {\n\n if (!window || window.closed) {\n return;\n }\n\n if (!getWindowDetails()) {\n return;\n }\n\n const domain = getWindowDetails().domain;\n\n if (!domain) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n origin: domain,\n source: getWindowDetails().win\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n };\n });\n });\n}\n\nfunction openBridgeFrame(name : string, url : string) : HTMLIFrameElement {\n\n const iframe = document.createElement(`iframe`);\n\n iframe.setAttribute(`name`, name);\n iframe.setAttribute(`id`, name);\n\n iframe.setAttribute(`style`, `display: none; margin: 0; padding: 0; border: 0px none; overflow: hidden;`);\n iframe.setAttribute(`frameborder`, `0`);\n iframe.setAttribute(`border`, `0`);\n iframe.setAttribute(`scrolling`, `no`);\n iframe.setAttribute(`allowTransparency`, `true`);\n\n iframe.setAttribute(`tabindex`, `-1`);\n iframe.setAttribute(`hidden`, `true`);\n iframe.setAttribute(`title`, ``);\n iframe.setAttribute(`role`, `presentation`);\n\n iframe.src = url;\n\n return iframe;\n}\n\nexport function hasBridge(url : string, domain : string) : boolean {\n const bridges = globalStore('bridges');\n return bridges.has(domain || getDomainFromUrl(url));\n}\n\nexport function openBridge(url : string, domain : string) : ZalgoPromise {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n \n domain = domain || getDomainFromUrl(url);\n \n return bridges.getOrSet(domain, () => ZalgoPromise.try(() => {\n\n if (getDomain() === domain) {\n throw new Error(`Can not open bridge on the same domain as current domain: ${ domain }`);\n }\n\n const name = getBridgeName(domain);\n const frame = getFrameByName(window, name);\n\n if (frame) {\n throw new Error(`Frame with name ${ name } already exists on page`);\n }\n\n const iframe = openBridgeFrame(name, url);\n bridgeFrames.set(domain, iframe);\n\n return documentBodyReady.then(body => {\n\n body.appendChild(iframe);\n const bridge = iframe.contentWindow;\n\n return new ZalgoPromise((resolve, reject) => {\n\n iframe.addEventListener('load', resolve);\n iframe.addEventListener('error', reject);\n\n }).then(() => {\n\n return awaitWindowHello(bridge, BRIDGE_TIMEOUT, `Bridge ${ url }`);\n\n }).then(() => {\n\n return bridge;\n });\n });\n }));\n}\n\nexport function linkWindow({ win, name, domain } : WinDetails) : WinDetails {\n const popupWindowsByName = globalStore('popupWindowsByName');\n const popupWindowsByWin = windowStore('popupWindowsByWin');\n\n for (const winName of popupWindowsByName.keys()) {\n const details = popupWindowsByName.get(winName);\n if (!details || isWindowClosed(details.win)) {\n popupWindowsByName.del(winName);\n }\n }\n\n if (isWindowClosed(win)) {\n return { win, name, domain };\n }\n\n const details = popupWindowsByWin.getOrSet(win, () : WinDetails => {\n if (!name) {\n return { win };\n }\n \n // $FlowFixMe\n return popupWindowsByName.getOrSet(name, () : WinDetails => {\n return { win, name };\n });\n });\n\n if (details.win && details.win !== win) {\n throw new Error(`Different window already linked for window: ${ name || 'undefined' }`);\n }\n\n if (name) {\n details.name = name;\n popupWindowsByName.set(name, details);\n }\n\n if (domain) {\n details.domain = domain;\n registerRemoteWindow(win);\n }\n\n popupWindowsByWin.set(win, details);\n \n return details;\n}\n\nexport function linkUrl(win : CrossDomainWindowType, url : string) {\n linkWindow({ win, domain: getDomainFromUrl(url) });\n}\n\nexport function listenForWindowOpen() {\n const windowOpen = window.open;\n\n window.open = function windowOpenWrapper(url : string, name : string, options : string, last : mixed) : mixed {\n const win = windowOpen.call(this, normalizeMockUrl(url), name, options, last);\n \n if (!win) {\n return win;\n }\n \n linkWindow({ win, name, domain: url ? getDomainFromUrl(url) : null });\n \n return win;\n };\n}\n\nexport function destroyBridges() {\n const bridges = globalStore('bridges');\n const bridgeFrames = globalStore('bridgeFrames');\n\n for (const domain of bridgeFrames.keys()) {\n const frame = bridgeFrames.get(domain);\n if (frame && frame.parentNode) {\n frame.parentNode.removeChild(frame);\n }\n }\n bridgeFrames.reset();\n bridges.reset();\n}\n","/* @flow */\n\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { listenForWindowOpen, listenForOpenTunnel } from './parent';\nimport { setupOpenTunnelToParent } from './bridge';\nimport { openTunnelToOpener } from './child';\n\nexport function setupBridge({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) {\n listenForWindowOpen();\n listenForOpenTunnel({ on, send, receiveMessage });\n setupOpenTunnelToParent({ send });\n openTunnelToOpener({ on, send, receiveMessage });\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { getParent, isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { getGlobal, globalStore } from '../global';\nimport type { SendType, ResponseMessageEvent } from '../types';\n\nfunction cleanTunnelWindows() {\n const tunnelWindows = globalStore('tunnelWindows');\n\n for (const key of tunnelWindows.keys()) {\n const tunnelWindow = tunnelWindows[key];\n\n try {\n noop(tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(key);\n continue;\n }\n\n if (isWindowClosed(tunnelWindow.source)) {\n tunnelWindows.del(key);\n }\n }\n}\n\ntype TunnelWindowDataType = {|\n name : string,\n source : CrossDomainWindowType,\n canary : () => void,\n sendMessage : (message : string) => void\n|};\n\nfunction addTunnelWindow({ name, source, canary, sendMessage } : TunnelWindowDataType) : string {\n cleanTunnelWindows();\n const id = uniqueID();\n const tunnelWindows = globalStore('tunnelWindows');\n tunnelWindows.set(id, { name, source, canary, sendMessage });\n return id;\n}\n\nexport function setupOpenTunnelToParent({ send } : {| send : SendType |}) {\n getGlobal(window).openTunnelToParent = function openTunnelToParent({ name, source, canary, sendMessage } : TunnelWindowDataType) : ZalgoPromise {\n\n const tunnelWindows = globalStore('tunnelWindows');\n const parentWindow = getParent(window);\n \n if (!parentWindow) {\n throw new Error(`No parent window found to open tunnel to`);\n }\n \n const id = addTunnelWindow({ name, source, canary, sendMessage });\n \n return send(parentWindow, MESSAGE_NAME.OPEN_TUNNEL, {\n \n name,\n \n sendMessage() {\n \n const tunnelWindow = tunnelWindows.get(id);\n \n try {\n // IE gets antsy if you try to even reference a closed window\n noop(tunnelWindow && tunnelWindow.source);\n } catch (err) {\n tunnelWindows.del(id);\n return;\n }\n \n if (!tunnelWindow || !tunnelWindow.source || isWindowClosed(tunnelWindow.source)) {\n return;\n }\n \n try {\n tunnelWindow.canary();\n } catch (err) {\n return;\n }\n \n // $FlowFixMe[object-this-reference]\n tunnelWindow.sendMessage.apply(this, arguments);\n }\n \n }, { domain: WILDCARD });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isSameDomain, getOpener, getDomain, getFrameByName, assertSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { getGlobal, windowStore } from '../global';\nimport type { OnType, SendType, ReceiveMessageType } from '../types';\n\nimport { needsBridge, registerRemoteWindow, rejectRemoteSendMessage, registerRemoteSendMessage, getBridgeName } from './common';\n\nfunction awaitRemoteBridgeForWindow (win : CrossDomainWindowType) : ZalgoPromise {\n return windowStore('remoteBridgeAwaiters').getOrSet(win, () => {\n return ZalgoPromise.try(() => {\n const frame = getFrameByName(win, getBridgeName(getDomain()));\n\n if (!frame) {\n return;\n }\n\n if (isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n return frame;\n }\n\n return new ZalgoPromise(resolve => {\n\n let interval;\n let timeout; // eslint-disable-line prefer-const\n\n interval = setInterval(() => { // eslint-disable-line prefer-const\n if (frame && isSameDomain(frame) && getGlobal(assertSameDomain(frame))) {\n clearInterval(interval);\n clearTimeout(timeout);\n return resolve(frame);\n }\n }, 100);\n\n timeout = setTimeout(() => {\n clearInterval(interval);\n return resolve();\n }, 2000);\n });\n });\n });\n}\n\nexport function openTunnelToOpener({ on, send, receiveMessage } : {| on : OnType, send : SendType, receiveMessage : ReceiveMessageType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const opener = getOpener(window);\n \n if (!opener || !needsBridge({ win: opener })) {\n return;\n }\n\n registerRemoteWindow(opener);\n\n return awaitRemoteBridgeForWindow(opener).then(bridge => {\n\n if (!bridge) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: no bridge found in opener`));\n }\n\n if (!window.name) {\n return rejectRemoteSendMessage(opener, new Error(`Can not register with opener: window does not have a name`));\n }\n\n return getGlobal(assertSameDomain(bridge)).openTunnelToParent({\n\n name: window.name,\n\n source: window,\n\n canary() {\n // pass\n },\n\n sendMessage(message) {\n\n try {\n noop(window);\n } catch (err) {\n return;\n }\n\n if (!window || window.closed) {\n return;\n }\n\n try {\n receiveMessage({\n data: message,\n // $FlowFixMe[object-this-reference]\n origin: this.origin,\n // $FlowFixMe[object-this-reference]\n source: this.source\n }, { on, send });\n } catch (err) {\n ZalgoPromise.reject(err);\n }\n }\n\n }).then(({ source, origin, data }) => {\n\n if (source !== opener) {\n throw new Error(`Source does not match opener`);\n }\n\n registerRemoteSendMessage(source, origin, data.sendMessage);\n\n }).catch(err => {\n\n rejectRemoteSendMessage(opener, err);\n throw err;\n });\n });\n });\n}\n","/* @flow */\n\nimport { isSameDomain, isWindowClosed, type CrossDomainWindowType, closeWindow,\n type DomainMatcher, getOpener, WINDOW_TYPE, isWindow, assertSameDomain, getFrameForWindow } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise, noop, submitForm } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE, METHOD } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { SendType } from '../types';\n\nfunction cleanupProxyWindows() {\n const idToProxyWindow = globalStore('idToProxyWindow');\n for (const id of idToProxyWindow.keys()) {\n // $FlowFixMe\n if (idToProxyWindow.get(id).shouldClean()) {\n idToProxyWindow.del(id);\n }\n }\n}\n\ntype SetLocationOptions = {|\n method? : $Values,\n body? : {|\n [string] : string | boolean\n |}\n|};\n\ntype SerializedWindowType = {|\n id : string,\n getType : () => ZalgoPromise<$Values>,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n isClosed : () => ZalgoPromise,\n setLocation : (url : string, opts? : SetLocationOptions) => ZalgoPromise,\n getName : () => ZalgoPromise,\n setName : (string) => ZalgoPromise,\n getInstanceID : () => ZalgoPromise\n|};\n\nfunction getSerializedWindow(winPromise : ZalgoPromise, { send, id = uniqueID() } : {| send : SendType, id? : string |}) : SerializedWindowType {\n \n let windowNamePromise = winPromise.then(win => {\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n });\n \n const windowTypePromise = winPromise.then(window => {\n if (!isWindowClosed(window)) {\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n } else {\n throw new Error(`Window is closed, can not determine type`);\n }\n });\n\n windowNamePromise.catch(noop);\n windowTypePromise.catch(noop);\n\n const getName = () => winPromise.then(win => {\n if (isWindowClosed(win)) {\n return;\n }\n\n if (isSameDomain(win)) {\n return assertSameDomain(win).name;\n }\n\n return windowNamePromise;\n });\n\n const getDefaultSetLocationOptions = () => {\n // $FlowFixMe\n return {};\n };\n\n const setLocation = (href : string, opts? : SetLocationOptions = getDefaultSetLocationOptions()) => winPromise.then(win => {\n const domain = `${ window.location.protocol }//${ window.location.host }`;\n const { method = METHOD.GET, body } = opts;\n\n if (href.indexOf('/') === 0) {\n href = `${ domain }${ href }`;\n } else if (!href.match(/^https?:\\/\\//) && href.indexOf(domain) !== 0) {\n throw new Error(`Expected url to be http or https url, or absolute path, got ${ JSON.stringify(href) }`);\n }\n\n if (method === METHOD.POST) {\n return getName().then(name => {\n if (!name) {\n throw new Error(`Can not post to window without target name`);\n }\n\n submitForm({\n url: href,\n target: name,\n method,\n body\n });\n });\n } else if (method === METHOD.GET) {\n if (isSameDomain(win)) {\n try {\n if (win.location && typeof win.location.replace === 'function') {\n // $FlowFixMe\n win.location.replace(href);\n return;\n }\n } catch (err) {\n // pass\n }\n }\n\n win.location = href;\n\n } else {\n throw new Error(`Unsupported method: ${ method }`);\n }\n });\n\n return {\n id,\n getType: () => {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise(() => winPromise.then(win => getWindowInstanceID(win, { send }))),\n close: () => winPromise.then(closeWindow),\n getName,\n focus: () => winPromise.then(win => {\n win.focus();\n }),\n isClosed: () => winPromise.then(win => {\n return isWindowClosed(win);\n }),\n setLocation,\n setName: (name) => winPromise.then(win => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n const sameDomain = isSameDomain(win);\n const frame = getFrameForWindow(win);\n\n if (!sameDomain) {\n throw new Error(`Can not set name for cross-domain window: ${ name }`);\n }\n\n assertSameDomain(win).name = name;\n if (frame) {\n frame.setAttribute('name', name);\n }\n\n windowNamePromise = ZalgoPromise.resolve(name);\n })\n };\n}\n\nexport class ProxyWindow {\n\n id : string\n isProxyWindow : true = true\n serializedWindow : SerializedWindowType\n actualWindow : ?CrossDomainWindowType\n actualWindowPromise : ZalgoPromise\n send : SendType\n name : string\n\n constructor({ send, win, serializedWindow } : {| win? : CrossDomainWindowType, serializedWindow? : SerializedWindowType, send : SendType |}) {\n this.actualWindowPromise = new ZalgoPromise();\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send });\n \n globalStore('idToProxyWindow').set(this.getID(), this);\n if (win) {\n this.setWindow(win, { send });\n }\n }\n\n getID() : string {\n return this.serializedWindow.id;\n }\n\n getType() : ZalgoPromise<$Values> {\n return this.serializedWindow.getType();\n }\n\n isPopup() : ZalgoPromise {\n return this.getType().then(type => {\n return type === WINDOW_TYPE.POPUP;\n });\n }\n\n setLocation(href : string, opts? : SetLocationOptions) : ZalgoPromise {\n return this.serializedWindow.setLocation(href, opts).then(() => this);\n }\n\n getName() : ZalgoPromise {\n return this.serializedWindow.getName();\n }\n\n setName(name : string) : ZalgoPromise {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise {\n const isPopupPromise = this.isPopup();\n const getNamePromise = this.getName();\n\n const reopenPromise = ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then(({ isPopup, name }) => {\n if (isPopup && name) {\n window.open('', name, 'noopener');\n }\n });\n const focusPromise = this.serializedWindow.focus();\n\n return ZalgoPromise.all([\n reopenPromise,\n focusPromise\n ]).then(() => this);\n }\n\n isClosed() : ZalgoPromise {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) {\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send, id: this.getID() });\n windowStore('winToProxyWindow').set(win, this);\n }\n\n awaitWindow() : ZalgoPromise {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (this.actualWindow) {\n return win === this.actualWindow;\n }\n \n return ZalgoPromise.hash({\n proxyInstanceID: this.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, { send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win, { send });\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise {\n return this.serializedWindow.getInstanceID();\n }\n\n shouldClean() : boolean {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n }\n\n serialize() : SerializedWindowType {\n return this.serializedWindow;\n }\n\n static unwrap(win : CrossDomainWindowType | ProxyWindow) : CrossDomainWindowType | ProxyWindow {\n return ProxyWindow.isProxyWindow(win)\n // $FlowFixMe\n ? win.unwrap()\n : win;\n }\n\n static serialize(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : SerializedWindowType {\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({ serializedWindow, send });\n }\n\n static isProxyWindow(obj : CrossDomainWindowType | ProxyWindow) : boolean {\n // $FlowFixMe\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n }\n\n static toProxyWindow(win : CrossDomainWindowType | ProxyWindow, { send } : {| send : SendType |}) : ProxyWindow {\n cleanupProxyWindows();\n\n if (ProxyWindow.isProxyWindow(win)) {\n // $FlowFixMe\n return win;\n }\n\n // $FlowFixMe\n const actualWindow : CrossDomainWindowType = win;\n \n return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({ win: actualWindow, send });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType;\n\nexport function serializeWindow(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, win : CrossDomainWindowType, { send } : {| send : SendType |}) : SerializedWindow {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, ProxyWindow.serialize(win, { send }));\n}\n\nexport function deserializeWindow(source : CrossDomainWindowType | ProxyWindow, origin : string, win : SerializedWindowType, { send } : {| send : SendType |}) : ProxyWindow {\n return ProxyWindow.deserialize(win, { send });\n}\n","/* @flow */\n\nimport { matchDomain, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, isRegex, arrayFrom } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { MESSAGE_NAME, WILDCARD, SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport type { OnType, SendType, CancelableType } from '../types';\n\nimport { ProxyWindow } from './window';\n\ntype StoredMethod = {|\n name : string,\n domain : DomainMatcher,\n val : Function,\n source : CrossDomainWindowType | ProxyWindow\n|};\n\nfunction addMethod(id : string, val : Function, name : string, source : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher) {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n \n if (ProxyWindow.isProxyWindow(source)) {\n proxyWindowMethods.set(id, { val, name, domain, source });\n } else {\n proxyWindowMethods.del(id);\n // $FlowFixMe\n const methods = methodStore.getOrSet(source, () => ({}));\n methods[id] = { domain, name, val, source };\n }\n}\n\nfunction lookupMethod(source : CrossDomainWindowType, id : string) : ?StoredMethod {\n const methodStore = windowStore('methodStore');\n const proxyWindowMethods = globalStore('proxyWindowMethods');\n const methods = methodStore.getOrSet(source, () => ({}));\n return methods[id] || proxyWindowMethods.get(id);\n}\n\nfunction stringifyArguments(args : $ReadOnlyArray = []) : string {\n return arrayFrom(args).map(arg => {\n if (typeof arg === 'string') {\n return `'${ arg }'`;\n }\n if (arg === undefined) {\n return 'undefined';\n }\n if (arg === null) {\n return 'null';\n }\n if (typeof arg === 'boolean') {\n return arg.toString();\n }\n if (Array.isArray(arg)) {\n return '[ ... ]';\n }\n if (typeof arg === 'object') {\n return '{ ... }';\n }\n if (typeof arg === 'function') {\n return '() => { ... }';\n }\n return `<${ typeof arg }>`;\n }).join(', ');\n}\n\nfunction listenForFunctionCalls({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore('builtinListeners').getOrSet('functionCalls', () => {\n return on(MESSAGE_NAME.METHOD, { domain: WILDCARD }, ({ source, origin, data } : {| source : CrossDomainWindowType, origin : string, data : Object |}) => {\n const { id, name } = data;\n\n const meth = lookupMethod(source, id);\n \n if (!meth) {\n throw new Error(`Could not find method '${ name }' with id: ${ data.id } in ${ getDomain(window) }`);\n }\n\n const { source: methodSource, domain, val } = meth;\n \n return ZalgoPromise.try(() => {\n if (!matchDomain(domain, origin)) {\n // $FlowFixMe\n throw new Error(`Method '${ data.name }' domain ${ JSON.stringify(isRegex(meth.domain) ? meth.domain.source : meth.domain) } does not match origin ${ origin } in ${ getDomain(window) }`);\n }\n \n if (ProxyWindow.isProxyWindow(methodSource)) {\n // $FlowFixMe\n return methodSource.matchWindow(source, { send }).then(match => {\n if (!match) {\n throw new Error(`Method call '${ data.name }' failed - proxy window does not match source in ${ getDomain(window) }`);\n }\n });\n }\n }).then(() => {\n return val.apply({ source, origin }, data.args);\n }, err => {\n return ZalgoPromise.try(() => {\n if (val.onError) {\n return val.onError(err);\n }\n }).then(() => {\n // $FlowFixMe\n if (err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(data.args) }) failed\\n\\n${ err.stack }`;\n }\n\n throw err;\n });\n }).then(result => {\n return { result, id, name };\n });\n });\n });\n}\n\nexport type SerializedFunction = CustomSerializedType;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction = {\n () : ZalgoPromise | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedFunction {\n listenForFunctionCalls({ on, send });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n let name = val.__name__ || val.name || key;\n\n if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {\n name = name.replace('anonymous::', `${ key }::`);\n }\n\n if (ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n\n // $FlowFixMe\n destination.awaitWindow().then(win => {\n addMethod(id, val, name, win, domain);\n });\n } else {\n addMethod(id, val, name, destination, domain);\n }\n\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, { id, name });\n}\n\nexport function deserializeFunction(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : {| id : string, name : string |}, { send } : {| send : SendType |}) : (...args : $ReadOnlyArray) => ZalgoPromise {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper() : ZalgoPromise {\n let originalStack;\n \n if (__DEBUG__) {\n originalStack = (new Error(`Original call to ${ name }():`)).stack;\n }\n \n return ProxyWindow.toProxyWindow(source, { send }).awaitWindow().then(win => {\n const meth = lookupMethod(win, id);\n \n if (meth && meth.val !== crossDomainFunctionWrapper) {\n return meth.val.apply({ source: window, origin: getDomain() }, arguments);\n } else {\n // $FlowFixMe[method-unbinding]\n const args = Array.prototype.slice.call(arguments);\n\n if (opts.fireAndForget) {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: true });\n } else {\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, { domain: origin, fireAndForget: false })\n .then(res => res.data.result);\n }\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `Remote call to ${ name }(${ stringifyArguments(arguments) }) failed\\n\\n${ err.stack }\\n\\n${ originalStack }`;\n }\n throw err;\n });\n }\n\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n\n crossDomainFunctionWrapper.origin = origin;\n\n return crossDomainFunctionWrapper;\n };\n\n const crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: true });\n\n return crossDomainFunctionWrapper;\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindow, type DomainMatcher } from 'cross-domain-utils/src';\nimport { TYPE, serialize, deserialize, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, deserializeFunction, type SerializedFunction } from './function';\nimport { serializePromise, deserializePromise, type SerializedPromise } from './promise';\nimport { serializeWindow, deserializeWindow, type SerializedWindow, ProxyWindow } from './window';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T, { on, send } : {| on : OnType, send : SendType |}) : string {\n return serialize(obj, {\n [ TYPE.PROMISE ]: (val : Thenable, key : string) : SerializedPromise => serializePromise(destination, domain, val, key, { on, send }),\n [ TYPE.FUNCTION ]: (val : Function, key : string) : SerializedFunction => serializeFunction(destination, domain, val, key, { on, send }),\n [ TYPE.OBJECT ]: (val : CrossDomainWindowType) : Object | SerializedWindow => {\n return (isWindow(val) || ProxyWindow.isProxyWindow(val)) ? serializeWindow(destination, domain, val, { send }) : val;\n }\n });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { send } : {| on : OnType, send : SendType |}) : T {\n return deserialize(message, {\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE ]: (serializedPromise) => deserializePromise(source, origin, serializedPromise),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION ]: (serializedFunction) => deserializeFunction(source, origin, serializedFunction, { send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { send })\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeType, type CustomSerializedType, type Thenable } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport type { OnType, SendType } from '../types';\n\nimport { serializeFunction, type SerializedFunction } from './function';\nimport { ProxyWindow } from './window';\n\nexport type SerializedPromise = CustomSerializedType;\n\nexport function serializePromise(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : Thenable, key : string, { on, send } : {| on : OnType, send : SendType |}) : SerializedPromise {\n return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then: serializeFunction(destination, domain, (resolve, reject) => val.then(resolve, reject), key, { on, send })\n });\n}\n\nexport function deserializePromise(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : {| then : Function |}) : ZalgoPromise {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, PROTOCOL } from 'cross-domain-utils/src';\n\nimport { SEND_STRATEGY, WILDCARD } from '../../conf';\nimport { needsGlobalMessagingForBrowser } from '../../lib';\nimport { getGlobal } from '../../global';\nimport { sendBridgeMessage, needsBridgeForBrowser, isBridge } from '../../bridge';\n\ntype SendStrategies = {|\n [$Values] : (CrossDomainWindowType, string, string) => void\n|};\n\nexport const SEND_MESSAGE_STRATEGIES : SendStrategies = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n if (domain.indexOf(PROTOCOL.FILE) === 0) {\n domain = WILDCARD;\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n\n if (domain.indexOf(PROTOCOL.MOCK) === 0) {\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send message to mock domain ${ domain }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n const windowDomain = getDomain(win);\n \n if (windowDomain !== domain) {\n throw new Error(`Mock domain target ${ domain } does not match window domain ${ windowDomain }`);\n }\n\n // $FlowFixMe\n domain = getActualDomain(win);\n\n }\n }\n\n win.postMessage(serializedMessage, domain);\n};\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n\n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : string) => {\n\n if (!needsBridgeForBrowser() && !isBridge()) {\n throw new Error(`Bridge not needed for browser`);\n }\n\n if (isSameDomain(win)) {\n throw new Error(`Post message through bridge disabled between same domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use bridge to communicate between two different windows, not between frames`);\n }\n\n sendBridgeMessage(win, domain, serializedMessage);\n };\n}\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__ || __POST_ROBOT__.__GLOBAL_MESSAGE_SUPPORT__) {\n \n SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = (win : CrossDomainWindowType, serializedMessage : string) => {\n\n if (!needsGlobalMessagingForBrowser()) {\n throw new Error(`Global messaging not needed for browser`);\n }\n\n if (!isSameDomain(win)) {\n throw new Error(`Post message through global disabled between different domain windows`);\n }\n\n if (isSameTopWindow(window, win) !== false) {\n throw new Error(`Can only use global to communicate between two different windows, not between frames`);\n }\n\n // $FlowFixMe\n const foreignGlobal = getGlobal(win);\n\n if (!foreignGlobal) {\n throw new Error(`Can not find postRobot global on foreign window`);\n }\n\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { stringifyError, noop } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport { windowStore, getGlobalKey } from '../../global';\nimport type { Message, PackedMessages } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nfunction packMessages(messages : $ReadOnlyArray) : PackedMessages {\n return {\n [ getGlobalKey() ]: messages\n };\n}\n\nexport function sendMessage(win : CrossDomainWindowType, domain : string, message : Message, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n const messageBuffer = windowStore();\n\n const domainBuffer = messageBuffer.getOrSet(win, () => ({}));\n\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n\n domainBuffer.flush = domainBuffer.flush || ZalgoPromise.flush().then(() => {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n\n const serializedMessage = serializeMessage(win, domain, packMessages(domainBuffer.buffer || []), { on, send });\n delete domainBuffer.buffer;\n\n const strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n const errors = [];\n\n for (const strategyName of strategies) {\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (errors.length === strategies.length) {\n throw new Error(`All post-robot messaging strategies failed:\\n\\n${ errors.map((err, i) => `${ i }. ${ stringifyError(err) }`).join('\\n\\n') }`);\n }\n });\n\n return domainBuffer.flush.then(() => {\n delete domainBuffer.flush;\n });\n }).then(noop);\n}\n","/* @flow */\n\nimport { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet, noop } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\nimport { ProxyWindow } from '../serialize/window';\n\nexport function resetListeners() {\n const responseListeners = globalStore('responseListeners');\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n responseListeners.reset();\n erroredResponseListeners.reset();\n}\n\nconst __DOMAIN_REGEX__ = '__domain_regex__';\n\nexport type RequestListenerType = {|\n handler : ({| source : CrossDomainWindowType, origin : string, data : mixed |}) => (mixed | ZalgoPromise),\n handleError : (err : mixed) => void\n|};\n\nexport type ResponseListenerType = {|\n name : string,\n win : CrossDomainWindowType,\n domain : DomainMatcher,\n promise : ZalgoPromise<*>,\n ack? : ?boolean,\n cancelled? : ?boolean\n|};\n\nexport function addResponseListener(hash : string, listener : ResponseListenerType) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.set(hash, listener);\n}\n\nexport function getResponseListener(hash : string) : ?ResponseListenerType {\n const responseListeners = globalStore('responseListeners');\n return responseListeners.get(hash);\n}\n\nexport function deleteResponseListener(hash : string) {\n const responseListeners = globalStore('responseListeners');\n responseListeners.del(hash);\n}\n\nexport function cancelResponseListeners() {\n const responseListeners = globalStore('responseListeners');\n for (const hash of responseListeners.keys()) {\n const listener = responseListeners.get(hash);\n if (listener) {\n listener.cancelled = true;\n }\n responseListeners.del(hash);\n }\n}\n\nexport function markResponseListenerErrored(hash : string) {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n erroredResponseListeners.set(hash, true);\n}\n\nexport function isResponseListenerErrored(hash : string) : boolean {\n const erroredResponseListeners = globalStore('erroredResponseListeners');\n return erroredResponseListeners.has(hash);\n}\n\nexport function getRequestListener({ name, win, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard), domain : ?(string | RegExp) |}) : ?RequestListenerType {\n const requestListeners = windowStore('requestListeners');\n\n if (win === WILDCARD) {\n win = null;\n }\n\n if (domain === WILDCARD) {\n domain = null;\n }\n\n if (!name) {\n throw new Error(`Name required to get request listener`);\n }\n\n for (const winQualifier of [ win, getWildcard() ]) {\n if (!winQualifier) {\n continue;\n }\n\n const nameListeners = requestListeners.get(winQualifier);\n\n if (!nameListeners) {\n continue;\n }\n\n const domainListeners = nameListeners[name];\n\n if (!domainListeners) {\n continue;\n }\n\n if (domain && typeof domain === 'string') {\n if (domainListeners[domain]) {\n return domainListeners[domain];\n }\n\n if (domainListeners[__DOMAIN_REGEX__]) {\n for (const { regex, listener } of domainListeners[__DOMAIN_REGEX__]) {\n if (matchDomain(regex, domain)) {\n return listener;\n }\n }\n }\n }\n\n if (domainListeners[WILDCARD]) {\n return domainListeners[WILDCARD];\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function addRequestListener({ name, win: winCandidate, domain } : {| name : string, win : ?(CrossDomainWindowType | WildCard | ProxyWindow), domain : ?DomainMatcher |}, listener : RequestListenerType) : {| cancel : () => void |} {\n const requestListeners = windowStore('requestListeners');\n\n if (!name || typeof name !== 'string') {\n throw new Error(`Name required to add request listener`);\n }\n\n // $FlowFixMe\n if (winCandidate && winCandidate !== WILDCARD && ProxyWindow.isProxyWindow(winCandidate)) {\n // $FlowFixMe\n const proxyWin : ProxyWindow = winCandidate;\n\n const requestListenerPromise = proxyWin.awaitWindow().then(actualWin => {\n return addRequestListener({ name, win: actualWin, domain }, listener);\n });\n\n return {\n cancel: () => {\n requestListenerPromise.then(requestListener => requestListener.cancel(), noop);\n }\n };\n }\n\n // $FlowFixMe\n let win : ?(CrossDomainWindowType | WildCard) = winCandidate;\n\n if (Array.isArray(win)) {\n const listenersCollection = [];\n\n for (const item of win) {\n listenersCollection.push(addRequestListener({ name, domain, win: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n if (Array.isArray(domain)) {\n const listenersCollection = [];\n\n for (const item of domain) {\n listenersCollection.push(addRequestListener({ name, win, domain: item }, listener));\n }\n\n return {\n cancel() {\n for (const cancelListener of listenersCollection) {\n cancelListener.cancel();\n }\n }\n };\n }\n\n const existingListener = getRequestListener({ name, win, domain });\n\n if (!win || win === WILDCARD) {\n win = getWildcard();\n }\n\n domain = domain || WILDCARD;\n const strDomain = domain.toString();\n\n if (existingListener) {\n if (win && domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (win) {\n throw new Error(`Request listener already exists for ${ name } for ${ win === getWildcard() ? 'wildcard' : 'specified' } window`);\n } else if (domain) {\n throw new Error(`Request listener already exists for ${ name } on domain ${ domain.toString() }`);\n } else {\n throw new Error(`Request listener already exists for ${ name }`);\n }\n }\n\n const winNameListeners = requestListeners.getOrSet(win, () => ({}));\n const winNameDomainListeners = getOrSet(winNameListeners, name, () => ({}));\n\n let winNameDomainRegexListeners;\n let winNameDomainRegexListener;\n\n if (isRegex(domain)) {\n winNameDomainRegexListeners = getOrSet(winNameDomainListeners, __DOMAIN_REGEX__, () => []);\n winNameDomainRegexListener = { regex: domain, listener };\n winNameDomainRegexListeners.push(winNameDomainRegexListener);\n } else {\n winNameDomainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete winNameDomainListeners[strDomain];\n\n if (winNameDomainRegexListener) {\n winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1));\n\n if (!winNameDomainRegexListeners.length) {\n delete winNameDomainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(winNameDomainListeners).length) {\n delete winNameListeners[name];\n }\n\n if (win && !Object.keys(winNameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { getDomain, isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop, stringifyError, uniqueID } from 'belter/src';\n\nimport { MESSAGE_TYPE, MESSAGE_ACK, MESSAGE_NAME } from '../../conf';\nimport { sendMessage } from '../send';\nimport { getRequestListener, getResponseListener, deleteResponseListener, isResponseListenerErrored } from '../listeners';\nimport type { RequestMessage, AckResponseMessage, ResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport function handleRequest(source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : {| on : OnType, send : SendType |}) : ZalgoPromise {\n\n const options = getRequestListener({ name: message.name, win: source, domain: origin });\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (__DEBUG__) {\n // eslint-disable-next-line no-console\n console.info('receive::req', logName, origin, '\\n\\n', message.data);\n }\n\n function sendAck() : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.ACK,\n hash: message.hash,\n name: message.name\n }, { on, send });\n } catch (err) {\n throw new Error(`Send ack message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n\n function sendResponse(ack : $Values, data : ?Object, error : ?mixed) : ZalgoPromise {\n return ZalgoPromise.flush().then(() => {\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n console.info('respond::res', logName, origin, '\\n\\n', data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n console.error('respond::err', logName, origin, '\\n\\n', error); // eslint-disable-line no-console\n }\n }\n\n try {\n return sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.RESPONSE,\n hash: message.hash,\n name: message.name,\n ack,\n data,\n error\n }, { on, send });\n } catch (err) {\n throw new Error(`Send response message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n }\n });\n }\n\n \n return ZalgoPromise.all([\n sendAck(),\n\n ZalgoPromise.try(() => {\n\n if (!options) {\n throw new Error(`No handler found for post message: ${ message.name } from ${ origin } in ${ window.location.protocol }//${ window.location.host }${ window.location.pathname }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_ACK.SUCCESS, data);\n\n }, error => {\n return sendResponse(MESSAGE_ACK.ERROR, null, error);\n })\n\n ]).then(noop).catch(err => {\n if (options && options.handleError) {\n return options.handleError(err);\n } else {\n throw err;\n }\n });\n}\n\nexport function handleAck(source : CrossDomainWindowType, origin : string, message : AckResponseMessage) {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n try {\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Ack origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n \n if (source !== options.win) {\n throw new Error(`Ack source does not match registered window`);\n }\n } catch (err) {\n options.promise.reject(err);\n }\n\n options.ack = true;\n}\n\nexport function handleResponse(source : CrossDomainWindowType, origin : string, message : ResponseMessage) : void | ZalgoPromise {\n\n if (isResponseListenerErrored(message.hash)) {\n return;\n }\n\n const options = getResponseListener(message.hash);\n\n if (!options) {\n 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 }`);\n }\n\n if (!matchDomain(options.domain, origin)) {\n throw new Error(`Response origin ${ origin } does not match domain ${ stringifyDomainPattern(options.domain) }`);\n }\n\n if (source !== options.win) {\n throw new Error(`Response source does not match registered window`);\n }\n\n deleteResponseListener(message.hash);\n\n const logName = (message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string') ? `${ message.data.name }()` : message.name;\n\n if (message.ack === MESSAGE_ACK.ERROR) {\n if (__DEBUG__) {\n console.error('receive::err', logName, origin, '\\n\\n', message.error); // eslint-disable-line no-console\n }\n\n options.promise.reject(message.error);\n\n } else if (message.ack === MESSAGE_ACK.SUCCESS) {\n if (__DEBUG__) {\n console.info('receive::res', logName, origin, '\\n\\n', message.data); // eslint-disable-line no-console\n }\n\n options.promise.resolve({ source, origin, data: message.data });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport type { Message } from '../types';\nimport { MESSAGE_TYPE } from '../../conf';\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore, getGlobalKey } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { handleRequest, handleResponse, handleAck } from './types';\n\nfunction deserializeMessages(message : string, source : CrossDomainWindowType, origin : string, { on, send } : {| on : OnType, send : SendType |}) : ?$ReadOnlyArray {\n let parsedMessage;\n\n try {\n parsedMessage = deserializeMessage(source, origin, message, { on, send });\n } catch (err) {\n return;\n }\n\n if (!parsedMessage) {\n return;\n }\n\n if (typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n const parseMessages = parsedMessage[getGlobalKey()];\n\n if (!Array.isArray(parseMessages)) {\n return;\n }\n\n return parseMessages;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : {| on : OnType, send : SendType |}) {\n const receivedMessages = globalStore('receivedMessages');\n\n try {\n if (!window || window.closed || !event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n if (isWindowClosed(source)) {\n return;\n }\n\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const messages = deserializeMessages(data, source, origin, { on, send });\n\n if (!messages) {\n return;\n }\n\n markWindowKnown(source);\n\n for (const message of messages) {\n if (receivedMessages.has(message.id)) {\n return;\n }\n\n receivedMessages.set(message.id, true);\n\n if (isWindowClosed(source) && !message.fireAndForget) {\n return;\n }\n\n if (message.origin.indexOf(PROTOCOL.FILE) === 0) {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n try {\n if (message.type === MESSAGE_TYPE.REQUEST) {\n handleRequest(source, origin, message, { on, send });\n } else if (message.type === MESSAGE_TYPE.RESPONSE) {\n handleResponse(source, origin, message);\n } else if (message.type === MESSAGE_TYPE.ACK) {\n handleAck(source, origin, message);\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n}\n\nexport function setupGlobalReceiveMessage({ on, send } : {| on : OnType, send : SendType |}) {\n const global = getGlobal();\n global.receiveMessage = global.receiveMessage || (message => receiveMessage(message, { on, send }));\n}\n\ntype ListenerEvent = {|\n source : CrossDomainWindowType,\n origin : string,\n data : string,\n sourceElement : CrossDomainWindowType,\n originalEvent? : {| origin : string |}\n|};\n\nexport function messageListener(event : ListenerEvent, { on, send } : {| on : OnType, send : SendType |}) {\n ZalgoPromise.try(() => {\n try {\n noop(event.source);\n } catch (err) {\n return;\n }\n\n const source = event.source || event.sourceElement;\n let origin = event.origin || (event.originalEvent && event.originalEvent.origin);\n const data = event.data;\n\n if (origin === 'null') {\n origin = `${ PROTOCOL.FILE }//`;\n }\n\n if (!source) {\n return;\n }\n\n if (!origin) {\n throw new Error(`Post message did not have origin domain`);\n }\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(source, window) === false) {\n return;\n }\n }\n\n receiveMessage({ source, origin, data }, { on, send });\n });\n}\n\nexport function listenForMessages({ on, send } : {| on : OnType, send : SendType |}) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n return addEventListener(window, 'message', event => {\n // $FlowFixMe\n messageListener(event, { on, send });\n });\n });\n}\n\nexport function stopListenForMessages() {\n const listener = globalStore().get('postMessageListener');\n if (listener) {\n listener.cancel();\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nimport { addRequestListener } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\n\nconst getDefaultServerOptions = () : ServerOptionsType => {\n // $FlowFixMe\n return {};\n};\n\nexport function on(name : string, options : ServerOptionsType | HandlerType, handler : ?HandlerType) : CancelableType {\n\n if (!name) {\n throw new Error('Expected name');\n }\n\n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n const winOrProxyWin = options.window;\n const domain = options.domain || WILDCARD;\n\n const successHandler = handler || options.handler;\n const errorHandler = options.errorHandler || (err => {\n throw err;\n });\n\n const requestListener = addRequestListener({ name, win: winOrProxyWin, domain }, {\n handler: successHandler,\n handleError: errorHandler\n });\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\ntype CancelableZalgoPromise = ZalgoPromise & {|\n cancel : () => void\n|};\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : CancelableZalgoPromise<{| source : mixed, origin : string, data : Object |}> {\n \n options = options || getDefaultServerOptions();\n if (typeof options === 'function') {\n handler = options;\n options = getDefaultServerOptions();\n }\n\n const promise = new ZalgoPromise();\n let listener; // eslint-disable-line prefer-const\n\n options.errorHandler = (err) => {\n listener.cancel();\n promise.reject(err);\n };\n\n listener = on(name, options, event => {\n listener.cancel();\n promise.resolve(event);\n if (handler) {\n return handler(event);\n }\n });\n\n // $FlowFixMe\n promise.cancel = listener.cancel;\n\n // $FlowFixMe\n return promise;\n}\n","/* @flow */\n\nimport { getUserAgent } from 'cross-domain-utils/src';\n\nexport function needsGlobalMessagingForBrowser() : boolean {\n\n if (getUserAgent(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) {\n return true;\n }\n\n return false;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isAncestor, isWindowClosed, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, isRegex, noop, safeInterval, stringify, stringifyError } from 'belter/src';\n\n\nimport { CHILD_WINDOW_TIMEOUT, MESSAGE_TYPE, WILDCARD, MESSAGE_NAME, ACK_TIMEOUT, RES_TIMEOUT, ACK_TIMEOUT_KNOWN, RESPONSE_CYCLE_TIME } from '../conf';\nimport { sendMessage, addResponseListener, deleteResponseListener, markResponseListenerErrored, type ResponseListenerType } from '../drivers';\nimport { awaitWindowHello, sayHello, isWindowKnown } from '../lib';\nimport { windowStore } from '../global';\nimport { ProxyWindow } from '../serialize/window';\nimport type { SendType } from '../types';\n\nimport { on } from './on';\n\nfunction validateOptions(name : string, win : CrossDomainWindowType, domain : ?DomainMatcher) {\n if (!name) {\n throw new Error('Expected name');\n }\n\n if (domain) {\n if (typeof domain !== 'string' && !Array.isArray(domain) && !isRegex(domain)) {\n throw new TypeError(`Can not send ${ name }. Expected domain ${ JSON.stringify(domain) } to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error(`Can not send ${ name }. Target window is closed`);\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, targetDomain : DomainMatcher, actualDomain : ?string, { send } : {| send : SendType |}) : ZalgoPromise {\n return ZalgoPromise.try(() => {\n if (typeof targetDomain === 'string') {\n return targetDomain;\n }\n\n return ZalgoPromise.try(() => {\n return actualDomain || sayHello(win, { send }).then(({ domain }) => domain);\n\n }).then(normalizedDomain => {\n if (!matchDomain(targetDomain, targetDomain)) {\n throw new Error(`Domain ${ stringify(targetDomain) } does not match ${ stringify(targetDomain) }`);\n }\n\n return normalizedDomain;\n });\n });\n}\n\nexport const send : SendType = (winOrProxyWin, name, data, options) => {\n options = options || {};\n const domainMatcher = options.domain || WILDCARD;\n const responseTimeout = options.timeout || RES_TIMEOUT;\n const childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;\n const fireAndForget = options.fireAndForget || false;\n\n return ProxyWindow.toProxyWindow(winOrProxyWin, { send }).awaitWindow().then(win => {\n\n // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domainMatcher);\n\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n }\n \n }).then(({ domain: actualDomain } = {}) => {\n\n return normalizeDomain(win, domainMatcher, actualDomain, { send });\n }).then(targetDomain => {\n const domain = targetDomain;\n\n const logName = (name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string') ? `${ data.name }()` : name;\n\n if (__DEBUG__) {\n console.info('send::req', logName, domain, '\\n\\n', data); // eslint-disable-line no-console\n }\n\n const promise = new ZalgoPromise();\n const hash = `${ name }_${ uniqueID() }`;\n\n if (!fireAndForget) {\n const responseListener : ResponseListenerType = { name, win, domain, promise };\n addResponseListener(hash, responseListener);\n\n const reqPromises = windowStore('requestPromises').getOrSet(win, () => []);\n reqPromises.push(promise);\n\n promise.catch(() => {\n markResponseListenerErrored(hash);\n deleteResponseListener(hash);\n });\n\n const totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;\n const totalResTimeout = responseTimeout;\n\n let ackTimeout = totalAckTimeout;\n let resTimeout = totalResTimeout;\n \n const interval = safeInterval(() => {\n if (isWindowClosed(win)) {\n return promise.reject(new Error(`Window closed for ${ name } before ${ responseListener.ack ? 'response' : 'ack' }`));\n }\n\n if (responseListener.cancelled) {\n return promise.reject(new Error(`Response listener was cancelled for ${ name }`));\n }\n\n ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);\n if (resTimeout !== -1) {\n resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);\n }\n\n if (!responseListener.ack && ackTimeout === 0) {\n return promise.reject(new Error(`No ack for postMessage ${ logName } in ${ getDomain() } in ${ totalAckTimeout }ms`));\n\n } else if (resTimeout === 0) {\n return promise.reject(new Error(`No response for postMessage ${ logName } in ${ getDomain() } in ${ totalResTimeout }ms`));\n }\n }, RESPONSE_CYCLE_TIME);\n\n promise.finally(() => {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n }).catch(noop);\n }\n\n return sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send }).then(() => {\n return fireAndForget ? promise.resolve() : promise;\n }, err => {\n throw new Error(`Send request message failed for ${ logName } in ${ getDomain() }\\n\\n${ stringifyError(err) }`);\n });\n });\n });\n};\n","/* @flow */\n\nimport { setup } from './setup';\nimport { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge, needsBridgeForBrowser, hasBridge,\n needsBridgeForWin, needsBridgeForDomain, destroyBridges } from './bridge';\n\nexport { ZalgoPromise as Promise } from 'zalgo-promise/src';\n\nexport * from './types';\nexport { ProxyWindow } from './serialize';\nexport { setup, destroy, serializeMessage, deserializeMessage, createProxyWindow, toProxyWindow } from './setup';\nexport { on, once, send } from './public';\nexport { markWindowKnown } from './lib';\nexport { cleanUpWindow } from './clean';\n\n// $FlowFixMe\nexport let bridge;\n\nif (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n bridge = { setupBridge, openBridge, linkWindow, linkUrl, isBridge, needsBridge,\n needsBridgeForBrowser, hasBridge, needsBridgeForWin, needsBridgeForDomain, destroyBridges };\n}\n\nif (__POST_ROBOT__.__AUTO_SETUP__) {\n setup();\n}\n","/* @flow */\n\nexport const BRIDGE_TIMEOUT = 5000;\nexport const CHILD_WINDOW_TIMEOUT = 5000;\n\nexport const ACK_TIMEOUT = 2000;\nexport const ACK_TIMEOUT_KNOWN = 10000;\nexport const RES_TIMEOUT : number = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\n","/* @flow */\n\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { initHello } from './lib';\nimport { listenForMessages, stopListenForMessages, receiveMessage, setupGlobalReceiveMessage, cancelResponseListeners } from './drivers';\nimport { getGlobal, deleteGlobal } from './global';\nimport { on, send } from './public';\nimport { setupBridge } from './bridge';\nimport { serializeMessage as internalSerializeMessage, deserializeMessage as internalDeserializeMessage, ProxyWindow } from './serialize';\n\nexport function serializeMessage(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\n}\n\nexport function createProxyWindow(win? : CrossDomainWindowType) : ProxyWindow {\n return new ProxyWindow({ send, win });\n}\n\nexport function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow {\n return ProxyWindow.toProxyWindow(win, { send });\n}\n\nexport function setup() {\n if (!getGlobal().initialized) {\n getGlobal().initialized = true;\n \n setupGlobalReceiveMessage({ on, send });\n listenForMessages({ on, send });\n \n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n setupBridge({ on, send, receiveMessage });\n }\n\n initHello({ on, send });\n }\n}\n\nexport function destroy() {\n cancelResponseListeners();\n stopListenForMessages();\n deleteGlobal();\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType, isWindowClosed } from 'cross-domain-utils/src';\nimport { noop } from 'belter/src';\n\nimport { windowStore } from './global';\n\nexport function cleanUpWindow(win : CrossDomainWindowType) {\n const requestPromises = windowStore('requestPromises');\n for (const promise of requestPromises.get(win, [])) {\n promise.reject(new Error(`Window ${ isWindowClosed(win) ? 'closed' : 'cleaned up' } before response`)).catch(noop);\n }\n}\n","/* @flow */\n\nimport { isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { getCurrentScriptUID } from 'belter/src';\n\nexport function getGlobalKey() : string {\n if (__ZOID__.__SCRIPT_NAMESPACE__) {\n return `${ __ZOID__.__GLOBAL_KEY__ }_${ getCurrentScriptUID() }`;\n } else {\n return __ZOID__.__GLOBAL_KEY__;\n }\n}\n\nexport function getGlobal(win : CrossDomainWindowType) : T {\n const globalKey = getGlobalKey();\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[globalKey]) {\n win[globalKey] = {};\n }\n\n return win[globalKey];\n}\n\nexport function tryGlobal(win : CrossDomainWindowType, handler : (T) => R) : ?R {\n try {\n return handler(getGlobal(win));\n } catch (err) {\n // pass\n }\n}\n\nexport function destroyGlobal() {\n const globalKey = getGlobalKey();\n delete window[globalKey];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow } from 'post-robot/src';\nimport { uniqueID, base64encode, base64decode } from 'belter/src';\nimport type { CrossDomainWindowType, DomainMatcher } from 'cross-domain-utils/src';\n\nimport { getGlobal } from './global';\n\nexport type ProxyObject = {|\n get : () => ZalgoPromise\n|};\n\nexport function getProxyObject(obj : T) : ProxyObject {\n return {\n get() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n // $FlowFixMe[object-this-reference]\n if (this.source && this.source !== window) {\n throw new Error(`Can not call get on proxy object from a remote window`);\n }\n \n return obj;\n });\n }\n };\n}\n\nexport function basicSerialize(data : T) : string {\n return base64encode(JSON.stringify(data));\n}\n\nexport function basicDeserialize(serializedData : string) : T {\n return JSON.parse(base64decode(serializedData));\n}\n\nexport const REFERENCE_TYPE = {\n UID: ('uid' : 'uid'),\n RAW: ('raw' : 'raw')\n};\n\nexport type UIDReferenceType = {| type : typeof REFERENCE_TYPE.UID, uid : string |};\nexport type RawReferenceType = {| type : typeof REFERENCE_TYPE.RAW, val : T |};\n\nexport type ReferenceType =\n UIDReferenceType |\n RawReferenceType;\n\nexport function getUIDRefStore(win : CrossDomainWindowType) : { [string] : T } {\n const global = getGlobal(win);\n global.references = global.references || {};\n return global.references;\n}\n\nexport function getUIDRef(val : T) : ReferenceType {\n const uid = uniqueID();\n const references = getUIDRefStore(window);\n references[uid] = val;\n return { type: REFERENCE_TYPE.UID, uid };\n}\n\nexport function getRawRef(val : T) : ReferenceType {\n return { type: REFERENCE_TYPE.RAW, val };\n}\n\nexport function getRefValue(win : CrossDomainWindowType, ref : ReferenceType) : T {\n if (ref.type === REFERENCE_TYPE.RAW) {\n return ref.val;\n }\n\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n return references[ref.uid];\n }\n\n throw new Error(`Unsupported ref type: ${ ref.type }`);\n}\n\nexport function cleanupRef(win : CrossDomainWindowType, ref : ReferenceType) {\n if (ref.type === REFERENCE_TYPE.UID) {\n const references = getUIDRefStore(win);\n delete references[ref.uid];\n }\n}\n\ntype Message = {|\n sender : {|\n domain : string\n |},\n metaData : M,\n reference : ReferenceType\n|};\n\ntype CrossDomainSerializeOptions = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string\n |},\n receiver : {|\n win : ProxyWindow | CrossDomainWindowType,\n domain : DomainMatcher\n |},\n passByReference? : boolean,\n basic? : boolean\n|};\n\ntype CrossDomainSerializedMessage = {|\n serializedData : string,\n cleanReference : () => void\n|};\n\nexport function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false } : CrossDomainSerializeOptions) : CrossDomainSerializedMessage {\n const proxyWin = toProxyWindow(receiver.win);\n const serializedMessage = basic\n ? JSON.stringify(data)\n : serializeMessage(proxyWin, receiver.domain, data);\n\n const reference = passByReference\n ? getUIDRef(serializedMessage)\n : getRawRef(serializedMessage);\n\n const message : Message = {\n sender: {\n domain: sender.domain\n },\n metaData,\n reference\n };\n\n const cleanReference = () => {\n cleanupRef(window, reference);\n };\n\n return {\n serializedData: basicSerialize(message),\n cleanReference\n };\n}\n\ntype CrossDomainDeserializeOptions = {|\n data : string,\n sender : {|\n win : CrossDomainWindowType | ({| metaData : M |}) => CrossDomainWindowType,\n domain? : string | ({| metaData : M |}) => string\n |},\n basic? : boolean\n|};\n\ntype CrossDomainDeserializedMessage = {|\n data : T,\n metaData : M,\n sender : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n reference : ReferenceType\n|};\n\nexport function crossDomainDeserialize({ data, sender, basic = false } : CrossDomainDeserializeOptions) : CrossDomainDeserializedMessage {\n const message : Message = basicDeserialize(data);\n\n const { reference, metaData } = message;\n\n let win;\n if (typeof sender.win === 'function') {\n win = sender.win({ metaData });\n } else {\n win = sender.win;\n }\n\n let domain;\n if (typeof sender.domain === 'function') {\n domain = sender.domain({ metaData });\n } else if (typeof sender.domain === 'string') {\n domain = sender.domain;\n } else {\n domain = message.sender.domain;\n }\n\n const serializedData = getRefValue(win, reference);\n const deserializedData = basic\n ? JSON.parse(serializedData)\n : deserializeMessage(win, domain, serializedData);\n \n return {\n data: deserializedData,\n metaData,\n sender: { win, domain },\n reference\n };\n}\n","/* @flow */\n\nimport { WINDOW_TYPE } from 'cross-domain-utils/src';\n\nexport const ZOID = `zoid`;\n\nexport const POST_MESSAGE = {\n DELEGATE: `${ ZOID }_delegate`,\n ALLOW_DELEGATE: `${ ZOID }_allow_delegate`\n};\n\nexport const PROP_TYPE = {\n STRING: ('string' : 'string'),\n OBJECT: ('object' : 'object'),\n FUNCTION: ('function' : 'function'),\n BOOLEAN: ('boolean' : 'boolean'),\n NUMBER: ('number' : 'number'),\n ARRAY: ('array' : 'array')\n};\n\nexport const WINDOW_REFERENCE = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global'),\n NAME: ('name' : 'name')\n};\n\nexport const PROP_SERIALIZATION = {\n JSON: ('json' : 'json'),\n DOTIFY: ('dotify' : 'dotify'),\n BASE64: ('base64' : 'base64')\n};\n\nexport const CONTEXT = WINDOW_TYPE;\n\nexport const WILDCARD = '*';\n\nexport const DEFAULT_DIMENSIONS = {\n WIDTH: '300px',\n HEIGHT: '150px'\n};\n\nexport const EVENT = {\n RENDER: 'zoid-render',\n RENDERED: 'zoid-rendered',\n DISPLAY: 'zoid-display',\n ERROR: 'zoid-error',\n CLOSE: 'zoid-close',\n DESTROY: 'zoid-destroy',\n PROPS: 'zoid-props',\n RESIZE: 'zoid-resize',\n FOCUS: 'zoid-focus'\n};\n\nexport const METHOD = {\n GET: ('get' : 'get'),\n POST: ('post' : 'post')\n};\n","/* @flow */\n\nimport { assertExists, memoize } from 'belter/src';\nimport { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop,\n findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop } from 'cross-domain-utils/src';\n\nimport { ZOID, WINDOW_REFERENCE } from '../constants';\nimport type { InitialChildPayload, WindowRef } from '../parent';\n\nimport { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType } from './serialize';\nimport { tryGlobal } from './global';\n\nfunction getWindowByRef(windowRef : WindowRef) : CrossDomainWindowType {\n if (windowRef.type === WINDOW_REFERENCE.OPENER) {\n return assertExists('opener', getOpener(window));\n\n } else if (windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, windowRef.distance));\n\n } else if (windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === 'string') {\n const { uid } = windowRef;\n const ancestor = getAncestor(window);\n\n if (!ancestor) {\n throw new Error(`Can not find ancestor window`);\n }\n\n for (const frame of getAllFramesInWindow(ancestor)) {\n if (isSameDomain(frame)) {\n const win = tryGlobal(frame, global => global.windows && global.windows[uid]);\n\n if (win) {\n return win;\n }\n }\n }\n } else if (windowRef.type === WINDOW_REFERENCE.NAME) {\n const { name } = windowRef;\n return assertExists('namedWindow', findFrameByName(assertExists('ancestor', getAncestor(window)), name));\n }\n\n throw new Error(`Unable to find ${ windowRef.type } parent component window`);\n}\n\nexport function buildChildWindowName({ name, serializedPayload } : {| name : string, serializedPayload : string |}) : string {\n return `__${ ZOID }__${ name }__${ serializedPayload }__`;\n}\n\nfunction parseWindowName(windowName : string) : {| name : string, serializedInitialPayload : string |} {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n\n const [ , zoidcomp, name, serializedInitialPayload ] = windowName.split('__');\n\n if (zoidcomp !== ZOID) {\n throw new Error(`Window not rendered by zoid - got ${ zoidcomp }`);\n }\n\n if (!name) {\n throw new Error(`Expected component name`);\n }\n\n if (!serializedInitialPayload) {\n throw new Error(`Expected serialized payload ref`);\n }\n\n return { name, serializedInitialPayload };\n}\n\nexport type InitialParentPayload = {|\n parent : {|\n domain : string,\n win : CrossDomainWindowType\n |},\n payload : InitialChildPayload,\n reference : ReferenceType\n|};\n\nconst parseInitialParentPayload = memoize((windowName : string) : InitialParentPayload => {\n const { serializedInitialPayload } = parseWindowName(windowName);\n\n const { data: payload, sender: parent, reference } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef)\n }\n });\n\n return {\n parent,\n payload,\n reference\n };\n});\n\nexport function getInitialParentPayload() : InitialParentPayload {\n return parseInitialParentPayload(window.name);\n}\n\nexport function isChildComponentWindow(name : string) : boolean {\n try {\n return parseWindowName(window.name).name === name;\n } catch (err) {\n // pass\n }\n\n return false;\n}\n\nexport function getWindowRef(targetWindow : CrossDomainWindowType, currentWindow? : CrossDomainWindowType = window) : ?WindowRef {\n if (targetWindow === getParent(currentWindow)) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow) };\n }\n\n if (targetWindow === getOpener(currentWindow)) {\n return { type: WINDOW_REFERENCE.OPENER };\n }\n\n if (isSameDomain(targetWindow) && !isTop(targetWindow)) {\n const windowName = assertSameDomain(targetWindow).name;\n if (windowName) {\n return { type: WINDOW_REFERENCE.NAME, name: windowName };\n }\n }\n}\n\ntype UpdateChildWindowNameWithRefOptions = {|\n componentName : string,\n parentComponentWindow : CrossDomainWindowType\n|};\n\nexport function updateChildWindowNameWithRef({ componentName, parentComponentWindow } : UpdateChildWindowNameWithRefOptions) {\n const { serializedInitialPayload } = parseWindowName(window.name);\n\n const { data, sender, reference, metaData } = crossDomainDeserialize({\n data: serializedInitialPayload,\n sender: {\n win: parentComponentWindow\n },\n basic: true\n });\n\n if (reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL) {\n const windowRef = getWindowRef(parentComponentWindow);\n\n const { serializedData: serializedPayload } = crossDomainSerialize({\n data,\n metaData: {\n windowRef\n },\n sender: {\n domain: sender.domain\n },\n receiver: {\n win: window,\n domain: getDomain()\n },\n basic: true\n });\n\n window.name = buildChildWindowName({\n name: componentName,\n serializedPayload\n });\n }\n}\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport type { PropsDefinitionType, PropsType, ChildPropsType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\n// $FlowFixMe\nexport function normalizeChildProp(propsDef : PropsDefinitionType, props : PropsType

, key : string, value : ?T, helpers : ChildHelpers) : ?T {\n if (!propsDef.hasOwnProperty(key)) {\n return value;\n }\n\n const prop = propsDef[key];\n\n if (typeof prop.childDecorate === 'function') {\n const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings } = helpers;\n const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings });\n\n // $FlowFixMe\n return decoratedValue;\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps(parentComponentWindow : CrossDomainWindowType, propsDef : PropsDefinitionType, props : PropsType

, origin : string, helpers : ChildHelpers, isUpdate : boolean = false) : ChildPropsType {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(propsDef, props, key, props[key], helpers);\n\n result[key] = value;\n if (prop && prop.alias && !result[prop.alias]) {\n result[prop.alias] = value;\n }\n }\n\n if (!isUpdate) {\n for (const key of Object.keys(propsDef)) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(propsDef, props, key, undefined, helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType,\n onCloseWindow, assertSameDomain } from 'cross-domain-utils/src';\nimport { markWindowKnown, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, onResize, elementReady, noop } from 'belter/src';\n\nimport { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef } from '../lib';\nimport { CONTEXT } from '../constants';\nimport type { NormalizedComponentOptionsType, getSiblingsPropType } from '../component';\nimport type { PropsType, ChildPropsType } from '../component/props';\nimport type { StringMatcherType } from '../types';\n\nimport { normalizeChildProps } from './props';\n\nexport type ChildExportsType

= {|\n updateProps : CrossDomainFunctionType<[ PropsType

], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers = {|\n uid : string,\n tag : string,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n onProps : ((PropsType

) => void) => {| cancel : () => void |},\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise,\n getSiblings : getSiblingsPropType\n|};\n\nfunction checkParentDomain(allowedParentDomains : StringMatcherType, domain : string) {\n if (!matchDomain(allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n}\n\nfunction focus() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n}\n\nfunction destroy() : ZalgoPromise {\n return ZalgoPromise.try(() => {\n window.close();\n });\n}\n\nexport type ChildComponent = {|\n getProps : () => ChildPropsType,\n init : () => ZalgoPromise\n|};\n\nexport function childComponent(options : NormalizedComponentOptionsType) : ChildComponent {\n const { tag, propsDef, autoResize, allowedParentDomains } = options;\n\n const onPropHandlers = [];\n\n const { parent, payload } = getInitialParentPayload();\n const { win: parentComponentWindow, domain: parentDomain } = parent;\n\n let props : ChildPropsType;\n const exportsPromise = new ZalgoPromise();\n\n const { version, uid, exports: parentExports, context, props: initialProps } = payload;\n\n if (version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit } = parentExports;\n\n const getParent = () => parentComponentWindow;\n const getParentDomain = () => parentDomain;\n \n const onProps = (handler : Function) => {\n onPropHandlers.push(handler);\n return {\n cancel: () => {\n onPropHandlers.splice(onPropHandlers.indexOf(handler), 1);\n }\n };\n };\n\n const resize = ({ width, height } : {| width : ?number, height : ?number |}) : ZalgoPromise => {\n return parentResize.fireAndForget({ width, height });\n };\n\n const xport = (xports : X) : ZalgoPromise => {\n exportsPromise.resolve(xports);\n return parentExport(xports);\n };\n\n const getSiblings = ({ anyParent } = {}) => {\n const result = [];\n const currentParent = props.parent;\n\n if (typeof anyParent === 'undefined') {\n anyParent = !currentParent;\n }\n\n if (!anyParent && !currentParent) {\n throw new Error(`No parent found for ${ tag } child`);\n }\n\n for (const win of getAllFramesInWindow(window)) {\n if (!isSameDomain(win)) {\n continue;\n }\n\n const xprops : ChildPropsType = assertSameDomain(win).xprops;\n\n if (!xprops || getParent() !== xprops.getParent()) {\n continue;\n }\n\n const winParent = xprops.parent;\n\n if (!anyParent && currentParent) {\n if (!winParent || winParent.uid !== currentParent.uid) {\n continue;\n }\n }\n\n const xports = tryGlobal(win, global => global.exports);\n\n result.push({\n props: xprops,\n exports: xports\n });\n }\n\n return result;\n };\n\n const getHelpers = () : ChildHelpers => {\n return {\n tag, show, hide, close, focus, onError, resize, getSiblings,\n onProps, getParent, getParentDomain, uid, export: xport\n };\n };\n\n const watchForClose = () => {\n window.addEventListener('beforeunload', () => {\n checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n checkClose.fireAndForget();\n });\n\n onCloseWindow(parentComponentWindow, () => {\n destroy();\n });\n };\n\n const setProps = (newProps : PropsType

, origin : string, isUpdate : boolean = false) => {\n const helpers = getHelpers();\n const normalizedProps = normalizeChildProps(parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate);\n\n if (props) {\n extend(props, normalizedProps);\n } else {\n props = normalizedProps;\n }\n\n for (const handler of onPropHandlers) {\n handler(props);\n }\n };\n \n const getAutoResize = () : ZalgoPromise<{| width : boolean, height : boolean, element : ?HTMLElement |}> => {\n const { width = false, height = false, element: elementRef = 'body' } = autoResize;\n return elementReady(elementRef).catch(noop).then(element => {\n return { width, height, element };\n });\n };\n\n const watchForResize = () : ?ZalgoPromise => {\n return getAutoResize().then(({ width, height, element }) => {\n if (!element || (!width && !height) || context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n };\n\n const updateProps = (newProps : (PropsType

)) : ZalgoPromise => {\n return ZalgoPromise.try(() => setProps(newProps, parentDomain, true));\n };\n\n const init = () => {\n return ZalgoPromise.try(() => {\n if (isSameDomain(parentComponentWindow)) {\n updateChildWindowNameWithRef({\n componentName: options.name,\n parentComponentWindow\n });\n }\n\n getGlobal(window).exports = options.exports({\n getExports: () => exportsPromise\n });\n\n checkParentDomain(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n watchForClose();\n\n return parentInit({ updateProps, close: destroy });\n \n }).then(() => {\n return watchForResize();\n \n }).catch(err => {\n onError(err);\n });\n };\n\n const getProps = () => {\n if (props) {\n return props;\n } else {\n setProps(initialProps, parentDomain);\n return props;\n }\n };\n\n return {\n init,\n getProps\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop, type EventEmitterType } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType, isWindowClosed, isSameDomain } from 'cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport type { CssDimensionsType } from '../types';\nimport { PROP_SERIALIZATION, PROP_TYPE } from '../constants';\n\nexport type EventHandlerType = (T) => void | ZalgoPromise;\nexport type Sibling = {|\n props : mixed,\n exports : mixed\n|};\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type uidPropType = string;\nexport type tagPropType = string;\nexport type closePropType = () => ZalgoPromise;\nexport type focusPropType = () => ZalgoPromise;\nexport type showPropType = () => ZalgoPromise;\nexport type exportPropType = (X) => ZalgoPromise;\nexport type getSiblingsPropType = (opts? : {| anyParent? : boolean |}) => $ReadOnlyArray;\nexport type hidePropType = () => ZalgoPromise;\nexport type resizePropType = ({| width : ?number, height : ?number |}) => ZalgoPromise;\nexport type getParentPropType = () => CrossDomainWindowType;\nexport type getParentDomainPropType = () => string;\nexport type contextPropType = string;\n\nexport type onDisplayPropType = EventHandlerType;\nexport type onRenderedPropType = EventHandlerType;\nexport type onRenderPropType = EventHandlerType;\nexport type onClosePropType = EventHandlerType;\nexport type onDestroyPropType = EventHandlerType;\nexport type onResizePropType = EventHandlerType;\nexport type onFocusPropType = EventHandlerType;\nexport type onErrorPropType = EventHandlerType;\nexport type onPropsPropType

= ((PropsType

) => void) => {| cancel : () => void |}; // eslint-disable-line no-use-before-define\n\nexport type ParentPropType = {|\n uid : string,\n // eslint-disable-next-line no-use-before-define\n props : PropsType

,\n export : exportPropType\n|};\n\nexport type PropsInputType

= {|\n parent? : ParentPropType,\n \n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : ?cspNoncePropType,\n context? : ?contextPropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onDestroy? : onDestroyPropType,\n onResize? : onResizePropType,\n onFocus? : onFocusPropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType

,\n\n ...P\n|};\n\nexport type PropsType

= {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n cspNonce? : ?cspNoncePropType,\n context? : ?contextPropType,\n dimensions : CssDimensionsType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onDestroy : onDestroyPropType,\n onResize : onResizePropType,\n onFocus : onFocusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n \n ...P\n|};\n\ntype onErrorChildPropType = (mixed) => ZalgoPromise;\n\nexport type ChildPropsType = {|\n ...PropsType

,\n\n parent? : ParentPropType,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getParent : getParentPropType,\n getParentDomain : getParentDomainPropType,\n resize : resizePropType,\n onError : onErrorChildPropType,\n onProps : onPropsPropType

,\n getSiblings : getSiblingsPropType\n|};\n\nexport type PropDefinitionType, X> = {|\n type : S,\n alias? : string,\n value? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n default? : ({|\n props : P,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => ?T,\n decorate? : ({|\n value : T,\n props : PropsType

,\n state : Object,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n container : HTMLElement | void,\n event : EventEmitterType\n |}) => T,\n childDecorate? : ({|\n value : ?T,\n uid : uidPropType,\n tag : tagPropType,\n close : closePropType,\n focus : focusPropType,\n onError : onErrorPropType,\n onProps : onPropsPropType

,\n resize : resizePropType,\n getParentDomain : getParentDomainPropType,\n getParent : getParentPropType,\n show : showPropType,\n hide : hidePropType,\n export : exportPropType,\n getSiblings : getSiblingsPropType\n |}) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n bodyParam? : boolean | string | ({| value : T |}) => (string | ZalgoPromise),\n // eslint-disable-next-line no-undef\n queryValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n // eslint-disable-next-line no-undef\n bodyValue? : ({| value : T |}) => (ZalgoPromise | R | string),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({| value : T, props : PropsType

|}) => void,\n sameDomain? : boolean,\n serialization? : $Values\n|};\n\nexport type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN;\nexport type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING;\nexport type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER;\nexport type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION;\nexport type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY;\nexport type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT;\n\nexport type DEFINITION_TYPE =\n BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE |\n FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE;\n\n\nexport type BooleanPropDefinitionType = PropDefinitionType;\nexport type StringPropDefinitionType = PropDefinitionType;\nexport type NumberPropDefinitionType = PropDefinitionType;\nexport type FunctionPropDefinitionType = PropDefinitionType;\nexport type ArrayPropDefinitionType | $ReadOnlyArray<*>, P, X> = PropDefinitionType; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType = PropDefinitionType;\n\nexport type MixedPropDefinitionType =\n BooleanPropDefinitionType<*, P, X> |\n StringPropDefinitionType<*, P, X> |\n NumberPropDefinitionType<*, P, X> |\n FunctionPropDefinitionType<*, P, X> |\n ObjectPropDefinitionType<*, P, X> |\n ArrayPropDefinitionType<*, P, X>;\n\nexport type UserPropsDefinitionType = {|\n [string] : MixedPropDefinitionType\n|};\n\nexport type BuiltInPropsDefinitionType = {|\n timeout : NumberPropDefinitionType,\n window : ObjectPropDefinitionType,\n close : FunctionPropDefinitionType,\n focus : FunctionPropDefinitionType,\n resize : FunctionPropDefinitionType,\n uid : StringPropDefinitionType,\n tag : StringPropDefinitionType,\n cspNonce : StringPropDefinitionType,\n getParent : FunctionPropDefinitionType,\n getParentDomain : FunctionPropDefinitionType,\n hide : FunctionPropDefinitionType,\n show : FunctionPropDefinitionType,\n export : FunctionPropDefinitionType, P, X>,\n getSiblings : FunctionPropDefinitionType,\n context : StringPropDefinitionType,\n\n onDisplay : FunctionPropDefinitionType,\n onRendered : FunctionPropDefinitionType,\n onRender : FunctionPropDefinitionType,\n onClose : FunctionPropDefinitionType,\n onDestroy : FunctionPropDefinitionType,\n onResize : FunctionPropDefinitionType,\n onFocus : FunctionPropDefinitionType,\n onError : FunctionPropDefinitionType,\n onProps : FunctionPropDefinitionType, P, X>\n|};\n\nexport type PropsDefinitionType = {|\n ...BuiltInPropsDefinitionType,\n [ string ] : MixedPropDefinitionType\n|};\n\nconst defaultNoop = () => noop;\n// eslint-disable-next-line flowtype/require-exact-type\nconst decorateOnce = ({ value } : { value : F }) : F => once(value);\n\nexport function getBuiltInProps() : BuiltInPropsDefinitionType {\n return {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate: ({ value }) => {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n\n if (isWindow(value)) {\n // $FlowFixMe\n if (isWindowClosed(value)) {\n throw new Error(`Window is closed`);\n }\n\n // $FlowFixMe\n if (!isSameDomain(value)) {\n throw new Error(`Window is not same domain`);\n }\n }\n },\n decorate: ({ value }) => {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: false,\n sendToChild: false\n },\n\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n context: {\n type: PROP_TYPE.STRING,\n required: false\n },\n\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop\n },\n\n close: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n uid: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ uid }) => uid\n },\n\n tag: {\n type: PROP_TYPE.STRING,\n required: false,\n sendToChild: false,\n childDecorate: ({ tag }) => tag\n },\n\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n show: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ show }) => show\n },\n\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ hide }) => hide\n },\n\n export: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ 'export': xport }) => xport\n },\n\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ onProps }) => onProps\n },\n\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: false,\n sendToChild: false,\n childDecorate: ({ getSiblings }) => getSiblings\n }\n };\n}\n\ntype PropCallback =\n ((string, BooleanPropDefinitionType | void, boolean) => R) &\n ((string, StringPropDefinitionType | void, string) => R) &\n ((string, NumberPropDefinitionType | void, number) => R) &\n ((string, FunctionPropDefinitionType | void, Function) => R) &\n ((string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*>) => R) &\n ((string, ObjectPropDefinitionType | void, Object) => R);\n\nexport function eachProp(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) {\n // $FlowFixMe[cannot-spread-indexer]\n for (const key of Object.keys({ ...props, ...propsDef })) {\n const propDef = propsDef[key];\n const value = props[key];\n\n // $FlowFixMe[incompatible-call]\n handler(key, propDef, value);\n }\n}\n\nexport function mapProps(props : PropsType

, propsDef : PropsDefinitionType, handler : PropCallback) : $ReadOnlyArray {\n const results = [];\n\n eachProp(props, propsDef, (key, propDef, value) => {\n // $FlowFixMe[incompatible-call]\n const result = handler(key, propDef, value);\n results.push(result);\n });\n return results;\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, base64encode, noop } from 'belter/src';\n\nimport { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION, METHOD, PROP_TYPE } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\nexport function extendProps(propsDef : PropsDefinitionType, existingProps : PropsType

, inputProps : PropsInputType

, helpers : ParentHelpers

, container : HTMLElement | void) {\n const { state, close, focus, event, onError } = helpers;\n\n // $FlowFixMe\n eachProp(inputProps, propsDef, (key, propDef, val) => {\n let valueDetermined = false;\n let value = val;\n\n const getDerivedValue = () => {\n if (!propDef) {\n return value;\n }\n\n const alias = propDef.alias;\n if (alias && !isDefined(val) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n \n if (propDef.value) {\n value = propDef.value({ props: existingProps, state, close, focus, event, onError, container });\n }\n \n if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) {\n value = propDef.default({ props: existingProps, state, close, focus, event, onError, container });\n }\n\n if (isDefined(value)) {\n if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n } else {\n if (propDef.required !== false && !isDefined(inputProps[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n \n if (__DEBUG__ && isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props: inputProps });\n }\n\n if (isDefined(value) && propDef.decorate) {\n // $FlowFixMe\n value = propDef.decorate({ value, props: existingProps, state, close, focus, event, onError, container });\n }\n\n return value;\n };\n\n const getter = () => {\n if (valueDetermined) {\n return value;\n }\n\n valueDetermined = true;\n return getDerivedValue();\n };\n\n Object.defineProperty(existingProps, key, {\n configurable: true,\n enumerable: true,\n get: getter\n });\n });\n\n // $FlowFixMe\n eachProp(existingProps, propsDef, noop);\n}\n\nexport function serializeProps(propsDef : PropsDefinitionType, props : (PropsType

), method : $Values) : ZalgoPromise<{ [string] : string | boolean }> {\n\n const params = {};\n\n return ZalgoPromise.all(mapProps(props, propsDef, (key, propDef, value) => {\n return ZalgoPromise.resolve().then(() => {\n\n if (value === null || typeof value === 'undefined' || !propDef) {\n return;\n }\n\n const getParam = {\n [ METHOD.GET ]: propDef.queryParam,\n [ METHOD.POST ]: propDef.bodyParam\n }[method];\n\n const getValue = {\n [ METHOD.GET ]: propDef.queryValue,\n [ METHOD.POST ]: propDef.bodyValue\n }[method];\n \n if (!getParam) {\n return;\n }\n\n return ZalgoPromise.hash({\n\n finalParam: ZalgoPromise.try(() => {\n if (typeof getParam === 'function') {\n // $FlowFixMe[incompatible-call]\n return getParam({ value });\n } else if (typeof getParam === 'string') {\n return getParam;\n } else {\n return key;\n }\n }),\n \n finalValue: ZalgoPromise.try(() => {\n if (typeof getValue === 'function' && isDefined(value)) {\n // $FlowFixMe[incompatible-call]\n // $FlowFixMe[incompatible-return]\n return getValue({ value });\n } else {\n // $FlowFixMe[incompatible-return]\n return value;\n }\n })\n\n }).then(({ finalParam, finalValue }) => {\n\n let result;\n\n if (typeof finalValue === 'boolean') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'string') {\n result = finalValue.toString();\n } else if (typeof finalValue === 'object' && finalValue !== null) {\n\n if (propDef.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(finalValue);\n } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) {\n result = base64encode(JSON.stringify(finalValue));\n } else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = dotify(finalValue, key);\n\n for (const dotkey of Object.keys(result)) {\n params[dotkey] = result[dotkey];\n }\n\n return;\n }\n\n } else if (typeof finalValue === 'number') {\n result = finalValue.toString();\n }\n\n params[finalParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow,\n type DomainMatcher } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType,\n noop, onResize, extendUrl, appendChild, cleanup,\n once, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed,\n awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD,\n WINDOW_REFERENCE, DEFAULT_DIMENSIONS } from '../constants';\nimport { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { CssDimensionsType, ContainerReferenceType } from '../types';\nimport type { NormalizedComponentOptionsType, AttributesType } from '../component';\n\nimport { serializeProps, extendProps } from './props';\n\nexport type RenderOptionsType

= {|\n uid : string,\n props : PropsType

,\n tag : string,\n context : $Values,\n close : (?string) => ZalgoPromise,\n focus : () => ZalgoPromise,\n doc : Document,\n container? : HTMLElement,\n dimensions : CssDimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType = {|\n init : (ChildExportsType

) => ZalgoPromise,\n close : () => ZalgoPromise,\n checkClose : CrossDomainFunctionType<[], boolean>,\n resize : CrossDomainFunctionType<[{| width? : ?number, height? : ?number |}], void>,\n onError : (mixed) => ZalgoPromise,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise,\n export : (X) => ZalgoPromise\n|};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCE.OPENER |} |\n {| type : typeof WINDOW_REFERENCE.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCE.GLOBAL, uid : string |} |\n {| type : typeof WINDOW_REFERENCE.NAME, name : string |};\n\nexport type InitialChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values,\n childDomainMatch : DomainMatcher,\n props : PropsType

,\n exports : ParentExportsType\n|};\n\nexport type InitialChildPayloadMetadata = {|\n windowRef : WindowRef\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers

= {|\n state : StateType,\n close : () => ZalgoPromise,\n focus : () => ZalgoPromise,\n resize : ({| width : ?number, height : ?number |}) => ZalgoPromise,\n onError : (mixed) => ZalgoPromise,\n updateProps : PropsInputType

=> ZalgoPromise,\n event : EventEmitterType,\n show : () => ZalgoPromise,\n hide : () => ZalgoPromise\n|};\n\nfunction getDefaultProps

() : PropsType

{\n // $FlowFixMe\n return {};\n}\n\ntype InternalState = {|\n visible : boolean\n|};\n\ntype Rerender = () => ZalgoPromise;\n\ntype RenderContainerOptions = {|\n context : $Values,\n proxyFrame : ?ProxyObject,\n proxyPrerenderFrame : ?ProxyObject,\n rerender : Rerender\n|};\n\ntype ResolveInitPromise = () => ZalgoPromise;\ntype RejectInitPromise = (mixed) => ZalgoPromise;\ntype GetProxyContainer = (container : ContainerReferenceType) => ZalgoPromise>;\ntype Show = () => ZalgoPromise;\ntype Hide = () => ZalgoPromise;\ntype Close = () => ZalgoPromise;\ntype OnError = (mixed) => ZalgoPromise;\ntype RenderContainer = (proxyContainer : ProxyObject, RenderContainerOptions) => ZalgoPromise>;\ntype SetProxyWin = (ProxyWindow) => ZalgoPromise;\ntype GetProxyWindow = () => ZalgoPromise;\ntype OpenFrame = (context : $Values, {| windowName : string |}) => ZalgoPromise>;\ntype OpenPrerenderFrame = (context : $Values) => ZalgoPromise>;\ntype Prerender = (proxyPrerenderWin : ProxyWindow, {| context : $Values|}) => ZalgoPromise;\ntype Open = (context : $Values, {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) => ZalgoPromise;\ntype OpenPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) => ZalgoPromise;\ntype WatchForUnload = () => ZalgoPromise;\ntype GetInternalState = () => ZalgoPromise;\ntype SetInternalState = (InternalState) => ZalgoPromise;\n\ntype ParentDelegateOverrides

= {|\n props : PropsType

,\n event : EventEmitterType,\n close : Close,\n onError : OnError,\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload,\n getInternalState : GetInternalState,\n setInternalState : SetInternalState,\n resolveInitPromise : ResolveInitPromise,\n rejectInitPromise : RejectInitPromise\n|};\n\ntype DelegateOverrides = {|\n getProxyContainer : GetProxyContainer,\n show : Show,\n hide : Hide,\n renderContainer : RenderContainer,\n getProxyWindow : GetProxyWindow,\n setProxyWin : SetProxyWin,\n openFrame : OpenFrame,\n openPrerenderFrame : OpenPrerenderFrame,\n prerender : Prerender,\n open : Open,\n openPrerender : OpenPrerender,\n watchForUnload : WatchForUnload\n|};\n\ntype RenderOptions = {|\n target : CrossDomainWindowType,\n container : ContainerReferenceType,\n context : $Values,\n rerender : Rerender\n|};\n\ntype ParentComponent = {|\n init : () => void,\n render : (RenderOptions) => ZalgoPromise,\n getProps : () => PropsType

,\n setProps : (newProps : PropsInputType

, isUpdate? : boolean) => void,\n export : (X) => ZalgoPromise,\n destroy : (err? : mixed) => ZalgoPromise,\n getHelpers : () => ParentHelpers

,\n getDelegateOverrides : () => ZalgoPromise,\n getExports : () => X\n|};\n\nconst getDefaultOverrides =

() : ParentDelegateOverrides

=> {\n // $FlowFixMe\n return {};\n};\n\ntype ParentOptions = {|\n uid : string,\n options : NormalizedComponentOptionsType,\n overrides? : ParentDelegateOverrides

,\n parentWin? : CrossDomainWindowType\n|};\n\nexport function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window } : ParentOptions) : ParentComponent {\n const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports } = options;\n\n const initPromise = new ZalgoPromise();\n const handledErrors = [];\n const clean = cleanup();\n const state = {};\n const inputProps = {};\n let internalState = {\n visible: true\n };\n const event = overrides.event ? overrides.event : eventEmitter();\n const props : PropsType

= overrides.props ? overrides.props : getDefaultProps();\n\n let currentProxyWin : ?ProxyWindow;\n let currentProxyContainer : ?ProxyObject;\n let childComponent : ?ChildExportsType

;\n let currentChildDomain : ?string;\n let currentContainer : HTMLElement | void;\n\n const onErrorOverride : ?OnError = overrides.onError;\n let getProxyContainerOverride : ?GetProxyContainer = overrides.getProxyContainer;\n let showOverride : ?Show = overrides.show;\n let hideOverride : ?Hide = overrides.hide;\n const closeOverride : ?Close = overrides.close;\n let renderContainerOverride : ?RenderContainer = overrides.renderContainer;\n let getProxyWindowOverride : ?GetProxyWindow = overrides.getProxyWindow;\n let setProxyWinOverride : ?SetProxyWin = overrides.setProxyWin;\n let openFrameOverride : ?OpenFrame = overrides.openFrame;\n let openPrerenderFrameOverride : ?OpenPrerenderFrame = overrides.openPrerenderFrame;\n let prerenderOverride : ?Prerender = overrides.prerender;\n let openOverride : ?Open = overrides.open;\n let openPrerenderOverride : ?OpenPrerender = overrides.openPrerender;\n let watchForUnloadOverride : ?WatchForUnload = overrides.watchForUnload;\n const getInternalStateOverride : ?GetInternalState = overrides.getInternalState;\n const setInternalStateOverride : ?SetInternalState = overrides.setInternalState;\n\n const getDimensions = () : CssDimensionsType => {\n if (typeof dimensions === 'function') {\n return dimensions({ props });\n }\n return dimensions;\n };\n\n const resolveInitPromise = () => {\n return ZalgoPromise.try(() => {\n if (overrides.resolveInitPromise) {\n return overrides.resolveInitPromise();\n }\n\n return initPromise.resolve();\n });\n };\n\n const rejectInitPromise = (err : mixed) => {\n return ZalgoPromise.try(() => {\n if (overrides.rejectInitPromise) {\n return overrides.rejectInitPromise(err);\n }\n\n return initPromise.reject(err);\n });\n };\n\n const getPropsForChild = (initialChildDomain : string) : ZalgoPromise> => {\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = propsDef[key];\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(initialChildDomain, getDomain(window))) {\n continue;\n }\n \n result[key] = props[key];\n }\n\n // $FlowFixMe\n return ZalgoPromise.hash(result);\n };\n\n const setupEvents = () => {\n event.on(EVENT.RENDER, () => props.onRender());\n event.on(EVENT.DISPLAY, () => props.onDisplay());\n event.on(EVENT.RENDERED, () => props.onRendered());\n event.on(EVENT.CLOSE, () => props.onClose());\n event.on(EVENT.DESTROY, () => props.onDestroy());\n event.on(EVENT.RESIZE, () => props.onResize());\n event.on(EVENT.FOCUS, () => props.onFocus());\n event.on(EVENT.PROPS, (newProps) => props.onProps(newProps));\n event.on(EVENT.ERROR, err => {\n if (props && props.onError) {\n return props.onError(err);\n } else {\n return rejectInitPromise(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n\n clean.register(event.reset);\n };\n\n const getInternalState = () => {\n return ZalgoPromise.try(() => {\n if (getInternalStateOverride) {\n return getInternalStateOverride();\n }\n\n return internalState;\n });\n };\n\n const setInternalState = (newInternalState) => {\n return ZalgoPromise.try(() => {\n if (setInternalStateOverride) {\n return setInternalStateOverride(newInternalState);\n }\n\n internalState = { ...internalState, ...newInternalState };\n return internalState;\n });\n };\n\n const getProxyWindow = () : ZalgoPromise => {\n if (getProxyWindowOverride) {\n return getProxyWindowOverride();\n }\n\n return ZalgoPromise.try(() => {\n const windowProp = props.window;\n\n if (windowProp) {\n const proxyWin = toProxyWindow(windowProp);\n clean.register(() => windowProp.close());\n return proxyWin;\n }\n\n return new ProxyWindow({ send });\n });\n };\n\n const setProxyWin = (proxyWin : ProxyWindow) : ZalgoPromise => {\n if (setProxyWinOverride) {\n return setProxyWinOverride(proxyWin);\n }\n\n return ZalgoPromise.try(() => {\n currentProxyWin = proxyWin;\n });\n };\n\n const show = () : ZalgoPromise => {\n if (showOverride) {\n return showOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: true }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(noop);\n };\n\n const hide = () : ZalgoPromise => {\n if (hideOverride) {\n return hideOverride();\n }\n\n return ZalgoPromise.hash({\n setState: setInternalState({ visible: false }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(noop);\n };\n\n const getUrl = () : string => {\n if (typeof url === 'function') {\n return url({ props });\n }\n\n return url;\n };\n\n const getAttributes = () : AttributesType => {\n if (typeof attributes === 'function') {\n return attributes({ props });\n }\n\n return attributes;\n };\n\n const buildQuery = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.GET);\n };\n\n const buildBody = () : ZalgoPromise<{| [string] : string | boolean |}> => {\n return serializeProps(propsDef, props, METHOD.POST);\n };\n\n const buildUrl = () : ZalgoPromise => {\n return buildQuery().then(query => {\n return extendUrl(normalizeMockUrl(getUrl()), { query });\n });\n };\n\n const getInitialChildDomain = () : string => {\n return getDomainFromUrl(getUrl());\n };\n\n const getDomainMatcher = () : DomainMatcher => {\n if (domainMatch) {\n return domainMatch;\n }\n\n return getInitialChildDomain();\n };\n\n const openFrame = (context : $Values, { windowName } : {| windowName : string |}) : ZalgoPromise> => {\n if (openFrameOverride) {\n return openFrameOverride(context, { windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n title: name,\n ...getAttributes().iframe\n };\n\n return getProxyObject(iframe({ attributes: attrs }));\n }\n });\n };\n\n const openPrerenderFrame = (context : $Values) : ZalgoPromise> => {\n if (openPrerenderFrameOverride) {\n return openPrerenderFrameOverride(context);\n }\n\n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n // $FlowFixMe\n const attrs = {\n name: `__${ ZOID }_prerender_frame__${ name }_${ uniqueID() }__`,\n title: `prerender__${ name }`,\n ...getAttributes().iframe\n };\n return getProxyObject(iframe({\n attributes: attrs\n }));\n }\n });\n };\n \n const openPrerender = (context : $Values, proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject) : ZalgoPromise => {\n if (openPrerenderOverride) {\n return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame);\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n clean.register(() => destroyElement(prerenderFrame));\n \n return awaitFrameWindow(prerenderFrame).then(prerenderFrameWindow => {\n return assertSameDomain(prerenderFrameWindow);\n }).then(win => {\n return toProxyWindow(win);\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n return proxyWin;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n });\n };\n\n const focus = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n if (currentProxyWin) {\n return ZalgoPromise.all([\n event.trigger(EVENT.FOCUS),\n currentProxyWin.focus()\n ]).then(noop);\n }\n });\n };\n\n const getCurrentWindowReferenceUID = () : string => {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register(() => {\n delete global.windows[uid];\n });\n return uid;\n };\n\n const getWindowRef = (target : CrossDomainWindowType, initialChildDomain : string, context : $Values, proxyWin : ProxyWindow) : WindowRef => {\n if (initialChildDomain === getDomain(window)) {\n return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID() };\n }\n\n if (target !== window) {\n throw new Error(`Can not construct cross-domain window reference for different target window`);\n }\n\n if (props.window) {\n const actualComponentWindow = proxyWin.getWindow();\n if (!actualComponentWindow) {\n throw new Error(`Can not construct cross-domain window reference for lazy window prop`);\n }\n\n if (getAncestor(actualComponentWindow) !== window) {\n throw new Error(`Can not construct cross-domain window reference for window prop with different ancestor`);\n }\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCE.OPENER };\n } else if (context === CONTEXT.IFRAME) {\n return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window) };\n }\n\n throw new Error(`Can not construct window reference for child`);\n };\n\n const runTimeout = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const timeout = props.timeout;\n\n if (timeout) {\n return initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n };\n\n const initChild = (childDomain : string, childExports : ChildExportsType

) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n currentChildDomain = childDomain;\n childComponent = childExports;\n resolveInitPromise();\n clean.register(() => childExports.close.fireAndForget().catch(noop));\n });\n };\n\n const resize = ({ width, height } : {| width? : ?number, height? : ?number |}) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n event.trigger(EVENT.RESIZE, { width, height });\n });\n };\n\n const destroy = (err : mixed) : ZalgoPromise => {\n // eslint-disable-next-line promise/no-promise-in-callback\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.DESTROY);\n }).catch(noop).then(() => {\n return clean.all(err);\n }).then(() => {\n initPromise.asyncReject(err || new Error('Component destroyed'));\n });\n };\n\n const close = memoize((err? : mixed) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n\n if (closeOverride) {\n // $FlowFixMe\n const source = closeOverride.__source__;\n\n if (isWindowClosed(source)) {\n return;\n }\n\n return closeOverride();\n }\n\n return ZalgoPromise.try(() => {\n return event.trigger(EVENT.CLOSE);\n }).then(() => {\n return destroy(err || new Error(`Component closed`));\n });\n });\n });\n\n const open = (context : $Values, { proxyWin, proxyFrame, windowName } : {| proxyWin : ProxyWindow, proxyFrame : ?ProxyObject, windowName : string |}) : ZalgoPromise => {\n if (openOverride) {\n return openOverride(context, { proxyWin, proxyFrame, windowName });\n }\n \n return ZalgoPromise.try(() => {\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n if (!proxyFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyFrame.get().then(frame => {\n return awaitFrameWindow(frame).then(win => {\n clean.register(() => destroyElement(frame));\n clean.register(() => cleanUpWindow(win));\n return win;\n });\n });\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = getDimensions();\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n // $FlowFixMe\n const attrs = {\n name: windowName,\n width,\n height,\n ...getAttributes().popup\n };\n \n const win = popup('', attrs);\n \n clean.register(() => closeWindow(win));\n clean.register(() => cleanUpWindow(win));\n\n return win;\n } else {\n throw new Error(`No render context available for ${ context }`);\n }\n\n }).then(win => {\n proxyWin.setWindow(win, { send });\n return proxyWin.setName(windowName).then(() => {\n return proxyWin;\n });\n });\n };\n\n const watchForUnload = () => {\n return ZalgoPromise.try(() => {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n destroy(new Error(`Window navigated away`));\n }));\n \n const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n\n if (watchForUnloadOverride) {\n return watchForUnloadOverride();\n }\n });\n };\n\n const watchForClose = (proxyWin : ProxyWindow, context : $Values) : ZalgoPromise => {\n let cancelled = false;\n\n clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (!cancelled) {\n if (isClosed) {\n return close(new Error(`Detected ${ context } close`));\n } else {\n return watchForClose(proxyWin, context);\n }\n }\n });\n };\n\n const checkWindowClose = (proxyWin : ProxyWindow) : ZalgoPromise => {\n let closed = false;\n \n return proxyWin.isClosed().then(isClosed => {\n if (isClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n\n return ZalgoPromise.delay(200)\n .then(() => proxyWin.isClosed())\n .then(secondIsClosed => {\n if (secondIsClosed) {\n closed = true;\n return close(new Error(`Detected component window close`));\n }\n });\n }).then(() => {\n return closed;\n });\n };\n\n const onError = (err : mixed) : ZalgoPromise => {\n if (onErrorOverride) {\n return onErrorOverride(err);\n }\n\n return ZalgoPromise.try(() => {\n if (handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n handledErrors.push(err);\n initPromise.asyncReject(err);\n\n return event.trigger(EVENT.ERROR, err);\n });\n };\n\n const exportsPromise : ZalgoPromise = new ZalgoPromise();\n\n const getExports = () : X => {\n return xports({\n getExports: () => exportsPromise\n });\n };\n\n const xport = (actualExports : X) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n exportsPromise.resolve(actualExports);\n });\n };\n\n initChild.onError = onError;\n\n const buildParentExports = (win : ProxyWindow) : ParentExportsType => {\n const checkClose = () => checkWindowClose(win);\n function init(childExports : ChildExportsType

) : ZalgoPromise {\n return initChild(this.origin, childExports);\n }\n return { init, close, checkClose, resize, onError, show, hide, export: xport };\n };\n\n const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, context : $Values|} = {}) : ZalgoPromise> => {\n return getPropsForChild(initialChildDomain).then(childProps => {\n return {\n uid,\n context,\n tag,\n childDomainMatch,\n version: __ZOID__.__VERSION__,\n props: childProps,\n exports: buildParentExports(proxyWin)\n };\n });\n };\n\n const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|} = {}) : ZalgoPromise => {\n return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context }).then(childPayload => {\n const { serializedData, cleanReference } = crossDomainSerialize({\n data: childPayload,\n metaData: {\n windowRef: getWindowRef(target, initialChildDomain, context, proxyWin)\n },\n sender: {\n domain: getDomain(window)\n },\n receiver: {\n win: proxyWin,\n domain: childDomainMatch\n },\n passByReference: initialChildDomain === getDomain()\n });\n\n clean.register(cleanReference);\n return serializedData;\n });\n };\n\n const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context } : {| proxyWin : ProxyWindow, initialChildDomain : string, childDomainMatch : DomainMatcher, target : CrossDomainWindowType, context : $Values|}) : ZalgoPromise => {\n return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context }).then(serializedPayload => {\n return buildChildWindowName({ name, serializedPayload });\n });\n };\n\n const renderTemplate = (renderer : (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame } : {| context : $Values, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement |}) : ?HTMLElement => {\n \n return renderer({\n uid, container, context, doc, frame, prerenderFrame,\n focus, close, state, props, tag, dimensions: getDimensions(), event\n });\n };\n\n const prerender = (proxyPrerenderWin : ProxyWindow, { context } : {| context : $Values|}) : ZalgoPromise => {\n if (prerenderOverride) {\n return prerenderOverride(proxyPrerenderWin, { context });\n }\n \n return ZalgoPromise.try(() => {\n if (!prerenderTemplate) {\n return;\n }\n\n let prerenderWindow = proxyPrerenderWin.getWindow();\n\n if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {\n return;\n }\n\n prerenderWindow = assertSameDomain(prerenderWindow);\n \n const doc = prerenderWindow.document;\n const el = renderTemplate(prerenderTemplate, { context, doc });\n\n if (!el) {\n return;\n }\n\n if (el.ownerDocument !== doc) {\n throw new Error(`Expected prerender template to have been created with document from child window`);\n }\n\n writeElementToWindow(prerenderWindow, el);\n\n let { width = false, height = false, element = 'body' } = autoResize;\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n const prerenderResizeListener = onResize(element, ({ width: newWidth, height: newHeight }) => {\n resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n });\n };\n const renderContainer : RenderContainer = (proxyContainer : ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender } : RenderContainerOptions) : ZalgoPromise> => {\n\n if (renderContainerOverride) {\n return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender });\n }\n\n return ZalgoPromise.hash({\n container: proxyContainer.get(),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then(({ container, frame, prerenderFrame, internalState: { visible } }) => {\n const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n if (!visible) {\n hideElement(innerContainer);\n }\n appendChild(container, innerContainer);\n const containerWatcher = watchElementForClose(innerContainer, () => {\n const removeError = new Error(`Detected container element removed from DOM`);\n return ZalgoPromise.delay(1).then(() => {\n if (isElementClosed(innerContainer)) {\n close(removeError);\n } else {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n });\n });\n \n clean.register(() => containerWatcher.cancel());\n clean.register(() => destroyElement(innerContainer));\n currentProxyContainer = getProxyObject(innerContainer);\n return currentProxyContainer;\n }\n });\n };\n\n const getBridgeUrl = () : ?string => {\n if (typeof options.bridgeUrl === 'function') {\n return options.bridgeUrl({ props });\n }\n\n return options.bridgeUrl;\n };\n\n const openBridge = (proxyWin : ProxyWindow, initialChildDomain : string, context : $Values) : ?ZalgoPromise => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n return ZalgoPromise.try(() => {\n return proxyWin.awaitWindow();\n \n }).then(win => {\n if (!bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain)) {\n return;\n }\n\n const bridgeUrl = getBridgeUrl();\n\n if (!bridgeUrl) {\n throw new Error(`Bridge needed to render ${ context }`);\n }\n\n const bridgeDomain = getDomainFromUrl(bridgeUrl);\n bridge.linkUrl(win, initialChildDomain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n };\n\n const getHelpers = () : ParentHelpers

=> {\n return {\n state, event, close, focus, resize,\n // eslint-disable-next-line no-use-before-define\n onError, updateProps, show, hide\n };\n };\n\n const getProps = () => props;\n\n const getDefaultPropsInput = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const setProps = (newInputProps : PropsInputType

= getDefaultPropsInput()) => {\n if (__DEBUG__ && validate) {\n validate({ props: newInputProps });\n }\n\n const container = currentContainer;\n const helpers = getHelpers();\n extend(inputProps, newInputProps);\n\n // $FlowFixMe\n extendProps(propsDef, props, inputProps, helpers, container);\n };\n\n const updateProps = (newProps : PropsInputType

) : ZalgoPromise => {\n setProps(newProps);\n\n return initPromise.then(() => {\n const child = childComponent;\n const proxyWin = currentProxyWin;\n const childDomain = currentChildDomain;\n \n if (!child || !proxyWin || !childDomain) {\n return;\n }\n\n return getPropsForChild(childDomain).then(childProps => {\n return child.updateProps(childProps).catch(err => {\n return checkWindowClose(proxyWin).then(closed => {\n if (!closed) {\n throw err;\n }\n });\n });\n });\n });\n };\n\n const getProxyContainer : GetProxyContainer = (container : ContainerReferenceType) : ZalgoPromise> => {\n if (getProxyContainerOverride) {\n return getProxyContainerOverride(container);\n }\n\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n if (isShadowElement(containerElement)) {\n containerElement = insertShadowSlot(containerElement);\n }\n\n currentContainer = containerElement;\n return getProxyObject(containerElement);\n });\n };\n\n const delegate = (context : $Values, target : CrossDomainWindowType) : ZalgoPromise => {\n const delegateProps = {};\n for (const propName of Object.keys(props)) {\n const propDef = propsDef[propName];\n if (propDef && propDef.allowDelegate) {\n delegateProps[propName] = props[propName];\n }\n }\n\n const childOverridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ name }`, {\n uid,\n overrides: {\n props: delegateProps, event, close, onError, getInternalState,\n setInternalState, resolveInitPromise, rejectInitPromise\n }\n }).then(({ data: { parent } }) => {\n const parentComp : ParentComponent = parent;\n\n clean.register(err => {\n if (!isWindowClosed(target)) {\n return parentComp.destroy(err);\n }\n });\n return parentComp.getDelegateOverrides();\n\n }).catch(err => {\n throw new Error(`Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n${ stringifyError(err) }`);\n });\n\n getProxyContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyContainer(...args));\n renderContainerOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.renderContainer(...args));\n showOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.show(...args));\n hideOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.hide(...args));\n watchForUnloadOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.watchForUnload(...args));\n\n if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) {\n getProxyWindowOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.getProxyWindow(...args));\n openFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openFrame(...args));\n openPrerenderFrameOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerenderFrame(...args));\n prerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.prerender(...args));\n openOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.open(...args));\n openPrerenderOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.openPrerender(...args));\n } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) {\n setProxyWinOverride = (...args) => childOverridesPromise.then(childOverrides => childOverrides.setProxyWin(...args));\n }\n\n return childOverridesPromise;\n };\n\n const getDelegateOverrides = () : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n return {\n getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload,\n openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin\n };\n });\n };\n\n const checkAllowRender = (target : CrossDomainWindowType, childDomainMatch : DomainMatcher, container : ContainerReferenceType) => {\n if (target === window) {\n return;\n }\n\n if (!isSameTopWindow(window, target)) {\n throw new Error(`Can only renderTo an adjacent frame`);\n }\n\n const origin = getDomain();\n\n if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ childDomainMatch.toString() } - can only render to ${ origin }`);\n }\n\n if (container && typeof container !== 'string') {\n throw new Error(`Container passed to renderTo must be a string selector, got ${ typeof container } }`);\n }\n };\n\n const init = () => {\n setupEvents();\n };\n\n const render = ({ target, container, context, rerender } : RenderOptions) : ZalgoPromise => {\n return ZalgoPromise.try(() => {\n const initialChildDomain = getInitialChildDomain();\n const childDomainMatch = getDomainMatcher();\n \n checkAllowRender(target, childDomainMatch, container);\n\n const delegatePromise = ZalgoPromise.try(() => {\n if (target !== window) {\n return delegate(context, target);\n }\n });\n\n const windowProp = props.window;\n\n const watchForUnloadPromise = watchForUnload();\n \n const buildBodyPromise = buildBody();\n const onRenderPromise = event.trigger(EVENT.RENDER);\n\n const getProxyContainerPromise = getProxyContainer(container);\n const getProxyWindowPromise = getProxyWindow();\n\n const finalSetPropsPromise = getProxyContainerPromise.then(() => {\n return setProps();\n });\n\n const buildUrlPromise = finalSetPropsPromise.then(() => {\n return buildUrl();\n });\n\n const buildWindowNamePromise = getProxyWindowPromise.then(proxyWin => {\n return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context });\n });\n\n const openFramePromise = buildWindowNamePromise.then(windowName => openFrame(context, { windowName }));\n const openPrerenderFramePromise = openPrerenderFrame(context);\n\n const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender });\n }).then(proxyContainer => {\n return proxyContainer;\n });\n\n const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then(({ windowName, proxyWin, proxyFrame }) => {\n return windowProp\n ? proxyWin\n : open(context, { windowName, proxyWin, proxyFrame });\n });\n\n const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return openPrerender(context, proxyWin, proxyPrerenderFrame);\n });\n\n const setStatePromise = openPromise.then(proxyWin => {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n });\n \n const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then(({ proxyPrerenderWin }) => {\n return prerender(proxyPrerenderWin, { context });\n });\n\n const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then(({ proxyWin, windowName }) => {\n if (windowProp) {\n return proxyWin.setName(windowName);\n }\n });\n\n const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise }).then(({ body }) => {\n if (options.method) {\n return options.method;\n }\n\n if (Object.keys(body).length) {\n return METHOD.POST;\n }\n\n return METHOD.GET;\n });\n\n\n const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then(({ proxyWin, windowUrl, body, method }) => {\n return proxyWin.setLocation(windowUrl, { method, body });\n });\n\n const watchForClosePromise = openPromise.then(proxyWin => {\n watchForClose(proxyWin, context);\n });\n\n const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then(() => {\n return event.trigger(EVENT.DISPLAY);\n });\n\n const openBridgePromise = openPromise.then(proxyWin => {\n return openBridge(proxyWin, initialChildDomain, context);\n });\n\n const runTimeoutPromise = loadUrlPromise.then(() => {\n return runTimeout();\n });\n\n const onRenderedPromise = initPromise.then(() => {\n return event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash({\n initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise,\n openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise,\n openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n onError(err),\n destroy(err)\n ]).then(() => {\n throw err;\n }, () => {\n throw err;\n });\n }).then(noop);\n };\n\n return {\n init,\n render,\n destroy,\n getProps,\n setProps,\n export: xport,\n getHelpers,\n getDelegateOverrides,\n getExports\n };\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { destroyElement, toCSS } from 'belter/src';\n\nimport { type RenderOptionsType } from '../../parent/parent';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'zoid-visible',\n INVISIBLE: 'zoid-invisible'\n};\n\n\nexport function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions } : RenderOptionsType

) : ?HTMLElement {\n const { width, height } = dimensions;\n\n if (__ZOID__.__DEFAULT_CONTAINER__) {\n if (!frame || !prerenderFrame) {\n return;\n }\n\n const div = doc.createElement('div');\n div.setAttribute('id', uid);\n const style = doc.createElement('style');\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n style.appendChild(doc.createTextNode(`\n #${ uid } {\n display: inline-block;\n position: relative;\n width: ${ width };\n height: ${ height };\n }\n\n #${ uid } > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #${ uid } > iframe.${ CLASS.INVISIBLE } {\n opacity: 0;\n }\n\n #${ uid } > iframe.${ CLASS.VISIBLE } {\n opacity: 1;\n }\n `));\n\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n\n prerenderFrame.classList.add(CLASS.VISIBLE);\n frame.classList.add(CLASS.INVISIBLE);\n \n event.on(EVENT.RENDERED, () => {\n prerenderFrame.classList.remove(CLASS.VISIBLE);\n prerenderFrame.classList.add(CLASS.INVISIBLE);\n \n frame.classList.remove(CLASS.INVISIBLE);\n frame.classList.add(CLASS.VISIBLE);\n \n setTimeout(() => {\n destroyElement(prerenderFrame);\n }, 1);\n });\n\n event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => {\n if (typeof newWidth === 'number') {\n div.style.width = toCSS(newWidth);\n }\n \n if (typeof newHeight === 'number') {\n div.style.height = toCSS(newHeight);\n }\n });\n\n return div;\n }\n}\n","/* @flow */\n/* eslint react/react-in-jsx-scope: off */\n\nimport { type RenderOptionsType } from '../../parent/parent';\n\nexport function defaultPrerenderTemplate

({ doc, props } : RenderOptionsType

) : ?HTMLElement {\n if (__ZOID__.__DEFAULT_PRERENDER__) {\n const html = doc.createElement('html');\n const body = doc.createElement('body');\n const style = doc.createElement('style');\n const spinner = doc.createElement('div');\n spinner.classList.add('spinner');\n\n if (props.cspNonce) {\n style.setAttribute('nonce', props.cspNonce);\n }\n\n html.appendChild(body);\n body.appendChild(spinner);\n body.appendChild(style);\n style.appendChild(doc.createTextNode(`\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n `));\n\n return html;\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';\n\nimport { childComponent, type ChildComponent } from '../child';\nimport { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';\nimport { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';\nimport { react, angular, vue, vue3, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';\nimport type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';\n\nimport { validateOptions } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,\n type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';\n\ntype LoggerPayload = { [string] : ?string | ?boolean };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types\n};\n\n/* Component\n ---------\n\n This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance\n of Component with the blueprint needed to set up ParentComponents and ChildComponents.\n\n This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and\n contains all of the configuration needed for them to set themselves up.\n*/\n\ntype Attributes = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\nexport type ExportsConfigDefinition = {|\n [string] : {|\n type : DEFINITION_TYPE\n |}\n|};\n\nexport type ExportsMapperDefinition = ({|\n getExports : () => ZalgoPromise\n|}) => X;\n\nexport type ExportsDefinition = ExportsConfigDefinition | ExportsMapperDefinition;\n\nexport type ComponentOptionsType = {|\n\n tag : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain? : DomainMatcher,\n bridgeUrl? : string,\n method? : $Values,\n\n props? : UserPropsDefinitionType,\n\n dimensions? : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize? : {| width? : boolean, height? : boolean, element? : string |},\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : Attributes | ({| props : PropsType

|}) => Attributes,\n\n eligible? : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext? : $Values,\n\n containerTemplate? : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType

) => ?HTMLElement,\n\n validate? : ({| props : PropsInputType

|}) => void,\n\n logger? : Logger,\n\n children? : () => C,\n\n exports? : ExportsDefinition\n|};\n\nexport type AttributesType = {|\n iframe? : { [string] : string },\n popup? : { [string] : string }\n|};\n\ntype AutoResizeType = {|\n width? : boolean,\n height? : boolean,\n element? : string\n|};\n\nexport type NormalizedComponentOptionsType = {|\n tag : string,\n name : string,\n\n url : string | ({| props : PropsType

|}) => string,\n domain : ?DomainMatcher,\n bridgeUrl : ?string,\n method : ?$Values,\n\n propsDef : PropsDefinitionType,\n dimensions : CssDimensionsType | ({| props : PropsType

|}) => CssDimensionsType,\n autoResize : AutoResizeType,\n\n allowedParentDomains : StringMatcherType,\n\n attributes : AttributesType | ({| props : PropsType

|}) => AttributesType,\n\n eligible : ({| props : PropsInputType

|}) => {| eligible : boolean, reason? : string |},\n\n defaultContext : $Values,\n\n containerTemplate : (RenderOptionsType

) => ?HTMLElement,\n prerenderTemplate : ?(RenderOptionsType

) => ?HTMLElement,\n\n validate : ?({| props : PropsInputType

|}) => void,\n logger : Logger,\n\n children : () => C,\n\n exports : ExportsMapperDefinition\n|};\n\nexport type ZoidComponentInstance = {|\n ...ParentHelpers

,\n ...X,\n ...C,\n isEligible : () => boolean,\n clone : () => ZoidComponentInstance,\n render : (container? : ContainerReferenceType, context? : $Values) => ZalgoPromise,\n renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values) => ZalgoPromise\n|};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent = {\n (props? : PropsInputType

| void) : ZoidComponentInstance,\n // eslint-disable-next-line no-undef\n driver : (string, mixed) => T,\n isChild : () => boolean,\n xprops? : PropsType

,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n instances : $ReadOnlyArray>\n};\n\nconst getDefaultAttributes = () : AttributesType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultAutoResize = () : AutoResizeType => {\n // $FlowFixMe\n return {};\n};\n\nconst getDefaultExports = () : () => X => {\n // $FlowFixMe\n return noop;\n};\n\nconst getDefaultDimensions = () : CssDimensionsType => {\n // $FlowFixMe\n return {};\n};\n\nfunction normalizeOptions(options : ComponentOptionsType) : NormalizedComponentOptionsType {\n const {\n tag,\n url,\n domain,\n bridgeUrl,\n props = {},\n dimensions = getDefaultDimensions(),\n autoResize = getDefaultAutoResize(),\n allowedParentDomains = WILDCARD,\n attributes = getDefaultAttributes(),\n defaultContext = CONTEXT.IFRAME,\n containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),\n prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),\n validate,\n eligible = () => ({ eligible: true }),\n logger = { info: noop },\n exports: xportsDefinition = getDefaultExports(),\n method,\n children = () : C => {\n // $FlowFixMe\n return {};\n }\n } = options;\n\n const name = tag.replace(/-/g, '_');\n\n // $FlowFixMe[incompatible-type]\n // $FlowFixMe[cannot-spread-inexact]\n const propsDef : PropsDefinitionType = {\n ...getBuiltInProps(),\n ...props\n };\n\n if (!containerTemplate) {\n throw new Error(`Container template required`);\n }\n\n const xports = typeof xportsDefinition === 'function'\n ? xportsDefinition\n : ({ getExports }) : X => {\n const result = {};\n\n for (const key of Object.keys(xportsDefinition)) {\n const { type } = xportsDefinition[key];\n const valuePromise = getExports().then(res => {\n // $FlowFixMe\n return res[key];\n });\n\n if (type === PROP_TYPE.FUNCTION) {\n result[key] = (...args) => valuePromise.then(value => value(...args));\n } else {\n result[key] = valuePromise;\n }\n }\n\n // $FlowFixMe\n return result;\n };\n\n return {\n name,\n tag,\n url,\n domain,\n bridgeUrl,\n method,\n propsDef,\n dimensions,\n autoResize,\n allowedParentDomains,\n attributes,\n defaultContext,\n containerTemplate,\n prerenderTemplate,\n validate,\n logger,\n eligible,\n children,\n exports: xports\n };\n}\n\nlet cleanInstances = cleanup();\nconst cleanZoid = cleanup();\n\nexport type Component = {|\n init : (props? : PropsInputType

| void) => ZoidComponentInstance,\n instances : $ReadOnlyArray>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise,\n registerChild : () => ?ChildComponent\n|};\n\nexport function component(opts : ComponentOptionsType) : Component {\n if (__DEBUG__) {\n validateOptions(opts);\n }\n\n const options = normalizeOptions(opts);\n\n const {\n name,\n tag,\n defaultContext,\n propsDef,\n eligible,\n children\n } = options;\n\n const global = getGlobal(window);\n const driverCache = {};\n const instances = [];\n\n const isChild = () : boolean => {\n if (isChildComponentWindow(name)) {\n const { payload } = getInitialParentPayload();\n if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {\n return true;\n }\n }\n\n return false;\n };\n\n const registerChild = memoize(() : ?ChildComponent => {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(`Can not register ${ name } as child - child already registered`);\n }\n\n const child = childComponent(options);\n child.init();\n return child;\n }\n });\n\n const listenForDelegate = () => {\n const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {\n return true;\n });\n\n const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {\n return {\n parent: parentComponent({\n uid, options, overrides, parentWin: source\n })\n };\n });\n\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n };\n\n const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise => {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n };\n\n const getDefaultContainer = (context : $Values, container? : ContainerReferenceType) : ContainerReferenceType => {\n if (container) {\n if (typeof container !== 'string' && !isElement(container)) {\n throw new TypeError(`Expected string or element selector to be passed`);\n }\n\n return container;\n }\n\n if (context === CONTEXT.POPUP) {\n return 'body';\n }\n\n throw new Error(`Expected element to be passed to render iframe`);\n };\n\n const getDefaultContext = (props : PropsInputType

, context : ?$Values) : ZalgoPromise<$Values> => {\n return ZalgoPromise.try(() => {\n if (props.window) {\n return toProxyWindow(props.window).getType();\n }\n\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {\n throw new Error(`Unrecognized context: ${ context }`);\n }\n\n return context;\n }\n\n return defaultContext;\n });\n };\n\n const getDefaultInputProps = () : PropsInputType

=> {\n // $FlowFixMe\n return {};\n };\n\n const init = (inputProps? : PropsInputType

| void) : ZoidComponentInstance => {\n // eslint-disable-next-line prefer-const\n let instance;\n\n const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;\n const props = inputProps || getDefaultInputProps();\n\n const { eligible: eligibility, reason } = eligible({ props });\n const isEligible = () => eligibility;\n\n const onDestroy = props.onDestroy;\n props.onDestroy = (...args) => {\n if (instance && eligibility) {\n instances.splice(instances.indexOf(instance), 1);\n }\n\n if (onDestroy) {\n return onDestroy(...args);\n }\n };\n\n const parent = parentComponent({\n uid, options\n });\n\n parent.init();\n\n if (eligibility) {\n parent.setProps(props);\n } else {\n if (props.onDestroy) {\n props.onDestroy();\n }\n }\n\n cleanInstances.register(err => {\n return parent.destroy(err || new Error(`zoid destroyed all components`));\n });\n\n const clone = ({ decorate = identity } = {}) => {\n return init(decorate(props));\n };\n\n const getChildren = () : C => {\n // $FlowFixMe\n const childComponents : {| [string] : ZoidComponent |} = children();\n const result = {};\n\n for (const childName of Object.keys(childComponents)) {\n const Child : ZoidComponent = childComponents[childName];\n\n result[childName] = (childInputProps) => {\n const parentProps : PropsType

= parent.getProps();\n const parentExport : exportPropType = parent.export;\n\n const childParent : ParentPropType = {\n uid,\n props: parentProps,\n export: parentExport\n };\n \n const childProps : PropsInputType = {\n ...childInputProps,\n parent: childParent\n };\n\n return Child(childProps);\n };\n }\n\n // $FlowFixMe\n return result;\n };\n\n const render = (target, container, context) => {\n return ZalgoPromise.try(() => {\n if (!eligibility) {\n const err = new Error(reason || `${ name } component is not eligible`);\n\n return parent.destroy(err).then(() => {\n throw err;\n });\n }\n\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n return getDefaultContext(props, context);\n\n }).then(finalContext => {\n container = getDefaultContainer(finalContext, container);\n\n if (target !== window && typeof container !== 'string') {\n throw new Error(`Must pass string element when rendering to another window`);\n }\n\n return parent.render({\n target,\n container,\n context: finalContext,\n rerender: () => {\n const newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n\n }).catch(err => {\n return parent.destroy(err).then(() => {\n throw err;\n });\n });\n };\n\n instance = {\n ...parent.getExports(),\n ...parent.getHelpers(),\n ...getChildren(),\n isEligible,\n clone,\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n\n if (eligibility) {\n instances.push(instance);\n }\n\n return instance;\n };\n\n const driver = (driverName : string, dep : mixed) : mixed => {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, vue3, angular2 };\n\n if (!drivers[driverName]) {\n throw new Error(`Could not find driver for framework: ${ driverName }`);\n }\n\n if (!driverCache[driverName]) {\n driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);\n }\n\n return driverCache[driverName];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n };\n\n registerChild();\n listenForDelegate();\n\n global.components = global.components || {};\n if (global.components[tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ tag }`);\n }\n global.components[tag] = true;\n\n return {\n init,\n instances,\n driver,\n isChild,\n canRenderTo,\n registerChild\n };\n}\n\nexport type ComponentDriverType = {|\n register : (string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L) => D\n|};\n\nexport type ZoidProps

= PropsType

;\n\n// eslint-disable-next-line no-undef\nexport type CreateZoidComponent = (options : ComponentOptionsType) => ZoidComponent;\n\nexport const create : CreateZoidComponent = (options : ComponentOptionsType) : ZoidComponent => {\n setupPostRobot();\n\n const comp = component(options);\n\n const init = (props? : PropsInputType

| void) => comp.init(props);\n init.driver = (name, dep) => comp.driver(name, dep);\n init.isChild = () => comp.isChild();\n init.canRenderTo = (win) => comp.canRenderTo(win);\n init.instances = comp.instances;\n\n const child = comp.registerChild();\n if (child) {\n window.xprops = init.xprops = child.getProps();\n }\n\n return init;\n};\n\nexport function destroyComponents(err? : mixed) : ZalgoPromise {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n}\n\nexport const destroyAll = destroyComponents;\n\nexport function destroy(err? : mixed) : ZalgoPromise {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n return cleanZoid.all(err);\n}\n"],"sourceRoot":""} \ No newline at end of file From 732f2c4cfa9c37bdfa373a5522b49f55ce93da37 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:26:30 +0500 Subject: [PATCH 15/32] docs: add note for defaultContext <> context --- docs/api/create.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/api/create.md b/docs/api/create.md index 07228459..0edaf8d9 100644 --- a/docs/api/create.md +++ b/docs/api/create.md @@ -352,6 +352,7 @@ const MyComponent = zoid.create({ defaultContext: 'popup' }); ``` +**Note: Use [parentProps.context](https://github.com/krakenjs/zoid/blob/main/docs/api/parent-props.md#context-string) to set context when framework's driver `render`s the component ## validate `({ props }) => void` From 8529789a73221a2c58b3fbde93bda049323496e0 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:26:53 +0500 Subject: [PATCH 16/32] docs: add prop `context` on parent-props --- docs/api/parent-props.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/api/parent-props.md b/docs/api/parent-props.md index 12b6874c..36a2820a 100644 --- a/docs/api/parent-props.md +++ b/docs/api/parent-props.md @@ -27,9 +27,20 @@ MyComponent({ }); ``` +## context `string` + +The type of window to host remote url in. Valid values are `iframe` and `popup`. Used with framework drivers for setting `context` at render time. + +```javascript +const MyFooFrameworkComponent = MyComponent.driver('foo', { FooFramework }) + + +// Now the foo framework's driver will call `render` method with `popup` context +``` + ## cspNonce `string` -A CSP nonce that will be passed to any inline `script` or `style` tags rendered by zoid in the default `containerTemplate` or `prerenderTemplate` fumctions. +A CSP nonce that will be passed to any inline `script` or `style` tags rendered by zoid in the default `containerTemplate` or `prerenderTemplate` functions. ```javascript MyComponent({ From ee9cbb6d9acdf071879e6bfcc897c093cfb6944f Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:27:52 +0500 Subject: [PATCH 17/32] refactor: add const MyLoginZoidComponentDef --- demo/common/LoginZoidComponentDef.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 demo/common/LoginZoidComponentDef.js diff --git a/demo/common/LoginZoidComponentDef.js b/demo/common/LoginZoidComponentDef.js new file mode 100644 index 00000000..6dd461d8 --- /dev/null +++ b/demo/common/LoginZoidComponentDef.js @@ -0,0 +1,16 @@ +const MyLoginZoidComponentDef = { + // The html tag used to render my component + tag: 'my-login-component', + // The url that will be loaded in the iframe or popup, when someone includes my component on their page + url: new URL('login.htm', window.location.href).href, + props: { + prefilledEmail: { + type: 'string', + required: false + }, + onLogin: { + type: 'function' + } + }, + dimensions: { width: '300px', height: '150px' } +}; \ No newline at end of file From a9e618d45e5818c313f700e47eb98a32fced2609 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:28:51 +0500 Subject: [PATCH 18/32] fix: dimensions demo/advanced/props --- demo/advanced/props/index.htm | 1 + demo/advanced/props/login.htm | 1 + demo/advanced/props/login.js | 25 +------------------------ 3 files changed, 3 insertions(+), 24 deletions(-) diff --git a/demo/advanced/props/index.htm b/demo/advanced/props/index.htm index daab38b6..e430bb48 100644 --- a/demo/advanced/props/index.htm +++ b/demo/advanced/props/index.htm @@ -5,6 +5,7 @@ + diff --git a/demo/advanced/props/login.htm b/demo/advanced/props/login.htm index 49c328ee..944902e9 100644 --- a/demo/advanced/props/login.htm +++ b/demo/advanced/props/login.htm @@ -7,6 +7,7 @@ + diff --git a/demo/advanced/props/login.js b/demo/advanced/props/login.js index 5157df0e..df2ba601 100644 --- a/demo/advanced/props/login.js +++ b/demo/advanced/props/login.js @@ -1,25 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href, - - // The properties they can (or must) pass down to my component - - props: { - - prefilledEmail: { - type: 'string', - required: false - }, - - onLogin: { - type: 'function' - } - } -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From 1538dfce1222702fc057181295397c265ede0977 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:29:19 +0500 Subject: [PATCH 19/32] fix: dimensions demo/advanced/react-end-to-end --- demo/advanced/react-end-to-end/index.htm | 3 ++- demo/advanced/react-end-to-end/login.htm | 1 + demo/advanced/react-end-to-end/login.js | 11 +---------- 3 files changed, 4 insertions(+), 11 deletions(-) diff --git a/demo/advanced/react-end-to-end/index.htm b/demo/advanced/react-end-to-end/index.htm index ead8eac7..118b4270 100644 --- a/demo/advanced/react-end-to-end/index.htm +++ b/demo/advanced/react-end-to-end/index.htm @@ -9,6 +9,7 @@ + @@ -17,7 +18,7 @@ + diff --git a/demo/advanced/react-end-to-end/login.js b/demo/advanced/react-end-to-end/login.js index 0976e3b7..df2ba601 100644 --- a/demo/advanced/react-end-to-end/login.js +++ b/demo/advanced/react-end-to-end/login.js @@ -1,11 +1,2 @@ -window.LoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From 6c08183947c1885223a34e299aa468f99e366541 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:29:51 +0500 Subject: [PATCH 20/32] fix: dimensions demo/advanced/remote --- demo/advanced/remote/index.htm | 1 + demo/advanced/remote/login-button.htm | 1 + demo/advanced/remote/login.htm | 1 + demo/advanced/remote/login.js | 11 +---------- 4 files changed, 4 insertions(+), 10 deletions(-) diff --git a/demo/advanced/remote/index.htm b/demo/advanced/remote/index.htm index 3a3eb165..40d80853 100644 --- a/demo/advanced/remote/index.htm +++ b/demo/advanced/remote/index.htm @@ -7,6 +7,7 @@ + diff --git a/demo/advanced/remote/login-button.htm b/demo/advanced/remote/login-button.htm index 6ed66e46..2dc09711 100644 --- a/demo/advanced/remote/login-button.htm +++ b/demo/advanced/remote/login-button.htm @@ -9,6 +9,7 @@ + diff --git a/demo/advanced/remote/login.htm b/demo/advanced/remote/login.htm index d22246a0..64b9a230 100644 --- a/demo/advanced/remote/login.htm +++ b/demo/advanced/remote/login.htm @@ -7,6 +7,7 @@ + diff --git a/demo/advanced/remote/login.js b/demo/advanced/remote/login.js index 5145b956..df2ba601 100644 --- a/demo/advanced/remote/login.js +++ b/demo/advanced/remote/login.js @@ -1,11 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From 92fe11652046b7a5607ccd0a9fe7a8fc8054e103 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:30:25 +0500 Subject: [PATCH 21/32] fix: dimensions demo/advanced/remote-popup --- demo/advanced/remote-popup/index.htm | 1 + demo/advanced/remote-popup/login-button.htm | 1 + demo/advanced/remote-popup/login.htm | 1 + demo/advanced/remote-popup/login.js | 11 +---------- 4 files changed, 4 insertions(+), 10 deletions(-) diff --git a/demo/advanced/remote-popup/index.htm b/demo/advanced/remote-popup/index.htm index a474f351..5b496ecb 100644 --- a/demo/advanced/remote-popup/index.htm +++ b/demo/advanced/remote-popup/index.htm @@ -7,6 +7,7 @@ + diff --git a/demo/advanced/remote-popup/login-button.htm b/demo/advanced/remote-popup/login-button.htm index 43b1cba4..123268f4 100644 --- a/demo/advanced/remote-popup/login-button.htm +++ b/demo/advanced/remote-popup/login-button.htm @@ -9,6 +9,7 @@ + diff --git a/demo/advanced/remote-popup/login.htm b/demo/advanced/remote-popup/login.htm index d22246a0..64b9a230 100644 --- a/demo/advanced/remote-popup/login.htm +++ b/demo/advanced/remote-popup/login.htm @@ -7,6 +7,7 @@ + diff --git a/demo/advanced/remote-popup/login.js b/demo/advanced/remote-popup/login.js index 5145b956..df2ba601 100644 --- a/demo/advanced/remote-popup/login.js +++ b/demo/advanced/remote-popup/login.js @@ -1,11 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From 86ccf917adf3361267ff3fe8e1561c110933942a Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:32:56 +0500 Subject: [PATCH 22/32] refactor: login def demo/basic/iframe --- demo/basic/iframe/index.htm | 1 + demo/basic/iframe/login.htm | 1 + demo/basic/iframe/login.js | 15 +-------------- 3 files changed, 3 insertions(+), 14 deletions(-) diff --git a/demo/basic/iframe/index.htm b/demo/basic/iframe/index.htm index c0962914..9a715a6d 100644 --- a/demo/basic/iframe/index.htm +++ b/demo/basic/iframe/index.htm @@ -5,6 +5,7 @@ + diff --git a/demo/basic/iframe/login.htm b/demo/basic/iframe/login.htm index d22246a0..64b9a230 100644 --- a/demo/basic/iframe/login.htm +++ b/demo/basic/iframe/login.htm @@ -7,6 +7,7 @@ + diff --git a/demo/basic/iframe/login.js b/demo/basic/iframe/login.js index 290174ea..df2ba601 100644 --- a/demo/basic/iframe/login.js +++ b/demo/basic/iframe/login.js @@ -1,15 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - dimensions: { - width: '300px', - height: '150px', - }, - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From 0ee6d46d5ea7b5f3e3aca6f1815fb51b87c1af1f Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:33:33 +0500 Subject: [PATCH 23/32] fix: dimensions demo/basic/popup --- demo/basic/popup/index.htm | 1 + demo/basic/popup/login.htm | 1 + demo/basic/popup/login.js | 15 +-------------- 3 files changed, 3 insertions(+), 14 deletions(-) diff --git a/demo/basic/popup/index.htm b/demo/basic/popup/index.htm index 9f8a6f6c..3caeabd0 100644 --- a/demo/basic/popup/index.htm +++ b/demo/basic/popup/index.htm @@ -6,6 +6,7 @@ + diff --git a/demo/basic/popup/login.htm b/demo/basic/popup/login.htm index d22246a0..20e6ba3f 100644 --- a/demo/basic/popup/login.htm +++ b/demo/basic/popup/login.htm @@ -7,6 +7,7 @@ + diff --git a/demo/basic/popup/login.js b/demo/basic/popup/login.js index 462fb925..f0a9561d 100644 --- a/demo/basic/popup/login.js +++ b/demo/basic/popup/login.js @@ -1,21 +1,8 @@ window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href, - - dimensions: { - width: '300px', - height: '150px' - }, + ...MyLoginZoidComponentDef, // The background overlay - containerTemplate: ({ uid, tag, context, focus, close, doc }) => { function closeComponent(event) { From cc39d5ff74fa6c6e71b183659f9ca2e19ae953e7 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:33:55 +0500 Subject: [PATCH 24/32] fix: dimensions demo/frameworks/angular --- demo/frameworks/angular/index.htm | 1 + demo/frameworks/angular/login.htm | 1 + demo/frameworks/angular/login.js | 11 +---------- 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/demo/frameworks/angular/index.htm b/demo/frameworks/angular/index.htm index bd6ede60..97ef7d35 100644 --- a/demo/frameworks/angular/index.htm +++ b/demo/frameworks/angular/index.htm @@ -7,6 +7,7 @@ + + diff --git a/demo/frameworks/angular/login.js b/demo/frameworks/angular/login.js index 5145b956..df2ba601 100644 --- a/demo/frameworks/angular/login.js +++ b/demo/frameworks/angular/login.js @@ -1,11 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From ffc329ba2b63780349fd654e8147e5dba60bc0b1 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:34:13 +0500 Subject: [PATCH 25/32] fix: dimensions demo/frameworks/angular2 --- demo/frameworks/angular2/index.htm | 1 + demo/frameworks/angular2/login.htm | 1 + demo/frameworks/angular2/login.js | 11 +---------- 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/demo/frameworks/angular2/index.htm b/demo/frameworks/angular2/index.htm index 4fcdcbd1..c61f45d6 100644 --- a/demo/frameworks/angular2/index.htm +++ b/demo/frameworks/angular2/index.htm @@ -12,6 +12,7 @@ + diff --git a/demo/frameworks/angular2/login.htm b/demo/frameworks/angular2/login.htm index 67ba1502..9ea25fd6 100644 --- a/demo/frameworks/angular2/login.htm +++ b/demo/frameworks/angular2/login.htm @@ -7,6 +7,7 @@ + diff --git a/demo/frameworks/angular2/login.js b/demo/frameworks/angular2/login.js index 5145b956..df2ba601 100644 --- a/demo/frameworks/angular2/login.js +++ b/demo/frameworks/angular2/login.js @@ -1,11 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From a8c470fb03d526a4c7d0038e88eb90e0940b64d2 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:35:13 +0500 Subject: [PATCH 26/32] fix: dimensions demo/frameworks/react --- demo/frameworks/react/index.htm | 1 + demo/frameworks/react/login.htm | 1 + demo/frameworks/react/login.js | 11 +---------- 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/demo/frameworks/react/index.htm b/demo/frameworks/react/index.htm index 81c36912..e751157e 100644 --- a/demo/frameworks/react/index.htm +++ b/demo/frameworks/react/index.htm @@ -9,6 +9,7 @@ + diff --git a/demo/frameworks/react/login.htm b/demo/frameworks/react/login.htm index 67ba1502..9ea25fd6 100644 --- a/demo/frameworks/react/login.htm +++ b/demo/frameworks/react/login.htm @@ -7,6 +7,7 @@ + diff --git a/demo/frameworks/react/login.js b/demo/frameworks/react/login.js index 5145b956..df2ba601 100644 --- a/demo/frameworks/react/login.js +++ b/demo/frameworks/react/login.js @@ -1,11 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From a1f7d1bc9f1e0b46ab7cdbe060953ba9a5279cc7 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:35:41 +0500 Subject: [PATCH 27/32] fix: dimensions demo/frameworks/vue3 --- demo/frameworks/vue3/index.htm | 1 + demo/frameworks/vue3/login.htm | 1 + demo/frameworks/vue3/login.js | 12 +----------- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/demo/frameworks/vue3/index.htm b/demo/frameworks/vue3/index.htm index e2660bdf..fcf25801 100644 --- a/demo/frameworks/vue3/index.htm +++ b/demo/frameworks/vue3/index.htm @@ -9,6 +9,7 @@ + diff --git a/demo/frameworks/vue3/login.htm b/demo/frameworks/vue3/login.htm index f64b85e1..66c2d62c 100644 --- a/demo/frameworks/vue3/login.htm +++ b/demo/frameworks/vue3/login.htm @@ -8,6 +8,7 @@ + diff --git a/demo/frameworks/vue3/login.js b/demo/frameworks/vue3/login.js index 891e42b6..df2ba601 100644 --- a/demo/frameworks/vue3/login.js +++ b/demo/frameworks/vue3/login.js @@ -1,12 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); - +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From eb6cb0783afe3b0d553e4de4576e5d5be55132d0 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:36:17 +0500 Subject: [PATCH 28/32] fix: dimensions demo/frameworks/vue --- demo/frameworks/vue/index.htm | 1 + demo/frameworks/vue/login.htm | 1 + demo/frameworks/vue/login.js | 12 +----------- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/demo/frameworks/vue/index.htm b/demo/frameworks/vue/index.htm index 770642ef..dbcd563f 100644 --- a/demo/frameworks/vue/index.htm +++ b/demo/frameworks/vue/index.htm @@ -8,6 +8,7 @@ + diff --git a/demo/frameworks/vue/login.htm b/demo/frameworks/vue/login.htm index 499205b8..991788de 100644 --- a/demo/frameworks/vue/login.htm +++ b/demo/frameworks/vue/login.htm @@ -7,6 +7,7 @@ + diff --git a/demo/frameworks/vue/login.js b/demo/frameworks/vue/login.js index 891e42b6..df2ba601 100644 --- a/demo/frameworks/vue/login.js +++ b/demo/frameworks/vue/login.js @@ -1,12 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href -}); - +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From 63ecb6ee189c30e9483d464f349fbee1c48b8f0f Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:36:40 +0500 Subject: [PATCH 29/32] fix: vue.component is not a function --- demo/frameworks/vue/index.htm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/frameworks/vue/index.htm b/demo/frameworks/vue/index.htm index dbcd563f..9b5b6678 100644 --- a/demo/frameworks/vue/index.htm +++ b/demo/frameworks/vue/index.htm @@ -6,7 +6,7 @@ - + From 22f32ae5e15072e8addb2d7eb1d7ffde55c7d4f8 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:37:23 +0500 Subject: [PATCH 30/32] fix: dimensions demo/frameworks/angular2_Typescript --- demo/frameworks/angular2_TypeScript/index.htm | 3 ++- demo/frameworks/angular2_TypeScript/login.htm | 1 + demo/frameworks/angular2_TypeScript/login.js | 24 +------------------ 3 files changed, 4 insertions(+), 24 deletions(-) diff --git a/demo/frameworks/angular2_TypeScript/index.htm b/demo/frameworks/angular2_TypeScript/index.htm index c7c66b44..6d82ff79 100644 --- a/demo/frameworks/angular2_TypeScript/index.htm +++ b/demo/frameworks/angular2_TypeScript/index.htm @@ -12,8 +12,9 @@ - + + + diff --git a/demo/frameworks/angular2_TypeScript/login.js b/demo/frameworks/angular2_TypeScript/login.js index 080226bc..df2ba601 100644 --- a/demo/frameworks/angular2_TypeScript/login.js +++ b/demo/frameworks/angular2_TypeScript/login.js @@ -1,24 +1,2 @@ -window.MyLoginZoidComponent = zoid.create({ - - // The html tag used to render my component - - tag: 'my-login-component', - - // The url that will be loaded in the iframe or popup, when someone includes my component on their page - - url: new URL('login.htm', window.location.href).href, - - props: { - - prefilledEmail: { - type: 'string', - required: false - }, - - onLogin: { - type: 'function', - required: true - } - } -}); +window.MyLoginZoidComponent = zoid.create(MyLoginZoidComponentDef); From 54c3f3c0657b821680f5a2b438b20885f6c7b095 Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:38:16 +0500 Subject: [PATCH 31/32] fix: npm package paths angular2_Typescript/config --- demo/frameworks/angular2_TypeScript/config.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/demo/frameworks/angular2_TypeScript/config.js b/demo/frameworks/angular2_TypeScript/config.js index c34f7c03..13baac7b 100644 --- a/demo/frameworks/angular2_TypeScript/config.js +++ b/demo/frameworks/angular2_TypeScript/config.js @@ -12,12 +12,12 @@ System.config({ map: { 'app': './', - '@angular/core': 'npm:@angular/core/bundles/core.umd.js', - '@angular/common': 'npm:@angular/common/bundles/common.umd.js', - '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', - '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', - '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', - 'rxjs': 'npm:rxjs', + '@angular/core': 'npm:@angular/core@2/bundles/core.umd.js', + '@angular/common': 'npm:@angular/common@2/bundles/common.umd.js', + '@angular/compiler': 'npm:@angular/compiler@2/bundles/compiler.umd.js', + '@angular/platform-browser': 'npm:@angular/platform-browser@2/bundles/platform-browser.umd.js', + '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic@2/bundles/platform-browser-dynamic.umd.js', + 'rxjs': 'npm:rxjs@5.0.0', 'typescript': 'npm:typescript@2.2.1/lib/typescript.js' }, // packages defines our app package From eb1beb749fe5964a8ef1a9b406097d612a73d7fd Mon Sep 17 00:00:00 2001 From: artmanque Date: Mon, 7 Mar 2022 13:41:31 +0500 Subject: [PATCH 32/32] Revert "fix: remove prepare script temporary" This reverts commit eb08a0c58ba64d357ef38a9a131fadd28071803c. --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 1de7d1c4..d6b89cbf 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "clean": "rimraf dist coverage", "reinstall": "rimraf flow-typed && rimraf node_modules && npm install && flow-typed install", "debug": "cross-env NODE_ENV=debug", + "prepare": "husky install", "prerelease": "npm run clean && npm run test && npm run build", "release": "standard-version", "postrelease": "git push && git push --follow-tags && npm publish"