UNPKG

373 kBSource Map (JSON)View Raw
1{"version":3,"sources":["webpack://zoid/webpack/universalModuleDefinition","webpack://zoid/webpack/bootstrap","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/belter/src/dom.js","webpack://zoid/./node_modules/cross-domain-safe-weakmap/src/native.js","webpack://zoid/./node_modules/belter/src/css.js","webpack://zoid/./node_modules/post-robot/src/conf/config.js","webpack://zoid/./node_modules/post-robot/src/conf/constants.js","webpack://zoid/./node_modules/post-robot/src/global.js","webpack://zoid/./node_modules/post-robot/src/lib/hello.js","webpack://zoid/./node_modules/post-robot/src/lib/windows.js","webpack://zoid/./node_modules/universal-serialize/src/constants.js","webpack://zoid/./node_modules/universal-serialize/src/common.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/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/lib/compat.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/public/send.js","webpack://zoid/./node_modules/post-robot/src/index.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/child/props.js","webpack://zoid/./src/child/window.js","webpack://zoid/./src/child/index.js","webpack://zoid/./src/parent/drivers.js","webpack://zoid/./src/parent/props.js","webpack://zoid/./node_modules/post-robot/src/clean.js","webpack://zoid/./src/parent/index.js","webpack://zoid/./src/delegate/index.js","webpack://zoid/./src/component/templates/container.js","webpack://zoid/./src/component/templates/component.js","webpack://zoid/./src/component/props.js","webpack://zoid/./src/component/component.js","webpack://zoid/./src/component/validate.js","webpack://zoid/./src/index.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","_extends","assign","target","arguments","length","source","apply","isPromise","item","Promise","window","Window","constructor","toString","then","err","flushPromise","dispatchedErrors","possiblyUnhandledPromiseHandlers","activeCount","flushActive","promise","resolve","startActive","endActive","ZalgoPromise","handler","_this","resolved","rejected","errorHandled","error","handlers","dispatching","stack","result","isAsync","res","reject","_proto","prototype","Error","dispatch","_this2","setTimeout","indexOf","push","j","dispatchPossiblyUnhandledError","asyncReject","_this3","_loop","_handlers$i","onSuccess","onError","catch","undefined","finally","onFinally","try","timeout","time","_this4","clearTimeout","toPromise","TypeError","all","promises","count","results","_loop2","prom","hash","keys","map","items","method","onPossiblyUnhandledException","cancel","splice","context","args","delay","flush","isRegex","PROTOCOL","MOCK","FILE","ABOUT","WILDCARD","WINDOW_TYPE","IFRAME","POPUP","IE_WIN_ACCESS_ERROR","isAboutProtocol","win","location","protocol","getParent","parent","getOpener","opener","canReadFromWindow","getActualDomain","host","getDomain","domain","mockDomain","isSameDomain","desc","getOwnPropertyDescriptor","isActuallySameDomain","assertSameDomain","isAncestorParent","child","childParent","getParents","getFrames","frames","len","frame","getAllChildFrames","_i3","_getFrames2","_i5","_getAllChildFrames2","getTop","top","_i7","_getAllChildFrames4","getAllFramesInWindow","concat","iframeWindows","iframeFrames","isWindowClosed","allowMock","closed","message","mockclosed","iframeIndex","collection","safeIndexOf","contentWindow","parentNode","doc","ownerDocument","documentElement","contains","isFrameWindowClosed","getAncestor","anyMatch","collection1","collection2","_i17","item1","_i19","getDistanceFromTop","distance","isSameTopWindow","win1","win2","top1","top2","allFrames1","allFrames2","opener1","opener2","matchDomain","pattern","origin","Array","isArray","Boolean","match","JSON","stringify","some","subpattern","getDomainFromUrl","url","split","slice","join","onCloseWindow","callback","maxtime","Infinity","check","isWindow","obj","__cross_domain_utils_window_check__","objectIDs","awaitFrameLoadPromises","counter","Date","now","CrossDomainSafeWeakMap","weakmap","values","Math","random","WeakMap","freeze","testWeakMap","testKey","set","hasNativeWeakMap","_cleanupClosedWindows","delete","isSafeToReadWrite","entry","writable","index","has","getOrSet","base64encode","str","btoa","Buffer","from","uniqueID","chars","replace","charAt","floor","toISOString","toLowerCase","serializeArgs","subkey","val","uid","getObjectID","memoizePromise","cache","memoizedPromiseFunction","_len2","_key2","reset","inlineMemoize","logic","__inline_memoize_cache__","noop","once","called","stringifyError","level","newErr","extend","safeInterval","loop","arrayFrom","isDefined","cleanup","tasks","cleaned","register","task","pop","assertExists","thing","isDocumentReady","document","body","readyState","urlEncode","waitForDocumentReady","interval","setInterval","clearInterval","parseQuery","queryString","params","_i2","_queryString$split2","pair","decodeURIComponent","extendQuery","originalQuery","props","filter","appendChild","container","isElement","element","Element","nodeType","style","getElementSafe","id","querySelector","elementReady","el","PopupOpenError","awaitFrameLoad","addEventListener","cleanIframes","linkFrameWindow","awaitFrameWindow","loadedFrame","iframe","options","tag","styleText","createElement","class","className","setAttribute","attributes","_i10","_Object$keys2","styleSheet","cssText","createTextNode","html","innerHTML","allowTransparency","backgroundColor","border","isIE","navigator","userAgent","hasAttribute","getElement","event","removeEventListener","destroyElement","removeChild","isElementClosed","onResize","_temp","_ref2","_ref2$width","width","_ref2$height","height","_ref2$interval","_ref2$win","currentWidth","offsetWidth","currentHeight","offsetHeight","observer","newWidth","newHeight","ResizeObserver","observe","MutationObserver","childList","subtree","characterData","disconnect","isPerc","test","isPx","toPx","parseInt","toNum","toCSS","MESSAGE_NAME","METHOD","HELLO","OPEN_TUNNEL","SERIALIZATION_TYPE","CROSS_DOMAIN_ZALGO_PROMISE","CROSS_DOMAIN_FUNCTION","CROSS_DOMAIN_WINDOW","getGlobal","getObj","globalStore","defStore","store","storeKey","defVal","del","WildCard","getWildcard","global","WINDOW_WILDCARD","windowStore","winStore","getStore","getInstanceID","getHelloPromise","sayHello","_ref3","send","instanceID","_ref4","data","getWindowInstanceID","_ref5","_ref6","markWindowKnown","TYPE","FUNCTION","ERROR","PROMISE","REGEX","DATE","ARRAY","OBJECT","STRING","NUMBER","BOOLEAN","NULL","UNDEFINED","isSerializedType","__type__","determineType","serializeType","type","__val__","SERIALIZER","_SERIALIZER","_ref","code","toJSON","defaultSerializers","DESERIALIZER","_DESERIALIZER","RegExp","defaultDeserializers","cleanupProxyWindows","idToProxyWindow","_idToProxyWindow$keys2","shouldClean","getSerializedWindow","windowName","close","closeWindow","getName","focus","isClosed","setLocation","href","setName","frameElement","ProxyWindow","serializedWindow","actualWindow","isProxyWindow","actualWindowPromise","setWindow","getType","isPopup","isIframe","open","getWindow","awaitWindow","matchWindow","_this5","proxyInstanceID","knownWindowInstanceID","unwrap","serialize","toProxyWindow","deserialize","on","realWin","proxyWindow","addMethod","methodStore","proxyWindowMethods","lookupMethod","serializeFunction","destination","meth","methodSource","listenForFunctionCalls","__id__","__name__","serializeMessage","_serialize","serializers","serializer","serializePromise","deserializeMessage","_deserialize","deserializers","parse","deserializer","serializedPromise","serializedFunction","getDeserializedFunction","opts","crossDomainFunctionWrapper","_arguments","fireAndForget","__origin__","__source__","deserializeFunction","_ref8","SEND_MESSAGE_STRATEGIES","sendMessage","_serializeMessage","serializedMessage","strategies","errors","strategyName","dom","forEach","postMessage","mockUserAgent","getUserAgent","foreignGlobal","receiveMessage","__DOMAIN_REGEX__","getResponseListener","deleteResponseListener","isResponseListenerErrored","getRequestListener","requestListeners","_i4","winQualifier","nameListeners","domainListeners","_i6","_domainListeners$__DO2","_domainListeners$__DO3","listener","regex","RECEIVE_MESSAGE_TYPES","_RECEIVE_MESSAGE_TYPE","sendResponse","ack","response","pathname","handleError","receivedMessages","parsedMessage","parseMessage","requestListener","addRequestListener","listenersCollection","_i8","_win2","_i12","_domain2","_i14","existingListener","regexListeners","regexListener","strDomain","errorHandler","bridge","responseTimeout","childTimeout","validateOptions","actualParent","_i15","_getFrames8","isAncestor","awaitWindowHello","normalizeDomain","targetDomain","logName","responseListener","addResponseListener","reqPromises","markResponseListenerErrored","totalAckTimeout","isWindowKnown","totalResTimeout","ackTimeout","resTimeout","cancelled","max","internalSerializeMessage","internalDeserializeMessage","getProxyObject","ZOID","POST_MESSAGE","PROP_TYPE","PROP_SERIALIZATION","DOTIFY","BASE64","CONTEXT","DEFAULT_DIMENSIONS","WIDTH","HEIGHT","EVENT","RENDER","RENDERED","DISPLAY","CLOSE","PROPS","RESIZE","normalizeChildProp","component","helpers","prop","getPropDefinition","childDecorate","parseChildWindowName","_windowName$split","zoidcomp","encodedPayload","atob","base64decode","getChildPayload","ChildComponent","parentDomain","parentComponentWindow","onPropHandlers","autoResize","childPayload","__ZOID__","version","getParentComponentWindow","checkParentDomain","initialProps","getPropsByRef","setProps","watchForClose","init","buildExports","watchForResize","getHelpers","resize","onProps","getParentDomain","allowedParentDomains","ref","getNthParent","ancestor","_getAllFramesInWindow2","windows","getProps","isUpdate","existingProps","sameDomain","alias","_component$getPropNam2","getPropNames","normalizeChildProps","_this$onPropHandlers2","checkClose","destroy","getAutoResize","_ref3$width","_ref3$height","_ref3$element","_this4$getAutoResize","updateProps","_this6","RENDER_DRIVERS","getQueryParam","queryParam","getQueryValue","queryValue","openOnClick","openFrame","title","proxyFrame","frameWatcher","clean","_requestPromises$get2","cleanUpWindow","openPrerenderFrame","openPrerender","proxyWin","proxyPrerenderFrame","prerenderFrame","prerenderFrameWindow","delegate","ParentComponent","driver","initPromise","handledErrors","state","setupEvents","registerActiveComponent","destroyActiveComponent","watchForUnload","triggered","eventName","handlerList","trigger","_len3","_key3","triggerOnce","_len4","_key4","onRender","onDisplay","onRendered","onClose","render","log","childDomain","getChildDomain","checkAllowRender","buildUrl","getProxyContainer","renderContainer","proxyContainer","setState","setProxyWin","prerender","proxyPrerenderWin","loadUrl","setWindowName","buildWindowName","openBridge","runTimeout","containerElement","buildChildPayload","getPropsRef","getPropsForChild","propRef","_ref7","_ref7$target","getWindowRef","buildParentExports","validate","inputProps","propNames","aliases","propDef","default","_Object$keys4","decorate","required","extendProps","propsDef","builtinProps","serialization","dotify","prefix","newobj","every","_Object$keys6","dotkey","query","originalUrl","originalHash","_url$split","_originalUrl$split","hashString","extendUrl","normalizeMockUrl","getUrl","sendToChild","_this7","_this8","_this9","_this10","windowProp","_this11","_this12","_this13","_this$component$getPr2","propName","allowDelegate","overridesPromise","overrides","_ref9","_this$driver$delegate2","_this14","_this15","_this16","unloadWindowListener","_this17","initChild","_this18","_this19","_ref10","_ref11","_this20","_this21","secondClosed","_this22","_ref12","_this23","prerenderTemplate","prerenderWindow","isBlankDomain","renderTemplate","tagName","_arrayFrom2","children","_arrayFrom4","writeElementToWindow","_ref13","_ref13$width","_ref13$height","_ref13$element","_ref14","renderer","_ref15","_this24","dimensions","_ref16","_this25","_ref17","innerContainer","containerTemplate","_this26","_this27","DelegateComponent","watchForSourceClose","getDelegate","getOverrides","closeSourceWindowListener","CLASS","VISIBLE","INVISIBLE","defaultContainerTemplate","_ref$dimensions","div","cspNonce","classList","add","remove","defaultPrerenderTemplate","spinner","defaultNoop","decorateOnce","Component","bridgeUrl","defaultContext","driverCache","xprops","logger","PROP_TYPE_LIST","validatePropDefinitions","components","_ref$width","_ref$height","popup","debug","info","warn","registerChild","listenDelegate","dep","isChild","_ref2$data","canRenderTo","getBridgeUrl","payload","getDefaultContainer","getDefaultContext","renderTo","instance","activeComponents","initialized","setupGlobalReceiveMessage","sourceElement","originalEvent","messageListener","initHello","destroyAll","destroyBridges","destroyComponents","responseListeners","_responseListeners$ke2","cancelResponseListeners","__webpack_exports__","component_destroy","component_Component"],"mappings":"CAAA,SAAAA,MAAAC;IACA,mBAAAC,WAAA,mBAAAC,SACAA,OAAAD,UAAAD,YACA,qBAAAG,iBAAAC,MACAD,OAAA,YAAAH,WACA,mBAAAC,UACAA,QAAA,OAAAD,YAEAD,KAAA,OAAAC;CARA,CASC,sBAAAK,cAAAC,MAAA;IACD;QCTA,IAAAC,mBAAA;QAGA,SAAAC,oBAAAC;YAGA,IAAAF,iBAAAE,WACA,OAAAF,iBAAAE,UAAAR;YAGA,IAAAC,SAAAK,iBAAAE,YAAA;gBACAC,GAAAD;gBACAE,IAAA;gBACAV,SAAA;;YAUA,OANAW,QAAAH,UAAAI,KAAAX,OAAAD,SAAAC,eAAAD,SAAAO;YAGAN,OAAAS,KAAA,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;YAAA,OAAA9R;YAAA7lB,oBAAAQ,EAAAm3B,qBAAA;YAAA,OAAA7R;YAAA9lB,oBAAAQ,EAAAm3B,qBAAA;YAAA,OAAA1R;YAAAjmB,oBAAAQ,EAAAm3B,qBAAA;YAAA,OAAAtR","file":"zoid.frame.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 _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' && window.Window && item instanceof window.Window) {\n return false;\n }\n\n if (typeof window !== 'undefined' && window.constructor && item instanceof window.constructor) {\n return false;\n }\n\n let toString = ({}).toString;\n\n if (toString) {\n let 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 = [];\n\nexport function dispatchPossiblyUnhandledError<T>(err : mixed, promise : ZalgoPromise<T>) {\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<*>>) : ZalgoPromise<void> { // eslint-disable-line no-undef\n let 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<R : mixed> {\n\n resolved : boolean\n rejected : boolean\n errorHandled : boolean\n value : R\n error : mixed\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<R> {\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<R> {\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 let 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<R> {\n this.errorHandled = true;\n this.reject(error);\n return this;\n }\n \n dispatch() {\n\n let { 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 for (let i = 0; i < handlers.length; i++) {\n\n let { 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\n if (result.resolved) {\n promise.resolve(result.value);\n } else {\n promise.reject(result.error);\n }\n\n result.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 result.then(res => {\n promise.resolve(res);\n }, err => {\n promise.reject(err);\n });\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<X : mixed, Y : mixed>(onSuccess : void | (result : R) => (ZalgoPromise<X> | Y), onError : void | (error : mixed) => (ZalgoPromise<X> | Y)) : ZalgoPromise<X | Y> {\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 let promise : ZalgoPromise<X | Y> = 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<X : mixed, Y : mixed>(onError : (error : mixed) => ZalgoPromise<X> | Y) : ZalgoPromise<X | Y> {\n return this.then(undefined, onError);\n }\n\n finally(onFinally : () => mixed) : ZalgoPromise<R> {\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<R> {\n\n if (this.resolved || this.rejected) {\n return this;\n }\n\n let 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<R> {\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 static resolve<X : mixed>(value : X | ZalgoPromise<X>) : ZalgoPromise<X> {\n\n if (value instanceof ZalgoPromise) {\n return value;\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<R> {\n return new ZalgoPromise().reject(error);\n }\n\n static asyncReject(error : mixed) : ZalgoPromise<R> {\n return new ZalgoPromise().asyncReject(error);\n }\n\n static all<X : Array<mixed>>(promises : X) : ZalgoPromise<$TupleMap<X, <Y>(ZalgoPromise<Y> | Y) => Y>> { // eslint-disable-line no-undef\n\n let promise = new ZalgoPromise();\n let count = promises.length;\n let results = [];\n\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n\n for (let i = 0; i < promises.length; i++) {\n let 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 ZalgoPromise.resolve(prom).then(result => {\n results[i] = result;\n count -= 1;\n if (count === 0) {\n promise.resolve(results);\n }\n }, err => {\n promise.reject(err);\n });\n }\n\n if (count === 0) {\n promise.resolve(results);\n }\n\n return promise;\n }\n\n static hash<O : Object>(promises : O) : ZalgoPromise<$ObjMap<O, <Y>(ZalgoPromise<Y> | Y) => Y>> { // eslint-disable-line no-undef\n let result = {};\n \n return ZalgoPromise.all(Object.keys(promises).map(key => {\n return ZalgoPromise.resolve(promises[key]).then(value => {\n result[key] = value;\n });\n })).then(() => {\n return result;\n });\n }\n\n static map<T, X>(items : Array<T>, method : (T) => (ZalgoPromise<X> | X)) : ZalgoPromise<Array<X>> {\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<X : mixed, Y : mixed, C : mixed, A : Array<mixed>>(method : (...args : A) => (ZalgoPromise<X> | Y), context : ?C, args : ?A) : ZalgoPromise<X | Y> {\n\n if (method && typeof method !== 'function' && !method.call) {\n throw new Error('Promise.try expected a function');\n }\n\n let result;\n\n startActive();\n \n try {\n // $FlowFixMe\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n\n endActive();\n\n return ZalgoPromise.resolve(result);\n }\n\n static delay(delay : number) : ZalgoPromise<void> {\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<void> {\n return awaitActive(ZalgoPromise);\n }\n}\n","/* @flow */\n\nexport function isRegex(item : mixed) : boolean {\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : Array<mixed>) {\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\nlet IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\\r\\n';\n\nexport function isFileProtocol(win : SameDomainWindowType = window) : boolean {\n return win.location.protocol === PROTOCOL.FILE;\n}\n\nexport function isAboutProtocol(win : SameDomainWindowType = window) : boolean {\n return win.location.protocol === PROTOCOL.ABOUT;\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) : string {\n\n win = win || window;\n\n let location = win.location;\n\n if (!location) {\n throw new Error(`Can not read window location`);\n }\n\n let protocol = location.protocol;\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 let parent = getParent(win);\n if (parent && canReadFromWindow(parent)) {\n // $FlowFixMe\n return getActualDomain(parent);\n }\n\n return `${ PROTOCOL.ABOUT }//`;\n }\n\n let 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) : string {\n\n win = win || window;\n\n let 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 let 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 (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\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) : Array<CrossDomainWindowType> {\n\n let 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 let 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) : Array<CrossDomainWindowType> {\n\n let 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) : Array<CrossDomainWindowType> {\n\n let result = [];\n\n for (let frame of getFrames(win)) {\n result.push(frame);\n\n for (let childFrame of getAllChildFrames(frame)) {\n result.push(childFrame);\n }\n }\n\n return result;\n}\n\nexport function getTop(win : CrossDomainWindowType) : ?CrossDomainWindowType {\n\n if (!win) {\n return;\n }\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 (let 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 let opener = getNextOpener(win);\n\n if (opener) {\n return getUltimateTop(opener);\n }\n\n return top;\n}\n\nexport function getAllFramesInWindow(win : CrossDomainWindowType) : Array<CrossDomainWindowType> {\n let top = getTop(win);\n\n if (!top) {\n throw new Error(`Can not determine top window`);\n }\n\n return [ ...getAllChildFrames(top), top ];\n}\n\nexport function getAllWindows(win? : CrossDomainWindowType = window) : $ReadOnlyArray<CrossDomainWindowType> {\n let frames = getAllFramesInWindow(win);\n let 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 let doc = frame.ownerDocument;\n\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n return true;\n }\n\n return false;\n}\n\nfunction safeIndexOf<T>(collection : Array<T>, 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\nlet iframeWindows = [];\nlet 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 let iframeIndex = safeIndexOf(iframeWindows, win);\n\n if (iframeIndex !== -1) {\n let 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 let winFrames = getFrames(win);\n\n for (let 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 let frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n for (let childFrame of getFrames(win)) {\n let namedFrame = findChildFrameByName(childFrame, name);\n\n if (namedFrame) {\n return namedFrame;\n }\n }\n}\n\nexport function findFrameByName(win : CrossDomainWindowType, name : string) : ?CrossDomainWindowType {\n\n let frame;\n\n frame = getFrameByName(win, name);\n\n if (frame) {\n return frame;\n }\n\n let top = getTop(win) || win;\n\n return findChildFrameByName(top, name);\n}\n\nexport function isParent(win : CrossDomainWindowType, frame : CrossDomainWindowType) : boolean {\n\n let frameParent = getParent(frame);\n\n if (frameParent) {\n return frameParent === win;\n }\n\n for (let 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 let opener = getOpener(win);\n\n if (opener) {\n return opener;\n }\n\n let parent = getParent(win);\n\n if (parent) {\n return parent;\n }\n}\n\nexport function getAncestors(win : CrossDomainWindowType) : Array<CrossDomainWindowType> {\n\n let 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 let 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 (let frame of getFrames(parent)) {\n if (frame === child) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isPopup() : boolean {\n return Boolean(getOpener(window));\n}\n\nexport function isIframe() : boolean {\n return Boolean(getParent(window));\n}\n\nexport function isFullpage() : boolean {\n return Boolean(!isIframe() && !isPopup());\n}\n\nfunction anyMatch(collection1, collection2) : boolean {\n\n for (let item1 of collection1) {\n for (let 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 let top1 = getTop(win1) || win1;\n let 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 let allFrames1 = getAllFramesInWindow(win1);\n let allFrames2 = getAllFramesInWindow(win2);\n\n if (anyMatch(allFrames1, allFrames2)) {\n return true;\n }\n\n let opener1 = getOpener(top1);\n let 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 let 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 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 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 closeWindow(win : CrossDomainWindowType) {\n try {\n win.close();\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n\nexport function safeIndexOf<T>(collection : Array<T>, 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 : Array<mixed>) {\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\nlet defineProperty = Object.defineProperty;\nlet counter = Date.now() % 1e9;\n\nexport class CrossDomainSafeWeakMap<K : Object, V : mixed> {\n\n name : string\n weakmap : WeakMap<K, V>\n keys : Array<K>\n values : Array<V>\n\n constructor() {\n counter += 1;\n\n // eslint-disable-next-line no-bitwise\n this.name = `__weakmap_${ Math.random() * 1e9 >>> 0 }__${ counter }`;\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 let weakmap = this.weakmap;\n let keys = this.keys;\n\n for (let i = 0; i < keys.length; i++) {\n let 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 let 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 let name = this.name;\n let entry = key[name];\n\n if (entry && entry[0] === key) {\n entry[1] = value;\n } else {\n 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 let keys = this.keys;\n let values = this.values;\n let 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 let 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 let 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 let keys = this.keys;\n let 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 let 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 let 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 let keys = this.keys;\n let 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 let 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 let 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 let 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 let value = getter();\n this.set(key, value);\n return value;\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 base64encode(str : string) : string {\n if (typeof btoa === 'function') {\n return btoa(str);\n } else if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf8').toString('base64');\n }\n\n throw new Error(`Can not find window.btoa or Buffer`);\n}\n\nexport function base64decode(str : string) : string {\n if (typeof window !== 'undefined' && typeof window.atob === 'function') {\n return window.atob(str);\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 let chars = '0123456789abcdef';\n\n let randomID = 'xxxxxxxxxx'.replace(/./g, () => {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n });\n\n let timeID = base64encode(\n new Date().toISOString().slice(11, 19).replace('T', '.')\n ).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n\n return `${ 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 : Array<mixed>) : string {\n try {\n return JSON.stringify(Array.prototype.slice.call(args), (subkey, val) => {\n if (typeof val === 'function') {\n return `memoize[${ getObjectID(val) }]`;\n }\n return val;\n });\n } catch (err) {\n throw new Error(`Arguments not serializable -- can not be used to memoize`);\n }\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoize<R>(method : (...args : Array<any>) => R, options : { time? : number, name? : string, thisNamespace? : boolean } = {}) : ((...args : Array<any>) => R) {\n let cacheMap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedFunction(...args : Array<any>) : R {\n let cache = cacheMap.getOrSet(options.thisNamespace ? this : method, () => ({}));\n\n let key : string = serializeArgs(args);\n\n let cacheTime = options.time;\n if (cache[key] && cacheTime && (Date.now() - cache[key].time) < cacheTime) {\n delete cache[key];\n }\n\n if (cache[key]) {\n return cache[key].value;\n }\n\n let time = Date.now();\n let value = method.apply(this, arguments);\n\n cache[key] = { time, value };\n\n return cache[key].value;\n }\n\n memoizedFunction.reset = () => {\n cacheMap.delete(options.thisNamespace ? this : method);\n };\n\n if (options.name) {\n memoizedFunction.displayName = `${ options.name }:memoized`;\n }\n\n return memoizedFunction;\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function memoizePromise<R>(method : (...args : Array<any>) => ZalgoPromise<R>) : ((...args : Array<any>) => ZalgoPromise<R>) {\n let cache = {};\n\n // eslint-disable-next-line flowtype/no-weak-types\n function memoizedPromiseFunction(...args : Array<any>) : ZalgoPromise<R> {\n let key : string = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n cache[key] = 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 memoizedPromiseFunction;\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function promisify<R>(method : (...args : Array<any>) => R, options : { name? : string } = {}) : ((...args : Array<any>) => ZalgoPromise<R>) {\n function promisifiedFunction() : ZalgoPromise<R> {\n return ZalgoPromise.try(method, this, arguments);\n }\n\n if (options.name) {\n promisifiedFunction.displayName = `${ options.name }:promisified`;\n }\n\n return promisifiedFunction;\n}\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport function inlineMemoize<R>(method : (...args : Array<any>) => R, logic : (...args : Array<any>) => R, args : Array<any> = []) : R {\n // $FlowFixMe\n let cache = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n let key = serializeArgs(args);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n \n let result = cache[key] = logic(...args);\n return result;\n}\n\n// eslint-disable-next-line no-unused-vars\nexport function noop(...args : Array<mixed>) {\n // pass\n}\n\nexport function once(method : Function) : Function {\n let called = false;\n\n return function onceFunction() : mixed {\n if (!called) {\n called = true;\n return method.apply(this, arguments);\n }\n };\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 let regmatch = str.match(pattern);\n if (regmatch) {\n return regmatch[1];\n }\n}\n\nexport function awaitKey<T: mixed>(obj : Object, key : string) : ZalgoPromise<T> {\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() : mixed {\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 return `<unknown error: ${ Object.prototype.toString.call(err) }>`;\n }\n\n if (typeof err === 'string') {\n return err;\n }\n\n if (err instanceof Error) {\n let stack = err && err.stack;\n let 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 return Object.prototype.toString.call(err);\n\n } catch (newErr) { // eslint-disable-line unicorn/catch-error-name\n return `Error while stringifying error: ${ stringifyError(newErr, level + 1) }`;\n }\n}\n\nexport function stringifyErrorMessage(err : mixed) : string {\n\n let defaultMessage = `<unknown error: ${ Object.prototype.toString.call(err) }>`;\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 return Object.prototype.toString.call(item);\n}\n\nexport function domainMatches(hostname : string, domain : string) : boolean {\n hostname = hostname.split('://')[1];\n let index = hostname.indexOf(domain);\n return (index !== -1 && hostname.slice(index) === domain);\n}\n\nexport function patchMethod(obj : Object, name : string, handler : Function) {\n let original = obj[name];\n\n obj[name] = function patchedMethod() : mixed {\n return handler({\n context: this,\n args: Array.prototype.slice.call(arguments),\n original,\n callOriginal: () => original.apply(this, arguments)\n });\n };\n}\n\nexport function extend<T : Object | Function>(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 (let key in source) {\n if (source.hasOwnProperty(key)) {\n obj[key] = source[key];\n }\n }\n\n return obj;\n}\n\nexport function values<T>(obj : { [string] : T }) : Array<T> {\n let result = [];\n for (let key in obj) {\n if (obj.hasOwnProperty(key)) {\n result.push(obj[key]);\n }\n }\n return result;\n}\n\nexport function perc(pixels : number, percentage : number) : number {\n return Math.round((pixels * percentage) / 100);\n}\n\nexport function min(...args : Array<number>) : number {\n return Math.min(...args);\n}\n\nexport function max(...args : Array<number>) : number {\n return Math.max(...args);\n}\n\nexport function regexMap<T>(str : string, regexp : RegExp, handler : () => T) : Array<T> {\n let 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<T, R>(obj : { [string] : T }, filter? : (T, ?string) => mixed = Boolean) : { [string] : R } {\n let result = {};\n\n for (let 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 <T>(item : T) : T {\n return item;\n}\n\nexport function regexTokenize(text : string, regexp : RegExp) : Array<string> {\n let result = [];\n text.replace(regexp, token => {\n result.push(token);\n return '';\n });\n return result;\n}\n\nexport function promiseDebounce<T>(method : () => ZalgoPromise<T> | T, delay : number = 50) : () => ZalgoPromise<T> {\n\n let promise;\n let timeout;\n\n return function promiseDebouncedMethod() : ZalgoPromise<T> {\n if (timeout) {\n clearTimeout(timeout);\n }\n\n let 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\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 (let 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 let 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, key.length - 2);\n value = value.split(',').map(deserializePrimitive);\n } else {\n value = deserializePrimitive(value);\n }\n\n let keyResult = result;\n let parts = key.split('.');\n for (let i = 0; i < parts.length; i++) {\n let part = parts[i];\n let isLast = (i + 1 === parts.length);\n let isIndex = !isLast && isInteger(parts[i + 1]);\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<mixed>) => ZalgoPromise<void>,\n triggerOnce : (eventName : string, ...args : $ReadOnlyArray<mixed>) => ZalgoPromise<void>\n};\n\nexport function eventEmitter() : EventEmitterType {\n let triggered = {};\n let handlers = {};\n\n return {\n\n on(eventName : string, handler : Function) : CancelableType {\n let 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 let listener = this.on(eventName, () => {\n listener.cancel();\n handler();\n });\n\n return listener;\n },\n\n trigger(eventName : string, ...args : $ReadOnlyArray<mixed>) : ZalgoPromise<void> {\n\n let handlerList = handlers[eventName];\n let promises = [];\n\n if (handlerList) {\n for (let 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<mixed>) : ZalgoPromise<void> {\n\n if (triggered[eventName]) {\n return ZalgoPromise.resolve();\n }\n\n triggered[eventName] = true;\n return this.trigger(eventName, ...args);\n }\n };\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 let 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 let interval = safeInterval(() => {\n time -= 100;\n if (time <= 0) {\n interval.cancel();\n method();\n }\n }, 100);\n}\n\nexport function defineLazyProp<T>(obj : Object | Array<mixed>, 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 let 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<T>(item : Iterable<T>) : Array<T> { // eslint-disable-line no-undef\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 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 let constructor = obj.constructor;\n\n if (typeof constructor !== 'function') {\n return false;\n }\n\n let 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<T : Array<mixed> | Object> (item : T, replacer : (mixed, string | number, string) => mixed, fullKey : string = '') : T {\n\n if (Array.isArray(item)) {\n let length = item.length;\n let result : Array<mixed> = [];\n\n for (let i = 0; i < length; i++) {\n\n \n defineLazyProp(result, i, () => {\n let itemKey = fullKey ? `${ fullKey }.${ i }` : `${ i }`;\n let 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 let result = {};\n\n for (let key in item) {\n if (!item.hasOwnProperty(key)) {\n continue;\n }\n\n defineLazyProp(result, key, () => {\n let itemKey = fullKey ? `${ fullKey }.${ key }` : `${ key }`;\n // $FlowFixMe\n let 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 let 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 : Array<string>,\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 let result = string.slice(start).match(pattern);\n\n if (!result) {\n return;\n }\n\n // $FlowFixMe\n let index : number = result.index;\n let 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) : Array<RegexResultType> {\n\n let matches = [];\n let start = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let 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<void> {\n return ZalgoPromise.try(method).then(() => cycle(method));\n}\n\nexport function debounce<T>(method : (...args : Array<mixed>) => T, time : number = 100) : (...args : Array<mixed>) => void {\n\n let timeout;\n\n return function debounceWrapper() {\n clearTimeout(timeout);\n\n timeout = setTimeout(() => {\n return method.apply(this, arguments);\n }, time);\n };\n}\n\nexport function isRegex(item : mixed) : boolean {\n return Object.prototype.toString.call(item) === '[object RegExp]';\n}\n\ntype FunctionProxy<T : Function> = (method : T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport let weakMapMemoize : FunctionProxy<*> = <R : mixed>(method : (arg : any) => R) : ((...args : Array<any>) => R) => {\n\n let 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<R : mixed, T : (...args : $ReadOnlyArray<mixed>) => ZalgoPromise<R>> = (T) => T;\n\n// eslint-disable-next-line flowtype/no-weak-types\nexport let weakMapMemoizePromise : FunctionPromiseProxy<*, *> = <R : mixed>(method : (arg : any) => ZalgoPromise<R>) : ((...args : Array<any>) => ZalgoPromise<R>) => {\n\n let weakmap = new WeakMap();\n\n // eslint-disable-next-line flowtype/no-weak-types\n return function weakmapMemoizedPromise(arg : any) : ZalgoPromise<R> {\n return weakmap.getOrSet(arg, () =>\n method.call(this, arg).finally(() => {\n weakmap.delete(arg);\n })\n );\n };\n};\n\nexport function getOrSet<O : Object, T : mixed>(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 : <T : mixed>(string, T) => T, // eslint-disable-line no-undef\n register : (Function) => void,\n all : () => ZalgoPromise<void>\n|};\n\nexport function cleanup(obj : Object) : CleanupType {\n\n const tasks = [];\n let cleaned = false;\n\n return {\n set<T : mixed>(name : string, item : T) : T {\n if (!cleaned) {\n obj[name] = item;\n this.register(() => {\n delete obj[name];\n });\n }\n return item;\n },\n\n register(method : Function) {\n if (cleaned) {\n method();\n } else {\n tasks.push(once(method));\n }\n },\n\n all() : ZalgoPromise<void> {\n const results = [];\n cleaned = true;\n\n while (tasks.length) {\n const task = tasks.pop();\n results.push(task());\n }\n\n return ZalgoPromise.all(results).then(noop);\n }\n };\n}\n\nexport function tryCatch<T>(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\nexport function removeFromArray<X, T : Array<X>>(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<T>(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<string>) : $ReadOnlyArray<string> {\n const result = {};\n for (const item of arr) {\n // eslint-disable-next-line const-immutable/no-mutation\n result[item] = true;\n }\n return Object.keys(result);\n}\n","/* @flow */\n/* eslint max-lines: off */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { linkFrameWindow, isWindowClosed,\n type SameDomainWindowType, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\n\nimport { inlineMemoize, noop, stringify, capitalizeFirstLetter,\n once, extend, safeInterval, uniqueID, arrayFrom } from './util';\nimport { isDevice } from './device';\nimport { KEY_CODES } from './constants';\nimport type { CancelableType } from './types';\n\ntype ElementRefType = string | HTMLElement;\n\nexport function isDocumentReady() : boolean {\n return Boolean(document.body) && document.readyState === 'complete';\n}\n\nexport function urlEncode(str : string) : string {\n return str.replace(/\\?/g, '%3F').replace(/&/g, '%26').replace(/#/g, '%23').replace(/\\+/g, '%2B');\n}\n\nexport function waitForWindowReady() : ZalgoPromise<void> {\n return inlineMemoize(waitForWindowReady, () : ZalgoPromise<void> => {\n return new ZalgoPromise(resolve => {\n if (isDocumentReady()) {\n resolve();\n }\n\n window.addEventListener('load', () => resolve());\n });\n });\n}\n\nexport function waitForDocumentReady() : ZalgoPromise<void> {\n return inlineMemoize(waitForDocumentReady, () : ZalgoPromise<void> => {\n return new ZalgoPromise(resolve => {\n\n if (isDocumentReady()) {\n return resolve();\n }\n\n let interval = setInterval(() => {\n if (isDocumentReady()) {\n clearInterval(interval);\n return resolve();\n }\n }, 10);\n });\n });\n}\n\nexport function waitForDocumentBody() : ZalgoPromise<HTMLBodyElement> {\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\nexport function parseQuery(queryString : string) : Object {\n return inlineMemoize(parseQuery, () : Object => {\n let 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 function formatQuery(obj : { [ string ] : string } = {}) : string {\n\n return Object.keys(obj).filter(key => {\n return typeof obj[key] === 'string';\n }).map(key => {\n return `${ urlEncode(key) }=${ urlEncode(obj[key]) }`;\n }).join('&');\n}\n\nexport function extendQuery(originalQuery : string, props : { [ string ] : string } = {}) : 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? : { [string] : string }, hash? : { [string] : string } } = {}) : string {\n\n let query = options.query || {};\n let 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 let queryString = extendQuery(originalQuery, query);\n let 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<void> {\n return new ZalgoPromise(resolve => {\n win.location = url;\n if (!urlWillRedirectPage(url)) {\n resolve();\n }\n });\n}\n\nexport function hasMetaViewPort() : boolean {\n let 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 enablePerformance() : boolean {\n return inlineMemoize(enablePerformance, () : boolean => {\n /* eslint-disable compat/compat */\n return Boolean(\n window.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 /* eslint-enable compat/compat */\n });\n}\n\nexport function getPageRenderTime() : ZalgoPromise<?number> {\n return waitForDocumentReady().then(() => {\n\n if (!enablePerformance()) {\n return;\n }\n\n let timing = window.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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;')\n .replace(/\\//g, '&#x2F;');\n}\n\nexport function isBrowser() : boolean {\n return (typeof window !== 'undefined');\n}\n\nexport function querySelectorAll(selector : string, doc : HTMLElement = window.document) : Array<HTMLElement> {\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) {\n return handler(event);\n }\n });\n}\n\nexport function getScript({ host = window.location.host, path } : { host? : string, path : string }) : ?HTMLScriptElement {\n return inlineMemoize(getScript, () : ?HTMLScriptElement => {\n\n let url = `${ host }${ path }`;\n let scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));\n\n for (let script of scripts) {\n if (!script.src) {\n continue;\n }\n\n let 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 let value = Math.random().toString();\n window.localStorage.setItem('__test__localStorage__', value);\n let 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() : Array<{ country? : string, lang : string }> {\n let nav = window.navigator;\n\n let locales = nav.languages\n ? Array.prototype.slice.apply(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 let [ 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 isElement(element : mixed) : boolean {\n\n if (element instanceof window.Element) {\n return true;\n }\n\n if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {\n return true;\n }\n\n return false;\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 let 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<window.HTMLElement> {\n return new ZalgoPromise((resolve, reject) => {\n\n let 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 let interval = setInterval(() => {\n\n el = getElementSafe(id);\n\n if (el) {\n clearInterval(interval);\n return resolve(el);\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\nexport function PopupOpenError(message : string) {\n this.message = message;\n}\n\nPopupOpenError.prototype = Object.create(Error.prototype);\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|};\n\nexport function popup(url : string, options? : PopupOptions) : CrossDomainWindowType {\n\n // $FlowFixMe\n options = options || {};\n\n let { 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 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 let name = options.name || '';\n delete options.name;\n\n // eslint-disable-next-line array-callback-return\n let params = Object.keys(options).map(key => {\n // $FlowFixMe\n if (options[key]) {\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, true);\n } catch (err) {\n throw new PopupOpenError(`Can not open popup window - ${ err.stack || err.message }`);\n }\n\n if (isWindowClosed(win)) {\n let err = new PopupOpenError(`Can not open popup window - blocked`);\n throw err;\n }\n\n window.addEventListener('unload', () => win.close());\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 let tag = el.tagName.toLowerCase();\n\n if (tag !== 'html') {\n throw new Error(`Expected element to be html, got ${ tag }`);\n }\n\n let 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? : ?Array<string>,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string\n};\n\nlet awaitFrameLoadPromises : WeakMap<HTMLIFrameElement, ZalgoPromise<HTMLIFrameElement>>;\n\nexport function awaitFrameLoad(frame : HTMLIFrameElement) : ZalgoPromise<HTMLIFrameElement> {\n awaitFrameLoadPromises = awaitFrameLoadPromises || new WeakMap();\n\n if (awaitFrameLoadPromises.has(frame)) {\n let promise = awaitFrameLoadPromises.get(frame);\n if (promise) {\n return promise;\n }\n }\n\n let 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<CrossDomainWindowType> {\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\nexport function createElement(tag : string = 'div', options : ElementOptionsType = {}, container : ?HTMLElement) : HTMLElement {\n\n tag = tag.toLowerCase();\n let 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 (let 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\n\nexport type IframeElementOptionsType = {\n style? : { [ string ] : string },\n class? : ?Array<string>,\n attributes? : { [ string ] : string },\n styleSheet? : ?string,\n html? : ?string,\n url? : ?string\n};\n\nexport function iframe(options : IframeElementOptionsType = {}, container : ?HTMLElement) : HTMLIFrameElement {\n\n let attributes = options.attributes || {};\n let style = options.style || {};\n\n let frame = createElement('iframe', {\n attributes: {\n allowTransparency: 'true',\n ...attributes\n },\n style: {\n backgroundColor: 'transparent',\n border: 'none',\n ...style\n },\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 let 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 : Array<string>, handler : (event : Event) => void) : CancelableType {\n\n handler = once(handler);\n\n for (let eventName of eventNames) {\n element.addEventListener(eventName, handler);\n }\n\n return {\n cancel: once(() => {\n for (let 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 let capitalizedName = capitalizeFirstLetter(name);\n\n for (let 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<void> {\n return new ZalgoPromise((resolve, reject) => {\n\n let el = getElement(element);\n\n if (!el) {\n return resolve();\n }\n\n let hasStarted = false;\n\n let startTimeout;\n let endTimeout;\n let startEvent;\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\nconst STYLE = {\n\n DISPLAY: {\n NONE: 'none',\n BLOCK: 'block'\n },\n\n VISIBILITY: {\n VISIBLE: 'visible',\n HIDDEN: 'hidden'\n },\n\n IMPORTANT: 'important'\n};\n\nexport function makeElementVisible(element : HTMLElement) {\n element.style.setProperty('visibility', '');\n}\n\nexport function makeElementInvisible(element : HTMLElement) {\n element.style.setProperty('visibility', STYLE.VISIBILITY.HIDDEN, STYLE.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', STYLE.DISPLAY.NONE, STYLE.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<void> {\n let animation = animate(element, name, clean);\n showElement(element);\n return animation;\n}\n\nexport function animateAndHide(element : HTMLElement, name : string, clean : (Function) => void) : ZalgoPromise<void> {\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) {\n return true;\n }\n return false;\n}\n\nexport function watchElementForClose(element : HTMLElement, handler : () => mixed) : CancelableType {\n handler = once(handler);\n\n let interval;\n\n if (isElementClosed(element)) {\n handler();\n } else {\n interval = safeInterval(() => {\n if (isElementClosed(element)) {\n interval.cancel();\n handler();\n }\n }, 50);\n }\n\n return {\n cancel() {\n if (interval) {\n interval.cancel();\n }\n }\n };\n}\n\nexport function fixScripts(el : HTMLElement, doc : Document = window.document) {\n for (let script of querySelectorAll('script', el)) {\n let parentNode = script.parentNode;\n\n if (!parentNode) {\n continue;\n }\n\n let 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 = {}) : {} {\n let currentWidth = el.offsetWidth;\n let currentHeight = el.offsetHeight;\n\n handler({ width: currentWidth, height: currentHeight });\n\n let check = () => {\n let newWidth = el.offsetWidth;\n let 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 if (typeof win.ResizeObserver !== 'undefined') {\n observer = new win.ResizeObserver(check);\n observer.observe(el);\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 win.addEventListener('resize', check);\n } else {\n let loop = () => {\n check();\n timeout = setTimeout(loop, interval);\n };\n loop();\n }\n\n return {\n cancel: () => {\n observer.disconnect();\n window.removeEventListener('resize', check);\n clearTimeout(timeout);\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 let testWeakMap = new WeakMap();\n let testKey = {};\n let 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","/* @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 let 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\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 = __TEST__ ? 2000 : -1;\nexport const RESPONSE_CYCLE_TIME = 500;\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","/* @flow */\n\nimport { type CrossDomainWindowType, type SameDomainWindowType } from 'cross-domain-utils/src';\nimport { WeakMap } from 'cross-domain-safe-weakmap/src';\nimport { getOrSet } from 'belter/src';\n\nexport function getGlobal(win : SameDomainWindowType = window) : Object {\n if (win !== window) {\n return win[__POST_ROBOT__.__GLOBAL_KEY__];\n }\n const global : Object = win[__POST_ROBOT__.__GLOBAL_KEY__] = win[__POST_ROBOT__.__GLOBAL_KEY__] || {};\n return global;\n}\n\nexport function deleteGlobal() {\n delete window[__POST_ROBOT__.__GLOBAL_KEY__];\n}\n\ntype ObjectGetter = () => Object;\nconst getObj : ObjectGetter = () => ({});\n\ntype GetOrSet<T> = ((string, () => T) => T) & ((string, () => void) => void);\n\ntype GlobalStore<T> = {|\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<T>,\n reset : () => void,\n keys : () => $ReadOnlyArray<string>\n|};\n\n// $FlowFixMe\nexport function globalStore<T : mixed>(key? : string = 'store', defStore? : ObjectGetter = getObj) : GlobalStore<T> {\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<T> = {|\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\n// $FlowFixMe\nexport function windowStore<T>(key? : string = 'store', defStore? : ObjectGetter = getObj) : WindowStore<T> {\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\nimport { getAncestor, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { noop, uniqueID } from 'belter/src';\n\nimport { MESSAGE_NAME, WILDCARD } from '../conf';\nimport { windowStore, globalStore } 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<{ win : CrossDomainWindowType, domain : string }> {\n const helloPromises = windowStore('helloPromises');\n return helloPromises.getOrSet(win, () => new ZalgoPromise());\n}\n\nfunction listenForHello({ on } : { on : OnType }) : CancelableType {\n return on(MESSAGE_NAME.HELLO, { domain: WILDCARD }, ({ source, origin }) => {\n getHelloPromise(source).resolve({ win: 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 getHelloPromise(win).resolve({ win, domain: origin });\n return { win, domain: origin, instanceID };\n });\n}\n\nexport function getWindowInstanceID(win : CrossDomainWindowType, { send } : { send : SendType }) : ZalgoPromise<string> {\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(noop);\n }\n\n return listener;\n });\n}\n\nexport function awaitWindowHello(win : CrossDomainWindowType, timeout : number = 5000, name : string = 'Window') : ZalgoPromise<{ win : CrossDomainWindowType, 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\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\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 { 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<typeof TYPE> | 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 if (Object.prototype.toString.call(val) === '[object RegExp]') {\n return TYPE.REGEX;\n }\n\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<T : string, V : mixed>(type : T, val : V) : CustomSerializedType<T, V> {\n return {\n __type__: type,\n __val__: val\n };\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} from './serializers';\n\ntype NativeSerializer<V : mixed, S : mixed, T : $Values<typeof TYPE>> = (value : V, key : string) => NativeSerializedType<T, S>;\ntype CustomSerializer<V : mixed, S : mixed, T : string> = (value : V, key : string) => CustomSerializedType<T, S>;\ntype PrimitiveSerializer<V : mixed, S : mixed> = (value : V, key : string) => S;\ntype CustomOrPrimitiveSerializer<V : mixed, T : string> = CustomSerializer<V, *, T> | PrimitiveSerializer<V, *>;\ntype NativeOrCustomOrPrimitiveSerializer<V : mixed, S : mixed, T : string> = NativeSerializer<V, S, T> | CustomOrPrimitiveSerializer<V, T>;\n\ntype Serializers = {|\n function? : CustomOrPrimitiveSerializer<Function, typeof TYPE.FUNCTION>,\n error? : NativeOrCustomOrPrimitiveSerializer<Error, SerializedError, typeof TYPE.ERROR>,\n promise? : CustomOrPrimitiveSerializer<Thenable, typeof TYPE.PROMISE>,\n regex? : NativeOrCustomOrPrimitiveSerializer<RegExp, SerializedRegex, typeof TYPE.REGEX>,\n date? : NativeOrCustomOrPrimitiveSerializer<Date, SerializedDate, typeof TYPE.DATE>,\n array? : CustomOrPrimitiveSerializer<$ReadOnlyArray<mixed>, typeof TYPE.ARRAY>,\n object? : CustomOrPrimitiveSerializer<Object, typeof TYPE.OBJECT>,\n string? : CustomOrPrimitiveSerializer<string, typeof TYPE.STRING>,\n number? : CustomOrPrimitiveSerializer<number, typeof TYPE.NUMBER>,\n boolean? : CustomOrPrimitiveSerializer<boolean, typeof TYPE.BOOLEAN>,\n null? : CustomOrPrimitiveSerializer<null, typeof TYPE.NULL>\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};\n\n// $FlowFixMe\nconst defaultSerializers : Serializers = {};\n\nexport function serialize<T : mixed>(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\nexport type SerializedError = {|\n message : string,\n stack : string,\n code : string | number | void\n|};\n\n// $FlowFixMe\nexport function serializeError({ message, stack, code } : Error) : NativeSerializedType<typeof TYPE.ERROR, SerializedError> {\n return serializeType(TYPE.ERROR, { message, stack, code });\n}\n\nexport function deserializeError({ message, stack, code } : SerializedError) : Error {\n const error = new Error(message);\n // $FlowFixMe\n error.code = code;\n error.stack = `${ stack }\\n\\n${ error.stack }`;\n return error;\n}\n","/* @flow */\n\nexport type SerializedPromise = void;\n\nexport function serializePromise() : SerializedPromise {\n // pass\n}\n\nexport function deserializePromise() {\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<typeof TYPE.REGEX, SerializedRegex> {\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<typeof TYPE.DATE, SerializedDate> {\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<T : mixed = mixed> = $ReadOnlyArray<T>;\n\nexport function serializeArray<T : mixed>(val : $ReadOnlyArray<T>) : SerializedArray<T> {\n return val;\n}\n\nexport function deserializeArray<T : mixed>(val : SerializedArray<T>) : $ReadOnlyArray<T> {\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 { 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} from './serializers';\n\ntype Deserializer<V : mixed, S : mixed> = (serializedValue : S, key : string) => V;\ntype PrimitiveDeserializer<V, S = V> = (serializedValue : S, key : string) => V;\n\ntype Deserializers = {\n function? : Deserializer<Function, *>,\n error? : Deserializer<Error, SerializedError>,\n promise? : Deserializer<Thenable, *>,\n regex? : Deserializer<RegExp, SerializedRegex>,\n date? : Deserializer<Date, SerializedDate>,\n array? : PrimitiveDeserializer<$ReadOnlyArray<mixed>>,\n object? : PrimitiveDeserializer<Object>,\n string? : PrimitiveDeserializer<string>,\n number? : PrimitiveDeserializer<number>,\n boolean? : PrimitiveDeserializer<boolean>,\n null? : PrimitiveDeserializer<null>,\n [string] : Deserializer<mixed, *>\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};\n\n// $FlowFixMe\nconst defaultDeserializers : Deserializers = {};\n\nexport function deserialize<T : mixed | null | void>(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 } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { uniqueID, memoizePromise } from 'belter/src';\nimport { serializeType, type CustomSerializedType } from 'universal-serialize/src';\n\nimport { SERIALIZATION_TYPE } from '../conf';\nimport { windowStore, globalStore } from '../global';\nimport { getWindowInstanceID } from '../lib';\nimport { linkWindow } from '../bridge';\nimport type { OnType, 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 SerializedProxyWindow = {|\n id : string,\n type : $Values<typeof WINDOW_TYPE>,\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n isClosed : () => ZalgoPromise<boolean>,\n setLocation : (string) => ZalgoPromise<void>,\n getName : () => ZalgoPromise<?string>,\n setName : (string) => ZalgoPromise<void>,\n getInstanceID : () => ZalgoPromise<string>\n|};\n\nfunction getSerializedWindow(id : string, win : CrossDomainWindowType, { send } : { send : SendType }) : SerializedProxyWindow {\n let windowName;\n \n return {\n id,\n type: getOpener(win) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME,\n getInstanceID: memoizePromise(() => getWindowInstanceID(win, { send })),\n close: () => ZalgoPromise.try(() => {\n closeWindow(win);\n }),\n getName: () => ZalgoPromise.try(() => {\n if (isWindowClosed(win)) {\n return;\n }\n\n return windowName;\n }),\n focus: () => ZalgoPromise.try(() => {\n win.focus();\n }),\n isClosed: () => ZalgoPromise.try(() => {\n return isWindowClosed(win);\n }),\n setLocation: (href) => ZalgoPromise.try(() => {\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 setName: (name) => ZalgoPromise.try(() => {\n if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) {\n linkWindow({ win, name });\n }\n\n win = assertSameDomain(win);\n\n win.name = name;\n\n if (win.frameElement) {\n win.frameElement.setAttribute('name', name);\n }\n\n windowName = name;\n })\n };\n}\n\nexport class ProxyWindow {\n\n isProxyWindow : true = true\n serializedWindow : SerializedProxyWindow\n actualWindow : CrossDomainWindowType\n actualWindowPromise : ZalgoPromise<CrossDomainWindowType>\n send : SendType\n name : string\n\n constructor(serializedWindow : SerializedProxyWindow, actualWindow? : ?CrossDomainWindowType, { send } : { send : SendType }) {\n this.serializedWindow = serializedWindow;\n this.actualWindowPromise = new ZalgoPromise();\n this.send = send;\n if (actualWindow) {\n this.setWindow(actualWindow);\n }\n }\n\n getType() : $Values<typeof WINDOW_TYPE> {\n return this.serializedWindow.type;\n }\n\n isPopup() : boolean {\n return this.getType() === WINDOW_TYPE.POPUP;\n }\n\n isIframe() : boolean {\n return this.getType() === WINDOW_TYPE.IFRAME;\n }\n\n setLocation(href : string) : ZalgoPromise<ProxyWindow> {\n return this.serializedWindow.setLocation(href).then(() => this);\n }\n\n setName(name : string) : ZalgoPromise<ProxyWindow> {\n return this.serializedWindow.setName(name).then(() => this);\n }\n\n close() : ZalgoPromise<ProxyWindow> {\n return this.serializedWindow.close().then(() => this);\n }\n\n focus() : ZalgoPromise<ProxyWindow> {\n return ZalgoPromise.try(() => {\n return ZalgoPromise.all([\n this.isPopup() && this.serializedWindow.getName().then(name => {\n if (name) {\n window.open('', name);\n }\n }),\n this.serializedWindow.focus()\n ]);\n }).then(() => this);\n }\n\n isClosed() : ZalgoPromise<boolean> {\n return this.serializedWindow.isClosed();\n }\n\n getWindow() : ?CrossDomainWindowType {\n return this.actualWindow;\n }\n\n setWindow(win : CrossDomainWindowType) {\n this.actualWindow = win;\n this.serializedWindow = getSerializedWindow(this.serializedWindow.id, win, { send: this.send });\n this.actualWindowPromise.resolve(win);\n }\n\n awaitWindow() : ZalgoPromise<CrossDomainWindowType> {\n return this.actualWindowPromise;\n }\n\n matchWindow(win : CrossDomainWindowType) : ZalgoPromise<boolean> {\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: this.send })\n }).then(({ proxyInstanceID, knownWindowInstanceID }) => {\n const match = proxyInstanceID === knownWindowInstanceID;\n\n if (match) {\n this.setWindow(win);\n }\n\n return match;\n });\n });\n }\n\n unwrap() : CrossDomainWindowType | ProxyWindow {\n return this.actualWindow || this;\n }\n\n getInstanceID() : ZalgoPromise<string> {\n return this.serializedWindow.getInstanceID();\n }\n\n serialize() : SerializedProxyWindow {\n return this.serializedWindow;\n }\n\n shouldClean() : boolean {\n return this.actualWindow && isWindowClosed(this.actualWindow);\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 }) : SerializedProxyWindow {\n cleanupProxyWindows();\n\n return ProxyWindow.toProxyWindow(win, { send }).serialize();\n }\n\n static deserialize(serializedWindow : SerializedProxyWindow, { on, send } : { on : OnType, send : SendType }) : ProxyWindow {\n cleanupProxyWindows();\n \n return globalStore('idToProxyWindow').getOrSet(serializedWindow.id, () => {\n return new ProxyWindow(serializedWindow, null, { on, send });\n });\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 realWin : CrossDomainWindowType = win;\n\n // $FlowFixMe\n return windowStore('winToProxyWindow').getOrSet(win, () => {\n const id = uniqueID();\n const serializedWindow = getSerializedWindow(id, realWin, { send });\n const proxyWindow = new ProxyWindow(serializedWindow, realWin, { send });\n\n return globalStore('idToProxyWindow').set(id, proxyWindow);\n });\n }\n}\n\nexport type SerializedWindow = CustomSerializedType<typeof SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, SerializedProxyWindow>;\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 : SerializedProxyWindow, { on, send } : { on : OnType, send : SendType }) : ProxyWindow {\n return ProxyWindow.deserialize(win, { on, 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 = 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<void> {\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 } 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 listenForFunctionCalls({ on } : { on : OnType }) : 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 '${ data.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).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 }()\\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<typeof SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, {\n id : string,\n name : string\n}>;\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype SerializableFunction<T> = {\n () : ZalgoPromise<T> | T,\n __id__? : string,\n __name__? : string\n};\n\nexport function serializeFunction<T>(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, val : SerializableFunction<T>, key : string, { on } : { on : OnType }) : SerializedFunction {\n listenForFunctionCalls({ on });\n \n const id = val.__id__ || uniqueID();\n destination = ProxyWindow.unwrap(destination);\n const name = val.__name__ || val.name || key;\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<T>(source : CrossDomainWindowType | ProxyWindow, origin : string, { id, name } : { id : string, name : string }, { send } : { send : SendType }) : (...args : $ReadOnlyArray<mixed>) => ZalgoPromise<T> {\n const getDeserializedFunction = (opts? : Object = {}) => {\n function crossDomainFunctionWrapper<X : mixed>() : ZalgoPromise<X> {\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\n const options = { domain: origin, fireAndForget: opts.fireAndForget };\n const args = Array.prototype.slice.call(arguments);\n\n return send(win, MESSAGE_NAME.METHOD, { id, name, args }, options)\n .then(res => {\n if (!opts.fireAndForget) {\n return res.data.result;\n }\n });\n }\n \n }).catch(err => {\n // $FlowFixMe\n if (__DEBUG__ && originalStack && err.stack) {\n // $FlowFixMe\n err.stack = `${ 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<T : mixed>(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, { on, send }) : val;\n }\n });\n}\n\nexport function deserializeMessage<T : mixed>(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string, { on, 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, { on, send }),\n [ SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW ]: (serializedWindow) => deserializeWindow(source, origin, serializedWindow, { on, 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<typeof SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {\n then : SerializedFunction\n}>;\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<T>(source : CrossDomainWindowType | ProxyWindow, origin : string, { then } : { then : Function }) : ZalgoPromise<T> {\n return new ZalgoPromise(then);\n}\n","/* @flow */\n\nimport { isSameDomain, isSameTopWindow, isActuallySameDomain, getActualDomain,\n getDomain, type CrossDomainWindowType, type DomainMatcher, 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\nexport const SEND_MESSAGE_STRATEGIES = {};\n\nSEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = (win : CrossDomainWindowType, serializedMessage : string, domain : DomainMatcher) => {\n\n if (__TEST__) {\n if (needsGlobalMessagingForBrowser() && isSameTopWindow(window, win) === false) {\n return;\n }\n }\n\n let domains;\n\n if (Array.isArray(domain)) {\n domains = domain;\n } else if (typeof domain === 'string') {\n domains = [ domain ];\n } else {\n domains = [ WILDCARD ];\n }\n\n domains = domains.map(dom => {\n\n if (__TEST__) {\n if (dom.indexOf(PROTOCOL.MOCK) === 0) {\n if (window.location.protocol === PROTOCOL.FILE) {\n return WILDCARD;\n }\n\n if (!isActuallySameDomain(win)) {\n throw new Error(`Attempting to send messsage to mock domain ${ dom }, but window is actually cross-domain`);\n }\n\n // $FlowFixMe\n return getActualDomain(win);\n\n }\n }\n \n if (dom.indexOf(PROTOCOL.FILE) === 0) {\n return WILDCARD;\n }\n\n return dom;\n });\n\n domains.forEach(dom => {\n win.postMessage(serializedMessage, dom);\n });\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 return;\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 return;\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 { isWindowClosed, getDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { uniqueID, stringifyError } from 'belter/src';\n\nimport { serializeMessage } from '../../serialize';\nimport type { Message } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nimport { SEND_MESSAGE_STRATEGIES } from './strategies';\n\nexport function sendMessage(win : CrossDomainWindowType, domain : DomainMatcher, message : Message, { on, send } : { on : OnType, send : SendType }) {\n if (isWindowClosed(win)) {\n throw new Error('Window is closed');\n }\n \n const serializedMessage = serializeMessage(win, domain, {\n [ __POST_ROBOT__.__GLOBAL_KEY__ ]: {\n id: uniqueID(),\n origin: getDomain(window),\n ...message\n }\n }, { on, send });\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(stringifyError).join('\\n\\n') }`);\n }\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 { type ZalgoPromise } from 'zalgo-promise/src';\nimport { matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';\nimport { isRegex, getOrSet } from 'belter/src';\n\nimport { getWildcard, type WildCard, globalStore, windowStore } from '../global';\nimport { WILDCARD } from '../conf';\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<mixed>),\n handleError : (err : mixed) => void,\n window : ?CrossDomainWindowType,\n name : string,\n domain : DomainMatcher\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\nexport function addRequestListener({ name, win, domain } : { name : string, win : ?(CrossDomainWindowType | WildCard), 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 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\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 nameListeners = requestListeners.getOrSet(win, () => ({}));\n // $FlowFixMe\n const domainListeners = getOrSet(nameListeners, name, () => ({}));\n\n const strDomain = domain.toString();\n\n let regexListeners;\n let regexListener;\n\n if (isRegex(domain)) {\n regexListeners = getOrSet(domainListeners, __DOMAIN_REGEX__, () => []);\n regexListener = { regex: domain, listener };\n regexListeners.push(regexListener);\n } else {\n domainListeners[strDomain] = listener;\n }\n\n return {\n cancel() {\n delete domainListeners[strDomain];\n\n if (regexListener) {\n regexListeners.splice(regexListeners.indexOf(regexListener, 1));\n\n if (!regexListeners.length) {\n delete domainListeners[__DOMAIN_REGEX__];\n }\n }\n\n if (!Object.keys(domainListeners).length) {\n // $FlowFixMe\n delete nameListeners[name];\n }\n\n // $FlowFixMe\n if (win && !Object.keys(nameListeners).length) {\n requestListeners.del(win);\n }\n }\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { isWindowClosed, matchDomain, stringifyDomainPattern, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { noop } 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, SuccessResponseMessage, ErrorResponseMessage } from '../types';\nimport type { OnType, SendType } from '../../types';\n\nexport const RECEIVE_MESSAGE_TYPES = {\n\n [ MESSAGE_TYPE.REQUEST ](source : CrossDomainWindowType, origin : string, message : RequestMessage, { on, send } : { on : OnType, send : SendType }) : ZalgoPromise<void> {\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 sendResponse(type : $Values<typeof MESSAGE_TYPE>, ack? : $Values<typeof MESSAGE_ACK>, response = {}) {\n\n if (message.fireAndForget || isWindowClosed(source)) {\n return;\n }\n\n if (__DEBUG__ && type !== MESSAGE_TYPE.ACK) {\n if (ack === MESSAGE_ACK.SUCCESS) {\n // $FlowFixMe\n console.info('respond::res', logName, origin, '\\n\\n', response.data); // eslint-disable-line no-console\n } else if (ack === MESSAGE_ACK.ERROR) {\n // $FlowFixMe\n console.error('respond::err', logName, origin, '\\n\\n', response.error); // eslint-disable-line no-console\n }\n }\n\n // $FlowFixMe\n sendMessage(source, origin, {\n type,\n ack,\n hash: message.hash,\n name: message.name,\n ...response\n }, { on, send });\n }\n\n return ZalgoPromise.all([\n\n sendResponse(MESSAGE_TYPE.ACK),\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 if (!matchDomain(options.domain, origin)) {\n throw new Error(`Request origin ${ origin } does not match domain ${ options.domain.toString() }`);\n }\n\n const data = message.data;\n\n return options.handler({ source, origin, data });\n\n }).then(data => {\n return sendResponse(MESSAGE_TYPE.RESPONSE, MESSAGE_ACK.SUCCESS, { data });\n\n }, error => {\n return sendResponse(MESSAGE_TYPE.RESPONSE, MESSAGE_ACK.ERROR, { 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\n [ MESSAGE_TYPE.ACK ](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 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\n options.ack = true;\n },\n\n [ MESSAGE_TYPE.RESPONSE ](source : CrossDomainWindowType, origin : string, message : SuccessResponseMessage | ErrorResponseMessage) : void | ZalgoPromise<void> {\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};\n","/* @flow */\n\nimport { isWindowClosed, type CrossDomainWindowType, getDomain, isSameTopWindow, PROTOCOL } from 'cross-domain-utils/src';\nimport { addEventListener, noop } from 'belter/src';\n\nimport { markWindowKnown, needsGlobalMessagingForBrowser } from '../../lib';\nimport { deserializeMessage } from '../../serialize';\nimport { getGlobal, globalStore } from '../../global';\nimport type { OnType, SendType, MessageEvent, CancelableType } from '../../types';\n\nimport { RECEIVE_MESSAGE_TYPES } from './types';\n\nfunction parseMessage(message : string, source : CrossDomainWindowType, origin : string, { on, send } : { on : OnType, send : SendType }) : ?Object {\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 parsedMessage = parsedMessage[__POST_ROBOT__.__GLOBAL_KEY__];\n\n if (!parsedMessage || typeof parsedMessage !== 'object' || parsedMessage === null) {\n return;\n }\n\n if (!parsedMessage.type || typeof parsedMessage.type !== 'string') {\n return;\n }\n\n if (!RECEIVE_MESSAGE_TYPES[parsedMessage.type]) {\n return;\n }\n\n return parsedMessage;\n}\n\nexport function receiveMessage(event : MessageEvent, { on, send } : { on : OnType, send : SendType }) {\n const receivedMessages = globalStore('receivedMessages');\n\n if (!window || window.closed) {\n throw new Error(`Message recieved in closed window`);\n }\n\n try {\n if (!event.source) {\n return;\n }\n } catch (err) {\n return;\n }\n\n let { source, origin, data } = event;\n\n if (__TEST__) {\n // $FlowFixMe\n origin = getDomain(source);\n }\n\n const message = parseMessage(data, source, origin, { on, send });\n\n if (!message) {\n return;\n }\n\n markWindowKnown(source);\n\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 RECEIVE_MESSAGE_TYPES[message.type](source, origin, message, { on, send });\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\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\nexport function listenForMessages({ on, send } : { on : OnType, send : SendType }) : CancelableType {\n return globalStore().getOrSet('postMessageListener', () => {\n // $FlowFixMe\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, type RequestListenerType } from '../drivers';\nimport { WILDCARD } from '../conf';\nimport type { ServerOptionsType, HandlerType, CancelableType } from '../types';\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 if (typeof options === 'function') {\n handler = options;\n // $FlowFixMe\n options = {};\n }\n\n if (!handler) {\n throw new Error('Expected handler');\n }\n\n options = options || {};\n options.name = name;\n options.handler = handler || options.handler;\n\n const win = options.window;\n const domain = options.domain;\n\n const listenerOptions : RequestListenerType = {\n handler: options.handler,\n handleError: options.errorHandler || (err => {\n throw err;\n }),\n window: win,\n domain: domain || WILDCARD,\n name\n };\n\n const requestListener = addRequestListener({ name, win, domain }, listenerOptions);\n\n return {\n cancel() {\n requestListener.cancel();\n }\n };\n}\n\nexport function once(name : string, options? : ServerOptionsType | HandlerType, handler? : HandlerType) : ZalgoPromise<{ source : mixed, origin : string, data : Object }> {\n \n // $FlowFixMe\n options = options || {};\n if (typeof options === 'function') {\n handler = options;\n // $FlowFixMe\n options = {};\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 promise.cancel = listener.cancel;\n return promise;\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 } 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 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(`Expected domain to be a string, array, or regex`);\n }\n }\n\n if (isWindowClosed(win)) {\n throw new Error('Target window is closed');\n }\n}\n\nfunction normalizeDomain(win : CrossDomainWindowType, domain : DomainMatcher, childTimeout : number, { send } : { send : SendType }) : ZalgoPromise<string | $ReadOnlyArray<string>> {\n return ZalgoPromise.try(() => {\n if (isAncestor(window, win)) {\n return awaitWindowHello(win, childTimeout);\n } else if (isRegex(domain)) {\n // $FlowFixMe\n return sayHello(win, { send });\n } else {\n return { domain };\n }\n // $FlowFixMe\n }).then(({ domain: normalizedDomain }) => {\n\n // $FlowFixMe\n return normalizedDomain;\n });\n}\n\nexport const send : SendType = (win, name, data, options) => {\n\n // $FlowFixMe\n options = options || {};\n let domain = 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 // $FlowFixMe\n return ZalgoPromise.try(() => {\n validateOptions(name, win, domain);\n return normalizeDomain(win, domain, childTimeout, { send });\n }).then(targetDomain => {\n\n if (!matchDomain(domain, targetDomain)) {\n throw new Error(`Domain ${ stringify(domain) } does not match ${ stringify(targetDomain) }`);\n }\n\n 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 sendMessage(win, domain, {\n type: MESSAGE_TYPE.REQUEST,\n hash,\n name,\n data,\n fireAndForget\n }, { on, send });\n \n return fireAndForget ? promise.resolve() : promise;\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, toProxyWindow } from './setup';\nexport { on, once, send } from './public';\nexport { markWindowKnown } from './lib';\nexport { cleanUpWindow } from './clean';\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\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<T>(destination : CrossDomainWindowType | ProxyWindow, domain : DomainMatcher, obj : T) : string {\n return internalSerializeMessage(destination, domain, obj, { on, send });\n}\n\nexport function deserializeMessage<T : mixed>(source : CrossDomainWindowType | ProxyWindow, origin : string, message : string) : T {\n return internalDeserializeMessage(source, origin, message, { on, send });\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';\n\nexport function getGlobal(win? : CrossDomainWindowType = window) : Object {\n\n if (!isSameDomain(win)) {\n throw new Error(`Can not get global for window on different domain`);\n }\n\n if (!win[__ZOID__.__GLOBAL_KEY__]) {\n win[__ZOID__.__GLOBAL_KEY__] = {};\n }\n\n return win[__ZOID__.__GLOBAL_KEY__];\n}\n\nexport function destroyGlobal() {\n delete window[__ZOID__.__GLOBAL_KEY__];\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\n\nexport type ProxyObject<T> = {|\n get : () => ZalgoPromise<T>\n|};\n\nexport function getProxyObject<T>(obj : T) : ProxyObject<T> {\n return {\n get() : ZalgoPromise<T> {\n return ZalgoPromise.try(() => {\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","/* @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`,\n OBJECT: `object`,\n FUNCTION: `function`,\n BOOLEAN: `boolean`,\n NUMBER: `number`,\n ARRAY: `array`\n};\n\nexport const INITIAL_PROPS = {\n RAW: 'raw',\n UID: 'uid'\n};\n\nexport const WINDOW_REFERENCES = {\n OPENER: ('opener' : 'opener'),\n PARENT: ('parent' : 'parent'),\n GLOBAL: ('global' : 'global')\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 PROPS: 'zoid-props',\n RESIZE: 'zoid-resize'\n};\n","/* @flow */\n\nimport { getDomain, isSameDomain, type CrossDomainWindowType } from 'cross-domain-utils/src';\n\nimport type { Component } from '../component';\nimport type { PropsType, MixedPropDefinitionType } from '../component/props';\n\nimport type { ChildHelpers } from './index';\n\nexport function normalizeChildProp<T, P>(component : Component<P>, props : (PropsType<P>), key : string, value : T, helpers : ChildHelpers<P>) : ?T {\n\n // $FlowFixMe\n const prop : MixedPropDefinitionType<P> = component.getPropDefinition(key);\n\n if (!prop) {\n return value;\n }\n\n if (typeof prop.childDecorate === 'function') {\n return prop.childDecorate({ value, ...helpers });\n }\n\n return value;\n}\n\n// eslint-disable-next-line max-params\nexport function normalizeChildProps<P>(parentComponentWindow : CrossDomainWindowType, component : Component<P>, props : (PropsType<P>), origin : string, helpers : ChildHelpers<P>, isUpdate : boolean = false) : (PropsType<P>) {\n\n const result = {};\n\n for (const key of Object.keys(props)) {\n const prop = component.getPropDefinition(key);\n\n if (prop && prop.sameDomain && (origin !== getDomain(window) || !isSameDomain(parentComponentWindow))) {\n continue;\n }\n\n // $FlowFixMe\n const value = normalizeChildProp(component, 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 component.getPropNames()) {\n if (!props.hasOwnProperty(key)) {\n result[key] = normalizeChildProp(component, props, key, props[key], helpers);\n }\n }\n }\n\n // $FlowFixMe\n return result;\n}\n","/* @flow */\n\nimport { inlineMemoize, stringifyError, base64decode } from 'belter/src';\n\nimport { ZOID } from '../constants';\nimport type { ChildPayload } from '../parent';\n\nfunction parseChildWindowName(windowName : string) : ChildPayload {\n return inlineMemoize(parseChildWindowName, () => {\n if (!windowName) {\n throw new Error(`No window name`);\n }\n \n const [ , zoidcomp, name, encodedPayload ] = 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 (!encodedPayload) {\n throw new Error(`Expected encoded payload`);\n }\n \n try {\n return JSON.parse(base64decode(encodedPayload));\n } catch (err) {\n throw new Error(`Can not decode window name payload: ${ encodedPayload }: ${ stringifyError(err) }`);\n }\n }, [ windowName ]);\n}\n\nexport function getChildPayload() : ?ChildPayload {\n try {\n return parseChildWindowName(window.name);\n } catch (err) {\n // pass\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { isSameDomain, matchDomain, getDomain, getOpener,\n getNthParentFromTop, getAncestor, getAllFramesInWindow,\n type CrossDomainWindowType, onCloseWindow } from 'cross-domain-utils/src';\nimport { markWindowKnown, deserializeMessage, type CrossDomainFunctionType } from 'post-robot/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { extend, waitForDocumentBody, onResize, getElementSafe, assertExists } from 'belter/src';\n\nimport { getGlobal } from '../lib';\nimport { CONTEXT, INITIAL_PROPS, WINDOW_REFERENCES } from '../constants';\nimport type { Component } from '../component';\nimport type { PropsType } from '../component/props';\nimport type { WindowRef, PropRef, ParentExportsType } from '../parent';\n\nimport { normalizeChildProps } from './props';\nimport { getChildPayload } from './window';\n\nexport * from './window';\n\nexport type ChildExportsType<P> = {|\n updateProps : CrossDomainFunctionType<[ PropsType<P> ], void>,\n close : CrossDomainFunctionType<[], void>\n|};\n\nexport type ChildHelpers<P> = {|\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n resize : ({ width : ?number, height : ?number }) => ZalgoPromise<void>,\n onError : (mixed) => ZalgoPromise<void>,\n onProps : ((PropsType<P>) => void) => void,\n getParent : () => CrossDomainWindowType,\n getParentDomain : () => string\n|};\n\n/* Child Component\n ---------------\n\n This is the portion of code which runs inside the frame or popup window containing the component's implementation.\n\n When the component author calls myComponent.attach(), it creates a new instance of ChildComponent, which is then\n responsible for managing the state and messaging back up to the parent, and providing props for the component to\n utilize.\n*/\n\nexport class ChildComponent<P> {\n\n component : Component<P>\n props : PropsType<P>\n context : string\n parent : ParentExportsType<P>\n parentDomain : string\n parentComponentWindow : CrossDomainWindowType\n\n onPropHandlers : Array<(PropsType<P>) => void> // eslint-disable-line flowtype/no-mutable-array\n autoResize : { width : boolean, height : boolean, element? : string }\n\n constructor(component : Component<P>) {\n ZalgoPromise.try(() => {\n this.component = component;\n this.onPropHandlers = [];\n \n const childPayload = getChildPayload();\n\n if (!childPayload) {\n throw new Error(`No child payload found`);\n }\n\n if (childPayload.version !== __ZOID__.__VERSION__) {\n throw new Error(`Parent window has zoid version ${ childPayload.version }, child window has version ${ __ZOID__.__VERSION__ }`);\n }\n\n const { parent, parentDomain, exports, context, props } = childPayload;\n\n this.context = context;\n this.parentComponentWindow = this.getParentComponentWindow(parent);\n this.parentDomain = parentDomain;\n this.parent = deserializeMessage(this.parentComponentWindow, parentDomain, exports);\n\n this.checkParentDomain(parentDomain);\n\n const initialProps = this.getPropsByRef(this.parentComponentWindow, parentDomain, props);\n this.setProps(initialProps, parentDomain);\n markWindowKnown(this.parentComponentWindow);\n \n this.watchForClose();\n\n return this.parent.init(this.buildExports());\n\n }).then(() => {\n return this.watchForResize();\n\n }).catch(err => {\n this.onError(err);\n });\n }\n\n getHelpers() : ChildHelpers<P> {\n return {\n focus: () => this.focus(),\n close: () => this.close(),\n resize: ({ width, height }) => this.resize({ width, height }),\n onError: (err) => this.onError(err),\n onProps: (handler) => this.onProps(handler),\n getParent: () => this.parentComponentWindow,\n getParentDomain: () => this.parentDomain\n };\n }\n\n checkParentDomain(domain : string) {\n if (!matchDomain(this.component.allowedParentDomains, domain)) {\n throw new Error(`Can not be rendered by domain: ${ domain }`);\n }\n }\n\n onProps(handler : Function) {\n this.onPropHandlers.push(handler);\n }\n\n getPropsByRef(parentComponentWindow : CrossDomainWindowType, domain : string, { type, value, uid } : PropRef) : (PropsType<P>) {\n let props;\n\n if (type === INITIAL_PROPS.RAW) {\n props = value;\n } else if (type === INITIAL_PROPS.UID) {\n if (!isSameDomain(parentComponentWindow)) {\n throw new Error(`Parent component window is on a different domain - expected ${ getDomain() } - can not retrieve props`);\n }\n\n const global = getGlobal(parentComponentWindow);\n props = assertExists('props', global && global.props[uid]);\n }\n\n if (!props) {\n throw new Error(`Could not find props`);\n }\n\n return deserializeMessage(parentComponentWindow, domain, props);\n }\n\n getParentComponentWindow(ref : WindowRef) : CrossDomainWindowType {\n const { type } = ref;\n \n if (type === WINDOW_REFERENCES.OPENER) {\n return assertExists('opener', getOpener(window));\n \n } else if (type === WINDOW_REFERENCES.PARENT && typeof ref.distance === 'number') {\n return assertExists('parent', getNthParentFromTop(window, ref.distance));\n\n } else if (type === WINDOW_REFERENCES.GLOBAL && ref.uid && typeof ref.uid === 'string') {\n const { uid } = ref;\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 global = getGlobal(frame);\n\n if (global && global.windows && global.windows[uid]) {\n return global.windows[uid];\n }\n }\n }\n }\n \n throw new Error(`Unable to find ${ type } parent component window`);\n }\n\n getProps() : PropsType<P> {\n // $FlowFixMe\n this.props = this.props || {};\n return this.props;\n }\n\n setProps(props : PropsType<P>, origin : string, isUpdate : boolean = false) {\n const helpers = this.getHelpers();\n const existingProps = this.getProps();\n const normalizedProps = normalizeChildProps(this.parentComponentWindow, this.component, props, origin, helpers, isUpdate);\n\n extend(existingProps, normalizedProps);\n\n for (const handler of this.onPropHandlers) {\n handler.call(this, existingProps);\n }\n }\n\n watchForClose() {\n window.addEventListener('beforeunload', () => {\n this.parent.checkClose.fireAndForget();\n });\n\n window.addEventListener('unload', () => {\n this.parent.checkClose.fireAndForget();\n });\n\n onCloseWindow(this.parentComponentWindow, () => {\n this.destroy();\n });\n }\n\n getAutoResize() : { width : boolean, height : boolean, element : ?HTMLElement } {\n let { width = false, height = false, element = 'body' } = this.autoResize || this.component.autoResize || {};\n element = getElementSafe(element);\n return { width, height, element };\n }\n\n watchForResize() : ?ZalgoPromise<void> {\n return waitForDocumentBody().then(() => {\n const { width, height, element } = this.getAutoResize();\n\n if (!element || (!width && !height) || this.context === CONTEXT.POPUP) {\n return;\n }\n\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n this.resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height });\n });\n }\n\n buildExports() : ChildExportsType<P> {\n\n const self = this;\n\n return {\n updateProps(props : (PropsType<P>)) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => self.setProps(props, this.__origin__, true));\n },\n\n close() : ZalgoPromise<void> {\n return ZalgoPromise.try(() => self.destroy());\n }\n };\n }\n\n resize({ width, height } : { width : ?number, height : ?number }) : ZalgoPromise<void> {\n return this.parent.resize.fireAndForget({ width, height });\n }\n\n close() : ZalgoPromise<void> {\n return this.parent.close();\n }\n \n destroy() : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n window.close();\n });\n }\n\n focus() : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n window.focus();\n });\n }\n\n onError(err : mixed) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n if (this.parent && this.parent.onError) {\n return this.parent.onError(err);\n } else {\n throw err;\n }\n });\n }\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { cleanUpWindow, ProxyWindow, toProxyWindow } from 'post-robot/src';\nimport { assertSameDomain, closeWindow } from 'cross-domain-utils/src';\nimport { iframe, popup, destroyElement, normalizeDimension, watchElementForClose,\n awaitFrameWindow, uniqueID } from 'belter/src';\n\nimport { CONTEXT } from '../constants';\nimport { getProxyObject, type ProxyObject } from '../lib';\n\n\nexport type ContextDriverType = {|\n openOnClick : boolean,\n openFrame? : () => ProxyObject<HTMLIFrameElement>,\n open : (?ProxyObject<HTMLIFrameElement>) => ZalgoPromise<ProxyWindow>,\n openPrerenderFrame? : () => ProxyObject<HTMLIFrameElement>,\n openPrerender : (ProxyWindow, ?ProxyObject<HTMLIFrameElement>) => ZalgoPromise<ProxyWindow>,\n resize? : ({ width : ?number, height : ?number }) => void,\n delegate : $ReadOnlyArray<string>\n|};\n\nexport const RENDER_DRIVERS : { [string] : ContextDriverType } = {};\n\nRENDER_DRIVERS[CONTEXT.IFRAME] = {\n openOnClick: false,\n\n openFrame() : ProxyObject<HTMLIFrameElement> {\n return getProxyObject(iframe({\n attributes: {\n title: this.component.name,\n ...this.component.attributes.iframe\n }\n }));\n },\n\n open(proxyFrame : ?ProxyObject<HTMLIFrameElement>) : ZalgoPromise<ProxyWindow> {\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\n const frameWatcher = watchElementForClose(frame, () => this.close());\n this.clean.register(() => frameWatcher.cancel());\n this.clean.register(() => destroyElement(frame));\n this.clean.register(() => cleanUpWindow(win));\n\n return toProxyWindow(win);\n });\n });\n },\n\n openPrerenderFrame() : ProxyObject<HTMLIFrameElement> {\n return getProxyObject(iframe({\n attributes: {\n name: `__zoid_prerender_frame__${ this.component.name }_${ uniqueID() }__`,\n title: `prerender__${ this.component.name }`,\n ...this.component.attributes.iframe\n }\n }));\n },\n\n openPrerender(proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject<HTMLIFrameElement>) : ZalgoPromise<ProxyWindow> {\n if (!proxyPrerenderFrame) {\n throw new Error(`Expected proxy frame to be passed`);\n }\n \n return proxyPrerenderFrame.get().then(prerenderFrame => {\n this.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 },\n\n delegate: [\n 'getProxyContainer',\n 'renderContainer',\n 'openFrame',\n 'openPrerenderFrame',\n 'prerender',\n 'open',\n 'openPrerender'\n ]\n};\n\nif (__ZOID__.__POPUP_SUPPORT__) {\n RENDER_DRIVERS[CONTEXT.POPUP] = {\n openOnClick: true,\n\n open() : ZalgoPromise<ProxyWindow> {\n return ZalgoPromise.try(() => {\n let { width, height } = this.component.dimensions;\n\n width = normalizeDimension(width, window.outerWidth);\n height = normalizeDimension(height, window.outerWidth);\n\n const win = popup('', {\n width,\n height,\n ...this.component.attributes.popup\n });\n\n this.clean.register(() => {\n closeWindow(win);\n cleanUpWindow(win);\n });\n\n return toProxyWindow(win);\n });\n },\n\n openPrerender(proxyWin : ProxyWindow) : ZalgoPromise<ProxyWindow> {\n return ZalgoPromise.try(() => {\n return proxyWin;\n });\n },\n\n delegate: [\n 'getProxyContainer',\n 'renderContainer',\n 'setProxyWin'\n ]\n };\n}\n","/* @flow */\n\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { dotify, isDefined, extend } from 'belter/src';\n\nimport type { Component } from '../component';\nimport type { BuiltInPropsDefinitionType, PropsInputType, PropsType, MixedPropDefinitionType } from '../component/props';\nimport { PROP_SERIALIZATION } from '../constants';\n\nimport type { ParentHelpers } from './index';\n\n/* Normalize Props\n ---------------\n\n Turn props into normalized values, using defaults, function options, etc.\n*/\n\nexport function extendProps<P>(component : Component<P>, props : PropsType<P>, inputProps : PropsInputType<P>, helpers : ParentHelpers<P>, isUpdate : boolean = false) { // eslint-disable-line complexity\n\n // $FlowFixMe\n inputProps = inputProps || {};\n extend(props, inputProps);\n\n const propNames = isUpdate ? [] : [ ...component.getPropNames() ];\n\n for (const key of Object.keys(inputProps)) {\n if (propNames.indexOf(key) === -1) {\n propNames.push(key);\n }\n }\n\n const aliases = [];\n\n const { state, close, focus, onError } = helpers;\n\n for (const key of propNames) {\n const propDef = component.getPropDefinition(key);\n let value = inputProps[key];\n\n if (!propDef) {\n continue;\n }\n\n const alias = propDef.alias;\n if (alias) {\n if (!isDefined(value) && isDefined(inputProps[alias])) {\n value = inputProps[alias];\n }\n aliases.push(alias);\n }\n\n if (propDef.value) {\n value = propDef.value({ props, state, close, focus, onError });\n }\n\n if (!isDefined(value) && propDef.default) {\n value = propDef.default({ props, state, close, focus, onError });\n }\n\n if (isDefined(value)) {\n if (propDef.type === 'array' ? !Array.isArray(value) : (typeof value !== propDef.type)) {\n throw new TypeError(`Prop is not of type ${ propDef.type }: ${ key }`);\n }\n }\n \n // $FlowFixMe\n props[key] = value;\n }\n\n for (const alias of aliases) {\n delete props[alias];\n }\n\n // $FlowFixMe\n for (const key of Object.keys(props)) {\n const propDef = component.getPropDefinition(key);\n const value = props[key];\n\n if (!propDef) {\n continue;\n }\n\n if (isDefined(value) && propDef.validate) {\n // $FlowFixMe\n propDef.validate({ value, props });\n }\n\n if (isDefined(value) && propDef.decorate) {\n props[key] = propDef.decorate({ value, props, state, close, focus, onError });\n }\n }\n\n for (const key of component.getPropNames()) {\n const propDef = component.getPropDefinition(key);\n if (propDef.required !== false && !isDefined(props[key])) {\n throw new Error(`Expected prop \"${ key }\" to be defined`);\n }\n }\n}\n\n// $FlowFixMe\nfunction getQueryParam<T, P>(prop : MixedPropDefinitionType<P>, key : string, value : T) : ZalgoPromise<string> {\n return ZalgoPromise.try(() => {\n if (typeof prop.queryParam === 'function') {\n return prop.queryParam({ value });\n } else if (typeof prop.queryParam === 'string') {\n return prop.queryParam;\n } else {\n return key;\n }\n });\n}\n\n// $FlowFixMe\nfunction getQueryValue<T, P>(prop : MixedPropDefinitionType<P>, key : string, value : T) : ZalgoPromise<mixed> {\n return ZalgoPromise.try(() => {\n if (typeof prop.queryValue === 'function' && isDefined(value)) {\n return prop.queryValue({ value });\n } else {\n return value;\n }\n });\n}\n\nexport function propsToQuery<P>(propsDef : BuiltInPropsDefinitionType<P>, props : (PropsType<P>)) : ZalgoPromise<{ [string] : string }> {\n\n const params = {};\n\n // $FlowFixMe\n const keys = Object.keys(props);\n \n return ZalgoPromise.all(keys.map(key => {\n\n const prop = propsDef[key];\n\n if (!prop) {\n return; // eslint-disable-line array-callback-return\n }\n\n return ZalgoPromise.resolve().then(() => {\n\n const value = props[key];\n\n if (!value) {\n return;\n }\n\n if (!prop.queryParam) {\n return;\n }\n\n return value;\n\n }).then(value => {\n\n if (value === null || typeof value === 'undefined') {\n return;\n }\n\n return ZalgoPromise.all([\n getQueryParam(prop, key, value),\n getQueryValue(prop, key, value)\n ]).then(([ queryParam, queryValue ]) => {\n\n let result;\n\n if (typeof queryValue === 'boolean') {\n result = queryValue.toString();\n } else if (typeof queryValue === 'string') {\n result = queryValue.toString();\n } else if (typeof queryValue === 'object' && queryValue !== null) {\n\n if (prop.serialization === PROP_SERIALIZATION.JSON) {\n result = JSON.stringify(queryValue);\n } else if (prop.serialization === PROP_SERIALIZATION.BASE64) {\n result = btoa(JSON.stringify(queryValue));\n } else if (prop.serialization === PROP_SERIALIZATION.DOTIFY || !prop.serialization) {\n result = dotify(queryValue, 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 queryValue === 'number') {\n result = queryValue.toString();\n }\n\n params[queryParam] = result;\n });\n });\n\n })).then(() => {\n return params;\n });\n}\n","/* @flow */\n\nimport { type CrossDomainWindowType } 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 cleaned up before response`)).catch(noop);\n }\n}\n","/* @flow */\n/* eslint max-lines: 0 */\n\nimport { send, bridge, serializeMessage, ProxyWindow, toProxyWindow, type CrossDomainFunctionType } from 'post-robot/src';\nimport { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain,\n getDomain, type CrossDomainWindowType,\n getDistanceFromTop, normalizeMockUrl, assertSameDomain } 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, type CleanupType, base64encode,\n once, stringifyError, destroyElement, getElementSafe } from 'belter/src';\n\nimport { ZOID, POST_MESSAGE, CONTEXT, EVENT,\n INITIAL_PROPS, WINDOW_REFERENCES } from '../constants';\nimport type { Component, onErrorPropType } from '../component';\nimport { getGlobal, getProxyObject, type ProxyObject } from '../lib';\nimport type { PropsInputType, PropsType } from '../component/props';\nimport type { ChildExportsType } from '../child';\nimport type { DimensionsType } from '../types';\n\nimport { RENDER_DRIVERS, type ContextDriverType } from './drivers';\nimport { propsToQuery, extendProps } from './props';\n\nexport type RenderOptionsType<P> = {|\n uid : string,\n props : PropsInputType<P>,\n tag : string,\n context : string,\n close : (?string) => ZalgoPromise<void>,\n focus : () => ZalgoPromise<ProxyWindow>,\n doc : Document,\n container? : HTMLElement,\n dimensions : DimensionsType,\n state : Object,\n event : EventEmitterType,\n frame : ?HTMLIFrameElement,\n prerenderFrame : ?HTMLIFrameElement\n|};\n\nexport type ParentExportsType<P> = {|\n init : (ChildExportsType<P>) => ZalgoPromise<void>,\n close : () => ZalgoPromise<void>,\n checkClose : CrossDomainFunctionType<[], void>,\n resize : CrossDomainFunctionType<[{ width? : ?number, height? : ?number }], void>,\n onError : (mixed) => ZalgoPromise<void>\n|};\n\nexport type PropRef =\n {| type : typeof INITIAL_PROPS.RAW, uid? : string, value? : string |};\n\nexport type WindowRef =\n {| type : typeof WINDOW_REFERENCES.OPENER |} |\n {| type : typeof WINDOW_REFERENCES.PARENT, distance : number |} |\n {| type : typeof WINDOW_REFERENCES.GLOBAL, uid : string |};\n\nexport type ChildPayload = {|\n uid : string,\n tag : string,\n version : string,\n context : $Values<typeof CONTEXT>,\n parentDomain : string,\n childDomain : string,\n parent : WindowRef,\n props : PropRef,\n exports : string\n|};\n\nexport type StateType = Object;\n\nexport type ParentHelpers<P> = {|\n state : StateType,\n close : () => ZalgoPromise<void>,\n focus : () => ZalgoPromise<void>,\n resize : ({ width : ?number, height : ?number }) => ZalgoPromise<void>,\n onError : (mixed) => ZalgoPromise<void>,\n updateProps : PropsInputType<P> => ZalgoPromise<void>,\n event : EventEmitterType\n|};\n\nexport class ParentComponent<P> {\n\n component : Component<P>\n driver : ContextDriverType\n clean : CleanupType\n event : EventEmitterType\n\n initPromise : ZalgoPromise<void>\n handledErrors : Array<mixed> // eslint-disable-line flowtype/no-mutable-array\n \n props : PropsType<P>\n state : StateType\n child : ?ChildExportsType<P>\n\n proxyWin : ?ProxyWindow\n\n constructor(component : Component<P>, props : PropsInputType<P>) {\n this.initPromise = new ZalgoPromise();\n this.handledErrors = [];\n\n // $FlowFixMe\n this.props = {};\n\n this.clean = cleanup(this);\n this.state = {};\n\n this.component = component;\n\n this.setupEvents(props.onError);\n this.setProps(props);\n this.component.registerActiveComponent(this);\n this.clean.register(() => this.component.destroyActiveComponent(this));\n this.watchForUnload();\n }\n\n setupEvents(onError : ?onErrorPropType) {\n this.event = eventEmitter();\n \n this.event.on(EVENT.RENDER, () => this.props.onRender());\n this.event.on(EVENT.DISPLAY, () => this.props.onDisplay());\n this.event.on(EVENT.RENDERED, () => this.props.onRendered());\n this.event.on(EVENT.CLOSE, () => this.props.onClose());\n this.event.on(EVENT.PROPS, (props) => this.props.onProps(props));\n\n this.event.on(EVENT.ERROR, err => {\n if (this.props && this.props.onError) {\n return this.props.onError(err);\n } else if (onError) {\n return onError(err);\n } else {\n return this.initPromise.reject(err).then(() => {\n setTimeout(() => {\n throw err;\n }, 1);\n });\n }\n });\n }\n\n render(target : CrossDomainWindowType, container : string | HTMLElement, context : $Values<typeof CONTEXT>) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n this.component.log(`render`);\n\n this.driver = RENDER_DRIVERS[context];\n const uid = `${ ZOID }-${ this.component.tag }-${ uniqueID() }`;\n const domain = this.getDomain();\n const childDomain = this.getChildDomain();\n \n this.component.checkAllowRender(target, domain, container);\n\n if (target !== window) {\n this.delegate(context, target);\n }\n\n const tasks = {};\n\n tasks.init = this.initPromise;\n tasks.buildUrl = this.buildUrl();\n tasks.onRender = this.event.trigger(EVENT.RENDER);\n\n tasks.getProxyContainer = this.getProxyContainer(container);\n\n tasks.openFrame = this.openFrame();\n tasks.openPrerenderFrame = this.openPrerenderFrame();\n\n tasks.renderContainer = ZalgoPromise.hash({ proxyContainer: tasks.getProxyContainer, proxyFrame: tasks.openFrame, proxyPrerenderFrame: tasks.openPrerenderFrame }).then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => {\n return this.renderContainer(proxyContainer, { context, uid, proxyFrame, proxyPrerenderFrame });\n });\n\n tasks.open = this.driver.openOnClick\n ? this.open()\n : tasks.openFrame.then(proxyFrame => this.open(proxyFrame));\n\n tasks.openPrerender = ZalgoPromise.hash({ proxyWin: tasks.open, proxyPrerenderFrame: tasks.openPrerenderFrame }).then(({ proxyWin, proxyPrerenderFrame }) => {\n return this.openPrerender(proxyWin, proxyPrerenderFrame);\n });\n\n tasks.setState = tasks.open.then(proxyWin => {\n this.proxyWin = proxyWin;\n return this.setProxyWin(proxyWin);\n });\n \n tasks.prerender = ZalgoPromise.hash({ proxyPrerenderWin: tasks.openPrerender, state: tasks.setState }).then(({ proxyPrerenderWin }) => {\n return this.prerender(proxyPrerenderWin, { context, uid });\n });\n\n tasks.loadUrl = ZalgoPromise.hash({ proxyWin: tasks.open, url: tasks.buildUrl, windowName: tasks.setWindowName, prerender: tasks.prerender }).then(({ proxyWin, url }) => {\n return proxyWin.setLocation(url);\n });\n\n tasks.buildWindowName = tasks.open.then(proxyWin => {\n return this.buildWindowName({ proxyWin, childDomain, domain, target, context, uid });\n });\n\n tasks.setWindowName = ZalgoPromise.hash({ proxyWin: tasks.open, windowName: tasks.buildWindowName }).then(({ proxyWin, windowName }) => {\n return proxyWin.setName(windowName);\n });\n\n tasks.watchForClose = tasks.open.then(proxyWin => {\n this.watchForClose(proxyWin);\n });\n\n tasks.onDisplay = ZalgoPromise.hash({ container: tasks.renderContainer, prerender: tasks.prerender }).then(() => {\n return this.event.trigger(EVENT.DISPLAY);\n });\n\n tasks.openBridge = tasks.open.then(proxyWin => {\n return this.openBridge(proxyWin, childDomain, context);\n });\n\n tasks.runTimeout = tasks.loadUrl.then(() => {\n return this.runTimeout();\n });\n\n tasks.onRender = tasks.init.then(() => {\n return this.event.trigger(EVENT.RENDERED);\n });\n\n return ZalgoPromise.hash(tasks).catch(err => {\n for (const taskName of Object.keys(tasks)) {\n tasks[taskName].reject(err);\n }\n\n throw err;\n });\n \n }).catch(err => {\n return ZalgoPromise.all([\n this.onError(err),\n this.destroy(err)\n ]).then(() => {\n throw err;\n });\n }).then(noop);\n }\n\n getProxyContainer(container : string | HTMLElement) : ZalgoPromise<ProxyObject<HTMLElement>> {\n return ZalgoPromise.try(() => {\n return elementReady(container);\n }).then(containerElement => {\n return getProxyObject(containerElement);\n });\n }\n\n buildWindowName({ proxyWin, childDomain, domain, target, uid, context } : { proxyWin : ProxyWindow, childDomain : string, domain : string | RegExp, target : CrossDomainWindowType, context : $Values<typeof CONTEXT>, uid : string }) : string {\n const childPayload = this.buildChildPayload({ proxyWin, childDomain, domain, target, context, uid });\n return `__${ ZOID }__${ this.component.name }__${ base64encode(JSON.stringify(childPayload)) }__`;\n }\n\n getPropsRef(proxyWin : ProxyWindow, childDomain : string, domain : string | RegExp, uid : string) : PropRef {\n const value = serializeMessage(proxyWin, domain, this.getPropsForChild(domain));\n\n const propRef = (childDomain === getDomain())\n ? { type: INITIAL_PROPS.UID, uid }\n : { type: INITIAL_PROPS.RAW, value };\n\n if (propRef.type === INITIAL_PROPS.UID) {\n const global = getGlobal(window);\n global.props = global.props || {};\n global.props[uid] = value;\n\n this.clean.register(() => {\n delete global.props[uid];\n });\n }\n\n return propRef;\n }\n\n buildChildPayload({ proxyWin, childDomain, domain, target = window, context, uid } : { proxyWin : ProxyWindow, childDomain : string, domain : string | RegExp, target : CrossDomainWindowType, context : $Values<typeof CONTEXT>, uid : string } = {}) : ChildPayload {\n return {\n uid,\n context,\n version: __ZOID__.__VERSION__,\n childDomain,\n parentDomain: getDomain(window),\n tag: this.component.tag,\n parent: this.getWindowRef(target, childDomain, uid, context),\n props: this.getPropsRef(proxyWin, childDomain, domain, uid),\n exports: serializeMessage(proxyWin, domain, this.buildParentExports(proxyWin))\n };\n }\n\n setProxyWin(proxyWin : ProxyWindow) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n this.proxyWin = proxyWin;\n });\n }\n\n getHelpers() : ParentHelpers<P> {\n return {\n state: this.state,\n event: this.event,\n close: () => this.close(),\n focus: () => this.focus(),\n resize: ({ width, height }) => this.resize({ width, height }),\n onError: (err) => this.onError(err),\n updateProps: (props) => this.updateProps(props)\n };\n }\n\n setProps(props : PropsInputType<P>, isUpdate : boolean = false) {\n if (this.component.validate) {\n this.component.validate({ props });\n }\n\n const helpers = this.getHelpers();\n extendProps(this.component, this.props, props, helpers, isUpdate);\n }\n\n buildUrl() : ZalgoPromise<string> {\n return propsToQuery({ ...this.component.props, ...this.component.builtinProps }, this.props).then(query => {\n return extendUrl(normalizeMockUrl(this.component.getUrl(this.props)), { query });\n });\n }\n\n getDomain() : string | RegExp {\n return this.component.getDomain(this.props);\n }\n\n getChildDomain() : string {\n return this.component.getChildDomain(this.props);\n }\n\n getPropsForChild(domain : string | RegExp) : (PropsType<P>) {\n const result = {};\n\n for (const key of Object.keys(this.props)) {\n const prop = this.component.getPropDefinition(key);\n\n if (prop && prop.sendToChild === false) {\n continue;\n }\n\n if (prop && prop.sameDomain && !matchDomain(domain, getDomain(window))) {\n continue;\n }\n \n result[key] = this.props[key];\n }\n\n // $FlowFixMe\n return result;\n }\n\n updateProps(props : PropsInputType<P>) : ZalgoPromise<void> {\n this.setProps(props, true);\n\n return this.initPromise.then(() => {\n if (this.child) {\n return this.child.updateProps(this.getPropsForChild(this.getDomain())).catch(err => {\n if (!this.child || !this.proxyWin) {\n return;\n }\n\n return this.checkClose(this.proxyWin).then(() => {\n if (this.child) {\n throw err;\n }\n });\n });\n }\n });\n }\n\n openFrame() : ZalgoPromise<?ProxyObject<HTMLIFrameElement>> {\n return ZalgoPromise.try(() => {\n if (this.driver.openFrame) {\n return this.driver.openFrame.call(this);\n }\n });\n }\n\n openPrerenderFrame() : ZalgoPromise<?ProxyObject<HTMLIFrameElement>> {\n return ZalgoPromise.try(() => {\n if (this.driver.openPrerenderFrame) {\n return this.driver.openPrerenderFrame.call(this);\n }\n });\n }\n \n open(proxyFrame : ?ProxyObject<HTMLIFrameElement>) : ZalgoPromise<ProxyWindow> {\n return ZalgoPromise.try(() => {\n this.component.log(`open`);\n\n const windowProp = this.props.window;\n\n if (windowProp) {\n this.clean.register(() => windowProp.close());\n return toProxyWindow(windowProp);\n }\n\n return this.driver.open.call(this, proxyFrame);\n\n }).then(proxyWin => {\n this.proxyWin = proxyWin;\n return proxyWin;\n });\n }\n\n openPrerender(proxyWin : ProxyWindow, proxyPrerenderFrame : ?ProxyObject<HTMLIFrameElement>) : ZalgoPromise<ProxyWindow> {\n return ZalgoPromise.try(() => {\n return this.driver.openPrerender.call(this, proxyWin, proxyPrerenderFrame);\n });\n }\n\n focus() : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n if (this.proxyWin) {\n return this.proxyWin.focus().then(noop);\n }\n });\n }\n\n delegate(context : $Values<typeof CONTEXT>, target : CrossDomainWindowType) {\n this.component.log(`delegate`);\n\n const props = {};\n for (const propName of this.component.getPropNames()) {\n if (this.component.getPropDefinition(propName).allowDelegate) {\n props[propName] = this.props[propName];\n }\n }\n\n const overridesPromise = send(target, `${ POST_MESSAGE.DELEGATE }_${ this.component.name }`, {\n context,\n props,\n overrides: {\n event: this.event,\n close: () => this.close(),\n onError: (err) => this.onError(err)\n }\n\n }).then(({ data }) => {\n this.clean.register(data.destroy);\n return data.overrides;\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 for (const key of this.driver.delegate) {\n // $FlowFixMe\n this[key] = function overriddenFunction() : ZalgoPromise<mixed> {\n return overridesPromise.then(overrides => {\n return overrides[key].apply(this, arguments);\n });\n };\n }\n }\n\n getWindowRef(target : CrossDomainWindowType, domain : string, uid : string, context : $Values<typeof CONTEXT>) : WindowRef {\n \n if (domain === getDomain(window)) {\n const global = getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n this.clean.register(() => {\n delete global.windows[uid];\n });\n \n return { type: WINDOW_REFERENCES.GLOBAL, uid };\n }\n\n if (context === CONTEXT.POPUP) {\n return { type: WINDOW_REFERENCES.OPENER };\n }\n\n return { type: WINDOW_REFERENCES.PARENT, distance: getDistanceFromTop(window) };\n }\n\n watchForClose(proxyWin : ProxyWindow) : ZalgoPromise<void> {\n let cancelled = false;\n\n this.clean.register(() => {\n cancelled = true;\n });\n\n return ZalgoPromise.delay(2000).then(() => {\n return proxyWin.isClosed();\n }).then(isClosed => {\n if (isClosed) {\n this.component.log(`detect_close_child`);\n return this.close();\n } else if (!cancelled) {\n return this.watchForClose(proxyWin);\n }\n });\n }\n\n watchForUnload() {\n const unloadWindowListener = addEventListener(window, 'unload', once(() => {\n this.component.log(`navigate_away`);\n this.destroy(new Error(`Window navigated away`));\n }));\n\n this.clean.register(unloadWindowListener.cancel);\n }\n\n runTimeout() : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n const timeout = this.props.timeout;\n\n if (timeout) {\n return this.initPromise.timeout(timeout, new Error(`Loading component timed out after ${ timeout } milliseconds`));\n }\n });\n }\n\n initChild(child : ChildExportsType<P>) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n this.clean.set('child', child);\n this.initPromise.resolve();\n });\n }\n\n buildParentExports(win : ProxyWindow) : ParentExportsType<P> {\n const onError = (err) => this.onError(err);\n const init = (child) => this.initChild(child);\n const close = () => this.close();\n const checkClose = () => this.checkClose(win);\n const resize = ({ width, height }) => this.resize({ width, height });\n\n init.onError = onError;\n\n return { init, close, checkClose, resize, onError };\n }\n\n resize({ width, height } : { width? : ?number, height? : ?number }) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n this.event.trigger(EVENT.RESIZE, { width, height });\n });\n }\n\n checkClose(win : ProxyWindow) : ZalgoPromise<void> {\n return win.isClosed().then(closed => {\n if (closed) {\n return this.close();\n }\n\n return ZalgoPromise.delay(200)\n .then(() => win.isClosed())\n .then(secondClosed => {\n if (secondClosed) {\n return this.close();\n }\n });\n });\n }\n\n close() : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n this.component.log(`close`);\n return this.event.trigger(EVENT.CLOSE);\n\n }).then(() => {\n if (this.child) {\n this.child.close.fireAndForget().catch(noop);\n }\n\n return this.destroy(new Error(`Window closed`), false);\n });\n }\n\n prerender(proxyPrerenderWin : ProxyWindow, { context, uid } : { context : $Values<typeof CONTEXT>, uid : string }) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n const prerenderTemplate = this.component.prerenderTemplate;\n\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 = this.renderTemplate(prerenderTemplate, { context, uid, 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' } = this.component.autoResize || {};\n element = getElementSafe(element, doc);\n \n if (element && (width || height)) {\n onResize(element, ({ width: newWidth, height: newHeight }) => {\n this.resize({\n width: width ? newWidth : undefined,\n height: height ? newHeight : undefined\n });\n }, { width, height, win: prerenderWindow });\n }\n });\n }\n\n renderTemplate(renderer : (RenderOptionsType<P>) => ?HTMLElement, { context, uid, container, doc, frame, prerenderFrame } : { context : $Values<typeof CONTEXT>, uid : string, container? : HTMLElement, doc : Document, frame? : ?HTMLIFrameElement, prerenderFrame? : ?HTMLIFrameElement }) : ?HTMLElement {\n // $FlowFixMe\n return renderer.call(this, {\n container,\n context,\n uid,\n doc,\n frame,\n prerenderFrame,\n focus: () => this.focus(),\n close: () => this.close(),\n state: this.state,\n props: this.props,\n tag: this.component.tag,\n dimensions: this.component.dimensions,\n event: this.event\n });\n }\n\n renderContainer(proxyContainer : ProxyObject<HTMLElement>, { proxyFrame, proxyPrerenderFrame, context, uid } :\n { context : $Values<typeof CONTEXT>, uid : string, proxyFrame : ?ProxyObject<HTMLIFrameElement>, proxyPrerenderFrame : ?ProxyObject<HTMLIFrameElement> }) : ZalgoPromise<?ProxyObject<HTMLElement>> {\n \n\n return ZalgoPromise.hash({\n container: proxyContainer.get().then(elementReady),\n // $FlowFixMe\n frame: proxyFrame ? proxyFrame.get() : null,\n // $FlowFixMe\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null\n }).then(({ container, frame, prerenderFrame }) => {\n const innerContainer = this.renderTemplate(this.component.containerTemplate, { context, uid, container, frame, prerenderFrame, doc: document });\n if (innerContainer) {\n appendChild(container, innerContainer);\n this.clean.register(() => destroyElement(innerContainer));\n return getProxyObject(innerContainer);\n }\n });\n }\n\n destroy(err? : mixed, trigger? : boolean = true) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n if (!err) {\n trigger = false;\n err = new Error('Component destroyed');\n }\n this.component.log(`destroy`);\n return this.onError(err, trigger);\n }).then(() => {\n return this.clean.all();\n });\n }\n\n onError(err : mixed, trigger? : boolean = true) : ZalgoPromise<void> {\n return ZalgoPromise.try(() => {\n if (this.handledErrors.indexOf(err) !== -1) {\n return;\n }\n\n this.handledErrors.push(err);\n this.initPromise.asyncReject(err);\n\n if (trigger) {\n return this.event.trigger(EVENT.ERROR, err);\n }\n });\n }\n\n openBridge(proxyWin : ProxyWindow, domain : string, context : $Values<typeof CONTEXT>) : ?ZalgoPromise<?CrossDomainWindowType> {\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 }) || bridge.hasBridge(domain, domain)) {\n return;\n }\n\n const bridgeUrl = this.component.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, domain);\n return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);\n });\n }\n }\n}\n","/* @flow */\n\nimport { onCloseWindow, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { ProxyWindow } from 'post-robot/src';\nimport { cleanup, type CleanupType, type EventEmitterType } from 'belter/src';\n\nimport { ParentComponent } from '../parent';\nimport { RENDER_DRIVERS, type ContextDriverType } from '../parent/drivers';\nimport type { Component } from '../component';\n\nexport type DelegatePropsType = {|\n onClose : () => ?ZalgoPromise<void>,\n onDisplay : () => ?ZalgoPromise<void>,\n window : ?ProxyWindow\n|};\n\nexport type DelegateOptionsType = {|\n context : string,\n props : DelegatePropsType,\n overrides : {\n close : () => ZalgoPromise<void>,\n onError : (mixed) => ZalgoPromise<void>,\n event : EventEmitterType\n }\n|};\n\nexport type DelegateReturnType = {|\n overrides : Object,\n destroy : () => ZalgoPromise<void>\n|};\n\nexport class DelegateComponent<P> {\n\n component : Component<P>\n source : CrossDomainWindowType\n context : string\n driver : ContextDriverType\n props : DelegatePropsType\n clean : CleanupType\n\n focus : () => ZalgoPromise<void>\n resize : ({ width? : ?number, height? : ?number }) => ZalgoPromise<void>\n renderTemplate : Function\n\n close : () => ZalgoPromise<void>\n onError : (mixed) => ZalgoPromise<void>\n event : EventEmitterType\n\n constructor(component : Component<P>, source : CrossDomainWindowType, options : DelegateOptionsType) {\n this.component = component;\n this.context = options.context;\n this.driver = RENDER_DRIVERS[options.context];\n this.clean = cleanup(this);\n \n this.focus = ParentComponent.prototype.focus;\n this.resize = ParentComponent.prototype.resize;\n this.renderTemplate = ParentComponent.prototype.renderTemplate;\n\n // $FlowFixMe\n this.props = {};\n \n for (const propName of Object.keys(options.props)) {\n const propDef = this.component.getPropDefinition(propName);\n if (propDef && propDef.allowDelegate && options.props[propName]) {\n // $FlowFixMe\n this.props[propName] = options.props[propName];\n }\n }\n\n this.close = options.overrides.close;\n this.onError = options.overrides.onError;\n this.event = options.overrides.event;\n\n this.component.registerActiveComponent(this);\n this.clean.register(() => this.component.destroyActiveComponent(this));\n\n this.watchForSourceClose(source);\n }\n\n getDelegate() : DelegateReturnType {\n return {\n overrides: this.getOverrides(),\n destroy: () => this.destroy()\n };\n }\n\n watchForSourceClose(source : CrossDomainWindowType) {\n const closeSourceWindowListener = onCloseWindow(source, () => this.destroy(), 3000);\n this.clean.register(closeSourceWindowListener.cancel);\n }\n\n getOverrides() : { [string] : mixed } {\n const overrides = {};\n const self = this;\n\n for (const key of this.driver.delegate) {\n overrides[key] = function delegateOverride() : mixed {\n // $FlowFixMe\n return ParentComponent.prototype[key].apply(self, arguments);\n };\n overrides[key].__name__ = key;\n }\n\n return overrides;\n }\n\n destroy() : ZalgoPromise<void> {\n return this.clean.all();\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';\nimport { EVENT } from '../../constants';\n\nconst CLASS = {\n VISIBLE: 'visible',\n INVISIBLE: 'invisible'\n};\n\nexport function defaultContainerTemplate<P>({ uid, frame, prerenderFrame, doc, props, event, dimensions : { width, height } } : RenderOptionsType<P>) : ?HTMLElement {\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';\n\nexport function defaultPrerenderTemplate<P>({ doc, props } : RenderOptionsType<P>) : ?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\nimport { ZalgoPromise } from 'zalgo-promise/src';\nimport { once, noop } from 'belter/src';\nimport { isWindow, type CrossDomainWindowType } from 'cross-domain-utils/src';\nimport { ProxyWindow, toProxyWindow } from 'post-robot/src';\n\nimport { PROP_SERIALIZATION } from '../constants';\n\nexport type EventHandlerType<T> = (T) => void | ZalgoPromise<void>;\n\nexport type timeoutPropType = number;\nexport type windowPropType = CrossDomainWindowType | ProxyWindow;\nexport type cspNoncePropType = string;\nexport type closePropType = () => ZalgoPromise<void>;\nexport type focusPropType = () => ZalgoPromise<void>;\nexport type resizePropType = ({ width : ?number, height : ?number }) => ZalgoPromise<void>;\n\nexport type onDisplayPropType = EventHandlerType<void>;\nexport type onRenderedPropType = EventHandlerType<void>;\nexport type onRenderPropType = EventHandlerType<void>;\nexport type onClosePropType = EventHandlerType<void>;\nexport type onErrorPropType = EventHandlerType<mixed>;\nexport type onPropsPropType<P> = ((PropsType<P>) => void) => void; // eslint-disable-line no-use-before-define\n\nexport type PropsInputType<P> = {\n timeout? : timeoutPropType,\n window? : windowPropType,\n cspNonce? : cspNoncePropType,\n\n onDisplay? : onDisplayPropType,\n onRendered? : onRenderedPropType,\n onRender? : onRenderPropType,\n onClose? : onClosePropType,\n onError? : onErrorPropType,\n onProps? : onPropsPropType<P>\n} & P;\n\nexport type PropsType<P> = {|\n timeout? : timeoutPropType,\n window? : ?windowPropType,\n close? : ?closePropType,\n focus? : ?focusPropType,\n resize? : ?resizePropType,\n cspNonce? : ?cspNoncePropType,\n\n onDisplay : onDisplayPropType,\n onRendered : onRenderedPropType,\n onRender : onRenderPropType,\n onClose : onClosePropType,\n onError : onErrorPropType,\n onProps : onPropsPropType<P>\n|} & P;\n\ntype PropDefinitionType<T, P, S : string> = {|\n type : S,\n alias? : string,\n value? : ({ props : P, state : Object, close : () => ZalgoPromise<void>, focus : () => ZalgoPromise<void>, onError : (mixed) => ZalgoPromise<void> }) => ?T,\n required? : boolean,\n queryParam? : boolean | string | ({ value : T }) => (string | ZalgoPromise<string>),\n queryValue? : ({ value : T }) => (ZalgoPromise<mixed> | mixed),\n sendToChild? : boolean,\n allowDelegate? : boolean,\n validate? : ({ value : T, props : PropsInputType<P> }) => void,\n decorate? : ({ value : T, props : PropsType<P>, state : Object, close : () => ZalgoPromise<void>, focus : () => ZalgoPromise<void>, onError : (mixed) => ZalgoPromise<void> }) => T,\n default? : ({ props : P, state : Object }) => ?T,\n sameDomain? : boolean,\n serialization? : $Values<typeof PROP_SERIALIZATION>,\n childDecorate? : ({ value : T, close : () => ZalgoPromise<void>, focus : () => ZalgoPromise<void>, onError : (mixed) => ZalgoPromise<void>, onProps : ((PropsType<P>) => void) => void, resize : ({ width : ?number, height : ?number }) => ZalgoPromise<void> }) => ?T\n|};\n\nexport type BooleanPropDefinitionType<T : boolean, P> = PropDefinitionType<T, P, 'boolean'>;\nexport type StringPropDefinitionType<T : string, P> = PropDefinitionType<T, P, 'string'>;\nexport type NumberPropDefinitionType<T : number, P> = PropDefinitionType<T, P, 'number'>;\nexport type FunctionPropDefinitionType<T : Function, P> = PropDefinitionType<T, P, 'function'>;\nexport type ArrayPropDefinitionType<T : Array<*> | $ReadOnlyArray<*>, P> = PropDefinitionType<T, P, 'array'>; // eslint-disable-line flowtype/no-mutable-array\nexport type ObjectPropDefinitionType<T : Object, P> = PropDefinitionType<T, P, 'object'>;\n\nexport type MixedPropDefinitionType<P> = BooleanPropDefinitionType<*, P> | StringPropDefinitionType<*, P> | NumberPropDefinitionType<*, P> | FunctionPropDefinitionType<*, P> | ObjectPropDefinitionType<*, P> | ArrayPropDefinitionType<*, P>;\n\nexport type UserPropsDefinitionType<P> = {\n [string] : MixedPropDefinitionType<P>\n};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type BuiltInPropsDefinitionType<P> = {\n timeout : NumberPropDefinitionType<timeoutPropType, P>,\n window : ObjectPropDefinitionType<windowPropType, P>,\n close : FunctionPropDefinitionType<closePropType, P>,\n focus : FunctionPropDefinitionType<focusPropType, P>,\n resize : FunctionPropDefinitionType<resizePropType, P>,\n\n onDisplay : FunctionPropDefinitionType<onDisplayPropType, P>,\n onRendered : FunctionPropDefinitionType<onRenderedPropType, P>,\n onRender : FunctionPropDefinitionType<onRenderPropType, P>,\n onClose : FunctionPropDefinitionType<onClosePropType, P>,\n onError : FunctionPropDefinitionType<onErrorPropType, P>,\n onProps : FunctionPropDefinitionType<onPropsPropType<P>, P>\n};\n\nconst defaultNoop = () => noop;\nconst decorateOnce = ({ value }) => once(value);\n\nexport function getBuiltInProps<P>() : BuiltInPropsDefinitionType<P> {\n return {\n window: {\n type: 'object',\n sendToChild: false,\n required: false,\n allowDelegate: true,\n validate({ value } : { value : CrossDomainWindowType | ProxyWindow }) {\n if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) {\n throw new Error(`Expected Window or ProxyWindow`);\n }\n },\n decorate({ value } : { value : CrossDomainWindowType | ProxyWindow }) : ProxyWindow {\n return toProxyWindow(value);\n }\n },\n\n timeout: {\n type: 'number',\n required: false,\n sendToChild: false\n },\n\n close: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ close }) => close\n },\n\n focus: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ focus }) => focus\n },\n\n resize: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ resize }) => resize\n },\n\n cspNonce: {\n type: 'string',\n required: false\n },\n\n getParent: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ getParent }) => getParent\n },\n\n getParentDomain: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ getParentDomain }) => getParentDomain\n },\n\n onDisplay: {\n type: 'function',\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRendered: {\n type: 'function',\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onRender: {\n type: 'function',\n required: false,\n sendToChild: false,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onClose: {\n type: 'function',\n required: false,\n sendToChild: false,\n allowDelegate: true,\n default: defaultNoop,\n decorate: decorateOnce\n },\n\n onError: {\n type: 'function',\n required: false,\n sendToChild: false,\n childDecorate: ({ onError }) => onError\n },\n\n onProps: {\n type: 'function',\n required: false,\n sendToChild: false,\n default: defaultNoop,\n childDecorate: ({ onProps }) => onProps\n }\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, getDomainFromUrl, type CrossDomainWindowType, isSameTopWindow, getDomain, matchDomain, isSameDomain } from 'cross-domain-utils/src';\nimport { isRegex, noop, isElement } from 'belter/src';\n\nimport { ChildComponent, getChildPayload } from '../child';\nimport { ParentComponent, type RenderOptionsType, type ParentHelpers } from '../parent';\nimport { DelegateComponent } from '../delegate';\nimport { CONTEXT, POST_MESSAGE, WILDCARD, DEFAULT_DIMENSIONS } from '../constants';\nimport { react, angular, vue, angular2 } from '../drivers';\nimport { getGlobal, destroyGlobal } from '../lib';\nimport type { CssDimensionsType, StringMatcherType } from '../types';\n\nimport { validate } from './validate';\nimport { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';\nimport { getBuiltInProps, type UserPropsDefinitionType, type BuiltInPropsDefinitionType, type PropsInputType, type PropsType, type MixedPropDefinitionType } from './props';\n\ntype LoggerPayload = { [string] : ?string };\n\n// eslint-disable-next-line flowtype/require-exact-type\ntype Logger = {\n debug : (event : string, payload? : LoggerPayload) => any, // eslint-disable-line flowtype/no-weak-types\n info : (event : string, payload? : LoggerPayload) => any, // eslint-disable-line flowtype/no-weak-types\n warn : (event : string, payload? : LoggerPayload) => any, // eslint-disable-line flowtype/no-weak-types\n error : (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\nexport type ComponentOptionsType<P> = {|\n\n tag : string,\n\n url : string | ({ props : PropsType<P> }) => string,\n domain? : string | RegExp,\n bridgeUrl? : string,\n\n props? : UserPropsDefinitionType<P>,\n\n dimensions? : CssDimensionsType,\n autoResize? : { width? : boolean, height? : boolean, element? : string },\n\n allowedParentDomains? : StringMatcherType,\n\n attributes? : {\n iframe? : { [string] : string },\n popup? : { [string] : string }\n },\n\n defaultContext? : $Values<typeof CONTEXT>,\n\n containerTemplate? : (RenderOptionsType<P>) => ?HTMLElement,\n prerenderTemplate? : (RenderOptionsType<P>) => ?HTMLElement,\n\n validate? : ({ props : PropsInputType<P> }) => void,\n\n logger? : Logger\n|};\n\ntype ZoidRenderer = {|\n render : (container? : string | HTMLElement, context? : $Values<typeof CONTEXT>) => ZalgoPromise<void>,\n renderTo : (target : CrossDomainWindowType, container? : string, context? : $Values<typeof CONTEXT>) => ZalgoPromise<void>\n|};\n\nexport type ZoidComponentInstance<P> = {| ...ParentHelpers<P>, ...ZoidRenderer |};\n\n// eslint-disable-next-line flowtype/require-exact-type\nexport type ZoidComponent<P> = {\n (PropsInputType<P>) : ZoidComponentInstance<P>,\n driver : (string, mixed) => mixed,\n isChild : () => boolean,\n xprops? : PropsType<P>,\n canRenderTo : (CrossDomainWindowType) => ZalgoPromise<boolean>\n};\n\nexport class Component<P> {\n\n tag : string\n name : string\n \n url : string | ({ props : PropsType<P> }) => string\n domain : void | string | RegExp\n bridgeUrl : void | string\n\n props : UserPropsDefinitionType<P>\n builtinProps : BuiltInPropsDefinitionType<P>\n\n dimensions : CssDimensionsType\n autoResize : void | { width? : boolean, height? : boolean, element? : string }\n\n allowedParentDomains : StringMatcherType\n\n defaultContext : $Values<typeof CONTEXT>\n \n attributes : {\n iframe? : { [string] : string },\n popup? : { [string] : string }\n }\n\n containerTemplate : (RenderOptionsType<P>) => ?HTMLElement\n prerenderTemplate : ?(RenderOptionsType<P>) => ?HTMLElement\n\n validate : void | ({ props : PropsInputType<P> }) => void\n\n driverCache : { [string] : mixed }\n\n xprops : ?PropsType<P>\n\n logger : Logger\n\n propNames : $ReadOnlyArray<string>\n\n constructor(options : ComponentOptionsType<P>) {\n validate(options);\n\n // The tag name of the component. Used by some drivers (e.g. angular) to turn the component into an html element,\n // e.g. <my-component>\n\n this.tag = options.tag;\n this.name = this.tag.replace(/-/g, '_');\n\n this.allowedParentDomains = options.allowedParentDomains || WILDCARD;\n\n const global = getGlobal();\n global.components = global.components || {};\n\n if (global.components[this.tag]) {\n throw new Error(`Can not register multiple components with the same tag: ${ this.tag }`);\n }\n\n // A json based spec describing what kind of props the component accepts. This is used to validate any props before\n // they are passed down to the child.\n\n this.builtinProps = getBuiltInProps();\n this.props = options.props || {};\n\n // The dimensions of the component, e.g. { width: '300px', height: '150px' }\n\n const { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT } = options.dimensions || {};\n this.dimensions = { width, height };\n\n this.url = options.url;\n this.domain = options.domain;\n this.bridgeUrl = options.bridgeUrl;\n\n this.attributes = options.attributes || {};\n this.attributes.iframe = this.attributes.iframe || {};\n this.attributes.popup = this.attributes.popup || {};\n\n this.defaultContext = options.defaultContext || CONTEXT.IFRAME;\n\n this.autoResize = options.autoResize;\n\n if (options.containerTemplate) {\n this.containerTemplate = options.containerTemplate;\n } else if (__ZOID__.__DEFAULT_CONTAINER__) {\n this.containerTemplate = defaultContainerTemplate;\n }\n\n if (options.prerenderTemplate) {\n this.prerenderTemplate = options.prerenderTemplate;\n } else if (__ZOID__.__DEFAULT_PRERENDER__) {\n this.prerenderTemplate = defaultPrerenderTemplate;\n }\n\n this.validate = options.validate;\n\n this.logger = options.logger || {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop\n };\n\n this.registerChild();\n this.listenDelegate();\n\n global.components[this.tag] = this;\n }\n\n getPropNames() : $ReadOnlyArray<string> {\n if (this.propNames) {\n return this.propNames;\n }\n\n const propNames = Object.keys(this.props);\n for (const key of Object.keys(this.builtinProps)) {\n if (propNames.indexOf(key) === -1) {\n propNames.push(key);\n }\n }\n\n this.propNames = propNames;\n return propNames;\n }\n\n getPropDefinition(name : string) : MixedPropDefinitionType<P> {\n return this.props[name] || this.builtinProps[name];\n }\n\n driver(name : string, dep : mixed) : mixed {\n if (__ZOID__.__FRAMEWORK_SUPPORT__) {\n const drivers = { react, angular, vue, angular2 };\n\n if (!drivers[name]) {\n throw new Error(`Could not find driver for framework: ${ name }`);\n }\n \n this.driverCache = this.driverCache || {};\n \n if (!this.driverCache[name]) {\n this.driverCache[name] = drivers[name].register(this, dep);\n }\n \n return this.driverCache[name];\n } else {\n throw new Error(`Driver support not enabled`);\n }\n }\n\n registerChild() {\n if (this.isChild()) {\n if (window.xprops) {\n throw new Error(`Can not register ${ this.name } as child - can not attach multiple components to the same window`);\n }\n\n const child = new ChildComponent(this);\n window.xprops = this.xprops = child.getProps();\n }\n }\n\n listenDelegate() {\n on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ this.name }`, () => {\n return true;\n });\n\n on(`${ POST_MESSAGE.DELEGATE }_${ this.name }`, ({ source, data: { context, props, overrides } }) => {\n const delegate = new DelegateComponent(this, source, { context, props, overrides });\n return delegate.getDelegate();\n });\n }\n\n canRenderTo(win : CrossDomainWindowType) : ZalgoPromise<boolean> {\n return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ this.name }`).then(({ data }) => {\n return data;\n }).catch(() => {\n return false;\n });\n }\n\n getUrl(props : PropsType<P>) : string {\n if (typeof this.url === 'function') {\n return this.url({ props });\n }\n\n return this.url;\n }\n\n getChildDomain(props : PropsType<P>) : string {\n if (this.domain && typeof this.domain === 'string') {\n return this.domain;\n }\n\n return getDomainFromUrl(this.getUrl(props));\n }\n\n getDomain(props : PropsType<P>) : string | RegExp {\n if (this.domain && isRegex(this.domain)) {\n return this.domain;\n }\n\n return this.getChildDomain(props);\n }\n\n getBridgeUrl() : ?string {\n if (this.bridgeUrl) {\n return this.bridgeUrl;\n }\n }\n\n isChild() : boolean {\n const payload = getChildPayload();\n return Boolean(payload && payload.tag === this.tag && payload.childDomain === getDomain());\n }\n\n getDefaultContainer(context : $Values<typeof CONTEXT>, container? : string | HTMLElement) : string | HTMLElement {\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 getDefaultContext(context : ?$Values<typeof CONTEXT>, props : PropsInputType<P>) : $Values<typeof CONTEXT> {\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 this.defaultContext;\n }\n\n init(props : PropsInputType<P>) : ZoidComponentInstance<P> {\n\n // $FlowFixMe\n props = props || {};\n \n const parent = new ParentComponent(this, props);\n\n const render = (target, container, context) => ZalgoPromise.try(() => {\n if (!isWindow(target)) {\n throw new Error(`Must pass window to renderTo`);\n }\n\n context = this.getDefaultContext(context, props);\n container = this.getDefaultContainer(context, container);\n return parent.render(target, container, context);\n });\n\n return {\n ...parent.getHelpers(),\n render: (container, context) => render(window, container, context),\n renderTo: (target, container, context) => render(target, container, context)\n };\n }\n\n checkAllowRender(target : CrossDomainWindowType, domain : string | RegExp, container : string | HTMLElement) {\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(domain, origin) && !isSameDomain(target)) {\n throw new Error(`Can not render remotely to ${ domain.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 log(event : string, payload? : LoggerPayload) {\n this.logger.info(`${ this.name }_${ event }`, payload);\n }\n\n registerActiveComponent<Q>(instance : ParentComponent<Q> | DelegateComponent<Q>) {\n const global = getGlobal();\n global.activeComponents = global.activeComponents || [];\n global.activeComponents.push(instance);\n }\n\n destroyActiveComponent<Q>(instance : ParentComponent<Q> | DelegateComponent<Q>) {\n const global = getGlobal();\n global.activeComponents = global.activeComponents || [];\n global.activeComponents.splice(global.activeComponents.indexOf(instance), 1);\n }\n}\n\nexport type ComponentDriverType<P, T : mixed> = {|\n register : (Component<P>, T) => mixed\n|};\n\nexport function create<P>(options : ComponentOptionsType<P>) : ZoidComponent<P> {\n setupPostRobot();\n\n const component : Component<P> = new Component(options);\n\n const init = (props) => component.init(props);\n init.driver = (name, dep) => component.driver(name, dep);\n init.isChild = () => component.isChild();\n init.canRenderTo = (win) => component.canRenderTo(win);\n init.xprops = component.xprops;\n \n return init;\n}\n\nexport function destroyAll() : ZalgoPromise<void> {\n if (bridge) {\n bridge.destroyBridges();\n }\n\n const results = [];\n\n const global = getGlobal();\n global.activeComponents = global.activeComponents || [];\n while (global.activeComponents.length) {\n results.push(global.activeComponents[0].destroy(new Error(`zoid desroyed all`), false));\n }\n\n return ZalgoPromise.all(results).then(noop);\n}\n\nexport const destroyComponents = destroyAll;\n\nexport function destroy() {\n destroyAll();\n destroyGlobal();\n destroyPostRobot();\n}\n","/* @flow */\n\nimport { isPerc, isPx, values } from 'belter/src';\n\nimport { CONTEXT, PROP_TYPE } from '../constants';\n\nimport type { ComponentOptionsType } from './index';\n\nfunction validatePropDefinitions<P>(options : ComponentOptionsType<P>) {\n\n if (options.props && !(typeof options.props === 'object')) {\n throw new Error(`Expected options.props to be an object`);\n }\n\n const PROP_TYPE_LIST = values(PROP_TYPE);\n\n if (options.props) {\n for (const key of Object.keys(options.props)) {\n const prop = options.props[key];\n\n if (!prop || !(typeof prop === 'object')) {\n throw new Error(`Expected options.props.${ key } to be an object`);\n }\n\n if (!prop.type) {\n throw new Error(`Expected prop.type`);\n }\n\n if (PROP_TYPE_LIST.indexOf(prop.type) === -1) {\n throw new Error(`Expected prop.type to be one of ${ PROP_TYPE_LIST.join(', ') }`);\n }\n\n if (prop.required && prop.default) {\n throw new Error(`Required prop can not have a default value`);\n }\n\n if (prop.type === PROP_TYPE.FUNCTION && prop.queryParam && !prop.queryValue) {\n throw new Error(`Do not pass queryParam for function prop`);\n }\n }\n }\n}\n\n// eslint-disable-next-line complexity\nexport function validate<P>(options : ?ComponentOptionsType<P>) { // eslint-ignore-line\n\n if (!options) {\n throw new Error(`Expected options to be passed`);\n }\n\n // eslint-disable-next-line security/detect-unsafe-regex, unicorn/no-unsafe-regex\n if (!options.tag || !options.tag.match(/^([a-z0-9]+-)+[a-z0-9]+$/)) {\n throw new Error(`Invalid options.tag: ${ options.tag }`);\n }\n\n validatePropDefinitions(options);\n\n if (options.dimensions) {\n if (options.dimensions && !isPx(options.dimensions.width) && !isPerc(options.dimensions.width)) {\n throw new Error(`Expected options.dimensions.width to be a px or % string value`);\n }\n\n if (options.dimensions && !isPx(options.dimensions.height) && !isPerc(options.dimensions.height)) {\n throw new Error(`Expected options.dimensions.height to be a px or % string value`);\n }\n }\n\n if (options.defaultContext) {\n if (options.defaultContext !== CONTEXT.IFRAME && options.defaultContext !== CONTEXT.POPUP) {\n throw new Error(`Unsupported context type: ${ options.defaultContext || 'unknown' }`);\n }\n }\n\n if (!options.url) {\n throw new Error(`Must pass url`);\n }\n\n if (typeof options.url !== 'string' && typeof options.url !== 'function') {\n throw new TypeError(`Expected url to be string or function`);\n }\n\n if (options.prerenderTemplate && typeof options.prerenderTemplate !== 'function') {\n throw new Error(`Expected options.prerenderTemplate to be a function`);\n }\n\n if ((options.containerTemplate || !__ZOID__.__DEFAULT_CONTAINER__) && typeof options.containerTemplate !== 'function') {\n throw new Error(`Expected options.containerTemplate to be a function`);\n }\n}\n","/* @flow */\n\nexport { PopupOpenError } from 'belter/src';\nexport { create, destroy, destroyComponents, destroyAll, Component } from './component';\nexport type { ZoidComponent, ZoidComponentInstance } from './component';\nexport type { RenderOptionsType } from './parent';\nexport { PROP_TYPE, PROP_SERIALIZATION, CONTEXT, EVENT } from './constants';\n"],"sourceRoot":""}
\No newline at end of file