ok
Direktori : /home2/selectio/public_html/fms-worksuite/public/vendor/onesignal/ |
Current File : /home2/selectio/public_html/fms-worksuite/public/vendor/onesignal/OneSignalSDKWorker.js.map |
{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./node_modules/tslib/tslib.es6.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/libraries/Log.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/libraries/Emitter.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/services/IndexedDb.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/AppState.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/ServiceWorkerState.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/Subscription.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/services/Database.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/TimeoutError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/context/shared/utils/Utils.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/libraries/sw/Log.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/WindowEnvironmentKind.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/EnvironmentKind.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/SdkEnvironment.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/libraries/WorkerMessenger.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/utils/OneSignalUtils.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/Environment.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/utils.js","webpack:///./node_modules/bowser/src/bowser.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/SubscriptionStateKind.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/OneSignalApiShared.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/OneSignalError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/InvalidArgumentError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/IntegrationKind.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/Session.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/OneSignalApiBase.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/shared/OutcomesHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/ServiceWorkerHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/Event.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/Prompts.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/RawPushSubscription.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/NotImplementedError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/SdkInitError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/Outcomes.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/NotSubscribedError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/OneSignalApiError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/OneSignalApiSW.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/utils/PermissionUtils.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/DeliveryPlatformKind.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/PushDeviceRecord.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/PromptsHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/DeviceRecord.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/SMSProfile.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/EmailProfile.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/sw/CancelableTimeout.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/page/ServiceWorkerUtilHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/TestEnvironmentKind.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/NotificationPermission.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/PermissionManager.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/utils/LocalStorage.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/PageViewManager.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/Path.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/ServiceWorkerRegistrationError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/ServiceWorkerManager.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/PermissionPromptType.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/InvalidStateError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/PushPermissionNotGrantedError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/errors/SubscriptionError.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/SubscriptionManager.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/utils/Encoding.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/ContextHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/LimitStore.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/slidedown/constants.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/CustomLinkManager.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/EventHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/context/browser/models/Browser.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/SubscriptionHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/MainHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/UpdateManager.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/sessionManager/sw/SessionManager.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/ContextSW.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/SecondaryChannelSynchronizer.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/OneSignalApi.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/SecondaryChannelEmail.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/SecondaryChannelDeviceRecord.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/updaters/SecondaryChannelIdentifierUpdater.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/updaters/SecondaryChannelTagsUpdater.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/updaters/SecondaryChannelExternalUserIdUpdater.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/updaters/SecondaryChannelFocusUpdater.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/updaters/SecondaryChannelSessionUpdater.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/providers/SecondaryChannelProfileProviderBase.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/providers/SecondaryChannelProfileProviderEmail.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/providers/SecondaryChannelProfileProviderSMS.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/SecondaryChannelSMS.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/managers/channelManager/shared/SecondaryChannelManager.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/utils/BrowserUtils.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/shared/ExternalUserIdHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/models/AppConfig.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/config/index.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/utils/TagUtils.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/ConfigHelper.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/helpers/ConverterHelper.js","webpack:///(webpack)/buildin/global.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/utils/AwaitableTimeout.js","webpack:///./node_modules/jsonp/index.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/service-worker/ServiceWorker.js","webpack:///(webpack)/buildin/amd-define.js","webpack:///../../OneSignal/OneSignal-Website-SDK/build/ts-to-es6/src/entries/worker.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","configurable","enumerable","get","r","value","n","__esModule","object","property","prototype","hasOwnProperty","p","s","setPrototypeOf","Array","assign","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","step","next","e","rejected","result","done","then","apply","Log","[object Object]","window","localStorage","level","getItem","toLowerCase","setItem","proxyMethodsCreated","undefined","createProxyMethods","methods","log","trace","info","warn","error","nativeMethod","keys","nativeMethodExists","console","methodToMapTo","shouldMap","shouldLog","bind","Emitter_Emitter","this","_events","event","listener","push","that","fn","off","arguments","on","listeners","j","length","splice","removeAllListeners","args","shift","len","slice","IndexedDb_DATABASE_VERSION","IndexedDb_IndexedDb","databaseName","emitter","request","indexedDB","open","onerror","onDatabaseOpenError","onblocked","onDatabaseOpenBlocked","onupgradeneeded","onDatabaseUpgradeNeeded","onsuccess","database","onDatabaseError","onversionchange","onDatabaseVersionChange","openLock","preventDefault","target","Utils","contains","message","debug","errorCode","_","db","oldVersion","createObjectStore","keyPath","OneSignal","_isNewVisitor","table","key","ensureDatabaseOpen","transaction","objectStore","jsonResult","cursor","openCursor","cursorResult","cursorResultKey","continue","tslib_es6","put","store","delete","clear","AppState","ServiceWorkerState","Subscription","deviceId","subscriptionToken","optedOut","createdAt","expirationTime","bundle","subscription","Database_DatabaseEventName","DatabaseEventName","Database_Database","databaseInstance","singletonInstance","databaseInstanceName","id","data","timestamp","SdkEnvironment","getWindowEnv","WindowEnvironmentKind","ServiceWorker","OneSignalUtils","isUsingSubscriptionWorkaround","getTestEnv","TestEnvironmentKind","None","shouldUsePostmam","proxyFrameHost","POSTMAM_COMMANDS","REMOTE_DATABASE_GET","reply","applyDbResultFilter","REMOTE_DATABASE_GET_ALL","getAll","keypath","REMOTE_DATABASE_PUT","REMOTE_OPERATION_COMPLETE","emit","EVENTS","SET","REMOTE_DATABASE_REMOVE","remove","config","appIdStr","appId","subdomain","vapidPublicKey","externalUserId","authHash","externalIdToSave","getValueOrDefault","authHashToSave","type","appConfig","httpUseOneSignalCom","state","defaultNotificationUrl","defaultNotificationTitle","lastKnownPushEnabled","clickedNotifications","appState","clickedNotificationUrls","url","notificationDetails","workerVersion","dbOptedOut","dbNotOptedOut","setDeviceId","profileJson","EmailProfile","deserialize","emailProfile","serialize","SMSProfile","profile","consent","sessionKey","session","allClickedNotifications","find","notification","URL","origin","notificationId","promises","map","sentDuringSession","all","getSession","Session","setSession","removeSession","setEmailProfile","getEmailProfile","smsProfile","setSMSProfile","getSMSProfile","setSubscription","getSubscription","setProvideUserConsent","getProvideUserConsent","workerState","setServiceWorkerState","getServiceWorkerState","setAppState","getAppState","setAppConfig","getAppConfig","getExternalUserId","getExternalUserIdAuthHash","getLastNotificationClicked","removeNotificationClickedById","removeAllNotificationClicked","resetSentUniqueOutcomes","getNotificationClickedByUrl","getNotificationClickedById","getNotificationReceivedById","setExternalUserId","TimeoutError_TimeoutError","OneSignalError","super","Utils_Utils","indexOfAble","match","indexOf","style","text","charAt","toUpperCase","defaultValue","obj","JSON","stringify","hash","uriComponent","encodeURIComponent","promise","milliseconds","timeoutPromise","setTimeout","race","str","targetLength","padString","version","osVersionParts","toString","split","majorVersion","padStart","minorVersion","Number","subject","delimiter","maxParts","parts","skipParts","Math","max","join","Error","playerId","funcToExecute","enforceAppId","enforcePlayerId","isArray","errors","OneSignalApiError","MissingAppId","arrayToSort","predicateForProperty","descending","doItInPlace","internalArrayToSort","sort","a","b","propertyA","propertyB","__webpack_exports__","self","EnvironmentKind","SdkEnvironment_RESOURCE_HTTP_PORT","SdkEnvironment_API_URL_PORT","SdkEnvironment_TURBINE_API_URL_PORT","SdkEnvironment_TURBINE_ENDPOINTS","SdkEnvironment_SdkEnvironment","Production","usingProxyOrigin","Environment","isSafari","IntegrationKind","Secure","isTopFrame","top","isHttpsProtocol","location","protocol","context","InvalidArgumentError","Empty","SecureProxy","isLocalhostAllowedAsSecureOrigin","hostname","InsecureProxy","isFrameContextInsecure","navigator","serviceWorker","getRegistration","serviceWorkerManager","isBrowser","ServiceWorkerGlobalScope","Unknown","href","pathname","search","endsWith","getBuildEnv","Development","OneSignalSubscriptionPopup","Host","OneSignalProxyFrame","OneSignalSubscriptionModal","CustomIframe","buildEnv","Staging","EnumOutOfRange","getApiEnv","action","isTurbineEndpoint","port","some","turbine_endpoint","WorkerMessengerCommand","WorkerMessengerReplyBuffer","replies","command","callback","onceListenerOnly","record","targetRecord","listenersForCommand","listenerRecordIndex","WorkerMessenger","payload","_managers_SdkEnvironment__WEBPACK_IMPORTED_MODULE_2__","_models_WindowEnvironmentKind__WEBPACK_IMPORTED_MODULE_3__","clients","matchAll","includeUncontrolled","client","_Log__WEBPACK_IMPORTED_MODULE_5__","postMessage","windowClient","_errors_InvalidArgumentError__WEBPACK_IMPORTED_MODULE_1__","directPostMessageToSW","workerRegistration","availableWorker","_helpers_page_ServiceWorkerUtilHelper__WEBPACK_IMPORTED_MODULE_6__","getAvailableServiceWorker","_Environment__WEBPACK_IMPORTED_MODULE_4__","supportsServiceWorkers","addEventListener","onWorkerMessageReceivedFromPage","listenForPage","onPageMessageReceivedFromServiceWorker","listenerRecords","findListenersForMessage","listenersToRemove","listenersToCall","listenerRecord","deleteListenerRecord","addListener","deleteListenerRecords","deleteAllListenerRecords","userConfig","allowLocalhostAsSecureOrigin","windowEnv","_managers_SdkEnvironment__WEBPACK_IMPORTED_MODULE_1__","bowser__WEBPACK_IMPORTED_MODULE_0___default","safari","internalIsUsingSubscriptionWorkaround","_detect","userAgent","uuid","test","uuidStr","crypto","global","msCrypto","replace","getRandomValues","Uint8Array","random","methodName","_libraries_Log__WEBPACK_IMPORTED_MODULE_4__","_context_shared_utils_Utils__WEBPACK_IMPORTED_MODULE_5__","getConsoleStyle","_Environment__WEBPACK_IMPORTED_MODULE_2__","bowser__WEBPACK_IMPORTED_MODULE_2___default","TRADITIONAL_CHINESE_LANGUAGE_TAG","SIMPLIFIED_CHINESE_LANGUAGE_TAG","languageTag","language","languageSubtags","traditionalSubtag","simpleSubtag","substring","_managers_SdkEnvironment__WEBPACK_IMPORTED_MODULE_0__","_models_WindowEnvironmentKind__WEBPACK_IMPORTED_MODULE_1__","__SRC_STYLESHEETS_MD5_HASH__","awaitOneSignalInitAndSupported","initialized","once","SDK_INITIALIZED","logMethodCall","_utils_OneSignalUtils__WEBPACK_IMPORTED_MODULE_5__","addCssClass","targetSelectorOrElement","cssClass","element","document","querySelector","classList","add","awaitSdkEvent","eventName","deepCopy","parse","definition","t","detect","ua","getFirstMatch","regex","iosdevice","android","nexusMobile","nexusTablet","chromeos","silk","sailfish","tizen","webos","windowsphone","windows","mac","linux","edgeVersion","versionIdentifier","tablet","mobile","xbox","opera","samsungBrowser","coast","yandexbrowser","ucbrowser","maxthon","epiphany","puffin","sleipnir","kMeleon","msedge","msie","chromeBook","chrome","vivaldi","seamonkey","firefox","firefoxos","phantom","slimer","blackberry","touchpad","bada","qupzilla","chromium","googlebot","blink","webkit","gecko","ios","osVersion","getWindowsVersion","osversion","osMajorVersion","x","bowser","getVersionPrecision","arr","iterator","compareVersions","versions","precision","chunks","delta","chunk","reverse","isUnsupportedBrowser","minVersions","strictMode","_bowser","browser","String","browserList","browserItem","check","SubscriptionStateKind","OneSignalApiShared","_context_shared_utils_Utils__WEBPACK_IMPORTED_MODULE_3__","_OneSignalApiBase__WEBPACK_IMPORTED_MODULE_2__","options","app_id","playerIds","titles","contents","icon","buttons","params","include_player_ids","isAnyWeb","web_buttons","headings","chrome_web_icon","firefox_icon","trimUndefined","post","deviceRecord","serializedDeviceRecord","response","success","parent_player_id","subscriptionId","identifier_auth_hash","identifierAuthHash","userId","_errors_OneSignalApiError__WEBPACK_IMPORTED_MODULE_1__","writable","constructor","captureStackTrace","stack","InvalidArgumentReason","_OneSignalError__WEBPACK_IMPORTED_MODULE_0__","argName","reason","errorMessage","Malformed","argument","SessionStatus","SessionOrigin","ONESIGNAL_SESSION_KEY","initializeNewSession","currentTimestamp","Date","getTime","deviceType","startTimestamp","accumulatedDuration","status","Active","lastDeactivatedTimestamp","lastActivatedTimestamp","OneSignalApiBase","headers","method","_errors_OneSignalApiError__WEBPACK_IMPORTED_MODULE_3__","callHeaders","Headers","append","getOrigin","_Environment__WEBPACK_IMPORTED_MODULE_0__","cache","body","fetch","getOneSignalApiUrl","json","identifyError","catch","err","_context_shared_utils_Utils__WEBPACK_IMPORTED_MODULE_2__","OutcomesHelper_SEND_OUTCOME","OutcomesHelper_SEND_UNIQUE_OUTCOME","OutcomesHelper_OutcomesHelper","outcomeName","isUnique","getAttribution","outcomeMethodString","utils","privateIsPushNotificationsEnabled","libraries_Log","Database","filter","reduce","acc","curr","notificationIds","previouslyAttributedArr","getAttributedNotifsByUniqueOutcomeName","outcomeAttribution","notifArr","Outcomes","Unattributed","newNotificationIds","existingSentOutcome","currentSession","getCurrentSession","sentOutcome","sessionExistsAndWasPreviouslySent","sessionWasClearedButWasPreviouslySent","outcomeProps","weight","Direct","saveSentUniqueOutcome","updateManager","sendOutcomeDirect","Indirect","sendOutcomeInfluenced","wasSentDuringSession","sendOutcomeUnattributed","direct","enabled","indirect","timeframeMs","influencedTimePeriodMin","maxTimestamp","allReceivedNotification","influencedNotificationsLimit","allReceivedNotificationSorted","sortArrayOfObjects","notif","matchingNotificationIds","notificationIdsToDelete","forEach","unattributed","NotSupported","ServiceWorkerHelper_ServiceWorkerActiveState","ServiceWorkerActiveState","ServiceWorkerHelper_ServiceWorkerHelper","sdkVersion","appendServiceWorkerParams","workerPath","getFullPath","workerFullPath","getBaseUrl","encodeHashAsUriComponent","sessionThresholdInSeconds","sendOnFocusEnabled","sessionOrigin","outcomesConfig","existingSession","device_type","clickedNotification","upsertSession","sendOnSessionCallIfNecessary","timeInSecondsBetweenTimestamps","finalizeSession","thresholdInSeconds","Inactive","CancelableTimeout","timeSinceLastActivatedInSeconds","cancelableFinalize","PlayerCreate","identifier","registration","pushManager","rawPushSubscription","RawPushSubscription","setFromW3cSubscription","fullDeviceRecord","PushDeviceRecord","newPlayerId","OneSignalApiSW","updateUserSession","SecondaryChannelManager","synchronizer","onSession","attribution","sendSessionDuration","onFocus","cleanupCurrentSession","timestamp1","timestamp2","floor","SILENT_EVENTS","RETRIGGER_REMOTE_EVENTS","LEGACY_EVENT_MAP","notificationPermissionChange","subscriptionChange","customPromptClick","Event","remoteTriggerEnv","displayData","env","capitalize","_Environment__WEBPACK_IMPORTED_MODULE_1__","legacyEventName","_triggerLegacy","opener","parent","subscriptionPopup","REMOTE_RETRIGGER_EVENT","eventData","proxyFrame","retriggerRemoteEvent","CustomEvent","bubbles","cancelable","detail","dispatchEvent","DelayedPromptType","existingW3cPushSubscription","w3cEndpoint","w3cP256dh","w3cAuth","existingSafariDeviceToken","safariDeviceToken","pushSubscription","endpoint","getKey","p256dh","auth","p256dh_base64encoded","btoa","fromCharCode","auth_base64encoded","existingPushSubscription","NotImplementedError","SdkInitErrorKind","SdkInitError","extra","InvalidAppId","AppNotConfiguredForWebPush","MissingSubdomain","WrongSiteUrl","siteUrl","MultipleInitialization","MissingSafariWebId","OutcomeAttributionType","NotSubscribedReason","NotSubscribedError","NoDeviceId","NoEmailSet","NoSMSSet","OptedOut","OneSignalApiErrorKind","_context_shared_utils_Utils__WEBPACK_IMPORTED_MODULE_4__","_reject","_OneSignalApiBase__WEBPACK_IMPORTED_MODULE_1__","notification_types","_models_SubscriptionStateKind__WEBPACK_IMPORTED_MODULE_2__","TemporaryWebRecord","_libraries_Log__WEBPACK_IMPORTED_MODULE_3__","enforceAppIdAndPlayerId","tslib__WEBPACK_IMPORTED_MODULE_0__","sessionDuration","active_time","_models_Outcomes__WEBPACK_IMPORTED_MODULE_5__","notification_ids","PermissionUtils","updateIfIdentical","newPermission","privateGetNotificationPermission","_services_Database__WEBPACK_IMPORTED_MODULE_1__","_Event__WEBPACK_IMPORTED_MODULE_2__","trigger","NATIVE_PROMPT_PERMISSIONCHANGED","to","DeliveryPlatformKind","_DeviceRecord__WEBPACK_IMPORTED_MODULE_3__","serializedBundle","web_auth","web_p256","subscriptionState","pushRegistration","_SubscriptionStateKind__WEBPACK_IMPORTED_MODULE_2__","Subscribed","NotSubscribed","_errors_NotImplementedError__WEBPACK_IMPORTED_MODULE_1__","PromptsHelper","prompts","getFirstSlidedownPromptOptionsWithType","_src_models_Prompts__WEBPACK_IMPORTED_MODULE_0__","Category","categories","_a","_b","tags","autoPrompt","slidedownType","Push","DeviceRecord","getLanguage","timezone","getTimezoneOffset","timezoneId","Intl","DateTimeFormat","resolvedOptions","timeZone","browserVersion","parseInt","isNaN","deviceModel","platform","deliveryPlatform","getDeliveryPlatform","pushNotification","_utils_OneSignalUtils__WEBPACK_IMPORTED_MODULE_4__","redetectBrowserUserAgent","_DeliveryPlatformKind__WEBPACK_IMPORTED_MODULE_3__","Safari","Firefox","Edge","ChromeLike","timezone_id","device_os","device_model","sdk","external_user_id","externalUserIdAuthHash","external_user_id_auth_hash","_errors_NotImplementedError__WEBPACK_IMPORTED_MODULE_2__","smsId","smsNumber","emailId","emailAddress","doNothing","_libraries_sw_Log__WEBPACK_IMPORTED_MODULE_1__","cancelableTimeout","delayInSeconds","delayInMilliseconds","timerId","clearTimeoutHandle","startedExecution","clearTimeout","cancel","ServiceWorkerUtilHelper","scope","_libraries_Log__WEBPACK_IMPORTED_MODULE_1__","active","installing","waiting","NotificationPermission","PermissionManager_PermissionManager","STORED_PERMISSION_KEY","safariWebId","reportedPermission","getReportedNotificationPermission","isPermissionEnvironmentAmbiguous","getInterpretedAmbiguousPermission","bowser_default","getSafariNotificationPermission","getOneSignalSubdomainNotificationPermission","getW3cNotificationPermission","permission","Notification","REMOTE_NOTIFICATION_PERMISSION","remoteNotificationPermission","Denied","isCurrentFrameContextCrossOrigin","topFrameOrigin","storedPermission","getStoredPermission","Default","LocalStorage_LocalStorage","setStoredPermission","getNotificationPermission","LocalStorage_IS_OPTED_OUT","LocalStorage_IS_PUSH_NOTIFICATIONS_ENABLED","LocalStorage_PAGE_VIEWS","Granted","count","PageViewManager_PageViewManager","incrementedPageViewCount","pageViewCountStr","sessionStorage","SESSION_STORAGE_KEY_NAME","pageViewCount","sessionCount","SET_SESSION_COUNT","newCountSingleTab","getPageViewCount","newCountAcrossTabs","getLocalPageViewCount","setPageViewCount","setLocalPageViewCount","Path_Path","path","trim","indexOfDelimiter","QUERY_STRING","getWithoutQueryString","pop","newPath","fileNameIndex","lastIndexOf","getFileName","pathWithoutFileName","ServiceWorkerRegistrationError_ServiceWorkerRegistrationError","statusText","errors_ServiceWorkerRegistrationError","ServiceWorkerManager_ServiceWorkerManager","registrationOptions","integration","getIntegration","ServiceWorkerHelper","Indeterminate","runCommand","SERVICE_WORKER_STATE","swFileName","activeSwFileName","swActiveStateByFileName","workerScriptPath","scriptURL","importedSw","URLSearchParams","fileName","OneSignalWorker","ThirdParty","proxyWorkerVersion","GET_WORKER_VERSION","NaN","workerMessenger","WorkerVersion","unicast","environmentInfo","browserType","getActiveState","notificationsEnabled","permissionManager","haveParamsChanged","workerNeedsUpdate","existingSwScope","configuredSwScope","a_old","b_new","serviceWorkerHref","getServiceWorkerHref","getWorkerVersion","NotificationDisplayed","NOTIFICATION_DISPLAYED","NotificationClicked","clickedListenerCallbackCount","messenger","GET_EVENT_LISTENER_COUNT","NOTIFICATION_CLICKED","callbackCount","numberOfListeners","now","RedirectPage","SERVICEWORKER_COMMAND_REDIRECT","NotificationDismissed","NOTIFICATION_DISMISSED","isHttps","AreYouVisible","incomingPayload","focused","hasFocus","AreYouVisibleResponse","httpPayload","ARE_YOU_VISIBLE_REQUEST","shouldInstallWorker","workerHref","register","establishServiceWorkerChannel","PermissionPromptType","InvalidStateError_InvalidStateReason","InvalidStateReason","PushPermissionNotGrantedError_PushPermissionNotGrantedErrorReason","PushPermissionNotGrantedErrorReason","InvalidStateError_InvalidStateError","RedundantPermissionMessage","extraInfo","permissionPromptType","PushPermissionAlreadyGranted","UnsupportedEnvironment","ServiceWorkerNotActivated","NoProxyFrame","description","PushPermissionNotGrantedError_PushPermissionNotGrantedError","Dismissed","Blocked","SubscriptionError_SubscriptionErrorReason","SubscriptionErrorReason","SubscriptionError_SubscriptionError","InvalidSafariSetup","SubscriptionManager_SubscriptionManager","subscriptionStrategy","subscribeFcmFromWorker","subscribeSafari","installWorker","subscribeFcmFromPage","createFromPushSubscription","newDeviceId","isAlreadyRegisteredWithOneSignal","sendPushDeviceRecordUpdate","sendPlayerCreate","associateSubscriptionWithEmail","REGISTERED","_sessionInitAlreadyRunning","requestNotificationPermission","strategy","updatePlayer","MutedByApi","results","requestPermission","email","deviceToken","pushSubscriptionDetails","existingDeviceToken","PERMISSION_PROMPT_DISPLAYED","subscribeSafariPromptPermission","triggerNotificationPermissionChanged","setFromSafariSubscription","requestPresubscribeNotificationPermission","_isRegisteringForPush","subscriptionManager","registerFailedSubscription","ServiceWorkerStatus403","ServiceWorkerStatus404","subscribeWithVapidKey","swRegistration","pushPermission","permissionState","userVisibleOnly","onesignalVapidPublicKey","base64String","base64","repeat","rawData","atob","outputArray","charCodeAt","base64ToUint8Array","buffer","doPushUnsubscribe","newPushSubscription","isNewSubscription","doPushSubscribe","getVapidKeyForBrowser","updateSubscriptionTime","updateCreatedAt","unsubscribe","applicationServerKey","subscriptionOptions","existingSubscription","subscribe","integrationKind","isSubscriptionExpiringForSecureIntegration","SUBSCRIPTION_EXPIRATION_STATE","serviceWorkerRegistration","subscriptionCreatedAt","ONE_YEAR","midpointExpirationTime","getSubscriptionStateForSecure","subscribed","GET_SUBSCRIPTION_STATE","getSubscriptionStateForInsecure","notificationPermission","isWorkerActive","pageViewManager","isFirstPageView","registerSubscription","incrementPageViewCount","helpers_ContextHelper","envPrefix","getBuildEnvPrefix","serviceWorkerManagerConfig","serviceWorkerPath","serviceWorkerParam","subscriptionManagerConfig","LimitStore","LIMIT","values","CUSTOM_LINK_CSS_CLASSES","containerClass","subscribeClass","explanationClass","resetClass","hide","unsubscribed","CUSTOM_LINK_CSS_SELECTORS","containerSelector","subscribeSelector","explanationSelector","CustomLinkManager_CustomLinkManager","loadSdkStyles","unsubscribeEnabled","isPushEnabled","customlinkContainerElements","injectMarkup","hideCustomLinkContainers","innerHTML","mountExplanationNode","mountSubscriptionNode","explanation","createElement","textContent","size","appendChild","subscribeButton","setCustomColors","setTextFromPushStatus","handleClick","dynamicResourceLoader","loadSdkStylesheet","hideElement","isOptedOut","autoAccept","requiresUserInteraction","registerForPushNotifications","_c","_d","_e","_f","_g","color","button","backgroundColor","containers","querySelectorAll","getIsPushNotificationsEnabled","getIsOptedOut","EventHelper_EventHelper","checkAndTriggerSubscriptionChanged","getSubscriptionState","setIsPushNotificationsEnabled","triggerSubscriptionChanged","newSubscriptionState","onSubscriptionChanged_showWelcomeNotification","onSubscriptionChanged_sendCategorySlidedownTags","onSubscriptionChanged_evaluateNotifyButtonDisplayPredicate","onSubscriptionChanged_updateCustomLink","isSubscribed","promptOptions","slidedown","isCategorySlidedownConfigured","tagManager","sendTags","__doNotShowWelcomeNotification","welcome_notification_opts","welcomeNotification","welcome_notification_disabled","title","unopenableWelcomeNotificationUrl","BrowserUtils","decodeHtmlEntities","sendNotification","en","__isOneSignalWelcomeNotification","WELCOME_NOTIFICATION_SENT","notifyButton","displayPredicate","launcher","show","customlink","initialize","SUBSCRIPTION_CHANGED","fireEventWithNotification","clickedNotificationInfo","clickedNotificationUrl","pageClickedNotifications","urlWithoutTrailingSlash","Browser","SubscriptionHelper_SubscriptionHelper","internalRegisterForPush","MainHelper_MainHelper","getDeviceId","createDeviceRecord","sessionManager","PageRefresh","rawSubscription","windowCreator","updateStoredPermission","REMOTE_NOTIFICATION_PERMISSION_CHANGED","forceUpdatePermission","close","FINISH_REMOTE_REGISTRATION","progress","swSubscription","getRawPushSubscriptionForSafari","getRawPushSubscriptionWhenUsingSubscriptionWorkaround","isBrowserAndSupportsServiceWorkers","getRawPushSubscriptionFromServiceWorkerRegistration","currentPermission","existingUser","isOptedIn","previousPermission","getAppId","fullscreen","autoAcceptTitle","actionMessage","exampleNotificationTitleDesktop","exampleNotificationTitleMobile","exampleNotificationMessageDesktop","exampleNotificationMessageMobile","exampleNotificationCaption","caption","acceptButton","cancelButton","promptOptionsStr","getFullscreenPermissionMessageOptions","getPromptOptionsPostHash","legacyParams","legacyParamKey","legacyParamValue","allowedPromptOptions","encoded_value","clickResult","CUSTOM_PROMPT_CLICKED","includeSubscription","getRawPushSubscription","getCurrentNotificationType","UpdateManager_UpdateManager","onSessionSent","sendOnSessionUpdate","enableOnSession","PlayerOnSession","ExternalUserIdHelper","addExternalUserIdToDeviceRecord","createUser","secondaryChannelManager","pushUpdatePromise","sendPushPlayerUpdate","isDeviceIdAvailable","setTags","outcomeRequestData","sendOutcome","SessionManager_SessionManager","_context","_deviceId","_deviceRecord","_sessionOrigin","ContextSW_ContextSW","getSubscriptionManager","getServiceWorkerManager","SecondaryChannelSynchronizer_SecondaryChannelSynchronizer","_channels","channel","OneSignalApi_OneSignalApi","getPlayer","jsonp_default","jsonpLib","downloadServerAppConfig","logoutEmail","SecondaryChannelEmail_SecondaryChannelEmail","secondaryChannelIdentifierUpdater","secondaryChannelExternalUserIdUpdater","secondaryChannelTagsUpdater","secondaryChannelSessionUpdater","secondaryChannelFocusUpdater","profileProvider","emailProfileBefore","getProfile","newEmailSubscriptionId","setIdentifier","emailProfileAfter","newProfile","updatePushPlayersRelationToEmailPlayer","existingEmailProfile","newEmailProfile","isExistingPushRecordSaved","emailPreviouslySavedAndDifferent","emailPreviouslySavedAndChanged","sendOnSession","sendOnFocus","SecondaryChannelDeviceRecord_SecondaryChannelDeviceRecord","pushDeviceRecordId","device_player_id","SecondaryChannelIdentifierUpdater_SecondaryChannelIdentifierUpdater","existingProfile","setProfile","SecondaryChannelTagsUpdater_SecondaryChannelTagsUpdater","getSubscriptionId","SecondaryChannelExternalUserIdUpdater_SecondaryChannelExternalUserIdUpdater","SecondaryChannelFocusUpdater_SecondaryChannelFocusUpdater","SecondaryChannelSessionUpdater_SecondaryChannelSessionUpdater","secondaryChannelRecord","newSubscriptionId","SecondaryChannelProfileProviderBase_SecondaryChannelProfileProviderBase","_pendingGetSubscriptionIdResolvers","SecondaryChannelProfileProviderEmail_SecondaryChannelProfileProviderEmail","Email","_super","SecondaryChannelProfileProviderSMS_SecondaryChannelProfileProviderSMS","SMS","SecondaryChannelSMS_SecondaryChannelSMS","SecondaryChannelManager_SecondaryChannelManager","emailProfileProvider","emailChannel","registerChannel","smsProfileProvider","smsChannel","sms","decodeTextArea","ConfigIntegrationKind","NotificationClickMatchBehavior","NotificationClickActionBehavior","config_SERVER_CONFIG_DEFAULTS_SESSION","reportingThreshold","enableOnSessionForUnsubcribed","enableOnFocus","config_SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS","pageViews","timeDelay","config_SERVER_CONFIG_DEFAULTS_SLIDEDOWN","errorButton","categoryDefaults","updateMessage","positiveUpdateButton","negativeUpdateButton","savingText","confirmMessage","config_CONFIG_DEFAULTS_SLIDEDOWN_OPTIONS","Prompts","delay","TagUtils_TagUtils","convertedTags","localTags","remoteTags","finalTags","categoryArray","checked","category","existingPlayerTags","isTagObjectEmpty","categoriesCopy","markAllTagsAsSpecified","existingTagValue","tag","getCheckedStatusForTagValue","tagValue","tagCategories","tagCategoriesCopy","ConfigHelper_IntegrationConfigurationKind","IntegrationConfigurationKind","ConverterHelper_ConverterHelper","isPromptOptionsVersion0","convertConfigToVersionOne","isSlidedownConfigVersion1","convertConfigToVersionTwo","acceptButtonText","cancelButtonText","higherLevelAcceptButtonText","higherLevelCancelButtonText","slidedownConfig","promptType","isCategorySlidedownConfiguredVersion1","version0Keys","version1Keys","ConfigHelper_MAX_CATEGORIES","ConfigHelper_ConfigHelper","isValidUuid","serverConfig","upgradeConfigToVersionTwo","getMergedConfig","checkRestrictedOrigin","code","restrictedOriginEnabled","doesCurrentOriginMatchConfigOrigin","configOrigin","Custom","WordPress","configuration","JavaScript","Dashboard","configIntegrationKind","getConfigIntegrationKind","getSubdomainForConfigIntegrationKind","setupBehavior","mergedUserConfig","getUserConfigForConfigIntegrationKind","siteName","siteInfo","http_use_onesignal_com","features","restrict_origin","enable","metrics","mixpanelReportingToken","mixpanel_reporting_token","safari_web_id","vapid_public_key","onesignal_vapid_public_key","receiveReceiptsEnable","receive_receipts_enable","valueOrDefault","enable_on_session","sessionThreshold","session_threshold","enableSessionDuration","web_on_focus_enabled","kind","initialState","staticPrompts","defaultsFromServer","wholeUserConfig","customlinkUser","customlinkDefaults","promptOptionsConfig","promptOption","_h","_j","limitCategoriesToMaxCount","native","autoRegister","isSlidedownAutoPromptConfigured","getCustomLinkConfig","getIntegrationCapabilities","autoResubscribe","workerName","registrationScope","subdomainName","proxyOrigin","getPromptOptionsForDashboardConfiguration","disable","bell","hideWhenSubscribed","isPushNotificationsEnabled","position","showCredit","offset","bottom","left","right","colors","circle.background","main","circle.foreground","accent","badge.background","badge.foreground","badge.bordercolor","pulse.color","dialog.button.background.hovering","dialog.button.background.active","dialog.button.background","dialog.button.foreground","tip.state.unsubscribed","tooltip","tip.state.subscribed","tip.state.blocked","blocked","message.prenotify","message.action.subscribing","subscribing","message.action.subscribed","message.action.resubscribed","message.action.unsubscribed","unsubscribing","dialog.main.title","dialog","dialog.main.button.subscribe","dialog.main.button.unsubscribe","unsubscribeButton","dialog.blocked.title","dialog.blocked.message","persistNotification","notificationBehavior","display","persist","webhooks","cors","corsEnable","notification.displayed","notificationDisplayedHook","notification.clicked","notificationClickedHook","notification.dismissed","notificationDismissedHook","notificationClickHandlerMatch","click","notificationClickHandlerAction","requiresUserPrivacyConsent","outcomes","notification_attribution","minutes_since_displayed","limit","isTopLevelServiceWorkerParamDefined","SERVICE_WORKER_PARAM","isTopLevelServiceWorkerPathDefined","SERVICE_WORKER_PATH","fallbackServiceWorkerParam","fallbackServiceWorkerPath","injectDefaultsIntoPromptOptions","integrationCapabilities","userValue","serverValue","proxyOriginEnabled","shouldUseServerConfigSubdomain","userProvidedSubdomain","capabilities","g","Function","eval","awaitableTimeout","ms","opts","script","timer","prefix","param","timeout","enc","getElementsByTagName","head","cleanup","parentNode","removeChild","noop","src","insertBefore","MAX_CONFIRMED_DELIVERY_DELAY","VERSION","environment","_libraries_sw_Log__WEBPACK_IMPORTED_MODULE_12__","_services_Database__WEBPACK_IMPORTED_MODULE_7__","bowser__WEBPACK_IMPORTED_MODULE_1___default","_libraries_WorkerMessenger__WEBPACK_IMPORTED_MODULE_3__","onServiceWorkerActivated","onPushReceived","onNotificationClosed","waitUntil","onNotificationClicked","onPushSubscriptionChange","SessionUpsert","debounceRefreshSession","SessionDeactivate","listen","setupMessageListeners","broadcast","Subscribe","appConfigBundle","_models_ContextSW__WEBPACK_IMPORTED_MODULE_4__","SubscribeNew","AmpSubscriptionState","_appConfigBundle","AmpSubscribe","_helpers_ConfigHelper__WEBPACK_IMPORTED_MODULE_13__","_OneSignalApiSW__WEBPACK_IMPORTED_MODULE_6__","AmpUnsubscribe","clientsStatus","receivedResponsesCount","hasAnyActiveSessions","SetLogging","_context_shared_utils_Utils__WEBPACK_IMPORTED_MODULE_15__","parseOrFetchNotifications","notifications","notificationEventPromiseFns","notificationReceivedPromises","rawNotification","buildStructuredNotificationObject","notificationReceived","displayNotification","executeWebhooks","sendConfirmedDelivery","UNSUBSCRIBED_FROM_NOTIFICATIONS","webhookTargetUrl","isServerCorsEnabled","postData","heading","content","fetchOptions","mode","X-OneSignal-Event","Content-Type","rr","player_id","_models_DeviceRecord__WEBPACK_IMPORTED_MODULE_18__","_utils_AwaitableTimeout__WEBPACK_IMPORTED_MODULE_19__","_OneSignalApiBase__WEBPACK_IMPORTED_MODULE_5__","windowClients","activeClients","isSubdomainIframe","frameType","_helpers_ServiceWorkerHelper__WEBPACK_IMPORTED_MODULE_16__","deactivateSession","checkIfAnyClientsFocusedAndUpdateSession","w","updateSessionBasedOnHasActive","osClients","getActiveClients","sessionInfo","sentRequestsCount","getClientStatusesCancelable","_helpers_sw_CancelableTimeout__WEBPACK_IMPORTED_MODULE_17__","cancelableRefreshSession","refreshSession","custom","alert","u","image","badge","vibrate","rawButton","imageUrl","parsedImageUrl","host","ensureImageResourceHttps","overrides","defaultTitle","_getTitle","defaultIcon","ensureNotificationResourcesHttps","notificationOptions","actions","requireInteraction","renotify","showNotification","launchUrl","dbDefaultNotificationUrl","notificationData","matchPreference","actionPreference","getNotificationUrlToOpen","notificationOpensLink","shouldOpenNotificationUrl","saveNotificationClickedPromise","notificationClicked","_models_Session__WEBPACK_IMPORTED_MODULE_11__","convertedAPIRequests","sendConvertedAPIRequests","doNotOpenLink","clientUrl","lastKnownHostUrl","clientOrigin","launchOrigin","WindowClient","focus","navigate","openUrl","onesignalRestPromise","opened","openWindow","claim","deviceIdExists","oldSubscription","getUserIdFromSubscriptionIdentifier","_models_PushDeviceRecord__WEBPACK_IMPORTED_MODULE_10__","providedNewSubscription","newSubscription","_models_RawPushSubscription__WEBPACK_IMPORTED_MODULE_8__","_models_SubscriptionStateKind__WEBPACK_IMPORTED_MODULE_9__","PermissionRevoked","PushSubscriptionRevoked","pageTitle","isValidPushPayload","_utils_OneSignalUtils__WEBPACK_IMPORTED_MODULE_14__","run","_src_service_worker_ServiceWorker__WEBPACK_IMPORTED_MODULE_0__"],"mappings":"aACA,IAAAA,KAGA,SAAAC,EAAAC,GAGA,GAAAF,EAAAE,GACA,OAAAF,EAAAE,GAAAC,QAGA,IAAAC,EAAAJ,EAAAE,IACAG,EAAAH,EACAI,GAAA,EACAH,YAUA,OANAI,EAAAL,GAAAM,KAAAJ,EAAAD,QAAAC,IAAAD,QAAAF,GAGAG,EAAAE,GAAA,EAGAF,EAAAD,QAKAF,EAAAQ,EAAAF,EAGAN,EAAAS,EAAAV,EAGAC,EAAAU,EAAA,SAAAR,EAAAS,EAAAC,GACAZ,EAAAa,EAAAX,EAAAS,IACAG,OAAAC,eAAAb,EAAAS,GACAK,cAAA,EACAC,YAAA,EACAC,IAAAN,KAMAZ,EAAAmB,EAAA,SAAAjB,GACAY,OAAAC,eAAAb,EA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G,EAAoBs2B,EAAA,EAAsBE,+BAGxCn0C,EAAQ+sB,oBAAoB8C,qBAAqB7Y,EAAqB2G,cAtBtEwuB,EAAA,EAASh2C,OAAO,MAAO,gBACvBg2C,EAAA,EAASh2C,OAAO,MAAO,oBA2BrCxI,mBACI,OAAO,IAAIb,QAAQC,IACfD,QAAQmM,KAAKkzC,EAAA,EAASxgD,IAAI,UAAW,gBAAiBwgD,EAAA,EAASxgD,IAAI,UAAW,eACzE6B,KAAK,EAAE+jD,EAAc6C,MAElBrnD,EADiB,OAAjBwkD,EACQA,EAEU,MAAb6C,EACGA,EAGA,QAWxBzmD,iCAAiC2B,GAC7B,IAAKA,IAAUA,EAAMmF,KACjB,OAAO3H,QAAQE,OAAO,uCAG1B,OADuB8H,EAAcu/C,mBAAmB/kD,EAAMmF,OAE1Dy3C,EAAA,EAAIn6C,MAAM,4CACHjF,QAAQC,SAASuC,EAAMmF,KAAK6c,UAMhCxkB,QAAQE,oDAAoDsC,EAAMmF,QAO7E9G,0BAA0BigC,GACtB,IACI,MAAM9qB,EAAU8qB,EAAQtc,OACxB,SAAIxO,GACAA,EAAQ6tC,QACR7tC,EAAQ6tC,OAAO9lD,GACfypD,EAAA,EAAevS,YAAYj/B,EAAQ6tC,OAAO9lD,MAI1CqhD,EAAA,EAAIn6C,MAAM,gEAAiE+Q,IACpE,GAGf,MAAO1V,GAEH,OADA8+C,EAAA,EAAIn6C,MAAM,mDAAoD3E,IACvD,IAKC,oBAAT0R,WACW,IAAX4G,EACPA,EAAOkhB,gBAAkB9xB,EAGzBgK,KAAK8nB,gBAAkB9xB,EAGP,oBAATgK,MACPhK,EAAcy/C,wCCxgClB3pD,EAAAD,QAAA,WACA,UAAA+S,MAAA,wECDA,IAAA82C,EAAA/pD,EAAA,IAIAqU,KAAKxM,UAAYkiD,EAAA","file":"OneSignalSDKWorker.js","sourcesContent":[" \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, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\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 = 49);\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [0, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator];\r\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","export default class Log {\n static shouldLog() {\n try {\n if (typeof window === \"undefined\" ||\n typeof window.localStorage === \"undefined\") {\n return false;\n }\n const level = window.localStorage.getItem(\"loglevel\");\n if (level && level.toLowerCase() === \"trace\") {\n return true;\n }\n else {\n return false;\n }\n }\n catch (e) {\n /* LocalStorage may not be accessible on browser profiles that restrict 3rd party cookies */\n return false;\n }\n }\n static setLevel(level) {\n if (typeof window === \"undefined\" ||\n typeof window.localStorage === \"undefined\") {\n return;\n }\n try {\n window.localStorage.setItem(\"loglevel\", level);\n Log.proxyMethodsCreated = undefined;\n Log.createProxyMethods();\n }\n catch (e) {\n /* LocalStorage may not be accessible on browser profiles that restrict 3rd party cookies */\n return;\n }\n }\n static createProxyMethods() {\n if (typeof Log.proxyMethodsCreated !== \"undefined\") {\n return;\n }\n else {\n Log.proxyMethodsCreated = true;\n }\n const methods = {\n log: \"debug\",\n trace: \"trace\",\n info: \"info\",\n warn: \"warn\",\n error: \"error\"\n };\n for (const nativeMethod of Object.keys(methods)) {\n const nativeMethodExists = typeof console[nativeMethod] !== \"undefined\";\n const methodToMapTo = methods[nativeMethod];\n const shouldMap = nativeMethodExists &&\n ((typeof __LOGGING__ !== \"undefined\" && __LOGGING__ === true) ||\n (Log.shouldLog()) ||\n methodToMapTo === \"error\");\n if (shouldMap) {\n Log[methodToMapTo] = console[nativeMethod].bind(console);\n }\n else {\n Log[methodToMapTo] = function () { };\n }\n }\n }\n}\nLog.createProxyMethods();\n//# sourceMappingURL=Log.js.map","/**\n * Source: https://github.com/pazguille/emitter-es6\n */\n/**\n * Creates a new instance of Emitter.\n * @class\n * @returns {Object} emitter - An instance of Emitter.\n * @example\n * var emitter = new Emitter();\n */\nexport default class Emitter {\n constructor() {\n this._events = {};\n }\n /**\n * Adds a listener to the collection for a specified event.\n */\n on(event, listener) {\n this._events[event] = this._events[event] || [];\n this._events[event].push(listener);\n return this;\n }\n /**\n * Adds a one time listener to the collection for a specified event. It will\n * execute only once.\n */\n once(event, listener) {\n const that = this;\n function fn() {\n that.off(event, fn);\n listener.apply(this, arguments);\n }\n fn.listener = listener;\n this.on(event, fn);\n return this;\n }\n /**\n * Removes a listener from the collection for a specified event.\n */\n off(event, listener) {\n const listeners = this._events[event];\n if (listeners !== undefined) {\n for (let j = 0; j < listeners.length; j += 1) {\n if (listeners[j] === listener || listeners[j].listener === listener) {\n listeners.splice(j, 1);\n break;\n }\n }\n if (listeners.length === 0)\n this.removeAllListeners(event);\n }\n return this;\n }\n /**\n * Removes all listeners from the collection for a specified event.\n */\n removeAllListeners(event) {\n try {\n if (event)\n delete this._events[event];\n else\n this._events = {};\n }\n catch (e) { }\n return this;\n }\n /**\n * Returns all listeners from the collection for a specified event.\n * @public\n * @function\n * @name Emitter#listeners\n * @param {String} event - Event name.\n * @returns {Array}\n * @example\n * me.listeners('ready');\n */\n listeners(event) {\n try {\n return this._events[event];\n }\n catch (e) {\n return undefined;\n }\n }\n /**\n * Returns number of listeners from the collection for a specified event.\n * @public\n * @function\n * @name Emitter#numberOfListeners\n * @param {String} event - Event name.\n * @returns {number}\n * @example\n * me.numberOfListeners('ready');\n */\n numberOfListeners(event) {\n const listeners = this.listeners(event);\n if (listeners)\n return listeners.length;\n return 0;\n }\n /**\n * Execute each item in the listener collection in order with the specified data.\n * @param event - String of the event name\n * @param args - Variable number of args to pass to the functions subscribe to the event\n */\n async emit(...args) {\n const event = args.shift();\n let listeners = this._events[event];\n if (listeners !== undefined) {\n listeners = listeners.slice(0);\n const len = listeners.length;\n for (let i = 0; i < len; i += 1)\n await listeners[i].apply(this, args);\n }\n return this;\n }\n}\n//# sourceMappingURL=Emitter.js.map","import Emitter from '../libraries/Emitter';\nimport Log from '../libraries/Log';\nimport Utils from \"../context/shared/utils/Utils\";\nconst DATABASE_VERSION = 3;\nexport default class IndexedDb {\n constructor(databaseName) {\n this.databaseName = databaseName;\n this.emitter = new Emitter();\n }\n open(databaseName) {\n return new Promise(resolve => {\n let request = undefined;\n try {\n // Open algorithm: https://www.w3.org/TR/IndexedDB/#h-opening\n request = indexedDB.open(databaseName, DATABASE_VERSION);\n }\n catch (e) {\n // Errors should be thrown on the request.onerror event, but just in case Firefox throws additional errors\n // for profile schema too high\n }\n if (!request) {\n return null;\n }\n request.onerror = this.onDatabaseOpenError;\n request.onblocked = this.onDatabaseOpenBlocked;\n request.onupgradeneeded = this.onDatabaseUpgradeNeeded;\n request.onsuccess = () => {\n this.database = request.result;\n this.database.onerror = this.onDatabaseError;\n this.database.onversionchange = this.onDatabaseVersionChange;\n resolve(this.database);\n };\n });\n }\n async ensureDatabaseOpen() {\n if (!this.openLock) {\n this.openLock = this.open(this.databaseName);\n }\n return await this.openLock;\n }\n onDatabaseOpenError(event) {\n // Prevent the error from bubbling: https://bugzilla.mozilla.org/show_bug.cgi?id=1331103#c3\n /**\n * To prevent error reporting tools like Sentry.io from picking up errors that\n * the site owner can't do anything about and use up their quota, hide database open\n * errors.\n */\n event.preventDefault();\n const error = event.target.error;\n if (Utils.contains(error.message, 'The operation failed for reasons unrelated to the database itself and not covered by any other error code') ||\n Utils.contains(error.message, 'A mutation operation was attempted on a database that did not allow mutations')) {\n Log.warn(\"OneSignal: IndexedDb web storage is not available on this origin since this profile's IndexedDb schema has been upgraded in a newer version of Firefox. See: https://bugzilla.mozilla.org/show_bug.cgi?id=1236557#c6\");\n }\n else {\n Log.warn('OneSignal: Fatal error opening IndexedDb database:', error);\n }\n }\n /**\n * Error events bubble. Error events are targeted at the request that generated the error, then the event bubbles to\n * the transaction, and then finally to the database object. If you want to avoid adding error handlers to every\n * request, you can instead add a single error handler on the database object.\n */\n onDatabaseError(event) {\n Log.debug('IndexedDb: Generic database error', event.target.errorCode);\n }\n /**\n * Occurs when the upgradeneeded should be triggered because of a version change but the database is still in use\n * (that is, not closed) somewhere, even after the versionchange event was sent.\n */\n onDatabaseOpenBlocked() {\n Log.debug('IndexedDb: Blocked event');\n }\n /**\n * Occurs when a database structure change (IDBOpenDBRequest.onupgradeneeded event or IDBFactory.deleteDatabase) was\n * requested elsewhere (most probably in another window/tab on the same computer).\n *\n * versionchange Algorithm: https://www.w3.org/TR/IndexedDB/#h-versionchange-transaction-steps\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/onversionchange\n */\n onDatabaseVersionChange(_) {\n Log.debug('IndexedDb: versionchange event');\n }\n /**\n * Occurs when a new version of the database needs to be created, or has not been created before, or a new version\n * of the database was requested to be opened when calling window.indexedDB.open.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/onupgradeneeded\n */\n onDatabaseUpgradeNeeded(event) {\n Log.debug('IndexedDb: Database is being rebuilt or upgraded (upgradeneeded event).');\n const db = event.target.result;\n if (event.oldVersion < 1) {\n db.createObjectStore(\"Ids\", { keyPath: \"type\" });\n db.createObjectStore(\"NotificationOpened\", { keyPath: \"url\" });\n db.createObjectStore(\"Options\", { keyPath: \"key\" });\n }\n if (event.oldVersion < 2) {\n db.createObjectStore(\"Sessions\", { keyPath: \"sessionKey\" });\n db.createObjectStore(\"NotificationReceived\", { keyPath: \"notificationId\" });\n db.createObjectStore(\"NotificationClicked\", { keyPath: \"notificationId\" });\n }\n if (event.oldVersion < 3) {\n db.createObjectStore(\"SentUniqueOutcome\", { keyPath: \"outcomeName\" });\n }\n // Wrap in conditional for tests\n if (typeof OneSignal !== \"undefined\") {\n OneSignal._isNewVisitor = true;\n }\n }\n /**\n * Asynchronously retrieves the value of the key at the table (if key is specified), or the entire table (if key is not specified).\n * @param table The table to retrieve the value from.\n * @param key The key in the table to retrieve the value of. Leave blank to get the entire table.\n * @returns {Promise} Returns a promise that fulfills when the value(s) are available.\n */\n async get(table, key) {\n const database = await this.ensureDatabaseOpen();\n if (key) {\n // Return a table-key value\n return await new Promise((resolve, reject) => {\n const request = database.transaction(table).objectStore(table).get(key);\n request.onsuccess = () => {\n resolve(request.result);\n };\n request.onerror = () => {\n reject(request.error);\n };\n });\n }\n else {\n // Return all values in table\n return await new Promise((resolve, reject) => {\n const jsonResult = {};\n const cursor = database.transaction(table).objectStore(table).openCursor();\n cursor.onsuccess = (event) => {\n const cursorResult = event.target.result;\n if (cursorResult) {\n const cursorResultKey = cursorResult.key;\n jsonResult[cursorResultKey] = cursorResult.value;\n cursorResult.continue();\n }\n else {\n resolve(jsonResult);\n }\n };\n cursor.onerror = () => {\n reject(cursor.error);\n };\n });\n }\n }\n async getAll(table) {\n return await new Promise(async (resolve, reject) => {\n const database = await this.ensureDatabaseOpen();\n const cursor = database.transaction(table).objectStore(table).openCursor();\n const result = [];\n cursor.onsuccess = (event) => {\n const cursorResult = event.target.result;\n if (cursorResult) {\n result.push(cursorResult.value);\n cursorResult.continue();\n }\n else {\n resolve(result);\n }\n };\n cursor.onerror = () => {\n reject(cursor.error);\n };\n });\n }\n /**\n * Asynchronously puts the specified value in the specified table.\n */\n async put(table, key) {\n await this.ensureDatabaseOpen();\n return await new Promise((resolve, reject) => {\n try {\n const request = this.database.transaction([table], 'readwrite').objectStore(table).put(key);\n request.onsuccess = () => {\n resolve(key);\n };\n request.onerror = e => {\n Log.error('Database PUT Transaction Error:', e);\n reject(e);\n };\n }\n catch (e) {\n Log.error('Database PUT Error:', e);\n reject(e);\n }\n });\n }\n /**\n * Asynchronously removes the specified key from the table, or if the key is not specified, removes all keys in the table.\n * @returns {Promise} Returns a promise containing a key that is fulfilled when deletion is completed.\n */\n async remove(table, key) {\n const database = await this.ensureDatabaseOpen();\n return new Promise((resolve, reject) => {\n try {\n const store = database.transaction([table], \"readwrite\").objectStore(table);\n // If key is present remove a single key from a table.\n // Otherwise wipe the table\n const request = key ? store.delete(key) : store.clear();\n request.onsuccess = () => {\n resolve(key);\n };\n request.onerror = e => {\n Log.error('Database REMOVE Transaction Error:', e);\n reject(e);\n };\n }\n catch (e) {\n Log.error('Database REMOVE Error:', e);\n reject(e);\n }\n });\n }\n}\n//# sourceMappingURL=IndexedDb.js.map","class AppState {\n}\nexport { AppState };\n//# sourceMappingURL=AppState.js.map","class ServiceWorkerState {\n}\nexport { ServiceWorkerState };\n//# sourceMappingURL=ServiceWorkerState.js.map","export class Subscription {\n serialize() {\n return {\n deviceId: this.deviceId,\n subscriptionToken: this.subscriptionToken,\n optedOut: this.optedOut,\n createdAt: this.createdAt,\n expirationTime: this.expirationTime,\n };\n }\n static deserialize(bundle) {\n const subscription = new Subscription();\n subscription.deviceId = bundle.deviceId;\n subscription.subscriptionToken = bundle.subscriptionToken;\n subscription.optedOut = bundle.optedOut;\n subscription.createdAt = bundle.createdAt;\n subscription.expirationTime = bundle.expirationTime;\n return subscription;\n }\n}\n//# sourceMappingURL=Subscription.js.map","import Emitter from \"../libraries/Emitter\";\nimport IndexedDb from \"./IndexedDb\";\nimport { AppState } from \"../models/AppState\";\nimport { ServiceWorkerState } from \"../models/ServiceWorkerState\";\nimport { Subscription } from \"../models/Subscription\";\nimport { TestEnvironmentKind } from \"../models/TestEnvironmentKind\";\nimport { WindowEnvironmentKind } from \"../models/WindowEnvironmentKind\";\nimport { EmailProfile } from \"../models/EmailProfile\";\nimport { ONESIGNAL_SESSION_KEY } from \"../models/Session\";\nimport SdkEnvironment from \"../managers/SdkEnvironment\";\nimport OneSignalUtils from \"../utils/OneSignalUtils\";\nimport Utils from \"../context/shared/utils/Utils\";\nimport Log from \"../libraries/Log\";\nimport { SMSProfile } from \"../models/SMSProfile\";\nvar DatabaseEventName;\n(function (DatabaseEventName) {\n DatabaseEventName[DatabaseEventName[\"SET\"] = 0] = \"SET\";\n})(DatabaseEventName || (DatabaseEventName = {}));\nexport default class Database {\n constructor(databaseName) {\n this.databaseName = databaseName;\n this.emitter = new Emitter();\n this.database = new IndexedDb(this.databaseName);\n }\n static resetInstance() {\n Database.databaseInstance = null;\n }\n static get singletonInstance() {\n if (!Database.databaseInstanceName) {\n Database.databaseInstanceName = \"ONE_SIGNAL_SDK_DB\";\n }\n if (!Database.databaseInstance) {\n Database.databaseInstance = new Database(Database.databaseInstanceName);\n }\n return Database.databaseInstance;\n }\n static applyDbResultFilter(table, key, result) {\n switch (table) {\n case \"Options\":\n if (result && key)\n return result.value;\n else if (result && !key)\n return result;\n else\n return null;\n case \"Ids\":\n if (result && key)\n return result.id;\n else if (result && !key)\n return result;\n else\n return null;\n case \"NotificationOpened\":\n if (result && key)\n return { data: result.data, timestamp: result.timestamp };\n else if (result && !key)\n return result;\n else\n return null;\n default:\n if (result)\n return result;\n else\n return null;\n }\n }\n shouldUsePostmam() {\n return SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker &&\n OneSignalUtils.isUsingSubscriptionWorkaround() &&\n SdkEnvironment.getTestEnv() === TestEnvironmentKind.None;\n }\n /**\n * Asynchronously retrieves the value of the key at the table (if key is specified), or the entire table\n * (if key is not specified).\n * If on an iFrame or popup environment, retrieves from the correct IndexedDB database using cross-domain messaging.\n * @param table The table to retrieve the value from.\n * @param key The key in the table to retrieve the value of. Leave blank to get the entire table.\n * @returns {Promise} Returns a promise that fulfills when the value(s) are available.\n */\n async get(table, key) {\n if (this.shouldUsePostmam()) {\n return await new Promise(async (resolve) => {\n OneSignal.proxyFrameHost.message(OneSignal.POSTMAM_COMMANDS.REMOTE_DATABASE_GET, [{\n table: table,\n key: key\n }], (reply) => {\n const result = reply.data[0];\n resolve(result);\n });\n });\n }\n else {\n const result = await this.database.get(table, key);\n const cleanResult = Database.applyDbResultFilter(table, key, result);\n return cleanResult;\n }\n }\n async getAll(table) {\n if (this.shouldUsePostmam()) {\n return await new Promise(async (resolve) => {\n OneSignal.proxyFrameHost.message(OneSignal.POSTMAM_COMMANDS.REMOTE_DATABASE_GET_ALL, {\n table: table\n }, (reply) => {\n const result = reply.data;\n resolve(result);\n });\n });\n }\n else {\n const result = await this.database.getAll(table);\n return result;\n }\n }\n /**\n * Asynchronously puts the specified value in the specified table.\n * @param table\n * @param keypath\n */\n async put(table, keypath) {\n await new Promise(async (resolve, reject) => {\n if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker &&\n OneSignalUtils.isUsingSubscriptionWorkaround() &&\n SdkEnvironment.getTestEnv() === TestEnvironmentKind.None) {\n OneSignal.proxyFrameHost.message(OneSignal.POSTMAM_COMMANDS.REMOTE_DATABASE_PUT, [{ table: table, keypath: keypath }], (reply) => {\n if (reply.data === OneSignal.POSTMAM_COMMANDS.REMOTE_OPERATION_COMPLETE) {\n resolve();\n }\n else {\n reject(`(Database) Attempted remote IndexedDB put(${table}, ${keypath}),` +\n `but did not get success response.`);\n }\n });\n }\n else {\n await this.database.put(table, keypath);\n resolve();\n }\n });\n this.emitter.emit(Database.EVENTS.SET, keypath);\n }\n /**\n * Asynchronously removes the specified key from the table, or if the key is not specified, removes all\n * keys in the table.\n * @returns {Promise} Returns a promise containing a key that is fulfilled when deletion is completed.\n */\n remove(table, keypath) {\n if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker &&\n OneSignalUtils.isUsingSubscriptionWorkaround() &&\n SdkEnvironment.getTestEnv() === TestEnvironmentKind.None) {\n return new Promise((resolve, reject) => {\n OneSignal.proxyFrameHost.message(OneSignal.POSTMAM_COMMANDS.REMOTE_DATABASE_REMOVE, [{ table: table, keypath: keypath }], (reply) => {\n if (reply.data === OneSignal.POSTMAM_COMMANDS.REMOTE_OPERATION_COMPLETE) {\n resolve();\n }\n else {\n reject(`(Database) Attempted remote IndexedDB remove(${table}, ${keypath}),` +\n `but did not get success response.`);\n }\n });\n });\n }\n else {\n return this.database.remove(table, keypath);\n }\n }\n async getAppConfig() {\n const config = {};\n const appIdStr = await this.get(\"Ids\", \"appId\");\n config.appId = appIdStr;\n config.subdomain = await this.get(\"Options\", \"subdomain\");\n config.vapidPublicKey = await this.get(\"Options\", \"vapidPublicKey\");\n return config;\n }\n async getExternalUserId() {\n return await this.get(\"Ids\", \"externalUserId\");\n }\n async getExternalUserIdAuthHash() {\n return await this.get(\"Ids\", \"externalUserIdAuthHash\");\n }\n async setExternalUserId(externalUserId, authHash) {\n const emptyString = \"\";\n const externalIdToSave = Utils.getValueOrDefault(externalUserId, emptyString);\n const authHashToSave = Utils.getValueOrDefault(authHash, emptyString);\n if (externalIdToSave === emptyString) {\n await this.remove(\"Ids\", \"externalUserId\");\n }\n else {\n await this.put(\"Ids\", { type: \"externalUserId\", id: externalIdToSave });\n }\n if (authHashToSave === emptyString) {\n await this.remove(\"Ids\", \"externalUserIdAuthHash\");\n }\n else {\n await this.put(\"Ids\", { type: \"externalUserIdAuthHash\", id: authHashToSave });\n }\n }\n async setAppConfig(appConfig) {\n if (appConfig.appId)\n await this.put(\"Ids\", { type: \"appId\", id: appConfig.appId });\n if (appConfig.subdomain)\n await this.put(\"Options\", { key: \"subdomain\", value: appConfig.subdomain });\n if (appConfig.httpUseOneSignalCom === true)\n await this.put(\"Options\", { key: \"httpUseOneSignalCom\", value: true });\n else if (appConfig.httpUseOneSignalCom === false)\n await this.put(\"Options\", { key: \"httpUseOneSignalCom\", value: false });\n if (appConfig.vapidPublicKey)\n await this.put(\"Options\", { key: \"vapidPublicKey\", value: appConfig.vapidPublicKey });\n }\n async getAppState() {\n const state = new AppState();\n state.defaultNotificationUrl = await this.get(\"Options\", \"defaultUrl\");\n state.defaultNotificationTitle = await this.get(\"Options\", \"defaultTitle\");\n state.lastKnownPushEnabled = await this.get(\"Options\", \"isPushEnabled\");\n state.clickedNotifications = await this.get(\"NotificationOpened\");\n return state;\n }\n async setAppState(appState) {\n if (appState.defaultNotificationUrl)\n await this.put(\"Options\", { key: \"defaultUrl\", value: appState.defaultNotificationUrl });\n if (appState.defaultNotificationTitle || appState.defaultNotificationTitle === \"\")\n await this.put(\"Options\", { key: \"defaultTitle\", value: appState.defaultNotificationTitle });\n if (appState.lastKnownPushEnabled != null)\n await this.put(\"Options\", { key: \"isPushEnabled\", value: appState.lastKnownPushEnabled });\n if (appState.clickedNotifications) {\n const clickedNotificationUrls = Object.keys(appState.clickedNotifications);\n for (const url of clickedNotificationUrls) {\n const notificationDetails = appState.clickedNotifications[url];\n if (notificationDetails) {\n await this.put(\"NotificationOpened\", {\n url: url,\n data: notificationDetails.data,\n timestamp: notificationDetails.timestamp\n });\n }\n else if (notificationDetails === null) {\n // If we get an object like:\n // { \"http://site.com/page\": null}\n // It means we need to remove that entry\n await this.remove(\"NotificationOpened\", url);\n }\n }\n }\n }\n async getServiceWorkerState() {\n const state = new ServiceWorkerState();\n state.workerVersion = await this.get(\"Ids\", \"WORKER1_ONE_SIGNAL_SW_VERSION\");\n return state;\n }\n async setServiceWorkerState(state) {\n if (state.workerVersion)\n await this.put(\"Ids\", { type: \"WORKER1_ONE_SIGNAL_SW_VERSION\", id: state.workerVersion });\n }\n async getSubscription() {\n const subscription = new Subscription();\n subscription.deviceId = await this.get(\"Ids\", \"userId\");\n subscription.subscriptionToken = await this.get(\"Ids\", \"registrationId\");\n // The preferred database key to store our subscription\n const dbOptedOut = await this.get(\"Options\", \"optedOut\");\n // For backwards compatibility, we need to read from this if the above is not found\n const dbNotOptedOut = await this.get(\"Options\", \"subscription\");\n const createdAt = await this.get(\"Options\", \"subscriptionCreatedAt\");\n const expirationTime = await this.get(\"Options\", \"subscriptionExpirationTime\");\n if (dbOptedOut != null) {\n subscription.optedOut = dbOptedOut;\n }\n else {\n if (dbNotOptedOut == null) {\n subscription.optedOut = false;\n }\n else {\n subscription.optedOut = !dbNotOptedOut;\n }\n }\n subscription.createdAt = createdAt;\n subscription.expirationTime = expirationTime;\n return subscription;\n }\n async setDeviceId(deviceId) {\n await this.put(\"Ids\", { type: \"userId\", id: deviceId });\n }\n async setSubscription(subscription) {\n if (subscription.deviceId) {\n await this.setDeviceId(subscription.deviceId);\n }\n if (typeof subscription.subscriptionToken !== \"undefined\") {\n // Allow null subscriptions to be set\n await this.put(\"Ids\", { type: \"registrationId\", id: subscription.subscriptionToken });\n }\n if (subscription.optedOut != null) { // Checks if null or undefined, allows false\n await this.put(\"Options\", { key: \"optedOut\", value: subscription.optedOut });\n }\n if (subscription.createdAt != null) {\n await this.put(\"Options\", { key: \"subscriptionCreatedAt\", value: subscription.createdAt });\n }\n if (subscription.expirationTime != null) {\n await this.put(\"Options\", { key: \"subscriptionExpirationTime\", value: subscription.expirationTime });\n }\n else {\n await this.remove(\"Options\", \"subscriptionExpirationTime\");\n }\n }\n async getEmailProfile() {\n const profileJson = await this.get(\"Ids\", \"emailProfile\");\n if (profileJson) {\n return EmailProfile.deserialize(profileJson);\n }\n else {\n return new EmailProfile();\n }\n }\n async setEmailProfile(emailProfile) {\n if (emailProfile) {\n await this.put(\"Ids\", { type: \"emailProfile\", id: emailProfile.serialize() });\n }\n }\n async getSMSProfile() {\n const profileJson = await this.get(\"Ids\", \"smsProfile\");\n if (profileJson) {\n return SMSProfile.deserialize(profileJson);\n }\n else {\n return new SMSProfile();\n }\n }\n async setSMSProfile(profile) {\n if (profile) {\n await this.put(\"Ids\", { type: \"smsProfile\", id: profile.serialize() });\n }\n }\n async setProvideUserConsent(consent) {\n await this.put(\"Options\", { key: \"userConsent\", value: consent });\n }\n async getProvideUserConsent() {\n return await this.get(\"Options\", \"userConsent\");\n }\n async getSession(sessionKey) {\n return await this.get(\"Sessions\", sessionKey);\n }\n async setSession(session) {\n await this.put(\"Sessions\", session);\n }\n async removeSession(sessionKey) {\n await this.remove(\"Sessions\", sessionKey);\n }\n async getLastNotificationClicked(appId) {\n let allClickedNotifications = [];\n try {\n allClickedNotifications = await this.getAll(\"NotificationClicked\");\n }\n catch (e) {\n Log.error(\"Database.getNotificationClickedByUrl\", e);\n }\n const predicate = (notification) => notification.appId === appId;\n return allClickedNotifications.find(predicate) || null;\n }\n async getNotificationClickedByUrl(url, appId) {\n let allClickedNotifications = [];\n try {\n allClickedNotifications = await this.getAll(\"NotificationClicked\");\n }\n catch (e) {\n Log.error(\"Database.getNotificationClickedByUrl\", e);\n }\n const predicate = (notification) => {\n if (notification.appId !== appId) {\n return false;\n }\n return new URL(url).origin === new URL(notification.url).origin;\n };\n return allClickedNotifications.find(predicate) || null;\n }\n async getNotificationClickedById(notificationId) {\n return await this.get(\"NotificationClicked\", notificationId);\n }\n async getNotificationReceivedById(notificationId) {\n return await this.get(\"NotificationReceived\", notificationId);\n }\n async removeNotificationClickedById(notificationId) {\n await this.remove(\"NotificationClicked\", notificationId);\n }\n async removeAllNotificationClicked() {\n await this.remove(\"NotificationClicked\");\n }\n async resetSentUniqueOutcomes() {\n const outcomes = await this.getAll(\"SentUniqueOutcome\");\n const promises = outcomes.map(o => {\n o.sentDuringSession = null;\n return Database.put(\"SentUniqueOutcome\", o);\n });\n await Promise.all(promises);\n }\n /**\n * Asynchronously removes the Ids, NotificationOpened, and Options tables from the database and recreates them\n * with blank values.\n * @returns {Promise} Returns a promise that is fulfilled when rebuilding is completed, or rejects with an error.\n */\n static async rebuild() {\n return Promise.all([\n Database.singletonInstance.remove(\"Ids\"),\n Database.singletonInstance.remove(\"NotificationOpened\"),\n Database.singletonInstance.remove(\"Options\"),\n Database.singletonInstance.remove(\"NotificationReceived\"),\n Database.singletonInstance.remove(\"NotificationClicked\"),\n Database.singletonInstance.remove(\"SentUniqueOutcome\")\n ]);\n }\n // START: Static mappings to instance methods\n static async on(...args) {\n return Database.singletonInstance.emitter.on.apply(Database.singletonInstance.emitter, args);\n }\n static async getCurrentSession() {\n return await Database.singletonInstance.getSession(ONESIGNAL_SESSION_KEY);\n }\n static async upsertSession(session) {\n await Database.singletonInstance.setSession(session);\n }\n static async cleanupCurrentSession() {\n await Database.singletonInstance.removeSession(ONESIGNAL_SESSION_KEY);\n }\n static async setEmailProfile(emailProfile) {\n return await Database.singletonInstance.setEmailProfile(emailProfile);\n }\n static async getEmailProfile() {\n return await Database.singletonInstance.getEmailProfile();\n }\n static async setSMSProfile(smsProfile) {\n return await Database.singletonInstance.setSMSProfile(smsProfile);\n }\n static async getSMSProfile() {\n return await Database.singletonInstance.getSMSProfile();\n }\n static async setSubscription(subscription) {\n return await Database.singletonInstance.setSubscription(subscription);\n }\n static async getSubscription() {\n return await Database.singletonInstance.getSubscription();\n }\n static async setProvideUserConsent(consent) {\n return await Database.singletonInstance.setProvideUserConsent(consent);\n }\n static async getProvideUserConsent() {\n return await Database.singletonInstance.getProvideUserConsent();\n }\n static async setServiceWorkerState(workerState) {\n return await Database.singletonInstance.setServiceWorkerState(workerState);\n }\n static async getServiceWorkerState() {\n return await Database.singletonInstance.getServiceWorkerState();\n }\n static async setAppState(appState) {\n return await Database.singletonInstance.setAppState(appState);\n }\n static async getAppState() {\n return await Database.singletonInstance.getAppState();\n }\n static async setAppConfig(appConfig) {\n return await Database.singletonInstance.setAppConfig(appConfig);\n }\n static async getAppConfig() {\n return await Database.singletonInstance.getAppConfig();\n }\n static async getExternalUserId() {\n return await Database.singletonInstance.getExternalUserId();\n }\n static async getExternalUserIdAuthHash() {\n return await Database.singletonInstance.getExternalUserIdAuthHash();\n }\n static async getLastNotificationClicked(appId) {\n return await Database.singletonInstance.getLastNotificationClicked(appId);\n }\n static async removeNotificationClickedById(notificationId) {\n return await Database.singletonInstance.removeNotificationClickedById(notificationId);\n }\n static async removeAllNotificationClicked() {\n return await Database.singletonInstance.removeAllNotificationClicked();\n }\n static async resetSentUniqueOutcomes() {\n return await Database.singletonInstance.resetSentUniqueOutcomes();\n }\n static async getNotificationClickedByUrl(url, appId) {\n return await Database.singletonInstance.getNotificationClickedByUrl(url, appId);\n }\n static async getNotificationClickedById(notificationId) {\n return await Database.singletonInstance.getNotificationClickedById(notificationId);\n }\n static async getNotificationReceivedById(notificationId) {\n return await Database.singletonInstance.getNotificationReceivedById(notificationId);\n }\n static async setExternalUserId(externalUserId, authHash) {\n await Database.singletonInstance.setExternalUserId(externalUserId, authHash);\n }\n static async setDeviceId(deviceId) {\n await Database.singletonInstance.setDeviceId(deviceId);\n }\n static async remove(table, keypath) {\n return await Database.singletonInstance.remove(table, keypath);\n }\n static async put(table, keypath) {\n return await Database.singletonInstance.put(table, keypath);\n }\n static async get(table, key) {\n return await Database.singletonInstance.get(table, key);\n }\n static async getAll(table) {\n return await Database.singletonInstance.getAll(table);\n }\n}\n/* End Temp Database Proxy */\nDatabase.EVENTS = DatabaseEventName;\n//# sourceMappingURL=Database.js.map","import OneSignalError from \"./OneSignalError\";\nexport default class TimeoutError extends OneSignalError {\n constructor(message = \"The asynchronous operation has timed out.\") {\n super(message);\n this.message = message;\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n//# sourceMappingURL=TimeoutError.js.map","import TimeoutError from '../../../errors/TimeoutError';\nimport { OneSignalApiErrorKind, OneSignalApiError } from \"../../../errors/OneSignalApiError\";\nexport class Utils {\n /**\n * Returns true if match is in string; otherwise, returns false.\n */\n static contains(indexOfAble, match) {\n if (!indexOfAble)\n return false;\n return indexOfAble.indexOf(match) !== -1;\n }\n static getConsoleStyle(style) {\n if (style == 'code') {\n return `padding: 0 1px 1px 5px;border: 1px solid #ddd;border-radius: 3px;font-family: Monaco,\"DejaVu Sans Mono\",\"Courier New\",monospace;color: #444;`;\n }\n else if (style == 'bold') {\n return `font-weight: 600;color: rgb(51, 51, 51);`;\n }\n else if (style == 'alert') {\n return `font-weight: 600;color: red;`;\n }\n else if (style == 'event') {\n return `color: green;`;\n }\n else if (style == 'postmessage') {\n return `color: orange;`;\n }\n else if (style == 'serviceworkermessage') {\n return `color: purple;`;\n }\n else {\n return '';\n }\n }\n /**\n * Returns the current object without keys that have undefined values.\n * Regardless of whether the return result is used, the passed-in object is destructively modified.\n * Only affects keys that the object directly contains (i.e. not those inherited via the object's prototype).\n * @param object\n */\n static trimUndefined(object) {\n for (const property in object) {\n if (object.hasOwnProperty(property)) {\n if (object[property] === undefined) {\n delete object[property];\n }\n }\n }\n return object;\n }\n /**\n * Capitalizes the first letter of the string.\n * @returns {string} The string with the first letter capitalized.\n */\n static capitalize(text) {\n return text.charAt(0).toUpperCase() + text.slice(1);\n }\n static isNullOrUndefined(value) {\n return typeof value === 'undefined' || value === null;\n }\n static valueOrDefault(value, defaultValue) {\n if (typeof value === \"undefined\" || value === null) {\n return defaultValue;\n }\n return value;\n }\n /**\n * JSON.stringify() but converts functions to \"[Function]\" so they aren't lost.\n * Helps when logging method calls.\n */\n static stringify(obj) {\n return JSON.stringify(obj, (_, value) => {\n if (typeof value === 'function') {\n return \"[Function]\";\n }\n else {\n return value;\n }\n }, 4);\n }\n /**\n * Used for generating query params\n * e.g: -> hash = { appId } // with appId = '1234'\n * -> returns \"appId=1234\"\n * @param {any} hash\n * @returns string\n */\n static encodeHashAsUriComponent(hash) {\n let uriComponent = '';\n const keys = Object.keys(hash);\n for (const key of keys) {\n const value = hash[key];\n uriComponent += `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n return uriComponent;\n }\n static timeoutPromise(promise, milliseconds) {\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError());\n }, milliseconds);\n });\n return Promise.race([promise, timeoutPromise]);\n }\n static getValueOrDefault(value, defaultValue) {\n if (value !== undefined && value !== null) {\n return value;\n }\n return defaultValue;\n }\n /**\n * This is similar to ECMAScript2107 String.prototype.padStart.\n * Switch to this after updating TypeScript and can confirm it gets transpiled down to ES6\n * @param str - String to pad left\n * @param targetLength - Length to make the string\n * @param padString - String value of length one to pad with.\n * @returns {string} - Resulting string padded\n */\n static padStart(str, targetLength, padString) {\n let result = str;\n while (result.length < targetLength) {\n result = padString + result;\n }\n return result;\n }\n /**\n * Returns trimmed version number\n * e.g: \"10.01.30\" becomes \"10.01\"\n * @param version - version number we want to check\n */\n static parseVersionString(version) {\n const osVersionParts = version.toString().split(\".\");\n const majorVersion = Utils.padStart(osVersionParts[0], 2, \"0\");\n let minorVersion;\n if (osVersionParts[1]) {\n minorVersion = Utils.padStart(osVersionParts[1], 2, \"0\");\n }\n else {\n minorVersion = \"00\";\n }\n return Number(`${majorVersion}.${minorVersion}`);\n }\n /**\n * Gives back the last x number of parts providing a string with a delimiter.\n * Example: lastParts(\"api.staging.onesignal.com\", \".\", 3) will return \"staging.onesignal.com\"\n */\n static lastParts(subject, delimiter, maxParts) {\n const parts = subject.split(delimiter);\n const skipParts = Math.max(parts.length - maxParts, 0);\n return parts.slice(skipParts).join(delimiter);\n }\n static enforceAppId(appId) {\n if (!appId) {\n throw new Error(\"App id cannot be empty\");\n }\n }\n static enforcePlayerId(playerId) {\n if (!playerId) {\n throw new Error(\"Player id cannot be empty\");\n }\n }\n static async enforceAppIdAndPlayerId(appId, playerId, funcToExecute) {\n Utils.enforceAppId(appId);\n Utils.enforcePlayerId(playerId);\n try {\n return await funcToExecute();\n }\n catch (e) {\n if (e && Array.isArray(e.errors) && e.errors.length > 0 &&\n Utils.contains(e.errors[0], \"app_id not found\")) {\n throw new OneSignalApiError(OneSignalApiErrorKind.MissingAppId);\n }\n else\n throw e;\n }\n }\n static sortArrayOfObjects(arrayToSort, predicateForProperty, descending = false, doItInPlace = true) {\n const internalArrayToSort = doItInPlace ? arrayToSort : arrayToSort.slice();\n internalArrayToSort.sort((a, b) => {\n const propertyA = predicateForProperty(a);\n const propertyB = predicateForProperty(b);\n if (propertyA > propertyB) {\n return !!descending ? -1 : 1;\n }\n if (propertyA < propertyB) {\n return !!descending ? 1 : -1;\n }\n return 0;\n });\n return internalArrayToSort;\n }\n}\nexport default Utils;\n//# sourceMappingURL=Utils.js.map","export default class Log {\n static debug(...args) {\n if (!!self.shouldLog) {\n console.debug(...args);\n }\n }\n static trace(...args) {\n if (!!self.shouldLog) {\n console.trace(...args);\n }\n }\n static info(...args) {\n if (!!self.shouldLog) {\n console.info(...args);\n }\n }\n static warn(...args) {\n if (!!self.shouldLog) {\n console.warn(...args);\n }\n }\n static error(...args) {\n if (!!self.shouldLog) {\n console.error(...args);\n }\n }\n}\n//# sourceMappingURL=Log.js.map","export var WindowEnvironmentKind;\n(function (WindowEnvironmentKind) {\n /**\n * A service worker environment.\n */\n WindowEnvironmentKind[\"ServiceWorker\"] = \"ServiceWorker\";\n /**\n * The top-level frame to the \"main\" client's site.\n */\n WindowEnvironmentKind[\"Host\"] = \"Host\";\n /**\n * Our subscription popup for alt-origin sites.\n */\n WindowEnvironmentKind[\"OneSignalSubscriptionPopup\"] = \"Popup\";\n /**\n * Our subscription modal for HTTPS sites, which loads in an iFrame.\n */\n WindowEnvironmentKind[\"OneSignalSubscriptionModal\"] = \"Modal\";\n /**\n * Our subscription helper iFrame.\n */\n WindowEnvironmentKind[\"OneSignalProxyFrame\"] = \"ProxyFrame\";\n /**\n * A custom iFrame on the site.\n */\n WindowEnvironmentKind[\"CustomIframe\"] = \"CustomFrame\";\n /**\n * An unknown window context type not matching any of the above.\n */\n WindowEnvironmentKind[\"Unknown\"] = \"Unknown\";\n})(WindowEnvironmentKind || (WindowEnvironmentKind = {}));\n//# sourceMappingURL=WindowEnvironmentKind.js.map","/**\n * Build Environment Kind\n */\nexport var EnvironmentKind;\n(function (EnvironmentKind) {\n EnvironmentKind[\"Development\"] = \"Development\";\n EnvironmentKind[\"Staging\"] = \"Staging\";\n EnvironmentKind[\"Production\"] = \"Production\";\n})(EnvironmentKind || (EnvironmentKind = {}));\n//# sourceMappingURL=EnvironmentKind.js.map","import { EnvironmentKind } from '../models/EnvironmentKind';\nimport { TestEnvironmentKind } from '../models/TestEnvironmentKind';\nimport { WindowEnvironmentKind } from '../models/WindowEnvironmentKind';\nimport { InvalidArgumentError, InvalidArgumentReason } from '../errors/InvalidArgumentError';\nimport { IntegrationKind } from \"../models/IntegrationKind\";\nimport Environment from \"../Environment\";\nimport OneSignalUtils from \"../utils/OneSignalUtils\";\nconst RESOURCE_HTTP_PORT = 4000;\nconst RESOURCE_HTTPS_PORT = 4001;\nconst API_URL_PORT = 3001;\nconst TURBINE_API_URL_PORT = 18080;\nconst TURBINE_ENDPOINTS = [\"outcomes\", \"on_focus\"];\nexport default class SdkEnvironment {\n /**\n * Returns development, staging, or production.\n *\n * The magic constants used to detect the environment is set or unset when\n * building the SDK.\n */\n static getBuildEnv() {\n if (typeof __BUILD_TYPE__ === \"undefined\") {\n return EnvironmentKind.Production;\n }\n switch (__BUILD_TYPE__) {\n case \"development\":\n return EnvironmentKind.Development;\n case \"staging\":\n return EnvironmentKind.Staging;\n case \"production\":\n return EnvironmentKind.Production;\n default:\n return EnvironmentKind.Production;\n }\n }\n /**\n * Returns development staging, or production.\n *\n * Refers to which API environment should be used. These constants are set when building the SDK\n */\n static getApiEnv() {\n if (typeof __API_TYPE__ === \"undefined\") {\n return EnvironmentKind.Production;\n }\n switch (__API_TYPE__) {\n case \"development\":\n return EnvironmentKind.Development;\n case \"staging\":\n return EnvironmentKind.Staging;\n case \"production\":\n return EnvironmentKind.Production;\n default:\n return EnvironmentKind.Production;\n }\n }\n /**\n * Determines whether the current frame context executing this function is part of a:\n *\n * a) HTTP site using a proxy subscription origin\n *\n * b) or, HTTPS site using a proxy subscription origin\n *\n * c) or, HTTPS site using its own origin for subscribing\n *\n * The determination affects permissions and subscription:\n *\n * a) Because the parent (top frame) of the proxy origin frame is HTTP, the entire context is\n * insecure. In the proxy origin frame, notification permissions are always \"denied\", access to\n * the service worker's registration throws a security error, and no service worker controls the\n * proxy origin frame.\n *\n * b) The context is secure. In the proxy origin frame, notification permissions are \"granted\" if\n * actually granted otherwise \"denied\" if either unprompted or blocked. The service worker\n * controls the proxy origin frame and access to the service worker's registration is allowed.\n * Requesting permissions from child frames is not allowed. Subscribing from child frames wasn't\n * allowed but is now allowed.\n *\n * c) All features are allowed.\n *\n * @param usingProxyOrigin Using a subdomain of os.tc or onesignal.com for subscribing to push.\n */\n static async getIntegration(usingProxyOrigin) {\n if (Environment.isSafari()) {\n /* HTTP doesn't apply to Safari sites */\n return IntegrationKind.Secure;\n }\n const isTopFrame = (window === window.top);\n const isHttpsProtocol = window.location.protocol === \"https:\";\n // For convenience, try to look up usingProxyOrigin instead of requiring it to be passed in\n if (usingProxyOrigin === undefined) {\n if (typeof OneSignal !== \"undefined\" && OneSignal.context && OneSignal.context.appConfig) {\n usingProxyOrigin = !!OneSignal.context.appConfig.subdomain;\n }\n else {\n throw new InvalidArgumentError(\"usingProxyOrigin\", InvalidArgumentReason.Empty);\n }\n }\n /*\n Executing from the top frame, we can easily determine whether we're HTTPS or HTTP.\n \n Executing from a child frame of any depth, we can check the current frame's protocol. If it's\n HTTP it's definitely insecure. If it's HTTPS, we attempt to call\n ServiceWorkerContainer.getRegistration and see if the call throws an error or succeeds. If the\n call throws an error, we can assume some parent frame in the chain above us is insecure.\n */\n if (isTopFrame) {\n if (isHttpsProtocol) {\n return usingProxyOrigin ?\n IntegrationKind.SecureProxy :\n IntegrationKind.Secure;\n }\n else {\n // If localhost and allowLocalhostAsSecureOrigin, it's still considered secure\n if (OneSignalUtils.isLocalhostAllowedAsSecureOrigin() &&\n (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) {\n return IntegrationKind.Secure;\n }\n /* The case of HTTP and not using a proxy origin isn't possible, because the SDK will throw\n an initialization error stating a proxy origin is required for HTTP sites. */\n return IntegrationKind.InsecureProxy;\n }\n }\n else {\n if (isHttpsProtocol) {\n /* Check whether any parent frames are insecure */\n const isFrameContextInsecure = await SdkEnvironment.isFrameContextInsecure();\n if (isFrameContextInsecure) {\n return IntegrationKind.InsecureProxy;\n }\n else {\n return usingProxyOrigin ?\n IntegrationKind.SecureProxy :\n IntegrationKind.Secure;\n }\n }\n else {\n /*\n Because this frame is insecure, the entire chain is insecure.\n \n The case of HTTP and not using a proxy origin isn't possible, because the SDK will throw an\n initialization error stating a proxy origin is required for HTTP sites. */\n return IntegrationKind.InsecureProxy;\n }\n }\n }\n /**\n * From a child frame, returns true if the current frame context is insecure.\n *\n * This is used to check if isPushNotificationsEnabled() should grab the service worker\n * registration. In an HTTPS iframe of an HTTP page, getting the service worker registration would\n * throw an error.\n *\n * This method can trigger console warnings due to using ServiceWorkerContainer.getRegistration in\n * an insecure frame.\n */\n static async isFrameContextInsecure() {\n // If we are the top frame, or service workers aren't available, don't run this check\n if (window === window.top ||\n !('serviceWorker' in navigator) ||\n typeof navigator.serviceWorker.getRegistration === 'undefined') {\n return false;\n }\n // Will be null if there was an issue retrieving a status\n const registrationResult = await OneSignal.context.serviceWorkerManager.getRegistration();\n return !registrationResult;\n }\n static isInsecureOrigin() {\n return window.location.protocol === \"http:\";\n }\n static getOrigin() {\n if (Environment.isBrowser()) {\n return window.location.origin;\n }\n else if (typeof self !== \"undefined\" && typeof ServiceWorkerGlobalScope !== \"undefined\") {\n return self.location.origin;\n }\n return \"Unknown\";\n }\n /**\n * Describes the current frame context.\n */\n static getWindowEnv() {\n if (typeof window === \"undefined\") {\n if (typeof self !== \"undefined\" && typeof ServiceWorkerGlobalScope !== \"undefined\") {\n return WindowEnvironmentKind.ServiceWorker;\n }\n else {\n return WindowEnvironmentKind.Unknown;\n }\n }\n else {\n // If the window is the root top-most level\n if (window === window.top) {\n if (location.href.indexOf(\"initOneSignal\") !== -1 ||\n (location.pathname === '/subscribe' &&\n location.search === '') &&\n (location.hostname.endsWith('.onesignal.com') ||\n location.hostname.endsWith('.os.tc') ||\n (location.hostname.indexOf('.localhost') !== -1 &&\n SdkEnvironment.getBuildEnv() === EnvironmentKind.Development))) {\n return WindowEnvironmentKind.OneSignalSubscriptionPopup;\n }\n else {\n return WindowEnvironmentKind.Host;\n }\n }\n else if (location.pathname === '/webPushIframe') {\n return WindowEnvironmentKind.OneSignalProxyFrame;\n }\n else if (location.pathname === '/webPushModal') {\n return WindowEnvironmentKind.OneSignalSubscriptionModal;\n }\n else {\n return WindowEnvironmentKind.CustomIframe;\n }\n }\n }\n /**\n * Describes whether the SDK is built in tests mode or not.\n *\n * This method is overriden when tests are run.\n */\n static getTestEnv() {\n return typeof __TEST__ === \"undefined\" ?\n TestEnvironmentKind.UnitTesting :\n TestEnvironmentKind.None;\n }\n /**\n * Returns build-specific prefixes used for operations like registering the\n * service worker.\n *\n * For example, in staging the registered service worker filename is\n * Staging-OneSignalSDKWorker.js.\n */\n static getBuildEnvPrefix(buildEnv = SdkEnvironment.getBuildEnv()) {\n switch (buildEnv) {\n case EnvironmentKind.Development:\n return 'Dev-';\n case EnvironmentKind.Staging:\n return 'Staging-';\n case EnvironmentKind.Production:\n return '';\n default:\n throw new InvalidArgumentError('buildEnv', InvalidArgumentReason.EnumOutOfRange);\n }\n }\n /**\n * Returns the URL object representing the components of OneSignal's API\n * endpoint.\n */\n static getOneSignalApiUrl(buildEnv = SdkEnvironment.getApiEnv(), action) {\n const apiOrigin = (typeof __API_ORIGIN__ !== \"undefined\") ? __API_ORIGIN__ || \"localhost\" : \"localhost\";\n switch (buildEnv) {\n case EnvironmentKind.Development:\n if (SdkEnvironment.isTurbineEndpoint(action)) {\n return new URL(`https://${apiOrigin}:${TURBINE_API_URL_PORT}/api/v1`);\n }\n return new URL(`https://${apiOrigin}:${API_URL_PORT}/api/v1`);\n case EnvironmentKind.Staging:\n return new URL(`https://${apiOrigin}/api/v1`);\n case EnvironmentKind.Production:\n return new URL('https://onesignal.com/api/v1');\n default:\n throw new InvalidArgumentError('buildEnv', InvalidArgumentReason.EnumOutOfRange);\n }\n }\n static getOneSignalResourceUrlPath(buildEnv = SdkEnvironment.getBuildEnv()) {\n const buildOrigin = (typeof __BUILD_ORIGIN__ !== \"undefined\") ? __BUILD_ORIGIN__ || \"localhost\" : \"localhost\";\n const isHttps = (typeof __IS_HTTPS__ !== \"undefined\") ? __IS_HTTPS__ : true;\n let origin;\n const protocol = isHttps ? \"https\" : \"http\";\n const port = isHttps ? RESOURCE_HTTPS_PORT : RESOURCE_HTTP_PORT;\n switch (buildEnv) {\n case EnvironmentKind.Development:\n origin = `${protocol}://${buildOrigin}:${port}`;\n break;\n case EnvironmentKind.Staging:\n origin = `https://${buildOrigin}`;\n break;\n case EnvironmentKind.Production:\n origin = \"https://onesignal.com\";\n break;\n default:\n throw new InvalidArgumentError('buildEnv', InvalidArgumentReason.EnumOutOfRange);\n }\n return new URL(`${origin}/sdks`);\n }\n static getOneSignalCssFileName(buildEnv = SdkEnvironment.getBuildEnv()) {\n const baseFileName = \"OneSignalSDKStyles.css\";\n switch (buildEnv) {\n case EnvironmentKind.Development:\n return `Dev-${baseFileName}`;\n case EnvironmentKind.Staging:\n return `Staging-${baseFileName}`;\n case EnvironmentKind.Production:\n return baseFileName;\n default:\n throw new InvalidArgumentError('buildEnv', InvalidArgumentReason.EnumOutOfRange);\n }\n }\n static isTurbineEndpoint(action) {\n if (!action) {\n return false;\n }\n return TURBINE_ENDPOINTS.some(turbine_endpoint => action.indexOf(turbine_endpoint) > -1);\n }\n}\n//# sourceMappingURL=SdkEnvironment.js.map","import { InvalidArgumentError, InvalidArgumentReason } from '../errors/InvalidArgumentError';\nimport SdkEnvironment from '../managers/SdkEnvironment';\nimport { WindowEnvironmentKind } from '../models/WindowEnvironmentKind';\nimport Environment from '../Environment';\nimport Log from './Log';\nimport ServiceWorkerUtilHelper from '../helpers/page/ServiceWorkerUtilHelper';\n/**\n * NOTE: This file contains a mix of code that runs in ServiceWorker and Page contexts\n*/\nexport var WorkerMessengerCommand;\n(function (WorkerMessengerCommand) {\n WorkerMessengerCommand[\"WorkerVersion\"] = \"GetWorkerVersion\";\n WorkerMessengerCommand[\"Subscribe\"] = \"Subscribe\";\n WorkerMessengerCommand[\"SubscribeNew\"] = \"SubscribeNew\";\n WorkerMessengerCommand[\"AmpSubscriptionState\"] = \"amp-web-push-subscription-state\";\n WorkerMessengerCommand[\"AmpSubscribe\"] = \"amp-web-push-subscribe\";\n WorkerMessengerCommand[\"AmpUnsubscribe\"] = \"amp-web-push-unsubscribe\";\n WorkerMessengerCommand[\"NotificationDisplayed\"] = \"notification.displayed\";\n WorkerMessengerCommand[\"NotificationClicked\"] = \"notification.clicked\";\n WorkerMessengerCommand[\"NotificationDismissed\"] = \"notification.dismissed\";\n WorkerMessengerCommand[\"RedirectPage\"] = \"command.redirect\";\n WorkerMessengerCommand[\"SessionUpsert\"] = \"os.session.upsert\";\n WorkerMessengerCommand[\"SessionDeactivate\"] = \"os.session.deactivate\";\n WorkerMessengerCommand[\"AreYouVisible\"] = \"os.page_focused_request\";\n WorkerMessengerCommand[\"AreYouVisibleResponse\"] = \"os.page_focused_response\";\n WorkerMessengerCommand[\"SetLogging\"] = \"os.set_sw_logging\";\n})(WorkerMessengerCommand || (WorkerMessengerCommand = {}));\nexport class WorkerMessengerReplyBuffer {\n constructor() {\n this.replies = {};\n }\n addListener(command, callback, onceListenerOnly) {\n const record = { callback, onceListenerOnly };\n const replies = this.replies[command.toString()];\n if (replies)\n replies.push(record);\n else\n this.replies[command.toString()] = [record];\n }\n findListenersForMessage(command) {\n return this.replies[command.toString()] || [];\n }\n deleteListenerRecords(command) {\n this.replies[command.toString()] = null;\n }\n deleteAllListenerRecords() {\n this.replies = {};\n }\n deleteListenerRecord(command, targetRecord) {\n const listenersForCommand = this.replies[command.toString()];\n if (listenersForCommand == null)\n return;\n for (let listenerRecordIndex = listenersForCommand.length - 1; listenerRecordIndex >= 0; listenerRecordIndex--) {\n const listenerRecord = listenersForCommand[listenerRecordIndex];\n if (listenerRecord === targetRecord) {\n listenersForCommand.splice(listenerRecordIndex, 1);\n }\n }\n }\n}\n/**\n* A Promise-based PostMessage helper to ease back-and-forth replies between\n* service workers and window frames.\n*/\nexport class WorkerMessenger {\n constructor(context, replies = new WorkerMessengerReplyBuffer()) {\n this.context = context;\n this.replies = replies;\n }\n /**\n * Broadcasts a message from a service worker to all clients, including uncontrolled clients.\n */\n async broadcast(command, payload) {\n if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker)\n return;\n const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });\n for (const client of clients) {\n Log.debug(`[Worker Messenger] [SW -> Page] Broadcasting '${command.toString()}' to window client ${client.url}.`);\n client.postMessage({\n command: command,\n payload: payload\n });\n }\n }\n /*\n If running on a page context:\n Sends a postMessage() to OneSignal's Serviceworker\n If running in a ServiceWorker context:\n Sends a postMessage() to the supplied windowClient\n */\n async unicast(command, payload, windowClient) {\n const env = SdkEnvironment.getWindowEnv();\n if (env === WindowEnvironmentKind.ServiceWorker) {\n if (!windowClient) {\n throw new InvalidArgumentError('windowClient', InvalidArgumentReason.Empty);\n }\n else {\n Log.debug(`[Worker Messenger] [SW -> Page] Unicasting '${command.toString()}' to window client ${windowClient.url}.`);\n windowClient.postMessage({\n command: command,\n payload: payload\n });\n }\n }\n else {\n Log.debug(`[Worker Messenger] [Page -> SW] Unicasting '${command.toString()}' to service worker.`);\n this.directPostMessageToSW(command, payload);\n }\n }\n async directPostMessageToSW(command, payload) {\n Log.debug(`[Worker Messenger] [Page -> SW] Direct command '${command.toString()}' to service worker.`);\n const workerRegistration = await this.context.serviceWorkerManager.getRegistration();\n if (!workerRegistration) {\n Log.error(\"`[Worker Messenger] [Page -> SW] Could not get ServiceWorkerRegistration to postMessage!\");\n return;\n }\n const availableWorker = ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration);\n if (!availableWorker) {\n Log.error(\"`[Worker Messenger] [Page -> SW] Could not get ServiceWorker to postMessage!\");\n return;\n }\n // The postMessage payload will still arrive at the SW even if it isn't active yet.\n availableWorker.postMessage({\n command: command,\n payload: payload\n });\n }\n /**\n * Due to https://github.com/w3c/ServiceWorker/issues/1156, listen() must\n * synchronously add self.addEventListener('message') if we are running in the\n * service worker.\n */\n async listen() {\n if (!Environment.supportsServiceWorkers())\n return;\n const env = SdkEnvironment.getWindowEnv();\n if (env === WindowEnvironmentKind.ServiceWorker) {\n self.addEventListener('message', this.onWorkerMessageReceivedFromPage.bind(this));\n Log.debug('[Worker Messenger] Service worker is now listening for messages.');\n }\n else\n await this.listenForPage();\n }\n /**\n * Listens for messages for the service worker.\n */\n async listenForPage() {\n navigator.serviceWorker.addEventListener('message', this.onPageMessageReceivedFromServiceWorker.bind(this));\n Log.debug(`(${location.origin}) [Worker Messenger] Page is now listening for messages.`);\n }\n onWorkerMessageReceivedFromPage(event) {\n const data = event.data;\n /* If this message doesn't contain our expected fields, discard the message */\n /* The payload may be null. AMP web push sends commands to our service worker in the format:\n \n { command: \"amp-web-push-subscription-state\", payload: null }\n { command: \"amp-web-push-unsubscribe\", payload: null }\n { command: \"amp-web-push-subscribe\", payload: null }\n \n */\n if (!data || !data.command) {\n return;\n }\n const listenerRecords = this.replies.findListenersForMessage(data.command);\n const listenersToRemove = [];\n const listenersToCall = [];\n Log.debug(`[Worker Messenger] Service worker received message:`, event.data);\n for (const listenerRecord of listenerRecords) {\n if (listenerRecord.onceListenerOnly) {\n listenersToRemove.push(listenerRecord);\n }\n listenersToCall.push(listenerRecord);\n }\n for (let i = listenersToRemove.length - 1; i >= 0; i--) {\n const listenerRecord = listenersToRemove[i];\n this.replies.deleteListenerRecord(data.command, listenerRecord);\n }\n for (const listenerRecord of listenersToCall) {\n listenerRecord.callback.apply(null, [data.payload]);\n }\n }\n /*\n Occurs when the page receives a message from the service worker.\n \n A map of callbacks is checked to see if anyone is listening to the specific\n message topic. If no one is listening to the message, it is discarded;\n otherwise, the listener callback is executed.\n */\n onPageMessageReceivedFromServiceWorker(event) {\n const data = event.data;\n /* If this message doesn't contain our expected fields, discard the message */\n if (!data || !data.command) {\n return;\n }\n const listenerRecords = this.replies.findListenersForMessage(data.command);\n const listenersToRemove = [];\n const listenersToCall = [];\n Log.debug(`[Worker Messenger] Page received message:`, event.data);\n for (const listenerRecord of listenerRecords) {\n if (listenerRecord.onceListenerOnly) {\n listenersToRemove.push(listenerRecord);\n }\n listenersToCall.push(listenerRecord);\n }\n for (let i = listenersToRemove.length - 1; i >= 0; i--) {\n const listenerRecord = listenersToRemove[i];\n this.replies.deleteListenerRecord(data.command, listenerRecord);\n }\n for (const listenerRecord of listenersToCall) {\n listenerRecord.callback.apply(null, [data.payload]);\n }\n }\n /*\n Subscribes a callback to be notified every time a service worker sends a\n message to the window frame with the specific command.\n */\n on(command, callback) {\n this.replies.addListener(command, callback, false);\n }\n /*\n Subscribes a callback to be notified the next time a service worker sends a\n message to the window frame with the specific command.\n \n The callback is executed once at most.\n */\n once(command, callback) {\n this.replies.addListener(command, callback, true);\n }\n /**\n Unsubscribe a callback from being notified about service worker messages\n with the specified command.\n */\n off(command) {\n if (command) {\n this.replies.deleteListenerRecords(command);\n }\n else {\n this.replies.deleteAllListenerRecords();\n }\n }\n}\n//# sourceMappingURL=WorkerMessenger.js.map","import bowser from \"bowser\";\nimport SdkEnvironment from \"../managers/SdkEnvironment\";\nimport Environment from \"../Environment\";\nimport { WindowEnvironmentKind } from \"../models/WindowEnvironmentKind\";\nimport Log from \"../libraries/Log\";\nimport { Utils } from \"../context/shared/utils/Utils\";\nexport class OneSignalUtils {\n static getBaseUrl() {\n return location.origin;\n }\n static isLocalhostAllowedAsSecureOrigin() {\n return (OneSignal.config &&\n OneSignal.config.userConfig &&\n OneSignal.config.userConfig.allowLocalhostAsSecureOrigin === true);\n }\n /**\n * Returns true if web push subscription occurs on a subdomain of OneSignal.\n * If true, our main IndexedDB is stored on the subdomain of onesignal.com, and not the user\"s site.\n * @remarks\n * This method returns true if:\n * - The browser is not Safari\n * - Safari uses a different method of subscription and does not require our workaround\n * - The init parameters contain a subdomain (even if the protocol is HTTPS)\n * - HTTPS users using our subdomain workaround still have the main IndexedDB stored on our subdomain\n * - The protocol of the current webpage is http:\n * Exceptions are:\n * - Safe hostnames like localhost and 127.0.0.1\n * - Because we don\"t want users to get the wrong idea when testing on localhost that direct permission is supported on HTTP, we\"ll ignore these exceptions. HTTPS will always be required for direct permission\n * - We are already in popup or iFrame mode, or this is called from the service worker\n */\n static isUsingSubscriptionWorkaround() {\n const windowEnv = SdkEnvironment.getWindowEnv();\n if (!OneSignal.config) {\n throw new Error(`(${windowEnv.toString()}) isUsingSubscriptionWorkaround() cannot be called until OneSignal.config exists.`);\n }\n if (bowser.safari) {\n return false;\n }\n const allowLocalhostAsSecureOrigin = this.isLocalhostAllowedAsSecureOrigin();\n return OneSignalUtils.internalIsUsingSubscriptionWorkaround(OneSignal.config.subdomain, allowLocalhostAsSecureOrigin);\n }\n static internalIsUsingSubscriptionWorkaround(subdomain, allowLocalhostAsSecureOrigin) {\n if (bowser.safari) {\n return false;\n }\n if (allowLocalhostAsSecureOrigin === true &&\n (location.hostname === \"localhost\" || location.hostname === \"127.0.0.1\")) {\n return false;\n }\n const windowEnv = SdkEnvironment.getWindowEnv();\n return ((windowEnv === WindowEnvironmentKind.Host || windowEnv === WindowEnvironmentKind.CustomIframe) &&\n (!!subdomain || location.protocol === \"http:\"));\n }\n static redetectBrowserUserAgent() {\n // During testing, the browser object may be initialized before the userAgent is injected\n if (bowser.name === \"\" && bowser.version === \"\") {\n return bowser._detect(navigator.userAgent);\n }\n return bowser;\n }\n /**\n * Returns true if the UUID is a string of 36 characters;\n * @param uuid\n * @returns {*|boolean}\n */\n static isValidUuid(uuid) {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(uuid);\n }\n static getRandomUuid() {\n let uuidStr = '';\n const crypto = typeof window === 'undefined' ? global.crypto : window.crypto || window.msCrypto;\n if (crypto) {\n uuidStr = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = (crypto.getRandomValues(new Uint8Array(1))[0] % 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n }\n else {\n uuidStr = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n }\n return uuidStr;\n }\n static logMethodCall(methodName, ...args) {\n return Log.debug(`Called %c${methodName}(${args.map(Utils.stringify).join(', ')})`, Utils.getConsoleStyle('code'), '.');\n }\n static isHttps() {\n if (OneSignalUtils.isSafari()) {\n return window.location.protocol === \"https:\";\n }\n return !OneSignalUtils.isUsingSubscriptionWorkaround();\n }\n static isSafari() {\n return Environment.isBrowser() && typeof window.safari !== \"undefined\";\n }\n}\nexport default OneSignalUtils;\n//# sourceMappingURL=OneSignalUtils.js.map","import SdkEnvironment from './managers/SdkEnvironment';\nimport { WindowEnvironmentKind } from './models/WindowEnvironmentKind';\nimport bowser from 'bowser';\nexport default class Environment {\n /**\n * True if not in a service worker environment.\n */\n static isBrowser() {\n return typeof window !== 'undefined';\n }\n static isSafari() {\n return Environment.isBrowser() && bowser.safari;\n }\n static version() {\n return (typeof __VERSION__ === \"undefined\" ? 1 : Number(__VERSION__));\n }\n static get TRADITIONAL_CHINESE_LANGUAGE_TAG() {\n return ['tw', 'hant'];\n }\n static get SIMPLIFIED_CHINESE_LANGUAGE_TAG() {\n return ['cn', 'hans'];\n }\n /* Specifications: https://tools.ietf.org/html/bcp47 */\n static getLanguage() {\n let languageTag = navigator.language;\n if (languageTag) {\n languageTag = languageTag.toLowerCase();\n const languageSubtags = languageTag.split('-');\n if (languageSubtags[0] == 'zh') {\n // The language is zh-?\n // We must categorize the language as either zh-Hans (simplified) or zh-Hant (traditional); OneSignal only supports these two Chinese variants\n for (const traditionalSubtag of Environment.TRADITIONAL_CHINESE_LANGUAGE_TAG) {\n if (languageSubtags.indexOf(traditionalSubtag) !== -1) {\n return 'zh-Hant';\n }\n }\n for (const simpleSubtag of Environment.SIMPLIFIED_CHINESE_LANGUAGE_TAG) {\n if (languageSubtags.indexOf(simpleSubtag) !== -1) {\n return 'zh-Hans';\n }\n }\n return 'zh-Hant'; // Return Chinese traditional by default\n }\n else {\n // Return the language subtag (it can be three characters, so truncate it down to 2 just to be sure)\n return languageSubtags[0].substring(0, 2);\n }\n }\n else {\n return 'en';\n }\n }\n static supportsServiceWorkers() {\n const env = SdkEnvironment.getWindowEnv();\n switch (env) {\n case WindowEnvironmentKind.ServiceWorker:\n return true;\n default:\n return typeof navigator !== \"undefined\" &&\n 'serviceWorker' in navigator;\n }\n }\n /*\n Returns the MD5 hash of all stylesheets within the src/stylesheets\n directory.\n */\n static getSdkStylesVersionHash() {\n return (typeof __SRC_STYLESHEETS_MD5_HASH__ === \"undefined\" ? '2' : __SRC_STYLESHEETS_MD5_HASH__);\n }\n}\n//# sourceMappingURL=Environment.js.map","import SdkEnvironment from './managers/SdkEnvironment';\nimport { WindowEnvironmentKind } from './models/WindowEnvironmentKind';\nimport Database from './services/Database';\nimport Log from './libraries/Log';\nimport { OneSignalUtils } from './utils/OneSignalUtils';\nimport { PermissionUtils } from './utils/PermissionUtils';\nimport { BrowserUtils } from './utils/BrowserUtils';\nimport { Utils } from \"./context/shared/utils/Utils\";\nimport bowser from 'bowser';\nexport function isArray(variable) {\n return Object.prototype.toString.call(variable) === '[object Array]';\n}\nexport function decodeHtmlEntities(text) {\n return BrowserUtils.decodeHtmlEntities(text);\n}\nexport function removeDomElement(selector) {\n var els = document.querySelectorAll(selector);\n if (els.length > 0) {\n for (let i = 0; i < els.length; i++) {\n const parentNode = els[i].parentNode;\n if (parentNode) {\n parentNode.removeChild(els[i]);\n }\n }\n }\n}\n/**\n * Helper method for public APIs that waits until OneSignal is initialized, rejects if push notifications are\n * not supported, and wraps these tasks in a Promise.\n */\nexport async function awaitOneSignalInitAndSupported() {\n return new Promise(resolve => {\n if (!OneSignal.initialized)\n OneSignal.emitter.once(OneSignal.EVENTS.SDK_INITIALIZED, resolve);\n else\n resolve();\n });\n}\n/**\n * Returns true if web push subscription occurs on a subdomain of OneSignal.\n * If true, our main IndexedDB is stored on the subdomain of onesignal.com, and not the user's site.\n * @remarks\n * This method returns true if:\n * - The browser is not Safari\n * - Safari uses a different method of subscription and does not require our workaround\n * - The init parameters contain a subdomain (even if the protocol is HTTPS)\n * - HTTPS users using our subdomain workaround still have the main IndexedDB stored on our subdomain\n * - The protocol of the current webpage is http:\n * Exceptions are:\n * - Safe hostnames like localhost and 127.0.0.1\n * - Because we don't want users to get the wrong idea when testing on localhost that direct permission is supported on HTTP, we'll ignore these exceptions. HTTPS will always be required for direct permission\n * - We are already in popup or iFrame mode, or this is called from the service worker\n */\nexport function isUsingSubscriptionWorkaround() {\n return OneSignalUtils.isUsingSubscriptionWorkaround();\n}\nexport async function triggerNotificationPermissionChanged(updateIfIdentical = false) {\n return PermissionUtils.triggerNotificationPermissionChanged(updateIfIdentical);\n}\n/**\n * JSON.stringify() but converts functions to \"[Function]\" so they aren't lost.\n * Helps when logging method calls.\n */\nexport function stringify(obj) {\n return Utils.stringify(obj);\n}\nexport function executeCallback(callback, ...args) {\n if (callback) {\n return callback.apply(null, args);\n }\n}\nexport function logMethodCall(methodName, ...args) {\n return OneSignalUtils.logMethodCall(methodName, ...args);\n}\nexport function isValidEmail(email) {\n return !!email &&\n !!email.match(/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])/);\n}\nexport function addDomElement(targetSelectorOrElement, addOrder, elementHtml) {\n let targetElement;\n if (typeof targetSelectorOrElement === 'string') {\n targetElement = document.querySelector(targetSelectorOrElement);\n }\n else {\n targetElement = targetSelectorOrElement;\n }\n if (targetElement) {\n targetElement.insertAdjacentHTML(addOrder, elementHtml);\n return;\n }\n throw new Error(`${targetSelectorOrElement} must be a CSS selector string or DOM Element object.`);\n}\nexport function clearDomElementChildren(targetSelectorOrElement) {\n if (typeof targetSelectorOrElement === 'string') {\n const element = document.querySelector(targetSelectorOrElement);\n if (element === null) {\n throw new Error(`Cannot find element with selector \"${targetSelectorOrElement}\"`);\n }\n while (element.firstChild) {\n element.removeChild(element.firstChild);\n }\n }\n else if (typeof targetSelectorOrElement === 'object') {\n while (targetSelectorOrElement.firstChild) {\n targetSelectorOrElement.removeChild(targetSelectorOrElement.firstChild);\n }\n }\n else\n throw new Error(`${targetSelectorOrElement} must be a CSS selector string or DOM Element object.`);\n}\nexport function addCssClass(targetSelectorOrElement, cssClass) {\n if (typeof targetSelectorOrElement === 'string') {\n const element = document.querySelector(targetSelectorOrElement);\n if (element === null) {\n throw new Error(`Cannot find element with selector \"${targetSelectorOrElement}\"`);\n }\n element.classList.add(cssClass);\n }\n else if (typeof targetSelectorOrElement === 'object') {\n targetSelectorOrElement.classList.add(cssClass);\n }\n else {\n throw new Error(`${targetSelectorOrElement} must be a CSS selector string or DOM Element object.`);\n }\n}\nexport function removeCssClass(targetSelectorOrElement, cssClass) {\n if (typeof targetSelectorOrElement === 'string') {\n const element = document.querySelector(targetSelectorOrElement);\n if (element === null) {\n throw new Error(`Cannot find element with selector \"${targetSelectorOrElement}\"`);\n }\n element.classList.remove(cssClass);\n }\n else if (typeof targetSelectorOrElement === 'object') {\n targetSelectorOrElement.classList.remove(cssClass);\n }\n else {\n throw new Error(`${targetSelectorOrElement} must be a CSS selector string or DOM Element object.`);\n }\n}\nexport function hasCssClass(targetSelectorOrElement, cssClass) {\n if (typeof targetSelectorOrElement === 'string') {\n const element = document.querySelector(targetSelectorOrElement);\n if (element === null) {\n throw new Error(`Cannot find element with selector \"${targetSelectorOrElement}\"`);\n }\n return element.classList.contains(cssClass);\n }\n else if (typeof targetSelectorOrElement === 'object') {\n return targetSelectorOrElement.classList.contains(cssClass);\n }\n else {\n throw new Error(`${targetSelectorOrElement} must be a CSS selector string or DOM Element object.`);\n }\n}\n/**\n * var DEVICE_TYPES = {\n * CHROME: 5,\n * SAFARI: 7,\n * FIREFOX: 8,\n * EDGE: 12,\n * UNKNOWN: -99\n * };\n */\nexport function getConsoleStyle(style) {\n return Utils.getConsoleStyle(style);\n}\n/**\n * Returns a promise for the setTimeout() method.\n * @param durationMs\n * @returns {Promise} Returns a promise that resolves when the timeout is complete.\n */\nexport function delay(durationMs) {\n return new Promise(resolve => {\n setTimeout(resolve, durationMs);\n });\n}\nexport function nothing() {\n return Promise.resolve();\n}\nexport function timeoutPromise(promise, milliseconds) {\n return Utils.timeoutPromise(promise, milliseconds);\n}\nexport function when(condition, promiseIfTrue, promiseIfFalse) {\n if (promiseIfTrue === undefined)\n promiseIfTrue = nothing();\n if (promiseIfFalse === undefined)\n promiseIfFalse = nothing();\n return (condition ? promiseIfTrue : promiseIfFalse);\n}\n/**\n * Returns true if match is in string; otherwise, returns false.\n */\nexport function contains(indexOfAble, match) {\n return Utils.contains(indexOfAble, match);\n}\n/**\n * Returns the current object without keys that have undefined values.\n * Regardless of whether the return result is used, the passed-in object is destructively modified.\n * Only affects keys that the object directly contains (i.e. not those inherited via the object's prototype).\n * @param object\n */\nexport function trimUndefined(object) {\n return Utils.trimUndefined(object);\n}\nexport function getRandomUuid() {\n return OneSignalUtils.getRandomUuid();\n}\n/**\n * Returns true if the UUID is a string of 36 characters;\n * @param uuid\n * @returns {*|boolean}\n */\nexport function isValidUuid(uuid) {\n return OneSignalUtils.isValidUuid(uuid);\n}\nexport function getUrlQueryParam(name) {\n let url = window.location.href;\n url = url.toLowerCase(); // This is just to avoid case sensitiveness\n name = name.replace(/[\\[\\]]/g, \"\\\\$&\").toLowerCase(); // This is just to avoid case sensitiveness for query parameter name\n var regex = new RegExp(\"[?&]\" + name + \"(=([^&#]*)|&|#|$)\"), results = regex.exec(url);\n if (!results)\n return null;\n if (!results[2])\n return '';\n return decodeURIComponent(results[2].replace(/\\+/g, \" \"));\n}\n/**\n * Wipe OneSignal-related IndexedDB data on the \"correct\" computed origin, but OneSignal must be initialized first to use.\n */\nexport function wipeIndexedDb() {\n Log.warn('OneSignal: Wiping IndexedDB data.');\n return Promise.all([\n Database.remove('Ids'),\n Database.remove('NotificationOpened'),\n Database.remove('Options')\n ]);\n}\n/**\n * Capitalizes the first letter of the string.\n * @returns {string} The string with the first letter capitalized.\n */\nexport function capitalize(text) {\n return Utils.capitalize(text);\n}\n/**\n * Unsubscribe from push notifications without removing the active service worker.\n */\nexport function unsubscribeFromPush() {\n Log.warn('OneSignal: Unsubscribing from push.');\n if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker) {\n return self.registration.pushManager.getSubscription()\n .then((subscription) => {\n if (subscription) {\n return subscription.unsubscribe();\n }\n else\n throw new Error('Cannot unsubscribe because not subscribed.');\n });\n }\n else {\n if (isUsingSubscriptionWorkaround()) {\n return new Promise((resolve, reject) => {\n Log.debug(\"Unsubscribe from push got called, and we're going to remotely execute it in HTTPS iFrame.\");\n OneSignal.proxyFrameHost.message(OneSignal.POSTMAM_COMMANDS.UNSUBSCRIBE_FROM_PUSH, null, (reply) => {\n Log.debug(\"Unsubscribe from push succesfully remotely executed.\");\n if (reply.data === OneSignal.POSTMAM_COMMANDS.REMOTE_OPERATION_COMPLETE) {\n resolve();\n }\n else {\n reject('Failed to remotely unsubscribe from push.');\n }\n });\n });\n }\n else {\n return OneSignal.context.serviceWorkerManager.getRegistration()\n .then((serviceWorker) => {\n if (!serviceWorker) {\n return Promise.resolve();\n }\n return serviceWorker;\n })\n .then(registration => registration.pushManager)\n .then(pushManager => pushManager.getSubscription())\n .then((subscription) => {\n if (subscription) {\n return subscription.unsubscribe();\n }\n else {\n return Promise.resolve();\n }\n });\n }\n }\n}\nexport function wait(milliseconds) {\n return new Promise(resolve => setTimeout(resolve, milliseconds));\n}\n/**\n * Returns the part of the string after the first occurence of the specified search.\n * @param string The entire string.\n * @param search The text returned will be everything *after* search.\n * e.g. substringAfter('A white fox', 'white') => ' fox'\n */\nexport function substringAfter(string, search) {\n return string.substr(string.indexOf(search) + search.length);\n}\nexport function once(targetSelectorOrElement, event, task, manualDestroy = false) {\n if (!event) {\n Log.error('Cannot call on() with no event: ', event);\n }\n if (!task) {\n Log.error('Cannot call on() with no task: ', task);\n }\n if (typeof targetSelectorOrElement === 'string') {\n const els = document.querySelectorAll(targetSelectorOrElement);\n if (els.length > 0) {\n for (let i = 0; i < els.length; i++)\n once(els[i], event, task);\n }\n }\n else if (isArray(targetSelectorOrElement)) {\n for (let i = 0; i < targetSelectorOrElement.length; i++)\n once(targetSelectorOrElement[i], event, task);\n }\n else if (typeof targetSelectorOrElement === 'object') {\n var taskWrapper = (function () {\n var internalTaskFunction = function (e) {\n var destroyEventListener = function () {\n targetSelectorOrElement.removeEventListener(e.type, taskWrapper);\n };\n if (!manualDestroy) {\n destroyEventListener();\n }\n task(e, destroyEventListener);\n };\n return internalTaskFunction;\n })();\n targetSelectorOrElement.addEventListener(event, taskWrapper);\n }\n else\n throw new Error(`${targetSelectorOrElement} must be a CSS selector string or DOM Element object.`);\n}\n/**\n * Returns the number of times the SDK has been loaded into the browser.\n * Expects a browser environment, otherwise this call will fail.\n */\nexport function getSdkLoadCount() {\n return window.__oneSignalSdkLoadCount || 0;\n}\nexport async function awaitSdkEvent(eventName) {\n return await new Promise(resolve => {\n OneSignal.emitter.once(eventName, (event) => {\n resolve(event);\n });\n });\n}\n/**\n * Increments the counter describing the number of times the SDK has been loaded into the browser.\n * Expects a browser environment, otherwise this call will fail.\n */\nexport function incrementSdkLoadCount() {\n window.__oneSignalSdkLoadCount = getSdkLoadCount() + 1;\n}\nexport function getPlatformNotificationIcon(notificationIcons) {\n if (!notificationIcons)\n return 'default-icon';\n if (bowser.safari && notificationIcons.safari)\n return notificationIcons.safari;\n else if (bowser.firefox && notificationIcons.firefox)\n return notificationIcons.firefox;\n return notificationIcons.chrome ||\n notificationIcons.firefox ||\n notificationIcons.safari ||\n 'default-icon';\n}\nexport function getDomElementOrStub(selector) {\n const foundElement = document.querySelector(selector);\n if (!foundElement) {\n Log.debug(`No instance of ${selector} found. Returning stub.`);\n return document.createElement('div');\n }\n return foundElement;\n}\nexport function deepCopy(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n//# sourceMappingURL=utils.js.map","/*!\n * Bowser - a browser detector\n * https://github.com/ded/bowser\n * MIT License | (c) Dustin Diaz 2015\n */\n\n!function (root, name, definition) {\n if (typeof module != 'undefined' && module.exports) module.exports = definition()\n else if (typeof define == 'function' && define.amd) define(name, definition)\n else root[name] = definition()\n}(this, 'bowser', function () {\n /**\n * See useragents.js for examples of navigator.userAgent\n */\n\n var t = true\n\n function detect(ua) {\n\n function getFirstMatch(regex) {\n var match = ua.match(regex);\n return (match && match.length > 1 && match[1]) || '';\n }\n\n function getSecondMatch(regex) {\n var match = ua.match(regex);\n return (match && match.length > 1 && match[2]) || '';\n }\n\n var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase()\n , likeAndroid = /like android/i.test(ua)\n , android = !likeAndroid && /android/i.test(ua)\n , nexusMobile = /nexus\\s*[0-6]\\s*/i.test(ua)\n , nexusTablet = !nexusMobile && /nexus\\s*[0-9]+/i.test(ua)\n , chromeos = /CrOS/.test(ua)\n , silk = /silk/i.test(ua)\n , sailfish = /sailfish/i.test(ua)\n , tizen = /tizen/i.test(ua)\n , webos = /(web|hpw)os/i.test(ua)\n , windowsphone = /windows phone/i.test(ua)\n , samsungBrowser = /SamsungBrowser/i.test(ua)\n , windows = !windowsphone && /windows/i.test(ua)\n , mac = !iosdevice && !silk && /macintosh/i.test(ua)\n , linux = !android && !sailfish && !tizen && !webos && /linux/i.test(ua)\n , edgeVersion = getFirstMatch(/edge\\/(\\d+(\\.\\d+)?)/i)\n , versionIdentifier = getFirstMatch(/version\\/(\\d+(\\.\\d+)?)/i)\n , tablet = /tablet/i.test(ua) && !/tablet pc/i.test(ua)\n , mobile = !tablet && /[^-]mobi/i.test(ua)\n , xbox = /xbox/i.test(ua)\n , result\n\n if (/opera/i.test(ua)) {\n // an old Opera\n result = {\n name: 'Opera'\n , opera: t\n , version: versionIdentifier || getFirstMatch(/(?:opera|opr|opios)[\\s\\/](\\d+(\\.\\d+)?)/i)\n }\n } else if (/opr\\/|opios/i.test(ua)) {\n // a new Opera\n result = {\n name: 'Opera'\n , opera: t\n , version: getFirstMatch(/(?:opr|opios)[\\s\\/](\\d+(\\.\\d+)?)/i) || versionIdentifier\n }\n }\n else if (/SamsungBrowser/i.test(ua)) {\n result = {\n name: 'Samsung Internet for Android'\n , samsungBrowser: t\n , version: versionIdentifier || getFirstMatch(/(?:SamsungBrowser)[\\s\\/](\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/coast/i.test(ua)) {\n result = {\n name: 'Opera Coast'\n , coast: t\n , version: versionIdentifier || getFirstMatch(/(?:coast)[\\s\\/](\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/yabrowser/i.test(ua)) {\n result = {\n name: 'Yandex Browser'\n , yandexbrowser: t\n , version: versionIdentifier || getFirstMatch(/(?:yabrowser)[\\s\\/](\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/ucbrowser/i.test(ua)) {\n result = {\n name: 'UC Browser'\n , ucbrowser: t\n , version: getFirstMatch(/(?:ucbrowser)[\\s\\/](\\d+(?:\\.\\d+)+)/i)\n }\n }\n else if (/mxios/i.test(ua)) {\n result = {\n name: 'Maxthon'\n , maxthon: t\n , version: getFirstMatch(/(?:mxios)[\\s\\/](\\d+(?:\\.\\d+)+)/i)\n }\n }\n else if (/epiphany/i.test(ua)) {\n result = {\n name: 'Epiphany'\n , epiphany: t\n , version: getFirstMatch(/(?:epiphany)[\\s\\/](\\d+(?:\\.\\d+)+)/i)\n }\n }\n else if (/puffin/i.test(ua)) {\n result = {\n name: 'Puffin'\n , puffin: t\n , version: getFirstMatch(/(?:puffin)[\\s\\/](\\d+(?:\\.\\d+)?)/i)\n }\n }\n else if (/sleipnir/i.test(ua)) {\n result = {\n name: 'Sleipnir'\n , sleipnir: t\n , version: getFirstMatch(/(?:sleipnir)[\\s\\/](\\d+(?:\\.\\d+)+)/i)\n }\n }\n else if (/k-meleon/i.test(ua)) {\n result = {\n name: 'K-Meleon'\n , kMeleon: t\n , version: getFirstMatch(/(?:k-meleon)[\\s\\/](\\d+(?:\\.\\d+)+)/i)\n }\n }\n else if (windowsphone) {\n result = {\n name: 'Windows Phone'\n , windowsphone: t\n }\n if (edgeVersion) {\n result.msedge = t\n result.version = edgeVersion\n }\n else {\n result.msie = t\n result.version = getFirstMatch(/iemobile\\/(\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/msie|trident/i.test(ua)) {\n result = {\n name: 'Internet Explorer'\n , msie: t\n , version: getFirstMatch(/(?:msie |rv:)(\\d+(\\.\\d+)?)/i)\n }\n } else if (chromeos) {\n result = {\n name: 'Chrome'\n , chromeos: t\n , chromeBook: t\n , chrome: t\n , version: getFirstMatch(/(?:chrome|crios|crmo)\\/(\\d+(\\.\\d+)?)/i)\n }\n } else if (/chrome.+? edge/i.test(ua)) {\n result = {\n name: 'Microsoft Edge'\n , msedge: t\n , version: edgeVersion\n }\n }\n else if (/vivaldi/i.test(ua)) {\n result = {\n name: 'Vivaldi'\n , vivaldi: t\n , version: getFirstMatch(/vivaldi\\/(\\d+(\\.\\d+)?)/i) || versionIdentifier\n }\n }\n else if (sailfish) {\n result = {\n name: 'Sailfish'\n , sailfish: t\n , version: getFirstMatch(/sailfish\\s?browser\\/(\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/seamonkey\\//i.test(ua)) {\n result = {\n name: 'SeaMonkey'\n , seamonkey: t\n , version: getFirstMatch(/seamonkey\\/(\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/firefox|iceweasel|fxios/i.test(ua)) {\n result = {\n name: 'Firefox'\n , firefox: t\n , version: getFirstMatch(/(?:firefox|iceweasel|fxios)[ \\/](\\d+(\\.\\d+)?)/i)\n }\n if (/\\((mobile|tablet);[^\\)]*rv:[\\d\\.]+\\)/i.test(ua)) {\n result.firefoxos = t\n }\n }\n else if (silk) {\n result = {\n name: 'Amazon Silk'\n , silk: t\n , version : getFirstMatch(/silk\\/(\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/phantom/i.test(ua)) {\n result = {\n name: 'PhantomJS'\n , phantom: t\n , version: getFirstMatch(/phantomjs\\/(\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/slimerjs/i.test(ua)) {\n result = {\n name: 'SlimerJS'\n , slimer: t\n , version: getFirstMatch(/slimerjs\\/(\\d+(\\.\\d+)?)/i)\n }\n }\n else if (/blackberry|\\bbb\\d+/i.test(ua) || /rim\\stablet/i.test(ua)) {\n result = {\n name: 'BlackBerry'\n , blackberry: t\n , version: versionIdentifier || getFirstMatch(/blackberry[\\d]+\\/(\\d+(\\.\\d+)?)/i)\n }\n }\n else if (webos) {\n result = {\n name: 'WebOS'\n , webos: t\n , version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\\/(\\d+(\\.\\d+)?)/i)\n };\n /touchpad\\//i.test(ua) && (result.touchpad = t)\n }\n else if (/bada/i.test(ua)) {\n result = {\n name: 'Bada'\n , bada: t\n , version: getFirstMatch(/dolfin\\/(\\d+(\\.\\d+)?)/i)\n };\n }\n else if (tizen) {\n result = {\n name: 'Tizen'\n , tizen: t\n , version: getFirstMatch(/(?:tizen\\s?)?browser\\/(\\d+(\\.\\d+)?)/i) || versionIdentifier\n };\n }\n else if (/qupzilla/i.test(ua)) {\n result = {\n name: 'QupZilla'\n , qupzilla: t\n , version: getFirstMatch(/(?:qupzilla)[\\s\\/](\\d+(?:\\.\\d+)+)/i) || versionIdentifier\n }\n }\n else if (/chromium/i.test(ua)) {\n result = {\n name: 'Chromium'\n , chromium: t\n , version: getFirstMatch(/(?:chromium)[\\s\\/](\\d+(?:\\.\\d+)?)/i) || versionIdentifier\n }\n }\n else if (/chrome|crios|crmo/i.test(ua)) {\n result = {\n name: 'Chrome'\n , chrome: t\n , version: getFirstMatch(/(?:chrome|crios|crmo)\\/(\\d+(\\.\\d+)?)/i)\n }\n }\n else if (android) {\n result = {\n name: 'Android'\n , version: versionIdentifier\n }\n }\n else if (/safari|applewebkit/i.test(ua)) {\n result = {\n name: 'Safari'\n , safari: t\n }\n if (versionIdentifier) {\n result.version = versionIdentifier\n }\n }\n else if (iosdevice) {\n result = {\n name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod'\n }\n // WTF: version is not part of user agent in web apps\n if (versionIdentifier) {\n result.version = versionIdentifier\n }\n }\n else if(/googlebot/i.test(ua)) {\n result = {\n name: 'Googlebot'\n , googlebot: t\n , version: getFirstMatch(/googlebot\\/(\\d+(\\.\\d+))/i) || versionIdentifier\n }\n }\n else {\n result = {\n name: getFirstMatch(/^(.*)\\/(.*) /),\n version: getSecondMatch(/^(.*)\\/(.*) /)\n };\n }\n\n // set webkit or gecko flag for browsers based on these engines\n if (!result.msedge && /(apple)?webkit/i.test(ua)) {\n if (/(apple)?webkit\\/537\\.36/i.test(ua)) {\n result.name = result.name || \"Blink\"\n result.blink = t\n } else {\n result.name = result.name || \"Webkit\"\n result.webkit = t\n }\n if (!result.version && versionIdentifier) {\n result.version = versionIdentifier\n }\n } else if (!result.opera && /gecko\\//i.test(ua)) {\n result.name = result.name || \"Gecko\"\n result.gecko = t\n result.version = result.version || getFirstMatch(/gecko\\/(\\d+(\\.\\d+)?)/i)\n }\n\n // set OS flags for platforms that have multiple browsers\n if (!result.windowsphone && !result.msedge && (android || result.silk)) {\n result.android = t\n } else if (!result.windowsphone && !result.msedge && iosdevice) {\n result[iosdevice] = t\n result.ios = t\n } else if (mac) {\n result.mac = t\n } else if (xbox) {\n result.xbox = t\n } else if (windows) {\n result.windows = t\n } else if (linux) {\n result.linux = t\n }\n\n function getWindowsVersion (s) {\n switch (s) {\n case 'NT': return 'NT'\n case 'XP': return 'XP'\n case 'NT 5.0': return '2000'\n case 'NT 5.1': return 'XP'\n case 'NT 5.2': return '2003'\n case 'NT 6.0': return 'Vista'\n case 'NT 6.1': return '7'\n case 'NT 6.2': return '8'\n case 'NT 6.3': return '8.1'\n case 'NT 10.0': return '10'\n default: return undefined\n }\n }\n\n // OS version extraction\n var osVersion = '';\n if (result.windows) {\n osVersion = getWindowsVersion(getFirstMatch(/Windows ((NT|XP)( \\d\\d?.\\d)?)/i))\n } else if (result.windowsphone) {\n osVersion = getFirstMatch(/windows phone (?:os)?\\s?(\\d+(\\.\\d+)*)/i);\n } else if (result.mac) {\n osVersion = getFirstMatch(/Mac OS X (\\d+([_\\.\\s]\\d+)*)/i);\n osVersion = osVersion.replace(/[_\\s]/g, '.');\n } else if (iosdevice) {\n osVersion = getFirstMatch(/os (\\d+([_\\s]\\d+)*) like mac os x/i);\n osVersion = osVersion.replace(/[_\\s]/g, '.');\n } else if (android) {\n osVersion = getFirstMatch(/android[ \\/-](\\d+(\\.\\d+)*)/i);\n } else if (result.webos) {\n osVersion = getFirstMatch(/(?:web|hpw)os\\/(\\d+(\\.\\d+)*)/i);\n } else if (result.blackberry) {\n osVersion = getFirstMatch(/rim\\stablet\\sos\\s(\\d+(\\.\\d+)*)/i);\n } else if (result.bada) {\n osVersion = getFirstMatch(/bada\\/(\\d+(\\.\\d+)*)/i);\n } else if (result.tizen) {\n osVersion = getFirstMatch(/tizen[\\/\\s](\\d+(\\.\\d+)*)/i);\n }\n if (osVersion) {\n result.osversion = osVersion;\n }\n\n // device type extraction\n var osMajorVersion = !result.windows && osVersion.split('.')[0];\n if (\n tablet\n || nexusTablet\n || iosdevice == 'ipad'\n || (android && (osMajorVersion == 3 || (osMajorVersion >= 4 && !mobile)))\n || result.silk\n ) {\n result.tablet = t\n } else if (\n mobile\n || iosdevice == 'iphone'\n || iosdevice == 'ipod'\n || android\n || nexusMobile\n || result.blackberry\n || result.webos\n || result.bada\n ) {\n result.mobile = t\n }\n\n // Graded Browser Support\n // http://developer.yahoo.com/yui/articles/gbs\n if (result.msedge ||\n (result.msie && result.version >= 10) ||\n (result.yandexbrowser && result.version >= 15) ||\n\t\t (result.vivaldi && result.version >= 1.0) ||\n (result.chrome && result.version >= 20) ||\n (result.samsungBrowser && result.version >= 4) ||\n (result.firefox && result.version >= 20.0) ||\n (result.safari && result.version >= 6) ||\n (result.opera && result.version >= 10.0) ||\n (result.ios && result.osversion && result.osversion.split(\".\")[0] >= 6) ||\n (result.blackberry && result.version >= 10.1)\n || (result.chromium && result.version >= 20)\n ) {\n result.a = t;\n }\n else if ((result.msie && result.version < 10) ||\n (result.chrome && result.version < 20) ||\n (result.firefox && result.version < 20.0) ||\n (result.safari && result.version < 6) ||\n (result.opera && result.version < 10.0) ||\n (result.ios && result.osversion && result.osversion.split(\".\")[0] < 6)\n || (result.chromium && result.version < 20)\n ) {\n result.c = t\n } else result.x = t\n\n return result\n }\n\n var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent || '' : '')\n\n bowser.test = function (browserList) {\n for (var i = 0; i < browserList.length; ++i) {\n var browserItem = browserList[i];\n if (typeof browserItem=== 'string') {\n if (browserItem in bowser) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Get version precisions count\n *\n * @example\n * getVersionPrecision(\"1.10.3\") // 3\n *\n * @param {string} version\n * @return {number}\n */\n function getVersionPrecision(version) {\n return version.split(\".\").length;\n }\n\n /**\n * Array::map polyfill\n *\n * @param {Array} arr\n * @param {Function} iterator\n * @return {Array}\n */\n function map(arr, iterator) {\n var result = [], i;\n if (Array.prototype.map) {\n return Array.prototype.map.call(arr, iterator);\n }\n for (i = 0; i < arr.length; i++) {\n result.push(iterator(arr[i]));\n }\n return result;\n }\n\n /**\n * Calculate browser version weight\n *\n * @example\n * compareVersions(['1.10.2.1', '1.8.2.1.90']) // 1\n * compareVersions(['1.010.2.1', '1.09.2.1.90']); // 1\n * compareVersions(['1.10.2.1', '1.10.2.1']); // 0\n * compareVersions(['1.10.2.1', '1.0800.2']); // -1\n *\n * @param {Array<String>} versions versions to compare\n * @return {Number} comparison result\n */\n function compareVersions(versions) {\n // 1) get common precision for both versions, for example for \"10.0\" and \"9\" it should be 2\n var precision = Math.max(getVersionPrecision(versions[0]), getVersionPrecision(versions[1]));\n var chunks = map(versions, function (version) {\n var delta = precision - getVersionPrecision(version);\n\n // 2) \"9\" -> \"9.0\" (for precision = 2)\n version = version + new Array(delta + 1).join(\".0\");\n\n // 3) \"9.0\" -> [\"000000000\"\", \"000000009\"]\n return map(version.split(\".\"), function (chunk) {\n return new Array(20 - chunk.length).join(\"0\") + chunk;\n }).reverse();\n });\n\n // iterate in reverse order by reversed chunks array\n while (--precision >= 0) {\n // 4) compare: \"000000009\" > \"000000010\" = false (but \"9\" > \"10\" = true)\n if (chunks[0][precision] > chunks[1][precision]) {\n return 1;\n }\n else if (chunks[0][precision] === chunks[1][precision]) {\n if (precision === 0) {\n // all version chunks are same\n return 0;\n }\n }\n else {\n return -1;\n }\n }\n }\n\n /**\n * Check if browser is unsupported\n *\n * @example\n * bowser.isUnsupportedBrowser({\n * msie: \"10\",\n * firefox: \"23\",\n * chrome: \"29\",\n * safari: \"5.1\",\n * opera: \"16\",\n * phantom: \"534\"\n * });\n *\n * @param {Object} minVersions map of minimal version to browser\n * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map\n * @param {String} [ua] user agent string\n * @return {Boolean}\n */\n function isUnsupportedBrowser(minVersions, strictMode, ua) {\n var _bowser = bowser;\n\n // make strictMode param optional with ua param usage\n if (typeof strictMode === 'string') {\n ua = strictMode;\n strictMode = void(0);\n }\n\n if (strictMode === void(0)) {\n strictMode = false;\n }\n if (ua) {\n _bowser = detect(ua);\n }\n\n var version = \"\" + _bowser.version;\n for (var browser in minVersions) {\n if (minVersions.hasOwnProperty(browser)) {\n if (_bowser[browser]) {\n if (typeof minVersions[browser] !== 'string') {\n throw new Error('Browser version in the minVersion map should be a string: ' + browser + ': ' + String(minVersions));\n }\n\n // browser version and min supported version.\n return compareVersions([version, minVersions[browser]]) < 0;\n }\n }\n }\n\n return strictMode; // not found\n }\n\n /**\n * Check if browser is supported\n *\n * @param {Object} minVersions map of minimal version to browser\n * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map\n * @param {String} [ua] user agent string\n * @return {Boolean}\n */\n function check(minVersions, strictMode, ua) {\n return !isUnsupportedBrowser(minVersions, strictMode, ua);\n }\n\n bowser.isUnsupportedBrowser = isUnsupportedBrowser;\n bowser.compareVersions = compareVersions;\n bowser.check = check;\n\n /*\n * Set our detect method to the main bowser object so we can\n * reuse it to test other user agents.\n * This is needed to implement future tests.\n */\n bowser._detect = detect;\n\n return bowser\n});\n","export var SubscriptionStateKind;\n(function (SubscriptionStateKind) {\n SubscriptionStateKind[SubscriptionStateKind[\"Default\"] = 0] = \"Default\";\n SubscriptionStateKind[SubscriptionStateKind[\"Subscribed\"] = 1] = \"Subscribed\";\n SubscriptionStateKind[SubscriptionStateKind[\"MutedByApi\"] = -2] = \"MutedByApi\";\n SubscriptionStateKind[SubscriptionStateKind[\"NotSubscribed\"] = -10] = \"NotSubscribed\";\n SubscriptionStateKind[SubscriptionStateKind[\"TemporaryWebRecord\"] = -20] = \"TemporaryWebRecord\";\n SubscriptionStateKind[SubscriptionStateKind[\"PermissionRevoked\"] = -21] = \"PermissionRevoked\";\n SubscriptionStateKind[SubscriptionStateKind[\"PushSubscriptionRevoked\"] = -22] = \"PushSubscriptionRevoked\";\n SubscriptionStateKind[SubscriptionStateKind[\"ServiceWorkerStatus403\"] = -23] = \"ServiceWorkerStatus403\";\n SubscriptionStateKind[SubscriptionStateKind[\"ServiceWorkerStatus404\"] = -24] = \"ServiceWorkerStatus404\";\n})(SubscriptionStateKind || (SubscriptionStateKind = {}));\n//# sourceMappingURL=SubscriptionStateKind.js.map","import { OneSignalApiErrorKind, OneSignalApiError } from './errors/OneSignalApiError';\nimport OneSignalApiBase from \"./OneSignalApiBase\";\nimport Utils from \"./context/shared/utils/Utils\";\nimport Log from \"./libraries/Log\";\nexport default class OneSignalApiShared {\n static getPlayer(appId, playerId) {\n Utils.enforceAppId(appId);\n Utils.enforcePlayerId(playerId);\n return OneSignalApiBase.get(`players/${playerId}?app_id=${appId}`);\n }\n static updatePlayer(appId, playerId, options) {\n Utils.enforceAppId(appId);\n Utils.enforcePlayerId(playerId);\n return OneSignalApiBase.put(`players/${playerId}`, Object.assign({ app_id: appId }, options));\n }\n static sendNotification(appId, playerIds, titles, contents, url, icon, data, buttons) {\n var params = {\n app_id: appId,\n contents: contents,\n include_player_ids: playerIds,\n isAnyWeb: true,\n data: data,\n web_buttons: buttons\n };\n if (titles) {\n params.headings = titles;\n }\n if (url) {\n params.url = url;\n }\n if (icon) {\n params.chrome_web_icon = icon;\n params.firefox_icon = icon;\n }\n Utils.trimUndefined(params);\n return OneSignalApiBase.post('notifications', params);\n }\n static async createUser(deviceRecord) {\n const serializedDeviceRecord = deviceRecord.serialize();\n Utils.enforceAppId(serializedDeviceRecord.app_id);\n const response = await OneSignalApiBase.post(`players`, serializedDeviceRecord);\n if (response && response.success)\n return response.id;\n return null;\n }\n static async logoutEmail(appConfig, emailProfile, deviceId) {\n Utils.enforceAppId(appConfig.appId);\n Utils.enforcePlayerId(deviceId);\n const response = await OneSignalApiBase.post(`players/${deviceId}/email_logout`, {\n app_id: appConfig.appId,\n parent_player_id: emailProfile.subscriptionId,\n identifier_auth_hash: emailProfile.identifierAuthHash ? emailProfile.identifierAuthHash : undefined\n });\n if (response && response.success) {\n return true;\n }\n else {\n return false;\n }\n }\n static async updateUserSession(userId, deviceRecord) {\n try {\n const serializedDeviceRecord = deviceRecord.serialize();\n Utils.enforceAppId(serializedDeviceRecord.app_id);\n Utils.enforcePlayerId(userId);\n const response = await OneSignalApiBase.post(`players/${userId}/on_session`, serializedDeviceRecord);\n if (response.id) {\n // A new user ID can be returned\n return response.id;\n }\n else {\n return userId;\n }\n }\n catch (e) {\n if (e && Array.isArray(e.errors) && e.errors.length > 0 &&\n Utils.contains(e.errors[0], 'app_id not found')) {\n throw new OneSignalApiError(OneSignalApiErrorKind.MissingAppId);\n }\n else\n throw e;\n }\n }\n static async sendOutcome(data) {\n Log.info(\"Outcome payload:\", data);\n try {\n await OneSignalApiBase.post(\"outcomes/measure\", data);\n }\n catch (e) {\n Log.error(\"sendOutcome\", e);\n }\n }\n}\n//# sourceMappingURL=OneSignalApiShared.js.map","export default class OneSignalError extends Error {\n constructor(message = '') {\n super(message);\n // extending Error is weird and does not propagate `message`\n Object.defineProperty(this, 'message', {\n configurable: true,\n enumerable: false,\n value: message,\n writable: true,\n });\n Object.defineProperty(this, 'name', {\n configurable: true,\n enumerable: false,\n value: this.constructor.name,\n writable: true,\n });\n if (Error.hasOwnProperty('captureStackTrace')) {\n Error.captureStackTrace(this, this.constructor);\n return;\n }\n Object.defineProperty(this, 'stack', {\n configurable: true,\n enumerable: false,\n value: (new Error(message)).stack,\n writable: true,\n });\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, OneSignalError.prototype);\n }\n}\n//# sourceMappingURL=OneSignalError.js.map","import OneSignalError from \"./OneSignalError\";\nexport var InvalidArgumentReason;\n(function (InvalidArgumentReason) {\n InvalidArgumentReason[InvalidArgumentReason[\"Empty\"] = 0] = \"Empty\";\n InvalidArgumentReason[InvalidArgumentReason[\"Malformed\"] = 1] = \"Malformed\";\n InvalidArgumentReason[InvalidArgumentReason[\"EnumOutOfRange\"] = 2] = \"EnumOutOfRange\";\n})(InvalidArgumentReason || (InvalidArgumentReason = {}));\nexport class InvalidArgumentError extends OneSignalError {\n constructor(argName, reason) {\n let errorMessage;\n switch (reason) {\n case InvalidArgumentReason.Empty:\n errorMessage = `Supply a non-empty value to '${argName}'.`;\n break;\n case InvalidArgumentReason.Malformed:\n errorMessage = `The value for '${argName}' was malformed.`;\n break;\n case InvalidArgumentReason.EnumOutOfRange:\n errorMessage = `The value for '${argName}' was out of range of the expected input enum.`;\n break;\n }\n super(errorMessage);\n this.argument = argName;\n this.reason = InvalidArgumentReason[reason];\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md\n * #extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, InvalidArgumentError.prototype);\n }\n}\n//# sourceMappingURL=InvalidArgumentError.js.map","export var IntegrationKind;\n(function (IntegrationKind) {\n /**\n * An secure HTTPS site using its own origin for subscribing.\n */\n IntegrationKind[\"Secure\"] = \"Secure\";\n /**\n * A secure HTTPS site using a proxy subscription origin (e.g. subdomain.os.tc or\n * subdomain.onesignal.com).\n */\n IntegrationKind[\"SecureProxy\"] = \"Secure Proxy\";\n /**\n * An insecure HTTP site using a proxy subscription origin (e.g. subdomain.os.tc or\n * subdomain.onesignal.com).\n */\n IntegrationKind[\"InsecureProxy\"] = \"Insecure Proxy\";\n})(IntegrationKind || (IntegrationKind = {}));\n//# sourceMappingURL=IntegrationKind.js.map","export var SessionStatus;\n(function (SessionStatus) {\n SessionStatus[\"Active\"] = \"active\";\n SessionStatus[\"Inactive\"] = \"inactive\";\n SessionStatus[\"Expired\"] = \"expired\";\n})(SessionStatus || (SessionStatus = {}));\nexport var SessionOrigin;\n(function (SessionOrigin) {\n SessionOrigin[SessionOrigin[\"PlayerCreate\"] = 1] = \"PlayerCreate\";\n SessionOrigin[SessionOrigin[\"PlayerOnSession\"] = 2] = \"PlayerOnSession\";\n SessionOrigin[SessionOrigin[\"VisibilityVisible\"] = 3] = \"VisibilityVisible\";\n SessionOrigin[SessionOrigin[\"VisibilityHidden\"] = 4] = \"VisibilityHidden\";\n SessionOrigin[SessionOrigin[\"BeforeUnload\"] = 5] = \"BeforeUnload\";\n SessionOrigin[SessionOrigin[\"PageRefresh\"] = 6] = \"PageRefresh\";\n SessionOrigin[SessionOrigin[\"Focus\"] = 7] = \"Focus\";\n SessionOrigin[SessionOrigin[\"Blur\"] = 8] = \"Blur\";\n})(SessionOrigin || (SessionOrigin = {}));\nexport const ONESIGNAL_SESSION_KEY = \"oneSignalSession\";\nexport function initializeNewSession(options) {\n const currentTimestamp = new Date().getTime();\n const sessionKey = options && options.sessionKey || ONESIGNAL_SESSION_KEY;\n const notificationId = (options && options.notificationId) || null;\n return {\n sessionKey,\n appId: options.appId,\n deviceId: options.deviceId,\n deviceType: options.deviceType,\n startTimestamp: currentTimestamp,\n accumulatedDuration: 0,\n notificationId,\n status: SessionStatus.Active,\n lastDeactivatedTimestamp: null,\n lastActivatedTimestamp: currentTimestamp,\n };\n}\n//# sourceMappingURL=Session.js.map","import Environment from './Environment';\nimport SdkEnvironment from './managers/SdkEnvironment';\nimport { Utils } from \"./context/shared/utils/Utils\";\nimport { OneSignalApiError, OneSignalApiErrorKind } from './errors/OneSignalApiError';\nimport Log from \"./libraries/Log\";\nexport class OneSignalApiBase {\n static get(action, data, headers) {\n return OneSignalApiBase.call('GET', action, data, headers);\n }\n static post(action, data, headers) {\n return OneSignalApiBase.call('POST', action, data, headers);\n }\n static put(action, data, headers) {\n return OneSignalApiBase.call('PUT', action, data, headers);\n }\n static delete(action, data, headers) {\n return OneSignalApiBase.call('DELETE', action, data, headers);\n }\n static call(method, action, data, headers) {\n if (method === \"GET\") {\n if (action.indexOf(\"players\") > -1 && action.indexOf(\"app_id=\") === -1) {\n console.error(\"Calls to player api are not permitted without app_id\");\n return Promise.reject(new OneSignalApiError(OneSignalApiErrorKind.MissingAppId));\n }\n }\n else {\n if (action.indexOf(\"players\") > -1 && (!data || !data[\"app_id\"])) {\n console.error(\"Calls to player api are not permitted without app_id\");\n return Promise.reject(new OneSignalApiError(OneSignalApiErrorKind.MissingAppId));\n }\n }\n const callHeaders = new Headers();\n callHeaders.append(\"Origin\", SdkEnvironment.getOrigin());\n callHeaders.append('SDK-Version', `onesignal/web/${Environment.version()}`);\n callHeaders.append('Content-Type', 'application/json;charset=UTF-8');\n if (headers) {\n for (const key of Object.keys(headers)) {\n callHeaders.append(key, headers[key]);\n }\n }\n const contents = {\n method: method || 'NO_METHOD_SPECIFIED',\n headers: callHeaders,\n cache: 'no-cache'\n };\n if (data)\n contents.body = JSON.stringify(data);\n let status;\n return fetch(SdkEnvironment.getOneSignalApiUrl(undefined, action).toString() + '/' + action, contents)\n .then(response => {\n status = response.status;\n return response.json();\n })\n .then(json => {\n if (status >= 200 && status < 300)\n return json;\n else {\n const error = OneSignalApiBase.identifyError(json);\n if (error === 'no-user-id-error') {\n // TODO: This returns undefined\n }\n else {\n return Promise.reject(json);\n }\n }\n })\n .catch(err => {\n Log.warn(`Could not complete request to /${action}`, err);\n return Promise.reject(err);\n });\n }\n static identifyError(error) {\n if (!error || !error.errors) {\n return 'no-error';\n }\n const errors = error.errors;\n if (Utils.contains(errors, 'No user with this id found') ||\n Utils.contains(errors, 'Could not find app_id for given player id.')) {\n return 'no-user-id-error';\n }\n return 'unknown-error';\n }\n}\nexport default OneSignalApiBase;\n//# sourceMappingURL=OneSignalApiBase.js.map","import { OutcomeAttributionType } from '../../models/Outcomes';\nimport Database from \"../../services/Database\";\nimport Log from \"../../libraries/Log\";\nimport { Utils } from \"../../context/shared/utils/Utils\";\nimport { logMethodCall, awaitOneSignalInitAndSupported } from '../../utils';\nconst SEND_OUTCOME = \"sendOutcome\";\nconst SEND_UNIQUE_OUTCOME = \"sendUniqueOutcome\";\nexport default class OutcomesHelper {\n /**\n * @param {string} appId\n * @param {OutcomesConfig} config - refers specifically to outcomes config\n * @param {boolean} isUnique\n * @param {string} outcomeName\n */\n constructor(appId, config, outcomeName, isUnique) {\n this.outcomeName = outcomeName;\n this.config = config;\n this.appId = appId;\n this.isUnique = isUnique;\n }\n /**\n * Returns `OutcomeAttribution` object which includes\n * 1) attribution type\n * 2) notification ids\n *\n * Note: this just looks at notifications that fall within the attribution window and\n * does not check if they have been previously attributed (used in both sendOutcome & sendUniqueOutcome)\n * @returns Promise\n */\n async getAttribution() {\n return await OutcomesHelper.getAttribution(this.config);\n }\n /**\n * Performs logging of method call and returns whether Outcomes are supported\n * @param {boolean} isUnique\n * @returns Promise\n */\n async beforeOutcomeSend() {\n const outcomeMethodString = this.isUnique ? SEND_UNIQUE_OUTCOME : SEND_OUTCOME;\n logMethodCall(outcomeMethodString, this.outcomeName);\n if (!this.config) {\n Log.debug(\"Outcomes feature not supported by main application yet.\");\n return false;\n }\n if (!this.outcomeName) {\n Log.error(\"Outcome name is required\");\n return false;\n }\n await awaitOneSignalInitAndSupported();\n const isSubscribed = await OneSignal.privateIsPushNotificationsEnabled();\n if (!isSubscribed) {\n Log.warn(\"Reporting outcomes is supported only for subscribed users.\");\n return false;\n }\n return true;\n }\n /**\n * Returns array of notification ids outcome is currently attributed with\n * @param {string} outcomeName\n * @returns Promise\n */\n async getAttributedNotifsByUniqueOutcomeName() {\n const sentOutcomes = await Database.getAll(\"SentUniqueOutcome\");\n return sentOutcomes\n .filter(o => o.outcomeName === this.outcomeName)\n .reduce((acc, curr) => {\n const notificationIds = curr.notificationIds || [];\n return [...acc, ...notificationIds];\n }, []);\n }\n /**\n * Returns array of new notifications that have never been attributed to the outcome\n * @param {string} outcomeName\n * @param {string[]} notificationIds\n */\n async getNotifsToAttributeWithUniqueOutcome(notificationIds) {\n const previouslyAttributedArr = await this.getAttributedNotifsByUniqueOutcomeName();\n return notificationIds.filter(id => (previouslyAttributedArr.indexOf(id) === -1));\n }\n shouldSendUnique(outcomeAttribution, notifArr) {\n // we should only send if type is unattributed OR there are notifs to attribute\n if (outcomeAttribution.type === OutcomeAttributionType.Unattributed) {\n return true;\n }\n return notifArr.length > 0;\n }\n async saveSentUniqueOutcome(newNotificationIds) {\n const outcomeName = this.outcomeName;\n const existingSentOutcome = await Database.get(\"SentUniqueOutcome\", outcomeName);\n const currentSession = await Database.getCurrentSession();\n const existingNotificationIds = !!existingSentOutcome ? existingSentOutcome.notificationIds : [];\n const notificationIds = [...existingNotificationIds, ...newNotificationIds];\n const timestamp = currentSession ? currentSession.startTimestamp : null;\n await Database.put(\"SentUniqueOutcome\", {\n outcomeName,\n notificationIds,\n sentDuringSession: timestamp\n });\n }\n async wasSentDuringSession() {\n const sentOutcome = await Database.get(\"SentUniqueOutcome\", this.outcomeName);\n if (!sentOutcome) {\n return false;\n }\n const session = await Database.getCurrentSession();\n const sessionExistsAndWasPreviouslySent = session && sentOutcome.sentDuringSession === session.startTimestamp;\n const sessionWasClearedButWasPreviouslySent = !session && !!sentOutcome.sentDuringSession;\n return sessionExistsAndWasPreviouslySent || sessionWasClearedButWasPreviouslySent;\n }\n async send(outcomeProps) {\n const { type, notificationIds, weight } = outcomeProps;\n switch (type) {\n case OutcomeAttributionType.Direct:\n if (this.isUnique) {\n await this.saveSentUniqueOutcome(notificationIds);\n }\n await OneSignal.context.updateManager.sendOutcomeDirect(this.appId, notificationIds, this.outcomeName, weight);\n return;\n case OutcomeAttributionType.Indirect:\n if (this.isUnique) {\n await this.saveSentUniqueOutcome(notificationIds);\n }\n await OneSignal.context.updateManager.sendOutcomeInfluenced(this.appId, notificationIds, this.outcomeName, weight);\n return;\n case OutcomeAttributionType.Unattributed:\n if (this.isUnique) {\n if (await this.wasSentDuringSession()) {\n Log.warn(`(Unattributed) unique outcome was already sent during this session`);\n return;\n }\n await this.saveSentUniqueOutcome([]);\n }\n await OneSignal.context.updateManager.sendOutcomeUnattributed(this.appId, this.outcomeName, weight);\n return;\n default:\n Log.warn(\"You are on a free plan. Please upgrade to use this functionality.\");\n return;\n }\n }\n // statics\n /**\n * Static method: returns `OutcomeAttribution` object which includes\n * 1) attribution type\n * 2) notification ids\n *\n * Note: this just looks at notifications that fall within the attribution window and\n * does not check if they have been previously attributed (used in both sendOutcome & sendUniqueOutcome)\n * @param {OutcomesConfig} config\n * @returns Promise\n */\n static async getAttribution(config) {\n /**\n * Flow:\n * 1. check if the url was opened as a result of a notif;\n * 2. if so, send an api call reporting direct notification outcome\n * (currently takes into account the match strategy selected in the app's settings);\n * 3. else check all received notifs within timeframe from config;\n * 4. send an api call reporting an influenced outcome for each matching notification\n * respecting the limit from config too;\n * 5. if no influencing notification found, report unattributed outcome to the api.\n */\n /* direct notifications */\n if (config.direct && config.direct.enabled) {\n const clickedNotifications = await Database.getAll(\"NotificationClicked\");\n if (clickedNotifications.length > 0) {\n return {\n type: OutcomeAttributionType.Direct,\n notificationIds: [clickedNotifications[0].notificationId]\n };\n }\n }\n /* influencing notifications */\n if (config.indirect && config.indirect.enabled) {\n const timeframeMs = config.indirect.influencedTimePeriodMin * 60 * 1000;\n const beginningOfTimeframe = new Date(new Date().getTime() - timeframeMs);\n const maxTimestamp = beginningOfTimeframe.getTime();\n const allReceivedNotification = await Database.getAll(\"NotificationReceived\");\n Log.debug(`\\tFound total of ${allReceivedNotification.length} received notifications`);\n if (allReceivedNotification.length > 0) {\n const max = config.indirect.influencedNotificationsLimit;\n /**\n * To handle correctly the case when user got subscribed to a new app id\n * we check the appId on notifications to match the current app.\n */\n const allReceivedNotificationSorted = Utils.sortArrayOfObjects(allReceivedNotification, (notif) => notif.timestamp, true, false);\n const matchingNotificationIds = allReceivedNotificationSorted\n .filter(notif => notif.timestamp >= maxTimestamp)\n .slice(0, max)\n .map(notif => notif.notificationId);\n Log.debug(`\\tTotal of ${matchingNotificationIds.length} received notifications are within reporting window.`);\n // Deleting all unmatched received notifications\n const notificationIdsToDelete = allReceivedNotificationSorted\n .filter(notif => matchingNotificationIds.indexOf(notif.notificationId) === -1)\n .map(notif => notif.notificationId);\n notificationIdsToDelete.forEach(id => Database.remove(\"NotificationReceived\", id));\n Log.debug(`\\t${notificationIdsToDelete.length} received notifications will be deleted.`);\n if (matchingNotificationIds.length > 0) {\n return {\n type: OutcomeAttributionType.Indirect,\n notificationIds: matchingNotificationIds,\n };\n }\n }\n }\n /* unattributed outcome report */\n if (config.unattributed && config.unattributed.enabled) {\n return {\n type: OutcomeAttributionType.Unattributed,\n notificationIds: []\n };\n }\n return {\n type: OutcomeAttributionType.NotSupported,\n notificationIds: [],\n };\n }\n}\n//# sourceMappingURL=OutcomesHelper.js.map","import { OneSignalApiSW } from \"../OneSignalApiSW\";\nimport Log from \"../libraries/sw/Log\";\nimport { initializeNewSession, SessionOrigin, SessionStatus } from \"../models/Session\";\nimport { OneSignalUtils } from \"../utils/OneSignalUtils\";\nimport Database from \"../services/Database\";\nimport { PushDeviceRecord } from \"../models/PushDeviceRecord\";\nimport { RawPushSubscription } from '../models/RawPushSubscription';\nimport OutcomesHelper from './shared/OutcomesHelper';\nimport { cancelableTimeout } from './sw/CancelableTimeout';\nimport Utils from \"../context/shared/utils/Utils\";\nimport { SecondaryChannelManager } from \"../managers/channelManager/shared/SecondaryChannelManager\";\nexport default class ServiceWorkerHelper {\n static getServiceWorkerHref(config, appId, sdkVersion) {\n return ServiceWorkerHelper.appendServiceWorkerParams(config.workerPath.getFullPath(), appId, sdkVersion);\n }\n static appendServiceWorkerParams(workerFullPath, appId, sdkVersion) {\n const fullPath = new URL(workerFullPath, OneSignalUtils.getBaseUrl()).href;\n const appIdAsQueryParam = Utils.encodeHashAsUriComponent({ appId });\n const sdkVersionAsQueryParam = Utils.encodeHashAsUriComponent({ sdkVersion });\n return `${fullPath}?${appIdAsQueryParam}?${sdkVersionAsQueryParam}`;\n }\n static async upsertSession(sessionThresholdInSeconds, sendOnFocusEnabled, deviceRecord, deviceId, sessionOrigin, outcomesConfig) {\n if (!deviceId) {\n Log.error(\"No deviceId provided for new session.\");\n return;\n }\n if (!deviceRecord.app_id) {\n Log.error(\"No appId provided for new session.\");\n return;\n }\n const existingSession = await Database.getCurrentSession();\n if (!existingSession) {\n const appId = deviceRecord.app_id;\n const session = initializeNewSession({ deviceId, appId, deviceType: deviceRecord.device_type });\n // if there is a record about a clicked notification in our database, attribute session to it.\n const clickedNotification = await Database.getLastNotificationClicked(appId);\n if (clickedNotification) {\n session.notificationId = clickedNotification.notificationId;\n }\n await Database.upsertSession(session);\n await ServiceWorkerHelper.sendOnSessionCallIfNecessary(sessionOrigin, deviceRecord, deviceId, session);\n return;\n }\n if (existingSession.status === SessionStatus.Active) {\n Log.debug(\"Session already active\", existingSession);\n return;\n }\n if (!existingSession.lastDeactivatedTimestamp) {\n Log.debug(\"Session is in invalid state\", existingSession);\n // TODO: possibly recover by re-starting session if deviceId is present?\n return;\n }\n const currentTimestamp = new Date().getTime();\n const timeSinceLastDeactivatedInSeconds = ServiceWorkerHelper.timeInSecondsBetweenTimestamps(currentTimestamp, existingSession.lastDeactivatedTimestamp);\n if (timeSinceLastDeactivatedInSeconds <= sessionThresholdInSeconds) {\n existingSession.status = SessionStatus.Active;\n existingSession.lastActivatedTimestamp = currentTimestamp;\n existingSession.lastDeactivatedTimestamp = null;\n await Database.upsertSession(existingSession);\n return;\n }\n // If failed to report/clean-up last time, we can attempt to try again here.\n // TODO: Possibly check that it's not unreasonably long.\n // TODO: Or couple with periodic ping for better results.\n await ServiceWorkerHelper.finalizeSession(existingSession, sendOnFocusEnabled, outcomesConfig);\n const session = initializeNewSession({ deviceId, appId: deviceRecord.app_id, deviceType: deviceRecord.device_type });\n await Database.upsertSession(session);\n await ServiceWorkerHelper.sendOnSessionCallIfNecessary(sessionOrigin, deviceRecord, deviceId, session);\n }\n static async deactivateSession(thresholdInSeconds, sendOnFocusEnabled, outcomesConfig) {\n const existingSession = await Database.getCurrentSession();\n if (!existingSession) {\n Log.debug(\"No active session found. Cannot deactivate.\");\n return undefined;\n }\n /**\n * For 2 subsequent deactivate requests we need to make sure there is an active finalization timeout.\n * Timer gets cleaned up before figuring out it's activate or deactivate.\n * No update needed for the session, early return.\n */\n if (existingSession.status === SessionStatus.Inactive) {\n return cancelableTimeout(() => ServiceWorkerHelper.finalizeSession(existingSession, sendOnFocusEnabled, outcomesConfig), thresholdInSeconds);\n }\n /**\n * Can only be active or expired at this point, but more statuses may come in in the future.\n * For anything but active, logging a warning and doing early return.\n */\n if (existingSession.status !== SessionStatus.Active) {\n Log.warn(`Session in invalid state ${existingSession.status}. Cannot deactivate.`);\n return undefined;\n }\n const currentTimestamp = new Date().getTime();\n const timeSinceLastActivatedInSeconds = ServiceWorkerHelper.timeInSecondsBetweenTimestamps(currentTimestamp, existingSession.lastActivatedTimestamp);\n existingSession.lastDeactivatedTimestamp = currentTimestamp;\n existingSession.accumulatedDuration += timeSinceLastActivatedInSeconds;\n existingSession.status = SessionStatus.Inactive;\n const cancelableFinalize = cancelableTimeout(() => ServiceWorkerHelper.finalizeSession(existingSession, sendOnFocusEnabled, outcomesConfig), thresholdInSeconds);\n await Database.upsertSession(existingSession);\n return cancelableFinalize;\n }\n /**\n * Sends on_session call on each new session initialization except the case\n * when player create call occurs, e.g. first subscribed or re-subscribed cases after clearing cookies,\n * since player#create call updates last_session field on player.\n */\n static async sendOnSessionCallIfNecessary(sessionOrigin, deviceRecord, deviceId, session) {\n if (sessionOrigin === SessionOrigin.PlayerCreate) {\n return;\n }\n if (!deviceRecord.identifier) {\n const subscription = await self.registration.pushManager.getSubscription();\n if (subscription) {\n const rawPushSubscription = RawPushSubscription.setFromW3cSubscription(subscription);\n const fullDeviceRecord = new PushDeviceRecord(rawPushSubscription).serialize();\n deviceRecord.identifier = fullDeviceRecord.identifier;\n }\n }\n const newPlayerId = await OneSignalApiSW.updateUserSession(deviceId, deviceRecord);\n // If the returned player id is different, save the new id to indexed db and update session\n if (newPlayerId !== deviceId) {\n session.deviceId = newPlayerId;\n await Promise.all([\n Database.setDeviceId(newPlayerId),\n Database.upsertSession(session),\n Database.resetSentUniqueOutcomes()\n ]);\n }\n // There isn't a OneSignal Global context to pull from so creating a new\n // SecondaryChannelManager instance.\n const secondaryChannelManager = new SecondaryChannelManager();\n await secondaryChannelManager.synchronizer.onSession();\n }\n static async finalizeSession(session, sendOnFocusEnabled, outcomesConfig) {\n Log.debug(\"Finalize session\", `started: ${new Date(session.startTimestamp)}`, `duration: ${session.accumulatedDuration}s`);\n if (sendOnFocusEnabled) {\n Log.debug(`send on_focus reporting session duration -> ${session.accumulatedDuration}s`);\n const attribution = await OutcomesHelper.getAttribution(outcomesConfig);\n Log.debug(\"send on_focus with attribution\", attribution);\n await OneSignalApiSW.sendSessionDuration(session.appId, session.deviceId, session.accumulatedDuration, session.deviceType, attribution);\n // There isn't a OneSignal Global context to pull from so creating a new\n // SecondaryChannelManager instance.\n const secondaryChannelManager = new SecondaryChannelManager();\n await secondaryChannelManager.synchronizer.onFocus(session.accumulatedDuration);\n }\n await Promise.all([\n Database.cleanupCurrentSession(),\n Database.removeAllNotificationClicked()\n ]);\n Log.debug(\"Finalize session finished\", `started: ${new Date(session.startTimestamp)}`);\n }\n static timeInSecondsBetweenTimestamps(timestamp1, timestamp2) {\n if (timestamp1 <= timestamp2) {\n return 0;\n }\n return Math.floor((timestamp1 - timestamp2) / 1000);\n }\n}\nexport var ServiceWorkerActiveState;\n(function (ServiceWorkerActiveState) {\n /**\n * OneSignalSDKWorker.js, or the equivalent custom file name, is active.\n */\n ServiceWorkerActiveState[\"OneSignalWorker\"] = \"OneSignal Worker\";\n /**\n * A service worker is active, but it is not OneSignalSDKWorker.js\n * (or the equivalent custom file names as provided by user config).\n */\n ServiceWorkerActiveState[\"ThirdParty\"] = \"3rd Party\";\n /**\n * No service worker is installed.\n */\n ServiceWorkerActiveState[\"None\"] = \"None\";\n /**\n * Service workers are not supported in this environment. This status is used\n * on HTTP pages where it isn't possible to know whether a service worker is\n * installed or not or in any of the other states.\n */\n ServiceWorkerActiveState[\"Indeterminate\"] = \"Indeterminate\";\n})(ServiceWorkerActiveState || (ServiceWorkerActiveState = {}));\n//# sourceMappingURL=ServiceWorkerHelper.js.map","import Environment from './Environment';\nimport SdkEnvironment from './managers/SdkEnvironment';\nimport { WindowEnvironmentKind } from './models/WindowEnvironmentKind';\nimport Log from './libraries/Log';\nimport Utils from \"./context/shared/utils/Utils\";\nconst SILENT_EVENTS = [\n 'notifyButtonHovering',\n 'notifyButtonHover',\n 'notifyButtonButtonClick',\n 'notifyButtonLauncherClick',\n 'animatedElementHiding',\n 'animatedElementHidden',\n 'animatedElementShowing',\n 'animatedElementShown',\n 'activeAnimatedElementActivating',\n 'activeAnimatedElementActive',\n 'activeAnimatedElementInactivating',\n 'activeAnimatedElementInactive',\n 'dbRetrieved',\n 'dbSet',\n 'testEvent'\n];\nconst RETRIGGER_REMOTE_EVENTS = [\n 'onesignal.prompt.custom.clicked',\n 'onesignal.prompt.native.permissionchanged',\n 'onesignal.subscription.changed',\n 'onesignal.internal.subscriptionset',\n 'dbRebuilt',\n 'initialize',\n 'subscriptionSet',\n 'sendWelcomeNotification',\n 'subscriptionChange',\n 'notificationPermissionChange',\n 'dbSet',\n 'register',\n 'notificationDisplay',\n 'notificationDismiss',\n 'notificationClick',\n 'permissionPromptDisplay',\n 'testWouldDisplay',\n 'testInitOptionDisabled',\n 'popupWindowTimeout'\n];\nconst LEGACY_EVENT_MAP = {\n notificationPermissionChange: 'onesignal.prompt.native.permissionchanged',\n subscriptionChange: 'onesignal.subscription.changed',\n customPromptClick: 'onesignal.prompt.custom.clicked',\n};\nexport default class Event {\n /**\n * Triggers the specified event with optional custom data.\n * @param eventName The string event name to be emitted.\n * @param data Any JavaScript variable to be passed with the event.\n * @param remoteTriggerEnv If this method is being called in a different environment (e.g. was triggered in iFrame but now retriggered on main host), this is the string of the original environment for logging purposes.\n */\n static async trigger(eventName, data, remoteTriggerEnv = null) {\n if (!Utils.contains(SILENT_EVENTS, eventName)) {\n const displayData = data;\n let env = Utils.capitalize(SdkEnvironment.getWindowEnv().toString());\n if (remoteTriggerEnv) {\n env = `${env} ⬸ ${Utils.capitalize(remoteTriggerEnv)}`;\n }\n if (displayData || displayData === false) {\n Log.debug(`(${env}) » %c${eventName}:`, Utils.getConsoleStyle('event'), displayData);\n }\n else {\n Log.debug(`(${env}) » %c${eventName}`, Utils.getConsoleStyle('event'));\n }\n }\n // Actually fire the event that can be listened to via OneSignal.on()\n if (Environment.isBrowser()) {\n if (eventName === OneSignal.EVENTS.SDK_INITIALIZED) {\n if (OneSignal.initialized)\n return;\n else\n OneSignal.initialized = true;\n }\n await OneSignal.emitter.emit(eventName, data);\n }\n if (LEGACY_EVENT_MAP.hasOwnProperty(eventName)) {\n const legacyEventName = LEGACY_EVENT_MAP[eventName];\n Event._triggerLegacy(legacyEventName, data);\n }\n // If this event was triggered in an iFrame or Popup environment, also trigger it on the host page\n if (Environment.isBrowser() &&\n (SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.OneSignalSubscriptionPopup ||\n SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.OneSignalProxyFrame)) {\n const creator = opener || parent;\n if (!creator) {\n Log.error(`Could not send event '${eventName}' back to host page because no creator (opener or parent) found!`);\n }\n else {\n // But only if the event matches certain events\n if (Utils.contains(RETRIGGER_REMOTE_EVENTS, eventName)) {\n if (SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.OneSignalSubscriptionPopup) {\n OneSignal.subscriptionPopup.message(OneSignal.POSTMAM_COMMANDS.REMOTE_RETRIGGER_EVENT, { eventName: eventName, eventData: data });\n }\n else {\n OneSignal.proxyFrame.retriggerRemoteEvent(eventName, data);\n }\n }\n }\n }\n }\n /**\n * Fires the event to be listened to via window.addEventListener().\n * @param eventName The string event name.\n * @param data Any JavaScript variable to be passed with the event.\n * @private\n */\n static _triggerLegacy(eventName, data) {\n const event = new CustomEvent(eventName, {\n bubbles: true, cancelable: true, detail: data\n });\n // Fire the event that listeners can listen to via 'window.addEventListener()'\n window.dispatchEvent(event);\n }\n}\n//# sourceMappingURL=Event.js.map","export var DelayedPromptType;\n(function (DelayedPromptType) {\n DelayedPromptType[\"Native\"] = \"native\";\n DelayedPromptType[\"Push\"] = \"push\";\n DelayedPromptType[\"Category\"] = \"category\";\n DelayedPromptType[\"Sms\"] = \"sms\";\n DelayedPromptType[\"Email\"] = \"email\";\n DelayedPromptType[\"SmsAndEmail\"] = \"smsAndEmail\"; // sms and email only\n})(DelayedPromptType || (DelayedPromptType = {}));\n//# sourceMappingURL=Prompts.js.map","export class RawPushSubscription {\n /**\n * Returns true if an existing recorded W3C or Safari subscription is\n * identical to the current subscription.\n */\n isNewSubscription() {\n if (this.existingW3cPushSubscription) {\n if (!!this.existingW3cPushSubscription.w3cEndpoint !== !!this.w3cEndpoint) {\n return true;\n }\n if (!!this.existingW3cPushSubscription.w3cEndpoint && !!this.w3cEndpoint &&\n this.existingW3cPushSubscription.w3cEndpoint.toString() !== this.w3cEndpoint.toString()) {\n return true;\n }\n if (this.existingW3cPushSubscription.w3cP256dh !== this.w3cP256dh) {\n return true;\n }\n if (this.existingW3cPushSubscription.w3cAuth !== this.w3cAuth) {\n return true;\n }\n return false;\n }\n else if (this.existingSafariDeviceToken) {\n return this.existingSafariDeviceToken !== this.safariDeviceToken;\n }\n return true;\n }\n /**\n * Given a native W3C browser push subscription, takes the endpoint, p256dh,\n * and auth.\n *\n * @param pushSubscription A native browser W3C push subscription.\n */\n static setFromW3cSubscription(pushSubscription) {\n const rawPushSubscription = new RawPushSubscription();\n if (pushSubscription) {\n rawPushSubscription.w3cEndpoint = new URL(pushSubscription.endpoint);\n // Retrieve p256dh and auth for encrypted web push protocol\n if (pushSubscription.getKey) {\n // p256dh and auth are both ArrayBuffer\n let p256dh = null;\n try {\n p256dh = pushSubscription.getKey('p256dh');\n }\n catch (e) {\n // User is most likely running < Chrome < 50\n }\n let auth = null;\n try {\n auth = pushSubscription.getKey('auth');\n }\n catch (e) {\n // User is most likely running < Firefox 45\n }\n if (p256dh) {\n // Base64 encode the ArrayBuffer (not URL-Safe, using standard Base64)\n const p256dh_base64encoded = btoa(String.fromCharCode.apply(null, new Uint8Array(p256dh)));\n rawPushSubscription.w3cP256dh = p256dh_base64encoded;\n }\n if (auth) {\n // Base64 encode the ArrayBuffer (not URL-Safe, using standard Base64)\n const auth_base64encoded = btoa(String.fromCharCode.apply(null, new Uint8Array(auth)));\n rawPushSubscription.w3cAuth = auth_base64encoded;\n }\n }\n }\n return rawPushSubscription;\n }\n /**\n * Given a native browser Safari push subscription, sets the device token\n * property.\n *\n * @param safariDeviceToken A native browser Safari push subscription.\n */\n setFromSafariSubscription(safariDeviceToken) {\n this.safariDeviceToken = safariDeviceToken;\n }\n serialize() {\n const serializedBundle = {\n /* Old Parameters */\n w3cEndpoint: this.w3cEndpoint ? this.w3cEndpoint.toString() : null,\n w3cP256dh: this.w3cP256dh,\n w3cAuth: this.w3cAuth,\n safariDeviceToken: this.safariDeviceToken,\n existingPushSubscription: this.existingW3cPushSubscription ? this.existingW3cPushSubscription.serialize() : null,\n existingSafariDeviceToken: this.existingSafariDeviceToken\n };\n return serializedBundle;\n }\n // TODO: had a hard to debug bug here due to \"any\" type bypassing typescript validation.\n // Check the usage and maybe change with strict type\n static deserialize(bundle) {\n const subscription = new RawPushSubscription();\n if (!bundle) {\n return subscription;\n }\n try {\n subscription.w3cEndpoint = new URL(bundle.w3cEndpoint);\n }\n catch (e) {\n // w3cEndpoint will be null for Safari\n }\n subscription.w3cP256dh = bundle.w3cP256dh;\n subscription.w3cAuth = bundle.w3cAuth;\n subscription.existingW3cPushSubscription = undefined;\n if (bundle.existingW3cPushSubscription) {\n subscription.existingW3cPushSubscription = RawPushSubscription.deserialize(bundle.existingW3cPushSubscription);\n }\n else if (bundle.existingPushSubscription) {\n subscription.existingW3cPushSubscription = RawPushSubscription.deserialize(bundle.existingPushSubscription);\n }\n subscription.safariDeviceToken = bundle.safariDeviceToken;\n subscription.existingSafariDeviceToken = bundle.existingSafariDeviceToken;\n return subscription;\n }\n}\n//# sourceMappingURL=RawPushSubscription.js.map","import OneSignalError from \"./OneSignalError\";\nexport default class NotImplementedError extends OneSignalError {\n constructor() {\n super('This code is not implemented yet.');\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, NotImplementedError.prototype);\n }\n}\n//# sourceMappingURL=NotImplementedError.js.map","import OneSignalError from \"./OneSignalError\";\nexport var SdkInitErrorKind;\n(function (SdkInitErrorKind) {\n SdkInitErrorKind[SdkInitErrorKind[\"InvalidAppId\"] = 0] = \"InvalidAppId\";\n SdkInitErrorKind[SdkInitErrorKind[\"AppNotConfiguredForWebPush\"] = 1] = \"AppNotConfiguredForWebPush\";\n SdkInitErrorKind[SdkInitErrorKind[\"MissingSubdomain\"] = 2] = \"MissingSubdomain\";\n SdkInitErrorKind[SdkInitErrorKind[\"WrongSiteUrl\"] = 3] = \"WrongSiteUrl\";\n SdkInitErrorKind[SdkInitErrorKind[\"MultipleInitialization\"] = 4] = \"MultipleInitialization\";\n SdkInitErrorKind[SdkInitErrorKind[\"MissingSafariWebId\"] = 5] = \"MissingSafariWebId\";\n SdkInitErrorKind[SdkInitErrorKind[\"Unknown\"] = 6] = \"Unknown\";\n})(SdkInitErrorKind || (SdkInitErrorKind = {}));\nexport class SdkInitError extends OneSignalError {\n constructor(reason, extra) {\n let errorMessage;\n switch (reason) {\n case SdkInitErrorKind.InvalidAppId:\n errorMessage = 'OneSignal: This app ID does not match any existing app. Double check your app ID.';\n break;\n case SdkInitErrorKind.AppNotConfiguredForWebPush:\n errorMessage = `OneSignal: This app ID does not have any web platforms enabled. Double check your app` +\n ` ID, or see step 1 on our setup guide (https://tinyurl.com/2x5jzk83).`;\n break;\n case SdkInitErrorKind.MissingSubdomain:\n errorMessage = `Non-HTTPS pages require the subdomainName parameter within the label set within the OneSignal Web configuration (https://tinyurl.com/ry39x7mk).`;\n break;\n case SdkInitErrorKind.WrongSiteUrl:\n if (extra && extra.siteUrl) {\n errorMessage = `OneSignal: This web push config can only be used on ${new URL(extra.siteUrl).origin}.` +\n ` Your current origin is ${location.origin}.`;\n }\n else {\n errorMessage = 'OneSignal: This web push config can not be used on the current site.';\n }\n break;\n case SdkInitErrorKind.MultipleInitialization:\n errorMessage = `OneSignal: The OneSignal web SDK can only be initialized once. Extra initializations ` +\n `are ignored. Please remove calls initializing the SDK more than once.`;\n break;\n case SdkInitErrorKind.MissingSafariWebId:\n errorMessage = `OneSignal: Safari browser support on Mac OS X requires the Safari web platform` +\n ` to be enabled. Please see the Safari Support steps in our web setup guide.`;\n break;\n case SdkInitErrorKind.Unknown:\n errorMessage = 'OneSignal: An unknown initialization error occurred.';\n break;\n }\n super(errorMessage);\n this.reason = SdkInitErrorKind[reason];\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md\n * #extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, SdkInitError.prototype);\n }\n}\n//# sourceMappingURL=SdkInitError.js.map","export var OutcomeAttributionType;\n(function (OutcomeAttributionType) {\n OutcomeAttributionType[OutcomeAttributionType[\"Direct\"] = 1] = \"Direct\";\n OutcomeAttributionType[OutcomeAttributionType[\"Indirect\"] = 2] = \"Indirect\";\n OutcomeAttributionType[OutcomeAttributionType[\"Unattributed\"] = 3] = \"Unattributed\";\n OutcomeAttributionType[OutcomeAttributionType[\"NotSupported\"] = 4] = \"NotSupported\";\n})(OutcomeAttributionType || (OutcomeAttributionType = {}));\n//# sourceMappingURL=Outcomes.js.map","import OneSignalError from \"./OneSignalError\";\nexport var NotSubscribedReason;\n(function (NotSubscribedReason) {\n NotSubscribedReason[NotSubscribedReason[\"Unknown\"] = 0] = \"Unknown\";\n NotSubscribedReason[NotSubscribedReason[\"NoDeviceId\"] = 1] = \"NoDeviceId\";\n NotSubscribedReason[NotSubscribedReason[\"NoEmailSet\"] = 2] = \"NoEmailSet\";\n NotSubscribedReason[NotSubscribedReason[\"NoSMSSet\"] = 3] = \"NoSMSSet\";\n NotSubscribedReason[NotSubscribedReason[\"OptedOut\"] = 4] = \"OptedOut\";\n})(NotSubscribedReason || (NotSubscribedReason = {}));\nexport class NotSubscribedError extends OneSignalError {\n constructor(reason) {\n let errorMessage;\n switch (reason) {\n case NotSubscribedReason.Unknown || NotSubscribedReason.NoDeviceId:\n errorMessage = 'This operation can only be performed after the user is subscribed.';\n break;\n case NotSubscribedReason.NoEmailSet:\n errorMessage = 'No email is currently set.';\n break;\n case NotSubscribedReason.NoSMSSet:\n errorMessage = 'No sms is currently set.';\n break;\n case NotSubscribedReason.OptedOut:\n errorMessage = `The user has manually opted out of receiving of notifications. ` +\n `This operation can only be performed after the user is fully resubscribed.`;\n break;\n }\n super(errorMessage);\n this.reason = NotSubscribedReason[reason];\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md\n * #extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, NotSubscribedError.prototype);\n }\n}\n//# sourceMappingURL=NotSubscribedError.js.map","import OneSignalError from \"./OneSignalError\";\nexport var OneSignalApiErrorKind;\n(function (OneSignalApiErrorKind) {\n OneSignalApiErrorKind[OneSignalApiErrorKind[\"MissingAppId\"] = 0] = \"MissingAppId\";\n})(OneSignalApiErrorKind || (OneSignalApiErrorKind = {}));\nexport class OneSignalApiError extends OneSignalError {\n constructor(reason) {\n let errorMessage;\n switch (reason) {\n case OneSignalApiErrorKind.MissingAppId:\n errorMessage = 'The API call is missing an app ID.';\n break;\n }\n super(errorMessage);\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md\n * #extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, OneSignalApiError.prototype);\n }\n}\n//# sourceMappingURL=OneSignalApiError.js.map","import { OneSignalApiBase } from \"./OneSignalApiBase\";\nimport { SubscriptionStateKind } from \"./models/SubscriptionStateKind\";\nimport Log from \"./libraries/Log\";\nimport { Utils } from \"./context/shared/utils/Utils\";\nimport { OutcomeAttributionType } from \"./models/Outcomes\";\nexport class OneSignalApiSW {\n static async downloadServerAppConfig(appId) {\n Utils.enforceAppId(appId);\n return await new Promise((resolve, _reject) => {\n resolve(OneSignalApiBase.get(`sync/${appId}/web`, null));\n });\n }\n /**\n * Given a GCM or Firefox subscription endpoint or Safari device token, returns the user ID from OneSignal's server.\n * Used if the user clears his or her IndexedDB database and we need the user ID again.\n */\n static getUserIdFromSubscriptionIdentifier(appId, deviceType, identifier) {\n // Calling POST /players with an existing identifier returns us that player ID\n Utils.enforceAppId(appId);\n return OneSignalApiBase.post(\"players\", {\n app_id: appId,\n device_type: deviceType,\n identifier: identifier,\n notification_types: SubscriptionStateKind.TemporaryWebRecord,\n }).then((response) => {\n if (response && response.id) {\n return response.id;\n }\n else {\n return null;\n }\n }).catch(e => {\n Log.debug(\"Error getting user ID from subscription identifier:\", e);\n return null;\n });\n }\n static async updatePlayer(appId, playerId, options) {\n const funcToExecute = async () => {\n await OneSignalApiBase.put(`players/${playerId}`, Object.assign({ app_id: appId }, options));\n };\n return await Utils.enforceAppIdAndPlayerId(appId, playerId, funcToExecute);\n }\n static async updateUserSession(userId, serializedDeviceRecord) {\n const funcToExecute = async () => {\n const response = await OneSignalApiBase.post(`players/${userId}/on_session`, serializedDeviceRecord);\n if (response.id) {\n // A new user ID can be returned\n return response.id;\n }\n else {\n return userId;\n }\n };\n return await Utils.enforceAppIdAndPlayerId(serializedDeviceRecord.app_id, userId, funcToExecute);\n }\n static async sendSessionDuration(appId, deviceId, sessionDuration, deviceType, attribution) {\n const funcToExecute = async () => {\n const payload = {\n app_id: appId,\n type: 1,\n state: \"ping\",\n active_time: sessionDuration,\n device_type: deviceType,\n };\n switch (attribution.type) {\n case OutcomeAttributionType.Direct:\n payload.direct = true;\n payload.notification_ids = attribution.notificationIds;\n break;\n case OutcomeAttributionType.Indirect:\n payload.direct = false;\n payload.notification_ids = attribution.notificationIds;\n break;\n default:\n break;\n }\n await OneSignalApiBase.post(`players/${deviceId}/on_focus`, payload);\n };\n Utils.enforceAppIdAndPlayerId(appId, deviceId, funcToExecute);\n }\n}\nexport default OneSignalApiSW;\n//# sourceMappingURL=OneSignalApiSW.js.map","import Database from \"../services/Database\";\nimport Event from '../Event';\nexport class PermissionUtils {\n static async triggerNotificationPermissionChanged(updateIfIdentical = false) {\n const newPermission = await OneSignal.privateGetNotificationPermission();\n const previousPermission = await Database.get('Options', 'notificationPermission');\n const shouldBeUpdated = newPermission !== previousPermission || updateIfIdentical;\n if (!shouldBeUpdated) {\n return;\n }\n await Database.put('Options', { key: 'notificationPermission', value: newPermission });\n Event.trigger(OneSignal.EVENTS.NATIVE_PROMPT_PERMISSIONCHANGED, { to: newPermission });\n }\n}\n//# sourceMappingURL=PermissionUtils.js.map","export var DeliveryPlatformKind;\n(function (DeliveryPlatformKind) {\n DeliveryPlatformKind[DeliveryPlatformKind[\"ChromeLike\"] = 5] = \"ChromeLike\";\n DeliveryPlatformKind[DeliveryPlatformKind[\"Safari\"] = 7] = \"Safari\";\n DeliveryPlatformKind[DeliveryPlatformKind[\"Firefox\"] = 8] = \"Firefox\";\n DeliveryPlatformKind[DeliveryPlatformKind[\"Email\"] = 11] = \"Email\";\n DeliveryPlatformKind[DeliveryPlatformKind[\"Edge\"] = 12] = \"Edge\";\n DeliveryPlatformKind[DeliveryPlatformKind[\"SMS\"] = 14] = \"SMS\";\n})(DeliveryPlatformKind || (DeliveryPlatformKind = {}));\n//# sourceMappingURL=DeliveryPlatformKind.js.map","import bowser from 'bowser';\nimport NotImplementedError from '../errors/NotImplementedError';\nimport { SubscriptionStateKind } from './SubscriptionStateKind';\nimport { DeviceRecord } from './DeviceRecord';\n/**\n * Describes a push notification device record.\n */\nexport class PushDeviceRecord extends DeviceRecord {\n /**\n * @param subscription Omitting this parameter does not void the record's identifier.\n */\n constructor(subscription) {\n super();\n this.subscription = subscription;\n }\n serialize() {\n const serializedBundle = super.serialize();\n if (this.subscription) {\n serializedBundle.identifier = bowser.safari ?\n this.subscription.safariDeviceToken :\n this.subscription.w3cEndpoint ? this.subscription.w3cEndpoint.toString() : null;\n serializedBundle.web_auth = this.subscription.w3cAuth;\n serializedBundle.web_p256 = this.subscription.w3cP256dh;\n }\n return serializedBundle;\n }\n static createFromPushSubscription(appId, rawPushSubscription, subscriptionState) {\n const pushRegistration = new PushDeviceRecord(rawPushSubscription);\n pushRegistration.appId = appId;\n pushRegistration.subscriptionState = rawPushSubscription ?\n SubscriptionStateKind.Subscribed :\n SubscriptionStateKind.NotSubscribed;\n if (subscriptionState) {\n pushRegistration.subscriptionState = subscriptionState;\n }\n return pushRegistration;\n }\n deserialize(_) { throw new NotImplementedError(); }\n}\n//# sourceMappingURL=PushDeviceRecord.js.map","import { DelayedPromptType, } from '../../src/models/Prompts';\nexport default class PromptsHelper {\n static isCategorySlidedownConfigured(prompts) {\n if (!prompts)\n return false;\n const options = PromptsHelper.getFirstSlidedownPromptOptionsWithType(prompts, DelayedPromptType.Category);\n if (!!options) {\n return (!!options.categories && options.categories.length > 0);\n }\n return false;\n }\n /**\n * Is Category Slidedown Configured (version 1 config schema)\n * @param {SlidedownOptionsVersion1} options\n * @returns boolean\n */\n static isCategorySlidedownConfiguredVersion1(options) {\n var _a, _b;\n return (((_b = (_a = options === null || options === void 0 ? void 0 : options.categories) === null || _a === void 0 ? void 0 : _a.tags) === null || _b === void 0 ? void 0 : _b.length) || 0) > 0;\n }\n static getFirstSlidedownPromptOptionsWithType(prompts, type) {\n return prompts ? prompts.filter(options => options.type === type)[0] : undefined;\n }\n static isSlidedownAutoPromptConfigured(prompts) {\n if (!prompts) {\n return false;\n }\n for (let i = 0; i < prompts.length; i++) {\n if (prompts[i].autoPrompt)\n return true;\n }\n return false;\n }\n static isSlidedownPushDependent(slidedownType) {\n return slidedownType === DelayedPromptType.Push || slidedownType === DelayedPromptType.Category;\n }\n}\n//# sourceMappingURL=PromptsHelper.js.map","import bowser from 'bowser';\nimport Environment from '../Environment';\nimport NotImplementedError from '../errors/NotImplementedError';\nimport { DeliveryPlatformKind } from './DeliveryPlatformKind';\nimport { OneSignalUtils } from \"../utils/OneSignalUtils\";\n/**\n * Describes the fields of a OneSignal \"player\" device record.\n *\n * This is used when creating or modifying push and email records.\n */\nexport class DeviceRecord {\n constructor() {\n // TODO: Possible implementation for appId initialization\n // this.appId = OneSignal.context.appConfig.appId;\n this.language = Environment.getLanguage();\n this.timezone = new Date().getTimezoneOffset() * -60;\n this.timezoneId = Intl.DateTimeFormat().resolvedOptions().timeZone;\n const browserVersion = parseInt(String(bowser.version), 10);\n this.browserVersion = isNaN(browserVersion) ? -1 : browserVersion;\n this.deviceModel = navigator.platform;\n this.sdkVersion = Environment.version().toString();\n this.deliveryPlatform = this.getDeliveryPlatform();\n // Unimplemented properties are appId, subscriptionState, and subscription\n }\n isSafari() {\n return bowser.safari && window.safari !== undefined && window.safari.pushNotification !== undefined;\n }\n getDeliveryPlatform() {\n // For testing purposes, allows changing the browser user agent\n const browser = OneSignalUtils.redetectBrowserUserAgent();\n if (this.isSafari()) {\n return DeliveryPlatformKind.Safari;\n }\n else if (browser.firefox) {\n return DeliveryPlatformKind.Firefox;\n }\n else if (browser.msedge) {\n return DeliveryPlatformKind.Edge;\n }\n else {\n return DeliveryPlatformKind.ChromeLike;\n }\n }\n serialize() {\n const serializedBundle = {\n device_type: this.deliveryPlatform,\n language: this.language,\n timezone: this.timezone,\n timezone_id: this.timezoneId,\n device_os: this.browserVersion,\n device_model: this.deviceModel,\n sdk: this.sdkVersion,\n notification_types: this.subscriptionState,\n };\n if (this.appId) {\n serializedBundle.app_id = this.appId;\n }\n if (this.externalUserId) {\n serializedBundle.external_user_id = this.externalUserId;\n }\n if (this.externalUserIdAuthHash) {\n serializedBundle.external_user_id_auth_hash = this.externalUserIdAuthHash;\n }\n return serializedBundle;\n }\n deserialize(_) { throw new NotImplementedError(); }\n}\n//# sourceMappingURL=DeviceRecord.js.map","export class SMSProfile {\n constructor(smsId, smsNumber, identifierAuthHash) {\n this.subscriptionId = smsId;\n this.identifier = smsNumber;\n this.identifierAuthHash = identifierAuthHash;\n }\n serialize() {\n return {\n identifierAuthHash: this.identifierAuthHash,\n smsNumber: this.identifier,\n smsId: this.subscriptionId,\n };\n }\n static deserialize(bundle) {\n return new SMSProfile(bundle.smsId, bundle.smsNumber, bundle.identifierAuthHash);\n }\n}\n//# sourceMappingURL=SMSProfile.js.map","export class EmailProfile {\n constructor(emailId, emailAddress, identifierAuthHash) {\n this.subscriptionId = emailId;\n this.identifier = emailAddress;\n this.identifierAuthHash = identifierAuthHash;\n }\n serialize() {\n return {\n identifierAuthHash: this.identifierAuthHash,\n emailAddress: this.identifier,\n emailId: this.subscriptionId,\n };\n }\n static deserialize(bundle) {\n return new EmailProfile(bundle.emailId, bundle.emailAddress, bundle.identifierAuthHash);\n }\n}\n//# sourceMappingURL=EmailProfile.js.map","import Log from \"../../libraries/sw/Log\";\nconst doNothing = () => {\n Log.debug(\"Do nothing\");\n};\nexport function cancelableTimeout(callback, delayInSeconds) {\n const delayInMilliseconds = delayInSeconds * 1000;\n let timerId;\n let clearTimeoutHandle = undefined;\n const promise = new Promise((resolve, reject) => {\n let startedExecution = false;\n timerId = self.setTimeout(async () => {\n startedExecution = true;\n try {\n await callback();\n resolve();\n }\n catch (e) {\n Log.error(\"Failed to execute callback\", e);\n reject();\n }\n }, delayInMilliseconds);\n clearTimeoutHandle = () => {\n Log.debug(\"Cancel called\");\n self.clearTimeout(timerId);\n if (!startedExecution) {\n resolve();\n }\n };\n });\n if (!clearTimeoutHandle) {\n Log.warn(\"clearTimeoutHandle was not assigned.\");\n return {\n promise,\n cancel: doNothing,\n };\n }\n return {\n promise,\n cancel: clearTimeoutHandle,\n };\n}\n//# sourceMappingURL=CancelableTimeout.js.map","import Log from \"../../libraries/Log\";\nexport default class ServiceWorkerUtilHelper {\n // Get the service worker based on a relative scope.\n // A relative scope is required as a domain can have none to many service workers installed.\n static async getRegistration(scope) {\n try {\n // Adding location.origin to negate the effects of a possible <base> html tag the page may have.\n const url = location.origin + scope;\n return await navigator.serviceWorker.getRegistration(url);\n }\n catch (e) {\n // This could be null in an HTTP context or error if the user doesn't accept cookies\n Log.warn(\"[Service Worker Status] Error Checking service worker registration\", scope, e);\n return null;\n }\n }\n // A ServiceWorkerRegistration will have a ServiceWorker in 1 of 3 states, get which ever is available.\n static getAvailableServiceWorker(registration) {\n const availableWorker = registration.active || registration.installing || registration.waiting;\n // This never be null unless ServiceWorkerRegistration is pointing to a worker that is completely gone.\n if (!availableWorker) {\n Log.warn(\"Could not find an available ServiceWorker instance!\");\n }\n return availableWorker;\n }\n}\n//# sourceMappingURL=ServiceWorkerUtilHelper.js.map","export var TestEnvironmentKind;\n(function (TestEnvironmentKind) {\n TestEnvironmentKind[\"None\"] = \"None\";\n TestEnvironmentKind[\"UnitTesting\"] = \"Unit Testing\";\n})(TestEnvironmentKind || (TestEnvironmentKind = {}));\n//# sourceMappingURL=TestEnvironmentKind.js.map","export var NotificationPermission;\n(function (NotificationPermission) {\n /**\n * The user has not granted notification permissions and may have just dismissed the notification permission prompt.\n */\n NotificationPermission[\"Default\"] = \"default\";\n /**\n * The user has granted notification permissions.\n */\n NotificationPermission[\"Granted\"] = \"granted\";\n /**\n * The user has blocked notifications.\n */\n NotificationPermission[\"Denied\"] = \"denied\";\n})(NotificationPermission || (NotificationPermission = {}));\n//# sourceMappingURL=NotificationPermission.js.map","import OneSignalUtils from '../utils/OneSignalUtils';\nimport bowser from 'bowser';\nimport { InvalidArgumentError, InvalidArgumentReason } from '../errors/InvalidArgumentError';\nimport { NotificationPermission } from '../models/NotificationPermission';\nimport SdkEnvironment from '../managers/SdkEnvironment';\nimport LocalStorage from '../utils/LocalStorage';\n/**\n * A permission manager to consolidate the different quirks of obtaining and evaluating permissions\n * across Safari, Chrome, and Firefox.\n */\nexport default class PermissionManager {\n static get STORED_PERMISSION_KEY() {\n return 'storedNotificationPermission';\n }\n /**\n * Returns an interpreted version of the browser's notification permission.\n *\n * On some environments, it isn't possible to obtain the actual notification\n * permission. For example, starting with Chrome 62+, cross-origin iframes and\n * insecure origins can no longer accurately detect the default notification\n * permission state.\n *\n * For cross-origin iframes, returned permissions are correct except that\n * \"denied\" is returned instead of \"default\".\n *\n * For insecure origins, returned permissions are always \"denied\". This\n * differs from cross-origin iframes where the cross-origin iframes are\n * acurrate if returning \"granted\", but insecure origins will always return\n * \"denied\" regardless of the actual permission.\n *\n * This method therefore returns the notification permission best suited for\n * our SDK, and it may not always be accurate. On most environments (i.e. not\n * Chrome 62+), the returned permission will be accurate.\n *\n * @param safariWebId The Safari web ID necessary to access the permission\n * state on Safari.\n */\n async getNotificationPermission(safariWebId) {\n const reportedPermission = await this.getReportedNotificationPermission(safariWebId);\n if (await this.isPermissionEnvironmentAmbiguous(reportedPermission))\n return await this.getInterpretedAmbiguousPermission(reportedPermission);\n return reportedPermission;\n }\n /**\n * Returns the browser's actual notification permission as reported without any modifications.\n *\n * One challenge is determining the frame context our permission query needs to run in:\n *\n * - For a regular top-level HTTPS site, query our current top-level frame\n *\n * - For a custom web push setup in a child HTTPS iframe, query our current child iframe (even\n * though the returned permission is ambiguous on Chrome 62+ if our origin is different from\n * that of the top-level frame)\n *\n * - For a regular HTTP site, query OneSignal's child subdomain.os.tc or subdomain.onesignal.com\n * iframe\n *\n * - For a regular HTTP site embedded in a child iframe, still query the nested child's\n * OneSignal subdomain.os.tc or subdomain.onesignal.com iframe\n *\n * This simplifies into determining whether the web push setup is using OneSignal's subdomain. If\n * not, we assume the current frame context, regardless of whether it is a child or top-level\n * frame, is the current context to run the permission query in.\n *\n * @param safariWebId The Safari web ID necessary to access the permission state on Safari.\n */\n async getReportedNotificationPermission(safariWebId) {\n if (bowser.safari)\n return PermissionManager.getSafariNotificationPermission(safariWebId);\n // Is this web push setup using subdomain.os.tc or subdomain.onesignal.com?\n if (OneSignalUtils.isUsingSubscriptionWorkaround())\n return await this.getOneSignalSubdomainNotificationPermission(safariWebId);\n else {\n const reportedPermission = this.getW3cNotificationPermission();\n if (await this.isPermissionEnvironmentAmbiguous(reportedPermission)) {\n return await this.getInterpretedAmbiguousPermission(reportedPermission);\n }\n return this.getW3cNotificationPermission();\n }\n }\n /**\n * Returns the Safari browser's notification permission as reported by the browser.\n *\n * @param safariWebId The Safari web ID necessary to access the permission state on Safari.\n */\n static getSafariNotificationPermission(safariWebId) {\n if (safariWebId)\n return window.safari.pushNotification.permission(safariWebId).permission;\n throw new InvalidArgumentError('safariWebId', InvalidArgumentReason.Empty);\n }\n /**\n * Returns the notification permission as reported by the browser for non-Safari browsers. This\n * includes Chrome, Firefox, Opera, Yandex, and every browser following the Notification API\n * standard.\n */\n getW3cNotificationPermission() {\n return Notification.permission;\n }\n /**\n * Returns the notification permission as reported by the browser for the OneSignal subdomain\n * iframe.\n *\n * @param safariWebId The Safari web ID necessary to access the permission state on Safari.\n */\n async getOneSignalSubdomainNotificationPermission(safariWebId) {\n return new Promise(resolve => {\n OneSignal.proxyFrameHost.message(OneSignal.POSTMAM_COMMANDS.REMOTE_NOTIFICATION_PERMISSION, { safariWebId: safariWebId }, (reply) => {\n const remoteNotificationPermission = reply.data;\n resolve(remoteNotificationPermission);\n });\n });\n }\n /**\n * To interpret the browser's reported notification permission, we need to know whether we're in\n * an environment where the returned permission should be treated ambiguously.\n *\n * The reported permission should only be treated ambiguously if:\n *\n * - We're not on Safari or Firefox (Chromium, Chrome, Opera, and Yandex will all eventually\n * share the same Chrome 62+ codebase)\n *\n * - And the reported permission is \"denied\"\n *\n * - And the current frame context is either a cross-origin iframe or insecure\n */\n async isPermissionEnvironmentAmbiguous(permission) {\n // For testing purposes, allows changing the browser user agent\n const browser = OneSignalUtils.redetectBrowserUserAgent();\n return (!browser.safari &&\n !browser.firefox &&\n permission === NotificationPermission.Denied &&\n (this.isCurrentFrameContextCrossOrigin() ||\n await SdkEnvironment.isFrameContextInsecure() ||\n OneSignalUtils.isUsingSubscriptionWorkaround()));\n }\n /**\n * Returns true if we're a cross-origin iframe.\n *\n * This means:\n *\n * - We're not the top-level frame\n * - We're unable to access to the top-level frame's origin, or we can access the origin but it\n * is different. On most browsers, accessing the top-level origin should throw an exception.\n */\n isCurrentFrameContextCrossOrigin() {\n let topFrameOrigin;\n try {\n // Accessing a cross-origin top-level frame's origin should throw an error\n topFrameOrigin = window.top.location.origin;\n }\n catch (e) {\n // We're in a cross-origin child iframe\n return true;\n }\n return window.top !== window &&\n topFrameOrigin !== window.location.origin;\n }\n /**\n * To workaround Chrome 62+'s permission ambiguity for \"denied\" permissions,\n * we assume the permission is \"default\" until we actually record the\n * permission being \"denied\" or \"granted\".\n *\n * This allows our best-effort approach to subscribe new users, and upon\n * subscribing, if we discover the actual permission to be denied, we record\n * this for next time.\n *\n * @param reportedPermission The notification permission as reported by the\n * browser without any modifications.\n */\n async getInterpretedAmbiguousPermission(reportedPermission) {\n switch (reportedPermission) {\n case NotificationPermission.Denied:\n const storedPermission = this.getStoredPermission();\n if (storedPermission) {\n // If we've recorded the last known actual browser permission, return that\n return storedPermission;\n }\n else {\n // If we don't have any stored permission, assume default\n return NotificationPermission.Default;\n }\n default:\n return reportedPermission;\n }\n }\n getStoredPermission() {\n return LocalStorage.getStoredPermission();\n }\n setStoredPermission(permission) {\n LocalStorage.setStoredPermission(permission);\n }\n async updateStoredPermission() {\n // TODO verify if `OneSignal.config.safariWebId` should be passed as a parameter\n const permission = await this.getNotificationPermission();\n return this.setStoredPermission(permission);\n }\n}\n//# sourceMappingURL=PermissionManager.js.map","import { NotificationPermission } from '../models/NotificationPermission';\nimport PermissionManager from '../managers/PermissionManager';\nconst IS_OPTED_OUT = \"isOptedOut\";\nconst IS_PUSH_NOTIFICATIONS_ENABLED = \"isPushNotificationsEnabled\";\nconst PAGE_VIEWS = \"os_pageViews\";\nexport default class LocalStorage {\n static getIsOptedOut() {\n return localStorage.getItem(IS_OPTED_OUT) === \"true\";\n }\n static getIsPushNotificationsEnabled() {\n return localStorage.getItem(IS_PUSH_NOTIFICATIONS_ENABLED) === \"true\";\n }\n static setIsOptedOut(value) {\n localStorage.setItem(IS_OPTED_OUT, value.toString());\n }\n static setIsPushNotificationsEnabled(value) {\n localStorage.setItem(IS_PUSH_NOTIFICATIONS_ENABLED, value.toString());\n }\n static setStoredPermission(value) {\n localStorage.setItem(PermissionManager.STORED_PERMISSION_KEY, value);\n }\n static getStoredPermission() {\n var permission = localStorage.getItem(PermissionManager.STORED_PERMISSION_KEY) || \"default\";\n switch (permission) {\n case \"granted\":\n return NotificationPermission.Granted;\n case \"denied\":\n return NotificationPermission.Denied;\n default:\n return NotificationPermission.Default;\n }\n }\n static setLocalPageViewCount(count) {\n localStorage.setItem(PAGE_VIEWS, count.toString());\n }\n static getLocalPageViewCount() {\n return Number(localStorage.getItem(PAGE_VIEWS));\n }\n}\n//# sourceMappingURL=LocalStorage.js.map","import SdkEnvironment from \"../managers/SdkEnvironment\";\nimport { WindowEnvironmentKind } from \"../models/WindowEnvironmentKind\";\nimport Log from \"../libraries/Log\";\nimport LocalStorage from '../utils/LocalStorage';\nexport class PageViewManager {\n constructor() {\n this.incrementedPageViewCount = false;\n }\n getPageViewCount() {\n try {\n /*\n sessionStorage may be supported by the browser but may not be available\n as an API in incognito mode and in cases where the user disables\n third-party cookies on some browsers.\n */\n const pageViewCountStr = sessionStorage.getItem(PageViewManager.SESSION_STORAGE_KEY_NAME);\n const pageViewCount = pageViewCountStr ? parseInt(pageViewCountStr) : 0;\n if (isNaN(pageViewCount)) {\n return 0;\n }\n else {\n return pageViewCount;\n }\n }\n catch (e) {\n /*\n If we're in incognito mode or sessionStorage is otherwise unsupported,\n pretend we're starting our first session.\n */\n return 0;\n }\n }\n setPageViewCount(sessionCount) {\n try {\n sessionStorage.setItem(PageViewManager.SESSION_STORAGE_KEY_NAME, sessionCount.toString());\n if (SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.OneSignalSubscriptionPopup) {\n // If we're setting sessionStorage and we're in an Popup, we need to also set sessionStorage on the\n // main page\n if (OneSignal.subscriptionPopup) {\n OneSignal.subscriptionPopup.message(OneSignal.POSTMAM_COMMANDS.SET_SESSION_COUNT);\n }\n }\n }\n catch (e) {\n /*\n If sessionStorage isn't available, don't error.\n */\n }\n }\n /**\n * Increments:\n * - session pageView count AND\n * - total pageView count\n *\n * at most once for the current page view.\n *\n * A flag is set to prevent incrementing the session count more than once for\n * the current page view. If the page is refreshed, this in-memory variable\n * will be automatically reset. Because of this, regardless of the number of\n * times this method is called on the current page view, the page view count\n * will only be incremented once.\n *\n * LocalStorage pageView count added for use in Delayed Prompts feature. This\n * pageView count persists even past sessions since it is saved to local stor-\n * age (as opposed to Session Storage which persists only for that tab)\n */\n incrementPageViewCount() {\n if (this.incrementedPageViewCount) {\n // For this method, we don't want to increment the session count more than\n // once per pageview\n return;\n }\n const newCountSingleTab = this.getPageViewCount() + 1;\n const newCountAcrossTabs = this.getLocalPageViewCount() + 1;\n this.setPageViewCount(newCountSingleTab);\n this.setLocalPageViewCount(newCountAcrossTabs);\n this.incrementedPageViewCount = true;\n Log.debug(`Incremented page view count: newCountSingleTab: ${newCountSingleTab},\n newCountAccrossTabs: ${newCountAcrossTabs}.`);\n }\n simulatePageNavigationOrRefresh() {\n this.incrementedPageViewCount = false;\n }\n /**\n * Returns true if this page is running OneSignal for the first time and has\n * not been navigated or refreshed.\n */\n isFirstPageView() {\n return this.getPageViewCount() === 1;\n }\n /**\n * Returns Page Views saved to Local Storage (Persists Longer than Single Session)\n */\n getLocalPageViewCount() {\n return LocalStorage.getLocalPageViewCount();\n }\n /**\n * Sets Page Views to Local Storage\n */\n setLocalPageViewCount(count) {\n LocalStorage.setLocalPageViewCount(count);\n }\n}\nPageViewManager.SESSION_STORAGE_KEY_NAME = \"onesignal-pageview-count\";\n//# sourceMappingURL=PageViewManager.js.map","import { InvalidArgumentError, InvalidArgumentReason } from '../errors/InvalidArgumentError';\n/**\n * Represents a normalized path.\n *\n * Paths spaces are trimmed.\n * Paths without file names will never contain trailing slashes, except for empty paths.\n */\nexport default class Path {\n constructor(path) {\n if (!path)\n throw new InvalidArgumentError('path', InvalidArgumentReason.Empty);\n this.path = path.trim();\n }\n getQueryString() {\n // If there are no ? characters, return null\n // If there are multiple ?, return the substring starting after the first ? all the way to the end\n const indexOfDelimiter = this.path.indexOf('?');\n if (indexOfDelimiter === -1) {\n return null;\n }\n if (this.path.length > indexOfDelimiter) {\n // Return the substring *after the first ? to the end\n return this.path.substring(indexOfDelimiter + 1);\n }\n else {\n // The last character is ?\n return null;\n }\n }\n getWithoutQueryString() {\n return this.path.split(Path.QUERY_STRING)[0];\n }\n getFileName() {\n var _a;\n return (_a = this.getWithoutQueryString().split('\\\\').pop()) === null || _a === void 0 ? void 0 : _a.split('/').pop();\n }\n getFileNameWithQuery() {\n var _a;\n return (_a = this.path.split('\\\\').pop()) === null || _a === void 0 ? void 0 : _a.split('/').pop();\n }\n getFullPath() {\n return this.path;\n }\n getPathWithoutFileName() {\n const newPath = this.getWithoutQueryString();\n const fileNameIndex = newPath.lastIndexOf(this.getFileName());\n let pathWithoutFileName = newPath.substring(0, fileNameIndex);\n pathWithoutFileName = pathWithoutFileName.replace(/[\\\\\\/]$/, '');\n return pathWithoutFileName;\n }\n}\nPath.QUERY_STRING = '?';\n//# sourceMappingURL=Path.js.map","import OneSignalError from './OneSignalError';\nexport class ServiceWorkerRegistrationError extends OneSignalError {\n constructor(status, statusText) {\n super(`Registration of a Service Worker failed.`);\n this.status = status;\n this.statusText = statusText;\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, ServiceWorkerRegistrationError.prototype);\n }\n}\nexport default ServiceWorkerRegistrationError;\n//# sourceMappingURL=ServiceWorkerRegistrationError.js.map","import Environment from '../Environment';\nimport { WorkerMessengerCommand } from '../libraries/WorkerMessenger';\nimport Path from '../models/Path';\nimport SdkEnvironment from '../managers/SdkEnvironment';\nimport Database from '../services/Database';\nimport { IntegrationKind } from '../models/IntegrationKind';\nimport { WindowEnvironmentKind } from '../models/WindowEnvironmentKind';\nimport NotImplementedError from '../errors/NotImplementedError';\nimport Log from '../libraries/Log';\nimport Event from '../Event';\nimport ServiceWorkerRegistrationError from \"../errors/ServiceWorkerRegistrationError\";\nimport OneSignalUtils from \"../utils/OneSignalUtils\";\nimport ServiceWorkerHelper, { ServiceWorkerActiveState } from \"../helpers/ServiceWorkerHelper\";\nimport { Utils } from \"../context/shared/utils/Utils\";\nimport ServiceWorkerUtilHelper from \"../helpers/page/ServiceWorkerUtilHelper\";\nexport class ServiceWorkerManager {\n constructor(context, config) {\n this.context = context;\n this.config = config;\n }\n // Gets details on the OneSignal service-worker (if any)\n async getRegistration() {\n return await ServiceWorkerUtilHelper.getRegistration(this.config.registrationOptions.scope);\n }\n async getActiveState() {\n /*\n Note: This method can only be called on a secure origin. On an insecure\n origin, it'll throw on getRegistration().\n */\n const integration = await SdkEnvironment.getIntegration();\n if (integration === IntegrationKind.InsecureProxy) {\n /* Service workers are not accessible on insecure origins */\n return ServiceWorkerActiveState.Indeterminate;\n }\n else if (integration === IntegrationKind.SecureProxy) {\n /* If the site setup is secure proxy, we're either on the top frame without access to the\n registration, or the child proxy frame that does have access to the registration. */\n const env = SdkEnvironment.getWindowEnv();\n switch (env) {\n case WindowEnvironmentKind.Host:\n case WindowEnvironmentKind.CustomIframe:\n /* Both these top-ish frames will need to ask the proxy frame to access the service worker\n registration */\n const proxyFrameHost = OneSignal.proxyFrameHost;\n if (!proxyFrameHost) {\n /* On init, this function may be called. Return a null state for now */\n return ServiceWorkerActiveState.Indeterminate;\n }\n else {\n return await proxyFrameHost.runCommand(OneSignal.POSTMAM_COMMANDS.SERVICE_WORKER_STATE);\n }\n case WindowEnvironmentKind.OneSignalSubscriptionPopup:\n /* This is a top-level frame, so it can access the service worker registration */\n break;\n case WindowEnvironmentKind.OneSignalSubscriptionModal:\n throw new NotImplementedError();\n }\n }\n const workerRegistration = await this.context.serviceWorkerManager.getRegistration();\n if (!workerRegistration) {\n return ServiceWorkerActiveState.None;\n }\n // We are now; 1. Getting the filename of the SW; 2. Checking if it is ours or a 3rd parties.\n const swFileName = ServiceWorkerManager.activeSwFileName(workerRegistration);\n const workerState = this.swActiveStateByFileName(swFileName);\n return workerState;\n }\n // Get the file name of the active ServiceWorker\n static activeSwFileName(workerRegistration) {\n const serviceWorker = ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration);\n if (!serviceWorker) {\n return null;\n }\n const workerScriptPath = new URL(serviceWorker.scriptURL).pathname;\n const swFileName = new Path(workerScriptPath).getFileName();\n // If the current service worker is Akamai's\n if (swFileName == \"akam-sw.js\") {\n // Check if its importing a ServiceWorker under it's \"othersw\" query param\n const searchParams = new URLSearchParams(new URL(serviceWorker.scriptURL).search);\n const importedSw = searchParams.get(\"othersw\");\n if (importedSw) {\n Log.debug(\"Found a ServiceWorker under Akamai's akam-sw.js?othersw=\", importedSw);\n return new Path(new URL(importedSw).pathname).getFileName();\n }\n }\n return swFileName;\n }\n // Check if the ServiceWorker file name is ours or a third party's\n swActiveStateByFileName(fileName) {\n if (!fileName)\n return ServiceWorkerActiveState.None;\n if (fileName == this.config.workerPath.getFileName())\n return ServiceWorkerActiveState.OneSignalWorker;\n return ServiceWorkerActiveState.ThirdParty;\n }\n async getWorkerVersion() {\n return new Promise(async (resolve) => {\n if (OneSignalUtils.isUsingSubscriptionWorkaround()) {\n const proxyFrameHost = OneSignal.proxyFrameHost;\n if (!proxyFrameHost) {\n /* On init, this function may be called. Return a null state for now */\n resolve(NaN);\n }\n else {\n const proxyWorkerVersion = await proxyFrameHost.runCommand(OneSignal.POSTMAM_COMMANDS.GET_WORKER_VERSION);\n resolve(proxyWorkerVersion);\n }\n }\n else {\n this.context.workerMessenger.once(WorkerMessengerCommand.WorkerVersion, workerVersion => {\n resolve(workerVersion);\n });\n await this.context.workerMessenger.unicast(WorkerMessengerCommand.WorkerVersion);\n }\n });\n }\n async shouldInstallWorker() {\n // 1. Does the browser support ServiceWorkers?\n if (!Environment.supportsServiceWorkers())\n return false;\n // 2. Is OneSignal initialized?\n if (!OneSignal.config)\n return false;\n // 3. Will the service worker be installed on os.tc instead of the current domain?\n if (OneSignal.config.subdomain) {\n // No, if configured to use our subdomain (AKA HTTP setup) AND this is on their page (HTTP or HTTPS).\n // But since safari does not need subscription workaround, installing SW for session tracking.\n if (OneSignal.environmentInfo.browserType !== \"safari\" &&\n SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.Host) {\n return false;\n }\n }\n // 4. Is a OneSignal ServiceWorker not installed now?\n // If not and notification permissions are enabled we should install.\n // This prevents an unnecessary install of the OneSignal worker which saves bandwidth\n const workerState = await this.getActiveState();\n Log.debug(\"[shouldInstallWorker] workerState\", workerState);\n if (workerState === ServiceWorkerActiveState.None || workerState === ServiceWorkerActiveState.ThirdParty) {\n const permission = await OneSignal.context.permissionManager.getNotificationPermission(OneSignal.config.safariWebId);\n const notificationsEnabled = permission === \"granted\";\n if (notificationsEnabled) {\n Log.info(\"[shouldInstallWorker] Notification Permissions enabled, will install ServiceWorker\");\n }\n return notificationsEnabled;\n }\n // 5. We have a OneSignal ServiceWorker installed, but did the path or scope of the ServiceWorker change?\n if (await this.haveParamsChanged()) {\n return true;\n }\n // 6. We have a OneSignal ServiceWorker installed, is there an update?\n return this.workerNeedsUpdate();\n }\n async haveParamsChanged() {\n // 1. No workerRegistration\n const workerRegistration = await this.context.serviceWorkerManager.getRegistration();\n if (!workerRegistration) {\n Log.info(\"[changedServiceWorkerParams] workerRegistration not found at scope\", this.config.registrationOptions.scope);\n return true;\n }\n // 2. Different scope\n const existingSwScope = new URL(workerRegistration.scope).pathname;\n const configuredSwScope = this.config.registrationOptions.scope;\n if (existingSwScope != configuredSwScope) {\n Log.info(\"[changedServiceWorkerParams] ServiceWorker scope changing\", { a_old: existingSwScope, b_new: configuredSwScope });\n return true;\n }\n // 3. Different href?, asking if (path + filename + queryParams) is different\n const availableWorker = ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration);\n const serviceWorkerHref = ServiceWorkerHelper.getServiceWorkerHref(this.config, this.context.appConfig.appId, Environment.version());\n // 3.1 If we can't get a scriptURL assume it is different\n if (!(availableWorker === null || availableWorker === void 0 ? void 0 : availableWorker.scriptURL)) {\n return true;\n }\n // 3.2 If the new serviceWorkerHref (page-env SDK version as query param) is different than existing worker URL\n if (serviceWorkerHref !== availableWorker.scriptURL) {\n Log.info(\"[changedServiceWorkerParams] ServiceWorker href changing:\", { a_old: availableWorker === null || availableWorker === void 0 ? void 0 : availableWorker.scriptURL, b_new: serviceWorkerHref });\n return true;\n }\n return false;\n }\n /**\n * Performs a service worker update by swapping out the current service worker\n * with a content-identical but differently named alternate service worker\n * file.\n */\n async workerNeedsUpdate() {\n Log.info(\"[Service Worker Update] Checking service worker version...\");\n let workerVersion;\n try {\n workerVersion = await Utils.timeoutPromise(this.getWorkerVersion(), 2000);\n }\n catch (e) {\n Log.info(\"[Service Worker Update] Worker did not reply to version query; assuming older version and updating.\");\n return true;\n }\n if (workerVersion !== Environment.version()) {\n Log.info(`[Service Worker Update] Updating service worker from ${workerVersion} --> ${Environment.version()}.`);\n return true;\n }\n Log.info(`[Service Worker Update] Service worker version is current at ${workerVersion} (no update required).`);\n return false;\n }\n async establishServiceWorkerChannel() {\n Log.debug('establishServiceWorkerChannel');\n const workerMessenger = this.context.workerMessenger;\n workerMessenger.off();\n workerMessenger.on(WorkerMessengerCommand.NotificationDisplayed, async (data) => {\n Log.debug(location.origin, 'Received notification display event from service worker.');\n await Event.trigger(OneSignal.EVENTS.NOTIFICATION_DISPLAYED, data);\n });\n workerMessenger.on(WorkerMessengerCommand.NotificationClicked, async (data) => {\n let clickedListenerCallbackCount;\n if (SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.OneSignalProxyFrame) {\n clickedListenerCallbackCount = await new Promise(resolve => {\n const proxyFrame = OneSignal.proxyFrame;\n if (proxyFrame) {\n proxyFrame.messenger.message(OneSignal.POSTMAM_COMMANDS.GET_EVENT_LISTENER_COUNT, OneSignal.EVENTS.NOTIFICATION_CLICKED, (reply) => {\n const callbackCount = reply.data;\n resolve(callbackCount);\n });\n }\n });\n }\n else\n clickedListenerCallbackCount = OneSignal.emitter.numberOfListeners(OneSignal.EVENTS.NOTIFICATION_CLICKED);\n if (clickedListenerCallbackCount === 0) {\n /*\n A site's page can be open but not listening to the\n notification.clicked event because it didn't call\n addListenerForNotificationOpened(). In this case, if there are no\n detected event listeners, we should save the event, instead of firing\n it without anybody receiving it.\n \n Or, since addListenerForNotificationOpened() only works once (you have\n to call it again each time), maybe it was only called once and the\n user isn't receiving the notification.clicked event for subsequent\n notifications on the same browser tab.\n \n Example: notificationClickHandlerMatch: 'origin', tab is clicked,\n event fires without anybody listening, calling\n addListenerForNotificationOpened() returns no results even\n though a notification was just clicked.\n */\n Log.debug('notification.clicked event received, but no event listeners; storing event in IndexedDb for later retrieval.');\n /* For empty notifications without a URL, use the current document's URL */\n let url = data.url;\n if (!data.url) {\n // Least likely to modify, since modifying this property changes the page's URL\n url = location.href;\n }\n await Database.put('NotificationOpened', { url: url, data: data, timestamp: Date.now() });\n }\n else\n await Event.trigger(OneSignal.EVENTS.NOTIFICATION_CLICKED, data);\n });\n workerMessenger.on(WorkerMessengerCommand.RedirectPage, data => {\n Log.debug(`${SdkEnvironment.getWindowEnv().toString()} Picked up command.redirect to ${data}, forwarding to host page.`);\n const proxyFrame = OneSignal.proxyFrame;\n if (proxyFrame) {\n proxyFrame.messenger.message(OneSignal.POSTMAM_COMMANDS.SERVICEWORKER_COMMAND_REDIRECT, data);\n }\n });\n workerMessenger.on(WorkerMessengerCommand.NotificationDismissed, async (data) => {\n await Event.trigger(OneSignal.EVENTS.NOTIFICATION_DISMISSED, data);\n });\n const isHttps = OneSignalUtils.isHttps();\n const isSafari = OneSignalUtils.isSafari();\n workerMessenger.on(WorkerMessengerCommand.AreYouVisible, async (incomingPayload) => {\n // For https sites in Chrome and Firefox service worker (SW) can get correct value directly.\n // For Safari, unfortunately, we need this messaging workaround because SW always gets false.\n if (isHttps && isSafari) {\n const payload = {\n timestamp: incomingPayload.timestamp,\n focused: document.hasFocus(),\n };\n await workerMessenger.directPostMessageToSW(WorkerMessengerCommand.AreYouVisibleResponse, payload);\n }\n else {\n const httpPayload = { timestamp: incomingPayload.timestamp };\n const proxyFrame = OneSignal.proxyFrame;\n if (proxyFrame) {\n proxyFrame.messenger.message(OneSignal.POSTMAM_COMMANDS.ARE_YOU_VISIBLE_REQUEST, httpPayload);\n }\n }\n });\n }\n /**\n * Installs a newer version of the OneSignal service worker.\n *\n * We have a couple different models of installing service workers:\n *\n * a) Originally, we provided users with two worker files:\n * OneSignalSDKWorker.js and OneSignalSDKUpdaterWorker.js. Two workers were\n * provided so each could be swapped with the other when the worker needed to\n * update. The contents of both workers were identical; only the filenames\n * were different, which is enough to update the worker.\n *\n * Starting with version 151510, the need for two files is no longer required.\n * We are able to update the worker automatically by always passing in the sdk\n * version as a query parameter. This is enough for the browser to detect a\n * change and re-install the worker.\n *\n * b) With AMP web push, users specify the worker file OneSignalSDKWorker.js\n * with an app ID parameter ?appId=12345. AMP web push\n * is vendor agnostic and doesn't know about OneSignal, so all relevant\n * information has to be passed to the service worker, which is the only\n * vendor-specific file.\n *\n * If AMP web push sees another worker like OneSignalSDKUpdaterWorker.js (deprecated), or\n * even the same OneSignalSDKWorker.js without the app ID query parameter, the\n * user is considered unsubscribed.\n *\n * c) Due to b's restriction, we must always install\n * OneSignalSDKWorker.js?appId=xxx. We also have to appropriately handle the\n * legacy case:\n *\n * c-1) Where developers running progressive web apps force-register\n * OneSignalSDKWorker.js\n *\n * Actually, users can customize the file names of the Service Worker but\n * it's up to them to be consistent with their naming. For AMP web push, users\n * can specify the full string to expect for the service worker. They can add\n * additional query parameters, but this must then stay consistent.\n */\n async installWorker() {\n console.log(\"Installing worker...\");\n if (!await this.shouldInstallWorker()) {\n return;\n }\n const workerState = await this.getActiveState();\n if (workerState === ServiceWorkerActiveState.ThirdParty) {\n Log.info(`[Service Worker Installation] 3rd party service worker detected.`);\n }\n const workerHref = ServiceWorkerHelper.getServiceWorkerHref(this.config, this.context.appConfig.appId, Environment.version());\n const scope = `${OneSignalUtils.getBaseUrl()}${this.config.registrationOptions.scope}`;\n Log.info(`[Service Worker Installation] Installing service worker ${workerHref} ${scope}.`);\n try {\n await navigator.serviceWorker.register(workerHref, { scope });\n }\n catch (error) {\n Log.error(`[Service Worker Installation] Installing service worker failed ${error}`);\n // Try accessing the service worker path directly to find out what the problem is and report it to OneSignal api.\n // If we are inside the popup and service worker fails to register, it's not developer's fault.\n // No need to report it to the api then.\n const env = SdkEnvironment.getWindowEnv();\n if (env === WindowEnvironmentKind.OneSignalSubscriptionPopup)\n throw error;\n const response = await fetch(workerHref);\n if (response.status === 403 || response.status === 404)\n throw new ServiceWorkerRegistrationError(response.status, response.statusText);\n throw error;\n }\n Log.debug(`[Service Worker Installation] Service worker installed.`);\n await this.establishServiceWorkerChannel();\n }\n}\n//# sourceMappingURL=ServiceWorkerManager.js.map","export var PermissionPromptType;\n(function (PermissionPromptType) {\n /**\n * The \"main\" browser native permission request dialog when prompting for local or push notification permissions.\n */\n PermissionPromptType[PermissionPromptType[\"HttpsPermissionRequest\"] = 'HTTPS permission request'] = \"HttpsPermissionRequest\";\n /**\n * The \"popup\" to subdomain.onesignal.com.\n */\n PermissionPromptType[PermissionPromptType[\"FullscreenHttpPermissionMessage\"] = 'fullscreen HTTP permission message'] = \"FullscreenHttpPermissionMessage\";\n /**\n * The full-screen HTTPS modal with a dimmed backdrop.\n */\n PermissionPromptType[PermissionPromptType[\"FullscreenHttpsPermissionMessage\"] = 'fullscreen HTTPS permission message'] = \"FullscreenHttpsPermissionMessage\";\n /**\n * The \"sliding down\" prompt.\n */\n PermissionPromptType[PermissionPromptType[\"SlidedownPermissionMessage\"] = 'slidedown permission message'] = \"SlidedownPermissionMessage\";\n /**\n * The \"notify button\".\n */\n PermissionPromptType[PermissionPromptType[\"SubscriptionBell\"] = 'subscription bell'] = \"SubscriptionBell\";\n})(PermissionPromptType || (PermissionPromptType = {}));\n//# sourceMappingURL=PermissionPromptType.js.map","import OneSignalError from \"./OneSignalError\";\nimport { PermissionPromptType } from \"../models/PermissionPromptType\";\nexport var InvalidStateReason;\n(function (InvalidStateReason) {\n InvalidStateReason[InvalidStateReason[\"MissingAppId\"] = 0] = \"MissingAppId\";\n InvalidStateReason[InvalidStateReason[\"RedundantPermissionMessage\"] = 1] = \"RedundantPermissionMessage\";\n InvalidStateReason[InvalidStateReason[\"PushPermissionAlreadyGranted\"] = 2] = \"PushPermissionAlreadyGranted\";\n InvalidStateReason[InvalidStateReason[\"UnsupportedEnvironment\"] = 3] = \"UnsupportedEnvironment\";\n InvalidStateReason[InvalidStateReason[\"MissingDomElement\"] = 4] = \"MissingDomElement\";\n InvalidStateReason[InvalidStateReason[\"ServiceWorkerNotActivated\"] = 5] = \"ServiceWorkerNotActivated\";\n InvalidStateReason[InvalidStateReason[\"NoProxyFrame\"] = 6] = \"NoProxyFrame\";\n})(InvalidStateReason || (InvalidStateReason = {}));\nexport class InvalidStateError extends OneSignalError {\n constructor(reason, extra) {\n let errorMessage;\n switch (reason) {\n case InvalidStateReason.MissingAppId:\n errorMessage = `Missing required app ID.`;\n break;\n case InvalidStateReason.RedundantPermissionMessage:\n let extraInfo = '';\n if (extra && extra.permissionPromptType)\n extraInfo = `(${PermissionPromptType[extra.permissionPromptType]})`;\n errorMessage = `Another permission message ${extraInfo} is being displayed.`;\n break;\n case InvalidStateReason.PushPermissionAlreadyGranted:\n errorMessage = `Push permission has already been granted.`;\n break;\n case InvalidStateReason.UnsupportedEnvironment:\n errorMessage = `The current environment does not support this operation.`;\n break;\n case InvalidStateReason.ServiceWorkerNotActivated:\n errorMessage = `The service worker must be activated first.`;\n break;\n case InvalidStateReason.NoProxyFrame:\n errorMessage = `No proxy frame.`;\n break;\n }\n super(errorMessage);\n this.description = InvalidStateReason[reason];\n this.reason = reason;\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md\n * #extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, InvalidStateError.prototype);\n }\n}\n//# sourceMappingURL=InvalidStateError.js.map","import OneSignalError from \"./OneSignalError\";\nexport var PushPermissionNotGrantedErrorReason;\n(function (PushPermissionNotGrantedErrorReason) {\n PushPermissionNotGrantedErrorReason[PushPermissionNotGrantedErrorReason[\"Blocked\"] = 0] = \"Blocked\";\n PushPermissionNotGrantedErrorReason[PushPermissionNotGrantedErrorReason[\"Dismissed\"] = 1] = \"Dismissed\";\n PushPermissionNotGrantedErrorReason[PushPermissionNotGrantedErrorReason[\"Default\"] = 2] = \"Default\";\n})(PushPermissionNotGrantedErrorReason || (PushPermissionNotGrantedErrorReason = {}));\nexport default class PushPermissionNotGrantedError extends OneSignalError {\n constructor(reason) {\n let errorMessage;\n switch (reason) {\n case PushPermissionNotGrantedErrorReason.Dismissed:\n errorMessage = 'The user dismissed the permission prompt.';\n break;\n case PushPermissionNotGrantedErrorReason.Blocked:\n errorMessage = 'Notification permissions are blocked.';\n break;\n case PushPermissionNotGrantedErrorReason.Default:\n errorMessage = 'Notification permissions have not been granted yet.';\n break;\n }\n super(errorMessage);\n this.reason = reason;\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md\n * #extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, PushPermissionNotGrantedError.prototype);\n }\n}\n//# sourceMappingURL=PushPermissionNotGrantedError.js.map","import OneSignalError from \"./OneSignalError\";\nexport var SubscriptionErrorReason;\n(function (SubscriptionErrorReason) {\n SubscriptionErrorReason[SubscriptionErrorReason[\"InvalidSafariSetup\"] = 0] = \"InvalidSafariSetup\";\n SubscriptionErrorReason[SubscriptionErrorReason[\"Blocked\"] = 1] = \"Blocked\";\n SubscriptionErrorReason[SubscriptionErrorReason[\"Dismissed\"] = 2] = \"Dismissed\";\n})(SubscriptionErrorReason || (SubscriptionErrorReason = {}));\nexport default class SubscriptionError extends OneSignalError {\n constructor(reason) {\n let errorMessage;\n switch (reason) {\n case SubscriptionErrorReason.InvalidSafariSetup:\n errorMessage = `The Safari site URL, icon size, or push certificate ` +\n `is invalid, or Safari is in a private session.`;\n break;\n case SubscriptionErrorReason.Blocked:\n errorMessage = 'Notification permissions are blocked.';\n break;\n case SubscriptionErrorReason.Dismissed:\n errorMessage = 'The notification permission prompt was dismissed.';\n break;\n }\n super(errorMessage);\n /**\n * Important! Required to make sure the correct error type is detected during instanceof checks.\n * Same applies to all derived classes.\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md\n * #extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n Object.setPrototypeOf(this, SubscriptionError.prototype);\n }\n}\n//# sourceMappingURL=SubscriptionError.js.map","import bowser from \"bowser\";\nimport Database from \"../services/Database\";\nimport OneSignalApiShared from \"../OneSignalApiShared\";\nimport Environment from \"../Environment\";\nimport Event from \"../Event\";\nimport Log from \"../libraries/Log\";\nimport { ServiceWorkerActiveState } from \"../helpers/ServiceWorkerHelper\";\nimport SdkEnvironment from \"../managers/SdkEnvironment\";\nimport { NotificationPermission } from \"../models/NotificationPermission\";\nimport { RawPushSubscription } from \"../models/RawPushSubscription\";\nimport { SubscriptionStateKind } from \"../models/SubscriptionStateKind\";\nimport { WindowEnvironmentKind } from \"../models/WindowEnvironmentKind\";\nimport { PushDeviceRecord } from \"../models/PushDeviceRecord\";\nimport { IntegrationKind } from \"../models/IntegrationKind\";\nimport { InvalidStateError, InvalidStateReason } from \"../errors/InvalidStateError\";\nimport PushPermissionNotGrantedError from \"../errors/PushPermissionNotGrantedError\";\nimport { PushPermissionNotGrantedErrorReason } from \"../errors/PushPermissionNotGrantedError\";\nimport { SdkInitError, SdkInitErrorKind } from \"../errors/SdkInitError\";\nimport SubscriptionError from \"../errors/SubscriptionError\";\nimport { SubscriptionErrorReason } from \"../errors/SubscriptionError\";\nimport ServiceWorkerRegistrationError from \"../errors/ServiceWorkerRegistrationError\";\nimport NotImplementedError from \"../errors/NotImplementedError\";\nimport { PermissionUtils } from \"../utils/PermissionUtils\";\nimport { base64ToUint8Array } from \"../utils/Encoding\";\nexport class SubscriptionManager {\n constructor(context, config) {\n this.context = context;\n this.config = config;\n }\n static isSafari() {\n return Environment.isSafari();\n }\n /**\n * Subscribes for a web push subscription.\n *\n * This method is aware of different subscription environments like subscribing from a webpage,\n * service worker, or OneSignal HTTP popup and will select the correct method. This is intended to\n * be the single public API for obtaining a raw web push subscription (i.e. what the browser\n * returns from a successful subscription).\n */\n async subscribe(subscriptionStrategy) {\n const env = SdkEnvironment.getWindowEnv();\n switch (env) {\n case WindowEnvironmentKind.CustomIframe:\n case WindowEnvironmentKind.Unknown:\n case WindowEnvironmentKind.OneSignalProxyFrame:\n throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);\n }\n let rawPushSubscription;\n switch (env) {\n case WindowEnvironmentKind.ServiceWorker:\n rawPushSubscription = await this.subscribeFcmFromWorker(subscriptionStrategy);\n break;\n case WindowEnvironmentKind.Host:\n case WindowEnvironmentKind.OneSignalSubscriptionModal:\n case WindowEnvironmentKind.OneSignalSubscriptionPopup:\n /*\n Check our notification permission before subscribing.\n \n - If notifications are blocked, we can't subscribe.\n - If notifications are granted, the user should be completely resubscribed.\n - If notifications permissions are untouched, the user will be prompted and then\n subscribed.\n \n Subscribing is only possible on the top-level frame, so there's no permission ambiguity\n here.\n */\n if ((await OneSignal.privateGetNotificationPermission()) === NotificationPermission.Denied)\n throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Blocked);\n if (SubscriptionManager.isSafari()) {\n rawPushSubscription = await this.subscribeSafari();\n /* Now that permissions have been granted, install the service worker */\n Log.info(\"Installing SW on Safari\");\n try {\n await this.context.serviceWorkerManager.installWorker();\n Log.info(\"SW on Safari successfully installed\");\n }\n catch (e) {\n Log.error(\"SW on Safari failed to install.\");\n }\n }\n else {\n rawPushSubscription = await this.subscribeFcmFromPage(subscriptionStrategy);\n }\n break;\n default:\n throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);\n }\n return rawPushSubscription;\n }\n /**\n * Creates a device record from the provided raw push subscription and forwards this device record\n * to OneSignal to create or update the device ID.\n *\n * @param rawPushSubscription The raw push subscription obtained from calling subscribe(). This\n * can be null, in which case OneSignal's device record is set to unsubscribed.\n *\n * @param subscriptionState Describes whether the device record is subscribed, unsubscribed, or in\n * another state. By default, this is set from the availability of rawPushSubscription (exists:\n * Subscribed, null: Unsubscribed). Other use cases may result in creation of a device record that\n * warrants a special subscription state. For example, a device ID can be retrieved by providing\n * an identifier, and a new device record will be created if the identifier didn't exist. These\n * records are marked with a special subscription state for tracking purposes.\n */\n async registerSubscription(pushSubscription, subscriptionState) {\n /*\n This may be called after the RawPushSubscription has been serialized across a postMessage\n frame. This means it will only have object properties and none of the functions. We have to\n recreate the RawPushSubscription.\n \n Keep in mind pushSubscription can be null in cases where resubscription isn't possible\n (blocked permission).\n */\n if (pushSubscription) {\n pushSubscription = RawPushSubscription.deserialize(pushSubscription);\n }\n const deviceRecord = PushDeviceRecord.createFromPushSubscription(this.config.appId, pushSubscription, subscriptionState);\n let newDeviceId = undefined;\n if (await this.isAlreadyRegisteredWithOneSignal()) {\n await this.context.updateManager.sendPushDeviceRecordUpdate(deviceRecord);\n }\n else {\n newDeviceId = await this.context.updateManager.sendPlayerCreate(deviceRecord);\n if (newDeviceId) {\n await this.associateSubscriptionWithEmail(newDeviceId);\n }\n }\n const subscription = await Database.getSubscription();\n subscription.deviceId = newDeviceId;\n subscription.optedOut = false;\n if (pushSubscription) {\n if (SubscriptionManager.isSafari()) {\n subscription.subscriptionToken = pushSubscription.safariDeviceToken;\n }\n else {\n subscription.subscriptionToken = pushSubscription.w3cEndpoint ? pushSubscription.w3cEndpoint.toString() : null;\n }\n }\n else {\n subscription.subscriptionToken = null;\n }\n await Database.setSubscription(subscription);\n if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker) {\n Event.trigger(OneSignal.EVENTS.REGISTERED);\n }\n if (typeof OneSignal !== \"undefined\") {\n OneSignal._sessionInitAlreadyRunning = false;\n }\n return subscription;\n }\n /**\n * Used before subscribing for push, we request notification permissions\n * before installing the service worker to prevent non-subscribers from\n * querying our server for an updated service worker every 24 hours.\n */\n static async requestPresubscribeNotificationPermission() {\n return await SubscriptionManager.requestNotificationPermission();\n }\n async unsubscribe(strategy) {\n if (strategy === 0 /* DestroySubscription */) {\n throw new NotImplementedError();\n }\n else if (strategy === 1 /* MarkUnsubscribed */) {\n if (SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.ServiceWorker) {\n const { deviceId } = await Database.getSubscription();\n await OneSignalApiShared.updatePlayer(this.context.appConfig.appId, deviceId, {\n notification_types: SubscriptionStateKind.MutedByApi\n });\n await Database.put('Options', { key: 'optedOut', value: true });\n }\n else {\n throw new NotImplementedError();\n }\n }\n else {\n throw new NotImplementedError();\n }\n }\n /**\n * Calls Notification.requestPermission(), but returns a Promise instead of\n * accepting a callback like the actual Notification.requestPermission();\n *\n * window.Notification.requestPermission: The callback was deprecated since Gecko 46 in favor of a Promise\n */\n static async requestNotificationPermission() {\n const results = await window.Notification.requestPermission();\n // TODO: Clean up our custom NotificationPermission enum\n // in favor of TS union type NotificationPermission instead of converting\n return NotificationPermission[results];\n }\n /**\n * Called after registering a subscription with OneSignal to associate this subscription with an\n * email record if one exists.\n */\n async associateSubscriptionWithEmail(newDeviceId) {\n const emailProfile = await Database.getEmailProfile();\n if (!emailProfile.subscriptionId) {\n return;\n }\n // Update the push device record with a reference to the new email ID and email address\n await OneSignalApiShared.updatePlayer(this.config.appId, newDeviceId, {\n parent_player_id: emailProfile.subscriptionId,\n email: emailProfile.identifier\n });\n }\n async isAlreadyRegisteredWithOneSignal() {\n const { deviceId } = await Database.getSubscription();\n return !!deviceId;\n }\n subscribeSafariPromptPermission() {\n return new Promise(resolve => {\n window.safari.pushNotification.requestPermission(`${SdkEnvironment.getOneSignalApiUrl().toString()}/safari`, this.config.safariWebId, {\n app_id: this.config.appId\n }, response => {\n if (response.deviceToken) {\n resolve(response.deviceToken.toLowerCase());\n }\n else {\n resolve(null);\n }\n });\n });\n }\n async subscribeSafari() {\n const pushSubscriptionDetails = new RawPushSubscription();\n if (!this.config.safariWebId) {\n throw new SdkInitError(SdkInitErrorKind.MissingSafariWebId);\n }\n const { deviceToken: existingDeviceToken } = window.safari.pushNotification.permission(this.config.safariWebId);\n pushSubscriptionDetails.existingSafariDeviceToken = existingDeviceToken;\n if (!existingDeviceToken) {\n /*\n We're about to show the Safari native permission request. It can fail for a number of\n reasons, e.g.:\n - Setup-related reasons when developers just starting to get set up\n - Address bar URL doesn't match safari certificate allowed origins (case-sensitive)\n - Safari web ID doesn't match provided web ID\n - Browsing in a Safari private window\n - Bad icon DPI\n \n but shouldn't fail for sites that have already gotten Safari working.\n \n We'll show the permissionPromptDisplay event if the Safari user isn't already subscribed,\n otherwise an already subscribed Safari user would not see the permission request again.\n */\n Event.trigger(OneSignal.EVENTS.PERMISSION_PROMPT_DISPLAYED);\n }\n const deviceToken = await this.subscribeSafariPromptPermission();\n PermissionUtils.triggerNotificationPermissionChanged();\n if (deviceToken) {\n pushSubscriptionDetails.setFromSafariSubscription(deviceToken);\n }\n else {\n throw new SubscriptionError(SubscriptionErrorReason.InvalidSafariSetup);\n }\n return pushSubscriptionDetails;\n }\n async subscribeFcmFromPage(subscriptionStrategy) {\n /*\n Before installing the service worker, request notification permissions. If\n the visitor doesn't grant permissions, this saves bandwidth bleeding from\n an unused install service worker periodically fetching an updated version\n from our CDN.\n */\n /*\n Trigger the permissionPromptDisplay event to the best of our knowledge.\n */\n if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker &&\n Notification.permission === NotificationPermission.Default) {\n await Event.trigger(OneSignal.EVENTS.PERMISSION_PROMPT_DISPLAYED);\n const permission = await SubscriptionManager.requestPresubscribeNotificationPermission();\n /*\n Notification permission changes are already broadcast by the page's\n notificationpermissionchange handler. This means that allowing or\n denying the permission prompt will cause double events. However, the\n native event handler does not broadcast an event for dismissing the\n prompt, because going from \"default\" permissions to \"default\"\n permissions isn't a change. We specifically broadcast \"default\" to \"default\" changes.\n */\n if (permission === NotificationPermission.Default)\n await PermissionUtils.triggerNotificationPermissionChanged(true);\n // If the user did not grant push permissions, throw and exit\n switch (permission) {\n case NotificationPermission.Default:\n Log.debug('Exiting subscription and not registering worker because the permission was dismissed.');\n OneSignal._sessionInitAlreadyRunning = false;\n OneSignal._isRegisteringForPush = false;\n throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Dismissed);\n case NotificationPermission.Denied:\n Log.debug('Exiting subscription and not registering worker because the permission was blocked.');\n OneSignal._sessionInitAlreadyRunning = false;\n OneSignal._isRegisteringForPush = false;\n throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Blocked);\n }\n }\n /* Now that permissions have been granted, install the service worker */\n try {\n await this.context.serviceWorkerManager.installWorker();\n }\n catch (err) {\n if (err instanceof ServiceWorkerRegistrationError) {\n if (err.status === 403) {\n await this.context.subscriptionManager.registerFailedSubscription(SubscriptionStateKind.ServiceWorkerStatus403, this.context);\n }\n else if (err.status === 404) {\n await this.context.subscriptionManager.registerFailedSubscription(SubscriptionStateKind.ServiceWorkerStatus404, this.context);\n }\n }\n throw err;\n }\n Log.debug('[Subscription Manager] Getting OneSignal service Worker...');\n const workerRegistration = await this.context.serviceWorkerManager.getRegistration();\n if (!workerRegistration) {\n throw new Error(\"OneSignal service worker not found!\");\n }\n Log.debug('[Subscription Manager] Service worker is ready to continue subscribing.');\n return await this.subscribeWithVapidKey(workerRegistration.pushManager, subscriptionStrategy);\n }\n async subscribeFcmFromWorker(subscriptionStrategy) {\n /*\n We're running inside of the service worker.\n \n Check to make sure our registration is activated, otherwise we can't\n subscribe for push.\n \n HACK: Firefox doesn't set self.registration.active in the service worker\n context. From a non-service worker context, like\n navigator.serviceWorker.getRegistration().active, the property actually is\n set, but it's just not set within the service worker context.\n \n Because of this, we're not able to check for this property on Firefox.\n */\n const swRegistration = self.registration;\n if (!swRegistration.active && !bowser.firefox) {\n throw new InvalidStateError(InvalidStateReason.ServiceWorkerNotActivated);\n /*\n Or should we wait for the service worker to be ready?\n \n await new Promise(resolve => self.onactivate = resolve);\n */\n }\n /*\n Check to make sure push permissions have been granted.\n */\n const pushPermission = await swRegistration.pushManager.permissionState({ userVisibleOnly: true });\n if (pushPermission === 'denied') {\n throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Blocked);\n }\n else if (pushPermission === 'prompt') {\n throw new PushPermissionNotGrantedError(PushPermissionNotGrantedErrorReason.Default);\n }\n return await this.subscribeWithVapidKey(swRegistration.pushManager, subscriptionStrategy);\n }\n /**\n * Returns the correct VAPID key to use for subscription based on the browser type.\n *\n * If the VAPID key isn't present, undefined is returned instead of null.\n */\n getVapidKeyForBrowser() {\n // Specifically return undefined instead of null if the key isn't available\n let key = undefined;\n if (bowser.firefox) {\n /*\n Firefox uses VAPID for application identification instead of\n authentication, and so all apps share an identification key.\n */\n key = this.config.onesignalVapidPublicKey;\n }\n else {\n /*\n Chrome and Chrome-like browsers including Opera and Yandex use VAPID for\n authentication, and so each app uses a uniquely generated key.\n */\n key = this.config.vapidPublicKey;\n }\n if (key) {\n return base64ToUint8Array(key).buffer;\n }\n else {\n return undefined;\n }\n }\n /**\n * Uses the browser's PushManager interface to actually subscribe for a web push subscription.\n *\n * @param pushManager An instance of the browser's push manager, either from the page or from the\n * service worker.\n *\n * @param subscriptionStrategy Given an existing push subscription, describes whether the existing\n * push subscription is resubscribed as-is leaving it unchanged, or unsubscribed to make room for\n * a new push subscription.\n */\n async subscribeWithVapidKey(pushManager, subscriptionStrategy) {\n /*\n Always try subscribing using VAPID by providing an applicationServerKey, except for cases\n where the user is already subscribed, handled below.\n */\n const existingPushSubscription = await pushManager.getSubscription();\n /* Depending on the subscription strategy, handle existing subscription in various ways */\n switch (subscriptionStrategy) {\n case 0 /* ResubscribeExisting */:\n if (!existingPushSubscription)\n break;\n if (existingPushSubscription.options) {\n Log.debug(\"[Subscription Manager] An existing push subscription exists and it's options is not null.\");\n }\n else {\n Log.debug('[Subscription Manager] An existing push subscription exists and options is null. ' +\n 'Unsubscribing from push first now.');\n /*\n NOTE: Only applies to rare edge case of migrating from senderId to a VAPID subscription\n There isn't a great solution if PushSubscriptionOptions (supported on Chrome 54+) isn't\n supported.\n \n We want to subscribe the user, but we don't know whether the user was subscribed via\n GCM's manifest.json or FCM's VAPID.\n \n This bug (https://bugs.chromium.org/p/chromium/issues/detail?id=692577) shows that a\n mismatched sender ID error is possible if you subscribe via FCM's VAPID while the user\n was originally subscribed via GCM's manifest.json (fails silently).\n \n Because of this, we should unsubscribe the user from push first and then resubscribe\n them.\n */\n /* We're unsubscribing, so we want to store the created at timestamp */\n await SubscriptionManager.doPushUnsubscribe(existingPushSubscription);\n }\n break;\n case 1 /* SubscribeNew */:\n /* Since we want a new subscription every time with this strategy, just unsubscribe. */\n if (existingPushSubscription) {\n await SubscriptionManager.doPushUnsubscribe(existingPushSubscription);\n }\n break;\n }\n // Actually subscribe the user to push\n const [newPushSubscription, isNewSubscription] = await SubscriptionManager.doPushSubscribe(pushManager, this.getVapidKeyForBrowser());\n // Update saved create and expired times\n await SubscriptionManager.updateSubscriptionTime(isNewSubscription, newPushSubscription.expirationTime);\n // Create our own custom object from the browser's native PushSubscription object\n const pushSubscriptionDetails = RawPushSubscription.setFromW3cSubscription(newPushSubscription);\n if (existingPushSubscription) {\n pushSubscriptionDetails.existingW3cPushSubscription =\n RawPushSubscription.setFromW3cSubscription(existingPushSubscription);\n }\n return pushSubscriptionDetails;\n }\n static async updateSubscriptionTime(updateCreatedAt, expirationTime) {\n const bundle = await Database.getSubscription();\n if (updateCreatedAt) {\n bundle.createdAt = new Date().getTime();\n }\n bundle.expirationTime = expirationTime;\n await Database.setSubscription(bundle);\n }\n static async doPushUnsubscribe(pushSubscription) {\n Log.debug('[Subscription Manager] Unsubscribing existing push subscription.');\n const result = await pushSubscription.unsubscribe();\n Log.debug(`[Subscription Manager] Unsubscribing existing push subscription result: ${result}`);\n return result;\n }\n // Subscribes the ServiceWorker for a pushToken.\n // If there is an error doing so unsubscribe from existing and try again\n // - This handles subscribing to new server VAPID key if it has changed.\n // return type - [PushSubscription, createdNewPushSubscription(boolean)]\n static async doPushSubscribe(pushManager, applicationServerKey) {\n if (!applicationServerKey) {\n throw new Error(\"Missing required 'applicationServerKey' to subscribe for push notifications!\");\n }\n const subscriptionOptions = {\n userVisibleOnly: true,\n applicationServerKey: applicationServerKey\n };\n Log.debug('[Subscription Manager] Subscribing to web push with these options:', subscriptionOptions);\n try {\n const existingSubscription = await pushManager.getSubscription();\n return [await pushManager.subscribe(subscriptionOptions), !existingSubscription];\n }\n catch (e) {\n if (e.name == \"InvalidStateError\") {\n // This exception is thrown if the key for the existing applicationServerKey is different,\n // so we must unregister first.\n // In Chrome, e.message contains will be the following in this case for reference;\n // Registration failed - A subscription with a different applicationServerKey (or gcm_sender_id) already exists;\n // to change the applicationServerKey, unsubscribe then resubscribe.\n Log.warn(\"[Subscription Manager] Couldn't re-subscribe due to applicationServerKey changing, \" +\n \"unsubscribe and attempting to subscribe with new key.\", e);\n const subscription = await pushManager.getSubscription();\n if (subscription) {\n await SubscriptionManager.doPushUnsubscribe(subscription);\n }\n return [await pushManager.subscribe(subscriptionOptions), true];\n }\n else\n throw e; // If some other error, bubble the exception up\n }\n }\n async isSubscriptionExpiring() {\n const integrationKind = await SdkEnvironment.getIntegration();\n const windowEnv = SdkEnvironment.getWindowEnv();\n switch (integrationKind) {\n case IntegrationKind.Secure:\n return await this.isSubscriptionExpiringForSecureIntegration();\n case IntegrationKind.SecureProxy:\n if (windowEnv === WindowEnvironmentKind.Host) {\n const proxyFrameHost = OneSignal.proxyFrameHost;\n if (!proxyFrameHost) {\n throw new InvalidStateError(InvalidStateReason.NoProxyFrame);\n }\n else {\n return await proxyFrameHost.runCommand(OneSignal.POSTMAM_COMMANDS.SUBSCRIPTION_EXPIRATION_STATE);\n }\n }\n else {\n return await this.isSubscriptionExpiringForSecureIntegration();\n }\n case IntegrationKind.InsecureProxy:\n /* If we're in an insecure frame context, check the stored expiration since we can't access\n the actual push subscription. */\n const { expirationTime } = await Database.getSubscription();\n if (!expirationTime) {\n /* If an existing subscription does not have a stored expiration time, do not\n treat it as expired. The subscription may have been created before this feature was added,\n or the browser may not assign any expiration time. */\n return false;\n }\n /* The current time (in UTC) is past the expiration time (also in UTC) */\n return new Date().getTime() >= expirationTime;\n }\n }\n async isSubscriptionExpiringForSecureIntegration() {\n const serviceWorkerState = await this.context.serviceWorkerManager.getActiveState();\n if (!(serviceWorkerState === ServiceWorkerActiveState.OneSignalWorker)) {\n /* If the service worker isn't activated, there's no subscription to look for */\n return false;\n }\n const serviceWorkerRegistration = await this.context.serviceWorkerManager.getRegistration();\n if (!serviceWorkerRegistration)\n return false;\n // It's possible to get here in Safari 11.1+ version\n // since they released support for service workers but not push api.\n if (!serviceWorkerRegistration.pushManager)\n return false;\n const pushSubscription = await serviceWorkerRegistration.pushManager.getSubscription();\n // Not subscribed to web push\n if (!pushSubscription)\n return false;\n // No push subscription expiration time\n if (!pushSubscription.expirationTime)\n return false;\n let { createdAt: subscriptionCreatedAt } = await Database.getSubscription();\n if (!subscriptionCreatedAt) {\n /* If we don't have a record of when the subscription was created, set it into the future to\n guarantee expiration and obtain a new subscription */\n const ONE_YEAR = 1000 * 60 * 60 * 24 * 365;\n subscriptionCreatedAt = new Date().getTime() + ONE_YEAR;\n }\n const midpointExpirationTime = subscriptionCreatedAt + ((pushSubscription.expirationTime - subscriptionCreatedAt) / 2);\n return !!pushSubscription.expirationTime && (\n /* The current time (in UTC) is past the expiration time (also in UTC) */\n new Date().getTime() >= pushSubscription.expirationTime ||\n new Date().getTime() >= midpointExpirationTime);\n }\n /**\n * Returns an object describing the user's actual push subscription state and opt-out status.\n */\n async getSubscriptionState() {\n /* Safari should always return Secure because HTTP doesn't apply on Safari */\n if (SubscriptionManager.isSafari()) {\n return this.getSubscriptionStateForSecure();\n }\n const windowEnv = SdkEnvironment.getWindowEnv();\n switch (windowEnv) {\n case WindowEnvironmentKind.ServiceWorker:\n const pushSubscription = await self.registration.pushManager.getSubscription();\n const { optedOut } = await Database.getSubscription();\n return {\n subscribed: !!pushSubscription,\n optedOut: !!optedOut\n };\n default:\n /* Regular browser window environments */\n const integration = await SdkEnvironment.getIntegration();\n switch (integration) {\n case IntegrationKind.Secure:\n return this.getSubscriptionStateForSecure();\n case IntegrationKind.SecureProxy:\n switch (windowEnv) {\n case WindowEnvironmentKind.OneSignalProxyFrame:\n case WindowEnvironmentKind.OneSignalSubscriptionPopup:\n case WindowEnvironmentKind.OneSignalSubscriptionModal:\n return this.getSubscriptionStateForSecure();\n default:\n /* Re-run this command in the proxy frame */\n const proxyFrameHost = OneSignal.proxyFrameHost;\n const pushSubscriptionState = await proxyFrameHost.runCommand(OneSignal.POSTMAM_COMMANDS.GET_SUBSCRIPTION_STATE);\n return pushSubscriptionState;\n }\n case IntegrationKind.InsecureProxy:\n return await this.getSubscriptionStateForInsecure();\n default:\n throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);\n }\n }\n }\n async getSubscriptionStateForSecure() {\n const { deviceId, optedOut } = await Database.getSubscription();\n if (SubscriptionManager.isSafari()) {\n const subscriptionState = window.safari.pushNotification.permission(this.config.safariWebId);\n const isSubscribedToSafari = !!(subscriptionState.permission === \"granted\" &&\n subscriptionState.deviceToken &&\n deviceId);\n return {\n subscribed: isSubscribedToSafari,\n optedOut: !!optedOut,\n };\n }\n const workerState = await this.context.serviceWorkerManager.getActiveState();\n const workerRegistration = await this.context.serviceWorkerManager.getRegistration();\n const notificationPermission = await this.context.permissionManager.getNotificationPermission(this.context.appConfig.safariWebId);\n const isWorkerActive = (workerState === ServiceWorkerActiveState.OneSignalWorker);\n if (!workerRegistration) {\n /* You can't be subscribed without a service worker registration */\n return {\n subscribed: false,\n optedOut: !!optedOut,\n };\n }\n /*\n * Removing pushSubscription from this method due to inconsistent behavior between browsers.\n * Doesn't matter for re-subscribing, worker is present and active.\n * Previous implementation for reference:\n * const pushSubscription = await workerRegistration.pushManager.getSubscription();\n * const isPushEnabled = !!(\n * pushSubscription &&\n * deviceId &&\n * notificationPermission === NotificationPermission.Granted &&\n * isWorkerActive\n * );\n */\n const isPushEnabled = !!(deviceId &&\n notificationPermission === NotificationPermission.Granted &&\n isWorkerActive);\n return {\n subscribed: isPushEnabled,\n optedOut: !!optedOut,\n };\n }\n async getSubscriptionStateForInsecure() {\n /* For HTTP, we need to rely on stored values; we never have access to the actual data */\n const { deviceId, subscriptionToken, optedOut } = await Database.getSubscription();\n const notificationPermission = await this.context.permissionManager.getNotificationPermission(this.context.appConfig.safariWebId);\n const isPushEnabled = !!(deviceId &&\n subscriptionToken &&\n notificationPermission === NotificationPermission.Granted);\n return {\n subscribed: isPushEnabled,\n optedOut: !!optedOut,\n };\n }\n /**\n * Broadcasting to the server the fact user tried to subscribe but there was an error during service worker registration.\n * Do it only once for the first page view.\n * @param subscriptionState Describes what went wrong with the service worker installation.\n */\n async registerFailedSubscription(subscriptionState, context) {\n if (context.pageViewManager.isFirstPageView()) {\n context.subscriptionManager.registerSubscription(new RawPushSubscription(), subscriptionState);\n context.pageViewManager.incrementPageViewCount();\n }\n }\n}\n//# sourceMappingURL=SubscriptionManager.js.map","/**\n * Used for VAPID, converts the VAPID public key into a byte format the browser accepts.\n */\nexport function base64ToUint8Array(base64String) {\n const padding = '='.repeat((4 - base64String.length % 4) % 4);\n const base64 = (base64String + padding).replace(/\\-/g, '+').replace(/_/g, '/');\n const rawData = atob(base64);\n const outputArray = new Uint8Array(rawData.length);\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n}\n/**\n * Used for VAPID, converts a browser-provided ArrayBuffer of the applicationServerKey back to its string form.\n */\nexport function arrayBufferToBase64(arrayBuffer) {\n var base64 = '';\n var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n var bytes = new Uint8Array(arrayBuffer);\n var byteLength = bytes.byteLength;\n var byteRemainder = byteLength % 3;\n var mainLength = byteLength - byteRemainder;\n var a, b, c, d;\n var chunk;\n // Main loop deals with bytes in chunks of 3\n for (var i = 0; i < mainLength; i = i + 3) {\n // Combine the three bytes into a single integer\n chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n // Use bitmasks to extract 6-bit segments from the triplet\n a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18\n b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12\n c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6\n d = chunk & 63; // 63 = 2^6 - 1\n // Convert the raw binary segments to the appropriate ASCII encoding\n base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];\n }\n // Deal with the remaining bytes and padding\n if (byteRemainder == 1) {\n chunk = bytes[mainLength];\n a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2\n // Set the 4 least significant bits to zero\n b = (chunk & 3) << 4; // 3 = 2^2 - 1\n base64 += encodings[a] + encodings[b] + '==';\n }\n else if (byteRemainder == 2) {\n chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];\n a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10\n b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4\n // Set the 2 least significant bits to zero\n c = (chunk & 15) << 2; // 15 = 2^4 - 1\n base64 += encodings[a] + encodings[b] + encodings[c] + '=';\n }\n return base64;\n}\n/**\n * From: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding\n */\nexport function base64Encode(str) {\n // first we use encodeURIComponent to get percent-encoded UTF-8,\n // then we convert the percent encodings into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\nexport function base64Decode(str) {\n // Going backwards: from bytestream, to percent-encoding, to original string.\n return decodeURIComponent(atob(str).split('').map(function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n}\n//# sourceMappingURL=Encoding.js.map","import { ServiceWorkerManager } from '../managers/ServiceWorkerManager';\nimport { SubscriptionManager } from '../managers/SubscriptionManager';\nimport Path from '../models/Path';\nimport SdkEnvironment from '../managers/SdkEnvironment';\nexport class ContextHelper {\n static getServiceWorkerManager(context) {\n const config = context.appConfig;\n const envPrefix = SdkEnvironment.getBuildEnvPrefix();\n const serviceWorkerManagerConfig = {\n workerPath: new Path(`/${envPrefix}OneSignalSDKWorker.js`),\n registrationOptions: { scope: '/' }\n };\n if (config.userConfig) {\n if (config.userConfig.path) {\n serviceWorkerManagerConfig.workerPath =\n new Path(`${config.userConfig.path}${config.userConfig.serviceWorkerPath}`);\n }\n if (config.userConfig.serviceWorkerParam) {\n serviceWorkerManagerConfig.registrationOptions = config.userConfig.serviceWorkerParam;\n }\n }\n return new ServiceWorkerManager(context, serviceWorkerManagerConfig);\n }\n static getSubscriptionManager(context) {\n const config = context.appConfig;\n const subscriptionManagerConfig = {\n safariWebId: config.safariWebId,\n appId: config.appId,\n vapidPublicKey: config.vapidPublicKey,\n onesignalVapidPublicKey: config.onesignalVapidPublicKey,\n };\n return new SubscriptionManager(context, subscriptionManagerConfig);\n }\n}\nexport default ContextHelper;\n//# sourceMappingURL=ContextHelper.js.map","/*\n LimitStore.put('colorado', 'rocky');\n [\"rocky\"]\n LimitStore.put('colorado', 'mountain');\n [\"rocky\", \"mountain\"]\n LimitStore.put('colorado', 'national');\n [\"mountain\", \"national\"]\n LimitStore.put('colorado', 'park');\n [\"national\", \"park\"]\n */\nexport default class LimitStore {\n static put(key, value) {\n if (LimitStore.store[key] === undefined) {\n LimitStore.store[key] = [null, null];\n }\n LimitStore.store[key].push(value);\n if (LimitStore.store[key].length == LimitStore.LIMIT + 1) {\n LimitStore.store[key].shift();\n }\n return LimitStore.store[key];\n }\n static get(key) {\n if (LimitStore.store[key] === undefined) {\n LimitStore.store[key] = [null, null];\n }\n return LimitStore.store[key];\n }\n static getFirst(key) {\n return LimitStore.get(key)[0];\n }\n static getLast(key) {\n return LimitStore.get(key)[1];\n }\n static remove(key) {\n delete LimitStore.store[key];\n }\n static isEmpty(key) {\n const values = LimitStore.get(key);\n return values[0] === null && values[1] === null;\n }\n}\nLimitStore.store = {};\nLimitStore.LIMIT = 2;\n//# sourceMappingURL=LimitStore.js.map","export const SLIDEDOWN_CSS_CLASSES = {\n allowButton: \"onesignal-slidedown-allow-button\",\n body: \"slidedown-body\",\n buttonIndicatorHolder: \"onesignal-button-indicator-holder\",\n cancelButton: \"onesignal-slidedown-cancel-button\",\n container: \"onesignal-slidedown-container\",\n dialog: \"onesignal-slidedown-dialog\",\n footer: \"slidedown-footer\",\n reset: \"onesignal-reset\",\n savingStateButton: \"onesignal-saving-state-button\",\n slideUp: 'slide-up',\n slideDown: 'slide-down',\n closeSlidedown: 'close-slidedown',\n icon: 'slidedown-body-icon',\n message: 'slidedown-body-message',\n defaultIcon: 'default-icon',\n loadingContainer: \"onesignal-loading-container\",\n clearfix: \"clearfix\"\n};\nexport const TOAST_CLASSES = {\n toastText: 'onesignal-toast-text'\n};\nexport const TOAST_IDS = {\n toastText: 'onesignal-toast-text'\n};\nexport const SLIDEDOWN_CSS_IDS = {\n allowButton: \"onesignal-slidedown-allow-button\",\n body: \"slidedown-body\",\n buttonIndicatorHolder: \"onesignal-button-indicator-holder\",\n cancelButton: \"onesignal-slidedown-cancel-button\",\n container: \"onesignal-slidedown-container\",\n dialog: \"onesignal-slidedown-dialog\",\n footer: \"slidedown-footer\",\n normalSlidedown: \"normal-slidedown\",\n loadingContainer: \"onesignal-loading-container\",\n};\nexport const SLIDEDOWN_BUTTON_CLASSES = {\n alignRight: 'align-right',\n primary: 'primary',\n secondary: 'secondary',\n slidedownButton: 'slidedown-button'\n};\nexport const TAGGING_CONTAINER_CSS_CLASSES = {\n categoryLabelInput: \"onesignal-category-label-input\",\n categoryLabelText: \"onesignal-category-label-text\",\n categoryLabel: \"onesignal-category-label\",\n checkmark: \"onesignal-checkmark\",\n taggingContainer: \"tagging-container\",\n taggingContainerCol: \"tagging-container-col\",\n loadingMessage: \"onesignal-loading-message\"\n};\nexport const TAGGING_CONTAINER_CSS_IDS = {\n taggingContainer: \"tagging-container\",\n};\nexport const DEFAULT_ICON = `data:image/svg+xml,%3Csvg fill='none' xmlns='http://www.w3.org/2000/svg'` +\n ` viewBox='0 0 40 40'%3E%3Cg clip-path='url(%23clip0)'%3E%3Cpath fill-rule='evenodd'` +\n ` clip-rule='evenodd' d='M33.232 28.434a2.5 2.5 0 001.768.733 1.667 1.667 0 010 ` +\n `3.333H5a1.667 1.667 0 110-3.333 2.5 2.5 0 002.5-2.5v-8.104A13.262 13.262 0 0118.333` +\n ` 5.122V1.667a1.666 1.666 0 113.334 0v3.455A13.262 13.262 0 0132.5 18.563v8.104a2.5` +\n ` 2.5 0 00.732 1.767zM16.273 35h7.454a.413.413 0 01.413.37 4.167 4.167 0 11-8.28 0` +\n ` .417.417 0 01.413-.37z' fill='%23BDC4CB'/%3E%3C/g%3E%3Cdefs%3E%3CclipPath` +\n ` id='clip0'%3E%3Cpath fill='%23fff' d='M0 0h40v40H0z'/%3E%3C/clipPath%3E%3C/defs%3E%3C/svg%3E`;\nexport const DANGER_ICON = `data:image/svg+xml;charset=UTF-8,%3csvg width='16' height='16' view` +\n `Box='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M7.98775 -0.001144` +\n `06C5.85015 0.0338508 3.81219 0.908665 2.31442 2.43419C1.565 3.18031 0.973715 4.06987 0.575897 ` +\n `5.04969C0.17808 6.02952 -0.0180997 7.07949 -0.000914196 8.13686C-0.00214385 9.17005 0.200528 1` +\n `0.1933 0.595487 11.148C0.990446 12.1028 1.56993 12.9702 2.30072 13.7005C3.03151 14.4309 3.8992` +\n `5 15.0098 4.85421 15.4042C5.80916 15.7986 6.83256 16.0007 7.86575 15.9989H8.00842C10.1467 15.9` +\n `769 12.1889 15.1075 13.6869 13.5816C15.185 12.0557 16.0165 9.99781 15.9991 7.85952C16.0015 6.8` +\n `138 15.7949 5.77814 15.3913 4.81345C14.9876 3.84876 14.3952 2.97451 13.6488 2.24213C12.9023 1.` +\n `50974 12.017 0.933994 11.0448 0.548751C10.0726 0.163508 9.03324 -0.0234551 7.98775 -0.00114406` +\n `ZM6.99909 11.0269C6.99428 10.8961 7.01558 10.7658 7.06175 10.6434C7.10792 10.521 7.17803 10.40` +\n `91 7.26797 10.3141C7.35792 10.2191 7.4659 10.143 7.58559 10.0903C7.70529 10.0375 7.8343 10.009` +\n `2 7.96509 10.0069H7.98309C8.24616 10.0074 8.49882 10.1097 8.6881 10.2924C8.87739 10.4751 8.988` +\n `6 10.724 8.99842 10.9869C9.00331 11.1176 8.98207 11.248 8.93594 11.3704C8.8898 11.4928 8.8197 ` +\n `11.6048 8.72974 11.6998C8.63978 11.7948 8.53176 11.8709 8.41202 11.9236C8.29229 11.9763 8.1632` +\n `3 12.0046 8.03242 12.0069H8.01442C7.75145 12.006 7.49897 11.9036 7.30976 11.721C7.12054 11.538` +\n `3 7.00923 11.2896 6.99909 11.0269ZM7.33242 8.33219V4.33219C7.33242 4.15538 7.40266 3.98581 7.5` +\n `2768 3.86079C7.65271 3.73576 7.82227 3.66552 7.99909 3.66552C8.1759 3.66552 8.34547 3.73576 8.` +\n `47049 3.86079C8.59551 3.98581 8.66575 4.15538 8.66575 4.33219V8.33219C8.66575 8.509 8.59551 8.` +\n `67857 8.47049 8.80359C8.34547 8.92862 8.1759 8.99886 7.99909 8.99886C7.82227 8.99886 7.65271 8` +\n `.92862 7.52768 8.80359C7.40266 8.67857 7.33242 8.509 7.33242 8.33219Z' fill='%23E54B4D'/%3e%3c/svg%3e`;\nexport const COLORS = {\n greyLoadingIndicator: \"#95A1AC\",\n whiteLoadingIndicator: \"#FFFFFF\"\n};\nexport const TAGGING_CONTAINER_STRINGS = {\n fetchingPreferences: \"Fetching your preferences\"\n};\nexport const CHANNEL_CAPTURE_CONTAINER_CSS_CLASSES = {\n channelCaptureContainer: 'channel-capture-container',\n inputWithValidationElement: 'input-with-validation-element',\n onesignalErrorInput: 'onesignal-error-input',\n onesignalSmsInput: 'iti-onesignal-sms-input',\n onesignalEmailInput: 'onesignal-email-input',\n onesignalValidationElementHidden: 'onesignal-validation-element-hidden',\n onesignalValidationElement: 'onesignal-validation-element',\n};\nexport const CHANNEL_CAPTURE_CONTAINER_CSS_IDS = {\n channelCaptureContainer: 'channel-capture-container',\n smsInputWithValidationElement: 'sms-input-with-validation-element',\n emailInputWithValidationElement: 'email-input-with-validation-element',\n onesignalSmsInput: 'iti-onesignal-sms-input',\n onesignalEmailInput: 'onesignal-email-input',\n onesignalSmsValidationElement: 'onesignal-sms-validation-element',\n onesignalEmailValidationElement: 'onesignal-email-validation-element',\n};\nconst STATE = {\n subscribed: \"state-subscribed\",\n unsubscribed: \"state-unsubscribed\",\n};\nexport const CUSTOM_LINK_CSS_CLASSES = {\n containerClass: \"onesignal-customlink-container\",\n subscribeClass: \"onesignal-customlink-subscribe\",\n explanationClass: \"onesignal-customlink-explanation\",\n resetClass: \"onesignal-reset\",\n hide: \"hide\",\n state: STATE,\n};\nexport const CUSTOM_LINK_CSS_SELECTORS = {\n containerSelector: `.${CUSTOM_LINK_CSS_CLASSES.containerClass}`,\n subscribeSelector: `.${CUSTOM_LINK_CSS_CLASSES.subscribeClass}`,\n explanationSelector: `.${CUSTOM_LINK_CSS_CLASSES.explanationClass}`,\n};\n//# sourceMappingURL=constants.js.map","import Log from \"../libraries/Log\";\nimport { CUSTOM_LINK_CSS_CLASSES, CUSTOM_LINK_CSS_SELECTORS } from \"../slidedown/constants\";\nimport { addCssClass } from \"../utils\";\nimport LocalStorage from \"../utils/LocalStorage\";\nexport class CustomLinkManager {\n constructor(config) {\n this.config = config;\n }\n async initialize() {\n var _a, _b;\n if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.enabled)) {\n return;\n }\n if (!(await this.loadSdkStyles())) {\n return;\n }\n Log.info(\"OneSignal: initializing customlink\");\n if (!((_b = this.config) === null || _b === void 0 ? void 0 : _b.unsubscribeEnabled) && CustomLinkManager.isPushEnabled()) {\n this.hideCustomLinkContainers();\n return;\n }\n // traditional for-loop required here to avoid layout shift\n for (let i = 0; i < this.customlinkContainerElements.length; i++) {\n await this.injectMarkup(this.customlinkContainerElements[i]);\n }\n }\n async injectMarkup(element) {\n // clear contents\n element.innerHTML = '';\n await this.mountExplanationNode(element);\n await this.mountSubscriptionNode(element);\n }\n async mountExplanationNode(element) {\n var _a;\n if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.text)) {\n Log.error(\"CustomLink: required property 'text' is missing in the config\");\n return;\n }\n if (this.config.text.explanation) {\n const explanation = document.createElement(\"p\");\n explanation.textContent = this.config.text.explanation;\n addCssClass(explanation, CUSTOM_LINK_CSS_CLASSES.resetClass);\n addCssClass(explanation, CUSTOM_LINK_CSS_CLASSES.explanationClass);\n if (this.config.size) {\n addCssClass(explanation, this.config.size);\n }\n if (CustomLinkManager.isPushEnabled()) {\n addCssClass(explanation, CUSTOM_LINK_CSS_CLASSES.state.subscribed);\n }\n else {\n addCssClass(explanation, CUSTOM_LINK_CSS_CLASSES.state.unsubscribed);\n }\n element.appendChild(explanation);\n }\n }\n async mountSubscriptionNode(element) {\n var _a;\n if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.text)) {\n Log.error(\"CustomLink: required property 'text' is missing in the config\");\n return;\n }\n if (this.config.text.subscribe) {\n const subscribeButton = document.createElement(\"button\");\n addCssClass(subscribeButton, CUSTOM_LINK_CSS_CLASSES.resetClass);\n addCssClass(subscribeButton, CUSTOM_LINK_CSS_CLASSES.subscribeClass);\n if (this.config.size) {\n addCssClass(subscribeButton, this.config.size);\n }\n if (this.config.style) {\n addCssClass(subscribeButton, this.config.style);\n }\n if (CustomLinkManager.isPushEnabled()) {\n addCssClass(subscribeButton, CUSTOM_LINK_CSS_CLASSES.state.subscribed);\n }\n else {\n addCssClass(subscribeButton, CUSTOM_LINK_CSS_CLASSES.state.unsubscribed);\n }\n this.setCustomColors(subscribeButton);\n await this.setTextFromPushStatus(subscribeButton);\n subscribeButton.addEventListener(\"click\", async () => {\n Log.info(\"CustomLink: subscribe clicked\");\n await this.handleClick(subscribeButton);\n });\n element.appendChild(subscribeButton);\n }\n }\n async loadSdkStyles() {\n const sdkStylesLoadResult = await OneSignal.context.dynamicResourceLoader.loadSdkStylesheet();\n if (sdkStylesLoadResult !== 0 /* Loaded */) {\n Log.debug('Not initializing custom link button because styles failed to load.');\n return false;\n }\n return true;\n }\n hideElement(element) {\n addCssClass(element, CUSTOM_LINK_CSS_CLASSES.hide);\n }\n /**\n * Used for hiding elements if \"Allow unsubscribe\" is on\n * @returns void\n */\n hideCustomLinkContainers() {\n this.customlinkContainerElements.forEach(element => {\n this.hideElement(element);\n });\n }\n async handleClick(element) {\n var _a, _b;\n if (CustomLinkManager.isPushEnabled()) {\n await OneSignal.setSubscription(false);\n await this.setTextFromPushStatus(element);\n }\n else {\n if (!CustomLinkManager.isOptedOut()) {\n const autoAccept = !OneSignal.environmentInfo.requiresUserInteraction;\n const options = { autoAccept };\n await OneSignal.registerForPushNotifications(options);\n // once subscribed, prevent unsubscribe by hiding customlinks\n if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.unsubscribeEnabled) && CustomLinkManager.isPushEnabled()) {\n this.hideCustomLinkContainers();\n }\n return;\n }\n await OneSignal.setSubscription(true);\n // once subscribed, prevent unsubscribe by hiding customlinks\n if (!((_b = this.config) === null || _b === void 0 ? void 0 : _b.unsubscribeEnabled) && CustomLinkManager.isPushEnabled()) {\n this.hideCustomLinkContainers();\n }\n }\n }\n async setTextFromPushStatus(element) {\n var _a, _b, _c, _d;\n if ((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.subscribe) {\n if (!CustomLinkManager.isPushEnabled()) {\n element.textContent = this.config.text.subscribe;\n }\n }\n if ((_d = (_c = this.config) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.unsubscribe) {\n if (CustomLinkManager.isPushEnabled()) {\n element.textContent = this.config.text.unsubscribe;\n }\n }\n }\n setCustomColors(element) {\n var _a, _b, _c, _d, _e, _f, _g;\n if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.color) || !this.config.color.text) {\n return;\n }\n if (((_b = this.config) === null || _b === void 0 ? void 0 : _b.style) === \"button\" && ((_c = this.config) === null || _c === void 0 ? void 0 : _c.color.button)) {\n element.style.backgroundColor = (_d = this.config) === null || _d === void 0 ? void 0 : _d.color.button;\n element.style.color = (_e = this.config) === null || _e === void 0 ? void 0 : _e.color.text;\n }\n else if (((_f = this.config) === null || _f === void 0 ? void 0 : _f.style) === \"link\") {\n element.style.color = (_g = this.config) === null || _g === void 0 ? void 0 : _g.color.text;\n }\n }\n get customlinkContainerElements() {\n const containers = document.querySelectorAll(CUSTOM_LINK_CSS_SELECTORS.containerSelector);\n return Array.prototype.slice.call(containers);\n }\n static isPushEnabled() {\n return LocalStorage.getIsPushNotificationsEnabled();\n }\n static isOptedOut() {\n return LocalStorage.getIsOptedOut();\n }\n}\n//# sourceMappingURL=CustomLinkManager.js.map","import Event from '../Event';\nimport LimitStore from '../LimitStore';\nimport OneSignalApiShared from '../OneSignalApiShared';\nimport Database from '../services/Database';\nimport Log from '../libraries/Log';\nimport { OneSignalUtils } from \"../utils/OneSignalUtils\";\nimport { BrowserUtils } from \"../utils/BrowserUtils\";\nimport PromptsHelper from './PromptsHelper';\nimport LocalStorage from '../utils/LocalStorage';\nimport { CustomLinkManager } from '../managers/CustomLinkManager';\nexport default class EventHelper {\n static onNotificationPermissionChange() {\n EventHelper.checkAndTriggerSubscriptionChanged();\n }\n static async onInternalSubscriptionSet(optedOut) {\n LimitStore.put('subscription.optedOut', optedOut);\n }\n static async checkAndTriggerSubscriptionChanged() {\n OneSignalUtils.logMethodCall('checkAndTriggerSubscriptionChanged');\n const context = OneSignal.context;\n const subscriptionState = await context.subscriptionManager.getSubscriptionState();\n const isPushEnabled = await OneSignal.privateIsPushNotificationsEnabled();\n const appState = await Database.getAppState();\n const { lastKnownPushEnabled } = appState;\n const didStateChange = (lastKnownPushEnabled === null ||\n isPushEnabled !== lastKnownPushEnabled);\n if (!didStateChange)\n return;\n Log.info(`The user's subscription state changed from ` +\n `${lastKnownPushEnabled === null ? '(not stored)' : lastKnownPushEnabled} ⟶ ${subscriptionState.subscribed}`);\n LocalStorage.setIsPushNotificationsEnabled(isPushEnabled);\n appState.lastKnownPushEnabled = isPushEnabled;\n await Database.setAppState(appState);\n EventHelper.triggerSubscriptionChanged(isPushEnabled);\n }\n static async _onSubscriptionChanged(newSubscriptionState) {\n EventHelper.onSubscriptionChanged_showWelcomeNotification(newSubscriptionState);\n EventHelper.onSubscriptionChanged_sendCategorySlidedownTags(newSubscriptionState);\n EventHelper.onSubscriptionChanged_evaluateNotifyButtonDisplayPredicate();\n EventHelper.onSubscriptionChanged_updateCustomLink();\n }\n static async onSubscriptionChanged_sendCategorySlidedownTags(isSubscribed) {\n var _a, _b;\n if (isSubscribed !== true) {\n return;\n }\n const prompts = (_b = (_a = OneSignal.context.appConfig.userConfig.promptOptions) === null || _a === void 0 ? void 0 : _a.slidedown) === null || _b === void 0 ? void 0 : _b.prompts;\n if (PromptsHelper.isCategorySlidedownConfigured(prompts)) {\n await OneSignal.context.tagManager.sendTags(false);\n }\n }\n static async onSubscriptionChanged_showWelcomeNotification(isSubscribed) {\n if (OneSignal.__doNotShowWelcomeNotification) {\n Log.debug('Not showing welcome notification because user has previously subscribed.');\n return;\n }\n if (isSubscribed === true) {\n const { deviceId } = await Database.getSubscription();\n const { appId } = await Database.getAppConfig();\n const welcome_notification_opts = OneSignal.config.userConfig.welcomeNotification;\n const welcome_notification_disabled = welcome_notification_opts !== undefined && welcome_notification_opts['disable'] === true;\n let title = welcome_notification_opts !== undefined &&\n welcome_notification_opts['title'] !== undefined &&\n welcome_notification_opts['title'] !== null\n ? welcome_notification_opts['title']\n : '';\n let message = welcome_notification_opts !== undefined &&\n welcome_notification_opts['message'] !== undefined &&\n welcome_notification_opts['message'] !== null &&\n welcome_notification_opts['message'].length > 0\n ? welcome_notification_opts['message']\n : 'Thanks for subscribing!';\n const unopenableWelcomeNotificationUrl = new URL(location.href).origin + '?_osp=do_not_open';\n const url = welcome_notification_opts && welcome_notification_opts['url'] && welcome_notification_opts['url'].length > 0\n ? welcome_notification_opts['url']\n : unopenableWelcomeNotificationUrl;\n title = BrowserUtils.decodeHtmlEntities(title);\n message = BrowserUtils.decodeHtmlEntities(message);\n if (!welcome_notification_disabled) {\n Log.debug('Sending welcome notification.');\n OneSignalApiShared.sendNotification(appId, [deviceId], { en: title }, { en: message }, url, null, { __isOneSignalWelcomeNotification: true }, undefined);\n Event.trigger(OneSignal.EVENTS.WELCOME_NOTIFICATION_SENT, {\n title: title,\n message: message,\n url: url\n });\n }\n }\n }\n static async onSubscriptionChanged_evaluateNotifyButtonDisplayPredicate() {\n if (!OneSignal.config.userConfig.notifyButton)\n return;\n const displayPredicate = OneSignal.config.userConfig.notifyButton.displayPredicate;\n if (displayPredicate && typeof displayPredicate === \"function\" && OneSignal.notifyButton) {\n const predicateResult = await displayPredicate();\n if (predicateResult !== false) {\n Log.debug('Showing notify button because display predicate returned true.');\n OneSignal.notifyButton.launcher.show();\n }\n else {\n Log.debug('Hiding notify button because display predicate returned false.');\n OneSignal.notifyButton.launcher.hide();\n }\n }\n }\n static async onSubscriptionChanged_updateCustomLink() {\n if (OneSignal.config.userConfig.promptOptions) {\n new CustomLinkManager(OneSignal.config.userConfig.promptOptions.customlink).initialize();\n }\n }\n static triggerSubscriptionChanged(to) {\n Event.trigger(OneSignal.EVENTS.SUBSCRIPTION_CHANGED, to);\n }\n /**\n * When notifications are clicked, because the site isn't open, the notification is stored in the database. The next\n * time the page opens, the event is triggered if its less than 5 minutes (usually page opens instantly from click).\n *\n * This method is fired for both HTTPS and HTTP sites, so for HTTP sites, the host URL needs to be used, not the\n * subdomain.onesignal.com URL.\n */\n static async fireStoredNotificationClicks(url = document.URL) {\n async function fireEventWithNotification(clickedNotificationInfo) {\n // Remove the notification from the recently clicked list\n // Once this page processes this retroactively provided clicked event, nothing should get the same event\n const appState = await Database.getAppState();\n appState.clickedNotifications[clickedNotificationInfo.url] = null;\n await Database.setAppState(appState);\n /* Clicked notifications look like:\n {\n \"url\": \"https://notify.tech\",\n \"data\": {\n \"id\": \"f44dfcc7-e8cd-47c6-af7e-e2b7ac68afca\",\n \"heading\": \"Example Notification\",\n \"content\": \"This is an example notification.\",\n \"icon\": \"https://onesignal.com/images/notification_logo.png\"\n (there would be a URL field here if it was set)\n },\n \"timestamp\": 1490998270607\n }\n */\n const { data: notification, timestamp } = clickedNotificationInfo;\n if (timestamp) {\n const minutesSinceNotificationClicked = (Date.now() - timestamp) / 1000 / 60;\n if (minutesSinceNotificationClicked > 5)\n return;\n }\n Event.trigger(OneSignal.EVENTS.NOTIFICATION_CLICKED, notification);\n }\n const appState = await Database.getAppState();\n /* Is the flag notificationClickHandlerMatch: origin enabled?\n \n If so, this means we should provide a retroactive notification.clicked event as long as there exists any recently clicked\n notification that matches this site's origin.\n \n Otherwise, the default behavior is to only provide a retroactive notification.clicked event if this page's URL exactly\n matches the notification's URL.\n */\n const notificationClickHandlerMatch = await Database.get('Options', 'notificationClickHandlerMatch');\n if (notificationClickHandlerMatch === 'origin') {\n for (const clickedNotificationUrl of Object.keys(appState.clickedNotifications)) {\n // Using notificationClickHandlerMatch: 'origin', as long as the notification's URL's origin matches our current tab's origin,\n // fire the clicked event\n if (new URL(clickedNotificationUrl).origin === location.origin) {\n const clickedNotification = appState.clickedNotifications[clickedNotificationUrl];\n await fireEventWithNotification(clickedNotification);\n }\n }\n }\n else {\n /*\n If a user is on https://site.com, document.URL and location.href both report the page's URL as https://site.com/.\n This causes checking for notifications for the current URL to fail, since there is a notification for https://site.com,\n but there is no notification for https://site.com/.\n \n As a workaround, if there are no notifications for https://site.com/, we'll do a check for https://site.com.\n */\n var pageClickedNotifications = appState.clickedNotifications[url];\n if (pageClickedNotifications) {\n await fireEventWithNotification(pageClickedNotifications);\n }\n else if (!pageClickedNotifications && url.endsWith('/')) {\n var urlWithoutTrailingSlash = url.substring(0, url.length - 1);\n pageClickedNotifications = appState.clickedNotifications[urlWithoutTrailingSlash];\n if (pageClickedNotifications) {\n await fireEventWithNotification(pageClickedNotifications);\n }\n }\n }\n }\n}\n//# sourceMappingURL=EventHelper.js.map","export var Browser;\n(function (Browser) {\n Browser[\"Safari\"] = \"safari\";\n Browser[\"Firefox\"] = \"firefox\";\n Browser[\"Chrome\"] = \"chrome\";\n Browser[\"Opera\"] = \"opera\";\n Browser[\"Edge\"] = \"edge\";\n Browser[\"Other\"] = \"other\";\n})(Browser || (Browser = {}));\n//# sourceMappingURL=Browser.js.map","import PushPermissionNotGrantedError from '../errors/PushPermissionNotGrantedError';\nimport { PushPermissionNotGrantedErrorReason } from '../errors/PushPermissionNotGrantedError';\nimport { WindowEnvironmentKind } from '../models/WindowEnvironmentKind';\nimport EventHelper from './EventHelper';\nimport { InvalidStateError, InvalidStateReason } from '../errors/InvalidStateError';\nimport { NotificationPermission } from '../models/NotificationPermission';\nimport { RawPushSubscription } from '../models/RawPushSubscription';\nimport Log from '../libraries/Log';\nimport SdkEnvironment from '../managers/SdkEnvironment';\nimport { PermissionUtils } from \"../utils/PermissionUtils\";\nimport LocalStorage from '../utils/LocalStorage';\nimport { SessionOrigin } from \"../models/Session\";\nimport MainHelper from \"./MainHelper\";\nimport { Browser } from \"../context/browser/models/Browser\";\nexport default class SubscriptionHelper {\n static async registerForPush() {\n const isPushEnabled = LocalStorage.getIsPushNotificationsEnabled();\n return await SubscriptionHelper.internalRegisterForPush(isPushEnabled);\n }\n static async internalRegisterForPush(isPushEnabled) {\n const context = OneSignal.context;\n let subscription = null;\n /*\n Within the same page navigation (the same session), do not register for\n push if the user is already subscribed, otherwise the user will have its\n session count incremented on each page refresh. However, if the user is\n not subscribed, subscribe.\n */\n if (isPushEnabled && !context.pageViewManager.isFirstPageView()) {\n Log.debug('Not registering for push because the user is subscribed and this is not the first page view.');\n Log.debug(\"But we want to rekindle their session.\");\n const deviceId = await MainHelper.getDeviceId();\n if (deviceId) {\n const deviceRecord = await MainHelper.createDeviceRecord(OneSignal.config.appId, true);\n await OneSignal.context.sessionManager.upsertSession(deviceId, deviceRecord, SessionOrigin.PageRefresh);\n }\n else {\n Log.error(\"Should have been impossible to have push as enabled but no device id.\");\n }\n return null;\n }\n if (typeof OneSignal !== \"undefined\") {\n if (OneSignal._isRegisteringForPush)\n return null;\n else\n OneSignal._isRegisteringForPush = true;\n }\n switch (SdkEnvironment.getWindowEnv()) {\n case WindowEnvironmentKind.Host:\n case WindowEnvironmentKind.OneSignalSubscriptionModal:\n try {\n const rawSubscription = await context.subscriptionManager.subscribe(0 /* ResubscribeExisting */);\n subscription = await context.subscriptionManager.registerSubscription(rawSubscription);\n context.pageViewManager.incrementPageViewCount();\n await PermissionUtils.triggerNotificationPermissionChanged();\n await EventHelper.checkAndTriggerSubscriptionChanged();\n }\n catch (e) {\n Log.info(e);\n }\n break;\n case WindowEnvironmentKind.OneSignalSubscriptionPopup:\n /*\n This is the code for the HTTP popup.\n */\n const windowCreator = opener || parent;\n let rawSubscription;\n // Update the stored permission first, so we know the real value even if the user closes the\n // popup\n await context.permissionManager.updateStoredPermission();\n try {\n /* If the user doesn't grant permissions, a PushPermissionNotGrantedError will be thrown here. */\n rawSubscription = await context.subscriptionManager.subscribe(1 /* SubscribeNew */);\n // Update the permission to granted\n await context.permissionManager.updateStoredPermission();\n }\n catch (e) {\n // Update the permission to denied or default\n await context.permissionManager.updateStoredPermission();\n if (e instanceof PushPermissionNotGrantedError) {\n switch (e.reason) {\n case PushPermissionNotGrantedErrorReason.Blocked:\n await context.permissionManager.updateStoredPermission();\n /* Force update false, because the iframe installs a native\n permission change handler that will be triggered when the user\n clicks out of the popup back to the parent page */\n OneSignal.subscriptionPopup.message(OneSignal.POSTMAM_COMMANDS.REMOTE_NOTIFICATION_PERMISSION_CHANGED, {\n permission: NotificationPermission.Denied,\n forceUpdatePermission: false\n });\n break;\n case PushPermissionNotGrantedErrorReason.Dismissed:\n /* Force update true because default permissions (before\n prompting) -> default permissions (after prompting) isn't a\n change, but we still want to be notified about it */\n OneSignal.subscriptionPopup.message(OneSignal.POSTMAM_COMMANDS.REMOTE_NOTIFICATION_PERMISSION_CHANGED, {\n permission: NotificationPermission.Default,\n forceUpdatePermission: true\n });\n break;\n }\n }\n /*\n Popup native permission request was blocked or dismissed\n Close the window\n */\n if (windowCreator) {\n window.close();\n return null;\n }\n }\n OneSignal.subscriptionPopup.message(OneSignal.POSTMAM_COMMANDS.FINISH_REMOTE_REGISTRATION, {\n rawPushSubscription: rawSubscription.serialize()\n }, (message) => {\n if (message.data.progress === true) {\n Log.debug('Got message from host page that remote reg. is in progress, closing popup.');\n if (windowCreator) {\n window.close();\n }\n }\n else {\n Log.debug('Got message from host page that remote reg. could not be finished.');\n }\n });\n break;\n default:\n if (typeof OneSignal !== \"undefined\")\n OneSignal._isRegisteringForPush = false;\n throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);\n }\n if (typeof OneSignal !== \"undefined\")\n OneSignal._isRegisteringForPush = false;\n return subscription;\n }\n static getRawPushSubscriptionForSafari(safariWebId) {\n const subscription = new RawPushSubscription();\n const { deviceToken: existingDeviceToken } = window.safari.pushNotification.permission(safariWebId);\n subscription.existingSafariDeviceToken = existingDeviceToken;\n return subscription;\n }\n static async getRawPushSubscriptionFromServiceWorkerRegistration(registration) {\n if (!registration) {\n return null;\n }\n const swSubscription = await registration.pushManager.getSubscription();\n if (!swSubscription) {\n return null;\n }\n return RawPushSubscription.setFromW3cSubscription(swSubscription);\n }\n static async getRawPushSubscriptionWhenUsingSubscriptionWorkaround() {\n // we would need to message service worker to get it. we'll get it from inside if necessary\n return null;\n }\n static async getRawPushSubscription(environmentInfo, safariWebId) {\n if (environmentInfo.browserType === Browser.Safari) {\n return SubscriptionHelper.getRawPushSubscriptionForSafari(safariWebId);\n }\n if (environmentInfo.isUsingSubscriptionWorkaround) {\n return SubscriptionHelper.getRawPushSubscriptionWhenUsingSubscriptionWorkaround();\n }\n if (environmentInfo.isBrowserAndSupportsServiceWorkers) {\n const registration = await OneSignal.context.serviceWorkerManager.getRegistration();\n return await SubscriptionHelper.getRawPushSubscriptionFromServiceWorkerRegistration(registration);\n }\n return null;\n }\n}\n//# sourceMappingURL=SubscriptionHelper.js.map","import { InvalidStateError, InvalidStateReason } from '../errors/InvalidStateError';\nimport Event from '../Event';\nimport SdkEnvironment from '../managers/SdkEnvironment';\nimport Database from '../services/Database';\nimport Log from '../libraries/Log';\nimport { SubscriptionStateKind } from '../models/SubscriptionStateKind';\nimport { NotificationPermission } from \"../models/NotificationPermission\";\nimport { PushDeviceRecord } from \"../models/PushDeviceRecord\";\nimport { OneSignalUtils } from \"../utils/OneSignalUtils\";\nimport { PermissionUtils } from \"../utils/PermissionUtils\";\nimport { Utils } from \"../context/shared/utils/Utils\";\nimport SubscriptionHelper from \"./SubscriptionHelper\";\nexport default class MainHelper {\n static async getCurrentNotificationType() {\n const currentPermission = await OneSignal.context.permissionManager.getNotificationPermission(OneSignal.context.appConfig.safariWebId);\n if (currentPermission === NotificationPermission.Default) {\n return SubscriptionStateKind.Default;\n }\n if (currentPermission === NotificationPermission.Denied) {\n // Due to this issue https://github.com/OneSignal/OneSignal-Website-SDK/issues/289 we cannot reliably detect\n // \"default\" permission in HTTP context. Browser reports denied for both \"default\" and \"denied\" statuses.\n // Returning SubscriptionStateKind.Default for this case.\n return (OneSignalUtils.isUsingSubscriptionWorkaround()) ?\n SubscriptionStateKind.Default :\n SubscriptionStateKind.NotSubscribed;\n }\n const existingUser = await OneSignal.context.subscriptionManager.isAlreadyRegisteredWithOneSignal();\n if (currentPermission === NotificationPermission.Granted && existingUser) {\n const isPushEnabled = await OneSignal.privateIsPushNotificationsEnabled();\n return isPushEnabled ? SubscriptionStateKind.Subscribed : SubscriptionStateKind.MutedByApi;\n }\n return SubscriptionStateKind.Default;\n }\n /**\n * If the user has manually opted out of notifications (OneSignal.setSubscription), returns -2; otherwise returns 1.\n * @param isOptedIn The result of OneSignal.getSubscription().\n */\n static getNotificationTypeFromOptIn(isOptedIn) {\n if (isOptedIn == true || isOptedIn == null) {\n return SubscriptionStateKind.Subscribed;\n }\n else {\n return SubscriptionStateKind.MutedByApi;\n }\n }\n /**\n * Stores a flag in sessionStorage that we've already shown the HTTP slidedown to this user and that we should not\n * show it again until they open a new window or tab to the site.\n */\n static markHttpSlidedownShown() {\n sessionStorage.setItem('ONESIGNAL_HTTP_PROMPT_SHOWN', 'true');\n }\n /**\n * Returns true if the HTTP slidedown was already shown inside the same session.\n */\n static isHttpPromptAlreadyShown() {\n return sessionStorage.getItem('ONESIGNAL_HTTP_PROMPT_SHOWN') == 'true';\n }\n static async checkAndTriggerNotificationPermissionChanged() {\n const previousPermission = await Database.get('Options', 'notificationPermission');\n const currentPermission = await OneSignal.getNotificationPermission();\n if (previousPermission !== currentPermission) {\n await PermissionUtils.triggerNotificationPermissionChanged();\n await Database.put('Options', {\n key: 'notificationPermission',\n value: currentPermission\n });\n }\n }\n static async getNotificationIcons() {\n const appId = await MainHelper.getAppId();\n if (!appId) {\n throw new InvalidStateError(InvalidStateReason.MissingAppId);\n }\n const url = `${SdkEnvironment.getOneSignalApiUrl().toString()}/apps/${appId}/icon`;\n const response = await fetch(url);\n const data = await response.json();\n if (data.errors) {\n Log.error(`API call %c${url}`, Utils.getConsoleStyle('code'), 'failed with:', data.errors);\n throw new Error('Failed to get notification icons.');\n }\n return data;\n }\n static getSlidedownOptions(promptOptions) {\n return Utils.getValueOrDefault(promptOptions.slidedown, { prompts: [] });\n }\n static getFullscreenPermissionMessageOptions(promptOptions) {\n if (!promptOptions) {\n return null;\n }\n if (!promptOptions.fullscreen) {\n return promptOptions;\n }\n return {\n autoAcceptTitle: promptOptions.fullscreen.autoAcceptTitle,\n actionMessage: promptOptions.fullscreen.actionMessage,\n exampleNotificationTitleDesktop: promptOptions.fullscreen.title,\n exampleNotificationTitleMobile: promptOptions.fullscreen.title,\n exampleNotificationMessageDesktop: promptOptions.fullscreen.message,\n exampleNotificationMessageMobile: promptOptions.fullscreen.message,\n exampleNotificationCaption: promptOptions.fullscreen.caption,\n acceptButton: promptOptions.fullscreen.acceptButton,\n cancelButton: promptOptions.fullscreen.cancelButton,\n };\n }\n static getPromptOptionsQueryString() {\n const promptOptions = MainHelper.getFullscreenPermissionMessageOptions(OneSignal.config.userConfig.promptOptions);\n let promptOptionsStr = '';\n if (promptOptions) {\n const hash = MainHelper.getPromptOptionsPostHash();\n for (const key of Object.keys(hash)) {\n var value = hash[key];\n promptOptionsStr += '&' + key + '=' + value;\n }\n }\n return promptOptionsStr;\n }\n static getPromptOptionsPostHash() {\n const promptOptions = MainHelper.getFullscreenPermissionMessageOptions(OneSignal.config.userConfig.promptOptions);\n if (promptOptions) {\n var legacyParams = {\n exampleNotificationTitleDesktop: 'exampleNotificationTitle',\n exampleNotificationMessageDesktop: 'exampleNotificationMessage',\n exampleNotificationTitleMobile: 'exampleNotificationTitle',\n exampleNotificationMessageMobile: 'exampleNotificationMessage'\n };\n for (const legacyParamKey of Object.keys(legacyParams)) {\n const legacyParamValue = legacyParams[legacyParamKey];\n if (promptOptions[legacyParamKey]) {\n promptOptions[legacyParamValue] = promptOptions[legacyParamKey];\n }\n }\n var allowedPromptOptions = [\n 'autoAcceptTitle',\n 'siteName',\n 'autoAcceptTitle',\n 'subscribeText',\n 'showGraphic',\n 'actionMessage',\n 'exampleNotificationTitle',\n 'exampleNotificationMessage',\n 'exampleNotificationCaption',\n 'acceptButton',\n 'cancelButton',\n 'timeout'\n ];\n var hash = {};\n for (var i = 0; i < allowedPromptOptions.length; i++) {\n var key = allowedPromptOptions[i];\n var value = promptOptions[key];\n var encoded_value = encodeURIComponent(value);\n if (value || value === false || value === '') {\n hash[key] = encoded_value;\n }\n }\n }\n return hash;\n }\n static triggerCustomPromptClicked(clickResult) {\n Event.trigger(OneSignal.EVENTS.CUSTOM_PROMPT_CLICKED, {\n result: clickResult\n });\n }\n static async getAppId() {\n if (OneSignal.config.appId) {\n return Promise.resolve(OneSignal.config.appId);\n }\n else {\n const appId = await Database.get('Ids', 'appId');\n return appId;\n }\n }\n static async createDeviceRecord(appId, includeSubscription = false) {\n let subscription;\n if (includeSubscription) {\n // TODO: refactor to replace config with dependency injection\n const rawSubscription = await SubscriptionHelper.getRawPushSubscription(OneSignal.environmentInfo, OneSignal.config.safariWebId);\n if (rawSubscription) {\n subscription = rawSubscription;\n }\n }\n const deviceRecord = new PushDeviceRecord(subscription);\n deviceRecord.appId = appId;\n deviceRecord.subscriptionState = await MainHelper.getCurrentNotificationType();\n return deviceRecord;\n }\n static async getDeviceId() {\n const subscription = await OneSignal.database.getSubscription();\n return subscription.deviceId || undefined;\n }\n}\n//# sourceMappingURL=MainHelper.js.map","import OneSignalApiShared from \"../OneSignalApiShared\";\nimport { SubscriptionStateKind } from '../models/SubscriptionStateKind';\nimport { NotSubscribedError, NotSubscribedReason } from \"../errors/NotSubscribedError\";\nimport MainHelper from '../helpers/MainHelper';\nimport Database from \"../services/Database\";\nimport Log from \"../libraries/Log\";\nimport Utils from \"../context/shared/utils/Utils\";\nimport { SessionOrigin } from \"../models/Session\";\nimport { awaitSdkEvent, logMethodCall } from '../utils';\nimport { ExternalUserIdHelper } from \"../helpers/shared/ExternalUserIdHelper\";\nexport class UpdateManager {\n constructor(context) {\n this.context = context;\n this.onSessionSent = context.pageViewManager.getPageViewCount() > 1;\n }\n async isDeviceIdAvailable() {\n return (await Database.getSubscription()).deviceId != null;\n }\n async getDeviceId() {\n const { deviceId } = await Database.getSubscription();\n if (!deviceId) {\n throw new NotSubscribedError(NotSubscribedReason.NoDeviceId);\n }\n return deviceId;\n }\n async createDeviceRecord() {\n return MainHelper.createDeviceRecord(this.context.appConfig.appId);\n }\n async sendPushDeviceRecordUpdate(deviceRecord) {\n const existingUser = await this.context.subscriptionManager.isAlreadyRegisteredWithOneSignal();\n if (!existingUser) {\n Log.debug(\"Not sending the update because user is not registered with OneSignal (no device id)\");\n return;\n }\n const deviceId = await this.getDeviceId();\n if (!deviceRecord) {\n deviceRecord = await this.createDeviceRecord();\n }\n if (this.onSessionSent) {\n await OneSignalApiShared.updatePlayer(this.context.appConfig.appId, deviceId, Object.assign({ notification_types: SubscriptionStateKind.Subscribed }, deviceRecord.serialize()));\n }\n else {\n await this.sendOnSessionUpdate(deviceRecord);\n }\n }\n // If user has been subscribed before, send the on_session update to our backend on the first page view.\n async sendOnSessionUpdate(deviceRecord) {\n if (this.onSessionSent) {\n return;\n }\n if (!this.context.pageViewManager.isFirstPageView()) {\n return;\n }\n const existingUser = await this.context.subscriptionManager.isAlreadyRegisteredWithOneSignal();\n if (!existingUser) {\n Log.debug(\"Not sending the on session because user is not registered with OneSignal (no device id)\");\n return;\n }\n const deviceId = await this.getDeviceId();\n if (!deviceRecord) {\n deviceRecord = await this.createDeviceRecord();\n }\n if (deviceRecord.subscriptionState !== SubscriptionStateKind.Subscribed &&\n OneSignal.config.enableOnSession !== true) {\n return;\n }\n try {\n // Not sending on_session here but from SW instead.\n // Not awaiting here on purpose\n this.context.sessionManager.upsertSession(deviceId, deviceRecord, SessionOrigin.PlayerOnSession);\n this.onSessionSent = true;\n }\n catch (e) {\n Log.error(`Failed to update user session. Error \"${e.message}\" ${e.stack}`);\n }\n }\n async sendPlayerCreate(deviceRecord) {\n await ExternalUserIdHelper.addExternalUserIdToDeviceRecord(deviceRecord);\n try {\n const deviceId = await OneSignalApiShared.createUser(deviceRecord);\n if (deviceId) {\n Log.info(\"Subscribed to web push and registered with OneSignal\", deviceRecord, deviceId);\n this.onSessionSent = true;\n // Not awaiting here on purpose\n this.context.sessionManager.upsertSession(deviceId, deviceRecord, SessionOrigin.PlayerCreate);\n return deviceId;\n }\n Log.error(`Failed to create user.`);\n return undefined;\n }\n catch (e) {\n Log.error(`Failed to create user. Error \"${e.message}\" ${e.stack}`);\n return undefined;\n }\n }\n onSessionAlreadyCalled() {\n return this.onSessionSent;\n }\n async sendExternalUserIdUpdate(externalUserId, authHash) {\n if (!authHash) {\n authHash = await Database.getExternalUserIdAuthHash();\n }\n const payload = {\n external_user_id: Utils.getValueOrDefault(externalUserId, \"\"),\n external_user_id_auth_hash: Utils.getValueOrDefault(authHash, undefined)\n };\n // 1. Update any secondary channels such as email with external_user_id\n // Not awaiting as this may never complete, as promise only completes if we have a player record for each channel.\n /* tslint:disable:no-floating-promises */\n this.context.secondaryChannelManager.synchronizer.setExternalUserId(payload.external_user_id, payload.external_user_id_auth_hash);\n /* tslint:enable:no-floating-promises */\n // 2. Update push player with external_user_id\n const pushUpdatePromise = this.sendPushPlayerUpdate(payload);\n if (await this.isDeviceIdAvailable()) {\n await pushUpdatePromise;\n }\n }\n async sendTagsUpdate(tags) {\n this.context.secondaryChannelManager.synchronizer.setTags(tags);\n const options = { tags };\n const authHash = await Database.getExternalUserIdAuthHash();\n if (!!authHash) {\n options.external_user_id_auth_hash = authHash;\n }\n const pushUpdatePromise = this.sendPushPlayerUpdate(options);\n if (await this.isDeviceIdAvailable()) {\n await pushUpdatePromise;\n }\n }\n // Send REST API payload to update the push player record.\n // Await until we have a push playerId, which is require to make a PUT call.\n async sendPushPlayerUpdate(payload) {\n let { deviceId } = await Database.getSubscription();\n if (!deviceId) {\n await awaitSdkEvent(OneSignal.EVENTS.REGISTERED);\n ({ deviceId } = await Database.getSubscription());\n }\n if (deviceId) {\n return await OneSignalApiShared.updatePlayer(this.context.appConfig.appId, deviceId, payload);\n }\n }\n async sendOutcomeDirect(appId, notificationIds, outcomeName, value) {\n logMethodCall(\"sendOutcomeDirect\");\n const deviceRecord = await this.createDeviceRecord();\n const outcomeRequestData = {\n app_id: appId,\n id: outcomeName,\n device_type: deviceRecord.deliveryPlatform,\n notification_ids: notificationIds,\n direct: true,\n };\n if (value !== undefined) {\n outcomeRequestData.weight = value;\n }\n await OneSignalApiShared.sendOutcome(outcomeRequestData);\n }\n async sendOutcomeInfluenced(appId, notificationIds, outcomeName, value) {\n logMethodCall(\"sendOutcomeInfluenced\");\n const deviceRecord = await this.createDeviceRecord();\n const outcomeRequestData = {\n app_id: appId,\n id: outcomeName,\n device_type: deviceRecord.deliveryPlatform,\n notification_ids: notificationIds,\n direct: false,\n };\n if (value !== undefined) {\n outcomeRequestData.weight = value;\n }\n await OneSignalApiShared.sendOutcome(outcomeRequestData);\n }\n async sendOutcomeUnattributed(appId, outcomeName, value) {\n logMethodCall(\"sendOutcomeUnattributed\");\n const deviceRecord = await this.createDeviceRecord();\n const outcomeRequestData = {\n app_id: appId,\n id: outcomeName,\n device_type: deviceRecord.deliveryPlatform,\n };\n if (value !== undefined) {\n outcomeRequestData.weight = value;\n }\n await OneSignalApiShared.sendOutcome(outcomeRequestData);\n }\n}\n//# sourceMappingURL=UpdateManager.js.map","export class SessionManager {\n constructor(_context) { }\n async upsertSession(_deviceId, _deviceRecord, _sessionOrigin) {\n // TODO: how should it be implemented if called from inside of service worker???\n }\n}\n//# sourceMappingURL=SessionManager.js.map","import { WorkerMessenger } from '../libraries/WorkerMessenger';\nimport { PageViewManager } from '../managers/PageViewManager';\nimport PermissionManager from '../managers/PermissionManager';\nimport ContextHelper from \"../helpers/ContextHelper\";\nimport { UpdateManager } from \"../managers/UpdateManager\";\nimport { SessionManager } from \"../managers/sessionManager/sw/SessionManager\";\nimport { SecondaryChannelManager } from '../managers/channelManager/shared/SecondaryChannelManager';\nexport default class ContextSW {\n constructor(appConfig) {\n this.appConfig = appConfig;\n this.subscriptionManager = ContextHelper.getSubscriptionManager(this);\n this.serviceWorkerManager = ContextHelper.getServiceWorkerManager(this);\n this.pageViewManager = new PageViewManager();\n this.sessionManager = new SessionManager(this);\n this.permissionManager = new PermissionManager();\n this.workerMessenger = new WorkerMessenger(this);\n this.updateManager = new UpdateManager(this);\n this.secondaryChannelManager = new SecondaryChannelManager();\n }\n}\n//# sourceMappingURL=ContextSW.js.map","export class SecondaryChannelSynchronizer {\n constructor() {\n this._channels = [];\n }\n registerChannel(channel) {\n this._channels.push(channel);\n }\n // Common things all Secondary channels will handle\n async onSession() {\n await Promise.all(this._channels.map(channel => channel.onSession()));\n }\n async onFocus(sessionDuration) {\n await Promise.all(this._channels.map(channel => channel.onFocus(sessionDuration)));\n }\n async setTags(tags) {\n await Promise.all(this._channels.map(channel => channel.setTags(tags)));\n }\n async setExternalUserId(id, authHash) {\n await Promise.all(this._channels.map(channel => channel.setExternalUserId(id, authHash)));\n }\n}\n//# sourceMappingURL=SecondaryChannelSynchronizer.js.map","import JSONP from 'jsonp';\nimport SdkEnvironment from \"./managers/SdkEnvironment\";\nimport { WindowEnvironmentKind } from './models/WindowEnvironmentKind';\nimport OneSignalApiSW from \"./OneSignalApiSW\";\nimport OneSignalApiShared from \"./OneSignalApiShared\";\nexport default class OneSignalApi {\n static getPlayer(appId, playerId) {\n return OneSignalApiShared.getPlayer(appId, playerId);\n }\n static updatePlayer(appId, playerId, options) {\n return OneSignalApiShared.updatePlayer(appId, playerId, options);\n }\n static sendNotification(appId, playerIds, titles, contents, url, icon, data, buttons) {\n return OneSignalApiShared.sendNotification(appId, playerIds, titles, contents, url, icon, data, buttons);\n }\n static jsonpLib(url, fn) {\n JSONP(url, null, fn);\n }\n static async downloadServerAppConfig(appId) {\n if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker) {\n return await new Promise((resolve, reject) => {\n // Due to CloudFlare's algorithms, the .js extension is required for proper caching. Don't remove it!\n OneSignalApi.jsonpLib(`${SdkEnvironment.getOneSignalApiUrl().toString()}/sync/${appId}/web`, (err, data) => {\n if (err)\n reject(err);\n else {\n if (data.success)\n resolve(data);\n else // For JSONP, we return a 200 even for errors, there's a success: false param\n reject(data);\n }\n });\n });\n }\n else {\n return await OneSignalApiSW.downloadServerAppConfig(appId);\n }\n }\n static async createUser(deviceRecord) {\n return await OneSignalApiShared.createUser(deviceRecord);\n }\n static async logoutEmail(appConfig, emailProfile, deviceId) {\n return await OneSignalApiShared.logoutEmail(appConfig, emailProfile, deviceId);\n }\n static async updateUserSession(userId, deviceRecord) {\n return await OneSignalApiShared.updateUserSession(userId, deviceRecord);\n }\n}\n//# sourceMappingURL=OneSignalApi.js.map","import { NotSubscribedError, NotSubscribedReason } from \"../../../errors/NotSubscribedError\";\nimport Log from \"../../../libraries/Log\";\nimport { EmailProfile } from \"../../../models/EmailProfile\";\nimport OneSignalApi from \"../../../OneSignalApi\";\nimport Database from \"../../../services/Database\";\nexport class SecondaryChannelEmail {\n constructor(secondaryChannelIdentifierUpdater, secondaryChannelExternalUserIdUpdater, secondaryChannelTagsUpdater, secondaryChannelSessionUpdater, secondaryChannelFocusUpdater) {\n this.secondaryChannelIdentifierUpdater = secondaryChannelIdentifierUpdater;\n this.secondaryChannelExternalUserIdUpdater = secondaryChannelExternalUserIdUpdater;\n this.secondaryChannelTagsUpdater = secondaryChannelTagsUpdater;\n this.secondaryChannelSessionUpdater = secondaryChannelSessionUpdater;\n this.secondaryChannelFocusUpdater = secondaryChannelFocusUpdater;\n }\n async logout() {\n // 1. Check if we have an registered email to logout to begin with.\n const emailProfile = await Database.getEmailProfile();\n if (!emailProfile.subscriptionId) {\n Log.warn(new NotSubscribedError(NotSubscribedReason.NoEmailSet));\n return false;\n }\n // 2. Logout only applies if we a de-linking email from a push record.\n const { deviceId } = await Database.getSubscription();\n if (!deviceId) {\n Log.warn(new NotSubscribedError(NotSubscribedReason.NoDeviceId));\n return false;\n }\n // 3. Make logout email REST API call\n const appConfig = await Database.getAppConfig();\n if (!await OneSignalApi.logoutEmail(appConfig, emailProfile, deviceId)) {\n Log.warn(\"Failed to logout email.\");\n return false;\n }\n // 4. If above is successful clear the email profile.\n await Database.setEmailProfile(new EmailProfile());\n return true;\n }\n async setIdentifier(identifier, authHash) {\n const { profileProvider } = this.secondaryChannelIdentifierUpdater;\n const emailProfileBefore = await profileProvider.getProfile();\n const newEmailSubscriptionId = await this.secondaryChannelIdentifierUpdater.setIdentifier(identifier, authHash);\n if (newEmailSubscriptionId) {\n const emailProfileAfter = profileProvider.newProfile(newEmailSubscriptionId, identifier);\n await this.updatePushPlayersRelationToEmailPlayer(emailProfileBefore, emailProfileAfter);\n }\n return newEmailSubscriptionId;\n }\n async updatePushPlayersRelationToEmailPlayer(existingEmailProfile, newEmailProfile) {\n const { deviceId } = await Database.getSubscription();\n // If we are subscribed to web push\n const isExistingPushRecordSaved = deviceId;\n // And if we previously saved an email ID and it's different from the new returned ID\n const isExistingEmailSaved = !!existingEmailProfile.subscriptionId;\n const emailPreviouslySavedAndDifferent = !isExistingEmailSaved ||\n existingEmailProfile.subscriptionId !== newEmailProfile.subscriptionId;\n // Or if we previously saved an email and the email changed\n const emailPreviouslySavedAndChanged = !existingEmailProfile.identifier ||\n newEmailProfile.identifier !== existingEmailProfile.identifier;\n if (!!deviceId && isExistingPushRecordSaved && (emailPreviouslySavedAndDifferent || emailPreviouslySavedAndChanged)) {\n const authHash = await OneSignal.database.getExternalUserIdAuthHash();\n const appConfig = await Database.getAppConfig();\n // Then update the push device record with a reference to the new email ID and email address\n await OneSignalApi.updatePlayer(appConfig.appId, deviceId, {\n parent_player_id: newEmailProfile.subscriptionId,\n email: newEmailProfile.identifier,\n external_user_id_auth_hash: authHash\n });\n }\n }\n async onSession() {\n await this.secondaryChannelSessionUpdater.sendOnSession();\n }\n async onFocus(sessionDuration) {\n await this.secondaryChannelFocusUpdater.sendOnFocus(sessionDuration);\n }\n async setTags(tags) {\n await this.secondaryChannelTagsUpdater.sendTags(tags);\n }\n async setExternalUserId(id, authHash) {\n await this.secondaryChannelExternalUserIdUpdater.setExternalUserId(id, authHash);\n }\n}\n//# sourceMappingURL=SecondaryChannelEmail.js.map","import NotImplementedError from '../errors/NotImplementedError';\nimport { DeviceRecord } from './DeviceRecord';\n/**\n * Describes a secondary channel device record, such as an email.\n */\nexport class SecondaryChannelDeviceRecord extends DeviceRecord {\n /**\n * @param identifier Omitting this parameter does not void the record's identifier.\n */\n constructor(deliveryPlatform, identifier, identifierAuthHash, pushDeviceRecordId) {\n super();\n this.deliveryPlatform = deliveryPlatform;\n this.identifier = identifier;\n this.identifierAuthHash = identifierAuthHash;\n this.pushDeviceRecordId = pushDeviceRecordId;\n }\n serialize() {\n const serializedBundle = super.serialize();\n if (this.identifier) {\n serializedBundle.identifier = this.identifier;\n }\n if (this.identifierAuthHash) {\n serializedBundle.identifier_auth_hash = this.identifierAuthHash;\n }\n if (this.pushDeviceRecordId) {\n serializedBundle.device_player_id = this.pushDeviceRecordId;\n }\n return serializedBundle;\n }\n deserialize(_) { throw new NotImplementedError(); }\n}\n//# sourceMappingURL=SecondaryChannelDeviceRecord.js.map","import { ExternalUserIdHelper } from \"../../../../helpers/shared/ExternalUserIdHelper\";\nimport { SecondaryChannelDeviceRecord } from \"../../../../models/SecondaryChannelDeviceRecord\";\nimport OneSignalApi from \"../../../../OneSignalApi\";\nimport Database from \"../../../../services/Database\";\n// Creates / updates the identifier for a Secondary Channel and persists to storage.\nexport class SecondaryChannelIdentifierUpdater {\n constructor(profileProvider) {\n this.profileProvider = profileProvider;\n }\n async setIdentifier(identifier, authHash) {\n const appConfig = await Database.getAppConfig();\n const existingProfile = await this.profileProvider.getProfile();\n const newProfile = this.profileProvider.newProfile(existingProfile.subscriptionId, identifier, authHash);\n if (existingProfile.subscriptionId) {\n await OneSignalApi.updatePlayer(appConfig.appId, existingProfile.subscriptionId, {\n identifier,\n identifier_auth_hash: authHash\n });\n }\n else {\n // Otherwise, make a POST call to create a new record\n const { deviceId } = await Database.getSubscription();\n const deviceRecord = new SecondaryChannelDeviceRecord(this.profileProvider.deviceType, newProfile.identifier, newProfile.identifierAuthHash, deviceId);\n deviceRecord.appId = appConfig.appId;\n await ExternalUserIdHelper.addExternalUserIdToDeviceRecord(deviceRecord);\n newProfile.subscriptionId = await OneSignalApi.createUser(deviceRecord);\n }\n // Record update / create call, save to storage\n if (!!newProfile.subscriptionId) {\n await this.profileProvider.setProfile(newProfile);\n }\n return newProfile.subscriptionId;\n }\n}\n//# sourceMappingURL=SecondaryChannelIdentifierUpdater.js.map","import OneSignalApi from \"../../../../OneSignalApi\";\nimport Database from \"../../../../services/Database\";\nexport class SecondaryChannelTagsUpdater {\n constructor(profileProvider) {\n this.profileProvider = profileProvider;\n }\n async sendTags(tags) {\n // We wait until we have a subscriptionId. We do this instead of an early return\n // so we do not lose this value and the update can then be made as soon as possible.\n // Note: This promise may never resolve if the channel identifier is never set.\n // - Example if OneSignal.setEmail(\"\"...\"\") is never called\n const subscriptionId = await this.profileProvider.getSubscriptionId();\n const { appId } = await Database.getAppConfig();\n const identifierAuthHash = (await this.profileProvider.getProfile()).identifierAuthHash;\n const payload = {\n tags: tags,\n identifier_auth_hash: identifierAuthHash\n };\n await OneSignalApi.updatePlayer(appId, subscriptionId, payload);\n }\n}\n//# sourceMappingURL=SecondaryChannelTagsUpdater.js.map","import OneSignalApiShared from \"../../../../OneSignalApiShared\";\nimport Database from \"../../../../services/Database\";\nexport class SecondaryChannelExternalUserIdUpdater {\n constructor(profileProvider) {\n this.profileProvider = profileProvider;\n }\n async setExternalUserId(id, authHash) {\n // We wait until we have a subscriptionId. We do this instead of an early return\n // so we do not lose this value and the update can then be made as soon as possible.\n // Note: This promise may never resolve if the channel identifier is never set.\n // - Example if OneSignal.setEmail(\"\"...\"\") is never called\n const subscriptionId = await this.profileProvider.getSubscriptionId();\n const { appId } = await Database.getAppConfig();\n const payload = {\n external_user_id: id,\n external_user_id_auth_hash: authHash\n };\n await OneSignalApiShared.updatePlayer(appId, subscriptionId, payload);\n }\n}\n//# sourceMappingURL=SecondaryChannelExternalUserIdUpdater.js.map","import OneSignalApiBase from \"../../../../OneSignalApiBase\";\nimport Database from \"../../../../services/Database\";\nexport class SecondaryChannelFocusUpdater {\n constructor(profileProvider) {\n this.profileProvider = profileProvider;\n }\n async sendOnFocus(sessionDuration) {\n const profile = await this.profileProvider.getProfile();\n // If we haven't created a secondary device record yet then there isn't an on focus event to track.\n if (!profile.subscriptionId) {\n return;\n }\n const appConfig = await Database.getAppConfig();\n // NOTE: Omitting outcome attribution from the payload, only applies to push records.\n const payload = {\n app_id: appConfig.appId,\n type: 1,\n state: \"ping\",\n active_time: sessionDuration,\n device_type: this.profileProvider.deviceType,\n };\n await OneSignalApiBase.post(`players/${profile.subscriptionId}/on_focus`, payload);\n }\n}\n//# sourceMappingURL=SecondaryChannelFocusUpdater.js.map","import { SecondaryChannelDeviceRecord } from \"../../../../models/SecondaryChannelDeviceRecord\";\nimport OneSignalApiShared from \"../../../../OneSignalApiShared\";\nimport Database from \"../../../../services/Database\";\nexport class SecondaryChannelSessionUpdater {\n constructor(profileProvider) {\n this.profileProvider = profileProvider;\n }\n async sendOnSession() {\n const profile = await this.profileProvider.getProfile();\n // If we haven't created an email record yet then there isn't an on session event to track.\n if (!profile.subscriptionId) {\n return;\n }\n const secondaryChannelRecord = new SecondaryChannelDeviceRecord(this.profileProvider.deviceType, profile.identifier, profile.identifierAuthHash);\n const appConfig = await Database.getAppConfig();\n secondaryChannelRecord.appId = appConfig.appId;\n const newSubscriptionId = await OneSignalApiShared.updateUserSession(profile.subscriptionId, secondaryChannelRecord);\n // If on_session gave us a new subscriptionId store the updated value\n if (newSubscriptionId !== profile.subscriptionId) {\n profile.subscriptionId = newSubscriptionId;\n await this.profileProvider.setProfile(profile);\n }\n }\n}\n//# sourceMappingURL=SecondaryChannelSessionUpdater.js.map","export class SecondaryChannelProfileProviderBase {\n constructor() {\n this._pendingGetSubscriptionIdResolvers = [];\n }\n async setProfile(profile) {\n if (!profile.subscriptionId) {\n return;\n }\n const subscriptionId = profile.subscriptionId;\n this._pendingGetSubscriptionIdResolvers.map(resolve => { resolve(subscriptionId); });\n this._pendingGetSubscriptionIdResolvers = [];\n }\n /*\n * Awaitable until we can guarantee a subscriptionId is available\n */\n async getSubscriptionId() {\n // 1. If we already have a stored subscriptionId return it now.\n const profile = await this.getProfile();\n if (profile.subscriptionId) {\n return profile.subscriptionId;\n }\n // 2. If we don't, create a Promise and store it's resolve so we can fire it later.\n return new Promise((resolve) => {\n this._pendingGetSubscriptionIdResolvers.push(resolve);\n });\n }\n}\n//# sourceMappingURL=SecondaryChannelProfileProviderBase.js.map","import { DeliveryPlatformKind } from \"../../../../models/DeliveryPlatformKind\";\nimport { EmailProfile } from \"../../../../models/EmailProfile\";\nimport Database from \"../../../../services/Database\";\nimport { SecondaryChannelProfileProviderBase } from \"./SecondaryChannelProfileProviderBase\";\nexport class SecondaryChannelProfileProviderEmail extends SecondaryChannelProfileProviderBase {\n constructor() {\n super(...arguments);\n this.deviceType = DeliveryPlatformKind.Email;\n }\n newProfile(subscriptionId, identifier, identifierAuthHash) {\n return new EmailProfile(subscriptionId, identifier, identifierAuthHash);\n }\n async getProfile() {\n return await Database.getEmailProfile();\n }\n async setProfile(profile) {\n await Database.setEmailProfile(profile);\n await super.setProfile(profile);\n }\n}\n//# sourceMappingURL=SecondaryChannelProfileProviderEmail.js.map","import { DeliveryPlatformKind } from \"../../../../models/DeliveryPlatformKind\";\nimport { SMSProfile } from \"../../../../models/SMSProfile\";\nimport Database from \"../../../../services/Database\";\nimport { SecondaryChannelProfileProviderBase } from \"./SecondaryChannelProfileProviderBase\";\nexport class SecondaryChannelProfileProviderSMS extends SecondaryChannelProfileProviderBase {\n constructor() {\n super(...arguments);\n this.deviceType = DeliveryPlatformKind.SMS;\n }\n newProfile(subscriptionId, identifier, identifierAuthHash) {\n return new SMSProfile(subscriptionId, identifier, identifierAuthHash);\n }\n async getProfile() {\n return await Database.getSMSProfile();\n }\n async setProfile(profile) {\n await Database.setSMSProfile(profile);\n await super.setProfile(profile);\n }\n}\n//# sourceMappingURL=SecondaryChannelProfileProviderSMS.js.map","import { NotSubscribedError, NotSubscribedReason } from \"../../../errors/NotSubscribedError\";\nimport Log from \"../../../libraries/Log\";\nimport Database from \"../../../services/Database\";\nimport { SMSProfile } from \"../../../models/SMSProfile\";\nexport class SecondaryChannelSMS {\n constructor(secondaryChannelIdentifierUpdater, secondaryChannelExternalUserIdUpdater, secondaryChannelTagsUpdater, secondaryChannelSessionUpdater, secondaryChannelFocusUpdater) {\n this.secondaryChannelIdentifierUpdater = secondaryChannelIdentifierUpdater;\n this.secondaryChannelExternalUserIdUpdater = secondaryChannelExternalUserIdUpdater;\n this.secondaryChannelTagsUpdater = secondaryChannelTagsUpdater;\n this.secondaryChannelSessionUpdater = secondaryChannelSessionUpdater;\n this.secondaryChannelFocusUpdater = secondaryChannelFocusUpdater;\n }\n async logout() {\n // 1. Check if we have an registered sms to logout to begin with.\n const smsProfile = await Database.getSMSProfile();\n if (!smsProfile.subscriptionId) {\n Log.warn(new NotSubscribedError(NotSubscribedReason.NoSMSSet));\n return false;\n }\n // 2. If above is successful clear the SMS profile.\n await Database.setSMSProfile(new SMSProfile());\n return true;\n }\n async setIdentifier(identifier, authHash) {\n return await this.secondaryChannelIdentifierUpdater.setIdentifier(identifier, authHash);\n }\n async onSession() {\n await this.secondaryChannelSessionUpdater.sendOnSession();\n }\n async onFocus(sessionDuration) {\n await this.secondaryChannelFocusUpdater.sendOnFocus(sessionDuration);\n }\n async setTags(tags) {\n await this.secondaryChannelTagsUpdater.sendTags(tags);\n }\n async setExternalUserId(id, authHash) {\n await this.secondaryChannelExternalUserIdUpdater.setExternalUserId(id, authHash);\n }\n}\n//# sourceMappingURL=SecondaryChannelSMS.js.map","import { SecondaryChannelSynchronizer } from \"./SecondaryChannelSynchronizer\";\nimport { SecondaryChannelEmail } from \"./SecondaryChannelEmail\";\nimport { SecondaryChannelIdentifierUpdater } from \"./updaters/SecondaryChannelIdentifierUpdater\";\nimport { SecondaryChannelTagsUpdater } from \"./updaters/SecondaryChannelTagsUpdater\";\nimport { SecondaryChannelExternalUserIdUpdater } from \"./updaters/SecondaryChannelExternalUserIdUpdater\";\nimport { SecondaryChannelFocusUpdater } from \"./updaters/SecondaryChannelFocusUpdater\";\nimport { SecondaryChannelSessionUpdater } from \"./updaters/SecondaryChannelSessionUpdater\";\nimport { SecondaryChannelProfileProviderEmail } from \"./providers/SecondaryChannelProfileProviderEmail\";\nimport { SecondaryChannelProfileProviderSMS } from \"./providers/SecondaryChannelProfileProviderSMS\";\nimport { SecondaryChannelSMS } from \"./SecondaryChannelSMS\";\nexport class SecondaryChannelManager {\n constructor() {\n this.synchronizer = new SecondaryChannelSynchronizer();\n // Add Email\n const emailProfileProvider = new SecondaryChannelProfileProviderEmail();\n const emailChannel = new SecondaryChannelEmail(new SecondaryChannelIdentifierUpdater(emailProfileProvider), new SecondaryChannelExternalUserIdUpdater(emailProfileProvider), new SecondaryChannelTagsUpdater(emailProfileProvider), new SecondaryChannelSessionUpdater(emailProfileProvider), new SecondaryChannelFocusUpdater(emailProfileProvider));\n this.email = emailChannel;\n this.synchronizer.registerChannel(emailChannel);\n // Add SMS\n const smsProfileProvider = new SecondaryChannelProfileProviderSMS();\n const smsChannel = new SecondaryChannelSMS(new SecondaryChannelIdentifierUpdater(smsProfileProvider), new SecondaryChannelExternalUserIdUpdater(smsProfileProvider), new SecondaryChannelTagsUpdater(smsProfileProvider), new SecondaryChannelSessionUpdater(smsProfileProvider), new SecondaryChannelFocusUpdater(smsProfileProvider));\n this.sms = smsChannel;\n this.synchronizer.registerChannel(smsChannel);\n }\n}\n//# sourceMappingURL=SecondaryChannelManager.js.map","import Environment from \"../Environment\";\nexport class BrowserUtils {\n static decodeHtmlEntities(text) {\n if (Environment.isBrowser()) {\n if (!BrowserUtils.decodeTextArea) {\n BrowserUtils.decodeTextArea = document.createElement(\"textarea\");\n }\n }\n if (BrowserUtils.decodeTextArea) {\n BrowserUtils.decodeTextArea.innerHTML = text;\n return BrowserUtils.decodeTextArea.value;\n }\n else {\n // Not running in a browser environment, text cannot be decoded\n return text;\n }\n }\n}\nBrowserUtils.decodeTextArea = null;\nexport default BrowserUtils;\n//# sourceMappingURL=BrowserUtils.js.map","import Database from \"../../services/Database\";\nexport class ExternalUserIdHelper {\n static async addExternalUserIdToDeviceRecord(deviceRecord) {\n const externalUserId = await Database.getExternalUserId();\n if (!externalUserId) {\n return;\n }\n deviceRecord.externalUserId = externalUserId;\n const externalUserIdAuthHash = await Database.getExternalUserIdAuthHash();\n if (externalUserIdAuthHash) {\n deviceRecord.externalUserIdAuthHash = externalUserIdAuthHash;\n }\n }\n}\n//# sourceMappingURL=ExternalUserIdHelper.js.map","export var ConfigIntegrationKind;\n(function (ConfigIntegrationKind) {\n ConfigIntegrationKind[\"TypicalSite\"] = \"typical\";\n ConfigIntegrationKind[\"WordPress\"] = \"wordpress\";\n ConfigIntegrationKind[\"Shopify\"] = \"shopify\";\n ConfigIntegrationKind[\"Blogger\"] = \"blogger\";\n ConfigIntegrationKind[\"Magento\"] = \"magento\";\n ConfigIntegrationKind[\"Drupal\"] = \"drupal\";\n ConfigIntegrationKind[\"SquareSpace\"] = \"squarespace\";\n ConfigIntegrationKind[\"Joomla\"] = \"joomla\";\n ConfigIntegrationKind[\"Weebly\"] = \"weebly\";\n ConfigIntegrationKind[\"Wix\"] = \"wix\";\n ConfigIntegrationKind[\"Custom\"] = \"custom\";\n})(ConfigIntegrationKind || (ConfigIntegrationKind = {}));\nexport var NotificationClickMatchBehavior;\n(function (NotificationClickMatchBehavior) {\n NotificationClickMatchBehavior[\"Exact\"] = \"exact\";\n NotificationClickMatchBehavior[\"Origin\"] = \"origin\";\n})(NotificationClickMatchBehavior || (NotificationClickMatchBehavior = {}));\nexport var NotificationClickActionBehavior;\n(function (NotificationClickActionBehavior) {\n NotificationClickActionBehavior[\"Navigate\"] = \"navigate\";\n NotificationClickActionBehavior[\"Focus\"] = \"focus\";\n})(NotificationClickActionBehavior || (NotificationClickActionBehavior = {}));\n//# sourceMappingURL=AppConfig.js.map","import { DelayedPromptType } from \"../../src/models/Prompts\";\nexport const SERVER_CONFIG_DEFAULTS_SESSION = {\n reportingThreshold: 30,\n enableOnSessionForUnsubcribed: false,\n enableOnFocus: true,\n};\nexport const SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS = {\n pageViews: 1,\n timeDelay: 0\n};\nexport const SERVER_CONFIG_DEFAULTS_SLIDEDOWN = {\n actionMessage: \"We'd like to show you notifications for the latest news and updates.\",\n acceptButton: \"Allow\",\n cancelButton: \"Cancel\",\n errorButton: \"Try Again\",\n categoryDefaults: {\n updateMessage: \"Update your push notification subscription preferences.\",\n positiveUpdateButton: \"Save Preferences\",\n negativeUpdateButton: \"Cancel\"\n },\n savingText: \"Saving...\",\n confirmMessage: \"Thank You!\"\n};\nexport const CONFIG_DEFAULTS_SLIDEDOWN_OPTIONS = {\n type: DelayedPromptType.Push,\n text: {\n actionMessage: SERVER_CONFIG_DEFAULTS_SLIDEDOWN.actionMessage,\n acceptButton: SERVER_CONFIG_DEFAULTS_SLIDEDOWN.acceptButton,\n cancelButton: SERVER_CONFIG_DEFAULTS_SLIDEDOWN.cancelButton\n },\n autoPrompt: false,\n delay: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS\n};\n//# sourceMappingURL=index.js.map","import { deepCopy } from '../../src/utils';\nexport default class TagUtils {\n static convertTagsApiToBooleans(tags) {\n const convertedTags = {};\n Object.keys(tags).forEach(key => {\n convertedTags[key] = tags[key] === \"1\" ? true : false;\n });\n return convertedTags;\n }\n static convertTagsBooleansToApi(tags) {\n const convertedTags = {};\n Object.keys(tags).forEach(key => {\n convertedTags[key] = tags[key] === true ? \"1\" : \"0\";\n });\n return convertedTags;\n }\n /**\n * Used in determining what Tag/Category preferences changed in order\n * to only update what is necessary\n * @param {TagsObject} localTags - tags from taggingContainer with values of type \"number\"\n * @param {TagsObject} remoteTags - remote player tags with values of type \"number\"\n * @returns array of keys of corresponding different values (finds difference)\n */\n static getObjectDifference(localTags, remoteTags) {\n const finalTags = {};\n // Going off local tags since it's our categories. Trying to find only changed tags and returning those\n // as a final object.\n Object.keys(localTags).forEach(key => {\n // only if user's tag value did not change, skip it\n if (remoteTags[key] === localTags[key]) {\n return;\n }\n finalTags[key] = localTags[key];\n });\n return finalTags;\n }\n static markAllTagsAsSpecified(categoryArray, checked) {\n categoryArray.forEach(category => {\n category.checked = checked;\n });\n }\n static isTagObjectEmpty(tags) {\n return Object.keys(tags).length === 0;\n }\n /**\n * Uses configured categories and remote player tags to calculate which boxes should be checked\n * @param {TagCategory[]} categories\n * @param {TagsObjectWithBoolean} existingPlayerTags?\n */\n static getCheckedTagCategories(categories, existingPlayerTags) {\n if (!existingPlayerTags) {\n return categories;\n }\n const isExistingPlayerTagsEmpty = TagUtils.isTagObjectEmpty(existingPlayerTags);\n if (isExistingPlayerTagsEmpty) {\n const categoriesCopy = deepCopy(categories);\n TagUtils.markAllTagsAsSpecified(categoriesCopy, true);\n return categoriesCopy;\n }\n const categoriesCopy = deepCopy(categories);\n return categoriesCopy.map(category => {\n const existingTagValue = existingPlayerTags[category.tag];\n category.checked = TagUtils.getCheckedStatusForTagValue(existingTagValue);\n return category;\n });\n }\n static getCheckedStatusForTagValue(tagValue) {\n // If user does not have tag assigned to them, consider it selected\n if (tagValue === undefined) {\n return true;\n }\n return tagValue;\n }\n static limitCategoriesToMaxCount(tagCategories, max) {\n let tagCategoriesCopy = deepCopy(tagCategories);\n tagCategoriesCopy = tagCategories.slice(0, max);\n return tagCategoriesCopy;\n }\n}\n//# sourceMappingURL=TagUtils.js.map","import { ConfigIntegrationKind } from \"../models/AppConfig\";\nimport { WindowEnvironmentKind } from \"../models/WindowEnvironmentKind\";\nimport { SdkInitError, SdkInitErrorKind } from \"../errors/SdkInitError\";\nimport SdkEnvironment from \"../managers/SdkEnvironment\";\nimport OneSignalUtils from \"../utils/OneSignalUtils\";\nimport Utils from \"../context/shared/utils/Utils\";\nimport { SERVER_CONFIG_DEFAULTS_SESSION, SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS, SERVER_CONFIG_DEFAULTS_SLIDEDOWN, CONFIG_DEFAULTS_SLIDEDOWN_OPTIONS } from \"../config\";\nimport { DelayedPromptType, } from '../models/Prompts';\nimport TagUtils from '../../src/utils/TagUtils';\nimport PromptsHelper from './PromptsHelper';\nimport { ConverterHelper } from \"./ConverterHelper\";\nexport var IntegrationConfigurationKind;\n(function (IntegrationConfigurationKind) {\n /**\n * Configuration comes from the dashboard only.\n */\n IntegrationConfigurationKind[IntegrationConfigurationKind[\"Dashboard\"] = 0] = \"Dashboard\";\n /**\n * Configuration comes from user-provided JavaScript code only.\n */\n IntegrationConfigurationKind[IntegrationConfigurationKind[\"JavaScript\"] = 1] = \"JavaScript\";\n})(IntegrationConfigurationKind || (IntegrationConfigurationKind = {}));\nconst MAX_CATEGORIES = 10;\nexport class ConfigHelper {\n static async getAppConfig(userConfig, downloadServerAppConfig) {\n try {\n if (!userConfig || !userConfig.appId || !OneSignalUtils.isValidUuid(userConfig.appId))\n throw new SdkInitError(SdkInitErrorKind.InvalidAppId);\n const serverConfig = await downloadServerAppConfig(userConfig.appId);\n ConverterHelper.upgradeConfigToVersionTwo(userConfig);\n const appConfig = this.getMergedConfig(userConfig, serverConfig);\n this.checkRestrictedOrigin(appConfig);\n return appConfig;\n }\n catch (e) {\n if (e) {\n if (e.code === 1)\n throw new SdkInitError(SdkInitErrorKind.InvalidAppId);\n else if (e.code === 2)\n throw new SdkInitError(SdkInitErrorKind.AppNotConfiguredForWebPush);\n }\n throw e;\n }\n }\n static checkRestrictedOrigin(appConfig) {\n if (appConfig.restrictedOriginEnabled) {\n if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker) {\n if (window.top === window &&\n !Utils.contains(window.location.hostname, \".os.tc\") &&\n !Utils.contains(window.location.hostname, \".onesignal.com\") &&\n !this.doesCurrentOriginMatchConfigOrigin(appConfig.origin)) {\n throw new SdkInitError(SdkInitErrorKind.WrongSiteUrl, {\n siteUrl: appConfig.origin\n });\n }\n }\n }\n }\n static doesCurrentOriginMatchConfigOrigin(configOrigin) {\n try {\n return location.origin === new URL(configOrigin).origin;\n }\n catch (e) {\n return false;\n }\n }\n static getIntegrationCapabilities(integration) {\n switch (integration) {\n case ConfigIntegrationKind.Custom:\n case ConfigIntegrationKind.WordPress:\n return { configuration: IntegrationConfigurationKind.JavaScript };\n default:\n return { configuration: IntegrationConfigurationKind.Dashboard };\n }\n }\n static getMergedConfig(userConfig, serverConfig) {\n const configIntegrationKind = this.getConfigIntegrationKind(serverConfig);\n const subdomain = this.getSubdomainForConfigIntegrationKind(configIntegrationKind, userConfig, serverConfig);\n const allowLocalhostAsSecureOrigin = (serverConfig.config.setupBehavior ?\n serverConfig.config.setupBehavior.allowLocalhostAsSecureOrigin :\n userConfig.allowLocalhostAsSecureOrigin);\n const isUsingSubscriptionWorkaround = OneSignalUtils.internalIsUsingSubscriptionWorkaround(subdomain, allowLocalhostAsSecureOrigin);\n const mergedUserConfig = this.getUserConfigForConfigIntegrationKind(configIntegrationKind, userConfig, serverConfig, isUsingSubscriptionWorkaround);\n return {\n appId: serverConfig.app_id,\n subdomain,\n siteName: serverConfig.config.siteInfo.name,\n origin: serverConfig.config.origin,\n httpUseOneSignalCom: serverConfig.config.http_use_onesignal_com,\n restrictedOriginEnabled: serverConfig.features.restrict_origin && serverConfig.features.restrict_origin.enable,\n metrics: {\n enable: serverConfig.features.metrics.enable,\n mixpanelReportingToken: serverConfig.features.metrics.mixpanel_reporting_token\n },\n safariWebId: serverConfig.config.safari_web_id,\n vapidPublicKey: serverConfig.config.vapid_public_key,\n onesignalVapidPublicKey: serverConfig.config.onesignal_vapid_public_key,\n userConfig: mergedUserConfig,\n // default confirmed deliveries feature to off\n receiveReceiptsEnable: serverConfig.features.receive_receipts_enable || false,\n enableOnSession: Utils.valueOrDefault(serverConfig.features.enable_on_session, SERVER_CONFIG_DEFAULTS_SESSION.enableOnSessionForUnsubcribed),\n sessionThreshold: Utils.valueOrDefault(serverConfig.features.session_threshold, SERVER_CONFIG_DEFAULTS_SESSION.reportingThreshold),\n enableSessionDuration: Utils.valueOrDefault(serverConfig.features.web_on_focus_enabled, SERVER_CONFIG_DEFAULTS_SESSION.enableOnFocus)\n };\n }\n static getConfigIntegrationKind(serverConfig) {\n if (serverConfig.config.integration)\n return serverConfig.config.integration.kind;\n return ConfigIntegrationKind.Custom;\n }\n static getCustomLinkConfig(serverConfig) {\n const initialState = {\n enabled: false,\n style: \"button\",\n size: \"medium\",\n unsubscribeEnabled: false,\n text: {\n explanation: \"\",\n subscribe: \"\",\n unsubscribe: \"\",\n },\n color: {\n button: \"\",\n text: \"\",\n }\n };\n if (!serverConfig || !serverConfig.config ||\n !serverConfig.config.staticPrompts || !serverConfig.config.staticPrompts.customlink ||\n !serverConfig.config.staticPrompts.customlink.enabled) {\n return initialState;\n }\n const customlink = serverConfig.config.staticPrompts.customlink;\n return {\n enabled: customlink.enabled,\n style: customlink.style,\n size: customlink.size,\n unsubscribeEnabled: customlink.unsubscribeEnabled,\n text: customlink.text ? {\n subscribe: customlink.text.subscribe,\n unsubscribe: customlink.text.unsubscribe,\n explanation: customlink.text.explanation,\n } : initialState.text,\n color: customlink.color ? {\n button: customlink.color.button,\n text: customlink.color.text,\n } : initialState.color,\n };\n }\n /**\n * Used for Custom Code Integration Type\n * @param {AppUserConfigPromptOptions|undefined} promptOptions\n * @param {ServerAppPromptConfig} defaultsFromServer\n * @param {AppUserConfig} wholeUserConfig\n * @param {boolean=false} isUsingSubscriptionWorkaround\n * @returns AppUserConfigPromptOptions\n */\n static injectDefaultsIntoPromptOptions(promptOptions, defaultsFromServer, wholeUserConfig, isUsingSubscriptionWorkaround = false) {\n var _a, _b;\n let customlinkUser = { enabled: false };\n if (promptOptions && promptOptions.customlink) {\n customlinkUser = promptOptions.customlink;\n }\n const customlinkDefaults = defaultsFromServer.customlink;\n const promptOptionsConfig = Object.assign(Object.assign({}, promptOptions), { customlink: {\n enabled: Utils.getValueOrDefault(customlinkUser.enabled, customlinkDefaults.enabled),\n style: Utils.getValueOrDefault(customlinkUser.style, customlinkDefaults.style),\n size: Utils.getValueOrDefault(customlinkUser.size, customlinkDefaults.size),\n unsubscribeEnabled: Utils.getValueOrDefault(customlinkUser.unsubscribeEnabled, customlinkDefaults.unsubscribeEnabled),\n text: {\n subscribe: Utils.getValueOrDefault(customlinkUser.text ? customlinkUser.text.subscribe : undefined, customlinkDefaults.text.subscribe),\n unsubscribe: Utils.getValueOrDefault(customlinkUser.text ? customlinkUser.text.unsubscribe : undefined, customlinkDefaults.text.unsubscribe),\n explanation: Utils.getValueOrDefault(customlinkUser.text ? customlinkUser.text.explanation : undefined, customlinkDefaults.text.explanation),\n },\n color: {\n button: Utils.getValueOrDefault(customlinkUser.color ? customlinkUser.color.button : undefined, customlinkDefaults.color.button),\n text: Utils.getValueOrDefault(customlinkUser.color ? customlinkUser.color.text : undefined, customlinkDefaults.color.text),\n },\n } });\n if (promptOptionsConfig.slidedown) {\n promptOptionsConfig.slidedown.prompts = (_b = (_a = promptOptionsConfig.slidedown) === null || _a === void 0 ? void 0 : _a.prompts) === null || _b === void 0 ? void 0 : _b.map(promptOption => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j;\n promptOption.type = Utils.getValueOrDefault(promptOption.type, DelayedPromptType.Push);\n if (promptOption.type === DelayedPromptType.Category) {\n promptOption.text = Object.assign(Object.assign({}, promptOption.text), { positiveUpdateButton: Utils.getValueOrDefault((_a = promptOption.text) === null || _a === void 0 ? void 0 : _a.positiveUpdateButton, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.categoryDefaults.positiveUpdateButton), negativeUpdateButton: Utils.getValueOrDefault((_b = promptOption.text) === null || _b === void 0 ? void 0 : _b.negativeUpdateButton, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.categoryDefaults.negativeUpdateButton), updateMessage: Utils.getValueOrDefault((_c = promptOption.text) === null || _c === void 0 ? void 0 : _c.updateMessage, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.categoryDefaults.updateMessage) });\n }\n promptOption.text = Object.assign(Object.assign({}, promptOption.text), { actionMessage: Utils.getValueOrDefault((_d = promptOption.text) === null || _d === void 0 ? void 0 : _d.actionMessage, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.actionMessage), acceptButton: Utils.getValueOrDefault((_e = promptOption.text) === null || _e === void 0 ? void 0 : _e.acceptButton, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.acceptButton), cancelButton: Utils.getValueOrDefault((_f = promptOption.text) === null || _f === void 0 ? void 0 : _f.cancelButton, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.cancelButton), confirmMessage: Utils.getValueOrDefault((_g = promptOption.text) === null || _g === void 0 ? void 0 : _g.confirmMessage, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.confirmMessage) });\n // default autoPrompt to true iff slidedown config exists but omitted the autoPrompt setting\n promptOption.autoPrompt = Utils.getValueOrDefault(promptOption.autoPrompt, true);\n promptOption.delay = {\n pageViews: Utils.getValueOrDefault((_h = promptOption.delay) === null || _h === void 0 ? void 0 : _h.pageViews, SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews),\n timeDelay: Utils.getValueOrDefault((_j = promptOption.delay) === null || _j === void 0 ? void 0 : _j.timeDelay, SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay)\n };\n if (promptOption.categories) {\n const { categories } = promptOption;\n promptOption.categories = TagUtils.limitCategoriesToMaxCount(categories, MAX_CATEGORIES);\n }\n return promptOption;\n });\n }\n else {\n promptOptionsConfig.slidedown = { prompts: [] };\n promptOptionsConfig.slidedown.prompts = [CONFIG_DEFAULTS_SLIDEDOWN_OPTIONS];\n }\n if (promptOptionsConfig.native) {\n promptOptionsConfig.native.enabled = !!promptOptionsConfig.native.enabled;\n promptOptionsConfig.native.autoPrompt = promptOptionsConfig.native.hasOwnProperty(\"autoPrompt\") ?\n !!promptOptionsConfig.native.enabled && !!promptOptionsConfig.native.autoPrompt :\n !!promptOptionsConfig.native.enabled;\n promptOptionsConfig.native.pageViews = Utils.getValueOrDefault(promptOptionsConfig.native.pageViews, SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews);\n promptOptionsConfig.native.timeDelay = Utils.getValueOrDefault(promptOptionsConfig.native.timeDelay, SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay);\n }\n else {\n promptOptionsConfig.native = {\n enabled: false,\n autoPrompt: false,\n pageViews: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews,\n timeDelay: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay\n };\n }\n /**\n * If autoRegister is true, show native prompt for https and slidedown for http ignoring any other related\n * prompt options.\n */\n if (wholeUserConfig.autoRegister === true) {\n if (isUsingSubscriptionWorkaround) {\n // disable native prompt\n promptOptionsConfig.native.enabled = false;\n promptOptionsConfig.native.autoPrompt = false;\n // enable slidedown & make it autoPrompt\n const text = {\n actionMessage: SERVER_CONFIG_DEFAULTS_SLIDEDOWN.actionMessage,\n acceptButton: SERVER_CONFIG_DEFAULTS_SLIDEDOWN.acceptButton,\n cancelButton: SERVER_CONFIG_DEFAULTS_SLIDEDOWN.cancelButton,\n };\n promptOptionsConfig.slidedown.prompts = [{ type: DelayedPromptType.Push, autoPrompt: true, text }];\n }\n else {\n //enable native prompt & make it autoPrompt\n promptOptionsConfig.native.enabled = true;\n promptOptionsConfig.native.autoPrompt = true;\n //leave slidedown settings without change\n }\n }\n // sets top level `autoPrompt` to trigger autoprompt codepath in initialization / prompting flow\n promptOptionsConfig.autoPrompt = promptOptionsConfig.native.autoPrompt ||\n PromptsHelper.isSlidedownAutoPromptConfigured(promptOptionsConfig.slidedown.prompts);\n return promptOptionsConfig;\n }\n /**\n * Used only with Dashboard Configuration\n * @param {ServerAppConfig} serverConfig\n * @returns AppUserConfigPromptOptions\n */\n static getPromptOptionsForDashboardConfiguration(serverConfig) {\n const staticPrompts = serverConfig.config.staticPrompts;\n const native = staticPrompts.native ? {\n enabled: staticPrompts.native.enabled,\n autoPrompt: staticPrompts.native.enabled && staticPrompts.native.autoPrompt !== false,\n pageViews: Utils.getValueOrDefault(staticPrompts.native.pageViews, SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews),\n timeDelay: Utils.getValueOrDefault(staticPrompts.native.timeDelay, SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay)\n } : {\n enabled: false,\n autoPrompt: false,\n pageViews: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews,\n timeDelay: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay\n };\n const { prompts } = staticPrompts.slidedown;\n return {\n autoPrompt: native.autoPrompt || PromptsHelper.isSlidedownAutoPromptConfigured(prompts),\n native,\n slidedown: {\n prompts\n },\n fullscreen: {\n enabled: staticPrompts.fullscreen.enabled,\n actionMessage: staticPrompts.fullscreen.actionMessage,\n acceptButton: staticPrompts.fullscreen.acceptButton,\n cancelButton: staticPrompts.fullscreen.cancelButton,\n title: staticPrompts.fullscreen.title,\n message: staticPrompts.fullscreen.message,\n caption: staticPrompts.fullscreen.caption,\n autoAcceptTitle: staticPrompts.fullscreen.autoAcceptTitle,\n },\n customlink: this.getCustomLinkConfig(serverConfig),\n };\n }\n static getUserConfigForConfigIntegrationKind(configIntegrationKind, userConfig, serverConfig, isUsingSubscriptionWorkaround = false) {\n const integrationCapabilities = this.getIntegrationCapabilities(configIntegrationKind);\n switch (integrationCapabilities.configuration) {\n case IntegrationConfigurationKind.Dashboard:\n /*\n Ignores code-based initialization configuration and uses dashboard configuration only.\n */\n return {\n appId: serverConfig.app_id,\n autoRegister: false,\n autoResubscribe: serverConfig.config.autoResubscribe,\n path: serverConfig.config.serviceWorker.path,\n serviceWorkerPath: serverConfig.config.serviceWorker.workerName,\n serviceWorkerParam: { scope: serverConfig.config.serviceWorker.registrationScope },\n subdomainName: serverConfig.config.siteInfo.proxyOrigin,\n promptOptions: this.getPromptOptionsForDashboardConfiguration(serverConfig),\n welcomeNotification: {\n disable: !serverConfig.config.welcomeNotification.enable,\n title: serverConfig.config.welcomeNotification.title,\n message: serverConfig.config.welcomeNotification.message,\n url: serverConfig.config.welcomeNotification.url\n },\n notifyButton: {\n enable: serverConfig.config.staticPrompts.bell.enabled,\n displayPredicate: serverConfig.config.staticPrompts.bell.hideWhenSubscribed ?\n () => {\n return OneSignal.isPushNotificationsEnabled()\n .then((isPushEnabled) => {\n /* The user is subscribed, so we want to return \"false\" to hide the notify button */\n return !isPushEnabled;\n });\n } :\n null,\n size: serverConfig.config.staticPrompts.bell.size,\n position: serverConfig.config.staticPrompts.bell.location,\n showCredit: false,\n offset: {\n bottom: `${serverConfig.config.staticPrompts.bell.offset.bottom}px`,\n left: `${serverConfig.config.staticPrompts.bell.offset.left}px`,\n right: `${serverConfig.config.staticPrompts.bell.offset.right}px`\n },\n colors: {\n 'circle.background': serverConfig.config.staticPrompts.bell.color.main,\n 'circle.foreground': serverConfig.config.staticPrompts.bell.color.accent,\n 'badge.background': 'black',\n 'badge.foreground': 'white',\n 'badge.bordercolor': 'black',\n 'pulse.color': serverConfig.config.staticPrompts.bell.color.accent,\n 'dialog.button.background.hovering': serverConfig.config.staticPrompts.bell.color.main,\n 'dialog.button.background.active': serverConfig.config.staticPrompts.bell.color.main,\n 'dialog.button.background': serverConfig.config.staticPrompts.bell.color.main,\n 'dialog.button.foreground': 'white',\n },\n text: {\n 'tip.state.unsubscribed': serverConfig.config.staticPrompts.bell.tooltip.unsubscribed,\n 'tip.state.subscribed': serverConfig.config.staticPrompts.bell.tooltip.subscribed,\n 'tip.state.blocked': serverConfig.config.staticPrompts.bell.tooltip.blocked,\n 'message.prenotify': serverConfig.config.staticPrompts.bell.tooltip.unsubscribed,\n 'message.action.subscribing': serverConfig.config.staticPrompts.bell.message.subscribing,\n 'message.action.subscribed': serverConfig.config.staticPrompts.bell.message.subscribing,\n 'message.action.resubscribed': serverConfig.config.staticPrompts.bell.message.subscribing,\n 'message.action.unsubscribed': serverConfig.config.staticPrompts.bell.message.unsubscribing,\n 'dialog.main.title': serverConfig.config.staticPrompts.bell.dialog.main.title,\n 'dialog.main.button.subscribe': serverConfig.config.staticPrompts.bell.dialog.main.subscribeButton,\n 'dialog.main.button.unsubscribe': serverConfig.config.staticPrompts.bell.dialog.main.unsubscribeButton,\n 'dialog.blocked.title': serverConfig.config.staticPrompts.bell.dialog.blocked.title,\n 'dialog.blocked.message': serverConfig.config.staticPrompts.bell.dialog.blocked.message,\n },\n },\n persistNotification: serverConfig.config.notificationBehavior ?\n serverConfig.config.notificationBehavior.display.persist : undefined,\n webhooks: {\n cors: serverConfig.config.webhooks.corsEnable,\n 'notification.displayed': serverConfig.config.webhooks.notificationDisplayedHook,\n 'notification.clicked': serverConfig.config.webhooks.notificationClickedHook,\n 'notification.dismissed': serverConfig.config.webhooks.notificationDismissedHook,\n },\n notificationClickHandlerMatch: serverConfig.config.notificationBehavior ?\n serverConfig.config.notificationBehavior.click.match : undefined,\n notificationClickHandlerAction: serverConfig.config.notificationBehavior ?\n serverConfig.config.notificationBehavior.click.action : undefined,\n allowLocalhostAsSecureOrigin: serverConfig.config.setupBehavior ?\n serverConfig.config.setupBehavior.allowLocalhostAsSecureOrigin : undefined,\n requiresUserPrivacyConsent: userConfig.requiresUserPrivacyConsent,\n outcomes: {\n direct: serverConfig.config.outcomes.direct,\n indirect: {\n enabled: serverConfig.config.outcomes.indirect.enabled,\n influencedTimePeriodMin: serverConfig.config.outcomes.indirect.notification_attribution.minutes_since_displayed,\n influencedNotificationsLimit: serverConfig.config.outcomes.indirect.notification_attribution.limit,\n },\n unattributed: serverConfig.config.outcomes.unattributed,\n }\n };\n case IntegrationConfigurationKind.JavaScript:\n /*\n Ignores dashboard configuration and uses code-based configuration only.\n Except injecting some default values for prompts.\n */\n const isTopLevelServiceWorkerParamDefined = typeof OneSignal !== 'undefined' &&\n !!OneSignal.SERVICE_WORKER_PARAM;\n const isTopLevelServiceWorkerPathDefined = typeof OneSignal !== 'undefined' &&\n !!OneSignal.SERVICE_WORKER_PATH;\n const fallbackServiceWorkerParam = isTopLevelServiceWorkerParamDefined ?\n OneSignal.SERVICE_WORKER_PARAM : { scope: '/' };\n const fallbackServiceWorkerPath = isTopLevelServiceWorkerPathDefined ?\n OneSignal.SERVICE_WORKER_PATH : 'OneSignalSDKWorker.js';\n const config = Object.assign(Object.assign(Object.assign(Object.assign({}, userConfig), { promptOptions: this.injectDefaultsIntoPromptOptions(userConfig.promptOptions, serverConfig.config.staticPrompts, userConfig, isUsingSubscriptionWorkaround) }), {\n serviceWorkerParam: !!userConfig.serviceWorkerParam ?\n userConfig.serviceWorkerParam : fallbackServiceWorkerParam,\n serviceWorkerPath: !!userConfig.serviceWorkerPath ?\n userConfig.serviceWorkerPath : fallbackServiceWorkerPath,\n path: !!userConfig.path ? userConfig.path : '/'\n }), { outcomes: {\n direct: serverConfig.config.outcomes.direct,\n indirect: {\n enabled: serverConfig.config.outcomes.indirect.enabled,\n influencedTimePeriodMin: serverConfig.config.outcomes.indirect.notification_attribution.minutes_since_displayed,\n influencedNotificationsLimit: serverConfig.config.outcomes.indirect.notification_attribution.limit,\n },\n unattributed: serverConfig.config.outcomes.unattributed,\n } });\n if (userConfig.hasOwnProperty(\"autoResubscribe\")) {\n config.autoResubscribe = !!userConfig.autoResubscribe;\n }\n else if (userConfig.hasOwnProperty(\"autoRegister\")) {\n config.autoResubscribe = !!userConfig.autoRegister;\n }\n else {\n config.autoResubscribe = !!serverConfig.config.autoResubscribe;\n }\n return config;\n }\n }\n /**\n * Describes how to merge a dashboard-set subdomain with a/lack of user-supplied subdomain.\n */\n static getSubdomainForConfigIntegrationKind(configIntegrationKind, userConfig, serverConfig) {\n const integrationCapabilities = this.getIntegrationCapabilities(configIntegrationKind);\n const userValue = userConfig.subdomainName;\n let serverValue = '';\n switch (integrationCapabilities.configuration) {\n case IntegrationConfigurationKind.Dashboard:\n serverValue = serverConfig.config.siteInfo.proxyOriginEnabled ?\n serverConfig.config.siteInfo.proxyOrigin :\n undefined;\n break;\n case IntegrationConfigurationKind.JavaScript:\n serverValue = serverConfig.config.subdomain;\n break;\n }\n if (serverValue && !this.shouldUseServerConfigSubdomain(userValue, integrationCapabilities)) {\n return undefined;\n }\n else {\n return serverValue;\n }\n }\n static shouldUseServerConfigSubdomain(userProvidedSubdomain, capabilities) {\n switch (capabilities.configuration) {\n case IntegrationConfigurationKind.Dashboard:\n /*\n Dashboard config using the new web config editor always takes precedence.\n */\n return true;\n case IntegrationConfigurationKind.JavaScript:\n /*\n * An HTTPS site may be using either a native push integration or a fallback\n * subdomain integration. Our SDK decides the integration based on whether\n * init option subdomainName appears and the site's protocol.\n *\n * To avoid having developers write JavaScript to customize the SDK,\n * configuration properties like subdomainName are downloaded on page start.\n *\n * New developers setting up web push can omit subdomainName, but existing\n * developers already having written code to configure OneSignal aren't\n * removing their code.\n *\n * When an HTTPS site is configured with a subdomain on the server-side, we do\n * not apply it even though we've downloaded this configuration unless the\n * user also declares it manually in their initialization code.\n */\n switch (location.protocol) {\n case 'https:':\n return !!userProvidedSubdomain;\n case 'http:':\n return true;\n default:\n return false;\n }\n }\n }\n}\n//# sourceMappingURL=ConfigHelper.js.map","import { DelayedPromptType } from \"../../src/models/Prompts\";\nimport PromptsHelper from \"./PromptsHelper\";\nexport class ConverterHelper {\n /**\n * Standardizes config to version 2 of the config schema\n * @param {AppUserConfig} userConfig\n */\n static upgradeConfigToVersionTwo(userConfig) {\n var _a, _b, _c;\n if (ConverterHelper.isPromptOptionsVersion0(userConfig.promptOptions)) {\n userConfig.promptOptions = ConverterHelper.convertConfigToVersionOne(userConfig.promptOptions);\n }\n if (ConverterHelper.isSlidedownConfigVersion1((_a = userConfig.promptOptions) === null || _a === void 0 ? void 0 : _a.slidedown)) {\n if ((_b = userConfig.promptOptions) === null || _b === void 0 ? void 0 : _b.slidedown) {\n userConfig.promptOptions.slidedown =\n ConverterHelper.convertConfigToVersionTwo((_c = userConfig.promptOptions) === null || _c === void 0 ? void 0 : _c.slidedown);\n }\n }\n }\n /**\n * convertConfigToVersionOne - converts v0 schema to v1 schema format\n *\n * v0 schema example\n * ---\n * promptOptions: {\n * acceptButtonText: '',\n * cancelButtonText: '',\n * actionMessage : '',\n * slidedown: {...}\n * }\n *\n * v1 schema example\n * ---\n * \"promptOptions\": {\n * \"slidedown\": {\n * \"enabled\": true,\n * \"autoPrompt\": true,\n * \"acceptButtonText\": \"\",\n * \"cancelButtonText\": \"\",\n * \"actionMessage\": \"\",\n * \"...\",\n * }\n * }\n * @param {any} promptOptions\n * @returns AppUserConfigPromptOptions\n */\n static convertConfigToVersionOne(promptOptions) {\n if (!promptOptions.slidedown) {\n promptOptions.slidedown = {};\n }\n const { acceptButtonText, cancelButtonText, actionMessage } = promptOptions.slidedown;\n // we may have supported both of these keys in the past (with and without \"Text\" postfix)\n // so we're leaving here and checking in case it is being used this way\n const higherLevelAcceptButtonText = promptOptions.acceptButtonText || promptOptions.acceptButton;\n const higherLevelCancelButtonText = promptOptions.cancelButtonText || promptOptions.cancelButton;\n /**\n * we should give preference to the lower level (\"slidedown\" level) text settings in the case that\n * text settings are configured at the higher level as well as the lower level\n *\n * Example:\n * \"promptOptions\": {\n * \"acceptButtonText\": \"\",\n * \"cancelButtonText\": \"\",\n * \"slidedown\": {\n * \"acceptButtonText\": \"\", <--\n * \"cancelButtonText\": \"\" <--\n * }\n * }\n */\n promptOptions.slidedown.acceptButtonText = acceptButtonText || higherLevelAcceptButtonText;\n promptOptions.slidedown.cancelButtonText = cancelButtonText || higherLevelCancelButtonText;\n promptOptions.slidedown.actionMessage = actionMessage || promptOptions.actionMessage;\n return promptOptions;\n }\n static convertConfigToVersionTwo(slidedownConfig) {\n var _a, _b, _c, _d;\n // determine if the slidedown is category type or regular push\n const promptType = PromptsHelper.isCategorySlidedownConfiguredVersion1(slidedownConfig) ?\n DelayedPromptType.Category : DelayedPromptType.Push;\n let positiveUpdateButton, negativeUpdateButton;\n if (promptType === DelayedPromptType.Category) {\n positiveUpdateButton = (_a = slidedownConfig.categories) === null || _a === void 0 ? void 0 : _a.positiveUpdateButton;\n negativeUpdateButton = (_b = slidedownConfig.categories) === null || _b === void 0 ? void 0 : _b.negativeUpdateButton;\n }\n const existingPromptsConfig = slidedownConfig.prompts || [];\n return {\n prompts: [\n ...existingPromptsConfig,\n {\n type: promptType,\n autoPrompt: slidedownConfig.autoPrompt,\n text: {\n actionMessage: slidedownConfig.actionMessage,\n acceptButton: slidedownConfig.acceptButton || slidedownConfig.acceptButtonText,\n cancelButton: slidedownConfig.cancelButton || slidedownConfig.cancelButtonText,\n // categories-specific...\n positiveUpdateButton,\n negativeUpdateButton,\n updateMessage: (_c = slidedownConfig === null || slidedownConfig === void 0 ? void 0 : slidedownConfig.categories) === null || _c === void 0 ? void 0 : _c.updateMessage\n },\n delay: {\n pageViews: slidedownConfig.pageViews,\n timeDelay: slidedownConfig.timeDelay\n },\n categories: (_d = slidedownConfig === null || slidedownConfig === void 0 ? void 0 : slidedownConfig.categories) === null || _d === void 0 ? void 0 : _d.tags\n }\n ]\n };\n }\n /**\n * For use with Custom Code & Wordpress Implementations\n * The OneSignal Wordpress Plugin still uses these legacy keys to set the slidedown text\n * @param {any} slidedownConfig\n * @returns boolean\n */\n static isPromptOptionsVersion0(slidedownConfig) {\n if (!!slidedownConfig) {\n const version0Keys = [\n 'acceptButtonText',\n 'cancelButtonText',\n 'actionMessage'\n ];\n for (let i = 0; i < version0Keys.length; i++) {\n if (slidedownConfig.hasOwnProperty(version0Keys[i]))\n return true;\n }\n }\n return false;\n }\n /**\n * For use with Custom Code Implementations\n * Checks whether `slidedownConfig` implements `SlidedownOptionsVersion1` interface\n * ------------------------------\n * v1 schema:\n * ----------\n * \"slidedown\": {\n * \"enabled\": true,\n * \"autoPrompt\": true,\n * \"...\",\n * \"categories\": {...}\n * }\n *\n * v2 schema:\n * ----------\n * \"slidedown\": {\n * \"prompts\": [{...}, {...}, {...}]\n * }\n *\n * Since config can also be set via custom-code and we have no strict checks,\n * this function helps to check whether the config implements any v1 style config options\n * by looking for any of the v1 payload first-level keys. See `SlidedownOptionsVersion1`\n * for the full list of keys.\n * @param slidedownConfig\n */\n static isSlidedownConfigVersion1(slidedownConfig) {\n if (!!slidedownConfig) {\n const version1Keys = [\n 'enabled',\n 'autoPrompt',\n 'pageViews',\n 'timeDelay',\n 'acceptButton',\n 'acceptButtonText',\n 'cancelButton',\n 'cancelButtonText',\n 'actionMessage',\n 'customizeTextEnabled',\n 'categories'\n ];\n for (let i = 0; i < version1Keys.length; i++) {\n if (slidedownConfig.hasOwnProperty(version1Keys[i]))\n return true;\n }\n }\n return false;\n }\n}\n//# sourceMappingURL=ConverterHelper.js.map","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1, eval)(\"this\");\r\n} catch (e) {\r\n\t// This works if the window reference is available\r\n\tif (typeof window === \"object\") g = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n","// timeout with option to await on it\nexport function awaitableTimeout(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n//# sourceMappingURL=AwaitableTimeout.js.map","/**\n * Module exports.\n */\n\nmodule.exports = jsonp;\n\n/**\n * Callback index.\n */\n\nvar count = 0;\n\n/**\n * Noop function.\n */\n\nfunction noop(){}\n\n/**\n * JSONP handler\n *\n * Options:\n * - param {String} qs parameter (`callback`)\n * - prefix {String} qs parameter (`__jp`)\n * - name {String} qs parameter (`prefix` + incr)\n * - timeout {Number} how long after a timeout error is emitted (`60000`)\n *\n * @param {String} url\n * @param {Object|Function} optional options / callback\n * @param {Function} optional callback\n */\n\nfunction jsonp(url, opts, fn){\n if ('function' == typeof opts) {\n fn = opts;\n opts = {};\n }\n if (!opts) opts = {};\n\n var prefix = opts.prefix || '__jp';\n\n // use the callback name that was passed if one was provided.\n // otherwise generate a unique name by incrementing our counter.\n var id = opts.name || (prefix + (count++));\n\n var param = opts.param || 'callback';\n var timeout = null != opts.timeout ? opts.timeout : 60000;\n var enc = encodeURIComponent;\n var target = document.getElementsByTagName('script')[0] || document.head;\n var script;\n var timer;\n\n\n if (timeout) {\n timer = setTimeout(function(){\n cleanup();\n if (fn) fn(new Error('Timeout'));\n }, timeout);\n }\n\n function cleanup(){\n if (script.parentNode) script.parentNode.removeChild(script);\n window[id] = noop;\n if (timer) clearTimeout(timer);\n }\n\n function cancel(){\n if (window[id]) {\n cleanup();\n }\n }\n\n window[id] = function(data){\n cleanup();\n if (fn) fn(null, data);\n };\n\n // add qs component\n url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id);\n url = url.replace('?&', '?');\n\n // create script\n script = document.createElement('script');\n script.src = url;\n target.parentNode.insertBefore(script, target);\n\n return cancel;\n}\n","import bowser from \"bowser\";\nimport Environment from \"../Environment\";\nimport { WorkerMessenger, WorkerMessengerCommand } from \"../libraries/WorkerMessenger\";\nimport ContextSW from \"../models/ContextSW\";\nimport OneSignalApiBase from \"../OneSignalApiBase\";\nimport OneSignalApiSW from \"../OneSignalApiSW\";\nimport Database from \"../services/Database\";\nimport { RawPushSubscription } from \"../models/RawPushSubscription\";\nimport { SubscriptionStateKind } from \"../models/SubscriptionStateKind\";\nimport { PushDeviceRecord } from \"../models/PushDeviceRecord\";\nimport { SessionStatus } from \"../models/Session\";\nimport Log from \"../libraries/sw/Log\";\nimport { ConfigHelper } from \"../helpers/ConfigHelper\";\nimport { OneSignalUtils } from \"../utils/OneSignalUtils\";\nimport { Utils } from \"../context/shared/utils/Utils\";\nimport ServiceWorkerHelper from \"../helpers/ServiceWorkerHelper\";\nimport { cancelableTimeout } from \"../helpers/sw/CancelableTimeout\";\nimport { DeviceRecord } from '../models/DeviceRecord';\nimport { awaitableTimeout } from \"../utils/AwaitableTimeout\";\nconst MAX_CONFIRMED_DELIVERY_DELAY = 25;\n/**\n * The main service worker script fetching and displaying notifications to users in the background even when the client\n * site is not running. The worker is registered via the navigator.serviceWorker.register() call after the user first\n * allows notification permissions, and is a pre-requisite to subscribing for push notifications.\n *\n * For HTTPS sites, the service worker is registered site-wide at the top-level scope. For HTTP sites, the service\n * worker is registered to the iFrame pointing to subdomain.onesignal.com.\n */\nexport class ServiceWorker {\n /**\n * An incrementing integer defined in package.json. Value doesn't matter as long as it's different from the\n * previous version.\n */\n static get VERSION() {\n return Environment.version();\n }\n /**\n * Describes what context the JavaScript code is running in and whether we're running in local development mode.\n */\n static get environment() {\n return Environment;\n }\n static get log() {\n return Log;\n }\n /**\n * An interface to the browser's IndexedDB.\n */\n static get database() {\n return Database;\n }\n /**\n * Describes the current browser name and version.\n */\n static get browser() {\n return bowser;\n }\n /**\n * Allows message passing between this service worker and pages on the same domain.\n * Clients include any HTTPS site page, or the nested iFrame pointing to OneSignal on any HTTP site. This allows\n * events like notification dismissed, clicked, and displayed to be fired on the clients. It also allows the\n * clients to communicate with the service worker to close all active notifications.\n */\n static get workerMessenger() {\n if (!self.workerMessenger) {\n self.workerMessenger = new WorkerMessenger(null);\n }\n return self.workerMessenger;\n }\n /**\n * Service worker entry point.\n */\n static run() {\n self.addEventListener('activate', ServiceWorker.onServiceWorkerActivated);\n self.addEventListener('push', ServiceWorker.onPushReceived);\n self.addEventListener('notificationclose', ServiceWorker.onNotificationClosed);\n self.addEventListener('notificationclick', event => event.waitUntil(ServiceWorker.onNotificationClicked(event)));\n self.addEventListener('pushsubscriptionchange', (event) => {\n event.waitUntil(ServiceWorker.onPushSubscriptionChange(event));\n });\n self.addEventListener('message', (event) => {\n const data = event.data;\n if (!data || !data.command) {\n return;\n }\n const payload = data.payload;\n switch (data.command) {\n case WorkerMessengerCommand.SessionUpsert:\n Log.debug(\"[Service Worker] Received SessionUpsert\", payload);\n ServiceWorker.debounceRefreshSession(event, payload);\n break;\n case WorkerMessengerCommand.SessionDeactivate:\n Log.debug(\"[Service Worker] Received SessionDeactivate\", payload);\n ServiceWorker.debounceRefreshSession(event, payload);\n break;\n default:\n return;\n }\n });\n /*\n According to\n https://w3c.github.io/ServiceWorker/#run-service-worker-algorithm:\n \n \"user agents are encouraged to show a warning that the event listeners\n must be added on the very first evaluation of the worker script.\"\n \n We have to register our event handler statically (not within an\n asynchronous method) so that the browser can optimize not waking up the\n service worker for events that aren't known for sure to be listened for.\n \n Also see: https://github.com/w3c/ServiceWorker/issues/1156\n */\n Log.debug('Setting up message listeners.');\n // self.addEventListener('message') is statically added inside the listen() method\n ServiceWorker.workerMessenger.listen();\n // Install messaging event handlers for page <-> service worker communication\n ServiceWorker.setupMessageListeners();\n }\n static async getAppId() {\n if (self.location.search) {\n const match = self.location.search.match(/appId=([0-9a-z-]+)&?/i);\n // Successful regex matches are at position 1\n if (match && match.length > 1) {\n const appId = match[1];\n return appId;\n }\n }\n const { appId } = await Database.getAppConfig();\n return appId;\n }\n static setupMessageListeners() {\n ServiceWorker.workerMessenger.on(WorkerMessengerCommand.WorkerVersion, _ => {\n Log.debug('[Service Worker] Received worker version message.');\n ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.WorkerVersion, Environment.version());\n });\n ServiceWorker.workerMessenger.on(WorkerMessengerCommand.Subscribe, async (appConfigBundle) => {\n const appConfig = appConfigBundle;\n Log.debug('[Service Worker] Received subscribe message.');\n const context = new ContextSW(appConfig);\n const rawSubscription = await context.subscriptionManager.subscribe(0 /* ResubscribeExisting */);\n const subscription = await context.subscriptionManager.registerSubscription(rawSubscription);\n ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.Subscribe, subscription.serialize());\n });\n ServiceWorker.workerMessenger.on(WorkerMessengerCommand.SubscribeNew, async (appConfigBundle) => {\n const appConfig = appConfigBundle;\n Log.debug('[Service Worker] Received subscribe new message.');\n const context = new ContextSW(appConfig);\n const rawSubscription = await context.subscriptionManager.subscribe(1 /* SubscribeNew */);\n const subscription = await context.subscriptionManager.registerSubscription(rawSubscription);\n ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.SubscribeNew, subscription.serialize());\n });\n ServiceWorker.workerMessenger.on(WorkerMessengerCommand.AmpSubscriptionState, async (_appConfigBundle) => {\n Log.debug('[Service Worker] Received AMP subscription state message.');\n const pushSubscription = await self.registration.pushManager.getSubscription();\n if (!pushSubscription) {\n await ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.AmpSubscriptionState, false);\n }\n else {\n const permission = await self.registration.pushManager.permissionState(pushSubscription.options);\n const { optedOut } = await Database.getSubscription();\n const isSubscribed = !!pushSubscription && permission === \"granted\" && optedOut !== true;\n await ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.AmpSubscriptionState, isSubscribed);\n }\n });\n ServiceWorker.workerMessenger.on(WorkerMessengerCommand.AmpSubscribe, async () => {\n Log.debug('[Service Worker] Received AMP subscribe message.');\n const appId = await ServiceWorker.getAppId();\n const appConfig = await ConfigHelper.getAppConfig({ appId }, OneSignalApiSW.downloadServerAppConfig);\n const context = new ContextSW(appConfig);\n const rawSubscription = await context.subscriptionManager.subscribe(0 /* ResubscribeExisting */);\n const subscription = await context.subscriptionManager.registerSubscription(rawSubscription);\n await Database.put('Ids', { type: 'appId', id: appId });\n ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.AmpSubscribe, subscription.deviceId);\n });\n ServiceWorker.workerMessenger.on(WorkerMessengerCommand.AmpUnsubscribe, async () => {\n Log.debug('[Service Worker] Received AMP unsubscribe message.');\n const appId = await ServiceWorker.getAppId();\n const appConfig = await ConfigHelper.getAppConfig({ appId }, OneSignalApiSW.downloadServerAppConfig);\n const context = new ContextSW(appConfig);\n await context.subscriptionManager.unsubscribe(1 /* MarkUnsubscribed */);\n ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.AmpUnsubscribe, null);\n });\n ServiceWorker.workerMessenger.on(WorkerMessengerCommand.AreYouVisibleResponse, async (payload) => {\n Log.debug('[Service Worker] Received response for AreYouVisible', payload);\n if (!self.clientsStatus) {\n return;\n }\n const timestamp = payload.timestamp;\n if (self.clientsStatus.timestamp !== timestamp) {\n return;\n }\n self.clientsStatus.receivedResponsesCount++;\n if (payload.focused) {\n self.clientsStatus.hasAnyActiveSessions = true;\n }\n });\n ServiceWorker.workerMessenger.on(WorkerMessengerCommand.SetLogging, async (payload) => {\n if (payload.shouldLog) {\n self.shouldLog = true;\n }\n else {\n self.shouldLog = undefined;\n }\n });\n }\n /**\n * Occurs when a push message is received.\n * This method handles the receipt of a push signal on all web browsers except Safari, which uses the OS to handle\n * notifications.\n */\n static onPushReceived(event) {\n Log.debug(`Called %conPushReceived(${JSON.stringify(event, null, 4)}):`, Utils.getConsoleStyle('code'), event);\n event.waitUntil(ServiceWorker.parseOrFetchNotifications(event)\n .then(async (notifications) => {\n //Display push notifications in the order we received them\n const notificationEventPromiseFns = [];\n const notificationReceivedPromises = [];\n const appId = await ServiceWorker.getAppId();\n for (const rawNotification of notifications) {\n Log.debug('Raw Notification from OneSignal:', rawNotification);\n const notification = ServiceWorker.buildStructuredNotificationObject(rawNotification);\n const notificationReceived = {\n notificationId: notification.id,\n appId,\n url: notification.url,\n timestamp: new Date().getTime(),\n };\n notificationReceivedPromises.push(Database.put(\"NotificationReceived\", notificationReceived));\n // TODO: decide what to do with all the notif received promises\n // Probably should have it's own error handling but not blocking the rest of the execution?\n // Never nest the following line in a callback from the point of entering from retrieveNotifications\n notificationEventPromiseFns.push((notif => {\n return ServiceWorker.displayNotification(notif)\n .then(() => {\n return ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.NotificationDisplayed, notif).catch(e => Log.error(e));\n })\n .then(() => ServiceWorker.executeWebhooks('notification.displayed', notif)\n .then(() => ServiceWorker.sendConfirmedDelivery(notif)).catch(e => Log.error(e)));\n }).bind(null, notification));\n }\n return notificationEventPromiseFns.reduce((p, fn) => {\n return p = p.then(fn);\n }, Promise.resolve());\n })\n .catch(e => {\n Log.debug('Failed to display a notification:', e);\n if (ServiceWorker.UNSUBSCRIBED_FROM_NOTIFICATIONS) {\n Log.debug('Because we have just unsubscribed from notifications, we will not show anything.');\n return undefined;\n }\n }));\n }\n /**\n * Makes a POST call to a specified URL to forward certain events.\n * @param event The name of the webhook event. Affects the DB key pulled for settings and the final event the user\n * consumes.\n * @param notification A JSON object containing notification details the user consumes.\n * @returns {Promise}\n */\n static async executeWebhooks(event, notification) {\n const webhookTargetUrl = await Database.get('Options', `webhooks.${event}`);\n if (!webhookTargetUrl)\n return null;\n const { deviceId } = await Database.getSubscription();\n const isServerCorsEnabled = await Database.get('Options', 'webhooks.cors');\n // JSON.stringify() does not include undefined values\n // Our response will not contain those fields here which have undefined values\n const postData = {\n event: event,\n id: notification.id,\n userId: deviceId,\n action: notification.action,\n buttons: notification.buttons,\n heading: notification.heading,\n content: notification.content,\n url: notification.url,\n icon: notification.icon,\n data: notification.data\n };\n const fetchOptions = {\n method: 'post',\n mode: 'no-cors',\n body: JSON.stringify(postData),\n };\n if (isServerCorsEnabled) {\n fetchOptions.mode = 'cors';\n fetchOptions.headers = {\n 'X-OneSignal-Event': event,\n 'Content-Type': 'application/json'\n };\n }\n Log.debug(`Executing ${event} webhook ${isServerCorsEnabled ? 'with' : 'without'} CORS %cPOST ${webhookTargetUrl}`, Utils.getConsoleStyle('code'), ':', postData);\n return await fetch(webhookTargetUrl, fetchOptions);\n }\n /**\n * Makes a PUT call to log the delivery of the notification\n * @param notification A JSON object containing notification details.\n * @returns {Promise}\n */\n static async sendConfirmedDelivery(notification) {\n if (!notification)\n return null;\n // Received receipts enabled?\n if (notification.rr !== \"y\")\n return null;\n const appId = await ServiceWorker.getAppId();\n const { deviceId } = await Database.getSubscription();\n // app and notification ids are required, decided to exclude deviceId from required params\n // In rare case we don't have it we can still report as confirmed to backend to increment count\n const hasRequiredParams = !!(appId && notification.id);\n if (!hasRequiredParams) {\n return null;\n }\n // JSON.stringify() does not include undefined values\n // Our response will not contain those fields here which have undefined values\n const postData = {\n player_id: deviceId,\n app_id: appId,\n device_type: DeviceRecord.prototype.getDeliveryPlatform()\n };\n Log.debug(`Called %csendConfirmedDelivery(${JSON.stringify(notification, null, 4)})`, Utils.getConsoleStyle('code'));\n await awaitableTimeout(Math.floor(Math.random() * MAX_CONFIRMED_DELIVERY_DELAY * 1000));\n return await OneSignalApiBase.put(`notifications/${notification.id}/report_received`, postData);\n }\n /**\n * Gets an array of active window clients along with whether each window client is the HTTP site's iFrame or an\n * HTTPS site page.\n * An active window client is a browser tab that is controlled by the service worker.\n * Technically, this list should only ever contain clients that are iFrames, or clients that are HTTPS site pages,\n * and not both. This doesn't really matter though.\n * @returns {Promise}\n */\n static async getActiveClients() {\n const windowClients = await self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n });\n const activeClients = [];\n for (const client of windowClients) {\n const windowClient = client;\n windowClient.isSubdomainIframe = false;\n // Test if this window client is the HTTP subdomain iFrame pointing to subdomain.onesignal.com\n if (client.frameType && client.frameType === 'nested') {\n // Subdomain iFrames point to 'https://subdomain.onesignal.com...'\n if (!Utils.contains(client.url, '.os.tc') &&\n !Utils.contains(client.url, '.onesignal.com')) {\n continue;\n }\n // Indicates this window client is an HTTP subdomain iFrame\n windowClient.isSubdomainIframe = true;\n }\n activeClients.push(windowClient);\n }\n return activeClients;\n }\n static async updateSessionBasedOnHasActive(event, hasAnyActiveSessions, options) {\n if (hasAnyActiveSessions) {\n await ServiceWorkerHelper.upsertSession(options.sessionThreshold, options.enableSessionDuration, options.deviceRecord, options.deviceId, options.sessionOrigin, options.outcomesConfig);\n }\n else {\n const cancelableFinalize = await ServiceWorkerHelper.deactivateSession(options.sessionThreshold, options.enableSessionDuration, options.outcomesConfig);\n if (cancelableFinalize) {\n self.cancel = cancelableFinalize.cancel;\n event.waitUntil(cancelableFinalize.promise);\n }\n }\n }\n static async refreshSession(event, options) {\n Log.debug(\"[Service Worker] refreshSession\");\n /**\n * if https -> getActiveClients -> check for the first focused\n * unfortunately, not enough for safari, it always returns false for focused state of a client\n * have to workaround it with messaging to the client.\n *\n * if http, also have to workaround with messaging:\n * SW to iframe -> iframe to page -> page to iframe -> iframe to SW\n */\n if (options.isHttps) {\n const windowClients = await self.clients.matchAll({ type: \"window\", includeUncontrolled: true });\n if (options.isSafari) {\n await ServiceWorker.checkIfAnyClientsFocusedAndUpdateSession(event, windowClients, options);\n }\n else {\n const hasAnyActiveSessions = windowClients.some(w => w.focused);\n Log.debug(\"[Service Worker] isHttps hasAnyActiveSessions\", hasAnyActiveSessions);\n await ServiceWorker.updateSessionBasedOnHasActive(event, hasAnyActiveSessions, options);\n }\n return;\n }\n else {\n const osClients = await ServiceWorker.getActiveClients();\n await ServiceWorker.checkIfAnyClientsFocusedAndUpdateSession(event, osClients, options);\n }\n }\n static async checkIfAnyClientsFocusedAndUpdateSession(event, windowClients, sessionInfo) {\n const timestamp = new Date().getTime();\n self.clientsStatus = {\n timestamp,\n sentRequestsCount: 0,\n receivedResponsesCount: 0,\n hasAnyActiveSessions: false,\n };\n const payload = { timestamp };\n windowClients.forEach(c => {\n if (self.clientsStatus) {\n // keeping track of number of sent requests mostly for debugging purposes\n self.clientsStatus.sentRequestsCount++;\n }\n c.postMessage({ command: WorkerMessengerCommand.AreYouVisible, payload });\n });\n const updateOnHasActive = async () => {\n if (!self.clientsStatus) {\n return;\n }\n if (self.clientsStatus.timestamp !== timestamp) {\n return;\n }\n Log.debug(\"updateSessionBasedOnHasActive\", self.clientsStatus);\n await ServiceWorker.updateSessionBasedOnHasActive(event, self.clientsStatus.hasAnyActiveSessions, sessionInfo);\n self.clientsStatus = undefined;\n };\n const getClientStatusesCancelable = cancelableTimeout(updateOnHasActive, 0.5);\n self.cancel = getClientStatusesCancelable.cancel;\n event.waitUntil(getClientStatusesCancelable.promise);\n }\n static debounceRefreshSession(event, options) {\n Log.debug(\"[Service Worker] debounceRefreshSession\", options);\n if (self.cancel) {\n self.cancel();\n self.cancel = undefined;\n }\n const executeRefreshSession = async () => {\n await ServiceWorker.refreshSession(event, options);\n };\n const cancelableRefreshSession = cancelableTimeout(executeRefreshSession, 1);\n self.cancel = cancelableRefreshSession.cancel;\n event.waitUntil(cancelableRefreshSession.promise);\n }\n /**\n * Constructs a structured notification object from the raw notification fetched from OneSignal's server. This\n * object is passed around from event to event, and is also returned to the host page for notification event details.\n * Constructed in onPushReceived, and passed along to other event handlers.\n * @param rawNotification The raw notification JSON returned from OneSignal's server.\n */\n static buildStructuredNotificationObject(rawNotification) {\n const notification = {\n id: rawNotification.custom.i,\n heading: rawNotification.title,\n content: rawNotification.alert,\n data: rawNotification.custom.a,\n url: rawNotification.custom.u,\n rr: rawNotification.custom.rr,\n icon: rawNotification.icon,\n image: rawNotification.image,\n tag: rawNotification.tag,\n badge: rawNotification.badge,\n vibrate: rawNotification.vibrate\n };\n // Add action buttons\n if (rawNotification.o) {\n notification.buttons = [];\n for (const rawButton of rawNotification.o) {\n notification.buttons.push({\n action: rawButton.i,\n title: rawButton.n,\n icon: rawButton.p,\n url: rawButton.u\n });\n }\n }\n return Utils.trimUndefined(notification);\n }\n /**\n * Given an image URL, returns a proxied HTTPS image using the https://images.weserv.nl service.\n * For a null image, returns null so that no icon is displayed.\n * If the image protocol is HTTPS, or origin contains localhost or starts with 192.168.*.*, we do not proxy the image.\n * @param imageUrl An HTTP or HTTPS image URL.\n */\n static ensureImageResourceHttps(imageUrl) {\n if (imageUrl) {\n try {\n const parsedImageUrl = new URL(imageUrl);\n if (parsedImageUrl.hostname === 'localhost' ||\n parsedImageUrl.hostname.indexOf('192.168') !== -1 ||\n parsedImageUrl.hostname === '127.0.0.1' ||\n parsedImageUrl.protocol === 'https:') {\n return imageUrl;\n }\n if (parsedImageUrl.hostname === 'i0.wp.com' ||\n parsedImageUrl.hostname === 'i1.wp.com' ||\n parsedImageUrl.hostname === 'i2.wp.com' ||\n parsedImageUrl.hostname === 'i3.wp.com') {\n /* Their site already uses Jetpack, just make sure Jetpack is HTTPS */\n return `https://${parsedImageUrl.hostname}${parsedImageUrl.pathname}`;\n }\n /* HTTPS origin hosts can be used by prefixing the hostname with ssl: */\n const replacedImageUrl = parsedImageUrl.host + parsedImageUrl.pathname;\n return `https://i0.wp.com/${replacedImageUrl}`;\n }\n catch (e) { }\n }\n else\n return null;\n }\n /**\n * Given a structured notification object, HTTPS-ifies the notification icons and action button icons, if they exist.\n */\n static ensureNotificationResourcesHttps(notification) {\n if (notification) {\n if (notification.icon) {\n notification.icon = ServiceWorker.ensureImageResourceHttps(notification.icon);\n }\n if (notification.image) {\n notification.image = ServiceWorker.ensureImageResourceHttps(notification.image);\n }\n if (notification.buttons && notification.buttons.length > 0) {\n for (const button of notification.buttons) {\n if (button.icon) {\n button.icon = ServiceWorker.ensureImageResourceHttps(button.icon);\n }\n }\n }\n }\n }\n /**\n * Actually displays a visible notification to the user.\n * Any event needing to display a notification calls this so that all the display options can be centralized here.\n * @param notification A structured notification object.\n */\n static async displayNotification(notification, overrides) {\n Log.debug(`Called %cdisplayNotification(${JSON.stringify(notification, null, 4)}):`, Utils.getConsoleStyle('code'), notification);\n // Use the default title if one isn't provided\n const defaultTitle = await ServiceWorker._getTitle();\n // Use the default icon if one isn't provided\n const defaultIcon = await Database.get('Options', 'defaultIcon');\n // Get option of whether we should leave notification displaying indefinitely\n const persistNotification = await Database.get('Options', 'persistNotification');\n // Get app ID for tag value\n const appId = await ServiceWorker.getAppId();\n notification.heading = notification.heading ? notification.heading : defaultTitle;\n notification.icon = notification.icon ? notification.icon : (defaultIcon ? defaultIcon : undefined);\n const extra = {};\n extra.tag = notification.tag || appId;\n extra.persistNotification = persistNotification !== false;\n // Allow overriding some values\n if (!overrides)\n overrides = {};\n notification = Object.assign(Object.assign({}, notification), overrides);\n ServiceWorker.ensureNotificationResourcesHttps(notification);\n const notificationOptions = {\n body: notification.content,\n icon: notification.icon,\n /*\n On Chrome 56, a large image can be displayed:\n https://bugs.chromium.org/p/chromium/issues/detail?id=614456\n */\n image: notification.image,\n /*\n On Chrome 44+, use this property to store extra information which\n you can read back when the notification gets invoked from a\n notification click or dismissed event. We serialize the\n notification in the 'data' field and read it back in other events.\n See:\n https://developers.google.com/web/updates/2015/05/notifying-you-of-changes-to-notifications?hl=en\n */\n data: notification,\n /*\n On Chrome 48+, action buttons show below the message body of the\n notification. Clicking either button takes the user to a link. See:\n https://developers.google.com/web/updates/2016/01/notification-actions\n */\n actions: notification.buttons,\n /*\n Tags are any string value that groups notifications together. Two\n or notifications sharing a tag replace each other.\n */\n tag: extra.tag,\n /*\n On Chrome 47+ (desktop), notifications will be dismissed after 20\n seconds unless requireInteraction is set to true. See:\n https://developers.google.com/web/updates/2015/10/notification-requireInteractiom\n */\n requireInteraction: extra.persistNotification,\n /*\n On Chrome 50+, by default notifications replacing\n identically-tagged notifications no longer vibrate/signal the user\n that a new notification has come in. This flag allows subsequent\n notifications to re-alert the user. See:\n https://developers.google.com/web/updates/2016/03/notifications\n */\n renotify: true,\n /*\n On Chrome 53+, returns the URL of the image used to represent the\n notification when there is not enough space to display the\n notification itself.\n \n The URL of an image to represent the notification when there is not\n enough space to display the notification itself such as, for\n example, the Android Notification Bar. On Android devices, the\n badge should accommodate devices up to 4x resolution, about 96 by\n 96 px, and the image will be automatically masked.\n */\n badge: notification.badge,\n /*\n A vibration pattern to run with the display of the notification. A\n vibration pattern can be an array with as few as one member. The\n values are times in milliseconds where the even indices (0, 2, 4,\n etc.) indicate how long to vibrate and the odd indices indicate how\n long to pause. For example [300, 100, 400] would vibrate 300ms,\n pause 100ms, then vibrate 400ms.\n */\n vibrate: notification.vibrate\n };\n return self.registration.showNotification(notification.heading, notificationOptions);\n }\n /**\n * Returns false if the given URL matches a few special URLs designed to skip opening a URL when clicking a\n * notification. Otherwise returns true and the link will be opened.\n * @param url\n */\n static shouldOpenNotificationUrl(url) {\n return (url !== 'javascript:void(0);' &&\n url !== 'do_not_open' &&\n !Utils.contains(url, '_osp=do_not_open'));\n }\n /**\n * Occurs when a notification is dismissed by the user (clicking the 'X') or all notifications are cleared.\n * Supported on: Chrome 50+ only\n */\n static onNotificationClosed(event) {\n Log.debug(`Called %conNotificationClosed(${JSON.stringify(event, null, 4)}):`, Utils.getConsoleStyle('code'), event);\n const notification = event.notification.data;\n ServiceWorker.workerMessenger.broadcast(WorkerMessengerCommand.NotificationDismissed, notification).catch(e => Log.error(e));\n event.waitUntil(ServiceWorker.executeWebhooks('notification.dismissed', notification));\n }\n /**\n * After clicking a notification, determines the URL to open based on whether an action button was clicked or the\n * notification body was clicked.\n */\n static async getNotificationUrlToOpen(notification) {\n // Defaults to the URL the service worker was registered\n // TODO: This should be fixed for HTTP sites\n let launchUrl = location.origin;\n // Use the user-provided default URL if one exists\n const { defaultNotificationUrl: dbDefaultNotificationUrl } = await Database.getAppState();\n if (dbDefaultNotificationUrl)\n launchUrl = dbDefaultNotificationUrl;\n // If the user clicked an action button, use the URL provided by the action button\n // Unless the action button URL is null\n if (notification.action) {\n // Find the URL tied to the action button that was clicked\n for (const button of notification.buttons) {\n if (button.action === notification.action &&\n button.url &&\n button.url !== '') {\n launchUrl = button.url;\n }\n }\n }\n else if (notification.url &&\n notification.url !== '') {\n // The user clicked the notification body instead of an action button\n launchUrl = notification.url;\n }\n return launchUrl;\n }\n /**\n * Occurs when the notification's body or action buttons are clicked. Does not occur if the notification is\n * dismissed by clicking the 'X' icon. See the notification close event for the dismissal event.\n */\n static async onNotificationClicked(event) {\n Log.debug(`Called %conNotificationClicked(${JSON.stringify(event, null, 4)}):`, Utils.getConsoleStyle('code'), event);\n // Close the notification first here, before we do anything that might fail\n event.notification.close();\n const notificationData = event.notification.data;\n // Chrome 48+: Get the action button that was clicked\n if (event.action)\n notificationData.action = event.action;\n let notificationClickHandlerMatch = 'exact';\n let notificationClickHandlerAction = 'navigate';\n const matchPreference = await Database.get('Options', 'notificationClickHandlerMatch');\n if (matchPreference)\n notificationClickHandlerMatch = matchPreference;\n const actionPreference = await this.database.get('Options', 'notificationClickHandlerAction');\n if (actionPreference)\n notificationClickHandlerAction = actionPreference;\n const launchUrl = await ServiceWorker.getNotificationUrlToOpen(notificationData);\n const notificationOpensLink = ServiceWorker.shouldOpenNotificationUrl(launchUrl);\n const appId = await ServiceWorker.getAppId();\n const deviceType = DeviceRecord.prototype.getDeliveryPlatform();\n let saveNotificationClickedPromise;\n const notificationClicked = {\n notificationId: notificationData.id,\n appId,\n url: launchUrl,\n timestamp: new Date().getTime(),\n };\n Log.info(\"NotificationClicked\", notificationClicked);\n saveNotificationClickedPromise = (async (notificationClicked) => {\n try {\n const existingSession = await Database.getCurrentSession();\n if (existingSession && existingSession.status === SessionStatus.Active) {\n return;\n }\n await Database.put(\"NotificationClicked\", notificationClicked);\n // upgrade existing session to be directly attributed to the notif\n // if it results in re-focusing the site\n if (existingSession) {\n existingSession.notificationId = notificationClicked.notificationId;\n await Database.upsertSession(existingSession);\n }\n }\n catch (e) {\n Log.error(\"Failed to save clicked notification.\", e);\n }\n })(notificationClicked);\n // Start making REST API requests BEFORE self.clients.openWindow is called.\n // It will cause the service worker to stop on Chrome for Android when site is added to the home screen.\n const { deviceId } = await Database.getSubscription();\n const convertedAPIRequests = ServiceWorker.sendConvertedAPIRequests(appId, deviceId, notificationData, deviceType);\n /*\n Check if we can focus on an existing tab instead of opening a new url.\n If an existing tab with exactly the same URL already exists, then this existing tab is focused instead of\n an identical new tab being created. With a special setting, any existing tab matching the origin will\n be focused instead of an identical new tab being created.\n */\n const activeClients = await ServiceWorker.getActiveClients();\n let doNotOpenLink = false;\n for (const client of activeClients) {\n let clientUrl = client.url;\n if (client.isSubdomainIframe) {\n const lastKnownHostUrl = await Database.get('Options', 'lastKnownHostUrl');\n // TODO: clientUrl is being overwritten by defaultUrl and lastKnownHostUrl.\n // Should only use clientUrl if it is not null.\n // Also need to decide which to use over the other.\n clientUrl = lastKnownHostUrl;\n if (!lastKnownHostUrl) {\n clientUrl = await Database.get('Options', 'defaultUrl');\n }\n }\n let clientOrigin = '';\n try {\n clientOrigin = new URL(clientUrl).origin;\n }\n catch (e) {\n Log.error(`Failed to get the HTTP site's actual origin:`, e);\n }\n let launchOrigin = null;\n try {\n // Check if the launchUrl is valid; it can be null\n launchOrigin = new URL(launchUrl).origin;\n }\n catch (e) { }\n if ((notificationClickHandlerMatch === 'exact' && clientUrl === launchUrl) ||\n (notificationClickHandlerMatch === 'origin' && clientOrigin === launchOrigin)) {\n if ((client['isSubdomainIframe'] && clientUrl === launchUrl) ||\n (!client['isSubdomainIframe'] && client.url === launchUrl) ||\n (notificationClickHandlerAction === 'focus' && clientOrigin === launchOrigin)) {\n ServiceWorker.workerMessenger.unicast(WorkerMessengerCommand.NotificationClicked, notificationData, client);\n try {\n if (client instanceof WindowClient)\n await client.focus();\n }\n catch (e) {\n Log.error(\"Failed to focus:\", client, e);\n }\n }\n else {\n /*\n We must focus first; once the client navigates away, it may not be on a domain the same domain, and\n the client ID may change, making it unable to focus.\n \n client.navigate() is available on Chrome 49+ and Firefox 50+.\n */\n if (client['isSubdomainIframe']) {\n try {\n Log.debug('Client is subdomain iFrame. Attempting to focus() client.');\n if (client instanceof WindowClient)\n await client.focus();\n }\n catch (e) {\n Log.error(\"Failed to focus:\", client, e);\n }\n if (notificationOpensLink) {\n Log.debug(`Redirecting HTTP site to ${launchUrl}.`);\n await Database.put(\"NotificationOpened\", { url: launchUrl, data: notificationData, timestamp: Date.now() });\n ServiceWorker.workerMessenger.unicast(WorkerMessengerCommand.RedirectPage, launchUrl, client);\n }\n else {\n Log.debug('Not navigating because link is special.');\n }\n }\n else if (client instanceof WindowClient && client.navigate) {\n try {\n Log.debug('Client is standard HTTPS site. Attempting to focus() client.');\n if (client instanceof WindowClient)\n await client.focus();\n }\n catch (e) {\n Log.error(\"Failed to focus:\", client, e);\n }\n try {\n if (notificationOpensLink) {\n Log.debug(`Redirecting HTTPS site to (${launchUrl}).`);\n await Database.put(\"NotificationOpened\", { url: launchUrl, data: notificationData, timestamp: Date.now() });\n await client.navigate(launchUrl);\n }\n else {\n Log.debug('Not navigating because link is special.');\n }\n }\n catch (e) {\n Log.error(\"Failed to navigate:\", client, launchUrl, e);\n }\n }\n else {\n // If client.navigate() isn't available, we have no other option but to open a new tab to the URL.\n await Database.put(\"NotificationOpened\", { url: launchUrl, data: notificationData, timestamp: Date.now() });\n await ServiceWorker.openUrl(launchUrl);\n }\n }\n doNotOpenLink = true;\n break;\n }\n }\n if (notificationOpensLink && !doNotOpenLink) {\n await Database.put(\"NotificationOpened\", { url: launchUrl, data: notificationData, timestamp: Date.now() });\n await ServiceWorker.openUrl(launchUrl);\n }\n if (saveNotificationClickedPromise) {\n await saveNotificationClickedPromise;\n }\n return await convertedAPIRequests;\n }\n /**\n * Makes network calls for the notification open event to;\n * 1. OneSignal.com to increase the notification open count.\n * 2. A website developer defined webhook URL, if set.\n */\n static async sendConvertedAPIRequests(appId, deviceId, notificationData, deviceType) {\n if (!notificationData.id) {\n console.error(\"No notification id, skipping networks calls to report open!\");\n return;\n }\n let onesignalRestPromise;\n if (appId) {\n onesignalRestPromise = OneSignalApiBase.put(`notifications/${notificationData.id}`, {\n app_id: appId,\n player_id: deviceId,\n opened: true,\n device_type: deviceType\n });\n }\n else\n console.error(\"No app Id, skipping OneSignal API call for notification open!\");\n await ServiceWorker.executeWebhooks('notification.clicked', notificationData);\n if (onesignalRestPromise)\n await onesignalRestPromise;\n }\n /**\n * Attempts to open the given url in a new browser tab. Called when a notification is clicked.\n * @param url May not be well-formed.\n */\n static async openUrl(url) {\n Log.debug('Opening notification URL:', url);\n try {\n return await self.clients.openWindow(url);\n }\n catch (e) {\n Log.warn(`Failed to open the URL '${url}':`, e);\n return null;\n }\n }\n /**\n * Fires when the ServiceWorker can control pages.\n * REQUIRED: AMP WebPush (amp-web-push v0.1) requires clients.claim()\n * - It depends on ServiceWorker having full control of the iframe,\n * requirement could be lifted by AMP in the future however.\n * - Without this the AMP symptom is the subscribe button does not update\n * right after accepting the notification permission from the pop-up.\n * @param event\n */\n static onServiceWorkerActivated(event) {\n Log.info(`OneSignal Service Worker activated (version ${Environment.version()})`);\n event.waitUntil(self.clients.claim());\n }\n static async onPushSubscriptionChange(event) {\n Log.debug(`Called %conPushSubscriptionChange(${JSON.stringify(event, null, 4)}):`, Utils.getConsoleStyle('code'), event);\n const appId = await ServiceWorker.getAppId();\n if (!appId) {\n // Without an app ID, we can't make any calls\n return;\n }\n const appConfig = await ConfigHelper.getAppConfig({ appId }, OneSignalApiSW.downloadServerAppConfig);\n if (!appConfig) {\n // Without a valid app config (e.g. deleted app), we can't make any calls\n return;\n }\n const context = new ContextSW(appConfig);\n // Get our current device ID\n let deviceIdExists;\n {\n let { deviceId } = await Database.getSubscription();\n deviceIdExists = !!deviceId;\n if (!deviceIdExists && event.oldSubscription) {\n // We don't have the device ID stored, but we can look it up from our old subscription\n deviceId = await OneSignalApiSW.getUserIdFromSubscriptionIdentifier(appId, PushDeviceRecord.prototype.getDeliveryPlatform(), event.oldSubscription.endpoint);\n // Store the device ID, so it can be looked up when subscribing\n const subscription = await Database.getSubscription();\n subscription.deviceId = deviceId;\n await Database.setSubscription(subscription);\n }\n deviceIdExists = !!deviceId;\n }\n // Get our new push subscription\n let rawPushSubscription;\n // Set it initially by the provided new push subscription\n const providedNewSubscription = event.newSubscription;\n if (providedNewSubscription) {\n rawPushSubscription = RawPushSubscription.setFromW3cSubscription(providedNewSubscription);\n }\n else {\n // Otherwise set our push registration by resubscribing\n try {\n rawPushSubscription = await context.subscriptionManager.subscribe(1 /* SubscribeNew */);\n }\n catch (e) {\n // Let rawPushSubscription be null\n }\n }\n const hasNewSubscription = !!rawPushSubscription;\n if (!deviceIdExists && !hasNewSubscription) {\n await Database.remove('Ids', 'userId');\n await Database.remove('Ids', 'registrationId');\n }\n else {\n /*\n Determine subscription state we should set new record to.\n \n If the permission is revoked, we should set the subscription state to permission revoked.\n */\n let subscriptionState = null;\n const pushPermission = Notification.permission;\n if (pushPermission !== \"granted\") {\n subscriptionState = SubscriptionStateKind.PermissionRevoked;\n }\n else if (!rawPushSubscription) {\n /*\n If it's not a permission revoked issue, the subscription expired or was revoked by the\n push server.\n */\n subscriptionState = SubscriptionStateKind.PushSubscriptionRevoked;\n }\n // rawPushSubscription may be null if no push subscription was retrieved\n await context.subscriptionManager.registerSubscription(rawPushSubscription, subscriptionState);\n }\n }\n /**\n * Returns a promise that is fulfilled with either the default title from the database (first priority) or the page title from the database (alternate result).\n */\n static _getTitle() {\n return new Promise(resolve => {\n Promise.all([Database.get('Options', 'defaultTitle'), Database.get('Options', 'pageTitle')])\n .then(([defaultTitle, pageTitle]) => {\n if (defaultTitle !== null) {\n resolve(defaultTitle);\n }\n else if (pageTitle != null) {\n resolve(pageTitle);\n }\n else {\n resolve('');\n }\n });\n });\n }\n /**\n * Returns an array of raw notification objects, read from the event.data.payload property\n * @param event\n * @returns An array of notifications. The new web push protocol will only ever contain one notification, however\n * an array is returned for backwards compatibility with the rest of the service worker plumbing.\n */\n static parseOrFetchNotifications(event) {\n if (!event || !event.data) {\n return Promise.reject(\"Missing event.data on push payload!\");\n }\n const isValidPayload = ServiceWorker.isValidPushPayload(event.data);\n if (isValidPayload) {\n Log.debug(\"Received a valid encrypted push payload.\");\n return Promise.resolve([event.data.json()]);\n }\n /*\n We received a push message payload from another service provider or a malformed\n payload. The last received notification will be displayed.\n */\n return Promise.reject(`Unexpected push message payload received: ${event.data}`);\n }\n /**\n * Returns true if the raw data payload is a OneSignal push message in the format of the new web push protocol.\n * Otherwise returns false.\n * @param rawData The raw PushMessageData from the push event's event.data, not already parsed to JSON.\n */\n static isValidPushPayload(rawData) {\n try {\n const payload = rawData.json();\n if (payload &&\n payload.custom &&\n payload.custom.i &&\n OneSignalUtils.isValidUuid(payload.custom.i)) {\n return true;\n }\n else {\n Log.debug('isValidPushPayload: Valid JSON but missing notification UUID:', payload);\n return false;\n }\n }\n catch (e) {\n Log.debug('isValidPushPayload: Parsing to JSON failed with:', e);\n return false;\n }\n }\n}\n// Expose this class to the global scope\nif (typeof self === \"undefined\" &&\n typeof global !== \"undefined\") {\n global.OneSignalWorker = ServiceWorker;\n}\nelse {\n self.OneSignalWorker = ServiceWorker;\n}\n// Run our main file\nif (typeof self !== \"undefined\") {\n ServiceWorker.run();\n}\n//# sourceMappingURL=ServiceWorker.js.map","module.exports = function() {\r\n\tthrow new Error(\"define cannot be used indirect\");\r\n};\r\n","/**\n * New clients will only be including this entry file, which will result in a reduced service worker size.\n */\nimport { ServiceWorker } from '../../src/service-worker/ServiceWorker';\nself.OneSignal = ServiceWorker;\n//# sourceMappingURL=worker.js.map"],"sourceRoot":""}