@amplitude/session-replay-browser 1.29.0 → 1.29.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{_ as e,a as t,b as n,c as i,d as r,o}from"./targeting-min.js";var s,a;!function(e){e.SET="$set",e.SET_ONCE="$setOnce",e.ADD="$add",e.APPEND="$append",e.PREPEND="$prepend",e.REMOVE="$remove",e.PREINSERT="$preInsert",e.POSTINSERT="$postInsert",e.UNSET="$unset",e.CLEAR_ALL="$clearAll"}(s||(s={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(a||(a={}));var l,c="".concat("AMP","_unsent"),d="$default_instance",u="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(l||(l={}));var h,g=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},v=e([],t(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),f=function(n){var i,r=g();if(!(null===(i=null==r?void 0:r.crypto)||void 0===i?void 0:i.getRandomValues))return function(e){return e?(e^16*Math.random()>>e/4).toString(16):(String(1e7)+String(-1e3)+String(-4e3)+String(-8e3)+String(-1e11)).replace(/[018]/g,f)}(n);var o=r.crypto.getRandomValues(new Uint8Array(16));return o[6]=15&o[6]|64,o[8]=63&o[8]|128,e([],t(o.entries()),!1).map(function(e){var n=t(e,2),i=n[0],r=n[1];return[4,6,8,10].includes(i)?"-".concat(v[r]):v[r]}).join("")},p=function(e){return{promise:e||Promise.resolve()}};!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Verbose=3]="Verbose",e[e.Debug=4]="Debug"}(h||(h={}));var m="Amplitude Logger ",y=function(){function e(){this.logLevel=h.None}return e.prototype.disable=function(){this.logLevel=h.None},e.prototype.enable=function(e){void 0===e&&(e=h.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Verbose||console.log("".concat(m,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Warn||console.warn("".concat(m,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Error||console.error("".concat(m,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Debug||console.log("".concat(m,"[Debug]: ").concat(e.join(" ")))},e}(),b=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:d,logLevel:h.Warn,loggerProvider:new y,offline:!1,optOut:!1,serverUrl:u,serverZone:"US",useBatch:!1}},S=function(){function e(e){var t,n,i,r;this._optOut=!1;var o=b();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:o.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||o.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||o.flushQueueSize,this.instanceName=e.instanceName||o.instanceName,this.loggerProvider=e.loggerProvider||o.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:o.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:o.offline,this.optOut=null!==(i=e.optOut)&&void 0!==i?i:o.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||o.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(r=e.useBatch)&&void 0!==r?r:o.useBatch,this.loggerProvider.enable(this.logLevel);var s=w(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=s.serverZone,this.serverUrl=s.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),I=function(e,t){return"EU"===e?t?"https://api.eu.amplitude.com/batch":"https://api.eu.amplitude.com/2/httpapi":t?"https://api2.amplitude.com/batch":u},w=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=b().serverZone),void 0===n&&(n=b().useBatch),e)return{serverUrl:e,serverZone:void 0};var i=["US","EU"].includes(t)?t:b().serverZone;return{serverZone:i,serverUrl:I(i,n)}},C=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:E(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),E=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},P=function(){function e(){this.queue=[]}return e.prototype.logEvent=function(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)},e.prototype.setEventReceiver=function(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(function(t){e(t)}),this.queue=[])},e}(),k=function(){return k=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},k.apply(this,arguments)};function O(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function R(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,r,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(i=o.next()).done;)s.push(i.value)}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return s}"function"==typeof SuppressedError&&SuppressedError;var T=function(e,t){var n,i,r=typeof e;if(r!==typeof t)return!1;try{for(var o=O(["string","number","boolean","undefined"]),s=o.next();!s.done;s=o.next()){if(s.value===r)return e===t}}catch(e){n={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),d=Object.keys(t).sort();if(!T(c,d))return!1;var u=!0;return Object.keys(e).forEach(function(n){T(e[n],t[n])||(u=!1)}),u}for(var h=0;h<e.length;h++)if(!T(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,i=new Array(n);n--;)i[n]=[t[n],e[t[n]]];return i});var _,x=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=k({},this.identity.userProperties),n=k(k({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,i,r,o,s,a,l=n.userProperties||{};try{for(var c=O(Object.entries(e)),d=c.next();!d.done;d=c.next()){var u=R(d.value,2),h=u[0],g=u[1];switch(h){case"$set":try{for(var v=(r=void 0,O(Object.entries(g))),f=v.next();!f.done;f=v.next()){var p=R(f.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){r={error:e}}finally{try{f&&!f.done&&(o=v.return)&&o.call(v)}finally{if(r)throw r.error}}break;case"$unset":try{for(var b=(s=void 0,O(Object.keys(g))),S=b.next();!S.done;S=b.next()){delete l[m=S.value]}}catch(e){s={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(s)throw s.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{d&&!d.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}return n.userProperties=l,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return k({},this.identity)},e.prototype.setIdentity=function(e){var t=k({},this.identity);this.identity=k({},e),T(t,this.identity)||this.listeners.forEach(function(t){t(e)})},e.prototype.addIdentityListener=function(e){this.listeners.add(e)},e.prototype.removeIdentityListener=function(e){this.listeners.delete(e)},e}(),M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,N=function(){function e(){this.identityStore=new x,this.eventBridge=new P,this.applicationContextProvider=new C}return e.getInstance=function(t){return M.analyticsConnectorInstances||(M.analyticsConnectorInstances={}),M.analyticsConnectorInstances[t]||(M.analyticsConnectorInstances[t]=new e),M.analyticsConnectorInstances[t]},e}(),L=function(e,t,n,i,r){return void 0===r&&(r=null),function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<h.Debug||!c||!l)return e.apply(r,o);var d,u={type:"invoke public method",name:t,args:o,stacktrace:(d=1,void 0===d&&(d=0),((new Error).stack||"").split("\n").slice(2+d).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};i&&u.states&&(u.states.before=i());var g=e.apply(r,o);return g&&g.promise?g.promise.then(function(){i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))}):(i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))),g}},D=function(e){var t=0;if(0===e.length)return t;for(var n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},q=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,o,s,a,c,d,u,h,g,v,f,p,m,y,b,S,I,w,C;if("object"!=typeof e)return null;var E=e.code||0,P=this.buildStatus(E);switch(P){case l.Success:return{status:P,statusCode:E,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case l.Invalid:return{status:P,statusCode:E,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(o=e.missing_field)&&void 0!==o?o:"",eventsWithInvalidFields:null!==(s=e.events_with_invalid_fields)&&void 0!==s?s:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(c=e.events_with_invalid_id_lengths)&&void 0!==c?c:{},epsThreshold:null!==(d=e.eps_threshold)&&void 0!==d?d:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(h=e.silenced_devices)&&void 0!==h?h:[],silencedEvents:null!==(g=e.silenced_events)&&void 0!==g?g:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case l.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case l.RateLimit:return{status:P,statusCode:E,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(b=e.throttled_devices)&&void 0!==b?b:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},exceededDailyQuotaDevices:null!==(I=e.exceeded_daily_quota_devices)&&void 0!==I?I:{},exceededDailyQuotaUsers:null!==(w=e.exceeded_daily_quota_users)&&void 0!==w?w:{},throttledEvents:null!==(C=e.throttled_events)&&void 0!==C?C:[]}};case l.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?l.Success:429===e?l.RateLimit:413===e?l.PayloadTooLarge:408===e?l.Timeout:e>=400&&e<500?l.Invalid:e>=500?l.Failed:l.Unknown},e}(),$=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return n(t,e),t.prototype.send=function(e,t){return i(this,void 0,void 0,function(){var n,i,o;return r(this,function(r){switch(r.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:{"Content-Type":"application/json",Accept:"*/*"},body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(i=r.sent()).text()];case 2:o=r.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:i.status})]}return[2]}})})},t}(q),j=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var n=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(JSON.stringify(n))),Promise.resolve({remoteConfig:n.remoteConfig,lastFetch:new Date(n.lastFetch)})}catch(e){return this.logger.debug("Remote config localstorage failed to parse: ",e),localStorage.removeItem(this.key),Promise.resolve(t)}},e.prototype.setConfig=function(e){try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}(),U=function(){function e(e,t,n){void 0===n&&(n="US"),this.callbackInfos=[],this.apiKey=e,this.serverUrl="US"===n?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config",this.logger=t,this.storage=new j(e,t)}return e.prototype.subscribe=function(e,t,n){var i=f(),r={id:i,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(r),"all"===t?this.subscribeAll(r):this.subscribeWaitForRemote(r,t.timeout),i},e.prototype.unsubscribe=function(e){var t=this.callbackInfos.findIndex(function(t){return t.id===e});return-1===t?(this.logger.debug("Remote config client unsubscribe failed because callback with id ".concat(e," doesn't exist.")),!1):(this.callbackInfos.splice(t,1),this.logger.debug("Remote config client unsubscribe succeeded removing callback with id ".concat(e,".")),!0)},e.prototype.updateConfigs=function(){return i(this,void 0,void 0,function(){var e,t=this;return r(this,function(n){switch(n.label){case 0:return[4,this.fetch()];case 1:return e=n.sent(),this.storage.setConfig(e),this.callbackInfos.forEach(function(n){t.sendCallback(n,e,"remote")}),[2]}})})},e.prototype.subscribeAll=function(e){return i(this,void 0,void 0,function(){var t,n,i,o=this;return r(this,function(r){switch(r.label){case 0:return t=this.fetch().then(function(t){o.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),o.sendCallback(e,t,"remote"),o.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(i=r.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(i))),this.sendCallback(e,i,"cache")),[4,t];case 2:return r.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return i(this,void 0,void 0,function(){var n,i;return r(this,function(r){switch(r.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),r.label=1;case 1:return r.trys.push([1,3,,5]),[4,Promise.race([this.fetch(),n])];case 2:return i=r.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,i,"remote"),this.storage.setConfig(i),[3,5];case 3:return r.sent(),this.logger.debug("Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache."),[4,this.storage.fetchConfig()];case 4:return null!==(i=r.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,i,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,i,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var i;e.lastCallback=new Date,i=e.key?e.key.split(".").reduce(function(e,t){return null===e?e:t in e?e[t]:null},t.remoteConfig):t.remoteConfig,e.callback(i,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),i(this,void 0,void 0,function(){var n,i,o,s,a,l,c=this;return r(this,function(d){switch(d.label){case 0:n=t/e,i={remoteConfig:null,lastFetch:new Date},o=function(i){var o,a,l,d,u;return r(this,function(r){switch(r.label){case 0:o=new AbortController,a=setTimeout(function(){return o.abort()},t),r.label=1;case 1:return r.trys.push([1,7,8,9]),[4,fetch(s.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:o.signal})];case 2:return(l=r.sent()).ok?[3,4]:[4,l.text()];case 3:return d=r.sent(),s.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(l.status,": ").concat(d)),[3,6];case 4:return[4,l.json()];case 5:return[2,{value:{remoteConfig:r.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(u=r.sent())instanceof Error&&"AbortError"===u.name?s.logger.debug("Remote config client fetch with retry time ".concat(e," timed out after ").concat(t,"ms")):s.logger.debug("Remote config client fetch with retry time ".concat(e," is rejected because: "),u),[3,9];case 8:return clearTimeout(a),[7];case 9:return i<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,11];case 10:r.sent(),r.label=11;case 11:return[2]}})},s=this,a=0,d.label=1;case 1:return a<e?[5,o(a)]:[3,4];case 2:if("object"==typeof(l=d.sent()))return[2,l.value];d.label=3;case 3:return a++,[3,1];case 4:return[2,i]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var t=encodeURIComponent(this.apiKey),n=new URLSearchParams;return n.append("config_group",e.CONFIG_GROUP),"".concat(this.serverUrl,"/").concat(t,"?").concat(n.toString())},e.CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(_||(_={}));const F="[Amplitude]",A=`${F} Session Replay ID`,B=_.US,K={enabled:!0},W=`${F} Session Replay Debug`,z="amp-mask";var J;!function(e){e.GET_SR_PROPS="get-sr-props",e.DEBUG_INFO="debug-info",e.FETCH_REQUEST="fetch-request",e.METADATA="metadata",e.TARGETING_DECISION="targeting-decision"}(J||(J={}));class G{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}const H="medium";const Q=(e,t,n)=>{switch(t){case"light":{if("input"!==e)return!0;const t=n?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!n.autocomplete.startsWith("cc-"))}case"medium":case"conservative":return!0;default:return Q(e,H,n)}},Z=(e,t)=>(n,i)=>((e,t={defaultMaskLevel:H},n)=>{var i,r,o;if(n){if(n.closest("."+z))return!0;const e=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some(e=>n.closest(e));if(e)return!0;if(n.closest(".amp-unmask"))return!1;const o=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some(e=>n.closest(e));if(o)return!1}return Q(e,null!==(o=t.defaultMaskLevel)&&void 0!==o?o:H,n)})(e,t,i)?n.replace(/[^\s]/g,"*"):n,X=(e,t)=>t||(e===_.STAGING?"https://api-sr.stag2.amplitude.com/sessions/v2/track":e===_.EU?"https://api-sr.eu.amplitude.com/sessions/v2/track":"https://api-sr.amplitude.com/sessions/v2/track"),V=e=>{const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)},Y=(e,t)=>{for(const n of t){const t=V(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},ee=()=>i(void 0,void 0,void 0,function*(){try{const e=g();if(e){const{usage:t,quota:n,usageDetails:i}=yield e.navigator.storage.estimate(),r=t?Math.round(t/1024):0;return{totalStorageSize:r,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(i)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}}),te=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t},ne=()=>({flushMaxRetries:2,logLevel:h.Warn,loggerProvider:new y,transportProvider:new $});class ie extends S{constructor(e,t){var n,i,r,o,s;const a=ne();super(Object.assign(Object.assign({transportProvider:a.transportProvider,loggerProvider:new G(t.loggerProvider||a.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=a.flushMaxRetries?t.flushMaxRetries:a.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||B,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||K,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"idb",this.applyBackgroundColorToBlockedElements=null!==(i=t.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,this.enableUrlChangePolling=null!==(r=t.enableUrlChangePolling)&&void 0!==r&&r,this.urlChangePollingInterval=null!==(o=t.urlChangePollingInterval)&&void 0!==o?o:1e3,this.captureDocumentTitle=null!==(s=t.captureDocumentTitle)&&void 0!==s&&s,t.privacyConfig&&(this.privacyConfig=t.privacyConfig),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every(e=>"string"==typeof e.selector&&"string"==typeof e.replacement))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every(e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t}))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode),t.experimental&&(this.experimental=t.experimental),t.omitElementTags&&(this.omitElementTags=t.omitElementTags)}}var re=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(re||{}),oe=(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(oe||{});class se{constructor(e,t){this.localConfig=t,this.remoteConfigClient=e}generateJoinedConfig(){var e,t,n;return i(this,void 0,void 0,function*(){const i=Object.assign({},this.localConfig);let r;if(i.optOut=this.localConfig.optOut,i.captureEnabled=!0,yield new Promise(e=>{this.remoteConfigClient.subscribe("configs.sessionReplay","all",(t,n)=>{var o;if(this.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${n}:`,JSON.stringify(t,null,2)),t){const e=t,n=e.sr_sampling_config,s=e.sr_privacy_config,a=e.sr_targeting_config,l=null===(o=i.interactionConfig)||void 0===o?void 0:o.ugcFilterRules;i.interactionConfig=e.sr_interaction_config,i.interactionConfig&&l&&(i.interactionConfig.ugcFilterRules=l),i.loggingConfig=e.sr_logging_config,(n||s||a)&&(r={},n&&(r.sr_sampling_config=n),s&&(r.sr_privacy_config=s),a&&(r.sr_targeting_config=a))}e()})}),!r)return{localConfig:this.localConfig,joinedConfig:i,remoteConfig:r};const{sr_sampling_config:o,sr_privacy_config:s,sr_targeting_config:a}=r;if(o&&Object.keys(o).length>0?(Object.prototype.hasOwnProperty.call(o,"capture_enabled")?i.captureEnabled=o.capture_enabled:i.captureEnabled=!1,Object.prototype.hasOwnProperty.call(o,"sample_rate")&&(i.sampleRate=o.sample_rate)):(i.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),s){const r=null!==(e=i.privacyConfig)&&void 0!==e?e:{},o={defaultMaskLevel:null!==(n=null!==(t=s.defaultMaskLevel)&&void 0!==t?t:r.defaultMaskLevel)&&void 0!==n?n:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[]},a=e=>{var t,n,i;const r={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])r[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])r[t]="mask";for(const t of null!==(i=e.unmaskSelector)&&void 0!==i?i:[])r[t]="unmask";return r},l=Object.assign(Object.assign({},a(r)),a(s));for(const[e,t]of Object.entries(l))"mask"===t?o.maskSelector.push(e):"block"===t?o.blockSelector.push(e):"unmask"===t&&o.unmaskSelector.push(e);i.privacyConfig=((e,t)=>{const n=document.createDocumentFragment(),i=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter(e=>{try{n.querySelector(e)}catch(n){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0}),0!==e.length)return e};return e.blockSelector=i(e.blockSelector),e.maskSelector=i(e.maskSelector),e.unmaskSelector=i(e.unmaskSelector),e})(o,this.localConfig.loggerProvider)}return a&&Object.keys(a).length>0&&(i.targetingConfig=a),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:te(i)},null,2)),{localConfig:this.localConfig,joinedConfig:i,remoteConfig:r}})}}var ae=Uint8Array,le=Uint16Array,ce=Uint32Array,de=new ae([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ue=new ae([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),he=new ae([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ge=function(e,t){for(var n=new le(31),i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new ce(n[30]);for(i=1;i<30;++i)for(var o=n[i];o<n[i+1];++o)r[o]=o-n[i]<<5|i;return[n,r]},ve=ge(de,2),fe=ve[0],pe=ve[1];fe[28]=258,pe[258]=28;for(var me=ge(ue,0)[1],ye=new le(32768),be=0;be<32768;++be){var Se=(43690&be)>>>1|(21845&be)<<1;Se=(61680&(Se=(52428&Se)>>>2|(13107&Se)<<2))>>>4|(3855&Se)<<4,ye[be]=((65280&Se)>>>8|(255&Se)<<8)>>>1}var Ie=function(e,t,n){for(var i=e.length,r=0,o=new le(t);r<i;++r)++o[e[r]-1];var s,a=new le(t);for(r=0;r<t;++r)a[r]=a[r-1]+o[r-1]<<1;if(n){s=new le(1<<t);var l=15-t;for(r=0;r<i;++r)if(e[r])for(var c=r<<4|e[r],d=t-e[r],u=a[e[r]-1]++<<d,h=u|(1<<d)-1;u<=h;++u)s[ye[u]>>>l]=c}else for(s=new le(i),r=0;r<i;++r)s[r]=ye[a[e[r]-1]++]>>>15-e[r];return s},we=new ae(288);for(be=0;be<144;++be)we[be]=8;for(be=144;be<256;++be)we[be]=9;for(be=256;be<280;++be)we[be]=7;for(be=280;be<288;++be)we[be]=8;var Ce=new ae(32);for(be=0;be<32;++be)Ce[be]=5;var Ee=Ie(we,9,0),Pe=Ie(Ce,5,0),ke=function(e){return(e/8|0)+(7&e&&1)},Oe=function(e,t,n){(null==n||n>e.length)&&(n=e.length);var i=new(e instanceof le?le:e instanceof ce?ce:ae)(n-t);return i.set(e.subarray(t,n)),i},Re=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8},Te=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8,e[i+2]|=n>>>16},_e=function(e,t){for(var n=[],i=0;i<e.length;++i)e[i]&&n.push({s:i,f:e[i]});var r=n.length,o=n.slice();if(!r)return[new ae(0),0];if(1==r){var s=new ae(n[0].s+1);return s[n[0].s]=1,[s,1]}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,d=1,u=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};d!=r-1;)a=n[n[c].f<n[u].f?c++:u++],l=n[c!=d&&n[c].f<n[u].f?c++:u++],n[d++]={s:-1,f:a.f+l.f,l:a,r:l};var h=o[0].s;for(i=1;i<r;++i)o[i].s>h&&(h=o[i].s);var g=new le(h+1),v=xe(n[d-1],g,0);if(v>t){i=0;var f=0,p=v-t,m=1<<p;for(o.sort(function(e,t){return g[t.s]-g[e.s]||e.f-t.f});i<r;++i){var y=o[i].s;if(!(g[y]>t))break;f+=m-(1<<v-g[y]),g[y]=t}for(f>>>=p;f>0;){var b=o[i].s;g[b]<t?f-=1<<t-g[b]++-1:++i}for(;i>=0&&f;--i){var S=o[i].s;g[S]==t&&(--g[S],++f)}v=t}return[new ae(g),v]},xe=function(e,t,n){return-1==e.s?Math.max(xe(e.l,t,n+1),xe(e.r,t,n+1)):t[e.s]=n},Me=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new le(++t),i=0,r=e[0],o=1,s=function(e){n[i++]=e},a=1;a<=t;++a)if(e[a]==r&&a!=t)++o;else{if(!r&&o>2){for(;o>138;o-=138)s(32754);o>2&&(s(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(s(r),--o;o>6;o-=6)s(8304);o>2&&(s(o-3<<5|8208),o=0)}for(;o--;)s(r);o=1,r=e[a]}return[n.subarray(0,i),t]},Ne=function(e,t){for(var n=0,i=0;i<t.length;++i)n+=e[i]*t[i];return n},Le=function(e,t,n){var i=n.length,r=ke(t+2);e[r]=255&i,e[r+1]=i>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var o=0;o<i;++o)e[r+o+4]=n[o];return 8*(r+4+i)},De=function(e,t,n,i,r,o,s,a,l,c,d){Re(t,d++,n),++r[256];for(var u=_e(r,15),h=u[0],g=u[1],v=_e(o,15),f=v[0],p=v[1],m=Me(h),y=m[0],b=m[1],S=Me(f),I=S[0],w=S[1],C=new le(19),E=0;E<y.length;++E)C[31&y[E]]++;for(E=0;E<I.length;++E)C[31&I[E]]++;for(var P=_e(C,7),k=P[0],O=P[1],R=19;R>4&&!k[he[R-1]];--R);var T,_,x,M,N=c+5<<3,L=Ne(r,we)+Ne(o,Ce)+s,D=Ne(r,h)+Ne(o,f)+s+14+3*R+Ne(C,k)+(2*C[16]+3*C[17]+7*C[18]);if(N<=L&&N<=D)return Le(t,d,e.subarray(l,l+c));if(Re(t,d,1+(D<L)),d+=2,D<L){T=Ie(h,g,0),_=h,x=Ie(f,p,0),M=f;var q=Ie(k,O,0);Re(t,d,b-257),Re(t,d+5,w-1),Re(t,d+10,R-4),d+=14;for(E=0;E<R;++E)Re(t,d+3*E,k[he[E]]);d+=3*R;for(var $=[y,I],j=0;j<2;++j){var U=$[j];for(E=0;E<U.length;++E){var F=31&U[E];Re(t,d,q[F]),d+=k[F],F>15&&(Re(t,d,U[E]>>>5&127),d+=U[E]>>>12)}}}else T=Ee,_=we,x=Pe,M=Ce;for(E=0;E<a;++E)if(i[E]>255){F=i[E]>>>18&31;Te(t,d,T[F+257]),d+=_[F+257],F>7&&(Re(t,d,i[E]>>>23&31),d+=de[F]);var A=31&i[E];Te(t,d,x[A]),d+=M[A],A>3&&(Te(t,d,i[E]>>>5&8191),d+=ue[A])}else Te(t,d,T[i[E]]),d+=_[i[E]];return Te(t,d,T[256]),d+_[256]},qe=new ce([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),$e=function(e,t,n,i,r){return function(e,t,n,i,r,o){var s=e.length,a=new ae(i+s+5*(1+Math.floor(s/7e3))+r),l=a.subarray(i,a.length-r),c=0;if(!t||s<8)for(var d=0;d<=s;d+=65535){var u=d+65535;u<s?c=Le(l,c,e.subarray(d,u)):(l[d]=o,c=Le(l,c,e.subarray(d,s)))}else{for(var h=qe[t-1],g=h>>>13,v=8191&h,f=(1<<n)-1,p=new le(32768),m=new le(f+1),y=Math.ceil(n/3),b=2*y,S=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&f},I=new ce(25e3),w=new le(288),C=new le(32),E=0,P=0,k=(d=0,0),O=0,R=0;d<s;++d){var T=S(d),_=32767&d,x=m[T];if(p[_]=x,m[T]=_,O<=d){var M=s-d;if((E>7e3||k>24576)&&M>423){c=De(e,l,0,I,w,C,P,k,R,d-R,c),k=E=P=0,R=d;for(var N=0;N<286;++N)w[N]=0;for(N=0;N<30;++N)C[N]=0}var L=2,D=0,q=v,$=_-x&32767;if(M>2&&T==S(d-$))for(var j=Math.min(g,M)-1,U=Math.min(32767,d),F=Math.min(258,M);$<=U&&--q&&_!=x;){if(e[d+L]==e[d+L-$]){for(var A=0;A<F&&e[d+A]==e[d+A-$];++A);if(A>L){if(L=A,D=$,A>j)break;var B=Math.min($,A-2),K=0;for(N=0;N<B;++N){var W=d-$+N+32768&32767,z=W-p[W]+32768&32767;z>K&&(K=z,x=W)}}}$+=(_=x)-(x=p[_])+32768&32767}if(D){I[k++]=268435456|pe[L]<<18|me[D];var J=31&pe[L],G=31&me[D];P+=de[J]+ue[G],++w[257+J],++C[G],O=d+L,++E}else I[k++]=e[d],++w[e[d]]}}c=De(e,l,o,I,w,C,P,k,R,d-R,c)}return Oe(a,0,i+ke(c)+r)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,i,!r)};function je(e,t){void 0===t&&(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var i=e,r=t,o=n.length,s=0;s!=o;){for(var a=Math.min(s+5552,o);s<a;++s)r+=i+=n[s];i%=65521,r%=65521}e=i,t=r},d:function(){return(e>>>8<<16|(255&t)<<8|t>>>8)+2*((255&e)<<23)}}}();n.p(e);var i,r,o,s=$e(e,t,2,4);return i=s,r=t.level,o=0==r?0:r<6?1:9==r?3:2,i[0]=120,i[1]=o<<6|(o?32-2*o:1),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(s,s.length-4,n.d()),s}const Ue=e=>{const t={...e,v:"v1"};return function(e,t){var n="";if(!t&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var i=0;i<e.length;){var r=e[i++];r<128||t?n+=String.fromCharCode(r):r<224?n+=String.fromCharCode((31&r)<<6|63&e[i++]):r<240?n+=String.fromCharCode((15&r)<<12|(63&e[i++])<<6|63&e[i++]):(r=((15&r)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r))}return n}(je(function(e,t){var n=e.length;if(!t&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new ae(e.length+(e.length>>>1)),r=0,o=function(e){i[r++]=e},s=0;s<n;++s){if(r+5>i.length){var a=new ae(r+8+(n-s<<1));a.set(i),i=a}var l=e.charCodeAt(s);l<128||t?o(l):l<2048?(o(192|l>>>6),o(128|63&l)):l>55295&&l<57344?(o(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++s))>>>18),o(128|l>>>12&63),o(128|l>>>6&63),o(128|63&l)):(o(224|l>>>12),o(128|l>>>6&63),o(128|63&l))}return Oe(i,0,r)}(JSON.stringify(t))),!0)};class Fe{constructor(e,t,n,i){var r;this.taskQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const t=Ue(e);return JSON.stringify(t)},this.addCompressedEventToManager=(e,t)=>{this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?this.worker.postMessage(JSON.stringify({event:e,sessionId:t})):this.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const o=g();if(this.canUseIdleCallback=o&&"requestIdleCallback"in o,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(r=t.performanceConfig)||void 0===r?void 0:r.timeout)||2e3,i){t.loggerProvider.log("[Experimental] Enabling web worker for compression");const e=new Worker(URL.createObjectURL(new Blob([i],{type:"application/javascript"})));e.onerror=e=>{t.loggerProvider.error(e)},e.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=e}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}))}enqueueEvent(e,t){var n;this.canUseIdleCallback&&(null===(n=this.config.performanceConfig)||void 0===n?void 0:n.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.taskQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(;this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0?requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1}}const Ae="Failed to store session replay events in IndexedDB",Be="1.29.0";class Ke{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n}){this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}addToQueue(...e){e.filter(e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:"Session replay event batch rejected due to exceeded retry count"}),!1)).forEach(e=>{this.queue=this.queue.concat(e),0!==e.timeout?setTimeout(()=>{e.timeout=0,this.schedule(0)},e.timeout):this.schedule(0)})}schedule(e){this.scheduled||(this.scheduled=setTimeout(()=>{this.flush(!0).then(()=>{this.queue.length>0&&this.schedule(e)})},e))}flush(e=!1){return i(this,void 0,void 0,function*(){const t=[],n=[];this.queue.forEach(e=>0===e.timeout?t.push(e):n.push(e)),this.queue=n,this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),yield Promise.all(t.map(t=>this.send(t,e)))})}send(e,t=!0){var n,r;return i(this,void 0,void 0,function*(){const i=e.apiKey;if(!i)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const o=e.deviceId;if(!o)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const s=(()=>{const e=g();return(null==e?void 0:e.location)?e.location.href:""})(),a=Be,l=e.sampleRate,c=new URLSearchParams({device_id:o,session_id:`${e.sessionId}`,type:`${e.type}`}),d=`${(null===(n=e.version)||void 0===n?void 0:n.type)||"standalone"}/${(null===(r=e.version)||void 0===r?void 0:r.version)||a}`,u=this.payloadBatcher({version:1,events:e.events});if(0!==u.events.length)try{const n={headers:{"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${i}`,"X-Client-Version":a,"X-Client-Library":d,"X-Client-Url":s.substring(0,1e3),"X-Client-Sample-Rate":`${l}`},body:JSON.stringify(u),method:"POST"},r=`${X(e.serverZone,this.trackServerUrl)}?${c.toString()}`,o=yield fetch(r,n);if(null===o)return void this.completeRequest({context:e,err:"Unexpected error occurred"});if(t)this.handleReponse(o.status,e);else{let t="";try{t=JSON.stringify(o.body,null,2)}catch(e){}this.completeRequest({context:e,success:`${o.status}: ${t}`})}}catch(t){this.completeRequest({context:e,err:t})}else this.completeRequest({context:e})})}handleReponse(e,t){switch((new q).buildStatus(e)){case l.Success:this.handleSuccessResponse(t);break;case l.Failed:this.handleOtherResponse(t);break;default:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}}handleSuccessResponse(e){const t=Math.round(new Blob(e.events).size/1024);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){this.addToQueue(Object.assign(Object.assign({},e),{timeout:e.attempts*this.retryTimeout}))}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}}class We{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,i;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const n=this.getStringSize(t);return this.getEventsArraySize(e)+n>=this.maxPersistedEventsSize||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(i=e.maxPersistedEventsSize)&&void 0!==i?i:this.maxPersistedEventsSize}getStringSize(e){return e.length}getEventsArraySize(e){let t=0;for(const n of e)t+=this.getStringSize(n);return t+(2+Math.max(0,e.length-1)+2*e.length)}}var ze;!function(e){e.RECORDING="recording",e.SENT="sent"}(ze||(ze={}));const Je="sessionCurrentSequence",Ge="sequencesToSend",He=e=>i(void 0,void 0,void 0,function*(){for(;e.length>0;){const t=10,n=e.splice(0,t);yield Promise.all(n)}}),Qe=e=>{let t,n;return e.objectStoreNames.contains(Je)||(n=e.createObjectStore(Je,{keyPath:"sessionId"})),e.objectStoreNames.contains(Ge)||(t=e.createObjectStore(Ge,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}};class Ze extends We{constructor(e){super(e),this.getSequencesToSend=()=>i(this,void 0,void 0,function*(){try{const e=[];let t=yield this.db.transaction("sequencesToSend").store.openCursor();for(;t;){const{sessionId:n,events:i}=t.value;e.push({events:i,sequenceId:t.key,sessionId:n}),t=yield t.continue()}return e}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.storeCurrentSequence=e=>i(this,void 0,void 0,function*(){try{const t=yield this.db.get(Je,e);if(!t)return;const n=yield this.db.put(Ge,{sessionId:e,events:t.events});return yield this.db.put(Je,{sessionId:e,events:[]}),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:n})}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.addEventToCurrentSequence=(e,t)=>i(this,void 0,void 0,function*(){try{const n=this.db.transaction(Je,"readwrite"),i=yield n.store.get(e);if(!i)return void(yield n.store.put({sessionId:e,events:[t]}));let r;if(this.shouldSplitEventsList(i.events,t))r=i.events,yield n.store.put({sessionId:e,events:[t]});else{const r=i.events.concat(t);yield n.store.put({sessionId:e,events:r})}if(yield n.done,!r)return;const o=yield this.storeSendingEvents(e,r);if(!o)return;return{events:r,sessionId:e,sequenceId:o}}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.storeSendingEvents=(e,t)=>i(this,void 0,void 0,function*(){try{return yield this.db.put(Ge,{sessionId:e,events:t})}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.cleanUpSessionEventsStore=(e,t)=>i(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(Ge,t)}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.transitionFromKeyValStore=e=>i(this,void 0,void 0,function*(){try{const t=yield function(){const e=g();return new Promise((t,n)=>{if(!e)return n(new Error("Global scope not found"));if(!e.indexedDB)return n(new Error("Session Replay: cannot find indexedDB"));try{const i=e.indexedDB.open("keyval-store");i.onupgradeneeded=function(){1===i.result.version&&(i.result.close(),i.transaction&&i.transaction.abort(),e.indexedDB.deleteDatabase("keyval-store"),t())},i.onsuccess=function(){t(i.result)},i.onerror=function(){n(i.error)}}catch(e){n(e)}})}();if(!t)return;const n=(e,t)=>i(this,void 0,void 0,function*(){const n=t.sessionSequences,r=[];Object.keys(n).forEach(o=>{const s=parseInt(o,10),a=n[s];if(s===t.currentSequenceId){const t=a.events.map(t=>i(this,void 0,void 0,function*(){return this.addEventToCurrentSequence(e,t)}));r.push(...t)}else a.status!==ze.SENT&&r.push(this.storeSendingEvents(e,a.events))}),yield He(r)}),r=`${c}_${this.apiKey.substring(0,10)}`;try{const o=t.transaction("keyval").objectStore("keyval").getAll(r),s=new Promise(t=>{o.onsuccess=r=>i(this,void 0,void 0,function*(){const i=r&&r.target.result,o=i&&i[0];if(o){const t=[];Object.keys(o).forEach(i=>{const r=parseInt(i,10),s=o[r];if(e===r)t.push(n(r,s));else{const e=s.sessionSequences;Object.keys(e).forEach(n=>{const i=parseInt(n,10);e[i].status!==ze.SENT&&t.push(this.storeSendingEvents(r,e[i].events))})}}),yield He(t)}t()})});yield s;const a=g();a&&a.indexedDB.deleteDatabase("keyval-store")}catch(e){this.loggerProvider.warn(`Failed to transition session replay events from keyval to new store: ${e}`)}}catch(e){this.loggerProvider.warn(`Failed to access keyval store: ${e}. For more information, visit: https://www.docs.developers.amplitude.com/session-replay/sdks/standalone/#indexeddb-best-practices`)}}),this.apiKey=e.apiKey,this.db=e.db}static new(e,t,n){return i(this,void 0,void 0,function*(){try{const r="replay"===e?"":`_${e}`,s=`${t.apiKey.substring(0,10)}_amp_session_replay_events${r}`,a=yield(e=>i(void 0,void 0,void 0,function*(){return yield o(e,1,{upgrade:Qe})}))(s),l=new Ze(Object.assign(Object.assign({},t),{db:a}));return yield l.transitionFromKeyValStore(n),l}catch(e){t.loggerProvider.warn(`${Ae}: ${e}`)}})}getCurrentSequenceEvents(e){return i(this,void 0,void 0,function*(){if(e){const t=yield this.db.get("sessionCurrentSequence",e);if(!t)return;return[t]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence"))t.push(e);return t})}}class Xe extends We{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}getSequencesToSend(){return i(this,void 0,void 0,function*(){return Object.entries(this.finalizedSequences).map(([e,{sessionId:t,events:n}])=>({sequenceId:Number(e),sessionId:t,events:n}))})}storeCurrentSequence(e){return i(this,void 0,void 0,function*(){if(this.sequences[e])return this.addSequence(e)})}addEventToCurrentSequence(e,t){return i(this,void 0,void 0,function*(){let n;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(n=this.addSequence(e)),this.sequences[e].push(t),n})}storeSendingEvents(e,t){return i(this,void 0,void 0,function*(){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},this.sequenceId++})}cleanUpSessionEventsStore(e,t){return i(this,void 0,void 0,function*(){void 0!==t&&delete this.finalizedSequences[t]})}}const Ve=({config:e,sessionId:t,minInterval:n,maxInterval:r,type:o,payloadBatcher:s,storeType:a})=>i(void 0,void 0,void 0,function*(){const l=new Ke(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:s})),c=()=>new Xe({loggerProvider:e.loggerProvider,maxInterval:r,minInterval:n}),d="idb"===a?yield i(void 0,void 0,void 0,function*(){const i=yield Ze.new(o,{loggerProvider:e.loggerProvider,minInterval:n,maxInterval:r,apiKey:e.apiKey},t);return e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),null!=i?i:c()}):c(),u=({events:t,sessionId:n,deviceId:r,sequenceId:s})=>{e.debugMode&&ee().then(({totalStorageSize:t,percentOfQuota:n,usageDetails:i})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${i}`)}).catch(()=>{}),l.sendEventsList({events:t,sessionId:n,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:r,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:o,onComplete:()=>i(void 0,void 0,void 0,function*(){yield d.cleanUpSessionEventsStore(n,s)})})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{d.storeCurrentSequence(t).then(e=>{e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}).catch(t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)})},addEvent:({event:t,sessionId:n,deviceId:i})=>{d.addEventToCurrentSequence(n,t.data).then(e=>e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})).catch(t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)})},sendStoredEvents:({deviceId:e})=>i(void 0,void 0,void 0,function*(){const t=yield d.getSequencesToSend();t&&t.forEach(t=>{u({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}),flush:function(e=!1){return i(this,void 0,void 0,function*(){return l.flush(e)})}}});class Ye{constructor(...e){const t=new Map;e.forEach(e=>{t.set(e.name,e.manager)}),this.managers=t}sendStoredEvents(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.sendStoredEvents(e))}),yield Promise.all(t)})}addEvent({sessionId:e,event:t,deviceId:n}){var i;null===(i=this.managers.get(t.type))||void 0===i||i.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach(n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})})}flush(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.flush(e))}),yield Promise.all(t)})}}const et={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},tt={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},nt={};function it(e){if(nt[e])return nt[e];const t=function(e){var t,n;const i=null==(n=null==(t=null==globalThis?void 0:globalThis.Zone)?void 0:t.__symbol__)?void 0:n.call(t,e);return i&&globalThis[i]?globalThis[i]:void 0}(e)||globalThis[e],n=t.prototype,i=e in et?et[e]:void 0,r=Boolean(i&&i.every(e=>{var t,i;return Boolean(null==(i=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:i.toString().includes("[native code]"))})),o=e in tt?tt[e]:void 0,s=Boolean(o&&o.every(e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))}));if(r&&s)return nt[e]=t.prototype,t.prototype;try{const i=document.createElement("iframe");document.body.appendChild(i);const r=i.contentWindow;if(!r)return t.prototype;const o=r[e].prototype;return document.body.removeChild(i),o?nt[e]=o:n}catch{return n}}const rt={};function ot(e,t,n){var i;const r=`${e}.${String(n)}`;if(rt[r])return rt[r].call(t);const o=it(e),s=null==(i=Object.getOwnPropertyDescriptor(o,n))?void 0:i.get;return s?(rt[r]=s,s.call(t)):t[n]}const st={};function at(e,t,n){const i=`${e}.${String(n)}`;if(st[i])return st[i].bind(t);const r=it(e)[n];return"function"!=typeof r?t[n]:(st[i]=r,r.bind(t))}const lt={childNodes:function(e){return ot("Node",e,"childNodes")},parentNode:function(e){return ot("Node",e,"parentNode")},parentElement:function(e){return ot("Node",e,"parentElement")},textContent:function(e){return ot("Node",e,"textContent")},contains:function(e,t){return at("Node",e,"contains")(t)},getRootNode:function(e){return at("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?ot("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?ot("Element",e,"shadowRoot"):null},querySelector:function(e,t){return ot("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return ot("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return it("MutationObserver").constructor}};function ct(){const e=g();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight||0}function dt(){const e=g();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth||0}let ut,ht,gt;function vt(e,t){if(gt=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};ut=Object.assign(Object.assign({},n),t),ht=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(ut.root,n);let i=ft(e,"all",()=>ft(e,"two",()=>ft(e,"one",()=>ft(e,"none"))));if(i){const t=xt(Mt(i,e));return t.length>0&&(i=t[0]),mt(i)}throw new Error("Selector was not found.")}function ft(e,t,n){let i=null,r=[],o=e,s=0;for(;o;){const e=(new Date).getTime()-gt.getTime();if(void 0!==ut.timeoutMs&&e>ut.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Rt(St(o))||Rt(...It(o))||Rt(...wt(o))||Rt(Ct(o))||[Et()];const l=Pt(o);if("all"==t)l&&(a=a.concat(a.filter(Ot).map(e=>kt(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(Ot).map(e=>kt(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&Ot(e)&&(a=[kt(e,l)])}else"none"==t&&(a=[Et()],l&&(a=[kt(a[0],l)]));for(let e of a)e.level=s;if(r.push(a),r.length>=ut.seedMinLength&&(i=pt(r,n),i))break;o=o.parentElement,s++}return i||(i=pt(r,n)),!i&&n?n():i}function pt(e,t){const n=xt(_t(e));if(n.length>ut.threshold)return t?t():null;for(let e of n)if(bt(e))return e;return null}function mt(e){let t=e[0],n=t.name;for(let i=1;i<e.length;i++){const r=e[i].level||0;n=t.level===r-1?`${e[i].name} > ${n}`:`${e[i].name} ${n}`,t=e[i]}return n}function yt(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function bt(e){const t=mt(e);switch(ht.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function St(e){const t=e.getAttribute("id");return t&&ut.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function It(e){const t=Array.from(e.attributes).filter(e=>ut.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function wt(e){return Array.from(e.classList).filter(ut.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function Ct(e){const t=e.tagName.toLowerCase();return ut.tagName(t)?{name:t,penalty:2}:null}function Et(){return{name:"*",penalty:3}}function Pt(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==e);)n=n.nextSibling;return i}function kt(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function Ot(e){return"html"!==e.name&&!e.name.startsWith("#")}function Rt(...e){const t=e.filter(Tt);return t.length>0?t:null}function Tt(e){return null!=e}function*_t(e,t=[]){if(e.length>0)for(let n of e[0])yield*_t(e.slice(1,e.length),t.concat(n));else yield t}function xt(e){return[...e].sort((e,t)=>yt(e)-yt(t))}function*Mt(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>ut.optimizedMinLength)for(let i=1;i<e.length-1;i++){if(n.counter>ut.maxNumberOfTries)return;n.counter+=1;const r=[...e];r.splice(i,1);const o=mt(r);if(n.visited.has(o))return;bt(r)&&Nt(r,t)&&(yield r,n.visited.set(o,!0),yield*Mt(r,t,n))}}function Nt(e,t){return ht.querySelector(mt(e))===t}const Lt=({version:e,events:t})=>{const n=[];return t.forEach(e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)}),{version:e,events:n}},Dt=({version:e,events:t})=>{const n=[];t.forEach(e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)});const i=n.reduce((e,t)=>{const{x:n,y:i,selector:r,timestamp:o}=t,s=o-o%36e5,a=`${n}:${i}:${null!=r?r:""}:${s}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:s,count:1}),e},{});return{version:e,events:Object.values(i)}},qt=(e,{eventsManager:t,sessionId:n,deviceIdFn:i,mirror:r,ugcFilterRules:o})=>s=>{if(s.type!==oe.Click)return;const a=g();if(!a)return;const{location:l,innerHeight:c,innerWidth:d}=a;if(!l)return;const{x:u,y:h}=s;if(void 0===u||void 0===h)return;const v=r.getNode(s.id);let f;if(v)try{f=vt(v)}catch(t){e.debug("error resolving selector from finder")}const{left:p,top:m}=function(e){var t,n,i,r;const o=e.document;return{left:o.scrollingElement?o.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:o.documentElement.scrollLeft||(null==o?void 0:o.body)&&(null===(t=lt.parentElement(o.body))||void 0===t?void 0:t.scrollLeft)||(null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.scrollLeft)||0,top:o.scrollingElement?o.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==o?void 0:o.documentElement.scrollTop)||(null==o?void 0:o.body)&&(null===(i=lt.parentElement(o.body))||void 0===i?void 0:i.scrollTop)||(null===(r=null==o?void 0:o.body)||void 0===r?void 0:r.scrollTop)||0}}(a),y={x:u+p,y:h+m,selector:f,viewportHeight:c,viewportWidth:d,pageUrl:Y(l.href,o),timestamp:Date.now(),type:"click"},b=i();b&&t.addEvent({sessionId:n,event:{type:"interaction",data:JSON.stringify(y)},deviceId:b})};class $t{constructor(e,t){const n=g();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=X(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:n,type:i}=this.context,r=new URLSearchParams({device_id:e,session_id:String(n),type:String(i),api_key:this.apiKey}),o=`${this.basePageUrl}?${r.toString()}`;this.sendBeacon(o,t)||this.sendXhr(o,t)}}class jt{static default(e,t){return new jt(new $t(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,i;const r=e(),o=g();o&&r&&this.transport.send(r,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:ct(),viewportWidth:dt(),pageUrl:Y(o.location.href,null!==(i=null===(n=this.config.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)&&void 0!==i?i:[]),timestamp:this.timestamp,type:"scroll"}]})},this._maxScrollX=0,this._maxScrollY=0,this._maxScrollWidth=dt(),this._maxScrollHeight=ct(),this.config=t,this.transport=e}get maxScrollX(){return this._maxScrollX}get maxScrollY(){return this._maxScrollY}get maxScrollWidth(){return this._maxScrollWidth}get maxScrollHeight(){return this._maxScrollHeight}update(e){const t=Date.now();if(e.x>this._maxScrollX){const n=dt();this._maxScrollX=e.x;const i=e.x+n;i>this._maxScrollWidth&&(this._maxScrollWidth=i),this.timestamp=t}if(e.y>this._maxScrollY){const n=ct();this._maxScrollY=e.y;const i=e.y+n;i>this._maxScrollHeight&&(this._maxScrollHeight=i),this.timestamp=t}}}class Ut{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Ft=new class{constructor(){this.dbs={},this.createStore=e=>i(this,void 0,void 0,function*(){return yield o(e,1,{upgrade:e=>{e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})}),this.openOrCreateDB=e=>i(this,void 0,void 0,function*(){if(this.dbs&&this.dbs[e])return this.dbs[e];const t=`${e.substring(0,10)}_amp_session_replay_targeting`,n=yield this.createStore(t);return this.dbs[e]=n,n}),this.getTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:n})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n),r=yield e.get("sessionTargetingMatch",i);return null==r?void 0:r.targetingMatch}catch(t){e.warn(`Failed to get targeting match for session id ${n}: ${t}`)}}),this.storeTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:n,targetingMatch:r})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n);return yield e.put("sessionTargetingMatch",{targetingMatch:r,sessionId:i,lastUpdated:Date.now()})}catch(t){e.warn(`Failed to store targeting match for session id ${n}: ${t}`)}}),this.clearStoreOfOldSessions=({loggerProvider:e,apiKey:t,currentSessionId:n})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n),r=e.transaction("sessionTargetingMatch","readwrite"),o=yield r.store.getAll();for(let e=0;e<o.length;e++){const t=o[e],n=Date.now()-t.lastUpdated;t.sessionId!==i&&n>1728e5&&(yield r.store.delete(t.sessionId))}yield r.done}catch(t){e.warn(`Failed to clear old targeting matches for sessions: ${t}`)}})}};function At(e={}){return{name:"amplitude/url-tracking@1",observer(t,n,i){var r,o,s;const a=Object.assign(Object.assign({},e),i),l=a.ugcFilterRules||[],c=null!==(r=a.enablePolling)&&void 0!==r&&r,d=null!==(o=a.pollingInterval)&&void 0!==o?o:1e3,u=null!==(s=a.captureDocumentTitle)&&void 0!==s&&s;if(!n)return()=>{};let h;const g=()=>n.location&&n.location.href||"",v=()=>{const e=g();if(void 0===h||e!==h){h=e;const i=(()=>{const{innerHeight:e,innerWidth:t,document:i}=n,r=g();let o="";return u&&(o=(null==i?void 0:i.title)||""),{href:l.length>0?Y(r,l):r,title:o,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(i)}},f=e=>function(...t){const n=e.apply(this,t);return v(),n},p=()=>{v()};if(c){const e=n.setInterval(()=>{v()},d);return v(),()=>{e&&n.clearInterval(e)}}if(n.history){const e=n.history.pushState.bind(n.history),t=n.history.replaceState.bind(n.history);return(()=>{n.history.pushState=f(e),n.history.replaceState=f(t)})(),n.addEventListener("popstate",v),n.addEventListener("hashchange",p),v(),()=>{n.history.pushState=e,n.history.replaceState=t,n.removeEventListener("popstate",v),n.removeEventListener("hashchange",p)}}return n.addEventListener("hashchange",p),v(),()=>{n.removeEventListener("hashchange",p)}},options:e}}class Bt{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.teardownEventListeners=e=>{const t=g();t&&(t.removeEventListener("blur",this.blurListener),t.removeEventListener("focus",this.focusListener),!e&&t.addEventListener("blur",this.blurListener),!e&&t.addEventListener("focus",this.focusListener),t.self&&"onpagehide"in t.self?(t.removeEventListener("pagehide",this.pageLeaveListener),!e&&t.addEventListener("pagehide",this.pageLeaveListener)):(t.removeEventListener("beforeunload",this.pageLeaveListener),!e&&t.addEventListener("beforeunload",this.pageLeaveListener)))},this.blurListener=()=>{this.sendEvents()},this.focusListener=()=>{this.recordEvents(!1)},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach(t=>{t(e)})},this.evaluateTargetingAndCapture=(e,t=!1,n=!1)=>i(this,void 0,void 0,function*(){if(this.identifiers&&this.identifiers.sessionId&&this.config){if(!this.config.targetingConfig){if(!t)return void this.loggerProvider.log("No targeting config set, skipping initialization/recording for event.");this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}if(this.lastTargetingParams=e,this.config.targetingConfig&&!this.sessionTargetingMatch){let t=e.event;t&&Object.values(a).includes(t.event_type)&&(t=void 0),this.sessionTargetingMatch=yield(({sessionId:e,targetingConfig:t,loggerProvider:n,apiKey:r,targetingParams:o})=>i(void 0,void 0,void 0,function*(){if(yield Ft.clearStoreOfOldSessions({loggerProvider:n,apiKey:r,currentSessionId:e}),!0===(yield Ft.getTargetingMatchForSession({loggerProvider:n,apiKey:r,sessionId:e})))return!0;let i=!0;try{const{evaluateTargeting:s}=yield import("./targeting-min.js").then(function(e){return e.i}),a=yield s(Object.assign(Object.assign({},o),{flag:t,sessionId:e,apiKey:r,loggerProvider:n}));a&&a.sr_targeting_config&&(i="on"===a.sr_targeting_config.key),Ft.storeTargetingMatchForSession({loggerProvider:n,apiKey:r,sessionId:e,targetingMatch:i})}catch(e){const t=e;n.warn(t.message)}return i}))({sessionId:this.identifiers.sessionId,targetingConfig:this.config.targetingConfig,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:t}}),this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:t,targetingParams:e},null,2))}t?this.initialize(!0):!n&&this.recordCancelCallback||(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),yield this.recordEvents())}else this.identifiers&&!this.identifiers.sessionId?this.loggerProvider.log("Session ID has not been set yet, cannot evaluate targeting for Session Replay."):this.loggerProvider.warn("Session replay init has not been called, cannot evaluate targeting.")}),this.addCustomRRWebEvent=(e,t={},n=!0)=>i(this,void 0,void 0,function*(){try{let i;const r=this.config;if(r&&e!==J.METADATA&&(i={config:te(r),version:Be},n)){const e=yield ee();i=Object.assign(Object.assign({},e),i)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},t),i)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}}),this.stopRecordingEvents=()=>{var e;try{this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(e=this.networkObservers)||void 0===e||e.stop()}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new G(new y)}init(e,t){return p(this._init(e,t))}_init(e,t){var n,r,o,s,a,l,c;return i(this,void 0,void 0,function*(){this.loggerProvider=new G(t.loggerProvider||new y),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.identifiers=new Ut({sessionId:t.sessionId,deviceId:t.deviceId}),this.joinedConfigGenerator=yield((e,t)=>i(void 0,void 0,void 0,function*(){const n=new ie(e,t),i=new U(e,n.loggerProvider,n.serverZone);return new se(i,n)}))(e,t);const{joinedConfig:d,localConfig:u,remoteConfig:h}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=d,this.setMetadata(t.sessionId,d,u,h,null===(n=t.version)||void 0===n?void 0:n.version,Be,null===(r=t.version)||void 0===r?void 0:r.type),t.sessionId&&(null===(o=this.config.interactionConfig)||void 0===o?void 0:o.enabled)){const e=jt.default({sessionId:t.sessionId,type:"interaction"},this.config);this.pageLeaveFns=[e.send(this.getDeviceId.bind(this)).bind(e)],this.scrollHook=e.hook.bind(e)}const v=[];let f,{storeType:p}=this.config;"idb"!==p||(null===(s=g())||void 0===s?void 0:s.indexedDB)||(p="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${p} for event storage.`);try{const e=yield Ve({config:this.config,sessionId:this.identifiers.sessionId,type:"replay",storeType:p});v.push({name:"replay",manager:e})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(a=this.config.interactionConfig)||void 0===a?void 0:a.enabled){const e=this.config.interactionConfig.batch?Dt:Lt;try{const t=yield Ve({config:this.config,sessionId:this.identifiers.sessionId,type:"interaction",minInterval:null!==(l=this.config.interactionConfig.trackEveryNms)&&void 0!==l?l:3e4,maxInterval:6e4,payloadBatcher:e,storeType:p});v.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new Ye(...v),this.eventCompressor&&this.eventCompressor.terminate();const m=g();if((null===(c=this.config.experimental)||void 0===c?void 0:c.useWebWorker)&&m&&m.Worker){const{compressionScript:e}=yield import("./worker-min.js");f=e}this.eventCompressor=new Fe(this.eventsManager,this.config,this.getDeviceId(),f),yield this.initializeNetworkObservers(),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),yield this.evaluateTargetingAndCapture({userProperties:t.userProperties},!0)})}setSessionId(e,t){return p(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,n){var r;return i(this,void 0,void 0,function*(){this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0;const i=this.identifiers&&this.identifiers.sessionId;i&&this.sendEvents(i);const o=t||this.getDeviceId();if(this.identifiers=new Ut({sessionId:e,deviceId:o}),this.joinedConfigGenerator&&i){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig();this.config=e}(null===(r=this.config)||void 0===r?void 0:r.targetingConfig)?yield this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties},!1,!0):yield this.recordEvents()})}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let i={};return n&&(i={[A]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(i[W]=JSON.stringify({appHash:D(e.apiKey).toString()}))),this.addCustomRRWebEvent(J.GET_SR_PROPS,{shouldRecord:n,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i}sendEvents(e){var t;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();this.eventsManager&&n&&i&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:i})}initialize(e=!1){var t;return i(this,void 0,void 0,function*(){if(!(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId))return this.loggerProvider.log("Session is not being recorded due to lack of session id."),Promise.resolve();const n=this.getDeviceId();return n?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())})}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(i=this.config.instanceName,void 0===i&&(i=d),N.getInstance(i)).identityStore.getIdentity().optOut}var i;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;let e=!1,t="",n=!1;if(this.config.targetingConfig)this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,n=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,n=!1);else{(i=this.identifiers.sessionId,r=this.config.sampleRate,o=D(i.toString()),31*Math.abs(o)%1e6/1e6<r)?(e=!0,n=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,n=!1)}var i,r,o;return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(J.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:n,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e,t,n;const i=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==i.length)return i}getMaskTextSelectors(){var e,t,n,i;if("conservative"===(null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.defaultMaskLevel))return"*";const r=null===(i=null===(n=this.config)||void 0===n?void 0:n.privacyConfig)||void 0===i?void 0:i.maskSelector;return r||void 0}getRecordingPlugins(e){var t,n,r,o,s,a;return i(this,void 0,void 0,function*(){const i=[];try{const e=At({ugcFilterRules:(null===(n=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)||[],enablePolling:(null===(r=this.config)||void 0===r?void 0:r.enableUrlChangePolling)||!1,pollingInterval:null===(o=this.config)||void 0===o?void 0:o.urlChangePollingInterval,captureDocumentTitle:null===(s=this.config)||void 0===s?void 0:s.captureDocumentTitle});i.push(e)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(null===(a=null==e?void 0:e.console)||void 0===a?void 0:a.enabled)try{const{getRecordConsolePlugin:t}=yield import("./console-plugin-min.js");i.push(t({level:e.console.levels}))}catch(e){this.loggerProvider.warn("Failed to load console plugin:",e)}return i.length>0?i:void 0})}getRecordFunction(){return i(this,void 0,void 0,function*(){if(this.recordFunction)return this.recordFunction;try{const{record:e}=yield import("./rrweb-record-min.js");return this.recordFunction=e,e}catch(e){return this.loggerProvider.warn("Failed to load rrweb-record module:",e),null}})}recordEvents(e=!0){var t,n,r,o,s;return i(this,void 0,void 0,function*(){const i=this.config,a=this.getShouldRecord(),l=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!a||!l||!i)return;this.stopRecordingEvents();const c=yield this.getRecordFunction();if(!c)return;yield this.initializeNetworkObservers(),null===(n=this.networkObservers)||void 0===n||n.start(e=>{this.addCustomRRWebEvent(J.FETCH_REQUEST,e)});const{privacyConfig:d,interactionConfig:u,loggingConfig:h}=i,g=(null==u?void 0:u.enabled)?{mouseInteraction:this.eventsManager&&qt(this.loggerProvider,{eventsManager:this.eventsManager,sessionId:l,deviceIdFn:this.getDeviceId.bind(this),mirror:c.mirror,ugcFilterRules:null!==(r=u.ugcFilterRules)&&void 0!==r?r:[]}),scroll:this.scrollHook}:{},v=(null==u?void 0:u.enabled)&&u.ugcFilterRules?u.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${l}.`);try{this.recordCancelCallback=c({emit:e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${l} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===re.Meta&&(e.data.href=Y(e.data.href,v)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,l)},inlineStylesheet:i.shouldInlineStylesheet,hooks:g,maskAllInputs:!0,maskTextClass:z,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:i.applyBackgroundColorToBlockedElements,maskInputFn:Z("input",d),maskTextFn:Z("text",d),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,slimDOMOptions:{script:null===(o=i.omitElementTags)||void 0===o?void 0:o.script,comment:null===(s=i.omitElementTags)||void 0===s?void 0:s.comment},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn("Error while capturing replay: ",t.toString()),!0},plugins:yield this.getRecordingPlugins(h)}),this.addCustomRRWebEvent(J.DEBUG_INFO),e&&this.addCustomRRWebEvent(J.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}})}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}flush(e=!1){var t;return i(this,void 0,void 0,function*(){return null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)})}shutdown(){this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()}mapSDKType(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null}setMetadata(e,t,n,i,r,o,s){const a=(null==e?void 0:e.toString())?D(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:i,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(s),replaySDKVersion:r,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:o}}initializeNetworkObservers(){var e,t,n;return i(this,void 0,void 0,function*(){if((null===(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===t?void 0:t.network)||void 0===n?void 0:n.enabled)&&!this.networkObservers)try{const{NetworkObservers:e}=yield import("./observers-min.js");this.networkObservers=new e}catch(e){this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",e)}})}}const Kt=e=>()=>{const{config:t}=e,{loggerProvider:n,logLevel:i}=t||ne();return{logger:n,logLevel:i}};var Wt=(()=>{const e=new Bt;return{init:L(e.init.bind(e),"init",Kt(e)),evaluateTargetingAndCapture:L(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Kt(e)),setSessionId:L(e.setSessionId.bind(e),"setSessionId",Kt(e)),getSessionId:L(e.getSessionId.bind(e),"getSessionId",Kt(e)),getSessionReplayProperties:L(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Kt(e)),flush:L(e.flush.bind(e),"flush",Kt(e)),shutdown:L(e.shutdown.bind(e),"shutdown",Kt(e))}})();const{init:zt,setSessionId:Jt,getSessionId:Gt,getSessionReplayProperties:Ht,flush:Qt,shutdown:Zt,evaluateTargetingAndCapture:Xt}=Wt;export{G as S,Gt as a,Ht as b,Zt as c,Xt as e,Qt as f,g,zt as i,Jt as s};
1
+ import{_ as e,a as t,b as n,c as i,d as r,o}from"./targeting-min.js";var s,a;!function(e){e.SET="$set",e.SET_ONCE="$setOnce",e.ADD="$add",e.APPEND="$append",e.PREPEND="$prepend",e.REMOVE="$remove",e.PREINSERT="$preInsert",e.POSTINSERT="$postInsert",e.UNSET="$unset",e.CLEAR_ALL="$clearAll"}(s||(s={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(a||(a={}));var l,c="".concat("AMP","_unsent"),d="$default_instance",u="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(l||(l={}));var h,g=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},v=e([],t(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),f=function(n){var i,r=g();if(!(null===(i=null==r?void 0:r.crypto)||void 0===i?void 0:i.getRandomValues))return function(e){return e?(e^16*Math.random()>>e/4).toString(16):(String(1e7)+String(-1e3)+String(-4e3)+String(-8e3)+String(-1e11)).replace(/[018]/g,f)}(n);var o=r.crypto.getRandomValues(new Uint8Array(16));return o[6]=15&o[6]|64,o[8]=63&o[8]|128,e([],t(o.entries()),!1).map(function(e){var n=t(e,2),i=n[0],r=n[1];return[4,6,8,10].includes(i)?"-".concat(v[r]):v[r]}).join("")},p=function(e){return{promise:e||Promise.resolve()}};!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Verbose=3]="Verbose",e[e.Debug=4]="Debug"}(h||(h={}));var m="Amplitude Logger ",y=function(){function e(){this.logLevel=h.None}return e.prototype.disable=function(){this.logLevel=h.None},e.prototype.enable=function(e){void 0===e&&(e=h.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Verbose||console.log("".concat(m,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Warn||console.warn("".concat(m,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Error||console.error("".concat(m,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Debug||console.log("".concat(m,"[Debug]: ").concat(e.join(" ")))},e}(),b=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:d,logLevel:h.Warn,loggerProvider:new y,offline:!1,optOut:!1,serverUrl:u,serverZone:"US",useBatch:!1}},S=function(){function e(e){var t,n,i,r;this._optOut=!1;var o=b();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:o.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||o.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||o.flushQueueSize,this.instanceName=e.instanceName||o.instanceName,this.loggerProvider=e.loggerProvider||o.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:o.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:o.offline,this.optOut=null!==(i=e.optOut)&&void 0!==i?i:o.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||o.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(r=e.useBatch)&&void 0!==r?r:o.useBatch,this.loggerProvider.enable(this.logLevel);var s=w(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=s.serverZone,this.serverUrl=s.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),I=function(e,t){return"EU"===e?t?"https://api.eu.amplitude.com/batch":"https://api.eu.amplitude.com/2/httpapi":t?"https://api2.amplitude.com/batch":u},w=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=b().serverZone),void 0===n&&(n=b().useBatch),e)return{serverUrl:e,serverZone:void 0};var i=["US","EU"].includes(t)?t:b().serverZone;return{serverZone:i,serverUrl:I(i,n)}},C=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:E(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),E=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},P=function(){function e(){this.queue=[]}return e.prototype.logEvent=function(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)},e.prototype.setEventReceiver=function(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(function(t){e(t)}),this.queue=[])},e}(),k=function(){return k=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},k.apply(this,arguments)};function O(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function R(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,r,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(i=o.next()).done;)s.push(i.value)}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return s}"function"==typeof SuppressedError&&SuppressedError;var T=function(e,t){var n,i,r=typeof e;if(r!==typeof t)return!1;try{for(var o=O(["string","number","boolean","undefined"]),s=o.next();!s.done;s=o.next()){if(s.value===r)return e===t}}catch(e){n={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),d=Object.keys(t).sort();if(!T(c,d))return!1;var u=!0;return Object.keys(e).forEach(function(n){T(e[n],t[n])||(u=!1)}),u}for(var h=0;h<e.length;h++)if(!T(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,i=new Array(n);n--;)i[n]=[t[n],e[t[n]]];return i});var _,x=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=k({},this.identity.userProperties),n=k(k({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,i,r,o,s,a,l=n.userProperties||{};try{for(var c=O(Object.entries(e)),d=c.next();!d.done;d=c.next()){var u=R(d.value,2),h=u[0],g=u[1];switch(h){case"$set":try{for(var v=(r=void 0,O(Object.entries(g))),f=v.next();!f.done;f=v.next()){var p=R(f.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){r={error:e}}finally{try{f&&!f.done&&(o=v.return)&&o.call(v)}finally{if(r)throw r.error}}break;case"$unset":try{for(var b=(s=void 0,O(Object.keys(g))),S=b.next();!S.done;S=b.next()){delete l[m=S.value]}}catch(e){s={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(s)throw s.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{d&&!d.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}return n.userProperties=l,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return k({},this.identity)},e.prototype.setIdentity=function(e){var t=k({},this.identity);this.identity=k({},e),T(t,this.identity)||this.listeners.forEach(function(t){t(e)})},e.prototype.addIdentityListener=function(e){this.listeners.add(e)},e.prototype.removeIdentityListener=function(e){this.listeners.delete(e)},e}(),M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,N=function(){function e(){this.identityStore=new x,this.eventBridge=new P,this.applicationContextProvider=new C}return e.getInstance=function(t){return M.analyticsConnectorInstances||(M.analyticsConnectorInstances={}),M.analyticsConnectorInstances[t]||(M.analyticsConnectorInstances[t]=new e),M.analyticsConnectorInstances[t]},e}(),L=function(e,t,n,i,r){return void 0===r&&(r=null),function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<h.Debug||!c||!l)return e.apply(r,o);var d,u={type:"invoke public method",name:t,args:o,stacktrace:(d=1,void 0===d&&(d=0),((new Error).stack||"").split("\n").slice(2+d).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};i&&u.states&&(u.states.before=i());var g=e.apply(r,o);return g&&g.promise?g.promise.then(function(){i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))}):(i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))),g}},D=function(e){var t=0;if(0===e.length)return t;for(var n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},q=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,o,s,a,c,d,u,h,g,v,f,p,m,y,b,S,I,w,C;if("object"!=typeof e)return null;var E=e.code||0,P=this.buildStatus(E);switch(P){case l.Success:return{status:P,statusCode:E,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case l.Invalid:return{status:P,statusCode:E,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(o=e.missing_field)&&void 0!==o?o:"",eventsWithInvalidFields:null!==(s=e.events_with_invalid_fields)&&void 0!==s?s:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(c=e.events_with_invalid_id_lengths)&&void 0!==c?c:{},epsThreshold:null!==(d=e.eps_threshold)&&void 0!==d?d:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(h=e.silenced_devices)&&void 0!==h?h:[],silencedEvents:null!==(g=e.silenced_events)&&void 0!==g?g:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case l.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case l.RateLimit:return{status:P,statusCode:E,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(b=e.throttled_devices)&&void 0!==b?b:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},exceededDailyQuotaDevices:null!==(I=e.exceeded_daily_quota_devices)&&void 0!==I?I:{},exceededDailyQuotaUsers:null!==(w=e.exceeded_daily_quota_users)&&void 0!==w?w:{},throttledEvents:null!==(C=e.throttled_events)&&void 0!==C?C:[]}};case l.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?l.Success:429===e?l.RateLimit:413===e?l.PayloadTooLarge:408===e?l.Timeout:e>=400&&e<500?l.Invalid:e>=500?l.Failed:l.Unknown},e}(),$=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return n(t,e),t.prototype.send=function(e,t){return i(this,void 0,void 0,function(){var n,i,o;return r(this,function(r){switch(r.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:{"Content-Type":"application/json",Accept:"*/*"},body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(i=r.sent()).text()];case 2:o=r.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:i.status})]}return[2]}})})},t}(q),j=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var n=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(JSON.stringify(n))),Promise.resolve({remoteConfig:n.remoteConfig,lastFetch:new Date(n.lastFetch)})}catch(e){return this.logger.debug("Remote config localstorage failed to parse: ",e),localStorage.removeItem(this.key),Promise.resolve(t)}},e.prototype.setConfig=function(e){try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}(),U=function(){function e(e,t,n,i){void 0===n&&(n="US"),this.callbackInfos=[],this.apiKey=e,this.serverUrl=i||("US"===n?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=t,this.storage=new j(e,t)}return e.prototype.subscribe=function(e,t,n){var i=f(),r={id:i,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(r),"all"===t?this.subscribeAll(r):this.subscribeWaitForRemote(r,t.timeout),i},e.prototype.unsubscribe=function(e){var t=this.callbackInfos.findIndex(function(t){return t.id===e});return-1===t?(this.logger.debug("Remote config client unsubscribe failed because callback with id ".concat(e," doesn't exist.")),!1):(this.callbackInfos.splice(t,1),this.logger.debug("Remote config client unsubscribe succeeded removing callback with id ".concat(e,".")),!0)},e.prototype.updateConfigs=function(){return i(this,void 0,void 0,function(){var e,t=this;return r(this,function(n){switch(n.label){case 0:return[4,this.fetch()];case 1:return e=n.sent(),this.storage.setConfig(e),this.callbackInfos.forEach(function(n){t.sendCallback(n,e,"remote")}),[2]}})})},e.prototype.subscribeAll=function(e){return i(this,void 0,void 0,function(){var t,n,i,o=this;return r(this,function(r){switch(r.label){case 0:return t=this.fetch().then(function(t){o.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),o.sendCallback(e,t,"remote"),o.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(i=r.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(i))),this.sendCallback(e,i,"cache")),[4,t];case 2:return r.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return i(this,void 0,void 0,function(){var n,i;return r(this,function(r){switch(r.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),r.label=1;case 1:return r.trys.push([1,3,,5]),[4,Promise.race([this.fetch(),n])];case 2:return i=r.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,i,"remote"),this.storage.setConfig(i),[3,5];case 3:return r.sent(),this.logger.debug("Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache."),[4,this.storage.fetchConfig()];case 4:return null!==(i=r.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,i,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,i,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var i;e.lastCallback=new Date,i=e.key?e.key.split(".").reduce(function(e,t){return null===e?e:t in e?e[t]:null},t.remoteConfig):t.remoteConfig,e.callback(i,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),i(this,void 0,void 0,function(){var n,i,o,s,a,l,c=this;return r(this,function(d){switch(d.label){case 0:n=t/e,i={remoteConfig:null,lastFetch:new Date},o=function(i){var o,a,l,d,u;return r(this,function(r){switch(r.label){case 0:o=new AbortController,a=setTimeout(function(){return o.abort()},t),r.label=1;case 1:return r.trys.push([1,7,8,9]),[4,fetch(s.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:o.signal})];case 2:return(l=r.sent()).ok?[3,4]:[4,l.text()];case 3:return d=r.sent(),s.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(l.status,": ").concat(d)),[3,6];case 4:return[4,l.json()];case 5:return[2,{value:{remoteConfig:r.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(u=r.sent())instanceof Error&&"AbortError"===u.name?s.logger.debug("Remote config client fetch with retry time ".concat(e," timed out after ").concat(t,"ms")):s.logger.debug("Remote config client fetch with retry time ".concat(e," is rejected because: "),u),[3,9];case 8:return clearTimeout(a),[7];case 9:return i<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,11];case 10:r.sent(),r.label=11;case 11:return[2]}})},s=this,a=0,d.label=1;case 1:return a<e?[5,o(a)]:[3,4];case 2:if("object"==typeof(l=d.sent()))return[2,l.value];d.label=3;case 3:return a++,[3,1];case 4:return[2,i]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var t=encodeURIComponent(this.apiKey),n=new URLSearchParams;return n.append("config_group",e.CONFIG_GROUP),"".concat(this.serverUrl,"/").concat(t,"?").concat(n.toString())},e.CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(_||(_={}));const F="[Amplitude]",A=`${F} Session Replay ID`,B=_.US,K={enabled:!0},W=`${F} Session Replay Debug`,z="amp-mask";var J;!function(e){e.GET_SR_PROPS="get-sr-props",e.DEBUG_INFO="debug-info",e.FETCH_REQUEST="fetch-request",e.METADATA="metadata",e.TARGETING_DECISION="targeting-decision"}(J||(J={}));class G{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}const H="medium";const Q=(e,t,n)=>{switch(t){case"light":{if("input"!==e)return!0;const t=n?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!n.autocomplete.startsWith("cc-"))}case"medium":case"conservative":return!0;default:return Q(e,H,n)}},Z=(e,t)=>(n,i)=>((e,t={defaultMaskLevel:H},n)=>{var i,r,o;if(n){if(n.closest("."+z))return!0;const e=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some(e=>n.closest(e));if(e)return!0;if(n.closest(".amp-unmask"))return!1;const o=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some(e=>n.closest(e));if(o)return!1}return Q(e,null!==(o=t.defaultMaskLevel)&&void 0!==o?o:H,n)})(e,t,i)?n.replace(/[^\s]/g,"*"):n,X=(e,t)=>t||(e===_.STAGING?"https://api-sr.stag2.amplitude.com/sessions/v2/track":e===_.EU?"https://api-sr.eu.amplitude.com/sessions/v2/track":"https://api-sr.amplitude.com/sessions/v2/track"),V=e=>{const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)},Y=(e,t)=>{for(const n of t){const t=V(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},ee=()=>i(void 0,void 0,void 0,function*(){try{const e=g();if(e){const{usage:t,quota:n,usageDetails:i}=yield e.navigator.storage.estimate(),r=t?Math.round(t/1024):0;return{totalStorageSize:r,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(i)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}}),te=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t},ne=()=>({flushMaxRetries:2,logLevel:h.Warn,loggerProvider:new y,transportProvider:new $});class ie extends S{constructor(e,t){var n,i,r,o,s;const a=ne();super(Object.assign(Object.assign({transportProvider:a.transportProvider,loggerProvider:new G(t.loggerProvider||a.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=a.flushMaxRetries?t.flushMaxRetries:a.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||B,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||K,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"idb",this.applyBackgroundColorToBlockedElements=null!==(i=t.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,this.enableUrlChangePolling=null!==(r=t.enableUrlChangePolling)&&void 0!==r&&r,this.urlChangePollingInterval=null!==(o=t.urlChangePollingInterval)&&void 0!==o?o:1e3,this.captureDocumentTitle=null!==(s=t.captureDocumentTitle)&&void 0!==s&&s,t.privacyConfig&&(this.privacyConfig=t.privacyConfig),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every(e=>"string"==typeof e.selector&&"string"==typeof e.replacement))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every(e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t}))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode),t.experimental&&(this.experimental=t.experimental),t.omitElementTags&&(this.omitElementTags=t.omitElementTags)}}var re=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(re||{}),oe=(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(oe||{});class se{constructor(e,t){this.localConfig=t,this.remoteConfigClient=e}generateJoinedConfig(){var e,t,n;return i(this,void 0,void 0,function*(){const i=Object.assign({},this.localConfig);let r;if(i.optOut=this.localConfig.optOut,i.captureEnabled=!0,yield new Promise(e=>{this.remoteConfigClient.subscribe("configs.sessionReplay","all",(t,n)=>{var o;if(this.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${n}:`,JSON.stringify(t,null,2)),t){const e=t,n=e.sr_sampling_config,s=e.sr_privacy_config,a=e.sr_targeting_config,l=null===(o=i.interactionConfig)||void 0===o?void 0:o.ugcFilterRules;i.interactionConfig=e.sr_interaction_config,i.interactionConfig&&l&&(i.interactionConfig.ugcFilterRules=l),i.loggingConfig=e.sr_logging_config,(n||s||a)&&(r={},n&&(r.sr_sampling_config=n),s&&(r.sr_privacy_config=s),a&&(r.sr_targeting_config=a))}e()})}),!r)return{localConfig:this.localConfig,joinedConfig:i,remoteConfig:r};const{sr_sampling_config:o,sr_privacy_config:s,sr_targeting_config:a}=r;if(o&&Object.keys(o).length>0?(Object.prototype.hasOwnProperty.call(o,"capture_enabled")?i.captureEnabled=o.capture_enabled:i.captureEnabled=!1,Object.prototype.hasOwnProperty.call(o,"sample_rate")&&(i.sampleRate=o.sample_rate)):(i.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),s){const r=null!==(e=i.privacyConfig)&&void 0!==e?e:{},o={defaultMaskLevel:null!==(n=null!==(t=s.defaultMaskLevel)&&void 0!==t?t:r.defaultMaskLevel)&&void 0!==n?n:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[]},a=e=>{var t,n,i;const r={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])r[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])r[t]="mask";for(const t of null!==(i=e.unmaskSelector)&&void 0!==i?i:[])r[t]="unmask";return r},l=Object.assign(Object.assign({},a(r)),a(s));for(const[e,t]of Object.entries(l))"mask"===t?o.maskSelector.push(e):"block"===t?o.blockSelector.push(e):"unmask"===t&&o.unmaskSelector.push(e);i.privacyConfig=((e,t)=>{const n=document.createDocumentFragment(),i=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter(e=>{try{n.querySelector(e)}catch(n){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0}),0!==e.length)return e};return e.blockSelector=i(e.blockSelector),e.maskSelector=i(e.maskSelector),e.unmaskSelector=i(e.unmaskSelector),e})(o,this.localConfig.loggerProvider)}return a&&Object.keys(a).length>0&&(i.targetingConfig=a),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:te(i)},null,2)),{localConfig:this.localConfig,joinedConfig:i,remoteConfig:r}})}}var ae=Uint8Array,le=Uint16Array,ce=Uint32Array,de=new ae([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ue=new ae([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),he=new ae([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ge=function(e,t){for(var n=new le(31),i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new ce(n[30]);for(i=1;i<30;++i)for(var o=n[i];o<n[i+1];++o)r[o]=o-n[i]<<5|i;return[n,r]},ve=ge(de,2),fe=ve[0],pe=ve[1];fe[28]=258,pe[258]=28;for(var me=ge(ue,0)[1],ye=new le(32768),be=0;be<32768;++be){var Se=(43690&be)>>>1|(21845&be)<<1;Se=(61680&(Se=(52428&Se)>>>2|(13107&Se)<<2))>>>4|(3855&Se)<<4,ye[be]=((65280&Se)>>>8|(255&Se)<<8)>>>1}var Ie=function(e,t,n){for(var i=e.length,r=0,o=new le(t);r<i;++r)++o[e[r]-1];var s,a=new le(t);for(r=0;r<t;++r)a[r]=a[r-1]+o[r-1]<<1;if(n){s=new le(1<<t);var l=15-t;for(r=0;r<i;++r)if(e[r])for(var c=r<<4|e[r],d=t-e[r],u=a[e[r]-1]++<<d,h=u|(1<<d)-1;u<=h;++u)s[ye[u]>>>l]=c}else for(s=new le(i),r=0;r<i;++r)s[r]=ye[a[e[r]-1]++]>>>15-e[r];return s},we=new ae(288);for(be=0;be<144;++be)we[be]=8;for(be=144;be<256;++be)we[be]=9;for(be=256;be<280;++be)we[be]=7;for(be=280;be<288;++be)we[be]=8;var Ce=new ae(32);for(be=0;be<32;++be)Ce[be]=5;var Ee=Ie(we,9,0),Pe=Ie(Ce,5,0),ke=function(e){return(e/8|0)+(7&e&&1)},Oe=function(e,t,n){(null==n||n>e.length)&&(n=e.length);var i=new(e instanceof le?le:e instanceof ce?ce:ae)(n-t);return i.set(e.subarray(t,n)),i},Re=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8},Te=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8,e[i+2]|=n>>>16},_e=function(e,t){for(var n=[],i=0;i<e.length;++i)e[i]&&n.push({s:i,f:e[i]});var r=n.length,o=n.slice();if(!r)return[new ae(0),0];if(1==r){var s=new ae(n[0].s+1);return s[n[0].s]=1,[s,1]}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,d=1,u=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};d!=r-1;)a=n[n[c].f<n[u].f?c++:u++],l=n[c!=d&&n[c].f<n[u].f?c++:u++],n[d++]={s:-1,f:a.f+l.f,l:a,r:l};var h=o[0].s;for(i=1;i<r;++i)o[i].s>h&&(h=o[i].s);var g=new le(h+1),v=xe(n[d-1],g,0);if(v>t){i=0;var f=0,p=v-t,m=1<<p;for(o.sort(function(e,t){return g[t.s]-g[e.s]||e.f-t.f});i<r;++i){var y=o[i].s;if(!(g[y]>t))break;f+=m-(1<<v-g[y]),g[y]=t}for(f>>>=p;f>0;){var b=o[i].s;g[b]<t?f-=1<<t-g[b]++-1:++i}for(;i>=0&&f;--i){var S=o[i].s;g[S]==t&&(--g[S],++f)}v=t}return[new ae(g),v]},xe=function(e,t,n){return-1==e.s?Math.max(xe(e.l,t,n+1),xe(e.r,t,n+1)):t[e.s]=n},Me=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new le(++t),i=0,r=e[0],o=1,s=function(e){n[i++]=e},a=1;a<=t;++a)if(e[a]==r&&a!=t)++o;else{if(!r&&o>2){for(;o>138;o-=138)s(32754);o>2&&(s(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(s(r),--o;o>6;o-=6)s(8304);o>2&&(s(o-3<<5|8208),o=0)}for(;o--;)s(r);o=1,r=e[a]}return[n.subarray(0,i),t]},Ne=function(e,t){for(var n=0,i=0;i<t.length;++i)n+=e[i]*t[i];return n},Le=function(e,t,n){var i=n.length,r=ke(t+2);e[r]=255&i,e[r+1]=i>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var o=0;o<i;++o)e[r+o+4]=n[o];return 8*(r+4+i)},De=function(e,t,n,i,r,o,s,a,l,c,d){Re(t,d++,n),++r[256];for(var u=_e(r,15),h=u[0],g=u[1],v=_e(o,15),f=v[0],p=v[1],m=Me(h),y=m[0],b=m[1],S=Me(f),I=S[0],w=S[1],C=new le(19),E=0;E<y.length;++E)C[31&y[E]]++;for(E=0;E<I.length;++E)C[31&I[E]]++;for(var P=_e(C,7),k=P[0],O=P[1],R=19;R>4&&!k[he[R-1]];--R);var T,_,x,M,N=c+5<<3,L=Ne(r,we)+Ne(o,Ce)+s,D=Ne(r,h)+Ne(o,f)+s+14+3*R+Ne(C,k)+(2*C[16]+3*C[17]+7*C[18]);if(N<=L&&N<=D)return Le(t,d,e.subarray(l,l+c));if(Re(t,d,1+(D<L)),d+=2,D<L){T=Ie(h,g,0),_=h,x=Ie(f,p,0),M=f;var q=Ie(k,O,0);Re(t,d,b-257),Re(t,d+5,w-1),Re(t,d+10,R-4),d+=14;for(E=0;E<R;++E)Re(t,d+3*E,k[he[E]]);d+=3*R;for(var $=[y,I],j=0;j<2;++j){var U=$[j];for(E=0;E<U.length;++E){var F=31&U[E];Re(t,d,q[F]),d+=k[F],F>15&&(Re(t,d,U[E]>>>5&127),d+=U[E]>>>12)}}}else T=Ee,_=we,x=Pe,M=Ce;for(E=0;E<a;++E)if(i[E]>255){F=i[E]>>>18&31;Te(t,d,T[F+257]),d+=_[F+257],F>7&&(Re(t,d,i[E]>>>23&31),d+=de[F]);var A=31&i[E];Te(t,d,x[A]),d+=M[A],A>3&&(Te(t,d,i[E]>>>5&8191),d+=ue[A])}else Te(t,d,T[i[E]]),d+=_[i[E]];return Te(t,d,T[256]),d+_[256]},qe=new ce([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),$e=function(e,t,n,i,r){return function(e,t,n,i,r,o){var s=e.length,a=new ae(i+s+5*(1+Math.floor(s/7e3))+r),l=a.subarray(i,a.length-r),c=0;if(!t||s<8)for(var d=0;d<=s;d+=65535){var u=d+65535;u<s?c=Le(l,c,e.subarray(d,u)):(l[d]=o,c=Le(l,c,e.subarray(d,s)))}else{for(var h=qe[t-1],g=h>>>13,v=8191&h,f=(1<<n)-1,p=new le(32768),m=new le(f+1),y=Math.ceil(n/3),b=2*y,S=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&f},I=new ce(25e3),w=new le(288),C=new le(32),E=0,P=0,k=(d=0,0),O=0,R=0;d<s;++d){var T=S(d),_=32767&d,x=m[T];if(p[_]=x,m[T]=_,O<=d){var M=s-d;if((E>7e3||k>24576)&&M>423){c=De(e,l,0,I,w,C,P,k,R,d-R,c),k=E=P=0,R=d;for(var N=0;N<286;++N)w[N]=0;for(N=0;N<30;++N)C[N]=0}var L=2,D=0,q=v,$=_-x&32767;if(M>2&&T==S(d-$))for(var j=Math.min(g,M)-1,U=Math.min(32767,d),F=Math.min(258,M);$<=U&&--q&&_!=x;){if(e[d+L]==e[d+L-$]){for(var A=0;A<F&&e[d+A]==e[d+A-$];++A);if(A>L){if(L=A,D=$,A>j)break;var B=Math.min($,A-2),K=0;for(N=0;N<B;++N){var W=d-$+N+32768&32767,z=W-p[W]+32768&32767;z>K&&(K=z,x=W)}}}$+=(_=x)-(x=p[_])+32768&32767}if(D){I[k++]=268435456|pe[L]<<18|me[D];var J=31&pe[L],G=31&me[D];P+=de[J]+ue[G],++w[257+J],++C[G],O=d+L,++E}else I[k++]=e[d],++w[e[d]]}}c=De(e,l,o,I,w,C,P,k,R,d-R,c)}return Oe(a,0,i+ke(c)+r)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,i,!r)};function je(e,t){void 0===t&&(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var i=e,r=t,o=n.length,s=0;s!=o;){for(var a=Math.min(s+5552,o);s<a;++s)r+=i+=n[s];i%=65521,r%=65521}e=i,t=r},d:function(){return(e>>>8<<16|(255&t)<<8|t>>>8)+2*((255&e)<<23)}}}();n.p(e);var i,r,o,s=$e(e,t,2,4);return i=s,r=t.level,o=0==r?0:r<6?1:9==r?3:2,i[0]=120,i[1]=o<<6|(o?32-2*o:1),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(s,s.length-4,n.d()),s}const Ue=e=>{const t={...e,v:"v1"};return function(e,t){var n="";if(!t&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var i=0;i<e.length;){var r=e[i++];r<128||t?n+=String.fromCharCode(r):r<224?n+=String.fromCharCode((31&r)<<6|63&e[i++]):r<240?n+=String.fromCharCode((15&r)<<12|(63&e[i++])<<6|63&e[i++]):(r=((15&r)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r))}return n}(je(function(e,t){var n=e.length;if(!t&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new ae(e.length+(e.length>>>1)),r=0,o=function(e){i[r++]=e},s=0;s<n;++s){if(r+5>i.length){var a=new ae(r+8+(n-s<<1));a.set(i),i=a}var l=e.charCodeAt(s);l<128||t?o(l):l<2048?(o(192|l>>>6),o(128|63&l)):l>55295&&l<57344?(o(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++s))>>>18),o(128|l>>>12&63),o(128|l>>>6&63),o(128|63&l)):(o(224|l>>>12),o(128|l>>>6&63),o(128|63&l))}return Oe(i,0,r)}(JSON.stringify(t))),!0)};class Fe{constructor(e,t,n,i){var r;this.taskQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const t=Ue(e);return JSON.stringify(t)},this.addCompressedEventToManager=(e,t)=>{this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?this.worker.postMessage(JSON.stringify({event:e,sessionId:t})):this.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const o=g();if(this.canUseIdleCallback=o&&"requestIdleCallback"in o,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(r=t.performanceConfig)||void 0===r?void 0:r.timeout)||2e3,i){t.loggerProvider.log("[Experimental] Enabling web worker for compression");const e=new Worker(URL.createObjectURL(new Blob([i],{type:"application/javascript"})));e.onerror=e=>{t.loggerProvider.error(e)},e.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=e}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}))}enqueueEvent(e,t){var n;this.canUseIdleCallback&&(null===(n=this.config.performanceConfig)||void 0===n?void 0:n.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.taskQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(;this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0?requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1}}const Ae="Failed to store session replay events in IndexedDB",Be="1.29.2";class Ke{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n}){this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}addToQueue(...e){e.filter(e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:"Session replay event batch rejected due to exceeded retry count"}),!1)).forEach(e=>{this.queue=this.queue.concat(e),0!==e.timeout?setTimeout(()=>{e.timeout=0,this.schedule(0)},e.timeout):this.schedule(0)})}schedule(e){this.scheduled||(this.scheduled=setTimeout(()=>{this.flush(!0).then(()=>{this.queue.length>0&&this.schedule(e)})},e))}flush(e=!1){return i(this,void 0,void 0,function*(){const t=[],n=[];this.queue.forEach(e=>0===e.timeout?t.push(e):n.push(e)),this.queue=n,this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),yield Promise.all(t.map(t=>this.send(t,e)))})}send(e,t=!0){var n,r;return i(this,void 0,void 0,function*(){const i=e.apiKey;if(!i)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const o=e.deviceId;if(!o)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const s=(()=>{const e=g();return(null==e?void 0:e.location)?e.location.href:""})(),a=Be,l=e.sampleRate,c=new URLSearchParams({device_id:o,session_id:`${e.sessionId}`,type:`${e.type}`}),d=`${(null===(n=e.version)||void 0===n?void 0:n.type)||"standalone"}/${(null===(r=e.version)||void 0===r?void 0:r.version)||a}`,u=this.payloadBatcher({version:1,events:e.events});if(0!==u.events.length)try{const n={headers:{"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${i}`,"X-Client-Version":a,"X-Client-Library":d,"X-Client-Url":s.substring(0,1e3),"X-Client-Sample-Rate":`${l}`},body:JSON.stringify(u),method:"POST"},r=`${X(e.serverZone,this.trackServerUrl)}?${c.toString()}`,o=yield fetch(r,n);if(null===o)return void this.completeRequest({context:e,err:"Unexpected error occurred"});if(t)this.handleReponse(o.status,e);else{let t="";try{t=JSON.stringify(o.body,null,2)}catch(e){}this.completeRequest({context:e,success:`${o.status}: ${t}`})}}catch(t){this.completeRequest({context:e,err:t})}else this.completeRequest({context:e})})}handleReponse(e,t){switch((new q).buildStatus(e)){case l.Success:this.handleSuccessResponse(t);break;case l.Failed:this.handleOtherResponse(t);break;default:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}}handleSuccessResponse(e){const t=Math.round(new Blob(e.events).size/1024);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){this.addToQueue(Object.assign(Object.assign({},e),{timeout:e.attempts*this.retryTimeout}))}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}}class We{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,i;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const n=this.getStringSize(t);return this.getEventsArraySize(e)+n>=this.maxPersistedEventsSize||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(i=e.maxPersistedEventsSize)&&void 0!==i?i:this.maxPersistedEventsSize}getStringSize(e){return e.length}getEventsArraySize(e){let t=0;for(const n of e)t+=this.getStringSize(n);return t+(2+Math.max(0,e.length-1)+2*e.length)}}var ze;!function(e){e.RECORDING="recording",e.SENT="sent"}(ze||(ze={}));const Je="sessionCurrentSequence",Ge="sequencesToSend",He=e=>i(void 0,void 0,void 0,function*(){for(;e.length>0;){const t=10,n=e.splice(0,t);yield Promise.all(n)}}),Qe=e=>{let t,n;return e.objectStoreNames.contains(Je)||(n=e.createObjectStore(Je,{keyPath:"sessionId"})),e.objectStoreNames.contains(Ge)||(t=e.createObjectStore(Ge,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}};class Ze extends We{constructor(e){super(e),this.getSequencesToSend=()=>i(this,void 0,void 0,function*(){try{const e=[];let t=yield this.db.transaction("sequencesToSend").store.openCursor();for(;t;){const{sessionId:n,events:i}=t.value;e.push({events:i,sequenceId:t.key,sessionId:n}),t=yield t.continue()}return e}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.storeCurrentSequence=e=>i(this,void 0,void 0,function*(){try{const t=yield this.db.get(Je,e);if(!t)return;const n=yield this.db.put(Ge,{sessionId:e,events:t.events});return yield this.db.put(Je,{sessionId:e,events:[]}),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:n})}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.addEventToCurrentSequence=(e,t)=>i(this,void 0,void 0,function*(){try{const n=this.db.transaction(Je,"readwrite"),i=yield n.store.get(e);if(!i)return void(yield n.store.put({sessionId:e,events:[t]}));let r;if(this.shouldSplitEventsList(i.events,t))r=i.events,yield n.store.put({sessionId:e,events:[t]});else{const r=i.events.concat(t);yield n.store.put({sessionId:e,events:r})}if(yield n.done,!r)return;const o=yield this.storeSendingEvents(e,r);if(!o)return;return{events:r,sessionId:e,sequenceId:o}}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.storeSendingEvents=(e,t)=>i(this,void 0,void 0,function*(){try{return yield this.db.put(Ge,{sessionId:e,events:t})}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.cleanUpSessionEventsStore=(e,t)=>i(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(Ge,t)}catch(e){this.loggerProvider.warn(`${Ae}: ${e}`)}}),this.transitionFromKeyValStore=e=>i(this,void 0,void 0,function*(){try{const t=yield function(){const e=g();return new Promise((t,n)=>{if(!e)return n(new Error("Global scope not found"));if(!e.indexedDB)return n(new Error("Session Replay: cannot find indexedDB"));try{const i=e.indexedDB.open("keyval-store");i.onupgradeneeded=function(){1===i.result.version&&(i.result.close(),i.transaction&&i.transaction.abort(),e.indexedDB.deleteDatabase("keyval-store"),t())},i.onsuccess=function(){t(i.result)},i.onerror=function(){n(i.error)}}catch(e){n(e)}})}();if(!t)return;const n=(e,t)=>i(this,void 0,void 0,function*(){const n=t.sessionSequences,r=[];Object.keys(n).forEach(o=>{const s=parseInt(o,10),a=n[s];if(s===t.currentSequenceId){const t=a.events.map(t=>i(this,void 0,void 0,function*(){return this.addEventToCurrentSequence(e,t)}));r.push(...t)}else a.status!==ze.SENT&&r.push(this.storeSendingEvents(e,a.events))}),yield He(r)}),r=`${c}_${this.apiKey.substring(0,10)}`;try{const o=t.transaction("keyval").objectStore("keyval").getAll(r),s=new Promise(t=>{o.onsuccess=r=>i(this,void 0,void 0,function*(){const i=r&&r.target.result,o=i&&i[0];if(o){const t=[];Object.keys(o).forEach(i=>{const r=parseInt(i,10),s=o[r];if(e===r)t.push(n(r,s));else{const e=s.sessionSequences;Object.keys(e).forEach(n=>{const i=parseInt(n,10);e[i].status!==ze.SENT&&t.push(this.storeSendingEvents(r,e[i].events))})}}),yield He(t)}t()})});yield s;const a=g();a&&a.indexedDB.deleteDatabase("keyval-store")}catch(e){this.loggerProvider.warn(`Failed to transition session replay events from keyval to new store: ${e}`)}}catch(e){this.loggerProvider.warn(`Failed to access keyval store: ${e}. For more information, visit: https://www.docs.developers.amplitude.com/session-replay/sdks/standalone/#indexeddb-best-practices`)}}),this.apiKey=e.apiKey,this.db=e.db}static new(e,t,n){return i(this,void 0,void 0,function*(){try{const r="replay"===e?"":`_${e}`,s=`${t.apiKey.substring(0,10)}_amp_session_replay_events${r}`,a=yield(e=>i(void 0,void 0,void 0,function*(){return yield o(e,1,{upgrade:Qe})}))(s),l=new Ze(Object.assign(Object.assign({},t),{db:a}));return yield l.transitionFromKeyValStore(n),l}catch(e){t.loggerProvider.warn(`${Ae}: ${e}`)}})}getCurrentSequenceEvents(e){return i(this,void 0,void 0,function*(){if(e){const t=yield this.db.get("sessionCurrentSequence",e);if(!t)return;return[t]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence"))t.push(e);return t})}}class Xe extends We{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}getSequencesToSend(){return i(this,void 0,void 0,function*(){return Object.entries(this.finalizedSequences).map(([e,{sessionId:t,events:n}])=>({sequenceId:Number(e),sessionId:t,events:n}))})}storeCurrentSequence(e){return i(this,void 0,void 0,function*(){if(this.sequences[e])return this.addSequence(e)})}addEventToCurrentSequence(e,t){return i(this,void 0,void 0,function*(){let n;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(n=this.addSequence(e)),this.sequences[e].push(t),n})}storeSendingEvents(e,t){return i(this,void 0,void 0,function*(){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},this.sequenceId++})}cleanUpSessionEventsStore(e,t){return i(this,void 0,void 0,function*(){void 0!==t&&delete this.finalizedSequences[t]})}}const Ve=({config:e,sessionId:t,minInterval:n,maxInterval:r,type:o,payloadBatcher:s,storeType:a})=>i(void 0,void 0,void 0,function*(){const l=new Ke(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:s})),c=()=>new Xe({loggerProvider:e.loggerProvider,maxInterval:r,minInterval:n}),d="idb"===a?yield i(void 0,void 0,void 0,function*(){const i=yield Ze.new(o,{loggerProvider:e.loggerProvider,minInterval:n,maxInterval:r,apiKey:e.apiKey},t);return e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),null!=i?i:c()}):c(),u=({events:t,sessionId:n,deviceId:r,sequenceId:s})=>{e.debugMode&&ee().then(({totalStorageSize:t,percentOfQuota:n,usageDetails:i})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${i}`)}).catch(()=>{}),l.sendEventsList({events:t,sessionId:n,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:r,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:o,onComplete:()=>i(void 0,void 0,void 0,function*(){yield d.cleanUpSessionEventsStore(n,s)})})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{d.storeCurrentSequence(t).then(e=>{e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}).catch(t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)})},addEvent:({event:t,sessionId:n,deviceId:i})=>{d.addEventToCurrentSequence(n,t.data).then(e=>e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})).catch(t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)})},sendStoredEvents:({deviceId:e})=>i(void 0,void 0,void 0,function*(){const t=yield d.getSequencesToSend();t&&t.forEach(t=>{u({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}),flush:function(e=!1){return i(this,void 0,void 0,function*(){return l.flush(e)})}}});class Ye{constructor(...e){const t=new Map;e.forEach(e=>{t.set(e.name,e.manager)}),this.managers=t}sendStoredEvents(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.sendStoredEvents(e))}),yield Promise.all(t)})}addEvent({sessionId:e,event:t,deviceId:n}){var i;null===(i=this.managers.get(t.type))||void 0===i||i.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach(n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})})}flush(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.flush(e))}),yield Promise.all(t)})}}const et={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},tt={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},nt={};function it(e){if(nt[e])return nt[e];const t=function(e){var t,n;const i=null==(n=null==(t=null==globalThis?void 0:globalThis.Zone)?void 0:t.__symbol__)?void 0:n.call(t,e);return i&&globalThis[i]?globalThis[i]:void 0}(e)||globalThis[e],n=t.prototype,i=e in et?et[e]:void 0,r=Boolean(i&&i.every(e=>{var t,i;return Boolean(null==(i=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:i.toString().includes("[native code]"))})),o=e in tt?tt[e]:void 0,s=Boolean(o&&o.every(e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))}));if(r&&s)return nt[e]=t.prototype,t.prototype;try{const i=document.createElement("iframe");document.body.appendChild(i);const r=i.contentWindow;if(!r)return t.prototype;const o=r[e].prototype;return document.body.removeChild(i),o?nt[e]=o:n}catch{return n}}const rt={};function ot(e,t,n){var i;const r=`${e}.${String(n)}`;if(rt[r])return rt[r].call(t);const o=it(e),s=null==(i=Object.getOwnPropertyDescriptor(o,n))?void 0:i.get;return s?(rt[r]=s,s.call(t)):t[n]}const st={};function at(e,t,n){const i=`${e}.${String(n)}`;if(st[i])return st[i].bind(t);const r=it(e)[n];return"function"!=typeof r?t[n]:(st[i]=r,r.bind(t))}const lt={childNodes:function(e){return ot("Node",e,"childNodes")},parentNode:function(e){return ot("Node",e,"parentNode")},parentElement:function(e){return ot("Node",e,"parentElement")},textContent:function(e){return ot("Node",e,"textContent")},contains:function(e,t){return at("Node",e,"contains")(t)},getRootNode:function(e){return at("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?ot("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?ot("Element",e,"shadowRoot"):null},querySelector:function(e,t){return ot("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return ot("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return it("MutationObserver").constructor}};function ct(){const e=g();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight||0}function dt(){const e=g();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth||0}let ut,ht,gt;function vt(e,t){if(gt=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};ut=Object.assign(Object.assign({},n),t),ht=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(ut.root,n);let i=ft(e,"all",()=>ft(e,"two",()=>ft(e,"one",()=>ft(e,"none"))));if(i){const t=xt(Mt(i,e));return t.length>0&&(i=t[0]),mt(i)}throw new Error("Selector was not found.")}function ft(e,t,n){let i=null,r=[],o=e,s=0;for(;o;){const e=(new Date).getTime()-gt.getTime();if(void 0!==ut.timeoutMs&&e>ut.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Rt(St(o))||Rt(...It(o))||Rt(...wt(o))||Rt(Ct(o))||[Et()];const l=Pt(o);if("all"==t)l&&(a=a.concat(a.filter(Ot).map(e=>kt(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(Ot).map(e=>kt(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&Ot(e)&&(a=[kt(e,l)])}else"none"==t&&(a=[Et()],l&&(a=[kt(a[0],l)]));for(let e of a)e.level=s;if(r.push(a),r.length>=ut.seedMinLength&&(i=pt(r,n),i))break;o=o.parentElement,s++}return i||(i=pt(r,n)),!i&&n?n():i}function pt(e,t){const n=xt(_t(e));if(n.length>ut.threshold)return t?t():null;for(let e of n)if(bt(e))return e;return null}function mt(e){let t=e[0],n=t.name;for(let i=1;i<e.length;i++){const r=e[i].level||0;n=t.level===r-1?`${e[i].name} > ${n}`:`${e[i].name} ${n}`,t=e[i]}return n}function yt(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function bt(e){const t=mt(e);switch(ht.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function St(e){const t=e.getAttribute("id");return t&&ut.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function It(e){const t=Array.from(e.attributes).filter(e=>ut.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function wt(e){return Array.from(e.classList).filter(ut.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function Ct(e){const t=e.tagName.toLowerCase();return ut.tagName(t)?{name:t,penalty:2}:null}function Et(){return{name:"*",penalty:3}}function Pt(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==e);)n=n.nextSibling;return i}function kt(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function Ot(e){return"html"!==e.name&&!e.name.startsWith("#")}function Rt(...e){const t=e.filter(Tt);return t.length>0?t:null}function Tt(e){return null!=e}function*_t(e,t=[]){if(e.length>0)for(let n of e[0])yield*_t(e.slice(1,e.length),t.concat(n));else yield t}function xt(e){return[...e].sort((e,t)=>yt(e)-yt(t))}function*Mt(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>ut.optimizedMinLength)for(let i=1;i<e.length-1;i++){if(n.counter>ut.maxNumberOfTries)return;n.counter+=1;const r=[...e];r.splice(i,1);const o=mt(r);if(n.visited.has(o))return;bt(r)&&Nt(r,t)&&(yield r,n.visited.set(o,!0),yield*Mt(r,t,n))}}function Nt(e,t){return ht.querySelector(mt(e))===t}const Lt=({version:e,events:t})=>{const n=[];return t.forEach(e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)}),{version:e,events:n}},Dt=({version:e,events:t})=>{const n=[];t.forEach(e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)});const i=n.reduce((e,t)=>{const{x:n,y:i,selector:r,timestamp:o}=t,s=o-o%36e5,a=`${n}:${i}:${null!=r?r:""}:${s}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:s,count:1}),e},{});return{version:e,events:Object.values(i)}},qt=(e,{eventsManager:t,sessionId:n,deviceIdFn:i,mirror:r,ugcFilterRules:o})=>s=>{if(s.type!==oe.Click)return;const a=g();if(!a)return;const{location:l,innerHeight:c,innerWidth:d}=a;if(!l)return;const{x:u,y:h}=s;if(void 0===u||void 0===h)return;const v=r.getNode(s.id);let f;if(v)try{f=vt(v)}catch(t){e.debug("error resolving selector from finder")}const{left:p,top:m}=function(e){var t,n,i,r;const o=e.document;return{left:o.scrollingElement?o.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:o.documentElement.scrollLeft||(null==o?void 0:o.body)&&(null===(t=lt.parentElement(o.body))||void 0===t?void 0:t.scrollLeft)||(null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.scrollLeft)||0,top:o.scrollingElement?o.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==o?void 0:o.documentElement.scrollTop)||(null==o?void 0:o.body)&&(null===(i=lt.parentElement(o.body))||void 0===i?void 0:i.scrollTop)||(null===(r=null==o?void 0:o.body)||void 0===r?void 0:r.scrollTop)||0}}(a),y={x:u+p,y:h+m,selector:f,viewportHeight:c,viewportWidth:d,pageUrl:Y(l.href,o),timestamp:Date.now(),type:"click"},b=i();b&&t.addEvent({sessionId:n,event:{type:"interaction",data:JSON.stringify(y)},deviceId:b})};class $t{constructor(e,t){const n=g();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=X(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:n,type:i}=this.context,r=new URLSearchParams({device_id:e,session_id:String(n),type:String(i),api_key:this.apiKey}),o=`${this.basePageUrl}?${r.toString()}`;this.sendBeacon(o,t)||this.sendXhr(o,t)}}class jt{static default(e,t){return new jt(new $t(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,i;const r=e(),o=g();o&&r&&this.transport.send(r,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:ct(),viewportWidth:dt(),pageUrl:Y(o.location.href,null!==(i=null===(n=this.config.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)&&void 0!==i?i:[]),timestamp:this.timestamp,type:"scroll"}]})},this._maxScrollX=0,this._maxScrollY=0,this._maxScrollWidth=dt(),this._maxScrollHeight=ct(),this.config=t,this.transport=e}get maxScrollX(){return this._maxScrollX}get maxScrollY(){return this._maxScrollY}get maxScrollWidth(){return this._maxScrollWidth}get maxScrollHeight(){return this._maxScrollHeight}update(e){const t=Date.now();if(e.x>this._maxScrollX){const n=dt();this._maxScrollX=e.x;const i=e.x+n;i>this._maxScrollWidth&&(this._maxScrollWidth=i),this.timestamp=t}if(e.y>this._maxScrollY){const n=ct();this._maxScrollY=e.y;const i=e.y+n;i>this._maxScrollHeight&&(this._maxScrollHeight=i),this.timestamp=t}}}class Ut{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Ft=new class{constructor(){this.dbs={},this.createStore=e=>i(this,void 0,void 0,function*(){return yield o(e,1,{upgrade:e=>{e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})}),this.openOrCreateDB=e=>i(this,void 0,void 0,function*(){if(this.dbs&&this.dbs[e])return this.dbs[e];const t=`${e.substring(0,10)}_amp_session_replay_targeting`,n=yield this.createStore(t);return this.dbs[e]=n,n}),this.getTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:n})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n),r=yield e.get("sessionTargetingMatch",i);return null==r?void 0:r.targetingMatch}catch(t){e.warn(`Failed to get targeting match for session id ${n}: ${t}`)}}),this.storeTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:n,targetingMatch:r})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n);return yield e.put("sessionTargetingMatch",{targetingMatch:r,sessionId:i,lastUpdated:Date.now()})}catch(t){e.warn(`Failed to store targeting match for session id ${n}: ${t}`)}}),this.clearStoreOfOldSessions=({loggerProvider:e,apiKey:t,currentSessionId:n})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n),r=e.transaction("sessionTargetingMatch","readwrite"),o=yield r.store.getAll();for(let e=0;e<o.length;e++){const t=o[e],n=Date.now()-t.lastUpdated;t.sessionId!==i&&n>1728e5&&(yield r.store.delete(t.sessionId))}yield r.done}catch(t){e.warn(`Failed to clear old targeting matches for sessions: ${t}`)}})}};function At(e={}){return{name:"amplitude/url-tracking@1",observer(t,n,i){var r,o,s;const a=Object.assign(Object.assign({},e),i),l=a.ugcFilterRules||[],c=null!==(r=a.enablePolling)&&void 0!==r&&r,d=null!==(o=a.pollingInterval)&&void 0!==o?o:1e3,u=null!==(s=a.captureDocumentTitle)&&void 0!==s&&s;if(!n)return()=>{};let h;const g=()=>n.location&&n.location.href||"",v=()=>{const e=g();if(void 0===h||e!==h){h=e;const i=(()=>{const{innerHeight:e,innerWidth:t,document:i}=n,r=g();let o="";return u&&(o=(null==i?void 0:i.title)||""),{href:l.length>0?Y(r,l):r,title:o,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(i)}},f=e=>function(...t){const n=e.apply(this,t);return v(),n},p=()=>{v()};if(c){const e=n.setInterval(()=>{v()},d);return v(),()=>{e&&n.clearInterval(e)}}if(n.history){const e=n.history.pushState.bind(n.history),t=n.history.replaceState.bind(n.history);return(()=>{n.history.pushState=f(e),n.history.replaceState=f(t)})(),n.addEventListener("popstate",v),n.addEventListener("hashchange",p),v(),()=>{n.history.pushState=e,n.history.replaceState=t,n.removeEventListener("popstate",v),n.removeEventListener("hashchange",p)}}return n.addEventListener("hashchange",p),v(),()=>{n.removeEventListener("hashchange",p)}},options:e}}class Bt{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.teardownEventListeners=e=>{const t=g();t&&(t.removeEventListener("blur",this.blurListener),t.removeEventListener("focus",this.focusListener),!e&&t.addEventListener("blur",this.blurListener),!e&&t.addEventListener("focus",this.focusListener),t.self&&"onpagehide"in t.self?(t.removeEventListener("pagehide",this.pageLeaveListener),!e&&t.addEventListener("pagehide",this.pageLeaveListener)):(t.removeEventListener("beforeunload",this.pageLeaveListener),!e&&t.addEventListener("beforeunload",this.pageLeaveListener)))},this.blurListener=()=>{this.sendEvents()},this.focusListener=()=>{this.recordEvents(!1)},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach(t=>{t(e)})},this.evaluateTargetingAndCapture=(e,t=!1,n=!1)=>i(this,void 0,void 0,function*(){if(this.identifiers&&this.identifiers.sessionId&&this.config){if(!this.config.targetingConfig){if(!t)return void this.loggerProvider.log("No targeting config set, skipping initialization/recording for event.");this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}if(this.lastTargetingParams=e,this.config.targetingConfig&&!this.sessionTargetingMatch){let t=e.event;t&&Object.values(a).includes(t.event_type)&&(t=void 0),this.sessionTargetingMatch=yield(({sessionId:e,targetingConfig:t,loggerProvider:n,apiKey:r,targetingParams:o})=>i(void 0,void 0,void 0,function*(){if(yield Ft.clearStoreOfOldSessions({loggerProvider:n,apiKey:r,currentSessionId:e}),!0===(yield Ft.getTargetingMatchForSession({loggerProvider:n,apiKey:r,sessionId:e})))return!0;let i=!0;try{const{evaluateTargeting:s}=yield import("./targeting-min.js").then(function(e){return e.i}),a=yield s(Object.assign(Object.assign({},o),{flag:t,sessionId:e,apiKey:r,loggerProvider:n}));a&&a.sr_targeting_config&&(i="on"===a.sr_targeting_config.key),Ft.storeTargetingMatchForSession({loggerProvider:n,apiKey:r,sessionId:e,targetingMatch:i})}catch(e){const t=e;n.warn(t.message)}return i}))({sessionId:this.identifiers.sessionId,targetingConfig:this.config.targetingConfig,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:t}}),this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:t,targetingParams:e},null,2))}t?this.initialize(!0):!n&&this.recordCancelCallback||(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),yield this.recordEvents())}else this.identifiers&&!this.identifiers.sessionId?this.loggerProvider.log("Session ID has not been set yet, cannot evaluate targeting for Session Replay."):this.loggerProvider.warn("Session replay init has not been called, cannot evaluate targeting.")}),this.addCustomRRWebEvent=(e,t={},n=!0)=>i(this,void 0,void 0,function*(){try{let i;const r=this.config;if(r&&e!==J.METADATA&&(i={config:te(r),version:Be},n)){const e=yield ee();i=Object.assign(Object.assign({},e),i)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},t),i)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}}),this.stopRecordingEvents=()=>{var e;try{this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(e=this.networkObservers)||void 0===e||e.stop()}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new G(new y)}init(e,t){return p(this._init(e,t))}_init(e,t){var n,r,o,s,a,l,c;return i(this,void 0,void 0,function*(){this.loggerProvider=new G(t.loggerProvider||new y),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.identifiers=new Ut({sessionId:t.sessionId,deviceId:t.deviceId}),this.joinedConfigGenerator=yield((e,t)=>i(void 0,void 0,void 0,function*(){const n=new ie(e,t),i=new U(e,n.loggerProvider,n.serverZone,t.configServerUrl);return new se(i,n)}))(e,t);const{joinedConfig:d,localConfig:u,remoteConfig:h}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=d,this.setMetadata(t.sessionId,d,u,h,null===(n=t.version)||void 0===n?void 0:n.version,Be,null===(r=t.version)||void 0===r?void 0:r.type),t.sessionId&&(null===(o=this.config.interactionConfig)||void 0===o?void 0:o.enabled)){const e=jt.default({sessionId:t.sessionId,type:"interaction"},this.config);this.pageLeaveFns=[e.send(this.getDeviceId.bind(this)).bind(e)],this.scrollHook=e.hook.bind(e)}const v=[];let f,{storeType:p}=this.config;"idb"!==p||(null===(s=g())||void 0===s?void 0:s.indexedDB)||(p="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${p} for event storage.`);try{const e=yield Ve({config:this.config,sessionId:this.identifiers.sessionId,type:"replay",storeType:p});v.push({name:"replay",manager:e})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(a=this.config.interactionConfig)||void 0===a?void 0:a.enabled){const e=this.config.interactionConfig.batch?Dt:Lt;try{const t=yield Ve({config:this.config,sessionId:this.identifiers.sessionId,type:"interaction",minInterval:null!==(l=this.config.interactionConfig.trackEveryNms)&&void 0!==l?l:3e4,maxInterval:6e4,payloadBatcher:e,storeType:p});v.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new Ye(...v),this.eventCompressor&&this.eventCompressor.terminate();const m=g();if((null===(c=this.config.experimental)||void 0===c?void 0:c.useWebWorker)&&m&&m.Worker){const{compressionScript:e}=yield import("./worker-min.js");f=e}this.eventCompressor=new Fe(this.eventsManager,this.config,this.getDeviceId(),f),yield this.initializeNetworkObservers(),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),yield this.evaluateTargetingAndCapture({userProperties:t.userProperties},!0)})}setSessionId(e,t){return p(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,n){var r;return i(this,void 0,void 0,function*(){this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0;const i=this.identifiers&&this.identifiers.sessionId;i&&this.sendEvents(i);const o=t||this.getDeviceId();if(this.identifiers=new Ut({sessionId:e,deviceId:o}),this.joinedConfigGenerator&&i){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig();this.config=e}(null===(r=this.config)||void 0===r?void 0:r.targetingConfig)?yield this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties},!1,!0):yield this.recordEvents()})}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let i={};return n&&(i={[A]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(i[W]=JSON.stringify({appHash:D(e.apiKey).toString()}))),this.addCustomRRWebEvent(J.GET_SR_PROPS,{shouldRecord:n,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i}sendEvents(e){var t;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();this.eventsManager&&n&&i&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:i})}initialize(e=!1){var t;return i(this,void 0,void 0,function*(){if(!(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId))return this.loggerProvider.log("Session is not being recorded due to lack of session id."),Promise.resolve();const n=this.getDeviceId();return n?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())})}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(i=this.config.instanceName,void 0===i&&(i=d),N.getInstance(i)).identityStore.getIdentity().optOut}var i;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;let e=!1,t="",n=!1;if(this.config.targetingConfig)this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,n=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,n=!1);else{(i=this.identifiers.sessionId,r=this.config.sampleRate,o=D(i.toString()),31*Math.abs(o)%1e6/1e6<r)?(e=!0,n=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,n=!1)}var i,r,o;return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(J.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:n,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e,t,n;const i=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==i.length)return i}getMaskTextSelectors(){var e,t,n,i;if("conservative"===(null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.defaultMaskLevel))return"*";const r=null===(i=null===(n=this.config)||void 0===n?void 0:n.privacyConfig)||void 0===i?void 0:i.maskSelector;return r||void 0}getRecordingPlugins(e){var t,n,r,o,s,a;return i(this,void 0,void 0,function*(){const i=[];try{const e=At({ugcFilterRules:(null===(n=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)||[],enablePolling:(null===(r=this.config)||void 0===r?void 0:r.enableUrlChangePolling)||!1,pollingInterval:null===(o=this.config)||void 0===o?void 0:o.urlChangePollingInterval,captureDocumentTitle:null===(s=this.config)||void 0===s?void 0:s.captureDocumentTitle});i.push(e)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(null===(a=null==e?void 0:e.console)||void 0===a?void 0:a.enabled)try{const{getRecordConsolePlugin:t}=yield import("./console-plugin-min.js");i.push(t({level:e.console.levels}))}catch(e){this.loggerProvider.warn("Failed to load console plugin:",e)}return i.length>0?i:void 0})}getRecordFunction(){return i(this,void 0,void 0,function*(){if(this.recordFunction)return this.recordFunction;try{const{record:e}=yield import("./rrweb-record-min.js");return this.recordFunction=e,e}catch(e){return this.loggerProvider.warn("Failed to load rrweb-record module:",e),null}})}recordEvents(e=!0){var t,n,r,o,s;return i(this,void 0,void 0,function*(){const i=this.config,a=this.getShouldRecord(),l=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!a||!l||!i)return;this.stopRecordingEvents();const c=yield this.getRecordFunction();if(!c)return;yield this.initializeNetworkObservers(),null===(n=this.networkObservers)||void 0===n||n.start(e=>{this.addCustomRRWebEvent(J.FETCH_REQUEST,e)});const{privacyConfig:d,interactionConfig:u,loggingConfig:h}=i,g=(null==u?void 0:u.enabled)?{mouseInteraction:this.eventsManager&&qt(this.loggerProvider,{eventsManager:this.eventsManager,sessionId:l,deviceIdFn:this.getDeviceId.bind(this),mirror:c.mirror,ugcFilterRules:null!==(r=u.ugcFilterRules)&&void 0!==r?r:[]}),scroll:this.scrollHook}:{},v=(null==u?void 0:u.enabled)&&u.ugcFilterRules?u.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${l}.`);try{this.recordCancelCallback=c({emit:e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${l} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===re.Meta&&(e.data.href=Y(e.data.href,v)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,l)},inlineStylesheet:i.shouldInlineStylesheet,hooks:g,maskAllInputs:!0,maskTextClass:z,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:i.applyBackgroundColorToBlockedElements,maskInputFn:Z("input",d),maskTextFn:Z("text",d),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,slimDOMOptions:{script:null===(o=i.omitElementTags)||void 0===o?void 0:o.script,comment:null===(s=i.omitElementTags)||void 0===s?void 0:s.comment},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn("Error while capturing replay: ",t.toString()),!0},plugins:yield this.getRecordingPlugins(h)}),this.addCustomRRWebEvent(J.DEBUG_INFO),e&&this.addCustomRRWebEvent(J.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}})}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}flush(e=!1){var t;return i(this,void 0,void 0,function*(){return null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)})}shutdown(){this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()}mapSDKType(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null}setMetadata(e,t,n,i,r,o,s){const a=(null==e?void 0:e.toString())?D(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:i,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(s),replaySDKVersion:r,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:o}}initializeNetworkObservers(){var e,t,n;return i(this,void 0,void 0,function*(){if((null===(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===t?void 0:t.network)||void 0===n?void 0:n.enabled)&&!this.networkObservers)try{const{NetworkObservers:e}=yield import("./observers-min.js");this.networkObservers=new e}catch(e){this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",e)}})}}const Kt=e=>()=>{const{config:t}=e,{loggerProvider:n,logLevel:i}=t||ne();return{logger:n,logLevel:i}};var Wt=(()=>{const e=new Bt;return{init:L(e.init.bind(e),"init",Kt(e)),evaluateTargetingAndCapture:L(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Kt(e)),setSessionId:L(e.setSessionId.bind(e),"setSessionId",Kt(e)),getSessionId:L(e.getSessionId.bind(e),"getSessionId",Kt(e)),getSessionReplayProperties:L(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Kt(e)),flush:L(e.flush.bind(e),"flush",Kt(e)),shutdown:L(e.shutdown.bind(e),"shutdown",Kt(e))}})();const{init:zt,setSessionId:Jt,getSessionId:Gt,getSessionReplayProperties:Ht,flush:Qt,shutdown:Zt,evaluateTargetingAndCapture:Xt}=Wt;export{G as S,Gt as a,Ht as b,Zt as c,Xt as e,Qt as f,g,zt as i,Jt as s};
2
2
  //# sourceMappingURL=index-min.js.map
Binary file