@amplitude/segment-session-replay-plugin 0.0.52 → 0.0.53

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
- function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},t(e,n)};function n(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r,i,o=function(){return o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function s(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function a(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{l(r.next(e))}catch(e){o(e)}}function a(e){try{l(r.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((r=r.apply(e,t||[])).next())})}function l(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(l){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,l])}}}function c(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function d(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError,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"}(r||(r={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(i||(i={}));var h,v="$default_instance",g="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"}(h||(h={}));var f=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},p=d([],u(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),m=function(e){var t,n=f();if(!(null===(t=null==n?void 0:n.crypto)||void 0===t?void 0:t.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,m)}(e);var r=n.crypto.getRandomValues(new Uint8Array(16));return r[6]=15&r[6]|64,r[8]=63&r[8]|128,d([],u(r.entries()),!1).map(function(e){var t=u(e,2),n=t[0],r=t[1];return[4,6,8,10].includes(n)?"-".concat(p[r]):p[r]}).join("")},y={},b={get exports(){return y},set exports(e){y=e}},S=Object.prototype.hasOwnProperty;function I(e){return"[Throws: "+(e?e.message:"?")+"]"}function w(e){var t=[];return function e(n){if(null===n||"object"!=typeof n)return n;if(-1!==t.indexOf(n))return"[Circular]";if(t.push(n),"function"==typeof n.toJSON)try{var r=e(n.toJSON());return t.pop(),r}catch(e){return I(e)}if(Array.isArray(n)){var i=n.map(e);return t.pop(),i}var o=Object.keys(n).reduce(function(t,r){return t[r]=e(function(e,t){if(S.call(e,t))try{return e[t]}catch(e){return I(e)}return e[t]}(n,r)),t},{});return t.pop(),o}(e)}b.exports=function(e,t,n){return JSON.stringify(w(e),t,n)};var C,E=y.ensureProperties=w,P=y||e({__proto__:null,ensureProperties:E,get default(){return y}},[y]),k=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"}(C||(C={}));var x="Amplitude Logger ",M=function(){function e(){this.logLevel=C.None}return e.prototype.disable=function(){this.logLevel=C.None},e.prototype.enable=function(e){void 0===e&&(e=C.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Verbose||console.log("".concat(x,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Warn||console.warn("".concat(x,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Error||console.error("".concat(x,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Debug||console.log("".concat(x,"[Debug]: ").concat(e.join(" ")))},e}(),T=function(e){return void 0===e||""===e?v:e},O=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:v,logLevel:C.Warn,loggerProvider:new M,offline:!1,optOut:!1,serverUrl:g,serverZone:"US",useBatch:!1}},R=function(){function e(e){var t,n,r,i;this._optOut=!1;var o=O();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=T(e.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!==(r=e.optOut)&&void 0!==r?r:o.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||o.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(i=e.useBatch)&&void 0!==i?i:o.useBatch,this.loggerProvider.enable(this.logLevel);var s=L(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}(),_=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":g},L=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=O().serverZone),void 0===n&&(n=O().useBatch),e)return{serverUrl:e,serverZone:void 0};var r=["US","EU"].includes(t)?t:O().serverZone;return{serverZone:r,serverUrl:_(r,n)}};var F=function(e,t,n,r,i){return void 0===i&&(i=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<C.Debug||!c||!l)return e.apply(i,o);var u,d={type:"invoke public method",name:t,args:o,stacktrace:(u=1,void 0===u&&(u=0),((new Error).stack||"").split("\n").slice(2+u).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};r&&d.states&&(d.states.before=r());var h=e.apply(i,o);return h&&h.promise?h.promise.then(function(){r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))}):(r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))),h}};class D{getApplicationContext(){return{versionName:this.versionName,language:q(),platform:"Web",os:void 0,deviceModel:void 0}}}const q=()=>"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||"";class A{constructor(){this.queue=[]}logEvent(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)}setEventReceiver(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(t=>{e(t)}),this.queue=[])}}const j=(e,t)=>{const n=["string","number","boolean","undefined"],r=typeof e;if(r!==typeof t)return!1;for(const i of n)if(i===r)return e===t;if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;const i=Array.isArray(e),o=Array.isArray(t);if(i!==o)return!1;if(!i||!o){const n=Object.keys(e).sort(),r=Object.keys(t).sort();if(!j(n,r))return!1;let i=!0;return Object.keys(e).forEach(n=>{j(e[n],t[n])||(i=!1)}),i}for(let n=0;n<e.length;n++)if(!j(e[n],t[n]))return!1;return!0};Object.entries||(Object.entries=function(e){const t=Object.keys(e);let n=t.length;const r=new Array(n);for(;n--;)r[n]=[t[n],e[t[n]]];return r});class B{constructor(){this.identity={userProperties:{}},this.listeners=new Set}editIdentity(){const e=this,t=Object.assign({},this.identity.userProperties),n=Object.assign(Object.assign({},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(e){return n.optOut=e,this},updateUserProperties:function(e){let t=n.userProperties||{};for(const[n,r]of Object.entries(e))switch(n){case"$set":for(const[e,n]of Object.entries(r))t[e]=n;break;case"$unset":for(const e of Object.keys(r))delete t[e];break;case"$clearAll":t={}}return n.userProperties=t,this},commit:function(){return e.setIdentity(n),this}}}getIdentity(){return Object.assign({},this.identity)}setIdentity(e){const t=Object.assign({},this.identity);this.identity=Object.assign({},e),j(t,this.identity)||this.listeners.forEach(t=>{t(e)})}addIdentityListener(e){this.listeners.add(e)}removeIdentityListener(e){this.listeners.delete(e)}}const N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self;class U{constructor(){this.identityStore=new B,this.eventBridge=new A,this.applicationContextProvider=new D}static getInstance(e){return N.analyticsConnectorInstances||(N.analyticsConnectorInstances={}),N.analyticsConnectorInstances[e]||(N.analyticsConnectorInstances[e]=new U),N.analyticsConnectorInstances[e]}}var W=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},z=function(){function e(){}return e.prototype.send=function(e,t,n){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,r,i,o,s,a,l,c,u,d,v,g,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 h.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!==(r=e.server_upload_time)&&void 0!==r?r:0}};case h.Invalid:return{status:P,statusCode:E,body:{error:null!==(i=e.error)&&void 0!==i?i:"",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!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(d=e.silenced_devices)&&void 0!==d?d:[],silencedEvents:null!==(v=e.silenced_events)&&void 0!==v?v:[],throttledDevices:null!==(g=e.throttled_devices)&&void 0!==g?g:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case h.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case h.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 h.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?h.Success:429===e?h.RateLimit:413===e?h.PayloadTooLarge:408===e?h.Timeout:e>=400&&e<500?h.Invalid:e>=500?h.Failed:h.Unknown},e}(),K=function(e){function t(t){void 0===t&&(t={});var n=e.call(this)||this;return n.customHeaders=t,n}return n(t,e),t.prototype.send=function(e,t){return a(this,void 0,void 0,function(){var n,r,i;return l(this,function(s){switch(s.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:o({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(r=s.sent()).text()];case 2:i=s.sent();try{return[2,this.buildResponse(JSON.parse(i))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}})})},t}(z),H=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t;try{this.isSupported="undefined"!=typeof localStorage}catch(e){this.logger.debug("Remote config localstorage failed to access: ",e),this.isSupported=!1}}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};if(!this.isSupported)return Promise.resolve(t);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(P(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){if(!this.isSupported)return Promise.resolve(!1);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}();var G,Q=401,J=403,$=429,Z=function(){function e(t,n,r,i,o,s,a){void 0===r&&(r="US"),void 0===s&&(s=e.DEFAULT_CONFIG_GROUP),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=t,this.configGroup=s,this.serverUrl=i||("US"===r?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=n,this.storage=a||new H(t,n),this.customFetch=o}return e.prototype.subscribe=function(e,t,n){var r=m(),i={id:r,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(i),"all"===t?this.subscribeAll(i):this.subscribeWaitForRemote(i,t.timeout),r},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 a(this,void 0,void 0,function(){var e,t=this;return l(this,function(n){switch(n.label){case 0:return this.lastSuccessfulFetch&&Date.now()-this.lastSuccessfulFetch<3e5?(this.logger.debug("Remote config client skipping updateConfigs: Too recent"),[2]):[4,this.getOrCreateFetchPromise()];case 1:return e=n.sent(),this.storage.setConfig(e),this.callbackInfos.forEach(function(n){t.sendCallback(n,e,"remote")}),[2]}})})},e.prototype.getOrCreateFetchPromise=function(){var e=this;return this.fetchPromise?this.fetchPromise:this.isLastFetchInvalidApiKey?(this.logger.debug("Remote config client skipping fetch: Invalid API key"),this.fetchPromise=Promise.resolve({remoteConfig:null,lastFetch:new Date}).finally(function(){e.fetchPromise=null}),this.fetchPromise):(this.fetchPromise=this.fetch().then(function(t){return null!==t.remoteConfig&&(e.lastSuccessfulFetch=Date.now()),t}).finally(function(){e.fetchPromise=null}),this.fetchPromise)},e.prototype.subscribeAll=function(e){return a(this,void 0,void 0,function(){var t,n,r,i=this;return l(this,function(o){switch(o.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){i.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),i.sendCallback(e,t,"remote"),i.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(r=o.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(r))),null!==r.remoteConfig?this.sendCallback(e,r,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return o.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return a(this,void 0,void 0,function(){var n,r;return l(this,function(i){switch(i.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),i.label=1;case 1:return i.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),n])];case 2:return r=i.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,r,"remote"),this.storage.setConfig(r),[3,5];case 3:return i.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!==(r=i.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,r,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,r,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var r;e.lastCallback=new Date,r=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(r,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),a(this,void 0,void 0,function(){var n,r,i,o,s,a,c=this;return l(this,function(u){switch(u.label){case 0:n=t/e,r={remoteConfig:null,lastFetch:new Date},i=function(r){var i,s,a,u,d,h,v,g,f;return l(this,function(l){switch(l.label){case 0:i=!0,s=new AbortController,a=setTimeout(function(){return s.abort()},t),l.label=1;case 1:return l.trys.push([1,10,11,12]),u=o.getUrlParams(),d={Accept:"*/*"},o.customFetch?[4,(p=o.customFetch({url:u,method:"GET",headers:d,signal:s.signal}),m=s.signal,new Promise(function(e,t){var n=function(){var e=new Error("Remote config custom fetch aborted by timeout");e.name="AbortError",t(e)};m.addEventListener("abort",n,{once:!0}),p.then(function(t){m.removeEventListener("abort",n),e(t)},function(e){m.removeEventListener("abort",n),t(e)})}))]:[3,3];case 2:return v=l.sent(),[3,5];case 3:return[4,fetch(u,{method:"GET",headers:d,signal:s.signal})];case 4:v=l.sent(),l.label=5;case 5:return(h=v).ok||h.status>=200&&h.status<300?[3,7]:[4,h.text()];case 6:return g=l.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(h.status,": ").concat(g)),h.status===Q||h.status===J?(o.logger.error("Remote config client fetch failed with ".concat(h.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,i=!1):h.status>=400&&h.status<500&&h.status!==$&&(i=!1),[3,9];case 7:return[4,h.json()];case 8:return[2,{value:{remoteConfig:l.sent(),lastFetch:new Date}}];case 9:return[3,12];case 10:return(f=l.sent())instanceof Error&&"AbortError"===f.name?o.logger.debug("Remote config client fetch with retry time ".concat(e," timed out after ").concat(t,"ms")):o.logger.debug("Remote config client fetch with retry time ".concat(e," is rejected because: "),f),[3,12];case 11:return clearTimeout(a),[7];case 12:return i?r<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,14]:[2,"break"];case 13:l.sent(),l.label=14;case 14:return[2]}var p,m})},o=this,s=0,u.label=1;case 1:return s<e?[5,i(s)]:[3,4];case 2:if("object"==typeof(a=u.sent()))return[2,a.value];if("break"===a)return[3,4];u.label=3;case 3:return s++,[3,1];case 4:return[2,r]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var e=encodeURIComponent(this.apiKey),t=new URLSearchParams;return t.append("config_group",this.configGroup),"".concat(this.serverUrl,"/").concat(e,"?").concat(t.toString())},e.DEFAULT_CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(G||(G={}));var V,X="https://app.amplitude.com",Y={US:X,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var ee="__AMPLITUDE_MESSENGER_INSTANCE__",te="__AMPLITUDE_MESSENGER__",ne=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?X:t;this[V]=!0,this.isSetup=!1,this.messageHandler=null,this.requestCallbacks={},this.actionHandlers=new Map,this.pendingMessages=new Map,this.scriptLoadPromises=new Map,this.endpoint=n}return e.prototype.notify=function(e){var t,n,r,i;null===(n=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message sent: ",JSON.stringify(e)),null===(i=null===(r=window.opener)||void 0===r?void 0:r.postMessage)||void 0===i||i.call(r,e,this.endpoint)},e.prototype.sendRequest=function(e,t,n){var r=this;void 0===n&&(n={timeout:15e3});var i="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),o={id:i,action:e,args:t};return new Promise(function(t,s){r.requestCallbacks[i]={resolve:t,reject:s},r.notify(o),n.timeout>0&&setTimeout(function(){s(new Error("".concat(e," timed out (id: ").concat(i,")"))),delete r.requestCallbacks[i]},n.timeout)})},e.prototype.handleResponse=function(e){var t;this.requestCallbacks[e.id]?(this.requestCallbacks[e.id].resolve(e.responseData),delete this.requestCallbacks[e.id]):null===(t=this.logger)||void 0===t||t.warn("No callback found for request id: ".concat(e.id))},e.prototype.registerActionHandler=function(e,t){var n,r,i,o;this.actionHandlers.has(e)&&(null===(o=null===(i=this.logger)||void 0===i?void 0:i.warn)||void 0===o||o.call(i,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var s=this.pendingMessages.get(e);if(s){this.pendingMessages.delete(e);try{for(var a=c(s),l=a.next();!l.done;l=a.next()){t(l.value)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}},e.prototype.loadScriptOnce=function(e){return a(this,void 0,void 0,function(){var t,n,r;return l(this,function(i){switch(i.label){case 0:if(t=this.scriptLoadPromises.get(e))return[2,t];n=function(e){return document.querySelector('script[src="'.concat(CSS.escape(e),'"]'))?Promise.resolve({status:!0}):new Promise(function(t,n){var r;try{var i=document.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.addEventListener("load",function(){t({status:!0})},{once:!0}),i.addEventListener("error",function(){n({status:!1,message:"Failed to load the script ".concat(e)})}),null===(r=document.head)||void 0===r||r.appendChild(i)}catch(e){n(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,n),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,n];case 2:return i.sent(),[3,4];case 3:throw r=i.sent(),this.scriptLoadPromises.delete(e),r;case 4:return[2]}})})},e.prototype.setup=function(e){var t,n,r=this,i=void 0===e?{}:e,o=i.logger,s=i.endpoint;o&&(this.logger=o),s&&this.endpoint===X&&(this.endpoint=s),this.isSetup||(this.isSetup=!0,null===(n=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Setting up messenger"),this.messageHandler=function(e){var t,n,i,o,s;if(null===(n=null===(t=r.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message received: ",JSON.stringify(e)),r.endpoint===e.origin){var a=e.data,l=null==a?void 0:a.action;if(l)if("id"in a&&a.id)null===(o=null===(i=r.logger)||void 0===i?void 0:i.debug)||void 0===o||o.call(i,"Received Response to previous request: ",JSON.stringify(e)),r.handleResponse(a);else{if("ping"===l)return void r.notify({action:"pong"});var c=r.actionHandlers.get(l);if(c)c(a.data);else{var u=null!==(s=r.pendingMessages.get(l))&&void 0!==s?s:[];u.push(a.data),r.pendingMessages.set(l,u)}}}},window.addEventListener("message",this.messageHandler),this.notify({action:"page-loaded"}))},e.prototype.destroy=function(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.isSetup=!1,this.actionHandlers.clear(),this.pendingMessages.clear(),this.requestCallbacks={},this.scriptLoadPromises.clear();var e=f();(null==e?void 0:e[te])===this&&delete e[te]},e}();function re(e){var t,n=f(),r=null==n?void 0:n[te];if("object"==typeof(t=r)&&null!==t&&ee in t&&!0===t[ee])return r;var i=new ne(e);return n&&(n[te]=i),i}V=ee;var ie=["desktop","tablet","mobile"],oe="__AMPLITUDE_BACKGROUND_CAPTURE__";function se(e,t){var n,r=e;if(!0!==r[oe]){r[oe]=!0;var i=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.1.0.js.gz",s=null,a=function(t,n){var r,i;"background-capture-complete"===t&&(null===(i=null===(r=e.logger)||void 0===r?void 0:r.debug)||void 0===i||i.call(r,"Background capture complete"),e.notify({action:"background-capture-complete",data:n}))};e.registerActionHandler("initialize-background-capture",function(t){var n,r;null===(r=null===(n=e.logger)||void 0===n?void 0:n.debug)||void 0===r||r.call(n,"Initializing background capture (external script)");var l=new URL(i,e.endpoint).toString(),c=t&&"object"==typeof t?function(e){if("string"==typeof e)return ie.includes(e)?e:void 0}(t.deviceMode):void 0;e.loadScriptOnce(l).then(function(){var t,n,r;null===(n=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Background capture script loaded (external)"),s=null===(r=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===r?void 0:r.call(window,o({messenger:e,onBackgroundCapture:a},void 0!==c?{initialDeviceMode:c}:{})),e.notify({action:"background-capture-loaded"})}).catch(function(){var t;null===(t=e.logger)||void 0===t||t.warn("Failed to initialize background capture")})}),e.registerActionHandler("close-background-capture",function(){var e;null===(e=null==s?void 0:s.close)||void 0===e||e.call(s),s=null})}}var ae,le="[Amplitude]",ce="".concat(le," Session Replay ID"),ue=G.US,de={enabled:!0},he=1e3,ve="".concat(le," Session Replay Debug"),ge="https://api-sr.amplitude.com/sessions/v2/track",fe="https://api-sr.eu.amplitude.com/sessions/v2/track",pe="https://api-sr.stag2.amplitude.com/sessions/v2/track",me=9e6,ye=/payload.*exceed/i,be=500,Se=1e4,Ie=1024,we="X-Session-Replay-Event-Skipped",Ce="amplitude-sr-iframe";!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",e.REPLAY_GATE_DECISION="replay-gate-decision"}(ae||(ae={}));var Ee=function(){function e(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}return e.prototype.getSafeMethod=function(e){var t;if(!this.logger)return function(){};var n=this.logger[e];return"function"==typeof n?(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger):function(){}},e.prototype.enable=function(e){this.logger.enable(e)},e.prototype.disable=function(){this.logger.disable()},e}(),Pe="medium";var ke=new Map,xe=function(e){var t=ke.get(e);if(t)return t;var n="\0TRAIL\0",r="\0MID\0",i="\0DS\0",o="\0ST\0",s="\0QU\0",a=e;a=(a=(a=(a=(a=(a=(a=(a=(a=(a=(a=a.replace(/\/\*\*$/,n)).replace(/\/\*\*\//g,r)).replace(/\*\*/g,i)).replace(/\*/g,o)).replace(/\?/g,s)).replace(/[.+^${}()|[\]\\]/g,"\\$&")).split(n).join("(/.*)?")).split(r).join("/(.*\\/)?")).split(i).join(".*")).split(o).join(".*")).split(s).join(".");var l=new RegExp("^".concat(a,"$"));return ke.set(e,l),l},Me=function(e,t,n){switch(t){case"light":if("input"!==e)return!1;var r=n?function(e){var t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!r&&(!!["password","hidden","email","tel"].includes(r)||!!n.autocomplete.startsWith("cc-"));case"medium":return"input"===e;case"conservative":return!0;default:return Me(e,Pe,n)}},Te=function(e,t){var n,r,i;if(e&&t.urlMaskLevels)try{for(var o=c(t.urlMaskLevels),s=o.next();!s.done;s=o.next()){var a=s.value;if(xe(a.match).test(e))return a.maskLevel}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null!==(i=t.defaultMaskLevel)&&void 0!==i?i:Pe},Oe=function(e,t,n,r){var i,o;if(void 0===t&&(t={defaultMaskLevel:Pe}),n){if(n.closest(".amp-mask, [data-amp-mask]"))return!0;var s=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some(function(e){return n.closest(e)});if(s)return!0;if(n.closest(".amp-unmask, [data-amp-unmask]"))return!1;var a=(null!==(o=t.unmaskSelector)&&void 0!==o?o:[]).some(function(e){return n.closest(e)});if(a)return!1}return Me(e,Te(r,t),n)},Re=function(e,t,n){return function(r,i){return Oe(e,t,i,null==n?void 0:n())?r.replace(/[^\s]/g,"*"):r}},_e=function(e,t){return function(n,r,i){var o;if("style"===n)return r;if(!(null!==(o=null==e?void 0:e.maskAttributes)&&void 0!==o?o:[]).includes(n))return r;var s=["INPUT","SELECT","TEXTAREA"].includes(i.tagName)?"input":"text";return Oe(s,e,i,null==t?void 0:t())?r.replace(/[^\s]/g,"*"):r}},Le=function(e){var t=null==e?void 0:e.blockSelector;return d(d([],u("string"==typeof t?t?[t]:[]:null!=t?t:[]),!1),["[data-amp-block]"],!1).join(",")},Fe=function(e,t){var n,r;return e&&("conservative"===Te(t,e)||"conservative"===e.defaultMaskLevel||(null===(n=e.urlMaskLevels)||void 0===n?void 0:n.some(function(e){return"conservative"===e.maskLevel})))?"*":d(d([],u(null!==(r=null==e?void 0:e.maskSelector)&&void 0!==r?r:[]),!1),["[data-amp-mask]"],!1).join(",")};function De(e,t){return t||("STAGING"===e?pe:"EU"===e?fe:ge)}var qe=function(){var e=f();return(null==e?void 0:e.location)?e.location.href:""},Ae=function(e,t){var n,r;try{for(var i=c(t),o=i.next();!o.done;o=i.next()){var s=o.value,a=xe(s.selector);if(a.test(e))return e.replace(a,s.replacement)}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return e},je=function(){return a(void 0,void 0,void 0,function(){var e,t,n,r,i,o,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),(e=f())?[4,e.navigator.storage.estimate()]:[3,2];case 1:return t=a.sent(),n=t.usage,r=t.quota,i=t.usageDetails,o=n?Math.round(n/Ie):0,s=n&&r?Math.round(1e3*(n/r+Number.EPSILON))/1e3:0,[2,{totalStorageSize:o,percentOfQuota:s,usageDetails:JSON.stringify(i)}];case 2:return[3,4];case 3:return a.sent(),[3,4];case 4:return[2,{totalStorageSize:0,percentOfQuota:0,usageDetails:""}]}})})},Be=function(e){var t=o({},e),n=t.apiKey;return t.apiKey="****".concat(n.substring(n.length-4)),t},Ne=function(){return{flushMaxRetries:2,logLevel:C.Warn,loggerProvider:new M,transportProvider:new K}},Ue=function(e){function t(t,n){var r,i,s,a,l,c,h,v,g,f,p,m,y,b,S=this,I=Ne();(S=e.call(this,o(o({transportProvider:I.transportProvider,loggerProvider:new Ee(n.loggerProvider||I.loggerProvider)},n),{apiKey:t}))||this).flushMaxRetries=void 0!==n.flushMaxRetries&&n.flushMaxRetries<=I.flushMaxRetries?n.flushMaxRetries:I.flushMaxRetries,S.apiKey=t,S.sampleRate=n.sampleRate||0,S.serverZone=n.serverZone||ue,S.configServerUrl=n.configServerUrl,S.trackServerUrl=n.trackServerUrl,S.shouldInlineStylesheet=n.shouldInlineStylesheet,S.inlineImages=n.inlineImages,S.version=n.version,S.performanceConfig=n.performanceConfig||de,S.storeType=null!==(r=n.storeType)&&void 0!==r?r:"memory",S.applyBackgroundColorToBlockedElements=null!==(i=n.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,S.enableUrlChangePolling=null!==(s=n.enableUrlChangePolling)&&void 0!==s&&s,S.urlChangePollingInterval=null!==(a=n.urlChangePollingInterval)&&void 0!==a?a:he,S.captureDocumentTitle=null!==(l=n.captureDocumentTitle)&&void 0!==l&&l,void 0!==n.fullSnapshotIntervalMs&&(S.fullSnapshotIntervalMs=n.fullSnapshotIntervalMs),void 0!==n.eagerFullSnapshotSend&&(S.eagerFullSnapshotSend=n.eagerFullSnapshotSend),S.captureFullSnapshotOnFocus=null!==(c=n.captureFullSnapshotOnFocus)&&void 0!==c&&c,void 0!==n.maxPersistedEventsSizeBytes&&(S.maxPersistedEventsSizeBytes=Ge(n.maxPersistedEventsSizeBytes,ze,Ke,"maxPersistedEventsSizeBytes",S.loggerProvider)),void 0!==n.maxSingleEventSizeBytes&&(S.maxSingleEventSizeBytes=Ge(n.maxSingleEventSizeBytes,ze,He,"maxSingleEventSizeBytes",S.loggerProvider)),S.privacyConfig=o(o({},null!==(h=n.privacyConfig)&&void 0!==h?h:{}),{unmaskSelector:Array.from(new Set(d([".".concat("amp-unmask")],u(null!==(g=null===(v=n.privacyConfig)||void 0===v?void 0:v.unmaskSelector)&&void 0!==g?g:[]),!1)))}),n.interactionConfig&&(S.interactionConfig=n.interactionConfig,S.interactionConfig.ugcFilterRules&&function(e){if(!e.every(function(e){return"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(function(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")}(S.interactionConfig.ugcFilterRules)),n.debugMode&&(S.debugMode=n.debugMode);var w=n;return S.useWebWorker=null===(m=null!==(f=n.useWebWorker)&&void 0!==f?f:null===(p=w.experimental)||void 0===p?void 0:p.useWebWorker)||void 0===m||m,S.enableTransportCompression=null===(y=n.enableTransportCompression)||void 0===y||y,S.sendTimeoutMs=n.sendTimeoutMs,S.captureAdoptedStyleSheets=null===(b=n.captureAdoptedStyleSheets)||void 0===b||b,n.crossOriginIframes&&(S.crossOriginIframes=n.crossOriginIframes),n.flushIntervalConfig?S.flushIntervalConfig=function(e,t){var n,r,i={};void 0!==e.minIntervalMs&&(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<We?(t.warn("flushIntervalConfig.minIntervalMs ".concat(e.minIntervalMs," is below floor ").concat(We,"ms; clamping.")),i.minIntervalMs=We):i.minIntervalMs=e.minIntervalMs);void 0!==e.maxIntervalMs&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<We?(t.warn("flushIntervalConfig.maxIntervalMs ".concat(e.maxIntervalMs," is below floor ").concat(We,"ms; clamping.")),i.maxIntervalMs=We):i.maxIntervalMs=e.maxIntervalMs);if(void 0!==i.minIntervalMs||void 0!==i.maxIntervalMs){var o=null!==(n=i.minIntervalMs)&&void 0!==n?n:be,s=null!==(r=i.maxIntervalMs)&&void 0!==r?r:Se;s<o&&(void 0===i.maxIntervalMs?(t.warn("flushIntervalConfig.minIntervalMs (".concat(o,") exceeds the default maxIntervalMs (").concat(Se,"); raising max to match min.")),i.maxIntervalMs=o):void 0===i.minIntervalMs?(t.warn("flushIntervalConfig.maxIntervalMs (".concat(s,") is below the default minIntervalMs (").concat(be,"); lowering min to match max.")),i.minIntervalMs=s):(t.warn("flushIntervalConfig.maxIntervalMs (".concat(i.maxIntervalMs,") is less than minIntervalMs (").concat(i.minIntervalMs,"); raising max to match min.")),i.maxIntervalMs=i.minIntervalMs))}return i}(n.flushIntervalConfig,S.loggerProvider):S.flushIntervalConfig={minIntervalMs:1e3,maxIntervalMs:1e4},S.handleSendEvents=n.handleSendEvents,S.handleFetchConfig=n.handleFetchConfig,S}return n(t,e),t}(R),We=100,ze=1e3,Ke=8e6,He=1e7;function Ge(e,t,n,r,i){if(Number.isFinite(e))return e<t?(i.warn("".concat(r," ").concat(e," is below floor ").concat(t,"; clamping.")),t):e>n?(i.warn("".concat(r," ").concat(e," exceeds ceiling ").concat(n,"; clamping.")),n):e;i.warn("".concat(r," value is not a finite number (got ").concat(String(e),"); ignoring."))}var Qe=(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))(Qe||{}),Je=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(Je||{}),$e=(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))($e||{}),Ze=function(e,t){var n=document.createDocumentFragment();return function(e,t,n){var r,i,s=o({},e);try{for(var a=c(["blockSelector","maskSelector","unmaskSelector"]),l=a.next();!l.done;l=a.next()){var u=l.value,d=e[u],h=("string"==typeof d?[d]:null!=d?d:[]).filter(function(e){try{return t(e),!0}catch(t){if(!n)throw new Error("Invalid privacy selector: ".concat(e));return n(e),!1}});s[u]=h.length?h:void 0}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}return s}(e,function(e){n.querySelector(e)},function(e){t.warn('[session-replay-browser] omitting selector "'.concat(e,'" because it is invalid'))})},Ve=function(){function e(e,t){this.localConfig=t,this.remoteConfigClient=e}return e.prototype.generateJoinedConfig=function(){var e,t,n,r,i,s,h;return a(this,void 0,void 0,function(){var a,v,g,f,p,m,y,b,S,I,w,C,E,P,k,x,M,T=this;return l(this,function(l){switch(l.label){case 0:(a=o({},this.localConfig)).optOut=this.localConfig.optOut,a.captureEnabled=!0,l.label=1;case 1:return l.trys.push([1,3,,4]),[4,new Promise(function(e,t){T.remoteConfigClient.subscribe("configs.sessionReplay",{timeout:1500},function(n,r){var i;if(T.localConfig.loggerProvider.debug("Session Replay remote configuration received from ".concat(r,":"),JSON.stringify(n,null,2)),n){var o=n,s=o.sr_sampling_config,l=o.sr_privacy_config,c=o.sr_targeting_config,u=null===(i=a.interactionConfig)||void 0===i?void 0:i.ugcFilterRules;a.interactionConfig=o.sr_interaction_config,a.interactionConfig&&u&&(a.interactionConfig.ugcFilterRules=u),a.loggingConfig=o.sr_logging_config,(s||l||c)&&(v={},s&&(v.sr_sampling_config=s),l&&(v.sr_privacy_config=l),c&&(v.sr_targeting_config=c)),e()}else t(new Error("No remote config received"))})})];case 2:return l.sent(),[3,4];case 3:return g=l.sent(),this.localConfig.loggerProvider.error("Failed to generate joined config: ",g),a.captureEnabled=!1,[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:void 0}];case 4:if(!v)return[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:v}];if(f=v.sr_sampling_config,p=v.sr_privacy_config,m=v.sr_targeting_config,f&&Object.keys(f).length>0?(Object.prototype.hasOwnProperty.call(f,"capture_enabled")?a.captureEnabled=f.capture_enabled:a.captureEnabled=!1,Object.prototype.hasOwnProperty.call(f,"sample_rate")&&(a.sampleRate=f.sample_rate),Object.prototype.hasOwnProperty.call(f,"min_session_duration_ms")&&(a.minSessionDurationMs=this.sanitizeMinSessionDurationMs(f.min_session_duration_ms))):(a.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),p){y=null!==(e=a.privacyConfig)&&void 0!==e?e:{},b={defaultMaskLevel:null!==(n=null!==(t=p.defaultMaskLevel)&&void 0!==t?t:y.defaultMaskLevel)&&void 0!==n?n:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:d([],u(new Set(d(d([],u(null!==(r=y.maskAttributes)&&void 0!==r?r:[]),!1),u(null!==(i=p.maskAttributes)&&void 0!==i?i:[]),!1))),!1),urlMaskLevels:d(d([],u(null!==(s=p.urlMaskLevels)&&void 0!==s?s:[]),!1),u(null!==(h=y.urlMaskLevels)&&void 0!==h?h:[]),!1)},S=function(e){var t,n,r,i,o,s,a,l,u,d={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);try{for(var h=c(null!==(a=e.blockSelector)&&void 0!==a?a:[]),v=h.next();!v.done;v=h.next()){d[v.value]="block"}}catch(e){t={error:e}}finally{try{v&&!v.done&&(n=h.return)&&n.call(h)}finally{if(t)throw t.error}}try{for(var g=c(null!==(l=e.maskSelector)&&void 0!==l?l:[]),f=g.next();!f.done;f=g.next()){d[f.value]="mask"}}catch(e){r={error:e}}finally{try{f&&!f.done&&(i=g.return)&&i.call(g)}finally{if(r)throw r.error}}try{for(var p=c(null!==(u=e.unmaskSelector)&&void 0!==u?u:[]),m=p.next();!m.done;m=p.next()){d[m.value]="unmask"}}catch(e){o={error:e}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(o)throw o.error}}return d},I=o(o({},S(y)),S(p));try{for(w=c(Object.entries(I)),C=w.next();!C.done;C=w.next())E=u(C.value,2),P=E[0],"mask"===(k=E[1])?b.maskSelector.push(P):"block"===k?b.blockSelector.push(P):"unmask"===k&&b.unmaskSelector.push(P)}catch(e){x={error:e}}finally{try{C&&!C.done&&(M=w.return)&&M.call(w)}finally{if(x)throw x.error}}a.privacyConfig=Ze(b,this.localConfig.loggerProvider)}return m&&Object.keys(m).length>0&&(a.targetingConfig=m),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:Be(a)},null,2)),[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:v}]}})})},e.prototype.sanitizeMinSessionDurationMs=function(e){if("number"==typeof e&&Number.isFinite(e)){if(!(e<0))return e>Xe?(this.localConfig.loggerProvider.warn("min_session_duration_ms remote value ".concat(e," exceeds ").concat(Xe,"ms ceiling; clamping.")),Xe):e;this.localConfig.loggerProvider.warn("min_session_duration_ms remote value is negative (".concat(e,"); ignoring."))}else this.localConfig.loggerProvider.warn("min_session_duration_ms remote value is not a finite number (got ".concat(String(e),"); ignoring."))},e}(),Xe=6e4,Ye=function(e,t){return a(void 0,void 0,void 0,function(){var n,r;return l(this,function(i){return n=new Ue(e,t),r=new Z(e,n.loggerProvider,n.serverZone,t.configServerUrl,t.handleFetchConfig),[2,new Ve(r,n)]})})};function et(e){for(var t=e.length,n=0;n<t&&!(e.charCodeAt(n)>127);n++);if(n===t)return t;for(var r=n;n<t;n++){var i=e.charCodeAt(n);if(i<=127)r++;else if(i<=2047)r+=2;else if(i>=55296&&i<=56319){var o=n+1<t?e.charCodeAt(n+1):NaN;o>=56320&&o<=57343?(r+=4,n++):r+=3}else r+=3}return r}function tt(e){for(var t=0,n=0;n<e.length;n++)t+=et(e[n]);return t}function nt(e,t){if(!(3*e.length<=t)){var n=et(e);return n>t?n:void 0}}function rt(e,t){t<0&&(t=0);for(var n=e.length,r=0,i=0;i<n;i++){var o=e.charCodeAt(i),s=1,a=1;if(o<=127)s=1;else if(o<=2047)s=2;else if(o>=55296&&o<=56319){var l=i+1<n?e.charCodeAt(i+1):NaN;l>=56320&&l<=57343?(s=4,a=2):s=3}else s=3;if(r+s>t)break;r+=s,2===a&&i++}return i>=n?{value:e,truncated:!1}:{value:e.slice(0,i),truncated:!0}}function it(e){if(e.type!==Qe.IncrementalSnapshot)return!1;var t=e.data;return t.source===Je.Mutation&&!t.isAttachIframe}function ot(e){var t,n,r=new Map;if(e.forEach(function(e,t){if(e.attributes&&"style"in e.attributes){var n=r.get(e.id);n?n.push(t):r.set(e.id,[t])}}),0===r.size)return e;var i=function(t){return e[t].attributes.style},s=new Set,a=new Map,l=function(e){if(1===e.length)return"continue";var t=-1;e.forEach(function(e,n){var r;("object"!=typeof(r=i(e))||null===r)&&(t=n)});var n=[];if(e.forEach(function(e,r){r!==t&&(s.add(e),r>t&&n.push(e))}),n.length>0){var r=n[n.length-1],o=function(e){var t,n,r,i,o={};try{for(var s=c(e),a=s.next();!a.done;a=s.next()){var l=a.value;try{for(var u=(r=void 0,c(Object.keys(l))),d=u.next();!d.done;d=u.next()){var h=d.value;o[h]=l[h]}}catch(e){r={error:e}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return o}(n.map(function(e){return i(e)}));s.delete(r),a.set(r,o)}};try{for(var u=c(r.values()),d=u.next();!d.done;d=u.next()){l(d.value)}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}if(0===s.size&&0===a.size)return e;var h=[];return e.forEach(function(e,t){var n=a.get(t);if(void 0===n)if(s.has(t)){var r=o({},e.attributes);delete r.style,Object.keys(r).length>0&&h.push(o(o({},e),{attributes:r}))}else h.push(e);else h.push(o(o({},e),{attributes:o(o({},e.attributes),{style:n})}))}),h}function st(e){var t,n,r,i,s=e[0],a=new Map,l=new Map,d=new Map,h=new Map,v=new Map;e.forEach(function(e,t){var n,r,i,o,s=e.data;try{for(var u=c(s.adds),g=u.next();!g.done;g=u.next()){var f=g.value;a.has(f.node.id)||a.set(f.node.id,t),l.set(f.node.id,t),v.set(f.node.id,f.parentId)}}catch(e){n={error:e}}finally{try{g&&!g.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}try{for(var p=c(s.removes),m=p.next();!m.done;m=p.next()){var y=m.value;d.has(y.id)||d.set(y.id,t),h.set(y.id,t)}}catch(e){i={error:e}}finally{try{m&&!m.done&&(o=p.return)&&o.call(p)}finally{if(i)throw i.error}}});var g=new Set,f=new Set;try{for(var p=c(a),m=p.next();!m.done;m=p.next()){var y=u(m.value,2),b=y[0],S=y[1],I=d.get(b);if(void 0!==I)l.get(b)>=h.get(b)||(S<I?g.add(b):I<S&&f.add(b))}}catch(e){t={error:e}}finally{try{m&&!m.done&&(n=p.return)&&n.call(p)}finally{if(t)throw t.error}}var w=new Set;if(g.size>0||f.size>0)for(var C=!0;C;){C=!1;try{for(var E=(r=void 0,c(v)),P=E.next();!P.done;P=E.next()){var k=u(P.value,2),x=k[0],M=k[1];if(!g.has(x)&&!f.has(x)&&!w.has(x)&&(g.has(M)||f.has(M)||w.has(M))){var T=d.get(x),O=a.get(x);void 0!==T&&void 0!==O&&T<O?f.add(x):void 0!==T&&void 0!==O&&T===O?w.add(x):g.add(x),C=!0}}}catch(e){r={error:e}}finally{try{P&&!P.done&&(i=E.return)&&i.call(E)}finally{if(r)throw r.error}}}var R=g.size>0||f.size>0||w.size>0,_=[];e.forEach(function(e,t){var n,r;try{for(var i=c(e.data.removes),o=i.next();!o.done;o=i.next()){var s=o.value;g.has(s.id)||(f.has(s.id)&&t>=a.get(s.id)||w.has(s.id)&&(g.has(s.parentId)||f.has(s.parentId)||w.has(s.parentId))||_.push(s))}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}});var L=e.flatMap(function(e){return e.data.adds}),F=e.flatMap(function(e){return e.data.texts}),D=e.flatMap(function(e){return e.data.attributes}),q=R?D.filter(function(e){return!g.has(e.id)&&!f.has(e.id)&&!w.has(e.id)}):D,A={source:Je.Mutation,removes:_,adds:R?L.filter(function(e){return!g.has(e.node.id)&&!f.has(e.node.id)&&!w.has(e.node.id)}):L,texts:R?F.filter(function(e){return!g.has(e.id)&&!f.has(e.id)&&!w.has(e.id)}):F,attributes:ot(q)};return o(o({},s),{data:A})}function at(e){if(e.length<=1)return e;for(var t=[],n=0;n<e.length;)if(it(e[n])){for(var r=n+1;r<e.length&&it(e[r]);)r++;t.push(r>n+1?st(e.slice(n,r)):e[n]),n=r}else t.push(e[n]),n++;return t}var lt=function(){function e(e,t,n,r,i){var o,s=this;this.taskQueue=[],this.pendingQueue=[],this.isProcessing=!1,this.compressEvent=function(e){var t=e,n=t.type,r=t.timestamp,i=t.delay,o=t.data;return null!=i?JSON.stringify({type:n,timestamp:r,delay:i,data:o}):JSON.stringify({type:n,timestamp:r,data:o})},this.addCompressedEventToManager=function(e,t){var n,r=nt(e,null!==(n=s.config.maxSingleEventSizeBytes)&&void 0!==n?n:me);void 0===r?s.eventsManager&&s.deviceId&&s.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:s.deviceId}):s.config.loggerProvider.warn("Session replay event dropped: serialized size ".concat(Math.round(r/1024)," KB exceeds maximum allowed event size. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support."))},this.addCompressedEvent=function(e,t){if(s.worker)try{s.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?s.worker.postMessage(JSON.stringify({event:e,sessionId:t})):s.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{var n=s.compressEvent(e);s.addCompressedEventToManager(n,t)}},this.flushQueue=function(){var e;for(s.pendingQueue.length>0&&(e=s.taskQueue).push.apply(e,d([],u(s.mergeMutationTasks(s.pendingQueue.splice(0))),!1));s.taskQueue.length>0;){var t=s.taskQueue.shift();if(t){var n=t.event,r=t.sessionId,i=s.compressEvent(n);s.addCompressedEventToManager(i,r)}}s.isProcessing=!1},this.terminate=function(){var e;null===(e=s.worker)||void 0===e||e.terminate()};var a=f();if(this.canUseIdleCallback=a&&"requestIdleCallback"in a,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(o=t.performanceConfig)||void 0===o?void 0:o.timeout)||2e3,this.onFullSnapshotProcessed=i,r){t.loggerProvider.log("Enabling web worker for compression");try{var l=new Blob([r],{type:"application/javascript"}),c=URL.createObjectURL(l),h=new Worker(c);h.onerror=function(e){e.preventDefault(),t.loggerProvider.error("Worker failed, falling back to non-worker compression: ".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")")),h.terminate(),s.worker=void 0},h.onmessage=function(e){var t=e.data,n=t.compressedEvent,r=t.sessionId;s.addCompressedEventToManager(n,r)},this.worker=h}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}return e.prototype.scheduleIdleProcessing=function(){var e=this;this.isProcessing||(this.isProcessing=!0,requestIdleCallback(function(t){e.processQueue(t)},{timeout:this.timeout}))},e.prototype.enqueueEvent=function(e,t){var n,r,i,o;if(e.type===Qe.FullSnapshot){if(this.config.loggerProvider.debug("Processing full snapshot immediately."),this.taskQueue.length>0||this.pendingQueue.length>0){var s=d(d([],u(this.taskQueue.splice(0)),!1),u(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1);try{for(var a=c(s),l=a.next();!l.done;l=a.next()){var h=l.value,v=this.compressEvent(h.event);this.addCompressedEventToManager(v,h.sessionId)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this.isProcessing=!1}var g=this.compressEvent(e);return this.addCompressedEventToManager(g,t),void(null===(i=this.onFullSnapshotProcessed)||void 0===i||i.call(this))}this.canUseIdleCallback&&(null===(o=this.config.performanceConfig)||void 0===o?void 0:o.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.pendingQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))},e.prototype.processQueue=function(e){var t,n=this;for(this.pendingQueue.length>0&&(t=this.taskQueue).push.apply(t,d([],u(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1));this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){var r=this.taskQueue.shift();if(r){var i=r.event,o=r.sessionId;this.addCompressedEvent(i,o)}}this.taskQueue.length>0||this.pendingQueue.length>0?requestIdleCallback(function(e){n.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1},e.prototype.mergeMutationTasks=function(e){var t,n,r;if(!1===(null===(r=this.config.performanceConfig)||void 0===r?void 0:r.mergeMutations))return e;if(e.length<=1)return e;for(var i=[],o=0;o<e.length;){for(var s=e[o].sessionId,a=o+1;a<e.length&&e[a].sessionId===s;)a++;var l=at(e.slice(o,a).map(function(e){return e.event}));try{for(var u=(t=void 0,c(l)),d=u.next();!d.done;d=u.next()){var h=d.value;i.push({event:h,sessionId:s})}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}o=a}return i},e}(),ct="Session replay event batch rejected due to exceeded retry count",ut="Failed to store session replay events in IndexedDB",dt="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",ht="1.51.4";function vt(e,t){return a(this,void 0,void 0,function(){var n,r,i,o,s,u,d,h,v,g,f,p,m,y,b=this;return l(this,function(S){switch(S.label){case 0:return S.trys.push([0,4,,5]),n=t.CompressionStream,r=new n("gzip"),i=r.writable.getWriter(),o=r.readable.getReader(),s=[],u=a(b,void 0,void 0,function(){var e,t,n;return l(this,function(r){switch(r.label){case 0:return[4,o.read()];case 1:if(e=r.sent(),t=e.done,n=e.value,t)return[3,3];s.push(n),r.label=2;case 2:return[3,0];case 3:return[2]}})}),[4,i.write((new TextEncoder).encode(e))];case 1:return S.sent(),[4,i.close()];case 2:return S.sent(),[4,u];case 3:S.sent(),d=s.reduce(function(e,t){return e+t.length},0),h=new Uint8Array(d),v=0;try{for(g=c(s),f=g.next();!f.done;f=g.next())p=f.value,h.set(p,v),v+=p.length}catch(e){m={error:e}}finally{try{f&&!f.done&&(y=g.return)&&y.call(g)}finally{if(m)throw m.error}}return[2,h];case 4:return S.sent(),[2,null];case 5:return[2]}})})}var gt=function(){function e(e){var t=e.trackServerUrl,n=e.loggerProvider,r=e.payloadBatcher,i=e.workerScript,o=e.enableTransportCompression,s=e.sendTimeoutMs,a=e.handleSendEvents,l=this;if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.timedOutWorkerRequests=new Map,this.flushPauseUntilMs=0,this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,this.mergeLogFiredThisPause=!1,this.killedSessions=new Set,this.loggerProvider=n,this.payloadBatcher=r||function(e){return e},this.trackServerUrl=t,this.enableTransportCompression=null==o||o,this.sendTimeoutMs=null!=s?s:1e4,this.handleSendEvents=a,i)try{var d=new Blob([i],{type:"application/javascript"}),h=URL.createObjectURL(d),v=new Worker(h);v.onerror=function(e){var t,r;e.preventDefault(),n.error("Track destination worker failed, falling back to main-thread sending: ".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")")),v.terminate(),l.worker=void 0;try{for(var i=c(l.pendingWorkerRequests),o=i.next();!o.done;o=i.next()){var s=u(o.value,2)[1];s.timeout&&clearTimeout(s.timeout),n.warn("Session replay event send failed due to worker crash: ".concat(e.message)),s.resolve()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}l.pendingWorkerRequests.clear(),l.timedOutWorkerRequests.clear()},v.onmessage=function(e){var t=e.data;if("log"===t.type)n.log(t.message);else if("warn"===t.type)n.warn(t.message);else if("payload_too_large"===t.type){var r=l.pendingWorkerRequests.get(t.id);if(r)r.timeout&&clearTimeout(r.timeout),l.handlePayloadTooLargeResponse(r.context,t.isWaf),r.resolve(),l.pendingWorkerRequests.delete(t.id);else(i=l.timedOutWorkerRequests.get(t.id))&&(l.timedOutWorkerRequests.delete(t.id),l.handlePayloadTooLargeResponse(i,t.isWaf))}else if("complete"===t.type){var i,o=l.pendingWorkerRequests.get(t.id);if(o)o.timeout&&clearTimeout(o.timeout),void 0!==t.skipCode&&l.applyServerDirective(o.context.sessionId,t.skipCode),l.completeRequest({context:o.context}),o.resolve(),l.pendingWorkerRequests.delete(t.id);else(i=l.timedOutWorkerRequests.get(t.id))&&(l.timedOutWorkerRequests.delete(t.id),void 0!==t.skipCode&&l.applyServerDirective(i.sessionId,t.skipCode),l.completeRequest({context:i}))}else"fetch-request"===t.type&&l.handleDelegatedFetch(v,t).catch(function(e){n.warn("Failed to handle delegated session replay fetch:",e)})},this.worker=v}catch(e){n.error("Failed to create track destination worker, falling back to main-thread sending:",e)}}return e.prototype.sendEventsList=function(e){this.addToQueue(o(o({},e),{attempts:0,timeout:0}))},e.prototype.markCoalesceNextFlush=function(){this.coalesceNextFlush=!0,this.schedule(0)},e.prototype.sendBeacon=function(e){var t,n,r=this,i=e.events,o=e.sessionId,s=e.deviceId,a=e.apiKey,l=e.serverZone,c=function(e){return et(e)},u=i,d=JSON.stringify({version:2,events:u});if(c(d)>65536){for(var h=0,v=u.length;h<v;){var g=Math.floor((h+v+1)/2);c(JSON.stringify({version:2,events:u.slice(0,g)}))<=65536?h=g:v=g-1}u=u.slice(0,h),d=JSON.stringify({version:2,events:u}),this.loggerProvider.warn("sendBeacon payload exceeded 64 KB limit, trimmed from ".concat(i.length," to ").concat(u.length," events"))}if(0!==u.length)if(this.handleSendEvents){var p=new URLSearchParams({device_id:s,session_id:String(o),type:"replay"}),m="".concat(De(l,this.trackServerUrl),"?").concat(p.toString()),y={"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(a)};this.loggerProvider.debug("Routing session replay exit batch (".concat(u.length," events) through custom transport for session id ").concat(o,"."));try{this.handleSendEvents({url:m,method:"POST",headers:y,body:d,keepalive:!0}).catch(function(e){r.loggerProvider.warn("Custom transport failed to send session replay exit batch:",e)})}catch(e){this.loggerProvider.warn("Custom transport threw while sending session replay exit batch:",e)}}else{var b=new URLSearchParams({device_id:s,session_id:String(o),type:"replay",api_key:a}),S="".concat(De(l,this.trackServerUrl),"?").concat(b.toString()),I=f();try{var w=new Blob([d],{type:"application/json"});!1===(null===(n=null===(t=null==I?void 0:I.navigator)||void 0===t?void 0:t.sendBeacon)||void 0===n?void 0:n.call(t,S,w))&&this.loggerProvider.warn("sendBeacon failed to queue session replay payload")}catch(e){}}},e.prototype.addToQueue=function(){for(var e=this,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];t.filter(function(t){return e.killedSessions.has(t.sessionId)?(e.completeRequest({context:t,err:dt}),!1):t.attempts<(t.flushMaxRetries||0)?(t.attempts+=1,!0):(e.completeRequest({context:t,err:ct}),!1)}).forEach(function(t){e.queue=e.queue.concat(t),e.schedule(0)})},e.prototype.schedule=function(e){var t=this;if(!this.scheduled){var n=this.flushPauseUntilMs-Date.now(),r=n>e?n:e;n>0&&(this.mergeOnNextFlush=!0),this.scheduled=setTimeout(function(){t.flush(!0).then(function(){t.queue.length>0&&t.schedule(e)})},r)}},e.prototype.flush=function(e){return void 0===e&&(e=!1),a(this,void 0,void 0,function(){var t,n,r,i,o,s,a;return l(this,function(l){switch(l.label){case 0:t=this.queue,this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),this.mergeOnNextFlush?(this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,t=this.mergeQueueAfterThrottle(t)):this.coalesceNextFlush&&(this.coalesceNextFlush=!1,t=this.mergeDrainBacklog(t)),l.label=1;case 1:l.trys.push([1,6,7,8]),n=c(t),r=n.next(),l.label=2;case 2:return r.done?[3,5]:(i=r.value,[4,this.send(i,e)]);case 3:l.sent(),l.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=l.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(a=n.return)&&a.call(n)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},e.prototype.mergeQueueAfterThrottle=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&!this.mergeLogFiredThisPause&&(this.mergeLogFiredThisPause=!0,this.loggerProvider.log("Session replay throttle pause ended; merged ".concat(e.length," queued batches into ").concat(t.length," request(s)"))),t},e.prototype.mergeDrainBacklog=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&this.loggerProvider.log("Session replay coalesced ".concat(e.length," persisted page-load backlog batches into ").concat(t.length," request(s)")),t},e.prototype.coalesceByIdentity=function(e){var t,n,r,i,s,h,v,g,f,p,m,y=this;if(e.length<=1)return e;var b=new Map;try{for(var S=c(e),I=S.next();!I.done;I=S.next()){var w=I.value,C=[w.sessionId,null!==(s=w.deviceId)&&void 0!==s?s:"",null!==(h=w.apiKey)&&void 0!==h?h:"",w.type,null!==(v=w.serverZone)&&void 0!==v?v:"",w.sampleRate,null!==(f=null===(g=w.version)||void 0===g?void 0:g.type)&&void 0!==f?f:"",null!==(m=null===(p=w.version)||void 0===p?void 0:p.version)&&void 0!==m?m:""].join("|"),E=b.get(C);E?E.push(w):b.set(C,[w])}}catch(e){t={error:e}}finally{try{I&&!I.done&&(n=S.return)&&n.call(S)}finally{if(t)throw t.error}}var P=[],k=function(e){var t,n;if(1===e.length)return P.push(e[0]),"continue";var r=null,i=0,s=function(){r&&P.push(r),r=null,i=0},h=function(e){var t=tt(e.events);if(null===r)return r=o(o({},e),{events:d([],u(e.events),!1),attempts:0}),i=t,"continue";if(i+t>4e6)return s(),r=o(o({},e),{events:d([],u(e.events),!1),attempts:0}),i=t,"continue";var n=r.onComplete,c=e.onComplete;r.events=r.events.concat(e.events),i+=t,r.onComplete=function(){return a(y,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,Promise.allSettled([n(),c()])];case 1:return e.sent(),[2]}})})}};try{for(var v=(t=void 0,c(e)),g=v.next();!g.done;g=v.next()){h(g.value)}}catch(e){t={error:e}}finally{try{g&&!g.done&&(n=v.return)&&n.call(v)}finally{if(t)throw t.error}}s()};try{for(var x=c(b.values()),M=x.next();!M.done;M=x.next()){k(M.value)}}catch(e){r={error:e}}finally{try{M&&!M.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}return P},e.prototype.send=function(e,t){return void 0===t&&(t=!0),a(this,void 0,void 0,function(){var n,r,i,o;return l(this,function(s){return this.killedSessions.has(e.sessionId)?[2,this.completeRequest({context:e,err:dt})]:(n=e.apiKey)?(r=e.deviceId)?0===(i=this.payloadBatcher({version:1,events:e.events})).events.length?(this.completeRequest({context:e}),[2]):(o=this.worker)?[2,this.sendViaWorker(o,e,i,t)]:[2,this.sendOnMainThread(n,r,e,i,t)]:[2,this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"})]:[2,this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"})]})})},e.prototype.sendViaWorker=function(e,t,n,r){return a(this,void 0,void 0,function(){var i,o=this;return l(this,function(s){return i="".concat(++this.sendIdCounter),[2,new Promise(function(s){var a,l=o.sendTimeoutMs>0?setTimeout(function(){var e=o.pendingWorkerRequests.get(i);e&&(o.pendingWorkerRequests.delete(i),o.rememberTimedOutRequest(i,e.context),o.loggerProvider.warn("Session replay worker send timed out after ".concat(o.sendTimeoutMs,"ms; leaving events for retry")),e.resolve())},o.sendTimeoutMs):void 0;o.pendingWorkerRequests.set(i,{context:t,resolve:s,timeout:l}),e.postMessage({type:"send",id:i,payload:n,useRetry:r,useCustomTransport:!!o.handleSendEvents,context:{apiKey:t.apiKey,deviceId:t.deviceId,sessionId:t.sessionId,events:t.events,eventType:t.type,flushMaxRetries:null!==(a=t.flushMaxRetries)&&void 0!==a?a:0,sampleRate:t.sampleRate,serverZone:t.serverZone,trackServerUrl:o.trackServerUrl,version:t.version,currentUrl:qe(),sdkVersion:ht,enableTransportCompression:o.enableTransportCompression,sendTimeoutMs:o.sendTimeoutMs}})})]})})},e.prototype.rememberTimedOutRequest=function(e,t){var n,r;if(this.timedOutWorkerRequests.set(e,t),this.timedOutWorkerRequests.size>256)try{for(var i=c(this.timedOutWorkerRequests.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;this.timedOutWorkerRequests.delete(s);break}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}},e.prototype.handleDelegatedFetch=function(e,t){var n,r,i;return a(this,void 0,void 0,function(){var o,s,a,c,u,d,h,v,g,f,p;return l(this,function(l){switch(l.label){case 0:o=t.requestId,s=t.url,a=t.method,c=t.headers,u=t.body,d=t.keepalive,l.label=1;case 1:return l.trys.push([1,10,,11]),h=void 0,this.handleSendEvents?[4,this.handleSendEvents({url:s,method:a,headers:c,body:u,keepalive:d})]:[3,3];case 2:return h=l.sent(),[3,5];case 3:return this.loggerProvider.warn("Delegated session replay fetch received without a custom transport configured; falling back to built-in fetch."),[4,fetch(s,{method:a,headers:c,body:u,keepalive:d})];case 4:h=l.sent(),l.label=5;case 5:if(v=h.status,g=null,f="",v>=200&&v<300&&(g=null!==(i=null===(r=null===(n=h.headers)||void 0===n?void 0:n.get)||void 0===r?void 0:r.call(n,we))&&void 0!==i?i:null),413!==v)return[3,9];l.label=6;case 6:return l.trys.push([6,8,,9]),[4,h.text()];case 7:return f=l.sent(),[3,9];case 8:return l.sent(),[3,9];case 9:return this.loggerProvider.debug("Delegated session replay fetch (request ".concat(o,") returned status ").concat(v,".")),e.postMessage({type:"fetch-response",requestId:o,status:v,skipHeader:g,body:f}),[3,11];case 10:return p=l.sent(),this.loggerProvider.debug("Delegated session replay fetch (request ".concat(o,") failed:"),p),e.postMessage({type:"fetch-response",requestId:o,status:0,skipHeader:null,body:String(p),error:!0}),[3,11];case 11:return[2]}})})},e.prototype.sendOnMainThread=function(e,t,n,r,i){var s,c,u,d,h,v,g;return a(this,void 0,void 0,function(){var a,p,m,y,b,S,I,w,C,E,P,k,x,M,T,O,R,_,L,F,D,q;return l(this,function(l){switch(l.label){case 0:a=qe(),p=ht,m=n.sampleRate,y=new URLSearchParams({device_id:t,session_id:"".concat(n.sessionId),type:"".concat(n.type)}),b="".concat(null!==(c=null===(s=n.version)||void 0===s?void 0:s.type)&&void 0!==c?c:"standalone","/").concat(null!==(d=null===(u=n.version)||void 0===u?void 0:u.version)&&void 0!==d?d:p),l.label=1;case 1:return l.trys.push([1,19,,23]),S=JSON.stringify(r),I=f(),this.enableTransportCompression&&I&&"CompressionStream"in I?[4,vt(S,I)]:[3,3];case 2:return C=l.sent(),[3,4];case 3:C=null,l.label=4;case 4:if(E=(w=C)?w.byteLength:et(S),P=new AbortController,k=o({"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(e),"X-Client-Version":p,"X-Client-Library":b,"X-Client-Url":a.substring(0,1e3),"X-Client-Sample-Rate":"".concat(m),"X-Sampling-Hash-Alg":"xxhash32"},w?{"Content-Encoding":"gzip"}:{}),T={headers:k,body:x=null!=w?w:S,method:"POST",keepalive:M=E<=65536,signal:P.signal},O="".concat(De(n.serverZone,this.trackServerUrl),"?").concat(y.toString()),0===r.events.length)return this.completeRequest({context:n}),[2];R=this.sendTimeoutMs>0?setTimeout(function(){P.abort()},this.sendTimeoutMs):void 0,_=void 0,l.label=5;case 5:return l.trys.push([5,,10,11]),this.handleSendEvents?[4,(A=this.handleSendEvents({url:O,method:"POST",headers:k,body:x,keepalive:M}),j=P.signal,new Promise(function(e,t){var n=function(){var e=new Error("Custom session replay transport aborted by send timeout");e.name="AbortError",t(e)};j.addEventListener("abort",n,{once:!0}),A.then(function(t){j.removeEventListener("abort",n),e(t)},function(e){j.removeEventListener("abort",n),t(e)})}))]:[3,7];case 6:return L=l.sent(),[3,9];case 7:return[4,fetch(O,T)];case 8:L=l.sent(),l.label=9;case 9:return _=L,[3,11];case 10:return R&&clearTimeout(R),[7];case 11:if(null===_)return this.completeRequest({context:n,err:"Unexpected error occurred"}),[2];if(_.status>=200&&_.status<300&&(F=null!==(g=null===(v=null===(h=_.headers)||void 0===h?void 0:h.get)||void 0===v?void 0:v.call(h,we))&&void 0!==g?g:null,this.applyServerDirective(n.sessionId,F)),i)return[3,12];D="";try{D=JSON.stringify(_.body,null,2)}catch(e){}return this.completeRequest({context:n,success:"".concat(_.status,": ").concat(D)}),[3,18];case 12:if(D="",413!==_.status)return[3,16];l.label=13;case 13:return l.trys.push([13,15,,16]),[4,_.text()];case 14:return D=l.sent(),[3,16];case 15:return l.sent(),[3,16];case 16:return[4,this.handleReponse(_.status,n,D)];case 17:l.sent(),l.label=18;case 18:return[3,23];case 19:return q=l.sent(),!!q&&"object"==typeof q&&"AbortError"===q.name&&i?[4,this.handleOtherResponse(n)]:[3,21];case 20:return l.sent(),[3,22];case 21:this.completeRequest({context:n,err:q}),l.label=22;case 22:return[3,23];case 23:return[2]}var A,j})})},e.prototype.handleReponse=function(e,t,n){return void 0===n&&(n=""),a(this,void 0,void 0,function(){var r;return l(this,function(i){switch(i.label){case 0:switch(r=(new z).buildStatus(e),r){case h.Success:return[3,1];case h.Failed:case h.Timeout:case h.RateLimit:return[3,2];case h.PayloadTooLarge:return[3,4]}return[3,5];case 1:return this.handleSuccessResponse(t),[3,8];case 2:return[4,this.handleOtherResponse(t)];case 3:return i.sent(),[3,8];case 4:return this.handlePayloadTooLargeResponse(t,ye.test(n)),[3,8];case 5:return 499!==e?[3,7]:[4,this.handleOtherResponse(t)];case 6:return i.sent(),[3,8];case 7:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"}),i.label=8;case 8:return[2]}})})},e.prototype.handlePayloadTooLargeResponse=function(e,t){var n=t?"WAF (compressed payload too large)":"server (event too large)",r=Math.round(e.events.reduce(function(e,t){return e+t.length},0)/Ie);if(t)if(1!==e.events.length){this.loggerProvider.warn("Session replay event batch rejected by ".concat(n," (").concat(e.events.length," events, ").concat(r," KB total) — splitting and retrying")),e.onComplete();var i=function(){return Promise.resolve()},s=Math.floor(e.events.length/2);this.sendEventsList(o(o({},e),{events:e.events.slice(0,s),onComplete:i})),this.sendEventsList(o(o({},e),{events:e.events.slice(s),onComplete:i}))}else this.completeRequest({context:e,err:"Session replay event dropped: single event (".concat(r," KB, 1 event) rejected by ").concat(n," — cannot split further")});else this.completeRequest({context:e,err:"Session replay event batch dropped: ".concat(n," rejected payload (").concat(e.events.length," events, ").concat(r," KB) — not retrying non-WAF 413")})},e.prototype.handleSuccessResponse=function(e){var t=Math.round(tt(e.events)/Ie);this.completeRequest({context:e,success:"Session replay event batch tracked successfully for session id ".concat(e.sessionId,", size of events: ").concat(t," KB")})},e.prototype.handleOtherResponse=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=Math.random()*e.attempts*this.retryTimeout,e.attempts++,e.attempts>(e.flushMaxRetries||0)?(this.completeRequest({context:e,err:ct}),[2]):[4,new Promise(function(e){return setTimeout(e,t)})];case 1:return n.sent(),[4,this.send(e,!0)];case 2:return n.sent(),[2]}})})},e.prototype.completeRequest=function(e){var t=e.context,n=e.err,r=e.success;t.onComplete(),n?this.loggerProvider.warn(n):r&&this.loggerProvider.log(r)},e.prototype.applyServerDirective=function(e,t){if(null===t)return this.flushPauseUntilMs=0,void(this.mergeLogFiredThisPause=!1);if("429"===t){var n=this.flushPauseUntilMs>Date.now();return this.flushPauseUntilMs=Date.now()+6e4,void(n||this.loggerProvider.log("Session replay throttled by server; pausing flush schedule for ".concat(60,"s")))}"4005"!==t&&"4004"!==t||this.killSession(e,t)},e.prototype.killSession=function(e,t){var n,r,i,o;if(!this.killedSessions.has(e)){if(this.killedSessions.add(e),this.killedSessions.size>256)try{for(var s=c(this.killedSessions),a=s.next();!a.done;a=s.next()){var l=a.value;this.killedSessions.delete(l);break}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}this.loggerProvider.log("Session replay capture stopped for session ".concat(e," by server directive ").concat(t,"; remaining events will be dropped"));var u=[];try{for(var d=c(this.queue),h=d.next();!h.done;h=d.next()){var v=h.value;v.sessionId===e?this.completeRequest({context:v,err:dt}):u.push(v)}}catch(e){i={error:e}}finally{try{h&&!h.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}this.queue=u}},e}();const ft=(e,t)=>t.some(t=>e instanceof t);let pt,mt;const yt=new WeakMap,bt=new WeakMap,St=new WeakMap;let It={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return yt.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Pt(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wt(e){It=e(It)}function Ct(e){return(mt||(mt=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(kt(this),t),Pt(this.request)}:function(...t){return Pt(e.apply(kt(this),t))}}function Et(e){return"function"==typeof e?Ct(e):(e instanceof IDBTransaction&&function(e){if(yt.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),r()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});yt.set(e,t)}(e),ft(e,pt||(pt=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,It):e)}function Pt(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(Pt(e.result)),r()},o=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",o)});return St.set(t,e),t}(e);if(bt.has(e))return bt.get(e);const t=Et(e);return t!==e&&(bt.set(e,t),St.set(t,e)),t}const kt=e=>St.get(e);function xt(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=Pt(s);return r&&s.addEventListener("upgradeneeded",e=>{r(Pt(s.result),e.oldVersion,e.newVersion,Pt(s.transaction),e)}),n&&s.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}const Mt=["get","getKey","getAll","getAllKeys","count"],Tt=["put","add","delete","clear"],Ot=new Map;function Rt(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Ot.get(t))return Ot.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=Tt.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!Mt.includes(n))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return r&&(s=s.index(t.shift())),(await Promise.all([s[n](...t),i&&o.done]))[0]};return Ot.set(t,o),o}wt(e=>({...e,get:(t,n,r)=>Rt(t,n)||e.get(t,n,r),has:(t,n)=>!!Rt(t,n)||e.has(t,n)}));const _t=["continue","continuePrimaryKey","advance"],Lt={},Ft=new WeakMap,Dt=new WeakMap,qt={get(e,t){if(!_t.includes(t))return e[t];let n=Lt[t];return n||(n=Lt[t]=function(...e){Ft.set(this,Dt.get(this)[t](...e))}),n}};async function*At(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,qt);for(Dt.set(n,t),St.set(n,kt(t));t;)yield n,t=await(Ft.get(n)||t.continue()),Ft.delete(n)}function jt(e,t){return t===Symbol.asyncIterator&&ft(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&ft(e,[IDBIndex,IDBObjectStore])}wt(e=>({...e,get:(t,n,r)=>jt(t,n)?At:e.get(t,n,r),has:(t,n)=>jt(t,n)||e.has(t,n)}));var Bt=function(){function e(e){var t,n,r,i=this;this.minInterval=be,this.maxInterval=Se,this.maxPersistedEventsSize=6e6,this._timeAtLastSplit=Date.now(),this.eventsContentBytes=new WeakMap,this.sequenceContentBytes=new Map,this.shouldSplitEventsList=function(e,t){var n=i.getEventsArraySize(e),r=i.maxPersistedEventsSize-n,o=t.length>=r;return!o&&3*t.length>=r&&(o=et(t)>=r),!!o||!!(Date.now()-i.timeAtLastSplit>i.interval&&e.length)&&(i.interval=Math.min(i.maxInterval,i.interval+i.minInterval),i._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!==(r=e.maxPersistedEventsSize)&&void 0!==r?r:this.maxPersistedEventsSize,this.interval=this.minInterval}return Object.defineProperty(e.prototype,"timeAtLastSplit",{get:function(){return this._timeAtLastSplit},enumerable:!1,configurable:!0}),e.prototype.isPrefixOf=function(e,t){return!(t.length<e.length)&&(0===e.length||t[e.length-1]===e.tail)},e.prototype.measureContentBytes=function(e,t){if(e&&e.length===t.length&&this.isPrefixOf(e,t))return e;var n=0,r=0;e&&this.isPrefixOf(e,t)&&(n=e.contentBytes,r=e.length);for(var i=r;i<t.length;i++)n+=et(t[i]);return{length:t.length,contentBytes:n,tail:t.length>0?t[t.length-1]:void 0}},e.prototype.getEventsContentBytes=function(e){var t=this.measureContentBytes(this.eventsContentBytes.get(e),e);return this.eventsContentBytes.set(e,t),t.contentBytes},e.prototype.getEventsArraySize=function(e){return this.getEventsContentBytes(e)+(2+Math.max(0,e.length-1)+2*e.length)},e.prototype.recallSequenceContentBytes=function(e,t){var n=this.sequenceContentBytes.get(e);n&&n.length===t.length&&this.isPrefixOf(n,t)&&this.eventsContentBytes.set(t,n)},e.prototype.rememberSequenceContentBytes=function(e,t){var n=this.measureContentBytes(this.sequenceContentBytes.get(e),t);this.sequenceContentBytes.set(e,n),this.eventsContentBytes.set(t,n)},e.prototype.forgetSequenceContentBytes=function(e){this.sequenceContentBytes.delete(e)},e}(),Nt=function(e,t,n){var r;"object"==typeof(r=n)&&null!==r&&"AbortError"===r.name?e.debug(t):e.warn(t)};var Ut="sessionCurrentSequence",Wt="sequencesToSend",zt=5e3;function Kt(e,t,n){var r=setTimeout(n,t);return e.then(function(){return clearTimeout(r)},function(){return clearTimeout(r)}),function(){return clearTimeout(r)}}var Ht,Gt,Qt,Jt=function(e){var t,n;return e.objectStoreNames.contains(Ut)||(n=e.createObjectStore(Ut,{keyPath:"sessionId"})),e.objectStoreNames.contains(Wt)||(t=e.createObjectStore(Wt,{keyPath:"sequenceId",autoIncrement:!0})).createIndex("sessionId","sessionId"),{sequencesStore:t,currentSequenceStore:n}},$t=function(e){return a(void 0,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,(n=xt(e,1,{upgrade:Jt}),r=2e3,i="IDB openDB timed out",void 0===i&&(i="IDB operation timed out"),new Promise(function(e,t){var o=setTimeout(function(){return t(new Error("".concat(i," after ").concat(r,"ms")))},r);n.then(function(t){clearTimeout(o),e(t)},function(e){clearTimeout(o),t(e)})}))];case 1:return[2,t.sent()]}var n,r,i})})},Zt=function(e){function t(t){var n,r=this;return(r=e.call(this,t)||this).consecutiveFailures=0,r.hasTriggeredFallback=!1,r.emptyFilteredCount=0,r.getSequencesToSend=function(){return a(r,void 0,void 0,function(){var e,t,n,r,i,o,s,a,c,u,d=this;return l(this,function(l){switch(l.label){case 0:e=!1,t=!1,l.label=1;case 1:return l.trys.push([1,9,,10]),n=[],(r=this.db.transaction("sequencesToSend","readwrite")).done.catch(function(n){e||t||(Nt(d.loggerProvider,"".concat(ut,": ").concat(n),n),d.recordFailure())}),i=Kt(r.done,zt,function(){e||t||(t=!0,Nt(d.loggerProvider,"".concat(ut,": transaction timed out")),d.recordFailure())}),[4,r.store.openCursor()];case 2:o=l.sent(),l.label=3;case 3:return o?(s=o.value,a=s.sessionId,0!==(c=s.events).length?[3,5]:(this.maybeLogEmptyFiltered("getSequencesToSend"),[4,o.delete()])):[3,8];case 4:return l.sent(),[3,6];case 5:n.push({events:c,sequenceId:o.key,sessionId:a}),l.label=6;case 6:return[4,o.continue()];case 7:return o=l.sent(),[3,3];case 8:return this.recordSuccess(),i(),[2,n];case 9:return u=l.sent(),t||(e=!0,Nt(this.loggerProvider,"".concat(ut,": ").concat(u),u),this.recordFailure()),[3,10];case 10:return[2,void 0]}})})},r.storeCurrentSequence=function(e){return a(r,void 0,void 0,function(){var t,n,r,i,a,c,u,d,h=this;return l(this,function(l){switch(l.label){case 0:t=!1,n=!1,l.label=1;case 1:return l.trys.push([1,5,,6]),(r=this.db.transaction([Ut,Wt],"readwrite")).done.catch(function(e){t||n||(Nt(h.loggerProvider,"".concat(ut,": ").concat(e),e),h.recordFailure())}),i=Kt(r.done,zt,function(){t||n||(n=!0,Nt(h.loggerProvider,"".concat(ut,": transaction timed out")),h.recordFailure())}),[4,r.objectStore(Ut).get(e)];case 2:return!(a=l.sent())||a.tabId&&a.tabId!==this.tabId?(i(),[2,void 0]):0===a.events.length?(this.maybeLogEmptyFiltered("storeCurrentSequence"),i(),[2,void 0]):[4,r.objectStore(Wt).put({sessionId:e,events:a.events,tabId:this.tabId})];case 3:return c=l.sent(),[4,r.objectStore(Ut).put({sessionId:e,events:[],tabId:this.tabId})];case 4:return l.sent(),this.rememberSequenceContentBytes(e,[]),this.recordSuccess(),i(),a.tabId,u=s(a,["tabId"]),[2,o(o({},u),{sessionId:e,sequenceId:c})];case 5:return d=l.sent(),this.forgetSequenceContentBytes(e),n||(t=!0,Nt(this.loggerProvider,"".concat(ut,": ").concat(d),d),this.recordFailure()),[3,6];case 6:return[2,void 0]}})})},r.addEventToCurrentSequence=function(e,t){return a(r,void 0,void 0,function(){var n,r,i,o,s,a,c,u,d,h,v,g,f,p,m=this;return l(this,function(l){switch(l.label){case 0:n=!1,r=!1,l.label=1;case 1:return l.trys.push([1,15,,16]),(i=this.db.transaction([Ut,Wt],"readwrite")).done.catch(function(e){n||r||(Nt(m.loggerProvider,"".concat(ut,": ").concat(e),e),m.recordFailure())}),o=Kt(i.done,zt,function(){n||r||(r=!0,Nt(m.loggerProvider,"".concat(ut,": transaction timed out")),m.recordFailure())}),[4,i.objectStore(Ut).get(e)];case 2:return(null==(s=l.sent())?void 0:s.tabId)&&s.tabId!==this.tabId?s.events.length>0?[4,i.objectStore(Wt).put({sessionId:e,events:s.events,tabId:s.tabId})]:[3,4]:[3,6];case 3:l.sent(),l.label=4;case 4:return a=[t],[4,i.objectStore(Ut).put({sessionId:e,events:a,tabId:this.tabId})];case 5:return l.sent(),this.rememberSequenceContentBytes(e,a),this.recordSuccess(),o(),[2,void 0];case 6:return(c=s)?[3,8]:(u=[t],[4,i.objectStore(Ut).put({sessionId:e,events:u,tabId:this.tabId})]);case 7:return l.sent(),this.rememberSequenceContentBytes(e,u),this.recordSuccess(),o(),[2,void 0];case 8:return this.recallSequenceContentBytes(e,c.events),this.shouldSplitEventsList(c.events,t)?[3,10]:(d=c.events.concat(t),[4,i.objectStore(Ut).put({sessionId:e,events:d,tabId:this.tabId})]);case 9:return l.sent(),this.rememberSequenceContentBytes(e,d),this.recordSuccess(),o(),[2,void 0];case 10:return 0!==(h=c.events).length?[3,12]:(this.maybeLogEmptyFiltered("addEventToCurrentSequence"),v=[t],[4,i.objectStore(Ut).put({sessionId:e,events:v,tabId:this.tabId})]);case 11:return l.sent(),this.rememberSequenceContentBytes(e,v),this.recordSuccess(),o(),[2,void 0];case 12:return g=[t],[4,i.objectStore(Ut).put({sessionId:e,events:g,tabId:this.tabId})];case 13:return l.sent(),this.rememberSequenceContentBytes(e,g),[4,i.objectStore(Wt).put({sessionId:e,events:h,tabId:this.tabId})];case 14:return f=l.sent(),this.recordSuccess(),o(),[2,{events:h,sessionId:e,sequenceId:f}];case 15:return p=l.sent(),this.forgetSequenceContentBytes(e),r||(n=!0,Nt(this.loggerProvider,"".concat(ut,": ").concat(p),p),this.recordFailure()),[3,16];case 16:return[2,void 0]}})})},r.storeSendingEvents=function(e,t){return a(r,void 0,void 0,function(){var n,r;return l(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.db.put(Wt,{sessionId:e,events:t,tabId:this.tabId})];case 1:return n=i.sent(),this.recordSuccess(),[2,n];case 2:return r=i.sent(),Nt(this.loggerProvider,"".concat(ut,": ").concat(r),r),this.recordFailure(),[3,3];case 3:return[2,void 0]}})})},r.cleanUpSessionEventsStore=function(e,t){return a(r,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:if(!t)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.db.delete(Wt,t)];case 2:return n.sent(),this.recordSuccess(),[3,4];case 3:return e=n.sent(),Nt(this.loggerProvider,"".concat(ut,": ").concat(e),e),this.recordFailure(),[3,4];case 4:return[2]}})})},r.db=t.db,r.tabId=t.tabId,r.onPersistentFailure=t.onPersistentFailure,r.consecutiveFailureThreshold=null!==(n=t.consecutiveFailureThreshold)&&void 0!==n?n:1,r}return n(t,e),t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug("Filtered empty session replay sequence at ".concat(e," (idb store)"))},t.prototype.recordFailure=function(){var e;this.consecutiveFailures++,!this.hasTriggeredFallback&&this.consecutiveFailures>=this.consecutiveFailureThreshold&&(this.hasTriggeredFallback=!0,null===(e=this.onPersistentFailure)||void 0===e||e.call(this))},t.prototype.recordSuccess=function(){this.consecutiveFailures=0},t.new=function(e,n){var r;return a(this,void 0,void 0,function(){var i,s,a,c,u;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,2,,3]),i="replay"===e?"":"_".concat(e),s="".concat(n.apiKey.substring(0,10),"_amp_session_replay_events").concat(i),[4,$t(s)];case 1:return a=l.sent(),c=null!==(r=n.tabId)&&void 0!==r?r:function(){try{return crypto.randomUUID()}catch(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}(),[2,new t(o(o({},n),{db:a,tabId:c}))];case 2:return u=l.sent(),Nt(n.loggerProvider,"".concat(ut,": ").concat(u),u),[3,3];case 3:return[2]}})})},t.prototype.getCurrentSequenceEvents=function(e){return a(this,void 0,void 0,function(){var t,n,r,i,o,a,u,d;return l(this,function(l){switch(l.label){case 0:return e?[4,this.db.get("sessionCurrentSequence",e)]:[3,2];case 1:return(i=l.sent())?i.tabId&&i.tabId!==this.tabId?[2,void 0]:(i.tabId,[2,[o=s(i,["tabId"])]]):[2,void 0];case 2:t=[],l.label=3;case 3:return l.trys.push([3,8,9,10]),[4,this.db.getAll("sessionCurrentSequence")];case 4:n=c.apply(void 0,[l.sent()]),r=n.next(),l.label=5;case 5:if(r.done)return[3,7];if((i=r.value).tabId&&i.tabId!==this.tabId)return[3,6];i.tabId,o=s(i,["tabId"]),t.push(o),l.label=6;case 6:return r=n.next(),[3,5];case 7:return[3,10];case 8:return a=l.sent(),u={error:a},[3,10];case 9:try{r&&!r.done&&(d=n.return)&&d.call(n)}finally{if(u)throw u.error}return[7];case 10:return[2,t]}})})},t}(Bt),Vt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.finalizedSequences={},t.sequences={},t.sequenceId=0,t.emptyFilteredCount=0,t}return n(t,e),t.prototype.resetCurrentSequence=function(e){this.sequences[e]=[]},t.prototype.addSequence=function(e){var t=this.sequenceId++,n=d([],u(this.sequences[e]),!1);return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}},t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug("Filtered empty session replay sequence at ".concat(e," (in-memory store)"))},t.prototype.getSequencesToSend=function(){return a(this,void 0,void 0,function(){var e,t,n,r,i,o,s,a,d,h;return l(this,function(l){e=[];try{for(t=c(Object.entries(this.finalizedSequences)),n=t.next();!n.done;n=t.next())r=u(n.value,2),i=r[0],o=r[1],s=o.sessionId,0!==(a=o.events).length?e.push({sequenceId:Number(i),sessionId:s,events:a}):(this.maybeLogEmptyFiltered("getSequencesToSend"),delete this.finalizedSequences[Number(i)])}catch(e){d={error:e}}finally{try{n&&!n.done&&(h=t.return)&&h.call(t)}finally{if(d)throw d.error}}return[2,e]})})},t.prototype.storeCurrentSequence=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){return(t=this.sequences[e])?0===t.length?(this.maybeLogEmptyFiltered("storeCurrentSequence"),[2,void 0]):[2,this.addSequence(e)]:[2,void 0]})})},t.prototype.addEventToCurrentSequence=function(e,t){return a(this,void 0,void 0,function(){var n;return l(this,function(r){return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(0===this.sequences[e].length?this.maybeLogEmptyFiltered("addEventToCurrentSequence"):n=this.addSequence(e)),this.sequences[e].push(t),[2,n]})})},t.prototype.storeSendingEvents=function(e,t){return a(this,void 0,void 0,function(){return l(this,function(n){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},[2,this.sequenceId++]})})},t.prototype.cleanUpSessionEventsStore=function(e,t){return a(this,void 0,void 0,function(){return l(this,function(e){return void 0!==t&&delete this.finalizedSequences[t],[2]})})},t}(Bt),Xt=function(e){var t=e.config,n=e.minInterval,r=e.maxInterval,i=e.maxPersistedEventsSize,s=e.type,c=e.payloadBatcher,h=e.storeType,v=e.trackDestinationWorkerScript,g=e.shouldSend;return a(void 0,void 0,void 0,function(){function e(e){return void 0===e&&(e=!1),a(this,void 0,void 0,function(){return l(this,function(t){return[2,p.flush(e)]})})}var f,p,m,y,b,S,I,w,C,E,P,k,x,M,T,O,R;return l(this,function(_){switch(_.label){case 0:return f=null!==(R=t.maxSingleEventSizeBytes)&&void 0!==R?R:me,p=new gt(o(o({},t),{loggerProvider:t.loggerProvider,payloadBatcher:c,workerScript:v})),m=function(){return new Vt({loggerProvider:t.loggerProvider,maxInterval:r,minInterval:n,maxPersistedEventsSize:i})},b=!1,I=function(){return a(void 0,void 0,void 0,function(){var e,n,r;return l(this,function(i){switch(i.label){case 0:return b?(b=!1,t.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store."),y?[4,S.getSequencesToSend()]:[3,2]):[2];case 1:return n=i.sent(),[3,3];case 2:n=void 0,i.label=3;case 3:return e=n,S=m(),e&&y&&(r=y,e.forEach(function(e){x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r})})),[2]}})})},w=function(){return a(void 0,void 0,void 0,function(){var e;return l(this,function(o){switch(o.label){case 0:return[4,Zt.new(s,{loggerProvider:t.loggerProvider,minInterval:n,maxInterval:r,maxPersistedEventsSize:i,apiKey:t.apiKey,onPersistentFailure:function(){I()}})];case 1:return(e=o.sent())?(b=!0,[2,e]):(t.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),[2,m()])}})})},"idb"!==h?[3,2]:[4,w()];case 1:return C=_.sent(),[3,3];case 2:C=m(),_.label=3;case 3:return S=C,E=[],P=0,k=function(e){if(!(e<=P)){var t=Math.min(e-P,E.length);t>0&&(E.splice(0,t),P=e)}},x=function(e){for(var n=e.events,r=e.sessionId,i=e.deviceId,o=e.sequenceId,c=n,u=[],d=0;d<n.length;d++){var h=nt(n[d],f);void 0!==h?(0===u.length&&(c=n.slice(0,d)),u.push(h)):c!==n&&c.push(n[d])}u.length>0&&t.loggerProvider.warn("Dropping ".concat(u.length," oversized event(s) from session replay sequence before send. Sizes: ").concat(u.map(function(e){return"".concat(Math.round(e/1024)," KB")}).join(", "),". If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.")),0!==c.length?(t.debugMode&&je().then(function(e){var n=e.totalStorageSize,r=e.percentOfQuota,i=e.usageDetails;t.loggerProvider.debug("Total storage size: ".concat(n," KB, percentage of quota: ").concat(r,"%, usage details: ").concat(i))}).catch(function(){}),p.sendEventsList({events:c,sessionId:r,flushMaxRetries:t.flushMaxRetries,apiKey:t.apiKey,deviceId:i,sampleRate:t.sampleRate,serverZone:t.serverZone,version:t.version,type:s,onComplete:function(){return a(void 0,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,S.cleanUpSessionEventsStore(r,o)];case 1:return e.sent(),[2]}})})}})):S.cleanUpSessionEventsStore(r,o).catch(function(e){t.loggerProvider.warn("Failed to clean up session replay events store:",e)})},M=function(e){var n=e.sessionId,r=e.deviceId;if(y=r,!g||g()){var i=P+E.length;S.storeCurrentSequence(n).then(function(e){e&&(k(i),x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r}))}).catch(function(e){t.loggerProvider.warn("Failed to get current sequence of session replay events for session:",e)})}},T=function(e){var n=e.deviceId;return a(void 0,void 0,void 0,function(){var e;return l(this,function(r){switch(r.label){case 0:return y=n,[4,S.getSequencesToSend()];case 1:return(null==(e=r.sent())?void 0:e.length)?(t.loggerProvider.log("Draining ".concat(e.length," stored sequence(s) from previous session.")),e.length>1&&p.markCoalesceNextFlush(),e.forEach(function(e){x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}),[2]):[2]}})})},O=function(e){var n=e.event,r=e.sessionId,i=e.deviceId;y=i;var o=!g||g(),s=P+E.length;E.push(n.data),S.addEventToCurrentSequence(r,n.data).then(function(e){if(e){if(!o)return S.cleanUpSessionEventsStore(e.sessionId,e.sequenceId).catch(function(e){t.loggerProvider.warn("Failed to clean up dropped session replay sequence:",e)}),void k(s);k(s),x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})}}).catch(function(e){t.loggerProvider.warn("Failed to add event to session replay capture:",e)})},[2,{sendCurrentSequenceEvents:M,addEvent:O,sendStoredEvents:T,flush:e,getBeaconEvents:function(){return d([],u(E),!1)},dropPendingBeaconEvents:function(){k(P+E.length)},trackDestination:p}]}})})},Yt=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=new Map;e.forEach(function(e){n.set(e.name,e.manager)}),this.managers=n}return e.prototype.sendStoredEvents=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.sendStoredEvents(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e.prototype.addEvent=function(e){var t,n=e.sessionId,r=e.event,i=e.deviceId;null===(t=this.managers.get(r.type))||void 0===t||t.addEvent({sessionId:n,event:r,deviceId:i})},e.prototype.sendCurrentSequenceEvents=function(e){var t=e.sessionId,n=e.deviceId;this.managers.forEach(function(e){e.sendCurrentSequenceEvents({sessionId:t,deviceId:n})})},e.prototype.flush=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.flush(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e}();function en(e,t){if(Qt=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";var n={root:document.body,idName:function(e){return!0},className:function(e){return!0},tagName:function(e){return!0},attr:function(e,t){return!1},seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};Ht=o(o({},n),t),Gt=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Ht.root,n);var r=tn(e,"all",function(){return tn(e,"two",function(){return tn(e,"one",function(){return tn(e,"none")})})});if(r){var i=hn(vn(r,e));return i.length>0&&(r=i[0]),rn(r)}throw new Error("Selector was not found.")}function tn(e,t,n){for(var r=null,i=[],o=e,s=0,a=function(){var e,a,l=(new Date).getTime()-Qt.getTime();if(void 0!==Ht.timeoutMs&&l>Ht.timeoutMs)throw new Error("Timeout: Can't find a unique selector after ".concat(l,"ms"));var h=cn(function(e){var t=e.getAttribute("id");if(t&&Ht.idName(t))return{name:"#"+CSS.escape(t),penalty:0};return null}(o))||cn.apply(void 0,d([],u(function(e){var t=Array.from(e.attributes).filter(function(e){return Ht.attr(e.name,e.value)});return t.map(function(e){return{name:"[".concat(CSS.escape(e.name),'="').concat(CSS.escape(e.value),'"]'),penalty:.5}})}(o)),!1))||cn.apply(void 0,d([],u(function(e){var t=Array.from(e.classList).filter(Ht.className);return t.map(function(e){return{name:"."+CSS.escape(e),penalty:1}})}(o)),!1))||cn(function(e){var t=e.tagName.toLowerCase();if(Ht.tagName(t))return{name:t,penalty:2};return null}(o))||[{name:"*",penalty:3}],v=function(e){var t=e.parentNode;if(!t)return null;var n=t.firstChild;if(!n)return null;var r=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&r++,n!==e);)n=n.nextSibling;return r}(o);if("all"==t)v&&(h=h.concat(h.filter(ln).map(function(e){return an(e,v)})));else if("two"==t)h=h.slice(0,1),v&&(h=h.concat(h.filter(ln).map(function(e){return an(e,v)})));else if("one"==t){var g=u(h=h.slice(0,1),1)[0];v&&ln(g)&&(h=[an(g,v)])}else"none"==t&&(h=[{name:"*",penalty:3}],v&&(h=[an(h[0],v)]));try{for(var f=(e=void 0,c(h)),p=f.next();!p.done;p=f.next()){(g=p.value).level=s}}catch(t){e={error:t}}finally{try{p&&!p.done&&(a=f.return)&&a.call(f)}finally{if(e)throw e.error}}if(i.push(h),i.length>=Ht.seedMinLength&&(r=nn(i,n)))return"break";o=o.parentElement,s++};o;){if("break"===a())break}return r||(r=nn(i,n)),!r&&n?n():r}function nn(e,t){var n,r,i=hn(dn(e));if(i.length>Ht.threshold)return t?t():null;try{for(var o=c(i),s=o.next();!s.done;s=o.next()){var a=s.value;if(sn(a))return a}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null}function rn(e){for(var t=e[0],n=t.name,r=1;r<e.length;r++){var i=e[r].level||0;n=t.level===i-1?"".concat(e[r].name," > ").concat(n):"".concat(e[r].name," ").concat(n),t=e[r]}return n}function on(e){return e.map(function(e){return e.penalty}).reduce(function(e,t){return e+t},0)}function sn(e){var t=rn(e);switch(Gt.querySelectorAll(t).length){case 0:throw new Error("Can't select any node with this selector: ".concat(t));case 1:return!0;default:return!1}}function an(e,t){return{name:e.name+":nth-child(".concat(t,")"),penalty:e.penalty+1}}function ln(e){return"html"!==e.name&&!e.name.startsWith("#")}function cn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.filter(un);return n.length>0?n:null}function un(e){return null!=e}function dn(e,t){var n,r,i,o,s,a;return void 0===t&&(t=[]),l(this,function(l){switch(l.label){case 0:if(!(e.length>0))return[3,9];l.label=1;case 1:l.trys.push([1,6,7,8]),n=c(e[0]),r=n.next(),l.label=2;case 2:return r.done?[3,5]:(i=r.value,[5,c(dn(e.slice(1,e.length),t.concat(i)))]);case 3:l.sent(),l.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=l.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(a=n.return)&&a.call(n)}finally{if(s)throw s.error}return[7];case 8:return[3,11];case 9:return[4,t];case 10:l.sent(),l.label=11;case 11:return[2]}})}function hn(e){return d([],u(e),!1).sort(function(e,t){return on(e)-on(t)})}function vn(e,t,n){var r,i,o;return void 0===n&&(n={counter:0,visited:new Map}),l(this,function(s){switch(s.label){case 0:if(!(e.length>2&&e.length>Ht.optimizedMinLength))return[3,5];r=1,s.label=1;case 1:return r<e.length-1?n.counter>Ht.maxNumberOfTries?[2]:(n.counter+=1,(i=d([],u(e),!1)).splice(r,1),o=rn(i),n.visited.has(o)?[2]:sn(i)&&function(e,t){return Gt.querySelector(rn(e))===t}(i,t)?[4,i]:[3,4]):[3,5];case 2:return s.sent(),n.visited.set(o,!0),[5,c(vn(i,t,n))];case 3:s.sent(),s.label=4;case 4:return r++,[3,1];case 5:return[2]}})}var gn=function(e){var t=e.version,n=e.events,r=[];return n.forEach(function(e){var t=JSON.parse(e);t.count=1,"click"===t.type&&r.push(t)}),{version:t,events:r}},fn=function(e){var t=e.version,n=e.events,r=[];n.forEach(function(e){var t=JSON.parse(e);"click"===t.type&&r.push(t)});var i=r.reduce(function(e,t){var n=t.x,r=t.y,i=t.selector,s=t.timestamp,a=s-s%36e5,l="".concat(n,":").concat(r,":").concat(null!=i?i:"",":").concat(a);return e[l]?e[l].count+=1:e[l]=o(o({},t),{timestamp:a,count:1}),e},{});return{version:t,events:Object.values(i)}},pn=function(e,t){var n=this;this.createHook=function(e){var t=e.eventsManager,r=e.sessionId,i=e.deviceIdFn,o=e.mirror,s=e.ugcFilterRules,a=e.performanceOptions;return function(e){if(e.type===$e.Click){var l=f();if(l){var c=l.location,u=l.innerHeight,d=l.innerWidth;if(c){var h=e.x,v=e.y;if(void 0!==h&&void 0!==v){var g,p=o.getNode(e.id);if(p)try{g=en(p,a)}catch(e){n.logger.debug("error resolving selector from finder")}var m=Ae(c.href,s),y={x:h+n.scrollWatcher.currentScrollX,y:v+n.scrollWatcher.currentScrollY,selector:g,viewportHeight:u,viewportWidth:d,pageUrl:m,timestamp:Date.now(),type:"click"},b=i();b&&t.addEvent({sessionId:r,event:{type:"interaction",data:JSON.stringify(y)},deviceId:b})}}}}}},this.logger=e,this.scrollWatcher=t};function mn(){var e=f();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function yn(){var e=f();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}var bn=function(){function e(e,t){var n=f();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=function(e,t){try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=function(){return!1},this.sendXhr=function(e,t){var n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=De(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e,this.handleSendEvents=t.handleSendEvents,this.loggerProvider=t.loggerProvider}return e.prototype.send=function(e,t){var n,r=this,i=this.context,o=i.sessionId,s=i.type;if(this.handleSendEvents){var a=new URLSearchParams({device_id:e,session_id:String(o),type:String(s)}),l="".concat(this.basePageUrl,"?").concat(a.toString()),c={"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(this.apiKey)};try{this.handleSendEvents({url:l,method:"POST",headers:c,body:JSON.stringify(t),keepalive:!0}).catch(function(e){var t;null===(t=r.loggerProvider)||void 0===t||t.warn("Custom transport failed to send session replay interaction beacon:",e)})}catch(e){null===(n=this.loggerProvider)||void 0===n||n.warn("Custom transport threw while sending session replay interaction beacon:",e)}}else{var u=new URLSearchParams({device_id:e,session_id:String(o),type:String(s),api_key:this.apiKey}),d="".concat(this.basePageUrl,"?").concat(u.toString());this.sendBeacon(d,t)||this.sendXhr(d,t)}},e}(),Sn=function(){function e(e,t){var n=this;this.timestamp=Date.now(),this.hook=function(e){n.update(e)},this.send=function(e){return function(t){var r,i,o,s,a=e(),l=f();if(l&&a){var c=null!==(r=l.scrollX)&&void 0!==r?r:0,u=null!==(i=l.scrollY)&&void 0!==i?i:0;(c>0||u>0)&&n.update({id:1,x:c,y:u}),n.transport.send(a,{version:1,events:[{maxScrollX:n._maxScrollX,maxScrollY:n._maxScrollY,maxScrollWidth:n._maxScrollWidth,maxScrollHeight:n._maxScrollHeight,viewportHeight:mn(),viewportWidth:yn(),pageUrl:Ae(l.location.href,null!==(s=null===(o=n.config.interactionConfig)||void 0===o?void 0:o.ugcFilterRules)&&void 0!==s?s:[]),timestamp:n.timestamp,type:"scroll"}]})}}},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=yn(),this._maxScrollHeight=mn(),this.config=t,this.transport=e}return e.default=function(t,n){return new e(new bn(t,n),n)},Object.defineProperty(e.prototype,"maxScrollX",{get:function(){return this._maxScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollY",{get:function(){return this._maxScrollY},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollWidth",{get:function(){return this._maxScrollWidth},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollHeight",{get:function(){return this._maxScrollHeight},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollX",{get:function(){return this._currentScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollY",{get:function(){return this._currentScrollY},enumerable:!1,configurable:!0}),e.prototype.update=function(e){var t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){var n=yn();this._maxScrollX=e.x;var r=e.x+n;r>this._maxScrollWidth&&(this._maxScrollWidth=r),this.timestamp=t}if(e.y>this._maxScrollY){var i=mn();this._maxScrollY=e.y;var o=e.y+i;o>this._maxScrollHeight&&(this._maxScrollHeight=o),this.timestamp=t}},e}(),In=function(e){var t=e.sessionId,n=e.deviceId;this.deviceId=n,this.sessionId=t,t&&n&&(this.sessionReplayId=function(e,t){return"".concat(t,"/").concat(e)}(t,n))},wn=864e5,Cn=function(e){return"".concat("AMP_SR_START_").concat(e.substring(0,10),"_")},En=function(e,t){return"".concat(Cn(e)).concat(t)},Pn=function(){try{var e=f();return null==e?void 0:e.localStorage}catch(e){return}},kn=function(){var e=this;this.dbs={},this.createStore=function(t){return a(e,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,xt(t,1,{upgrade:function(e){e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})];case 1:return[2,e.sent()]}})})},this.openOrCreateDB=function(t){return a(e,void 0,void 0,function(){var e,n;return l(this,function(r){switch(r.label){case 0:return this.dbs&&this.dbs[t]?[2,this.dbs[t]]:(e="".concat(t.substring(0,10),"_amp_session_replay_targeting"),[4,this.createStore(e)]);case 1:return n=r.sent(),this.dbs[t]=n,[2,n]}})})},this.getTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId;return a(e,void 0,void 0,function(){var e,t,o,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,e.get("sessionTargetingMatch",t)];case 2:return[2,null==(o=a.sent())?void 0:o.targetingMatch];case 3:return s=a.sent(),Nt(n,"Failed to get targeting match for session id ".concat(i,": ").concat(s),s),[3,4];case 4:return[2,void 0]}})})},this.storeTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId,o=t.targetingMatch;return a(e,void 0,void 0,function(){var e,t,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,e.put("sessionTargetingMatch",{targetingMatch:o,sessionId:t,lastUpdated:Date.now()})];case 2:return[2,a.sent()];case 3:return s=a.sent(),Nt(n,"Failed to store targeting match for session id ".concat(i,": ").concat(s),s),[3,4];case 4:return[2,void 0]}})})},this.clearStoreOfOldSessions=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.currentSessionId;return a(e,void 0,void 0,function(){var e,t,o,s,a,c,u,d;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,8,,9]),[4,this.openOrCreateDB(r)];case 1:return e=l.sent(),t=String(i),[4,(o=e.transaction("sessionTargetingMatch","readwrite")).store.getAll()];case 2:s=l.sent(),a=0,l.label=3;case 3:return a<s.length?(c=s[a],u=Date.now()-c.lastUpdated,c.sessionId!==t&&u>1728e5?[4,o.store.delete(c.sessionId)]:[3,5]):[3,6];case 4:l.sent(),l.label=5;case 5:return a++,[3,3];case 6:return[4,o.done];case 7:return l.sent(),[3,9];case 8:return d=l.sent(),Nt(n,"Failed to clear old targeting matches for sessions: ".concat(d),d),[3,9];case 9:return[2]}})})}},xn=new kn,Mn=function(e){var t=e.sessionId,n=e.targetingConfig,r=e.loggerProvider,i=e.apiKey,s=e.targetingParams,c=e.urlChange,u=void 0!==c&&c;return a(void 0,void 0,void 0,function(){var e,a,c,d,h,v;return l(this,function(l){switch(l.label){case 0:return[4,xn.clearStoreOfOldSessions({loggerProvider:r,apiKey:i,currentSessionId:t})];case 1:return l.sent(),[4,xn.getTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t})];case 2:if(!0===l.sent()&&!u)return[2,!0];e=!0,l.label=3;case 3:return l.trys.push([3,6,,7]),[4,import("./index-min3.js")];case 4:return a=l.sent().evaluateTargeting,c=o(o({},s),{flag:n,sessionId:"string"==typeof t?parseInt(t,10):t,apiKey:i,loggerProvider:r}),[4,a(c)];case 5:return(d=l.sent())&&d.sr_targeting_config&&(e="on"===d.sr_targeting_config.key),xn.storeTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t,targetingMatch:e}),[3,7];case 6:return h=l.sent(),v=h,r.warn(v.message),[3,7];case 7:return[2,e]}})})},Tn=2654435761,On=2246822519,Rn=3266489917,_n=374761393;function Ln(e,t){return(e<<t|e>>>32-t)>>>0}function Fn(e,t){return e=Ln(e=e+Math.imul(t,On)>>>0,13),e=Math.imul(e,Tn)>>>0}function Dn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function qn(e,t){void 0===t&&(t=0);var n,r=function(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r>=55296&&r<=56319&&n+1<e.length){var i=e.charCodeAt(n+1);i>=56320&&i<=57343&&(r=i-56320+(r-55296<<10)+65536,n++)}r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<65536?t.push(224|r>>12,128|r>>6&63,128|63&r):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}return new Uint8Array(t)}(e),i=r.length,o=0;if(i>=16){for(var s=t+Tn+On>>>0,a=t+On>>>0,l=t>>>0,c=t-Tn>>>0;o<=i-16;)s=Fn(s,Dn(r,o)),a=Fn(a,Dn(r,o+=4)),l=Fn(l,Dn(r,o+=4)),c=Fn(c,Dn(r,o+=4)),o+=4;n=Ln(s,1)+Ln(a,7)+Ln(l,12)+Ln(c,18)>>>0}else n=t+_n>>>0;for(n=n+i>>>0;o<=i-4;)n=n+Math.imul(Dn(r,o),Rn)>>>0,n=Math.imul(Ln(n,17),668265263)>>>0,o+=4;for(;o<i;)n=n+Math.imul(r[o],_n)>>>0,n=Math.imul(Ln(n,11),Tn)>>>0,o++;return n^=n>>>15,n=Math.imul(n,On)>>>0,n^=n>>>13,n=Math.imul(n,Rn)>>>0,(n^=n>>>16)>>>0}var An="__amplitude_url_tracking_patched__",jn=new WeakMap;function Bn(e,t,n){if(void 0===n&&(n={}),!(null==e?void 0:e.location))return function(){};var r=n.enablePolling,i=void 0!==r&&r,o=n.pollingInterval,s=void 0===o?he:o;if(i){var a=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""},l=a(),c=e.setInterval(function(){var e=a();e!==l&&(l=e,t(e))},s);return function(){null!=c&&e.clearInterval(c)}}var u=jn.get(e);if(!u){var d=void 0,h=new Set,v=function(){var t=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""}();void 0!==d&&t===d||(d=t,h.forEach(function(e){return e(t)}))},g=function(e){var t=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=e.apply(this,t);return v(),r};return t[An]=!0,t},f=e.history;if(null==f?void 0:f.pushState){var p=Reflect.get(f,"pushState");p[An]||(f.pushState=g(p))}if(null==f?void 0:f.replaceState){var m=Reflect.get(f,"replaceState");m[An]||(f.replaceState=g(m))}u={callbacks:h,notify:v,onPopStateOrHashChange:function(){return v()},listenersAttached:!1},jn.set(e,u)}var y=u;return y.listenersAttached||(e.addEventListener("popstate",y.onPopStateOrHashChange),e.addEventListener("hashchange",y.onPopStateOrHashChange),y.listenersAttached=!0),y.callbacks.add(t),function(){y.callbacks.delete(t),0===y.callbacks.size&&y.listenersAttached&&(e.removeEventListener("popstate",y.onPopStateOrHashChange),e.removeEventListener("hashchange",y.onPopStateOrHashChange),y.listenersAttached=!1)}}function Nn(e){return void 0===e&&(e={}),{name:"amplitude/url-tracking@1",observer:function(t,n,r){var i,s,a,l=o(o({},e),r),c=l.ugcFilterRules||[],u=null!==(i=l.enablePolling)&&void 0!==i&&i,d=null!==(s=l.pollingInterval)&&void 0!==s?s:he,h=null!==(a=l.captureDocumentTitle)&&void 0!==a&&a;if(!n)return function(){};var v=void 0,g=function(){return n.location&&n.location.href||""},f=function(){var e=g();if(void 0===v||e!==v){v=e;var r=function(){var e=n.innerHeight,t=n.innerWidth,r=n.document,i=g(),o="";return h&&(o=(null==r?void 0:r.title)||""),{href:c.length>0?Ae(i,c):i,title:o,viewportHeight:e,viewportWidth:t,type:"url-change-event"}}();t(r)}},p=Bn(n,function(){return f()},u?{enablePolling:!0,pollingInterval:d}:{});return f(),function(){return p()}},options:e}}Nn();var Un=function(){function e(){this.pendingLoadListeners=new Map}return e.prototype.start=function(){var e,t=this;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),f()&&(this.sendToAllIframes({type:Ce,action:"start"}),this.mutationObserver=new MutationObserver(function(e){var n,r,i,o,s,a;try{for(var l=c(e),u=l.next();!u.done;u=l.next()){var d=u.value;try{for(var h=(i=void 0,c(Array.from(d.addedNodes))),v=h.next();!v.done;v=h.next()){(p=v.value)instanceof HTMLIFrameElement?t.sendToIframeAfterLoad(p):p instanceof Element&&p.querySelectorAll("iframe").forEach(function(e){t.sendToIframeAfterLoad(e)})}}catch(e){i={error:e}}finally{try{v&&!v.done&&(o=h.return)&&o.call(h)}finally{if(i)throw i.error}}try{for(var g=(s=void 0,c(Array.from(d.removedNodes))),f=g.next();!f.done;f=g.next()){var p;if((p=f.value)instanceof HTMLIFrameElement){var m=t.pendingLoadListeners.get(p);m&&(p.removeEventListener("load",m),t.pendingLoadListeners.delete(p))}}}catch(e){s={error:e}}finally{try{f&&!f.done&&(a=g.return)&&a.call(g)}finally{if(s)throw s.error}}}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}),this.mutationObserver.observe(document.documentElement,{childList:!0,subtree:!0}))},e.prototype.stop=function(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),this.mutationObserver=void 0,this.pendingLoadListeners.forEach(function(e,t){t.removeEventListener("load",e)}),this.pendingLoadListeners.clear(),this.sendToAllIframes({type:Ce,action:"stop"})},e.prototype.sendToIframeAfterLoad=function(e){var t=this,n=function(){t.pendingLoadListeners.delete(e),t.sendToIframe(e,{type:Ce,action:"start"})};this.pendingLoadListeners.set(e,n),e.addEventListener("load",n,{once:!0})},e.prototype.sendToAllIframes=function(e){var t=this;document.querySelectorAll("iframe").forEach(function(n){return t.sendToIframe(n,e)})},e.prototype.sendToIframe=function(e,t){var n;try{null===(n=e.contentWindow)||void 0===n||n.postMessage(t,"*")}catch(e){}},e}();var Wn=function(){function e(){var e=this;this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.recordFunction=null,this.recordEventsInFlight=!1,this.recordingEnabled=!0,this.recordingGeneration=0,this.startChildRecordingOnSetup=!1,this.pendingEmitEvents=[],this.currentPageUrl="",this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.crossOriginIframeCoordinator=null,this.crossOriginParentSignalCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=function(t){var n=f();n&&(n.removeEventListener("blur",e.blurListener),n.removeEventListener("focus",e.focusListener),!t&&n.addEventListener("blur",e.blurListener),!t&&n.addEventListener("focus",e.focusListener),n.self&&"onpagehide"in n.self?(n.removeEventListener("pagehide",e.pageLeaveListener),!t&&n.addEventListener("pagehide",e.pageLeaveListener)):(n.removeEventListener("beforeunload",e.pageLeaveListener),!t&&n.addEventListener("beforeunload",e.pageLeaveListener)))},this.blurListener=function(){e.sendEvents()},this.focusListener=function(){var t;if(e.recordingEnabled)if(e.recordCancelCallback&&e.recordFunction){if(!1===(null===(t=e.config)||void 0===t?void 0:t.captureFullSnapshotOnFocus))return;try{e.recordFunction.takeFullSnapshot(!0)}catch(t){e.loggerProvider.warn("Failed to take full snapshot on focus:",t)}}else e.recordEventsInFlight||e.recordEvents(!1)},this.pageLeaveListener=function(t){var n;null===(n=e.eventCompressor)||void 0===n||n.flushQueue(),e.sendEvents(),e.pageLeaveFns.forEach(function(e){e(t)})},this.evaluateTargetingAndCapture=function(t,n,r,o){return void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),a(e,void 0,void 0,function(){var e,s,a,c,u,d,h,v,g,p,m,y;return l(this,function(l){switch(l.label){case 0:if(!this.identifiers||!this.identifiers.sessionId||!this.config)return 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."),[2];if(!this.config.targetingConfig){if(!n)return this.loggerProvider.log("No targeting config set, skipping initialization/recording for event."),[2];this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}return this.lastTargetingParams=t,e=this.config.targetingConfig,e&&!this.sessionTargetingMatch?(s=o?this.latestUrlChangeTargetingEvaluationId:void 0,(a=t.event)&&Object.values(i).includes(a.event_type)&&(a=void 0),c=null!==(m=null!==(v=null===(h=t.page)||void 0===h?void 0:h.url)&&void 0!==v?v:null===(p=null===(g=f())||void 0===g?void 0:g.location)||void 0===p?void 0:p.href)&&void 0!==m?m:"",u=null!==(y=t.page)&&void 0!==y?y:""!==c?{url:c}:void 0,[4,Mn({sessionId:this.identifiers.sessionId,targetingConfig:e,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:t.userProperties,event:a,page:u},urlChange:o})]):[3,2];case 1:if(d=l.sent(),o&&void 0!==s&&s!==this.latestUrlChangeTargetingEvaluationId)return this.loggerProvider.debug("Ignoring stale URL-change targeting result #".concat(s,"; latest is #").concat(this.latestUrlChangeTargetingEvaluationId,".")),[2];this.sessionTargetingMatch=this.sessionTargetingMatch||d,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:a,targetingParams:t},null,2)),l.label=2;case 2:return n?(this.initialize(!0),[3,5]):[3,3];case 3:return!r&&this.recordCancelCallback?[3,5]:(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),[4,this.recordEvents()]);case 4:l.sent(),l.label=5;case 5:return[2]}})})},this.addCustomRRWebEvent=function(t,n,r){return void 0===n&&(n={}),void 0===r&&(r=!0),a(e,void 0,void 0,function(){var e,i,s,a;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,3,,4]),e=void 0,(i=this.config)&&t!==ae.METADATA?(e={config:Be(i),version:ht},r?[4,je()]:[3,2]):[3,2];case 1:s=l.sent(),e=o(o({},s),e),l.label=2;case 2:return this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(t,o(o({},n),e)):this.loggerProvider.debug("Not able to add custom replay capture event ".concat(t," due to no ongoing recording.")),[3,4];case 3:return a=l.sent(),this.loggerProvider.debug("Error while adding custom replay capture event: ",a),[3,4];case 4:return[2]}})})},this.stopRecordingEvents=function(){var t,n,r;try{e.loggerProvider.log("Session Replay capture stopping."),e.recordCancelCallback&&e.recordCancelCallback(),e.recordCancelCallback=null,null===(t=e.networkObservers)||void 0===t||t.stop(),null===(n=e.crossOriginIframeCoordinator)||void 0===n||n.stop(),e.crossOriginIframeCoordinator=null,null===(r=e.crossOriginParentSignalCleanup)||void 0===r||r.call(e),e.crossOriginParentSignalCleanup=null}catch(t){var i=t;e.loggerProvider.warn("Error occurred while stopping replay capture: ".concat(i.toString()))}},this.loggerProvider=new Ee(new M)}return e.prototype.init=function(e,t){return k(this._init(e,t))},e.prototype.setupUrlChangeListener=function(){var e,t,n=this;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);var r=f();if(null==r?void 0:r.location){var i=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),o=Bn(r,function(e){if(n.currentPageUrl=e,i){var t=++n.latestUrlChangeTargetingEvaluationId;n.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:e}},!1,!1,!0),n.loggerProvider.debug("Queued URL-change targeting re-evaluation #".concat(t," for ").concat(e,"."))}});this.urlChangeCleanup=function(){o(),n.urlChangeCleanup=null}}},e.prototype.isBelowMinSessionDuration=function(){var e,t=null===(e=this.config)||void 0===e?void 0:e.minSessionDurationMs;return void 0!==t&&void 0!==this.sessionStartTime&&Date.now()-this.sessionStartTime<t},e.prototype.getCurrentPageForTargeting=function(){var e,t,n=null===(t=null===(e=f())||void 0===e?void 0:e.location)||void 0===t?void 0:t.href;return null!=n?{url:n}:void 0},e.prototype._init=function(e,t){var n,r,i,s,h,v,g,p,m,y,b,S,I,w;return a(this,void 0,void 0,function(){var a,C,E,P,k,x,T,O,R,_,L,F,D,q,A,j,B,N,U,W,z,K,H,G,Q,J,$,Z,V,X,ee,te=this;return l(this,function(l){switch(l.label){case 0:return null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),this.recordingEnabled=!0,this.startChildRecordingOnSetup=!1,this.loggerProvider=new Ee(t.loggerProvider||new M),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=qe(),this.identifiers=new In({sessionId:t.sessionId,deviceId:t.deviceId}),a=Date.now(),function(e,t,n){var r,i,o=Pn();if(o){var s=Cn(e);try{for(var a=[],l=0;l<o.length;l++)if((g=o.key(l))&&g.startsWith(s)){var u=o.getItem(g);if(null!==u){var d=Number(u);(!Number.isFinite(d)||d<=0||t-d>=wn)&&a.push(g)}}try{for(var h=c(a),v=h.next();!v.done;v=h.next()){var g=v.value;o.removeItem(g)}}catch(e){r={error:e}}finally{try{v&&!v.done&&(i=h.return)&&i.call(h)}finally{if(r)throw r.error}}}catch(e){null==n||n.debug("Failed to prune stale replay start times: ".concat(String(e)))}}}(e,a,this.loggerProvider),this.sessionStartTime=void 0!==t.sessionId&&null!==(r=function(e,t,n,r){var i=Pn();if(i){var o=En(e,t);try{var s=i.getItem(o);if(null!==s){var a=Number(s);if(Number.isFinite(a)&&a>0&&a<=n&&n-a<wn)return a}return i.setItem(o,String(n)),n}catch(e){return void(null==r||r.debug("Failed to read/write replay start time from storage: ".concat(String(e))))}}}(e,t.sessionId,a,this.loggerProvider))&&void 0!==r?r:a,C=this,[4,Ye(e,t)];case 1:return C.joinedConfigGenerator=l.sent(),[4,this.joinedConfigGenerator.generateJoinedConfig()];case 2:return E=l.sent(),P=E.joinedConfig,k=E.localConfig,x=E.remoteConfig,this.config=P,this.setMetadata(t.sessionId,P,k,x,null===(i=t.version)||void 0===i?void 0:i.version,ht,null===(s=t.version)||void 0===s?void 0:s.type),this.pageLeaveFns=[],t.sessionId&&(null===(h=this.config.interactionConfig)||void 0===h?void 0:h.enabled)&&(T=Sn.default({sessionId:t.sessionId,type:"interaction"},this.config),this.pageLeaveFns=[T.send(this.getDeviceId.bind(this)).bind(T)],this.scrollHook=T.hook.bind(T),this.clickHandler=new pn(this.loggerProvider,T)),O=[],"idb"!==(R=this.config.storeType)||(null===(v=f())||void 0===v?void 0:v.indexedDB)||(R="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log("Using ".concat(R," for event storage.")),F=f(),this.config.useWebWorker&&F&&F.Worker?[4,import("./index-min2.js")]:[3,4];case 3:D=l.sent(),q=D.compressionScript,A=D.trackDestinationScript,_=q,L=A,l.label=4;case 4:return l.trys.push([4,6,,7]),[4,Xt({config:this.config,type:"replay",minInterval:null===(g=this.config.flushIntervalConfig)||void 0===g?void 0:g.minIntervalMs,maxInterval:null===(p=this.config.flushIntervalConfig)||void 0===p?void 0:p.maxIntervalMs,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,storeType:R,trackDestinationWorkerScript:L,shouldSend:function(){return!te.isBelowMinSessionDuration()}})];case 5:return j=l.sent(),this.rrwebEventManager=j,O.push({name:"replay",manager:j}),[3,7];case 6:return B=l.sent(),z=B,this.loggerProvider.warn("Error occurred while creating replay events manager: ".concat(z.toString())),[3,7];case 7:if(!(null===(m=this.config.interactionConfig)||void 0===m?void 0:m.enabled))return[3,11];N=this.config.interactionConfig.batch?fn:gn,l.label=8;case 8:return l.trys.push([8,10,,11]),[4,Xt({config:this.config,type:"interaction",minInterval:null!==(y=this.config.interactionConfig.trackEveryNms)&&void 0!==y?y:3e4,maxInterval:6e4,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,payloadBatcher:N,storeType:R,trackDestinationWorkerScript:L})];case 9:return U=l.sent(),O.push({name:"interaction",manager:U}),[3,11];case 10:return W=l.sent(),z=W,this.loggerProvider.warn("Error occurred while creating interaction events manager: ".concat(z.toString())),[3,11];case 11:if(this.eventsManager=new(Yt.bind.apply(Yt,d([void 0],u(O),!1))),this.eventCompressor&&this.eventCompressor.terminate(),K=!0===this.config.eagerFullSnapshotSend?function(){return te.sendEvents()}:void 0,this.eventCompressor=new lt(this.eventsManager,this.config,this.getDeviceId(),_,K),this.pendingEmitEvents.length>0){H=this.pendingEmitEvents.splice(0);try{for(G=c(H),Q=G.next();!Q.done;Q=G.next())J=Q.value,$=J.event,Z=J.sessionId,this.eventCompressor.enqueueEvent($,Z)}catch(e){X={error:e}}finally{try{Q&&!Q.done&&(ee=G.return)&&ee.call(G)}finally{if(X)throw X.error}}}return this.pageLeaveFns=d(d([],u(this.pageLeaveFns),!1),[function(){var e;if(te.config&&(null===(e=te.identifiers)||void 0===e?void 0:e.sessionId)&&j){var t=j.getBeaconEvents();if(t.length){var n=te.getDeviceId();n&&(te.isBelowMinSessionDuration()||j.trackDestination.sendBeacon({events:t,sessionId:te.identifiers.sessionId,deviceId:n,apiKey:te.config.apiKey,serverZone:te.config.serverZone}))}}}],!1),[4,this.initializeNetworkObservers()];case 12:return l.sent(),(null===(b=f())||void 0===b?void 0:b.opener)&&(se(V=re()),V.setup(o({logger:this.loggerProvider},this.config.serverZone&&{endpoint:Y[this.config.serverZone]}))),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),[4,this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0)];case 13:return l.sent(),(this.config.targetingConfig||(null!==(w=null===(I=null===(S=this.config.privacyConfig)||void 0===S?void 0:S.urlMaskLevels)||void 0===I?void 0:I.length)&&void 0!==w?w:0)>0)&&this.setupUrlChangeListener(),[2]}})})},e.prototype.setSessionId=function(e,t){return k(this.asyncSetSessionId(e,t))},e.prototype.asyncSetSessionId=function(e,t,n){var r,i,o,s;return a(this,void 0,void 0,function(){var a,c,u,d,h;return l(this,function(l){switch(l.label){case 0:return a=null===(r=this.identifiers)||void 0===r?void 0:r.sessionId,c=this.getDeviceId(),void 0===a||a!==e||void 0!==t&&t!==c||void 0!==(null==n?void 0:n.userProperties)&&0!==Object.keys(n.userProperties).length?(this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,a&&this.sendEvents(a),(u=a!==e)&&(null===(i=this.rrwebEventManager)||void 0===i||i.dropPendingBeaconEvents()),d=t||this.getDeviceId(),this.identifiers=new In({sessionId:e,deviceId:d}),u&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,(null===(o=this.config)||void 0===o?void 0:o.apiKey)&&(function(e,t,n,r){var i=Pn();if(i)try{i.setItem(En(e,t),String(n))}catch(e){null==r||r.debug("Failed to write replay start time to storage: ".concat(String(e)))}}(this.config.apiKey,e,this.sessionStartTime,this.loggerProvider),void 0!==a&&function(e,t,n){var r=Pn();if(r)try{r.removeItem(En(e,t))}catch(e){null==n||n.debug("Failed to remove replay start time from storage: ".concat(String(e)))}}(this.config.apiKey,a,this.loggerProvider))),this.joinedConfigGenerator&&a?[4,this.joinedConfigGenerator.generateJoinedConfig()]:[3,2]):[2];case 1:h=l.sent().joinedConfig,this.config=h,l.label=2;case 2:return(null===(s=this.config)||void 0===s?void 0:s.targetingConfig)?[4,this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0)]:[3,4];case 3:return l.sent(),[3,6];case 4:return[4,this.recordEvents()];case 5:l.sent(),l.label=6;case 6:return[2]}})})},e.prototype.getSessionReplayProperties=function(){var e,t=this.config,n=this.identifiers;if(!t||!n)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};var r=this.getShouldRecord(),i={};return r&&((e={})[ce]=n.sessionReplayId?n.sessionReplayId:null,i=e,t.debugMode&&(i[ve]=JSON.stringify({appHash:W(t.apiKey).toString()}))),this.addCustomRRWebEvent(ae.GET_SR_PROPS,{shouldRecord:r,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i},e.prototype.sendEvents=function(e){var t,n,r=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();if(this.eventsManager&&r&&i){if(this.isBelowMinSessionDuration()){var o=this.sessionStartTime,s=this.config.minSessionDurationMs;return this.loggerProvider.log("Session ".concat(r," not sent: duration ").concat(Date.now()-o,"ms is below minimum ").concat(s,"ms.")),void this.suppressedSendCount++}if(!this.hasEmittedGateDecision&&void 0!==(null===(n=this.config)||void 0===n?void 0:n.minSessionDurationMs)&&this.recordCancelCallback&&this.recordFunction){this.hasEmittedGateDecision=!0;var a=void 0!==this.sessionStartTime?Date.now()-this.sessionStartTime:void 0;this.addCustomRRWebEvent(ae.REPLAY_GATE_DECISION,{sessionId:r,suppressedSendCount:this.suppressedSendCount,elapsedMs:a,minSessionDurationMs:this.config.minSessionDurationMs},!1)}this.eventsManager.sendCurrentSequenceEvents({sessionId:r,deviceId:i})}},e.prototype.initialize=function(e){var t;return void 0===e&&(e=!1),a(this,void 0,void 0,function(){var n;return l(this,function(r){return(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId)?(n=this.getDeviceId())?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),[2,this.recordEvents()]):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),[2,Promise.resolve()]):(this.loggerProvider.log("Session is not being recorded due to lack of session id."),[2,Promise.resolve()])})})},e.prototype.shouldOptOut=function(){var e,t,n,r;(null===(e=this.config)||void 0===e?void 0:e.instanceName)&&(n=(r=this.config.instanceName,U.getInstance(T(r))).identityStore.getIdentity().optOut);return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut},e.prototype.getShouldRecord=function(){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.recordingEnabled)return this.loggerProvider.log("Session ".concat(this.identifiers.sessionId," not being captured because recording was stopped.")),!1;if(!this.config.captureEnabled)return this.loggerProvider.log("Session ".concat(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 ".concat(this.identifiers.sessionId," out of recording due to optOut config.")),!1;var e,t,n=!1,r="",i=!1;this.config.targetingConfig?this.sessionTargetingMatch?(r="Capturing replays for session ".concat(this.identifiers.sessionId," due to matching targeting conditions."),this.loggerProvider.log(r),n=!0,i=!0):(r="Not capturing replays for session ".concat(this.identifiers.sessionId," due to not matching targeting conditions."),this.loggerProvider.log(r),n=!1,i=!1):(e=this.identifiers.sessionId,t=this.config.sampleRate,qn(e.toString())%1e6/1e6<t)?(n=!0,i=!0):(r="Opting session ".concat(this.identifiers.sessionId," out of recording due to sample rate."),this.loggerProvider.log(r),n=!1,i=!1);return this.lastShouldRecordDecision!==n&&this.config.targetingConfig&&(this.addCustomRRWebEvent(ae.TARGETING_DECISION,{message:r,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=n),n},e.prototype.getBlockSelectors=function(){var e;return Le(null===(e=this.config)||void 0===e?void 0:e.privacyConfig)},e.prototype.getMaskTextSelectors=function(){var e;return Fe(null===(e=this.config)||void 0===e?void 0:e.privacyConfig,this.currentPageUrl)},e.prototype.getRecordingPlugins=function(e){var t,n,r,i,o,s;return a(this,void 0,void 0,function(){var a,c,u,d;return l(this,function(l){switch(l.label){case 0:a=[];try{c=Nn({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===(i=this.config)||void 0===i?void 0:i.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle}),a.push(c)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(!(null===(s=null==e?void 0:e.console)||void 0===s?void 0:s.enabled))return[3,4];l.label=1;case 1:return l.trys.push([1,3,,4]),[4,import("./rrweb-plugin-console-record-min.js")];case 2:return u=l.sent().getRecordConsolePlugin,a.push(u({level:e.console.levels})),[3,4];case 3:return d=l.sent(),this.loggerProvider.warn("Failed to load console plugin:",d),[3,4];case 4:return[2,a.length>0?a:void 0]}})})},e.prototype.getRecordFunction=function(){return a(this,void 0,void 0,function(){var e,t;return l(this,function(n){switch(n.label){case 0:if(this.recordFunction)return[2,this.recordFunction];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,import("./rrweb-record-min.js")];case 2:return e=n.sent().record,this.recordFunction=e,[2,e];case 3:return t=n.sent(),this.loggerProvider.warn("Failed to load rrweb-record module:",t),[2,null];case 4:return[2]}})})},e.prototype.recordEvents=function(e){return void 0===e&&(e=!0),a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:if(this.recordEventsInFlight)return this.recordEventsPendingShouldLogMetadata=e,[2];this.recordEventsInFlight=!0,n.label=1;case 1:return n.trys.push([1,,6,7]),[4,this._recordEvents(e)];case 2:n.sent(),n.label=3;case 3:return null===this.recordEventsPendingShouldLogMetadata?[3,5]:(t=this.recordEventsPendingShouldLogMetadata,this.recordEventsPendingShouldLogMetadata=null,[4,this._recordEvents(t)]);case 4:return n.sent(),[3,3];case 5:return[3,7];case 6:return this.recordEventsInFlight=!1,this.recordEventsPendingShouldLogMetadata=null,[7];case 7:return[2]}})})},e.prototype.shouldAbandonRecordStart=function(e){return!this.recordingEnabled||e!==this.recordingGeneration},e.prototype._recordEvents=function(e){var t,n,r,i,s,c,u,d;return void 0===e&&(e=!0),a(this,void 0,void 0,function(){var a,h,v,g,p,m,y,b,S,I,w,C,E,P,k,x,M,T=this;return l(this,function(l){switch(l.label){case 0:return a=this.config,h=this.getShouldRecord(),v=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId,h&&v&&a?(this.stopRecordingEvents(),g=this.recordingGeneration,[4,this.getRecordFunction()]):[2];case 1:return!(p=l.sent())||this.shouldAbandonRecordStart(g)?[2]:[4,this.initializeNetworkObservers()];case 2:if(l.sent(),this.shouldAbandonRecordStart(g))return[2];m=null===(n=a.loggingConfig)||void 0===n?void 0:n.network,y=De(a.serverZone,a.trackServerUrl),b=[ge,fe,pe,y],null===(r=this.networkObservers)||void 0===r||r.start(function(e){b.some(function(t){return e.url.startsWith(t)})||T.addCustomRRWebEvent(ae.FETCH_REQUEST,e)},m),S=a.interactionConfig,I=a.loggingConfig,w=(null==S?void 0:S.enabled)?{mouseInteraction:this.eventsManager&&(null===(i=this.clickHandler)||void 0===i?void 0:i.createHook({eventsManager:this.eventsManager,sessionId:v,deviceIdFn:this.getDeviceId.bind(this),mirror:p.mirror,ugcFilterRules:null!==(s=S.ugcFilterRules)&&void 0!==s?s:[],performanceOptions:null===(c=a.performanceConfig)||void 0===c?void 0:c.interaction})),scroll:this.scrollHook}:{},C=(null==S?void 0:S.enabled)&&S.ugcFilterRules?S.ugcFilterRules:[],this.loggerProvider.log("Session Replay capture beginning for ".concat(v,".")),l.label=3;case 3:return l.trys.push([3,5,,6]),E=!!(null===(u=a.crossOriginIframes)||void 0===u?void 0:u.enabled),P=!1!==(null===(d=a.crossOriginIframes)||void 0===d?void 0:d.coordinateChildren),(k=E&&function(){try{var e=f();return!!e&&e.parent!==e}catch(e){return!0}}())&&P?(this.crossOriginParentSignalCleanup=function(e){var t=f();if(!t)return function(){};var n=t.parent;function r(t){if(t.source===n){var r=t.data;(null==r?void 0:r.type)===Ce&&("start"===r.action?e.onStart():"stop"===r.action&&e.onStop())}}return t.addEventListener("message",r),function(){return t.removeEventListener("message",r)}}({onStart:function(){T.recordingEnabled&&T._recordEventsInChildMode(p,v,a,w)},onStop:function(){try{T.recordCancelCallback&&T.recordCancelCallback(),T.recordCancelCallback=null}catch(t){var e=t;T.loggerProvider.warn("Error occurred while stopping child iframe replay capture: ".concat(e.toString()))}}}),this.startChildRecordingOnSetup&&(this.startChildRecordingOnSetup=!1,this._recordEventsInChildMode(p,v,a,w)),[2]):(this.startChildRecordingOnSetup=!1,[4,this.getRecordingPlugins(I)]);case 4:return x=l.sent(),this.shouldAbandonRecordStart(g)?[2]:(this.recordCancelCallback=p(o(o({},this.buildRRWebRecordOptions(a,w,function(e){if(T.shouldOptOut()||!T.recordingEnabled)return T.loggerProvider.log(T.shouldOptOut()?"Opting session ".concat(v," out of recording due to optOut config."):"Session Replay capture stopping for ".concat(v,".")),T.stopRecordingEvents(),void T.sendEvents();e.type===Qe.Meta&&(e.data.href=Ae(e.data.href,C)),T.eventCompressor?T.eventCompressor.enqueueEvent(e,v):T.pendingEmitEvents.push({event:e,sessionId:v})},"Error while capturing replay: ")),{plugins:x,recordCrossOriginIframes:E})),E&&!k&&P&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new Un),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(ae.DEBUG_INFO),e&&this.addCustomRRWebEvent(ae.METADATA,this.metadata),[3,6]);case 5:return M=l.sent(),this.loggerProvider.warn("Failed to initialize session replay:",M),[3,6];case 6:return[2]}})})},e.prototype.buildRRWebRecordOptions=function(e,t,n,r){var i=this,s=e.privacyConfig;return o(o(o(o({emit:n,inlineStylesheet:e.shouldInlineStylesheet,inlineImages:e.inlineImages,hooks:t},function(e,t){return void 0===t&&(t=function(){return""}),{maskAllInputs:!0,maskTextClass:"amp-mask",blockClass:"amp-block",blockSelector:Le(e),maskTextSelector:Fe(e,t()),maskInputFn:Re("input",e,t),maskTextFn:Re("text",e,t),maskAttributeFn:_e(e,t)}}(s,function(){return i.currentPageUrl})),{applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements}),void 0!==e.fullSnapshotIntervalMs&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler:function(e){var t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return i.loggerProvider.warn(r,t.toString()),!0}})},e.prototype._recordEventsInChildMode=function(e,t,n,r){try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,this.recordCancelCallback=e(o(o({},this.buildRRWebRecordOptions(n,r,function(){},"Error while capturing replay (child iframe): ")),{recordCrossOriginIframes:!0})),this.loggerProvider.log("Session Replay child iframe capture beginning for session ".concat(t,"."))}catch(e){this.loggerProvider.warn("Failed to initialize session replay in child iframe mode:",e)}},e.prototype.getDeviceId=function(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId},e.prototype.getSessionId=function(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId},e.prototype.start=function(){return k(this._start())},e.prototype._start=function(){return a(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return this.recordingEnabled=!0,this.startChildRecordingOnSetup=!0,[4,this.recordEvents()];case 1:return e.sent(),[2]}})})},e.prototype.stop=function(){this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,this.stopRecordingEvents(),this.sendEvents()},e.prototype.flush=function(e){var t;return void 0===e&&(e=!1),a(this,void 0,void 0,function(){return l(this,function(n){return[2,null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)]})})},e.prototype.shutdown=function(){var e,t;this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,null===(e=this.urlChangeCleanup)||void 0===e||e.call(this),null===(t=this.crossOriginParentSignalCleanup)||void 0===t||t.call(this),this.crossOriginParentSignalCleanup=null,this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()},e.prototype.mapSDKType=function(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null},e.prototype.setMetadata=function(e,t,n,r,i,o,s){var a=(null==e?void 0:e.toString())?W(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:r,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(s),replaySDKVersion:i,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:o}},e.prototype.initializeNetworkObservers=function(){var e,t,n;return a(this,void 0,void 0,function(){var r,i;return l(this,function(o){switch(o.label){case 0: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)return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,import("./observers-min.js")];case 2:return r=o.sent().NetworkObservers,this.networkObservers=new r,[3,4];case 3:return i=o.sent(),this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",i),[3,4];case 4:return[2]}})})},e}(),zn=function(e){return function(){var t=e.config||Ne();return{logger:t.loggerProvider,logLevel:t.logLevel}}},Kn=function(){var e=new Wn;return{init:F(e.init.bind(e),"init",zn(e)),evaluateTargetingAndCapture:F(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",zn(e)),setSessionId:F(e.setSessionId.bind(e),"setSessionId",zn(e)),getSessionId:F(e.getSessionId.bind(e),"getSessionId",zn(e)),getSessionReplayProperties:F(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",zn(e)),flush:F(e.flush.bind(e),"flush",zn(e)),start:F(e.start.bind(e),"start",zn(e)),stop:F(e.stop.bind(e),"stop",zn(e)),shutdown:F(e.shutdown.bind(e),"shutdown",zn(e))}}(),Hn=Kn.init,Gn=Kn.setSessionId,Qn=Kn.getSessionId,Jn=Kn.getSessionReplayProperties;Kn.flush,Kn.start,Kn.stop,Kn.shutdown,Kn.evaluateTargetingAndCapture;const $n="amp_session_id",Zn="Amplitude Session Replay Segment Plugin [Debug]:";function Vn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)"__proto__"!==r&&(e[r]=n[r])}return e}var Xn=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=Vn({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},i=0;i<n.length;i++){var o=n[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(a in r||(r[a]=t.read(s,a)),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",Vn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Vn({},this.attributes,t))},withConverter:function(t){return e(Vn({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const Yn=()=>{const e=Qn()||Xn.get($n);if(e){const t=parseInt(e.toString(),10);if(isNaN(t))return;return t}},er=(e,t)=>(Xn.set($n,e.toString()),Gn(e,t).promise),tr=(e,t)=>a(void 0,void 0,void 0,function*(){const n=Yn()||0;let r;e.event.integrations&&e.event.integrations["Actions Amplitude"]&&(r=e.event.integrations["Actions Amplitude"].session_id),r&&n<r&&(yield er(r,t));const i=Jn(),o=Object.assign(Object.assign({},i),e.event.properties);return e.updateEvent("properties",o),e}),nr="0.0.52",rr=({amplitudeApiKey:e,sessionReplayOptions:t,segmentInstance:n,enableWrapperDebug:r=!1})=>a(void 0,void 0,void 0,function*(){let i,o=!1,s=null==t?void 0:t.deviceId;const l={name:"Session Replay Events",type:"enrichment",version:nr,isLoaded:()=>o,load:(n,l)=>a(void 0,void 0,void 0,function*(){if(!s){const e=l.user();s=e.anonymousId()||void 0}const n=Yn();r&&console.log(`${Zn} initializing session replay with sessionId=${null!=n?n:"undefined"} and deviceId=${null!=s?s:"undefined"}`),i=Hn(e,Object.assign(Object.assign({},t),{sessionId:n,deviceId:s||void 0,version:{type:"segment",version:nr}})).promise,yield i,o=!0}),track:e=>a(void 0,void 0,void 0,function*(){return yield i,yield tr(e,s)}),page:e=>a(void 0,void 0,void 0,function*(){return yield i,yield tr(e,s)}),identify:e=>a(void 0,void 0,void 0,function*(){yield i;const t=Yn();return t&&(r&&console.log(`${Zn} calling setSessionId() with sessionId=${t} and deviceId=${null!=s?s:"undefined"}`),yield er(t,s)),e})};yield n.register(l)});export{c as _,d as a,u as b,a as c,l as d,o as e,rr as f,f as g,xt as o,rt as t};
1
+ function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},t(e,n)};function n(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r,i,o=function(){return o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function s(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function a(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{l(r.next(e))}catch(e){o(e)}}function a(e){try{l(r.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((r=r.apply(e,t||[])).next())})}function l(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(l){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,l])}}}function c(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function d(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError,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"}(r||(r={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(i||(i={}));var h,v="$default_instance",g="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"}(h||(h={}));var f=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},p=d([],u(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),m=function(e){var t,n=f();if(!(null===(t=null==n?void 0:n.crypto)||void 0===t?void 0:t.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,m)}(e);var r=n.crypto.getRandomValues(new Uint8Array(16));return r[6]=15&r[6]|64,r[8]=63&r[8]|128,d([],u(r.entries()),!1).map(function(e){var t=u(e,2),n=t[0],r=t[1];return[4,6,8,10].includes(n)?"-".concat(p[r]):p[r]}).join("")},y={},b={get exports(){return y},set exports(e){y=e}},S=Object.prototype.hasOwnProperty;function I(e){return"[Throws: "+(e?e.message:"?")+"]"}function w(e){var t=[];return function e(n){if(null===n||"object"!=typeof n)return n;if(-1!==t.indexOf(n))return"[Circular]";if(t.push(n),"function"==typeof n.toJSON)try{var r=e(n.toJSON());return t.pop(),r}catch(e){return I(e)}if(Array.isArray(n)){var i=n.map(e);return t.pop(),i}var o=Object.keys(n).reduce(function(t,r){return t[r]=e(function(e,t){if(S.call(e,t))try{return e[t]}catch(e){return I(e)}return e[t]}(n,r)),t},{});return t.pop(),o}(e)}b.exports=function(e,t,n){return JSON.stringify(w(e),t,n)};var C,E=y.ensureProperties=w,P=y||e({__proto__:null,ensureProperties:E,get default(){return y}},[y]),k=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"}(C||(C={}));var x="Amplitude Logger ",M=function(){function e(){this.logLevel=C.None}return e.prototype.disable=function(){this.logLevel=C.None},e.prototype.enable=function(e){void 0===e&&(e=C.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Verbose||console.log("".concat(x,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Warn||console.warn("".concat(x,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Error||console.error("".concat(x,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Debug||console.log("".concat(x,"[Debug]: ").concat(e.join(" ")))},e}(),T=function(e){return void 0===e||""===e?v:e},O=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:v,logLevel:C.Warn,loggerProvider:new M,offline:!1,optOut:!1,serverUrl:g,serverZone:"US",useBatch:!1}},R=function(){function e(e){var t,n,r,i;this._optOut=!1;var o=O();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=T(e.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!==(r=e.optOut)&&void 0!==r?r:o.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||o.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(i=e.useBatch)&&void 0!==i?i:o.useBatch,this.loggerProvider.enable(this.logLevel);var s=L(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}(),_=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":g},L=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=O().serverZone),void 0===n&&(n=O().useBatch),e)return{serverUrl:e,serverZone:void 0};var r=["US","EU"].includes(t)?t:O().serverZone;return{serverZone:r,serverUrl:_(r,n)}};var F=function(e,t,n,r,i){return void 0===i&&(i=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<C.Debug||!c||!l)return e.apply(i,o);var u,d={type:"invoke public method",name:t,args:o,stacktrace:(u=1,void 0===u&&(u=0),((new Error).stack||"").split("\n").slice(2+u).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};r&&d.states&&(d.states.before=r());var h=e.apply(i,o);return h&&h.promise?h.promise.then(function(){r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))}):(r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))),h}};class D{getApplicationContext(){return{versionName:this.versionName,language:q(),platform:"Web",os:void 0,deviceModel:void 0}}}const q=()=>"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||"";class A{constructor(){this.queue=[]}logEvent(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)}setEventReceiver(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(t=>{e(t)}),this.queue=[])}}const j=(e,t)=>{const n=["string","number","boolean","undefined"],r=typeof e;if(r!==typeof t)return!1;for(const i of n)if(i===r)return e===t;if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;const i=Array.isArray(e),o=Array.isArray(t);if(i!==o)return!1;if(!i||!o){const n=Object.keys(e).sort(),r=Object.keys(t).sort();if(!j(n,r))return!1;let i=!0;return Object.keys(e).forEach(n=>{j(e[n],t[n])||(i=!1)}),i}for(let n=0;n<e.length;n++)if(!j(e[n],t[n]))return!1;return!0};Object.entries||(Object.entries=function(e){const t=Object.keys(e);let n=t.length;const r=new Array(n);for(;n--;)r[n]=[t[n],e[t[n]]];return r});class B{constructor(){this.identity={userProperties:{}},this.listeners=new Set}editIdentity(){const e=this,t=Object.assign({},this.identity.userProperties),n=Object.assign(Object.assign({},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(e){return n.optOut=e,this},updateUserProperties:function(e){let t=n.userProperties||{};for(const[n,r]of Object.entries(e))switch(n){case"$set":for(const[e,n]of Object.entries(r))t[e]=n;break;case"$unset":for(const e of Object.keys(r))delete t[e];break;case"$clearAll":t={}}return n.userProperties=t,this},commit:function(){return e.setIdentity(n),this}}}getIdentity(){return Object.assign({},this.identity)}setIdentity(e){const t=Object.assign({},this.identity);this.identity=Object.assign({},e),j(t,this.identity)||this.listeners.forEach(t=>{t(e)})}addIdentityListener(e){this.listeners.add(e)}removeIdentityListener(e){this.listeners.delete(e)}}const N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self;class U{constructor(){this.identityStore=new B,this.eventBridge=new A,this.applicationContextProvider=new D}static getInstance(e){return N.analyticsConnectorInstances||(N.analyticsConnectorInstances={}),N.analyticsConnectorInstances[e]||(N.analyticsConnectorInstances[e]=new U),N.analyticsConnectorInstances[e]}}var W=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},z=function(){function e(){}return e.prototype.send=function(e,t,n){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,r,i,o,s,a,l,c,u,d,v,g,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 h.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!==(r=e.server_upload_time)&&void 0!==r?r:0}};case h.Invalid:return{status:P,statusCode:E,body:{error:null!==(i=e.error)&&void 0!==i?i:"",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!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(d=e.silenced_devices)&&void 0!==d?d:[],silencedEvents:null!==(v=e.silenced_events)&&void 0!==v?v:[],throttledDevices:null!==(g=e.throttled_devices)&&void 0!==g?g:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case h.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case h.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 h.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?h.Success:429===e?h.RateLimit:413===e?h.PayloadTooLarge:408===e?h.Timeout:e>=400&&e<500?h.Invalid:e>=500?h.Failed:h.Unknown},e}(),K=function(e){function t(t){void 0===t&&(t={});var n=e.call(this)||this;return n.customHeaders=t,n}return n(t,e),t.prototype.send=function(e,t){return a(this,void 0,void 0,function(){var n,r,i;return l(this,function(s){switch(s.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:o({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(r=s.sent()).text()];case 2:i=s.sent();try{return[2,this.buildResponse(JSON.parse(i))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}})})},t}(z),H=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t;try{this.isSupported="undefined"!=typeof localStorage}catch(e){this.logger.debug("Remote config localstorage failed to access: ",e),this.isSupported=!1}}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};if(!this.isSupported)return Promise.resolve(t);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(P(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){if(!this.isSupported)return Promise.resolve(!1);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}();var G,Q=401,J=403,$=429,Z=function(){function e(t,n,r,i,o,s,a){void 0===r&&(r="US"),void 0===s&&(s=e.DEFAULT_CONFIG_GROUP),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=t,this.configGroup=s,this.serverUrl=i||("US"===r?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=n,this.storage=a||new H(t,n),this.customFetch=o}return e.prototype.subscribe=function(e,t,n){var r=m(),i={id:r,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(i),"all"===t?this.subscribeAll(i):this.subscribeWaitForRemote(i,t.timeout),r},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 a(this,void 0,void 0,function(){var e,t=this;return l(this,function(n){switch(n.label){case 0:return this.lastSuccessfulFetch&&Date.now()-this.lastSuccessfulFetch<3e5?(this.logger.debug("Remote config client skipping updateConfigs: Too recent"),[2]):[4,this.getOrCreateFetchPromise()];case 1:return e=n.sent(),this.storage.setConfig(e),this.callbackInfos.forEach(function(n){t.sendCallback(n,e,"remote")}),[2]}})})},e.prototype.getOrCreateFetchPromise=function(){var e=this;return this.fetchPromise?this.fetchPromise:this.isLastFetchInvalidApiKey?(this.logger.debug("Remote config client skipping fetch: Invalid API key"),this.fetchPromise=Promise.resolve({remoteConfig:null,lastFetch:new Date}).finally(function(){e.fetchPromise=null}),this.fetchPromise):(this.fetchPromise=this.fetch().then(function(t){return null!==t.remoteConfig&&(e.lastSuccessfulFetch=Date.now()),t}).finally(function(){e.fetchPromise=null}),this.fetchPromise)},e.prototype.subscribeAll=function(e){return a(this,void 0,void 0,function(){var t,n,r,i=this;return l(this,function(o){switch(o.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){i.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),i.sendCallback(e,t,"remote"),i.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(r=o.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(r))),null!==r.remoteConfig?this.sendCallback(e,r,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return o.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return a(this,void 0,void 0,function(){var n,r;return l(this,function(i){switch(i.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),i.label=1;case 1:return i.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),n])];case 2:return r=i.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,r,"remote"),this.storage.setConfig(r),[3,5];case 3:return i.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!==(r=i.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,r,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,r,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var r;e.lastCallback=new Date,r=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(r,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),a(this,void 0,void 0,function(){var n,r,i,o,s,a,c=this;return l(this,function(u){switch(u.label){case 0:n=t/e,r={remoteConfig:null,lastFetch:new Date},i=function(r){var i,s,a,u,d,h,v,g,f;return l(this,function(l){switch(l.label){case 0:i=!0,s=new AbortController,a=setTimeout(function(){return s.abort()},t),l.label=1;case 1:return l.trys.push([1,10,11,12]),u=o.getUrlParams(),d={Accept:"*/*"},o.customFetch?[4,(p=o.customFetch({url:u,method:"GET",headers:d,signal:s.signal}),m=s.signal,new Promise(function(e,t){var n=function(){var e=new Error("Remote config custom fetch aborted by timeout");e.name="AbortError",t(e)};m.addEventListener("abort",n,{once:!0}),p.then(function(t){m.removeEventListener("abort",n),e(t)},function(e){m.removeEventListener("abort",n),t(e)})}))]:[3,3];case 2:return v=l.sent(),[3,5];case 3:return[4,fetch(u,{method:"GET",headers:d,signal:s.signal})];case 4:v=l.sent(),l.label=5;case 5:return(h=v).ok||h.status>=200&&h.status<300?[3,7]:[4,h.text()];case 6:return g=l.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(h.status,": ").concat(g)),h.status===Q||h.status===J?(o.logger.error("Remote config client fetch failed with ".concat(h.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,i=!1):h.status>=400&&h.status<500&&h.status!==$&&(i=!1),[3,9];case 7:return[4,h.json()];case 8:return[2,{value:{remoteConfig:l.sent(),lastFetch:new Date}}];case 9:return[3,12];case 10:return(f=l.sent())instanceof Error&&"AbortError"===f.name?o.logger.debug("Remote config client fetch with retry time ".concat(e," timed out after ").concat(t,"ms")):o.logger.debug("Remote config client fetch with retry time ".concat(e," is rejected because: "),f),[3,12];case 11:return clearTimeout(a),[7];case 12:return i?r<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,14]:[2,"break"];case 13:l.sent(),l.label=14;case 14:return[2]}var p,m})},o=this,s=0,u.label=1;case 1:return s<e?[5,i(s)]:[3,4];case 2:if("object"==typeof(a=u.sent()))return[2,a.value];if("break"===a)return[3,4];u.label=3;case 3:return s++,[3,1];case 4:return[2,r]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var e=encodeURIComponent(this.apiKey),t=new URLSearchParams;return t.append("config_group",this.configGroup),"".concat(this.serverUrl,"/").concat(e,"?").concat(t.toString())},e.DEFAULT_CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(G||(G={}));var V,X="https://app.amplitude.com",Y={US:X,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var ee="__AMPLITUDE_MESSENGER_INSTANCE__",te="__AMPLITUDE_MESSENGER__",ne=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?X:t;this[V]=!0,this.isSetup=!1,this.messageHandler=null,this.requestCallbacks={},this.actionHandlers=new Map,this.pendingMessages=new Map,this.scriptLoadPromises=new Map,this.endpoint=n}return e.prototype.notify=function(e){var t,n,r,i;null===(n=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message sent: ",JSON.stringify(e)),null===(i=null===(r=window.opener)||void 0===r?void 0:r.postMessage)||void 0===i||i.call(r,e,this.endpoint)},e.prototype.sendRequest=function(e,t,n){var r=this;void 0===n&&(n={timeout:15e3});var i="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),o={id:i,action:e,args:t};return new Promise(function(t,s){r.requestCallbacks[i]={resolve:t,reject:s},r.notify(o),n.timeout>0&&setTimeout(function(){s(new Error("".concat(e," timed out (id: ").concat(i,")"))),delete r.requestCallbacks[i]},n.timeout)})},e.prototype.handleResponse=function(e){var t;this.requestCallbacks[e.id]?(this.requestCallbacks[e.id].resolve(e.responseData),delete this.requestCallbacks[e.id]):null===(t=this.logger)||void 0===t||t.warn("No callback found for request id: ".concat(e.id))},e.prototype.registerActionHandler=function(e,t){var n,r,i,o;this.actionHandlers.has(e)&&(null===(o=null===(i=this.logger)||void 0===i?void 0:i.warn)||void 0===o||o.call(i,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var s=this.pendingMessages.get(e);if(s){this.pendingMessages.delete(e);try{for(var a=c(s),l=a.next();!l.done;l=a.next()){t(l.value)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}},e.prototype.loadScriptOnce=function(e){return a(this,void 0,void 0,function(){var t,n,r;return l(this,function(i){switch(i.label){case 0:if(t=this.scriptLoadPromises.get(e))return[2,t];n=function(e){return document.querySelector('script[src="'.concat(CSS.escape(e),'"]'))?Promise.resolve({status:!0}):new Promise(function(t,n){var r;try{var i=document.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.addEventListener("load",function(){t({status:!0})},{once:!0}),i.addEventListener("error",function(){n({status:!1,message:"Failed to load the script ".concat(e)})}),null===(r=document.head)||void 0===r||r.appendChild(i)}catch(e){n(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,n),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,n];case 2:return i.sent(),[3,4];case 3:throw r=i.sent(),this.scriptLoadPromises.delete(e),r;case 4:return[2]}})})},e.prototype.setup=function(e){var t,n,r=this,i=void 0===e?{}:e,o=i.logger,s=i.endpoint;o&&(this.logger=o),s&&this.endpoint===X&&(this.endpoint=s),this.isSetup||(this.isSetup=!0,null===(n=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Setting up messenger"),this.messageHandler=function(e){var t,n,i,o,s;if(null===(n=null===(t=r.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message received: ",JSON.stringify(e)),r.endpoint===e.origin){var a=e.data,l=null==a?void 0:a.action;if(l)if("id"in a&&a.id)null===(o=null===(i=r.logger)||void 0===i?void 0:i.debug)||void 0===o||o.call(i,"Received Response to previous request: ",JSON.stringify(e)),r.handleResponse(a);else{if("ping"===l)return void r.notify({action:"pong"});var c=r.actionHandlers.get(l);if(c)c(a.data);else{var u=null!==(s=r.pendingMessages.get(l))&&void 0!==s?s:[];u.push(a.data),r.pendingMessages.set(l,u)}}}},window.addEventListener("message",this.messageHandler),this.notify({action:"page-loaded"}))},e.prototype.destroy=function(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.isSetup=!1,this.actionHandlers.clear(),this.pendingMessages.clear(),this.requestCallbacks={},this.scriptLoadPromises.clear();var e=f();(null==e?void 0:e[te])===this&&delete e[te]},e}();function re(e){var t,n=f(),r=null==n?void 0:n[te];if("object"==typeof(t=r)&&null!==t&&ee in t&&!0===t[ee])return r;var i=new ne(e);return n&&(n[te]=i),i}V=ee;var ie=["desktop","tablet","mobile"],oe="__AMPLITUDE_BACKGROUND_CAPTURE__";function se(e,t){var n,r=e;if(!0!==r[oe]){r[oe]=!0;var i=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.1.0.js.gz",s=null,a=function(t,n){var r,i;"background-capture-complete"===t&&(null===(i=null===(r=e.logger)||void 0===r?void 0:r.debug)||void 0===i||i.call(r,"Background capture complete"),e.notify({action:"background-capture-complete",data:n}))};e.registerActionHandler("initialize-background-capture",function(t){var n,r;null===(r=null===(n=e.logger)||void 0===n?void 0:n.debug)||void 0===r||r.call(n,"Initializing background capture (external script)");var l=new URL(i,e.endpoint).toString(),c=t&&"object"==typeof t?function(e){if("string"==typeof e)return ie.includes(e)?e:void 0}(t.deviceMode):void 0;e.loadScriptOnce(l).then(function(){var t,n,r;null===(n=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Background capture script loaded (external)"),s=null===(r=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===r?void 0:r.call(window,o({messenger:e,onBackgroundCapture:a},void 0!==c?{initialDeviceMode:c}:{})),e.notify({action:"background-capture-loaded"})}).catch(function(){var t;null===(t=e.logger)||void 0===t||t.warn("Failed to initialize background capture")})}),e.registerActionHandler("close-background-capture",function(){var e;null===(e=null==s?void 0:s.close)||void 0===e||e.call(s),s=null})}}var ae,le="[Amplitude]",ce="".concat(le," Session Replay ID"),ue=G.US,de={enabled:!0},he=1e3,ve="".concat(le," Session Replay Debug"),ge="https://api-sr.amplitude.com/sessions/v2/track",fe="https://api-sr.eu.amplitude.com/sessions/v2/track",pe="https://api-sr.stag2.amplitude.com/sessions/v2/track",me=9e6,ye=/payload.*exceed/i,be=500,Se=1e4,Ie=1024,we="X-Session-Replay-Event-Skipped",Ce="amplitude-sr-iframe";!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",e.REPLAY_GATE_DECISION="replay-gate-decision"}(ae||(ae={}));var Ee=function(){function e(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}return e.prototype.getSafeMethod=function(e){var t;if(!this.logger)return function(){};var n=this.logger[e];return"function"==typeof n?(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger):function(){}},e.prototype.enable=function(e){this.logger.enable(e)},e.prototype.disable=function(){this.logger.disable()},e}(),Pe="medium";var ke=new Map,xe=function(e){var t=ke.get(e);if(t)return t;var n="\0TRAIL\0",r="\0MID\0",i="\0DS\0",o="\0ST\0",s="\0QU\0",a=e;a=(a=(a=(a=(a=(a=(a=(a=(a=(a=(a=a.replace(/\/\*\*$/,n)).replace(/\/\*\*\//g,r)).replace(/\*\*/g,i)).replace(/\*/g,o)).replace(/\?/g,s)).replace(/[.+^${}()|[\]\\]/g,"\\$&")).split(n).join("(/.*)?")).split(r).join("/(.*\\/)?")).split(i).join(".*")).split(o).join(".*")).split(s).join(".");var l=new RegExp("^".concat(a,"$"));return ke.set(e,l),l},Me=function(e,t,n){switch(t){case"light":if("input"!==e)return!1;var r=n?function(e){var t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!r&&(!!["password","hidden","email","tel"].includes(r)||!!n.autocomplete.startsWith("cc-"));case"medium":return"input"===e;case"conservative":return!0;default:return Me(e,Pe,n)}},Te=function(e,t){var n,r,i;if(e&&t.urlMaskLevels)try{for(var o=c(t.urlMaskLevels),s=o.next();!s.done;s=o.next()){var a=s.value;if(xe(a.match).test(e))return a.maskLevel}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null!==(i=t.defaultMaskLevel)&&void 0!==i?i:Pe},Oe=function(e,t,n,r){var i,o;if(void 0===t&&(t={defaultMaskLevel:Pe}),n){if(n.closest(".amp-mask, [data-amp-mask]"))return!0;var s=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some(function(e){return n.closest(e)});if(s)return!0;if(n.closest(".amp-unmask, [data-amp-unmask]"))return!1;var a=(null!==(o=t.unmaskSelector)&&void 0!==o?o:[]).some(function(e){return n.closest(e)});if(a)return!1}return Me(e,Te(r,t),n)},Re=function(e,t,n){return function(r,i){return Oe(e,t,i,null==n?void 0:n())?r.replace(/[^\s]/g,"*"):r}},_e=function(e,t){return function(n,r,i){var o;if("style"===n)return r;if(!(null!==(o=null==e?void 0:e.maskAttributes)&&void 0!==o?o:[]).includes(n))return r;var s=["INPUT","SELECT","TEXTAREA"].includes(i.tagName)?"input":"text";return Oe(s,e,i,null==t?void 0:t())?r.replace(/[^\s]/g,"*"):r}},Le=function(e){var t=null==e?void 0:e.blockSelector;return d(d([],u("string"==typeof t?t?[t]:[]:null!=t?t:[]),!1),["[data-amp-block]"],!1).join(",")},Fe=function(e,t){var n,r;return e&&("conservative"===Te(t,e)||"conservative"===e.defaultMaskLevel||(null===(n=e.urlMaskLevels)||void 0===n?void 0:n.some(function(e){return"conservative"===e.maskLevel})))?"*":d(d([],u(null!==(r=null==e?void 0:e.maskSelector)&&void 0!==r?r:[]),!1),["[data-amp-mask]"],!1).join(",")};function De(e,t){return t||("STAGING"===e?pe:"EU"===e?fe:ge)}var qe=function(){var e=f();return(null==e?void 0:e.location)?e.location.href:""},Ae=function(e,t){var n,r;try{for(var i=c(t),o=i.next();!o.done;o=i.next()){var s=o.value,a=xe(s.selector);if(a.test(e))return e.replace(a,s.replacement)}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return e},je=function(){return a(void 0,void 0,void 0,function(){var e,t,n,r,i,o,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),(e=f())?[4,e.navigator.storage.estimate()]:[3,2];case 1:return t=a.sent(),n=t.usage,r=t.quota,i=t.usageDetails,o=n?Math.round(n/Ie):0,s=n&&r?Math.round(1e3*(n/r+Number.EPSILON))/1e3:0,[2,{totalStorageSize:o,percentOfQuota:s,usageDetails:JSON.stringify(i)}];case 2:return[3,4];case 3:return a.sent(),[3,4];case 4:return[2,{totalStorageSize:0,percentOfQuota:0,usageDetails:""}]}})})},Be=function(e){var t=o({},e),n=t.apiKey;return t.apiKey="****".concat(n.substring(n.length-4)),t},Ne=function(){return{flushMaxRetries:2,logLevel:C.Warn,loggerProvider:new M,transportProvider:new K}},Ue=function(e){function t(t,n){var r,i,s,a,l,c,h,v,g,f,p,m,y,b,S=this,I=Ne();(S=e.call(this,o(o({transportProvider:I.transportProvider,loggerProvider:new Ee(n.loggerProvider||I.loggerProvider)},n),{apiKey:t}))||this).flushMaxRetries=void 0!==n.flushMaxRetries&&n.flushMaxRetries<=I.flushMaxRetries?n.flushMaxRetries:I.flushMaxRetries,S.apiKey=t,S.sampleRate=n.sampleRate||0,S.serverZone=n.serverZone||ue,S.configServerUrl=n.configServerUrl,S.trackServerUrl=n.trackServerUrl,S.shouldInlineStylesheet=n.shouldInlineStylesheet,S.inlineImages=n.inlineImages,S.version=n.version,S.performanceConfig=n.performanceConfig||de,S.storeType=null!==(r=n.storeType)&&void 0!==r?r:"memory",S.applyBackgroundColorToBlockedElements=null!==(i=n.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,S.enableUrlChangePolling=null!==(s=n.enableUrlChangePolling)&&void 0!==s&&s,S.urlChangePollingInterval=null!==(a=n.urlChangePollingInterval)&&void 0!==a?a:he,S.captureDocumentTitle=null!==(l=n.captureDocumentTitle)&&void 0!==l&&l,void 0!==n.fullSnapshotIntervalMs&&(S.fullSnapshotIntervalMs=n.fullSnapshotIntervalMs),void 0!==n.eagerFullSnapshotSend&&(S.eagerFullSnapshotSend=n.eagerFullSnapshotSend),S.captureFullSnapshotOnFocus=null!==(c=n.captureFullSnapshotOnFocus)&&void 0!==c&&c,void 0!==n.maxPersistedEventsSizeBytes&&(S.maxPersistedEventsSizeBytes=Ge(n.maxPersistedEventsSizeBytes,ze,Ke,"maxPersistedEventsSizeBytes",S.loggerProvider)),void 0!==n.maxSingleEventSizeBytes&&(S.maxSingleEventSizeBytes=Ge(n.maxSingleEventSizeBytes,ze,He,"maxSingleEventSizeBytes",S.loggerProvider)),S.privacyConfig=o(o({},null!==(h=n.privacyConfig)&&void 0!==h?h:{}),{unmaskSelector:Array.from(new Set(d([".".concat("amp-unmask")],u(null!==(g=null===(v=n.privacyConfig)||void 0===v?void 0:v.unmaskSelector)&&void 0!==g?g:[]),!1)))}),n.interactionConfig&&(S.interactionConfig=n.interactionConfig,S.interactionConfig.ugcFilterRules&&function(e){if(!e.every(function(e){return"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(function(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")}(S.interactionConfig.ugcFilterRules)),n.debugMode&&(S.debugMode=n.debugMode);var w=n;return S.useWebWorker=null===(m=null!==(f=n.useWebWorker)&&void 0!==f?f:null===(p=w.experimental)||void 0===p?void 0:p.useWebWorker)||void 0===m||m,S.enableTransportCompression=null===(y=n.enableTransportCompression)||void 0===y||y,S.sendTimeoutMs=n.sendTimeoutMs,S.captureAdoptedStyleSheets=null===(b=n.captureAdoptedStyleSheets)||void 0===b||b,n.crossOriginIframes&&(S.crossOriginIframes=n.crossOriginIframes),n.flushIntervalConfig?S.flushIntervalConfig=function(e,t){var n,r,i={};void 0!==e.minIntervalMs&&(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<We?(t.warn("flushIntervalConfig.minIntervalMs ".concat(e.minIntervalMs," is below floor ").concat(We,"ms; clamping.")),i.minIntervalMs=We):i.minIntervalMs=e.minIntervalMs);void 0!==e.maxIntervalMs&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<We?(t.warn("flushIntervalConfig.maxIntervalMs ".concat(e.maxIntervalMs," is below floor ").concat(We,"ms; clamping.")),i.maxIntervalMs=We):i.maxIntervalMs=e.maxIntervalMs);if(void 0!==i.minIntervalMs||void 0!==i.maxIntervalMs){var o=null!==(n=i.minIntervalMs)&&void 0!==n?n:be,s=null!==(r=i.maxIntervalMs)&&void 0!==r?r:Se;s<o&&(void 0===i.maxIntervalMs?(t.warn("flushIntervalConfig.minIntervalMs (".concat(o,") exceeds the default maxIntervalMs (").concat(Se,"); raising max to match min.")),i.maxIntervalMs=o):void 0===i.minIntervalMs?(t.warn("flushIntervalConfig.maxIntervalMs (".concat(s,") is below the default minIntervalMs (").concat(be,"); lowering min to match max.")),i.minIntervalMs=s):(t.warn("flushIntervalConfig.maxIntervalMs (".concat(i.maxIntervalMs,") is less than minIntervalMs (").concat(i.minIntervalMs,"); raising max to match min.")),i.maxIntervalMs=i.minIntervalMs))}return i}(n.flushIntervalConfig,S.loggerProvider):S.flushIntervalConfig={minIntervalMs:1e3,maxIntervalMs:1e4},S.handleSendEvents=n.handleSendEvents,S.handleFetchConfig=n.handleFetchConfig,S}return n(t,e),t}(R),We=100,ze=1e3,Ke=8e6,He=1e7;function Ge(e,t,n,r,i){if(Number.isFinite(e))return e<t?(i.warn("".concat(r," ").concat(e," is below floor ").concat(t,"; clamping.")),t):e>n?(i.warn("".concat(r," ").concat(e," exceeds ceiling ").concat(n,"; clamping.")),n):e;i.warn("".concat(r," value is not a finite number (got ").concat(String(e),"); ignoring."))}var Qe=(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))(Qe||{}),Je=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(Je||{}),$e=(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))($e||{}),Ze=function(e,t){var n=document.createDocumentFragment();return function(e,t,n){var r,i,s=o({},e);try{for(var a=c(["blockSelector","maskSelector","unmaskSelector"]),l=a.next();!l.done;l=a.next()){var u=l.value,d=e[u],h=("string"==typeof d?[d]:null!=d?d:[]).filter(function(e){try{return t(e),!0}catch(t){if(!n)throw new Error("Invalid privacy selector: ".concat(e));return n(e),!1}});s[u]=h.length?h:void 0}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}return s}(e,function(e){n.querySelector(e)},function(e){t.warn('[session-replay-browser] omitting selector "'.concat(e,'" because it is invalid'))})},Ve=function(){function e(e,t){this.localConfig=t,this.remoteConfigClient=e}return e.prototype.generateJoinedConfig=function(){var e,t,n,r,i,s,h;return a(this,void 0,void 0,function(){var a,v,g,f,p,m,y,b,S,I,w,C,E,P,k,x,M,T=this;return l(this,function(l){switch(l.label){case 0:(a=o({},this.localConfig)).optOut=this.localConfig.optOut,a.captureEnabled=!0,l.label=1;case 1:return l.trys.push([1,3,,4]),[4,new Promise(function(e,t){T.remoteConfigClient.subscribe("configs.sessionReplay",{timeout:1500},function(n,r){var i;if(T.localConfig.loggerProvider.debug("Session Replay remote configuration received from ".concat(r,":"),JSON.stringify(n,null,2)),n){var o=n,s=o.sr_sampling_config,l=o.sr_privacy_config,c=o.sr_targeting_config,u=null===(i=a.interactionConfig)||void 0===i?void 0:i.ugcFilterRules;a.interactionConfig=o.sr_interaction_config,a.interactionConfig&&u&&(a.interactionConfig.ugcFilterRules=u),a.loggingConfig=o.sr_logging_config,(s||l||c)&&(v={},s&&(v.sr_sampling_config=s),l&&(v.sr_privacy_config=l),c&&(v.sr_targeting_config=c)),e()}else t(new Error("No remote config received"))})})];case 2:return l.sent(),[3,4];case 3:return g=l.sent(),this.localConfig.loggerProvider.error("Failed to generate joined config: ",g),a.captureEnabled=!1,[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:void 0}];case 4:if(!v)return[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:v}];if(f=v.sr_sampling_config,p=v.sr_privacy_config,m=v.sr_targeting_config,f&&Object.keys(f).length>0?(Object.prototype.hasOwnProperty.call(f,"capture_enabled")?a.captureEnabled=f.capture_enabled:a.captureEnabled=!1,Object.prototype.hasOwnProperty.call(f,"sample_rate")&&(a.sampleRate=f.sample_rate),Object.prototype.hasOwnProperty.call(f,"min_session_duration_ms")&&(a.minSessionDurationMs=this.sanitizeMinSessionDurationMs(f.min_session_duration_ms))):(a.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),p){y=null!==(e=a.privacyConfig)&&void 0!==e?e:{},b={defaultMaskLevel:null!==(n=null!==(t=p.defaultMaskLevel)&&void 0!==t?t:y.defaultMaskLevel)&&void 0!==n?n:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:d([],u(new Set(d(d([],u(null!==(r=y.maskAttributes)&&void 0!==r?r:[]),!1),u(null!==(i=p.maskAttributes)&&void 0!==i?i:[]),!1))),!1),urlMaskLevels:d(d([],u(null!==(s=p.urlMaskLevels)&&void 0!==s?s:[]),!1),u(null!==(h=y.urlMaskLevels)&&void 0!==h?h:[]),!1)},S=function(e){var t,n,r,i,o,s,a,l,u,d={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);try{for(var h=c(null!==(a=e.blockSelector)&&void 0!==a?a:[]),v=h.next();!v.done;v=h.next()){d[v.value]="block"}}catch(e){t={error:e}}finally{try{v&&!v.done&&(n=h.return)&&n.call(h)}finally{if(t)throw t.error}}try{for(var g=c(null!==(l=e.maskSelector)&&void 0!==l?l:[]),f=g.next();!f.done;f=g.next()){d[f.value]="mask"}}catch(e){r={error:e}}finally{try{f&&!f.done&&(i=g.return)&&i.call(g)}finally{if(r)throw r.error}}try{for(var p=c(null!==(u=e.unmaskSelector)&&void 0!==u?u:[]),m=p.next();!m.done;m=p.next()){d[m.value]="unmask"}}catch(e){o={error:e}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(o)throw o.error}}return d},I=o(o({},S(y)),S(p));try{for(w=c(Object.entries(I)),C=w.next();!C.done;C=w.next())E=u(C.value,2),P=E[0],"mask"===(k=E[1])?b.maskSelector.push(P):"block"===k?b.blockSelector.push(P):"unmask"===k&&b.unmaskSelector.push(P)}catch(e){x={error:e}}finally{try{C&&!C.done&&(M=w.return)&&M.call(w)}finally{if(x)throw x.error}}a.privacyConfig=Ze(b,this.localConfig.loggerProvider)}return m&&Object.keys(m).length>0&&(a.targetingConfig=m),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:Be(a)},null,2)),[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:v}]}})})},e.prototype.sanitizeMinSessionDurationMs=function(e){if("number"==typeof e&&Number.isFinite(e)){if(!(e<0))return e>Xe?(this.localConfig.loggerProvider.warn("min_session_duration_ms remote value ".concat(e," exceeds ").concat(Xe,"ms ceiling; clamping.")),Xe):e;this.localConfig.loggerProvider.warn("min_session_duration_ms remote value is negative (".concat(e,"); ignoring."))}else this.localConfig.loggerProvider.warn("min_session_duration_ms remote value is not a finite number (got ".concat(String(e),"); ignoring."))},e}(),Xe=6e4,Ye=function(e,t){return a(void 0,void 0,void 0,function(){var n,r;return l(this,function(i){return n=new Ue(e,t),r=new Z(e,n.loggerProvider,n.serverZone,t.configServerUrl,t.handleFetchConfig),[2,new Ve(r,n)]})})};function et(e){for(var t=e.length,n=0;n<t&&!(e.charCodeAt(n)>127);n++);if(n===t)return t;for(var r=n;n<t;n++){var i=e.charCodeAt(n);if(i<=127)r++;else if(i<=2047)r+=2;else if(i>=55296&&i<=56319){var o=n+1<t?e.charCodeAt(n+1):NaN;o>=56320&&o<=57343?(r+=4,n++):r+=3}else r+=3}return r}function tt(e){for(var t=0,n=0;n<e.length;n++)t+=et(e[n]);return t}function nt(e,t){if(!(3*e.length<=t)){var n=et(e);return n>t?n:void 0}}function rt(e,t){t<0&&(t=0);for(var n=e.length,r=0,i=0;i<n;i++){var o=e.charCodeAt(i),s=1,a=1;if(o<=127)s=1;else if(o<=2047)s=2;else if(o>=55296&&o<=56319){var l=i+1<n?e.charCodeAt(i+1):NaN;l>=56320&&l<=57343?(s=4,a=2):s=3}else s=3;if(r+s>t)break;r+=s,2===a&&i++}return i>=n?{value:e,truncated:!1}:{value:e.slice(0,i),truncated:!0}}function it(e){if(e.type!==Qe.IncrementalSnapshot)return!1;var t=e.data;return t.source===Je.Mutation&&!t.isAttachIframe}function ot(e){var t,n,r=new Map;if(e.forEach(function(e,t){if(e.attributes&&"style"in e.attributes){var n=r.get(e.id);n?n.push(t):r.set(e.id,[t])}}),0===r.size)return e;var i=function(t){return e[t].attributes.style},s=new Set,a=new Map,l=function(e){if(1===e.length)return"continue";var t=-1;e.forEach(function(e,n){var r;("object"!=typeof(r=i(e))||null===r)&&(t=n)});var n=[];if(e.forEach(function(e,r){r!==t&&(s.add(e),r>t&&n.push(e))}),n.length>0){var r=n[n.length-1],o=function(e){var t,n,r,i,o={};try{for(var s=c(e),a=s.next();!a.done;a=s.next()){var l=a.value;try{for(var u=(r=void 0,c(Object.keys(l))),d=u.next();!d.done;d=u.next()){var h=d.value;o[h]=l[h]}}catch(e){r={error:e}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return o}(n.map(function(e){return i(e)}));s.delete(r),a.set(r,o)}};try{for(var u=c(r.values()),d=u.next();!d.done;d=u.next()){l(d.value)}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}if(0===s.size&&0===a.size)return e;var h=[];return e.forEach(function(e,t){var n=a.get(t);if(void 0===n)if(s.has(t)){var r=o({},e.attributes);delete r.style,Object.keys(r).length>0&&h.push(o(o({},e),{attributes:r}))}else h.push(e);else h.push(o(o({},e),{attributes:o(o({},e.attributes),{style:n})}))}),h}function st(e){var t,n,r,i,s=e[0],a=new Map,l=new Map,d=new Map,h=new Map,v=new Map;e.forEach(function(e,t){var n,r,i,o,s=e.data;try{for(var u=c(s.adds),g=u.next();!g.done;g=u.next()){var f=g.value;a.has(f.node.id)||a.set(f.node.id,t),l.set(f.node.id,t),v.set(f.node.id,f.parentId)}}catch(e){n={error:e}}finally{try{g&&!g.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}try{for(var p=c(s.removes),m=p.next();!m.done;m=p.next()){var y=m.value;d.has(y.id)||d.set(y.id,t),h.set(y.id,t)}}catch(e){i={error:e}}finally{try{m&&!m.done&&(o=p.return)&&o.call(p)}finally{if(i)throw i.error}}});var g=new Set,f=new Set;try{for(var p=c(a),m=p.next();!m.done;m=p.next()){var y=u(m.value,2),b=y[0],S=y[1],I=d.get(b);if(void 0!==I)l.get(b)>=h.get(b)||(S<I?g.add(b):I<S&&f.add(b))}}catch(e){t={error:e}}finally{try{m&&!m.done&&(n=p.return)&&n.call(p)}finally{if(t)throw t.error}}var w=new Set;if(g.size>0||f.size>0)for(var C=!0;C;){C=!1;try{for(var E=(r=void 0,c(v)),P=E.next();!P.done;P=E.next()){var k=u(P.value,2),x=k[0],M=k[1];if(!g.has(x)&&!f.has(x)&&!w.has(x)&&(g.has(M)||f.has(M)||w.has(M))){var T=d.get(x),O=a.get(x);void 0!==T&&void 0!==O&&T<O?f.add(x):void 0!==T&&void 0!==O&&T===O?w.add(x):g.add(x),C=!0}}}catch(e){r={error:e}}finally{try{P&&!P.done&&(i=E.return)&&i.call(E)}finally{if(r)throw r.error}}}var R=g.size>0||f.size>0||w.size>0,_=[];e.forEach(function(e,t){var n,r;try{for(var i=c(e.data.removes),o=i.next();!o.done;o=i.next()){var s=o.value;g.has(s.id)||(f.has(s.id)&&t>=a.get(s.id)||w.has(s.id)&&(g.has(s.parentId)||f.has(s.parentId)||w.has(s.parentId))||_.push(s))}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}});var L=e.flatMap(function(e){return e.data.adds}),F=e.flatMap(function(e){return e.data.texts}),D=e.flatMap(function(e){return e.data.attributes}),q=R?D.filter(function(e){return!g.has(e.id)&&!f.has(e.id)&&!w.has(e.id)}):D,A={source:Je.Mutation,removes:_,adds:R?L.filter(function(e){return!g.has(e.node.id)&&!f.has(e.node.id)&&!w.has(e.node.id)}):L,texts:R?F.filter(function(e){return!g.has(e.id)&&!f.has(e.id)&&!w.has(e.id)}):F,attributes:ot(q)};return o(o({},s),{data:A})}function at(e){if(e.length<=1)return e;for(var t=[],n=0;n<e.length;)if(it(e[n])){for(var r=n+1;r<e.length&&it(e[r]);)r++;t.push(r>n+1?st(e.slice(n,r)):e[n]),n=r}else t.push(e[n]),n++;return t}var lt=function(){function e(e,t,n,r,i){var o,s=this;this.taskQueue=[],this.pendingQueue=[],this.isProcessing=!1,this.compressEvent=function(e){var t=e,n=t.type,r=t.timestamp,i=t.delay,o=t.data;return null!=i?JSON.stringify({type:n,timestamp:r,delay:i,data:o}):JSON.stringify({type:n,timestamp:r,data:o})},this.addCompressedEventToManager=function(e,t){var n,r=nt(e,null!==(n=s.config.maxSingleEventSizeBytes)&&void 0!==n?n:me);void 0===r?s.eventsManager&&s.deviceId&&s.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:s.deviceId}):s.config.loggerProvider.warn("Session replay event dropped: serialized size ".concat(Math.round(r/1024)," KB exceeds maximum allowed event size. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support."))},this.addCompressedEvent=function(e,t){if(s.worker)try{s.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?s.worker.postMessage(JSON.stringify({event:e,sessionId:t})):s.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{var n=s.compressEvent(e);s.addCompressedEventToManager(n,t)}},this.flushQueue=function(){var e;for(s.pendingQueue.length>0&&(e=s.taskQueue).push.apply(e,d([],u(s.mergeMutationTasks(s.pendingQueue.splice(0))),!1));s.taskQueue.length>0;){var t=s.taskQueue.shift();if(t){var n=t.event,r=t.sessionId,i=s.compressEvent(n);s.addCompressedEventToManager(i,r)}}s.isProcessing=!1},this.terminate=function(){var e;null===(e=s.worker)||void 0===e||e.terminate()};var a=f();if(this.canUseIdleCallback=a&&"requestIdleCallback"in a,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(o=t.performanceConfig)||void 0===o?void 0:o.timeout)||2e3,this.onFullSnapshotProcessed=i,r){t.loggerProvider.log("Enabling web worker for compression");try{var l=new Blob([r],{type:"application/javascript"}),c=URL.createObjectURL(l),h=new Worker(c);h.onerror=function(e){e.preventDefault(),t.loggerProvider.error("Worker failed, falling back to non-worker compression: ".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")")),h.terminate(),s.worker=void 0},h.onmessage=function(e){var t=e.data,n=t.compressedEvent,r=t.sessionId;s.addCompressedEventToManager(n,r)},this.worker=h}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}return e.prototype.scheduleIdleProcessing=function(){var e=this;this.isProcessing||(this.isProcessing=!0,requestIdleCallback(function(t){e.processQueue(t)},{timeout:this.timeout}))},e.prototype.enqueueEvent=function(e,t){var n,r,i,o;if(e.type===Qe.FullSnapshot){if(this.config.loggerProvider.debug("Processing full snapshot immediately."),this.taskQueue.length>0||this.pendingQueue.length>0){var s=d(d([],u(this.taskQueue.splice(0)),!1),u(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1);try{for(var a=c(s),l=a.next();!l.done;l=a.next()){var h=l.value,v=this.compressEvent(h.event);this.addCompressedEventToManager(v,h.sessionId)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this.isProcessing=!1}var g=this.compressEvent(e);return this.addCompressedEventToManager(g,t),void(null===(i=this.onFullSnapshotProcessed)||void 0===i||i.call(this))}this.canUseIdleCallback&&(null===(o=this.config.performanceConfig)||void 0===o?void 0:o.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.pendingQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))},e.prototype.processQueue=function(e){var t,n=this;for(this.pendingQueue.length>0&&(t=this.taskQueue).push.apply(t,d([],u(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1));this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){var r=this.taskQueue.shift();if(r){var i=r.event,o=r.sessionId;this.addCompressedEvent(i,o)}}this.taskQueue.length>0||this.pendingQueue.length>0?requestIdleCallback(function(e){n.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1},e.prototype.mergeMutationTasks=function(e){var t,n,r;if(!1===(null===(r=this.config.performanceConfig)||void 0===r?void 0:r.mergeMutations))return e;if(e.length<=1)return e;for(var i=[],o=0;o<e.length;){for(var s=e[o].sessionId,a=o+1;a<e.length&&e[a].sessionId===s;)a++;var l=at(e.slice(o,a).map(function(e){return e.event}));try{for(var u=(t=void 0,c(l)),d=u.next();!d.done;d=u.next()){var h=d.value;i.push({event:h,sessionId:s})}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}o=a}return i},e}(),ct="Session replay event batch rejected due to exceeded retry count",ut="Failed to store session replay events in IndexedDB",dt="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",ht="1.51.5";function vt(e,t){return a(this,void 0,void 0,function(){var n,r,i,o,s,u,d,h,v,g,f,p,m,y,b=this;return l(this,function(S){switch(S.label){case 0:return S.trys.push([0,4,,5]),n=t.CompressionStream,r=new n("gzip"),i=r.writable.getWriter(),o=r.readable.getReader(),s=[],u=a(b,void 0,void 0,function(){var e,t,n;return l(this,function(r){switch(r.label){case 0:return[4,o.read()];case 1:if(e=r.sent(),t=e.done,n=e.value,t)return[3,3];s.push(n),r.label=2;case 2:return[3,0];case 3:return[2]}})}),[4,i.write((new TextEncoder).encode(e))];case 1:return S.sent(),[4,i.close()];case 2:return S.sent(),[4,u];case 3:S.sent(),d=s.reduce(function(e,t){return e+t.length},0),h=new Uint8Array(d),v=0;try{for(g=c(s),f=g.next();!f.done;f=g.next())p=f.value,h.set(p,v),v+=p.length}catch(e){m={error:e}}finally{try{f&&!f.done&&(y=g.return)&&y.call(g)}finally{if(m)throw m.error}}return[2,h];case 4:return S.sent(),[2,null];case 5:return[2]}})})}var gt=function(){function e(e){var t=e.trackServerUrl,n=e.loggerProvider,r=e.payloadBatcher,i=e.workerScript,o=e.enableTransportCompression,s=e.sendTimeoutMs,a=e.handleSendEvents,l=this;if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.timedOutWorkerRequests=new Map,this.flushPauseUntilMs=0,this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,this.mergeLogFiredThisPause=!1,this.killedSessions=new Set,this.loggerProvider=n,this.payloadBatcher=r||function(e){return e},this.trackServerUrl=t,this.enableTransportCompression=null==o||o,this.sendTimeoutMs=null!=s?s:1e4,this.handleSendEvents=a,i)try{var d=new Blob([i],{type:"application/javascript"}),h=URL.createObjectURL(d),v=new Worker(h);v.onerror=function(e){var t,r;e.preventDefault(),n.error("Track destination worker failed, falling back to main-thread sending: ".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")")),v.terminate(),l.worker=void 0;try{for(var i=c(l.pendingWorkerRequests),o=i.next();!o.done;o=i.next()){var s=u(o.value,2)[1];s.timeout&&clearTimeout(s.timeout),n.warn("Session replay event send failed due to worker crash: ".concat(e.message)),s.resolve()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}l.pendingWorkerRequests.clear(),l.timedOutWorkerRequests.clear()},v.onmessage=function(e){var t=e.data;if("log"===t.type)n.log(t.message);else if("warn"===t.type)n.warn(t.message);else if("payload_too_large"===t.type){var r=l.pendingWorkerRequests.get(t.id);if(r)r.timeout&&clearTimeout(r.timeout),l.handlePayloadTooLargeResponse(r.context,t.isWaf),r.resolve(),l.pendingWorkerRequests.delete(t.id);else(i=l.timedOutWorkerRequests.get(t.id))&&(l.timedOutWorkerRequests.delete(t.id),l.handlePayloadTooLargeResponse(i,t.isWaf))}else if("complete"===t.type){var i,o=l.pendingWorkerRequests.get(t.id);if(o)o.timeout&&clearTimeout(o.timeout),void 0!==t.skipCode&&l.applyServerDirective(o.context.sessionId,t.skipCode),l.completeRequest({context:o.context}),o.resolve(),l.pendingWorkerRequests.delete(t.id);else(i=l.timedOutWorkerRequests.get(t.id))&&(l.timedOutWorkerRequests.delete(t.id),void 0!==t.skipCode&&l.applyServerDirective(i.sessionId,t.skipCode),l.completeRequest({context:i}))}else"fetch-request"===t.type&&l.handleDelegatedFetch(v,t).catch(function(e){n.warn("Failed to handle delegated session replay fetch:",e)})},this.worker=v}catch(e){n.error("Failed to create track destination worker, falling back to main-thread sending:",e)}}return e.prototype.sendEventsList=function(e){this.addToQueue(o(o({},e),{attempts:0,timeout:0}))},e.prototype.markCoalesceNextFlush=function(){this.coalesceNextFlush=!0,this.schedule(0)},e.prototype.sendBeacon=function(e){var t,n,r=this,i=e.events,o=e.sessionId,s=e.deviceId,a=e.apiKey,l=e.serverZone,c=function(e){return et(e)},u=i,d=JSON.stringify({version:2,events:u});if(c(d)>65536){for(var h=0,v=u.length;h<v;){var g=Math.floor((h+v+1)/2);c(JSON.stringify({version:2,events:u.slice(0,g)}))<=65536?h=g:v=g-1}u=u.slice(0,h),d=JSON.stringify({version:2,events:u}),this.loggerProvider.warn("sendBeacon payload exceeded 64 KB limit, trimmed from ".concat(i.length," to ").concat(u.length," events"))}if(0!==u.length)if(this.handleSendEvents){var p=new URLSearchParams({device_id:s,session_id:String(o),type:"replay"}),m="".concat(De(l,this.trackServerUrl),"?").concat(p.toString()),y={"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(a)};this.loggerProvider.debug("Routing session replay exit batch (".concat(u.length," events) through custom transport for session id ").concat(o,"."));try{this.handleSendEvents({url:m,method:"POST",headers:y,body:d,keepalive:!0}).catch(function(e){r.loggerProvider.warn("Custom transport failed to send session replay exit batch:",e)})}catch(e){this.loggerProvider.warn("Custom transport threw while sending session replay exit batch:",e)}}else{var b=new URLSearchParams({device_id:s,session_id:String(o),type:"replay",api_key:a}),S="".concat(De(l,this.trackServerUrl),"?").concat(b.toString()),I=f();try{var w=new Blob([d],{type:"application/json"});!1===(null===(n=null===(t=null==I?void 0:I.navigator)||void 0===t?void 0:t.sendBeacon)||void 0===n?void 0:n.call(t,S,w))&&this.loggerProvider.warn("sendBeacon failed to queue session replay payload")}catch(e){}}},e.prototype.addToQueue=function(){for(var e=this,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];t.filter(function(t){return e.killedSessions.has(t.sessionId)?(e.completeRequest({context:t,err:dt}),!1):t.attempts<(t.flushMaxRetries||0)?(t.attempts+=1,!0):(e.completeRequest({context:t,err:ct}),!1)}).forEach(function(t){e.queue=e.queue.concat(t),e.schedule(0)})},e.prototype.schedule=function(e){var t=this;if(!this.scheduled){var n=this.flushPauseUntilMs-Date.now(),r=n>e?n:e;n>0&&(this.mergeOnNextFlush=!0),this.scheduled=setTimeout(function(){t.flush(!0).then(function(){t.queue.length>0&&t.schedule(e)})},r)}},e.prototype.flush=function(e){return void 0===e&&(e=!1),a(this,void 0,void 0,function(){var t,n,r,i,o,s,a;return l(this,function(l){switch(l.label){case 0:t=this.queue,this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),this.mergeOnNextFlush?(this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,t=this.mergeQueueAfterThrottle(t)):this.coalesceNextFlush&&(this.coalesceNextFlush=!1,t=this.mergeDrainBacklog(t)),l.label=1;case 1:l.trys.push([1,6,7,8]),n=c(t),r=n.next(),l.label=2;case 2:return r.done?[3,5]:(i=r.value,[4,this.send(i,e)]);case 3:l.sent(),l.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=l.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(a=n.return)&&a.call(n)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},e.prototype.mergeQueueAfterThrottle=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&!this.mergeLogFiredThisPause&&(this.mergeLogFiredThisPause=!0,this.loggerProvider.log("Session replay throttle pause ended; merged ".concat(e.length," queued batches into ").concat(t.length," request(s)"))),t},e.prototype.mergeDrainBacklog=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&this.loggerProvider.log("Session replay coalesced ".concat(e.length," persisted page-load backlog batches into ").concat(t.length," request(s)")),t},e.prototype.coalesceByIdentity=function(e){var t,n,r,i,s,h,v,g,f,p,m,y=this;if(e.length<=1)return e;var b=new Map;try{for(var S=c(e),I=S.next();!I.done;I=S.next()){var w=I.value,C=[w.sessionId,null!==(s=w.deviceId)&&void 0!==s?s:"",null!==(h=w.apiKey)&&void 0!==h?h:"",w.type,null!==(v=w.serverZone)&&void 0!==v?v:"",w.sampleRate,null!==(f=null===(g=w.version)||void 0===g?void 0:g.type)&&void 0!==f?f:"",null!==(m=null===(p=w.version)||void 0===p?void 0:p.version)&&void 0!==m?m:""].join("|"),E=b.get(C);E?E.push(w):b.set(C,[w])}}catch(e){t={error:e}}finally{try{I&&!I.done&&(n=S.return)&&n.call(S)}finally{if(t)throw t.error}}var P=[],k=function(e){var t,n;if(1===e.length)return P.push(e[0]),"continue";var r=null,i=0,s=function(){r&&P.push(r),r=null,i=0},h=function(e){var t=tt(e.events);if(null===r)return r=o(o({},e),{events:d([],u(e.events),!1),attempts:0}),i=t,"continue";if(i+t>4e6)return s(),r=o(o({},e),{events:d([],u(e.events),!1),attempts:0}),i=t,"continue";var n=r.onComplete,c=e.onComplete;r.events=r.events.concat(e.events),i+=t,r.onComplete=function(){return a(y,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,Promise.allSettled([n(),c()])];case 1:return e.sent(),[2]}})})}};try{for(var v=(t=void 0,c(e)),g=v.next();!g.done;g=v.next()){h(g.value)}}catch(e){t={error:e}}finally{try{g&&!g.done&&(n=v.return)&&n.call(v)}finally{if(t)throw t.error}}s()};try{for(var x=c(b.values()),M=x.next();!M.done;M=x.next()){k(M.value)}}catch(e){r={error:e}}finally{try{M&&!M.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}return P},e.prototype.send=function(e,t){return void 0===t&&(t=!0),a(this,void 0,void 0,function(){var n,r,i,o;return l(this,function(s){return this.killedSessions.has(e.sessionId)?[2,this.completeRequest({context:e,err:dt})]:(n=e.apiKey)?(r=e.deviceId)?0===(i=this.payloadBatcher({version:1,events:e.events})).events.length?(this.completeRequest({context:e}),[2]):(o=this.worker)?[2,this.sendViaWorker(o,e,i,t)]:[2,this.sendOnMainThread(n,r,e,i,t)]:[2,this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"})]:[2,this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"})]})})},e.prototype.sendViaWorker=function(e,t,n,r){return a(this,void 0,void 0,function(){var i,o=this;return l(this,function(s){return i="".concat(++this.sendIdCounter),[2,new Promise(function(s){var a,l=o.sendTimeoutMs>0?setTimeout(function(){var e=o.pendingWorkerRequests.get(i);e&&(o.pendingWorkerRequests.delete(i),o.rememberTimedOutRequest(i,e.context),o.loggerProvider.warn("Session replay worker send timed out after ".concat(o.sendTimeoutMs,"ms; leaving events for retry")),e.resolve())},o.sendTimeoutMs):void 0;o.pendingWorkerRequests.set(i,{context:t,resolve:s,timeout:l}),e.postMessage({type:"send",id:i,payload:n,useRetry:r,useCustomTransport:!!o.handleSendEvents,context:{apiKey:t.apiKey,deviceId:t.deviceId,sessionId:t.sessionId,events:t.events,eventType:t.type,flushMaxRetries:null!==(a=t.flushMaxRetries)&&void 0!==a?a:0,sampleRate:t.sampleRate,serverZone:t.serverZone,trackServerUrl:o.trackServerUrl,version:t.version,currentUrl:qe(),sdkVersion:ht,enableTransportCompression:o.enableTransportCompression,sendTimeoutMs:o.sendTimeoutMs}})})]})})},e.prototype.rememberTimedOutRequest=function(e,t){var n,r;if(this.timedOutWorkerRequests.set(e,t),this.timedOutWorkerRequests.size>256)try{for(var i=c(this.timedOutWorkerRequests.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;this.timedOutWorkerRequests.delete(s);break}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}},e.prototype.handleDelegatedFetch=function(e,t){var n,r,i;return a(this,void 0,void 0,function(){var o,s,a,c,u,d,h,v,g,f,p;return l(this,function(l){switch(l.label){case 0:o=t.requestId,s=t.url,a=t.method,c=t.headers,u=t.body,d=t.keepalive,l.label=1;case 1:return l.trys.push([1,10,,11]),h=void 0,this.handleSendEvents?[4,this.handleSendEvents({url:s,method:a,headers:c,body:u,keepalive:d})]:[3,3];case 2:return h=l.sent(),[3,5];case 3:return this.loggerProvider.warn("Delegated session replay fetch received without a custom transport configured; falling back to built-in fetch."),[4,fetch(s,{method:a,headers:c,body:u,keepalive:d})];case 4:h=l.sent(),l.label=5;case 5:if(v=h.status,g=null,f="",v>=200&&v<300&&(g=null!==(i=null===(r=null===(n=h.headers)||void 0===n?void 0:n.get)||void 0===r?void 0:r.call(n,we))&&void 0!==i?i:null),413!==v)return[3,9];l.label=6;case 6:return l.trys.push([6,8,,9]),[4,h.text()];case 7:return f=l.sent(),[3,9];case 8:return l.sent(),[3,9];case 9:return this.loggerProvider.debug("Delegated session replay fetch (request ".concat(o,") returned status ").concat(v,".")),e.postMessage({type:"fetch-response",requestId:o,status:v,skipHeader:g,body:f}),[3,11];case 10:return p=l.sent(),this.loggerProvider.debug("Delegated session replay fetch (request ".concat(o,") failed:"),p),e.postMessage({type:"fetch-response",requestId:o,status:0,skipHeader:null,body:String(p),error:!0}),[3,11];case 11:return[2]}})})},e.prototype.sendOnMainThread=function(e,t,n,r,i){var s,c,u,d,h,v,g;return a(this,void 0,void 0,function(){var a,p,m,y,b,S,I,w,C,E,P,k,x,M,T,O,R,_,L,F,D,q;return l(this,function(l){switch(l.label){case 0:a=qe(),p=ht,m=n.sampleRate,y=new URLSearchParams({device_id:t,session_id:"".concat(n.sessionId),type:"".concat(n.type)}),b="".concat(null!==(c=null===(s=n.version)||void 0===s?void 0:s.type)&&void 0!==c?c:"standalone","/").concat(null!==(d=null===(u=n.version)||void 0===u?void 0:u.version)&&void 0!==d?d:p),l.label=1;case 1:return l.trys.push([1,19,,23]),S=JSON.stringify(r),I=f(),this.enableTransportCompression&&I&&"CompressionStream"in I?[4,vt(S,I)]:[3,3];case 2:return C=l.sent(),[3,4];case 3:C=null,l.label=4;case 4:if(E=(w=C)?w.byteLength:et(S),P=new AbortController,k=o({"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(e),"X-Client-Version":p,"X-Client-Library":b,"X-Client-Url":a.substring(0,1e3),"X-Client-Sample-Rate":"".concat(m),"X-Sampling-Hash-Alg":"xxhash32"},w?{"Content-Encoding":"gzip"}:{}),T={headers:k,body:x=null!=w?w:S,method:"POST",keepalive:M=E<=65536,signal:P.signal},O="".concat(De(n.serverZone,this.trackServerUrl),"?").concat(y.toString()),0===r.events.length)return this.completeRequest({context:n}),[2];R=this.sendTimeoutMs>0?setTimeout(function(){P.abort()},this.sendTimeoutMs):void 0,_=void 0,l.label=5;case 5:return l.trys.push([5,,10,11]),this.handleSendEvents?[4,(A=this.handleSendEvents({url:O,method:"POST",headers:k,body:x,keepalive:M}),j=P.signal,new Promise(function(e,t){var n=function(){var e=new Error("Custom session replay transport aborted by send timeout");e.name="AbortError",t(e)};j.addEventListener("abort",n,{once:!0}),A.then(function(t){j.removeEventListener("abort",n),e(t)},function(e){j.removeEventListener("abort",n),t(e)})}))]:[3,7];case 6:return L=l.sent(),[3,9];case 7:return[4,fetch(O,T)];case 8:L=l.sent(),l.label=9;case 9:return _=L,[3,11];case 10:return R&&clearTimeout(R),[7];case 11:if(null===_)return this.completeRequest({context:n,err:"Unexpected error occurred"}),[2];if(_.status>=200&&_.status<300&&(F=null!==(g=null===(v=null===(h=_.headers)||void 0===h?void 0:h.get)||void 0===v?void 0:v.call(h,we))&&void 0!==g?g:null,this.applyServerDirective(n.sessionId,F)),i)return[3,12];D="";try{D=JSON.stringify(_.body,null,2)}catch(e){}return this.completeRequest({context:n,success:"".concat(_.status,": ").concat(D)}),[3,18];case 12:if(D="",413!==_.status)return[3,16];l.label=13;case 13:return l.trys.push([13,15,,16]),[4,_.text()];case 14:return D=l.sent(),[3,16];case 15:return l.sent(),[3,16];case 16:return[4,this.handleReponse(_.status,n,D)];case 17:l.sent(),l.label=18;case 18:return[3,23];case 19:return q=l.sent(),!!q&&"object"==typeof q&&"AbortError"===q.name&&i?[4,this.handleOtherResponse(n)]:[3,21];case 20:return l.sent(),[3,22];case 21:this.completeRequest({context:n,err:q}),l.label=22;case 22:return[3,23];case 23:return[2]}var A,j})})},e.prototype.handleReponse=function(e,t,n){return void 0===n&&(n=""),a(this,void 0,void 0,function(){var r;return l(this,function(i){switch(i.label){case 0:switch(r=(new z).buildStatus(e),r){case h.Success:return[3,1];case h.Failed:case h.Timeout:case h.RateLimit:return[3,2];case h.PayloadTooLarge:return[3,4]}return[3,5];case 1:return this.handleSuccessResponse(t),[3,8];case 2:return[4,this.handleOtherResponse(t)];case 3:return i.sent(),[3,8];case 4:return this.handlePayloadTooLargeResponse(t,ye.test(n)),[3,8];case 5:return 499!==e?[3,7]:[4,this.handleOtherResponse(t)];case 6:return i.sent(),[3,8];case 7:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"}),i.label=8;case 8:return[2]}})})},e.prototype.handlePayloadTooLargeResponse=function(e,t){var n=t?"WAF (compressed payload too large)":"server (event too large)",r=Math.round(e.events.reduce(function(e,t){return e+t.length},0)/Ie);if(t)if(1!==e.events.length){this.loggerProvider.warn("Session replay event batch rejected by ".concat(n," (").concat(e.events.length," events, ").concat(r," KB total) — splitting and retrying")),e.onComplete();var i=function(){return Promise.resolve()},s=Math.floor(e.events.length/2);this.sendEventsList(o(o({},e),{events:e.events.slice(0,s),onComplete:i})),this.sendEventsList(o(o({},e),{events:e.events.slice(s),onComplete:i}))}else this.completeRequest({context:e,err:"Session replay event dropped: single event (".concat(r," KB, 1 event) rejected by ").concat(n," — cannot split further")});else this.completeRequest({context:e,err:"Session replay event batch dropped: ".concat(n," rejected payload (").concat(e.events.length," events, ").concat(r," KB) — not retrying non-WAF 413")})},e.prototype.handleSuccessResponse=function(e){var t=Math.round(tt(e.events)/Ie);this.completeRequest({context:e,success:"Session replay event batch tracked successfully for session id ".concat(e.sessionId,", size of events: ").concat(t," KB")})},e.prototype.handleOtherResponse=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=Math.random()*e.attempts*this.retryTimeout,e.attempts++,e.attempts>(e.flushMaxRetries||0)?(this.completeRequest({context:e,err:ct}),[2]):[4,new Promise(function(e){return setTimeout(e,t)})];case 1:return n.sent(),[4,this.send(e,!0)];case 2:return n.sent(),[2]}})})},e.prototype.completeRequest=function(e){var t=e.context,n=e.err,r=e.success;t.onComplete(),n?this.loggerProvider.warn(n):r&&this.loggerProvider.log(r)},e.prototype.applyServerDirective=function(e,t){if(null===t)return this.flushPauseUntilMs=0,void(this.mergeLogFiredThisPause=!1);if("429"===t){var n=this.flushPauseUntilMs>Date.now();return this.flushPauseUntilMs=Date.now()+6e4,void(n||this.loggerProvider.log("Session replay throttled by server; pausing flush schedule for ".concat(60,"s")))}"4005"!==t&&"4004"!==t||this.killSession(e,t)},e.prototype.killSession=function(e,t){var n,r,i,o;if(!this.killedSessions.has(e)){if(this.killedSessions.add(e),this.killedSessions.size>256)try{for(var s=c(this.killedSessions),a=s.next();!a.done;a=s.next()){var l=a.value;this.killedSessions.delete(l);break}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}this.loggerProvider.log("Session replay capture stopped for session ".concat(e," by server directive ").concat(t,"; remaining events will be dropped"));var u=[];try{for(var d=c(this.queue),h=d.next();!h.done;h=d.next()){var v=h.value;v.sessionId===e?this.completeRequest({context:v,err:dt}):u.push(v)}}catch(e){i={error:e}}finally{try{h&&!h.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}this.queue=u}},e}();const ft=(e,t)=>t.some(t=>e instanceof t);let pt,mt;const yt=new WeakMap,bt=new WeakMap,St=new WeakMap;let It={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return yt.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Pt(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wt(e){It=e(It)}function Ct(e){return(mt||(mt=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(kt(this),t),Pt(this.request)}:function(...t){return Pt(e.apply(kt(this),t))}}function Et(e){return"function"==typeof e?Ct(e):(e instanceof IDBTransaction&&function(e){if(yt.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),r()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});yt.set(e,t)}(e),ft(e,pt||(pt=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,It):e)}function Pt(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(Pt(e.result)),r()},o=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",o)});return St.set(t,e),t}(e);if(bt.has(e))return bt.get(e);const t=Et(e);return t!==e&&(bt.set(e,t),St.set(t,e)),t}const kt=e=>St.get(e);function xt(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=Pt(s);return r&&s.addEventListener("upgradeneeded",e=>{r(Pt(s.result),e.oldVersion,e.newVersion,Pt(s.transaction),e)}),n&&s.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}const Mt=["get","getKey","getAll","getAllKeys","count"],Tt=["put","add","delete","clear"],Ot=new Map;function Rt(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Ot.get(t))return Ot.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=Tt.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!Mt.includes(n))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return r&&(s=s.index(t.shift())),(await Promise.all([s[n](...t),i&&o.done]))[0]};return Ot.set(t,o),o}wt(e=>({...e,get:(t,n,r)=>Rt(t,n)||e.get(t,n,r),has:(t,n)=>!!Rt(t,n)||e.has(t,n)}));const _t=["continue","continuePrimaryKey","advance"],Lt={},Ft=new WeakMap,Dt=new WeakMap,qt={get(e,t){if(!_t.includes(t))return e[t];let n=Lt[t];return n||(n=Lt[t]=function(...e){Ft.set(this,Dt.get(this)[t](...e))}),n}};async function*At(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,qt);for(Dt.set(n,t),St.set(n,kt(t));t;)yield n,t=await(Ft.get(n)||t.continue()),Ft.delete(n)}function jt(e,t){return t===Symbol.asyncIterator&&ft(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&ft(e,[IDBIndex,IDBObjectStore])}wt(e=>({...e,get:(t,n,r)=>jt(t,n)?At:e.get(t,n,r),has:(t,n)=>jt(t,n)||e.has(t,n)}));var Bt=function(){function e(e){var t,n,r,i=this;this.minInterval=be,this.maxInterval=Se,this.maxPersistedEventsSize=6e6,this._timeAtLastSplit=Date.now(),this.eventsContentBytes=new WeakMap,this.sequenceContentBytes=new Map,this.shouldSplitEventsList=function(e,t){var n=i.getEventsArraySize(e),r=i.maxPersistedEventsSize-n,o=t.length>=r;return!o&&3*t.length>=r&&(o=et(t)>=r),!!o||!!(Date.now()-i.timeAtLastSplit>i.interval&&e.length)&&(i.interval=Math.min(i.maxInterval,i.interval+i.minInterval),i._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!==(r=e.maxPersistedEventsSize)&&void 0!==r?r:this.maxPersistedEventsSize,this.interval=this.minInterval}return Object.defineProperty(e.prototype,"timeAtLastSplit",{get:function(){return this._timeAtLastSplit},enumerable:!1,configurable:!0}),e.prototype.isPrefixOf=function(e,t){return!(t.length<e.length)&&(0===e.length||t[e.length-1]===e.tail)},e.prototype.measureContentBytes=function(e,t){if(e&&e.length===t.length&&this.isPrefixOf(e,t))return e;var n=0,r=0;e&&this.isPrefixOf(e,t)&&(n=e.contentBytes,r=e.length);for(var i=r;i<t.length;i++)n+=et(t[i]);return{length:t.length,contentBytes:n,tail:t.length>0?t[t.length-1]:void 0}},e.prototype.getEventsContentBytes=function(e){var t=this.measureContentBytes(this.eventsContentBytes.get(e),e);return this.eventsContentBytes.set(e,t),t.contentBytes},e.prototype.getEventsArraySize=function(e){return this.getEventsContentBytes(e)+(2+Math.max(0,e.length-1)+2*e.length)},e.prototype.recallSequenceContentBytes=function(e,t){var n=this.sequenceContentBytes.get(e);n&&n.length===t.length&&this.isPrefixOf(n,t)&&this.eventsContentBytes.set(t,n)},e.prototype.rememberSequenceContentBytes=function(e,t){var n=this.measureContentBytes(this.sequenceContentBytes.get(e),t);this.sequenceContentBytes.set(e,n),this.eventsContentBytes.set(t,n)},e.prototype.forgetSequenceContentBytes=function(e){this.sequenceContentBytes.delete(e)},e}(),Nt=function(e,t,n){var r;"object"==typeof(r=n)&&null!==r&&"AbortError"===r.name?e.debug(t):e.warn(t)};var Ut="sessionCurrentSequence",Wt="sequencesToSend",zt=5e3;function Kt(e,t,n){var r=setTimeout(n,t);return e.then(function(){return clearTimeout(r)},function(){return clearTimeout(r)}),function(){return clearTimeout(r)}}var Ht,Gt,Qt,Jt=function(e){var t,n;return e.objectStoreNames.contains(Ut)||(n=e.createObjectStore(Ut,{keyPath:"sessionId"})),e.objectStoreNames.contains(Wt)||(t=e.createObjectStore(Wt,{keyPath:"sequenceId",autoIncrement:!0})).createIndex("sessionId","sessionId"),{sequencesStore:t,currentSequenceStore:n}},$t=function(e){return a(void 0,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,(n=xt(e,1,{upgrade:Jt}),r=2e3,i="IDB openDB timed out",void 0===i&&(i="IDB operation timed out"),new Promise(function(e,t){var o=setTimeout(function(){return t(new Error("".concat(i," after ").concat(r,"ms")))},r);n.then(function(t){clearTimeout(o),e(t)},function(e){clearTimeout(o),t(e)})}))];case 1:return[2,t.sent()]}var n,r,i})})},Zt=function(e){function t(t){var n,r=this;return(r=e.call(this,t)||this).consecutiveFailures=0,r.hasTriggeredFallback=!1,r.emptyFilteredCount=0,r.getSequencesToSend=function(){return a(r,void 0,void 0,function(){var e,t,n,r,i,o,s,a,c,u,d=this;return l(this,function(l){switch(l.label){case 0:e=!1,t=!1,l.label=1;case 1:return l.trys.push([1,9,,10]),n=[],(r=this.db.transaction("sequencesToSend","readwrite")).done.catch(function(n){e||t||(Nt(d.loggerProvider,"".concat(ut,": ").concat(n),n),d.recordFailure())}),i=Kt(r.done,zt,function(){e||t||(t=!0,Nt(d.loggerProvider,"".concat(ut,": transaction timed out")),d.recordFailure())}),[4,r.store.openCursor()];case 2:o=l.sent(),l.label=3;case 3:return o?(s=o.value,a=s.sessionId,0!==(c=s.events).length?[3,5]:(this.maybeLogEmptyFiltered("getSequencesToSend"),[4,o.delete()])):[3,8];case 4:return l.sent(),[3,6];case 5:n.push({events:c,sequenceId:o.key,sessionId:a}),l.label=6;case 6:return[4,o.continue()];case 7:return o=l.sent(),[3,3];case 8:return this.recordSuccess(),i(),[2,n];case 9:return u=l.sent(),t||(e=!0,Nt(this.loggerProvider,"".concat(ut,": ").concat(u),u),this.recordFailure()),[3,10];case 10:return[2,void 0]}})})},r.storeCurrentSequence=function(e){return a(r,void 0,void 0,function(){var t,n,r,i,a,c,u,d,h=this;return l(this,function(l){switch(l.label){case 0:t=!1,n=!1,l.label=1;case 1:return l.trys.push([1,5,,6]),(r=this.db.transaction([Ut,Wt],"readwrite")).done.catch(function(e){t||n||(Nt(h.loggerProvider,"".concat(ut,": ").concat(e),e),h.recordFailure())}),i=Kt(r.done,zt,function(){t||n||(n=!0,Nt(h.loggerProvider,"".concat(ut,": transaction timed out")),h.recordFailure())}),[4,r.objectStore(Ut).get(e)];case 2:return!(a=l.sent())||a.tabId&&a.tabId!==this.tabId?(i(),[2,void 0]):0===a.events.length?(this.maybeLogEmptyFiltered("storeCurrentSequence"),i(),[2,void 0]):[4,r.objectStore(Wt).put({sessionId:e,events:a.events,tabId:this.tabId})];case 3:return c=l.sent(),[4,r.objectStore(Ut).put({sessionId:e,events:[],tabId:this.tabId})];case 4:return l.sent(),this.rememberSequenceContentBytes(e,[]),this.recordSuccess(),i(),a.tabId,u=s(a,["tabId"]),[2,o(o({},u),{sessionId:e,sequenceId:c})];case 5:return d=l.sent(),this.forgetSequenceContentBytes(e),n||(t=!0,Nt(this.loggerProvider,"".concat(ut,": ").concat(d),d),this.recordFailure()),[3,6];case 6:return[2,void 0]}})})},r.addEventToCurrentSequence=function(e,t){return a(r,void 0,void 0,function(){var n,r,i,o,s,a,c,u,d,h,v,g,f,p,m=this;return l(this,function(l){switch(l.label){case 0:n=!1,r=!1,l.label=1;case 1:return l.trys.push([1,15,,16]),(i=this.db.transaction([Ut,Wt],"readwrite")).done.catch(function(e){n||r||(Nt(m.loggerProvider,"".concat(ut,": ").concat(e),e),m.recordFailure())}),o=Kt(i.done,zt,function(){n||r||(r=!0,Nt(m.loggerProvider,"".concat(ut,": transaction timed out")),m.recordFailure())}),[4,i.objectStore(Ut).get(e)];case 2:return(null==(s=l.sent())?void 0:s.tabId)&&s.tabId!==this.tabId?s.events.length>0?[4,i.objectStore(Wt).put({sessionId:e,events:s.events,tabId:s.tabId})]:[3,4]:[3,6];case 3:l.sent(),l.label=4;case 4:return a=[t],[4,i.objectStore(Ut).put({sessionId:e,events:a,tabId:this.tabId})];case 5:return l.sent(),this.rememberSequenceContentBytes(e,a),this.recordSuccess(),o(),[2,void 0];case 6:return(c=s)?[3,8]:(u=[t],[4,i.objectStore(Ut).put({sessionId:e,events:u,tabId:this.tabId})]);case 7:return l.sent(),this.rememberSequenceContentBytes(e,u),this.recordSuccess(),o(),[2,void 0];case 8:return this.recallSequenceContentBytes(e,c.events),this.shouldSplitEventsList(c.events,t)?[3,10]:(d=c.events.concat(t),[4,i.objectStore(Ut).put({sessionId:e,events:d,tabId:this.tabId})]);case 9:return l.sent(),this.rememberSequenceContentBytes(e,d),this.recordSuccess(),o(),[2,void 0];case 10:return 0!==(h=c.events).length?[3,12]:(this.maybeLogEmptyFiltered("addEventToCurrentSequence"),v=[t],[4,i.objectStore(Ut).put({sessionId:e,events:v,tabId:this.tabId})]);case 11:return l.sent(),this.rememberSequenceContentBytes(e,v),this.recordSuccess(),o(),[2,void 0];case 12:return g=[t],[4,i.objectStore(Ut).put({sessionId:e,events:g,tabId:this.tabId})];case 13:return l.sent(),this.rememberSequenceContentBytes(e,g),[4,i.objectStore(Wt).put({sessionId:e,events:h,tabId:this.tabId})];case 14:return f=l.sent(),this.recordSuccess(),o(),[2,{events:h,sessionId:e,sequenceId:f}];case 15:return p=l.sent(),this.forgetSequenceContentBytes(e),r||(n=!0,Nt(this.loggerProvider,"".concat(ut,": ").concat(p),p),this.recordFailure()),[3,16];case 16:return[2,void 0]}})})},r.storeSendingEvents=function(e,t){return a(r,void 0,void 0,function(){var n,r;return l(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.db.put(Wt,{sessionId:e,events:t,tabId:this.tabId})];case 1:return n=i.sent(),this.recordSuccess(),[2,n];case 2:return r=i.sent(),Nt(this.loggerProvider,"".concat(ut,": ").concat(r),r),this.recordFailure(),[3,3];case 3:return[2,void 0]}})})},r.cleanUpSessionEventsStore=function(e,t){return a(r,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:if(!t)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.db.delete(Wt,t)];case 2:return n.sent(),this.recordSuccess(),[3,4];case 3:return e=n.sent(),Nt(this.loggerProvider,"".concat(ut,": ").concat(e),e),this.recordFailure(),[3,4];case 4:return[2]}})})},r.db=t.db,r.tabId=t.tabId,r.onPersistentFailure=t.onPersistentFailure,r.consecutiveFailureThreshold=null!==(n=t.consecutiveFailureThreshold)&&void 0!==n?n:1,r}return n(t,e),t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug("Filtered empty session replay sequence at ".concat(e," (idb store)"))},t.prototype.recordFailure=function(){var e;this.consecutiveFailures++,!this.hasTriggeredFallback&&this.consecutiveFailures>=this.consecutiveFailureThreshold&&(this.hasTriggeredFallback=!0,null===(e=this.onPersistentFailure)||void 0===e||e.call(this))},t.prototype.recordSuccess=function(){this.consecutiveFailures=0},t.new=function(e,n){var r;return a(this,void 0,void 0,function(){var i,s,a,c,u;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,2,,3]),i="replay"===e?"":"_".concat(e),s="".concat(n.apiKey.substring(0,10),"_amp_session_replay_events").concat(i),[4,$t(s)];case 1:return a=l.sent(),c=null!==(r=n.tabId)&&void 0!==r?r:function(){try{return crypto.randomUUID()}catch(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}(),[2,new t(o(o({},n),{db:a,tabId:c}))];case 2:return u=l.sent(),Nt(n.loggerProvider,"".concat(ut,": ").concat(u),u),[3,3];case 3:return[2]}})})},t.prototype.getCurrentSequenceEvents=function(e){return a(this,void 0,void 0,function(){var t,n,r,i,o,a,u,d;return l(this,function(l){switch(l.label){case 0:return e?[4,this.db.get("sessionCurrentSequence",e)]:[3,2];case 1:return(i=l.sent())?i.tabId&&i.tabId!==this.tabId?[2,void 0]:(i.tabId,[2,[o=s(i,["tabId"])]]):[2,void 0];case 2:t=[],l.label=3;case 3:return l.trys.push([3,8,9,10]),[4,this.db.getAll("sessionCurrentSequence")];case 4:n=c.apply(void 0,[l.sent()]),r=n.next(),l.label=5;case 5:if(r.done)return[3,7];if((i=r.value).tabId&&i.tabId!==this.tabId)return[3,6];i.tabId,o=s(i,["tabId"]),t.push(o),l.label=6;case 6:return r=n.next(),[3,5];case 7:return[3,10];case 8:return a=l.sent(),u={error:a},[3,10];case 9:try{r&&!r.done&&(d=n.return)&&d.call(n)}finally{if(u)throw u.error}return[7];case 10:return[2,t]}})})},t}(Bt),Vt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.finalizedSequences={},t.sequences={},t.sequenceId=0,t.emptyFilteredCount=0,t}return n(t,e),t.prototype.resetCurrentSequence=function(e){this.sequences[e]=[]},t.prototype.addSequence=function(e){var t=this.sequenceId++,n=d([],u(this.sequences[e]),!1);return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}},t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug("Filtered empty session replay sequence at ".concat(e," (in-memory store)"))},t.prototype.getSequencesToSend=function(){return a(this,void 0,void 0,function(){var e,t,n,r,i,o,s,a,d,h;return l(this,function(l){e=[];try{for(t=c(Object.entries(this.finalizedSequences)),n=t.next();!n.done;n=t.next())r=u(n.value,2),i=r[0],o=r[1],s=o.sessionId,0!==(a=o.events).length?e.push({sequenceId:Number(i),sessionId:s,events:a}):(this.maybeLogEmptyFiltered("getSequencesToSend"),delete this.finalizedSequences[Number(i)])}catch(e){d={error:e}}finally{try{n&&!n.done&&(h=t.return)&&h.call(t)}finally{if(d)throw d.error}}return[2,e]})})},t.prototype.storeCurrentSequence=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){return(t=this.sequences[e])?0===t.length?(this.maybeLogEmptyFiltered("storeCurrentSequence"),[2,void 0]):[2,this.addSequence(e)]:[2,void 0]})})},t.prototype.addEventToCurrentSequence=function(e,t){return a(this,void 0,void 0,function(){var n;return l(this,function(r){return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(0===this.sequences[e].length?this.maybeLogEmptyFiltered("addEventToCurrentSequence"):n=this.addSequence(e)),this.sequences[e].push(t),[2,n]})})},t.prototype.storeSendingEvents=function(e,t){return a(this,void 0,void 0,function(){return l(this,function(n){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},[2,this.sequenceId++]})})},t.prototype.cleanUpSessionEventsStore=function(e,t){return a(this,void 0,void 0,function(){return l(this,function(e){return void 0!==t&&delete this.finalizedSequences[t],[2]})})},t}(Bt),Xt=function(e){var t=e.config,n=e.minInterval,r=e.maxInterval,i=e.maxPersistedEventsSize,s=e.type,c=e.payloadBatcher,h=e.storeType,v=e.trackDestinationWorkerScript,g=e.shouldSend;return a(void 0,void 0,void 0,function(){function e(e){return void 0===e&&(e=!1),a(this,void 0,void 0,function(){return l(this,function(t){return[2,p.flush(e)]})})}var f,p,m,y,b,S,I,w,C,E,P,k,x,M,T,O,R;return l(this,function(_){switch(_.label){case 0:return f=null!==(R=t.maxSingleEventSizeBytes)&&void 0!==R?R:me,p=new gt(o(o({},t),{loggerProvider:t.loggerProvider,payloadBatcher:c,workerScript:v})),m=function(){return new Vt({loggerProvider:t.loggerProvider,maxInterval:r,minInterval:n,maxPersistedEventsSize:i})},b=!1,I=function(){return a(void 0,void 0,void 0,function(){var e,n,r;return l(this,function(i){switch(i.label){case 0:return b?(b=!1,t.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store."),y?[4,S.getSequencesToSend()]:[3,2]):[2];case 1:return n=i.sent(),[3,3];case 2:n=void 0,i.label=3;case 3:return e=n,S=m(),e&&y&&(r=y,e.forEach(function(e){x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r})})),[2]}})})},w=function(){return a(void 0,void 0,void 0,function(){var e;return l(this,function(o){switch(o.label){case 0:return[4,Zt.new(s,{loggerProvider:t.loggerProvider,minInterval:n,maxInterval:r,maxPersistedEventsSize:i,apiKey:t.apiKey,onPersistentFailure:function(){I()}})];case 1:return(e=o.sent())?(b=!0,[2,e]):(t.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),[2,m()])}})})},"idb"!==h?[3,2]:[4,w()];case 1:return C=_.sent(),[3,3];case 2:C=m(),_.label=3;case 3:return S=C,E=[],P=0,k=function(e){if(!(e<=P)){var t=Math.min(e-P,E.length);t>0&&(E.splice(0,t),P=e)}},x=function(e){for(var n=e.events,r=e.sessionId,i=e.deviceId,o=e.sequenceId,c=n,u=[],d=0;d<n.length;d++){var h=nt(n[d],f);void 0!==h?(0===u.length&&(c=n.slice(0,d)),u.push(h)):c!==n&&c.push(n[d])}u.length>0&&t.loggerProvider.warn("Dropping ".concat(u.length," oversized event(s) from session replay sequence before send. Sizes: ").concat(u.map(function(e){return"".concat(Math.round(e/1024)," KB")}).join(", "),". If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.")),0!==c.length?(t.debugMode&&je().then(function(e){var n=e.totalStorageSize,r=e.percentOfQuota,i=e.usageDetails;t.loggerProvider.debug("Total storage size: ".concat(n," KB, percentage of quota: ").concat(r,"%, usage details: ").concat(i))}).catch(function(){}),p.sendEventsList({events:c,sessionId:r,flushMaxRetries:t.flushMaxRetries,apiKey:t.apiKey,deviceId:i,sampleRate:t.sampleRate,serverZone:t.serverZone,version:t.version,type:s,onComplete:function(){return a(void 0,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,S.cleanUpSessionEventsStore(r,o)];case 1:return e.sent(),[2]}})})}})):S.cleanUpSessionEventsStore(r,o).catch(function(e){t.loggerProvider.warn("Failed to clean up session replay events store:",e)})},M=function(e){var n=e.sessionId,r=e.deviceId;if(y=r,!g||g()){var i=P+E.length;S.storeCurrentSequence(n).then(function(e){e&&(k(i),x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r}))}).catch(function(e){t.loggerProvider.warn("Failed to get current sequence of session replay events for session:",e)})}},T=function(e){var n=e.deviceId;return a(void 0,void 0,void 0,function(){var e;return l(this,function(r){switch(r.label){case 0:return y=n,[4,S.getSequencesToSend()];case 1:return(null==(e=r.sent())?void 0:e.length)?(t.loggerProvider.log("Draining ".concat(e.length," stored sequence(s) from previous session.")),e.length>1&&p.markCoalesceNextFlush(),e.forEach(function(e){x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}),[2]):[2]}})})},O=function(e){var n=e.event,r=e.sessionId,i=e.deviceId;y=i;var o=!g||g(),s=P+E.length;E.push(n.data),S.addEventToCurrentSequence(r,n.data).then(function(e){if(e){if(!o)return S.cleanUpSessionEventsStore(e.sessionId,e.sequenceId).catch(function(e){t.loggerProvider.warn("Failed to clean up dropped session replay sequence:",e)}),void k(s);k(s),x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})}}).catch(function(e){t.loggerProvider.warn("Failed to add event to session replay capture:",e)})},[2,{sendCurrentSequenceEvents:M,addEvent:O,sendStoredEvents:T,flush:e,getBeaconEvents:function(){return d([],u(E),!1)},dropPendingBeaconEvents:function(){k(P+E.length)},trackDestination:p}]}})})},Yt=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=new Map;e.forEach(function(e){n.set(e.name,e.manager)}),this.managers=n}return e.prototype.sendStoredEvents=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.sendStoredEvents(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e.prototype.addEvent=function(e){var t,n=e.sessionId,r=e.event,i=e.deviceId;null===(t=this.managers.get(r.type))||void 0===t||t.addEvent({sessionId:n,event:r,deviceId:i})},e.prototype.sendCurrentSequenceEvents=function(e){var t=e.sessionId,n=e.deviceId;this.managers.forEach(function(e){e.sendCurrentSequenceEvents({sessionId:t,deviceId:n})})},e.prototype.flush=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.flush(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e}();function en(e,t){if(Qt=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";var n={root:document.body,idName:function(e){return!0},className:function(e){return!0},tagName:function(e){return!0},attr:function(e,t){return!1},seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};Ht=o(o({},n),t),Gt=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Ht.root,n);var r=tn(e,"all",function(){return tn(e,"two",function(){return tn(e,"one",function(){return tn(e,"none")})})});if(r){var i=hn(vn(r,e));return i.length>0&&(r=i[0]),rn(r)}throw new Error("Selector was not found.")}function tn(e,t,n){for(var r=null,i=[],o=e,s=0,a=function(){var e,a,l=(new Date).getTime()-Qt.getTime();if(void 0!==Ht.timeoutMs&&l>Ht.timeoutMs)throw new Error("Timeout: Can't find a unique selector after ".concat(l,"ms"));var h=cn(function(e){var t=e.getAttribute("id");if(t&&Ht.idName(t))return{name:"#"+CSS.escape(t),penalty:0};return null}(o))||cn.apply(void 0,d([],u(function(e){var t=Array.from(e.attributes).filter(function(e){return Ht.attr(e.name,e.value)});return t.map(function(e){return{name:"[".concat(CSS.escape(e.name),'="').concat(CSS.escape(e.value),'"]'),penalty:.5}})}(o)),!1))||cn.apply(void 0,d([],u(function(e){var t=Array.from(e.classList).filter(Ht.className);return t.map(function(e){return{name:"."+CSS.escape(e),penalty:1}})}(o)),!1))||cn(function(e){var t=e.tagName.toLowerCase();if(Ht.tagName(t))return{name:t,penalty:2};return null}(o))||[{name:"*",penalty:3}],v=function(e){var t=e.parentNode;if(!t)return null;var n=t.firstChild;if(!n)return null;var r=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&r++,n!==e);)n=n.nextSibling;return r}(o);if("all"==t)v&&(h=h.concat(h.filter(ln).map(function(e){return an(e,v)})));else if("two"==t)h=h.slice(0,1),v&&(h=h.concat(h.filter(ln).map(function(e){return an(e,v)})));else if("one"==t){var g=u(h=h.slice(0,1),1)[0];v&&ln(g)&&(h=[an(g,v)])}else"none"==t&&(h=[{name:"*",penalty:3}],v&&(h=[an(h[0],v)]));try{for(var f=(e=void 0,c(h)),p=f.next();!p.done;p=f.next()){(g=p.value).level=s}}catch(t){e={error:t}}finally{try{p&&!p.done&&(a=f.return)&&a.call(f)}finally{if(e)throw e.error}}if(i.push(h),i.length>=Ht.seedMinLength&&(r=nn(i,n)))return"break";o=o.parentElement,s++};o;){if("break"===a())break}return r||(r=nn(i,n)),!r&&n?n():r}function nn(e,t){var n,r,i=hn(dn(e));if(i.length>Ht.threshold)return t?t():null;try{for(var o=c(i),s=o.next();!s.done;s=o.next()){var a=s.value;if(sn(a))return a}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null}function rn(e){for(var t=e[0],n=t.name,r=1;r<e.length;r++){var i=e[r].level||0;n=t.level===i-1?"".concat(e[r].name," > ").concat(n):"".concat(e[r].name," ").concat(n),t=e[r]}return n}function on(e){return e.map(function(e){return e.penalty}).reduce(function(e,t){return e+t},0)}function sn(e){var t=rn(e);switch(Gt.querySelectorAll(t).length){case 0:throw new Error("Can't select any node with this selector: ".concat(t));case 1:return!0;default:return!1}}function an(e,t){return{name:e.name+":nth-child(".concat(t,")"),penalty:e.penalty+1}}function ln(e){return"html"!==e.name&&!e.name.startsWith("#")}function cn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.filter(un);return n.length>0?n:null}function un(e){return null!=e}function dn(e,t){var n,r,i,o,s,a;return void 0===t&&(t=[]),l(this,function(l){switch(l.label){case 0:if(!(e.length>0))return[3,9];l.label=1;case 1:l.trys.push([1,6,7,8]),n=c(e[0]),r=n.next(),l.label=2;case 2:return r.done?[3,5]:(i=r.value,[5,c(dn(e.slice(1,e.length),t.concat(i)))]);case 3:l.sent(),l.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=l.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(a=n.return)&&a.call(n)}finally{if(s)throw s.error}return[7];case 8:return[3,11];case 9:return[4,t];case 10:l.sent(),l.label=11;case 11:return[2]}})}function hn(e){return d([],u(e),!1).sort(function(e,t){return on(e)-on(t)})}function vn(e,t,n){var r,i,o;return void 0===n&&(n={counter:0,visited:new Map}),l(this,function(s){switch(s.label){case 0:if(!(e.length>2&&e.length>Ht.optimizedMinLength))return[3,5];r=1,s.label=1;case 1:return r<e.length-1?n.counter>Ht.maxNumberOfTries?[2]:(n.counter+=1,(i=d([],u(e),!1)).splice(r,1),o=rn(i),n.visited.has(o)?[2]:sn(i)&&function(e,t){return Gt.querySelector(rn(e))===t}(i,t)?[4,i]:[3,4]):[3,5];case 2:return s.sent(),n.visited.set(o,!0),[5,c(vn(i,t,n))];case 3:s.sent(),s.label=4;case 4:return r++,[3,1];case 5:return[2]}})}var gn=function(e){var t=e.version,n=e.events,r=[];return n.forEach(function(e){var t=JSON.parse(e);t.count=1,"click"===t.type&&r.push(t)}),{version:t,events:r}},fn=function(e){var t=e.version,n=e.events,r=[];n.forEach(function(e){var t=JSON.parse(e);"click"===t.type&&r.push(t)});var i=r.reduce(function(e,t){var n=t.x,r=t.y,i=t.selector,s=t.timestamp,a=s-s%36e5,l="".concat(n,":").concat(r,":").concat(null!=i?i:"",":").concat(a);return e[l]?e[l].count+=1:e[l]=o(o({},t),{timestamp:a,count:1}),e},{});return{version:t,events:Object.values(i)}},pn=function(e,t){var n=this;this.createHook=function(e){var t=e.eventsManager,r=e.sessionId,i=e.deviceIdFn,o=e.mirror,s=e.ugcFilterRules,a=e.performanceOptions;return function(e){if(e.type===$e.Click){var l=f();if(l){var c=l.location,u=l.innerHeight,d=l.innerWidth;if(c){var h=e.x,v=e.y;if(void 0!==h&&void 0!==v){var g,p=o.getNode(e.id);if(p)try{g=en(p,a)}catch(e){n.logger.debug("error resolving selector from finder")}var m=Ae(c.href,s),y={x:h+n.scrollWatcher.currentScrollX,y:v+n.scrollWatcher.currentScrollY,selector:g,viewportHeight:u,viewportWidth:d,pageUrl:m,timestamp:Date.now(),type:"click"},b=i();b&&t.addEvent({sessionId:r,event:{type:"interaction",data:JSON.stringify(y)},deviceId:b})}}}}}},this.logger=e,this.scrollWatcher=t};function mn(){var e=f();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function yn(){var e=f();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}var bn=function(){function e(e,t){var n=f();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=function(e,t){try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=function(){return!1},this.sendXhr=function(e,t){var n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=De(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e,this.handleSendEvents=t.handleSendEvents,this.loggerProvider=t.loggerProvider}return e.prototype.send=function(e,t){var n,r=this,i=this.context,o=i.sessionId,s=i.type;if(this.handleSendEvents){var a=new URLSearchParams({device_id:e,session_id:String(o),type:String(s)}),l="".concat(this.basePageUrl,"?").concat(a.toString()),c={"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(this.apiKey)};try{this.handleSendEvents({url:l,method:"POST",headers:c,body:JSON.stringify(t),keepalive:!0}).catch(function(e){var t;null===(t=r.loggerProvider)||void 0===t||t.warn("Custom transport failed to send session replay interaction beacon:",e)})}catch(e){null===(n=this.loggerProvider)||void 0===n||n.warn("Custom transport threw while sending session replay interaction beacon:",e)}}else{var u=new URLSearchParams({device_id:e,session_id:String(o),type:String(s),api_key:this.apiKey}),d="".concat(this.basePageUrl,"?").concat(u.toString());this.sendBeacon(d,t)||this.sendXhr(d,t)}},e}(),Sn=function(){function e(e,t){var n=this;this.timestamp=Date.now(),this.hook=function(e){n.update(e)},this.send=function(e){return function(t){var r,i,o,s,a=e(),l=f();if(l&&a){var c=null!==(r=l.scrollX)&&void 0!==r?r:0,u=null!==(i=l.scrollY)&&void 0!==i?i:0;(c>0||u>0)&&n.update({id:1,x:c,y:u}),n.transport.send(a,{version:1,events:[{maxScrollX:n._maxScrollX,maxScrollY:n._maxScrollY,maxScrollWidth:n._maxScrollWidth,maxScrollHeight:n._maxScrollHeight,viewportHeight:mn(),viewportWidth:yn(),pageUrl:Ae(l.location.href,null!==(s=null===(o=n.config.interactionConfig)||void 0===o?void 0:o.ugcFilterRules)&&void 0!==s?s:[]),timestamp:n.timestamp,type:"scroll"}]})}}},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=yn(),this._maxScrollHeight=mn(),this.config=t,this.transport=e}return e.default=function(t,n){return new e(new bn(t,n),n)},Object.defineProperty(e.prototype,"maxScrollX",{get:function(){return this._maxScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollY",{get:function(){return this._maxScrollY},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollWidth",{get:function(){return this._maxScrollWidth},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollHeight",{get:function(){return this._maxScrollHeight},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollX",{get:function(){return this._currentScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollY",{get:function(){return this._currentScrollY},enumerable:!1,configurable:!0}),e.prototype.update=function(e){var t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){var n=yn();this._maxScrollX=e.x;var r=e.x+n;r>this._maxScrollWidth&&(this._maxScrollWidth=r),this.timestamp=t}if(e.y>this._maxScrollY){var i=mn();this._maxScrollY=e.y;var o=e.y+i;o>this._maxScrollHeight&&(this._maxScrollHeight=o),this.timestamp=t}},e}(),In=function(e){var t=e.sessionId,n=e.deviceId;this.deviceId=n,this.sessionId=t,t&&n&&(this.sessionReplayId=function(e,t){return"".concat(t,"/").concat(e)}(t,n))},wn=864e5,Cn=function(e){return"".concat("AMP_SR_START_").concat(e.substring(0,10),"_")},En=function(e,t){return"".concat(Cn(e)).concat(t)},Pn=function(){try{var e=f();return null==e?void 0:e.localStorage}catch(e){return}},kn=function(){var e=this;this.dbs={},this.createStore=function(t){return a(e,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,xt(t,1,{upgrade:function(e){e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})];case 1:return[2,e.sent()]}})})},this.openOrCreateDB=function(t){return a(e,void 0,void 0,function(){var e,n;return l(this,function(r){switch(r.label){case 0:return this.dbs&&this.dbs[t]?[2,this.dbs[t]]:(e="".concat(t.substring(0,10),"_amp_session_replay_targeting"),[4,this.createStore(e)]);case 1:return n=r.sent(),this.dbs[t]=n,[2,n]}})})},this.getTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId;return a(e,void 0,void 0,function(){var e,t,o,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,e.get("sessionTargetingMatch",t)];case 2:return[2,null==(o=a.sent())?void 0:o.targetingMatch];case 3:return s=a.sent(),Nt(n,"Failed to get targeting match for session id ".concat(i,": ").concat(s),s),[3,4];case 4:return[2,void 0]}})})},this.storeTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId,o=t.targetingMatch;return a(e,void 0,void 0,function(){var e,t,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,e.put("sessionTargetingMatch",{targetingMatch:o,sessionId:t,lastUpdated:Date.now()})];case 2:return[2,a.sent()];case 3:return s=a.sent(),Nt(n,"Failed to store targeting match for session id ".concat(i,": ").concat(s),s),[3,4];case 4:return[2,void 0]}})})},this.clearStoreOfOldSessions=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.currentSessionId;return a(e,void 0,void 0,function(){var e,t,o,s,a,c,u,d;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,8,,9]),[4,this.openOrCreateDB(r)];case 1:return e=l.sent(),t=String(i),[4,(o=e.transaction("sessionTargetingMatch","readwrite")).store.getAll()];case 2:s=l.sent(),a=0,l.label=3;case 3:return a<s.length?(c=s[a],u=Date.now()-c.lastUpdated,c.sessionId!==t&&u>1728e5?[4,o.store.delete(c.sessionId)]:[3,5]):[3,6];case 4:l.sent(),l.label=5;case 5:return a++,[3,3];case 6:return[4,o.done];case 7:return l.sent(),[3,9];case 8:return d=l.sent(),Nt(n,"Failed to clear old targeting matches for sessions: ".concat(d),d),[3,9];case 9:return[2]}})})}},xn=new kn,Mn=function(e){var t=e.sessionId,n=e.targetingConfig,r=e.loggerProvider,i=e.apiKey,s=e.targetingParams,c=e.urlChange,u=void 0!==c&&c;return a(void 0,void 0,void 0,function(){var e,a,c,d,h,v;return l(this,function(l){switch(l.label){case 0:return[4,xn.clearStoreOfOldSessions({loggerProvider:r,apiKey:i,currentSessionId:t})];case 1:return l.sent(),[4,xn.getTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t})];case 2:if(!0===l.sent()&&!u)return[2,!0];e=!0,l.label=3;case 3:return l.trys.push([3,6,,7]),[4,import("./index-min3.js")];case 4:return a=l.sent().evaluateTargeting,c=o(o({},s),{flag:n,sessionId:"string"==typeof t?parseInt(t,10):t,apiKey:i,loggerProvider:r}),[4,a(c)];case 5:return(d=l.sent())&&d.sr_targeting_config&&(e="on"===d.sr_targeting_config.key),xn.storeTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t,targetingMatch:e}),[3,7];case 6:return h=l.sent(),v=h,r.warn(v.message),[3,7];case 7:return[2,e]}})})},Tn=2654435761,On=2246822519,Rn=3266489917,_n=374761393;function Ln(e,t){return(e<<t|e>>>32-t)>>>0}function Fn(e,t){return e=Ln(e=e+Math.imul(t,On)>>>0,13),e=Math.imul(e,Tn)>>>0}function Dn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function qn(e,t){void 0===t&&(t=0);var n,r=function(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r>=55296&&r<=56319&&n+1<e.length){var i=e.charCodeAt(n+1);i>=56320&&i<=57343&&(r=i-56320+(r-55296<<10)+65536,n++)}r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<65536?t.push(224|r>>12,128|r>>6&63,128|63&r):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}return new Uint8Array(t)}(e),i=r.length,o=0;if(i>=16){for(var s=t+Tn+On>>>0,a=t+On>>>0,l=t>>>0,c=t-Tn>>>0;o<=i-16;)s=Fn(s,Dn(r,o)),a=Fn(a,Dn(r,o+=4)),l=Fn(l,Dn(r,o+=4)),c=Fn(c,Dn(r,o+=4)),o+=4;n=Ln(s,1)+Ln(a,7)+Ln(l,12)+Ln(c,18)>>>0}else n=t+_n>>>0;for(n=n+i>>>0;o<=i-4;)n=n+Math.imul(Dn(r,o),Rn)>>>0,n=Math.imul(Ln(n,17),668265263)>>>0,o+=4;for(;o<i;)n=n+Math.imul(r[o],_n)>>>0,n=Math.imul(Ln(n,11),Tn)>>>0,o++;return n^=n>>>15,n=Math.imul(n,On)>>>0,n^=n>>>13,n=Math.imul(n,Rn)>>>0,(n^=n>>>16)>>>0}var An="__amplitude_url_tracking_patched__",jn=new WeakMap;function Bn(e,t,n){if(void 0===n&&(n={}),!(null==e?void 0:e.location))return function(){};var r=n.enablePolling,i=void 0!==r&&r,o=n.pollingInterval,s=void 0===o?he:o;if(i){var a=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""},l=a(),c=e.setInterval(function(){var e=a();e!==l&&(l=e,t(e))},s);return function(){null!=c&&e.clearInterval(c)}}var u=jn.get(e);if(!u){var d=void 0,h=new Set,v=function(){var t=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""}();void 0!==d&&t===d||(d=t,h.forEach(function(e){return e(t)}))},g=function(e){var t=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=e.apply(this,t);return v(),r};return t[An]=!0,t},f=e.history;if(null==f?void 0:f.pushState){var p=Reflect.get(f,"pushState");p[An]||(f.pushState=g(p))}if(null==f?void 0:f.replaceState){var m=Reflect.get(f,"replaceState");m[An]||(f.replaceState=g(m))}u={callbacks:h,notify:v,onPopStateOrHashChange:function(){return v()},listenersAttached:!1},jn.set(e,u)}var y=u;return y.listenersAttached||(e.addEventListener("popstate",y.onPopStateOrHashChange),e.addEventListener("hashchange",y.onPopStateOrHashChange),y.listenersAttached=!0),y.callbacks.add(t),function(){y.callbacks.delete(t),0===y.callbacks.size&&y.listenersAttached&&(e.removeEventListener("popstate",y.onPopStateOrHashChange),e.removeEventListener("hashchange",y.onPopStateOrHashChange),y.listenersAttached=!1)}}function Nn(e){return void 0===e&&(e={}),{name:"amplitude/url-tracking@1",observer:function(t,n,r){var i,s,a,l=o(o({},e),r),c=l.ugcFilterRules||[],u=null!==(i=l.enablePolling)&&void 0!==i&&i,d=null!==(s=l.pollingInterval)&&void 0!==s?s:he,h=null!==(a=l.captureDocumentTitle)&&void 0!==a&&a;if(!n)return function(){};var v=void 0,g=function(){return n.location&&n.location.href||""},f=function(){var e=g();if(void 0===v||e!==v){v=e;var r=function(){var e=n.innerHeight,t=n.innerWidth,r=n.document,i=g(),o="";return h&&(o=(null==r?void 0:r.title)||""),{href:c.length>0?Ae(i,c):i,title:o,viewportHeight:e,viewportWidth:t,type:"url-change-event"}}();t(r)}},p=Bn(n,function(){return f()},u?{enablePolling:!0,pollingInterval:d}:{});return f(),function(){return p()}},options:e}}Nn();var Un=function(){function e(){this.pendingLoadListeners=new Map}return e.prototype.start=function(){var e,t=this;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),f()&&(this.sendToAllIframes({type:Ce,action:"start"}),this.mutationObserver=new MutationObserver(function(e){var n,r,i,o,s,a;try{for(var l=c(e),u=l.next();!u.done;u=l.next()){var d=u.value;try{for(var h=(i=void 0,c(Array.from(d.addedNodes))),v=h.next();!v.done;v=h.next()){(p=v.value)instanceof HTMLIFrameElement?t.sendToIframeAfterLoad(p):p instanceof Element&&p.querySelectorAll("iframe").forEach(function(e){t.sendToIframeAfterLoad(e)})}}catch(e){i={error:e}}finally{try{v&&!v.done&&(o=h.return)&&o.call(h)}finally{if(i)throw i.error}}try{for(var g=(s=void 0,c(Array.from(d.removedNodes))),f=g.next();!f.done;f=g.next()){var p;if((p=f.value)instanceof HTMLIFrameElement){var m=t.pendingLoadListeners.get(p);m&&(p.removeEventListener("load",m),t.pendingLoadListeners.delete(p))}}}catch(e){s={error:e}}finally{try{f&&!f.done&&(a=g.return)&&a.call(g)}finally{if(s)throw s.error}}}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}),this.mutationObserver.observe(document.documentElement,{childList:!0,subtree:!0}))},e.prototype.stop=function(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),this.mutationObserver=void 0,this.pendingLoadListeners.forEach(function(e,t){t.removeEventListener("load",e)}),this.pendingLoadListeners.clear(),this.sendToAllIframes({type:Ce,action:"stop"})},e.prototype.sendToIframeAfterLoad=function(e){var t=this,n=function(){t.pendingLoadListeners.delete(e),t.sendToIframe(e,{type:Ce,action:"start"})};this.pendingLoadListeners.set(e,n),e.addEventListener("load",n,{once:!0})},e.prototype.sendToAllIframes=function(e){var t=this;document.querySelectorAll("iframe").forEach(function(n){return t.sendToIframe(n,e)})},e.prototype.sendToIframe=function(e,t){var n;try{null===(n=e.contentWindow)||void 0===n||n.postMessage(t,"*")}catch(e){}},e}();var Wn=function(){function e(){var e=this;this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.recordFunction=null,this.recordEventsInFlight=!1,this.recordingEnabled=!0,this.recordingGeneration=0,this.startChildRecordingOnSetup=!1,this.pendingEmitEvents=[],this.currentPageUrl="",this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.crossOriginIframeCoordinator=null,this.crossOriginParentSignalCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=function(t){var n=f();n&&(n.removeEventListener("blur",e.blurListener),n.removeEventListener("focus",e.focusListener),!t&&n.addEventListener("blur",e.blurListener),!t&&n.addEventListener("focus",e.focusListener),n.self&&"onpagehide"in n.self?(n.removeEventListener("pagehide",e.pageLeaveListener),!t&&n.addEventListener("pagehide",e.pageLeaveListener)):(n.removeEventListener("beforeunload",e.pageLeaveListener),!t&&n.addEventListener("beforeunload",e.pageLeaveListener)))},this.blurListener=function(){e.sendEvents()},this.focusListener=function(){var t;if(e.recordingEnabled)if(e.recordCancelCallback&&e.recordFunction){if(!1===(null===(t=e.config)||void 0===t?void 0:t.captureFullSnapshotOnFocus))return;try{e.recordFunction.takeFullSnapshot(!0)}catch(t){e.loggerProvider.warn("Failed to take full snapshot on focus:",t)}}else e.recordEventsInFlight||e.recordEvents(!1)},this.pageLeaveListener=function(t){var n;null===(n=e.eventCompressor)||void 0===n||n.flushQueue(),e.sendEvents(),e.pageLeaveFns.forEach(function(e){e(t)})},this.evaluateTargetingAndCapture=function(t,n,r,o){return void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),a(e,void 0,void 0,function(){var e,s,a,c,u,d,h,v,g,p,m,y;return l(this,function(l){switch(l.label){case 0:if(!this.identifiers||!this.identifiers.sessionId||!this.config)return 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."),[2];if(!this.config.targetingConfig){if(!n)return this.loggerProvider.log("No targeting config set, skipping initialization/recording for event."),[2];this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}return this.lastTargetingParams=t,e=this.config.targetingConfig,e&&!this.sessionTargetingMatch?(s=o?this.latestUrlChangeTargetingEvaluationId:void 0,(a=t.event)&&Object.values(i).includes(a.event_type)&&(a=void 0),c=null!==(m=null!==(v=null===(h=t.page)||void 0===h?void 0:h.url)&&void 0!==v?v:null===(p=null===(g=f())||void 0===g?void 0:g.location)||void 0===p?void 0:p.href)&&void 0!==m?m:"",u=null!==(y=t.page)&&void 0!==y?y:""!==c?{url:c}:void 0,[4,Mn({sessionId:this.identifiers.sessionId,targetingConfig:e,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:t.userProperties,event:a,page:u},urlChange:o})]):[3,2];case 1:if(d=l.sent(),o&&void 0!==s&&s!==this.latestUrlChangeTargetingEvaluationId)return this.loggerProvider.debug("Ignoring stale URL-change targeting result #".concat(s,"; latest is #").concat(this.latestUrlChangeTargetingEvaluationId,".")),[2];this.sessionTargetingMatch=this.sessionTargetingMatch||d,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:a,targetingParams:t},null,2)),l.label=2;case 2:return n?(this.initialize(!0),[3,5]):[3,3];case 3:return!r&&this.recordCancelCallback?[3,5]:(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),[4,this.recordEvents()]);case 4:l.sent(),l.label=5;case 5:return[2]}})})},this.addCustomRRWebEvent=function(t,n,r){return void 0===n&&(n={}),void 0===r&&(r=!0),a(e,void 0,void 0,function(){var e,i,s,a;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,3,,4]),e=void 0,(i=this.config)&&t!==ae.METADATA?(e={config:Be(i),version:ht},r?[4,je()]:[3,2]):[3,2];case 1:s=l.sent(),e=o(o({},s),e),l.label=2;case 2:return this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(t,o(o({},n),e)):this.loggerProvider.debug("Not able to add custom replay capture event ".concat(t," due to no ongoing recording.")),[3,4];case 3:return a=l.sent(),this.loggerProvider.debug("Error while adding custom replay capture event: ",a),[3,4];case 4:return[2]}})})},this.stopRecordingEvents=function(){var t,n,r;try{e.loggerProvider.log("Session Replay capture stopping."),e.recordCancelCallback&&e.recordCancelCallback(),e.recordCancelCallback=null,null===(t=e.networkObservers)||void 0===t||t.stop(),null===(n=e.crossOriginIframeCoordinator)||void 0===n||n.stop(),e.crossOriginIframeCoordinator=null,null===(r=e.crossOriginParentSignalCleanup)||void 0===r||r.call(e),e.crossOriginParentSignalCleanup=null}catch(t){var i=t;e.loggerProvider.warn("Error occurred while stopping replay capture: ".concat(i.toString()))}},this.loggerProvider=new Ee(new M)}return e.prototype.init=function(e,t){return k(this._init(e,t))},e.prototype.setupUrlChangeListener=function(){var e,t,n=this;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);var r=f();if(null==r?void 0:r.location){var i=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),o=Bn(r,function(e){if(n.currentPageUrl=e,i){var t=++n.latestUrlChangeTargetingEvaluationId;n.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:e}},!1,!1,!0),n.loggerProvider.debug("Queued URL-change targeting re-evaluation #".concat(t," for ").concat(e,"."))}});this.urlChangeCleanup=function(){o(),n.urlChangeCleanup=null}}},e.prototype.isBelowMinSessionDuration=function(){var e,t=null===(e=this.config)||void 0===e?void 0:e.minSessionDurationMs;return void 0!==t&&void 0!==this.sessionStartTime&&Date.now()-this.sessionStartTime<t},e.prototype.getCurrentPageForTargeting=function(){var e,t,n=null===(t=null===(e=f())||void 0===e?void 0:e.location)||void 0===t?void 0:t.href;return null!=n?{url:n}:void 0},e.prototype._init=function(e,t){var n,r,i,s,h,v,g,p,m,y,b,S,I,w;return a(this,void 0,void 0,function(){var a,C,E,P,k,x,T,O,R,_,L,F,D,q,A,j,B,N,U,W,z,K,H,G,Q,J,$,Z,V,X,ee,te=this;return l(this,function(l){switch(l.label){case 0:return null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),this.recordingEnabled=!0,this.startChildRecordingOnSetup=!1,this.loggerProvider=new Ee(t.loggerProvider||new M),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=qe(),this.identifiers=new In({sessionId:t.sessionId,deviceId:t.deviceId}),a=Date.now(),function(e,t,n){var r,i,o=Pn();if(o){var s=Cn(e);try{for(var a=[],l=0;l<o.length;l++)if((g=o.key(l))&&g.startsWith(s)){var u=o.getItem(g);if(null!==u){var d=Number(u);(!Number.isFinite(d)||d<=0||t-d>=wn)&&a.push(g)}}try{for(var h=c(a),v=h.next();!v.done;v=h.next()){var g=v.value;o.removeItem(g)}}catch(e){r={error:e}}finally{try{v&&!v.done&&(i=h.return)&&i.call(h)}finally{if(r)throw r.error}}}catch(e){null==n||n.debug("Failed to prune stale replay start times: ".concat(String(e)))}}}(e,a,this.loggerProvider),this.sessionStartTime=void 0!==t.sessionId&&null!==(r=function(e,t,n,r){var i=Pn();if(i){var o=En(e,t);try{var s=i.getItem(o);if(null!==s){var a=Number(s);if(Number.isFinite(a)&&a>0&&a<=n&&n-a<wn)return a}return i.setItem(o,String(n)),n}catch(e){return void(null==r||r.debug("Failed to read/write replay start time from storage: ".concat(String(e))))}}}(e,t.sessionId,a,this.loggerProvider))&&void 0!==r?r:a,C=this,[4,Ye(e,t)];case 1:return C.joinedConfigGenerator=l.sent(),[4,this.joinedConfigGenerator.generateJoinedConfig()];case 2:return E=l.sent(),P=E.joinedConfig,k=E.localConfig,x=E.remoteConfig,this.config=P,this.setMetadata(t.sessionId,P,k,x,null===(i=t.version)||void 0===i?void 0:i.version,ht,null===(s=t.version)||void 0===s?void 0:s.type),this.pageLeaveFns=[],t.sessionId&&(null===(h=this.config.interactionConfig)||void 0===h?void 0:h.enabled)&&(T=Sn.default({sessionId:t.sessionId,type:"interaction"},this.config),this.pageLeaveFns=[T.send(this.getDeviceId.bind(this)).bind(T)],this.scrollHook=T.hook.bind(T),this.clickHandler=new pn(this.loggerProvider,T)),O=[],"idb"!==(R=this.config.storeType)||(null===(v=f())||void 0===v?void 0:v.indexedDB)||(R="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log("Using ".concat(R," for event storage.")),F=f(),this.config.useWebWorker&&F&&F.Worker?[4,import("./index-min2.js")]:[3,4];case 3:D=l.sent(),q=D.compressionScript,A=D.trackDestinationScript,_=q,L=A,l.label=4;case 4:return l.trys.push([4,6,,7]),[4,Xt({config:this.config,type:"replay",minInterval:null===(g=this.config.flushIntervalConfig)||void 0===g?void 0:g.minIntervalMs,maxInterval:null===(p=this.config.flushIntervalConfig)||void 0===p?void 0:p.maxIntervalMs,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,storeType:R,trackDestinationWorkerScript:L,shouldSend:function(){return!te.isBelowMinSessionDuration()}})];case 5:return j=l.sent(),this.rrwebEventManager=j,O.push({name:"replay",manager:j}),[3,7];case 6:return B=l.sent(),z=B,this.loggerProvider.warn("Error occurred while creating replay events manager: ".concat(z.toString())),[3,7];case 7:if(!(null===(m=this.config.interactionConfig)||void 0===m?void 0:m.enabled))return[3,11];N=this.config.interactionConfig.batch?fn:gn,l.label=8;case 8:return l.trys.push([8,10,,11]),[4,Xt({config:this.config,type:"interaction",minInterval:null!==(y=this.config.interactionConfig.trackEveryNms)&&void 0!==y?y:3e4,maxInterval:6e4,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,payloadBatcher:N,storeType:R,trackDestinationWorkerScript:L})];case 9:return U=l.sent(),O.push({name:"interaction",manager:U}),[3,11];case 10:return W=l.sent(),z=W,this.loggerProvider.warn("Error occurred while creating interaction events manager: ".concat(z.toString())),[3,11];case 11:if(this.eventsManager=new(Yt.bind.apply(Yt,d([void 0],u(O),!1))),this.eventCompressor&&this.eventCompressor.terminate(),K=!0===this.config.eagerFullSnapshotSend?function(){return te.sendEvents()}:void 0,this.eventCompressor=new lt(this.eventsManager,this.config,this.getDeviceId(),_,K),this.pendingEmitEvents.length>0){H=this.pendingEmitEvents.splice(0);try{for(G=c(H),Q=G.next();!Q.done;Q=G.next())J=Q.value,$=J.event,Z=J.sessionId,this.eventCompressor.enqueueEvent($,Z)}catch(e){X={error:e}}finally{try{Q&&!Q.done&&(ee=G.return)&&ee.call(G)}finally{if(X)throw X.error}}}return this.pageLeaveFns=d(d([],u(this.pageLeaveFns),!1),[function(){var e;if(te.config&&(null===(e=te.identifiers)||void 0===e?void 0:e.sessionId)&&j){var t=j.getBeaconEvents();if(t.length){var n=te.getDeviceId();n&&(te.isBelowMinSessionDuration()||j.trackDestination.sendBeacon({events:t,sessionId:te.identifiers.sessionId,deviceId:n,apiKey:te.config.apiKey,serverZone:te.config.serverZone}))}}}],!1),[4,this.initializeNetworkObservers()];case 12:return l.sent(),(null===(b=f())||void 0===b?void 0:b.opener)&&(se(V=re()),V.setup(o({logger:this.loggerProvider},this.config.serverZone&&{endpoint:Y[this.config.serverZone]}))),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),[4,this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0)];case 13:return l.sent(),(this.config.targetingConfig||(null!==(w=null===(I=null===(S=this.config.privacyConfig)||void 0===S?void 0:S.urlMaskLevels)||void 0===I?void 0:I.length)&&void 0!==w?w:0)>0)&&this.setupUrlChangeListener(),[2]}})})},e.prototype.setSessionId=function(e,t){return k(this.asyncSetSessionId(e,t))},e.prototype.asyncSetSessionId=function(e,t,n){var r,i,o,s;return a(this,void 0,void 0,function(){var a,c,u,d,h;return l(this,function(l){switch(l.label){case 0:return a=null===(r=this.identifiers)||void 0===r?void 0:r.sessionId,c=this.getDeviceId(),void 0===a||a!==e||void 0!==t&&t!==c||void 0!==(null==n?void 0:n.userProperties)&&0!==Object.keys(n.userProperties).length?(this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,a&&this.sendEvents(a),(u=a!==e)&&(null===(i=this.rrwebEventManager)||void 0===i||i.dropPendingBeaconEvents()),d=t||this.getDeviceId(),this.identifiers=new In({sessionId:e,deviceId:d}),u&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,(null===(o=this.config)||void 0===o?void 0:o.apiKey)&&(function(e,t,n,r){var i=Pn();if(i)try{i.setItem(En(e,t),String(n))}catch(e){null==r||r.debug("Failed to write replay start time to storage: ".concat(String(e)))}}(this.config.apiKey,e,this.sessionStartTime,this.loggerProvider),void 0!==a&&function(e,t,n){var r=Pn();if(r)try{r.removeItem(En(e,t))}catch(e){null==n||n.debug("Failed to remove replay start time from storage: ".concat(String(e)))}}(this.config.apiKey,a,this.loggerProvider))),this.joinedConfigGenerator&&a?[4,this.joinedConfigGenerator.generateJoinedConfig()]:[3,2]):[2];case 1:h=l.sent().joinedConfig,this.config=h,l.label=2;case 2:return(null===(s=this.config)||void 0===s?void 0:s.targetingConfig)?[4,this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0)]:[3,4];case 3:return l.sent(),[3,6];case 4:return[4,this.recordEvents()];case 5:l.sent(),l.label=6;case 6:return[2]}})})},e.prototype.getSessionReplayProperties=function(){var e,t=this.config,n=this.identifiers;if(!t||!n)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};var r=this.getShouldRecord(),i={};return r&&((e={})[ce]=n.sessionReplayId?n.sessionReplayId:null,i=e,t.debugMode&&(i[ve]=JSON.stringify({appHash:W(t.apiKey).toString()}))),this.addCustomRRWebEvent(ae.GET_SR_PROPS,{shouldRecord:r,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i},e.prototype.sendEvents=function(e){var t,n,r=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();if(this.eventsManager&&r&&i){if(this.isBelowMinSessionDuration()){var o=this.sessionStartTime,s=this.config.minSessionDurationMs;return this.loggerProvider.log("Session ".concat(r," not sent: duration ").concat(Date.now()-o,"ms is below minimum ").concat(s,"ms.")),void this.suppressedSendCount++}if(!this.hasEmittedGateDecision&&void 0!==(null===(n=this.config)||void 0===n?void 0:n.minSessionDurationMs)&&this.recordCancelCallback&&this.recordFunction){this.hasEmittedGateDecision=!0;var a=void 0!==this.sessionStartTime?Date.now()-this.sessionStartTime:void 0;this.addCustomRRWebEvent(ae.REPLAY_GATE_DECISION,{sessionId:r,suppressedSendCount:this.suppressedSendCount,elapsedMs:a,minSessionDurationMs:this.config.minSessionDurationMs},!1)}this.eventsManager.sendCurrentSequenceEvents({sessionId:r,deviceId:i})}},e.prototype.initialize=function(e){var t;return void 0===e&&(e=!1),a(this,void 0,void 0,function(){var n;return l(this,function(r){return(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId)?(n=this.getDeviceId())?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),[2,this.recordEvents()]):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),[2,Promise.resolve()]):(this.loggerProvider.log("Session is not being recorded due to lack of session id."),[2,Promise.resolve()])})})},e.prototype.shouldOptOut=function(){var e,t,n,r;(null===(e=this.config)||void 0===e?void 0:e.instanceName)&&(n=(r=this.config.instanceName,U.getInstance(T(r))).identityStore.getIdentity().optOut);return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut},e.prototype.getShouldRecord=function(){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.recordingEnabled)return this.loggerProvider.log("Session ".concat(this.identifiers.sessionId," not being captured because recording was stopped.")),!1;if(!this.config.captureEnabled)return this.loggerProvider.log("Session ".concat(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 ".concat(this.identifiers.sessionId," out of recording due to optOut config.")),!1;var e,t,n=!1,r="",i=!1;this.config.targetingConfig?this.sessionTargetingMatch?(r="Capturing replays for session ".concat(this.identifiers.sessionId," due to matching targeting conditions."),this.loggerProvider.log(r),n=!0,i=!0):(r="Not capturing replays for session ".concat(this.identifiers.sessionId," due to not matching targeting conditions."),this.loggerProvider.log(r),n=!1,i=!1):(e=this.identifiers.sessionId,t=this.config.sampleRate,qn(e.toString())%1e6/1e6<t)?(n=!0,i=!0):(r="Opting session ".concat(this.identifiers.sessionId," out of recording due to sample rate."),this.loggerProvider.log(r),n=!1,i=!1);return this.lastShouldRecordDecision!==n&&this.config.targetingConfig&&(this.addCustomRRWebEvent(ae.TARGETING_DECISION,{message:r,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=n),n},e.prototype.getBlockSelectors=function(){var e;return Le(null===(e=this.config)||void 0===e?void 0:e.privacyConfig)},e.prototype.getMaskTextSelectors=function(){var e;return Fe(null===(e=this.config)||void 0===e?void 0:e.privacyConfig,this.currentPageUrl)},e.prototype.getRecordingPlugins=function(e){var t,n,r,i,o,s;return a(this,void 0,void 0,function(){var a,c,u,d;return l(this,function(l){switch(l.label){case 0:a=[];try{c=Nn({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===(i=this.config)||void 0===i?void 0:i.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle}),a.push(c)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(!(null===(s=null==e?void 0:e.console)||void 0===s?void 0:s.enabled))return[3,4];l.label=1;case 1:return l.trys.push([1,3,,4]),[4,import("./rrweb-plugin-console-record-min.js")];case 2:return u=l.sent().getRecordConsolePlugin,a.push(u({level:e.console.levels})),[3,4];case 3:return d=l.sent(),this.loggerProvider.warn("Failed to load console plugin:",d),[3,4];case 4:return[2,a.length>0?a:void 0]}})})},e.prototype.getRecordFunction=function(){return a(this,void 0,void 0,function(){var e,t;return l(this,function(n){switch(n.label){case 0:if(this.recordFunction)return[2,this.recordFunction];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,import("./rrweb-record-min.js")];case 2:return e=n.sent().record,this.recordFunction=e,[2,e];case 3:return t=n.sent(),this.loggerProvider.warn("Failed to load rrweb-record module:",t),[2,null];case 4:return[2]}})})},e.prototype.recordEvents=function(e){return void 0===e&&(e=!0),a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:if(this.recordEventsInFlight)return this.recordEventsPendingShouldLogMetadata=e,[2];this.recordEventsInFlight=!0,n.label=1;case 1:return n.trys.push([1,,6,7]),[4,this._recordEvents(e)];case 2:n.sent(),n.label=3;case 3:return null===this.recordEventsPendingShouldLogMetadata?[3,5]:(t=this.recordEventsPendingShouldLogMetadata,this.recordEventsPendingShouldLogMetadata=null,[4,this._recordEvents(t)]);case 4:return n.sent(),[3,3];case 5:return[3,7];case 6:return this.recordEventsInFlight=!1,this.recordEventsPendingShouldLogMetadata=null,[7];case 7:return[2]}})})},e.prototype.shouldAbandonRecordStart=function(e){return!this.recordingEnabled||e!==this.recordingGeneration},e.prototype._recordEvents=function(e){var t,n,r,i,s,c,u,d;return void 0===e&&(e=!0),a(this,void 0,void 0,function(){var a,h,v,g,p,m,y,b,S,I,w,C,E,P,k,x,M,T=this;return l(this,function(l){switch(l.label){case 0:return a=this.config,h=this.getShouldRecord(),v=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId,h&&v&&a?(this.stopRecordingEvents(),g=this.recordingGeneration,[4,this.getRecordFunction()]):[2];case 1:return!(p=l.sent())||this.shouldAbandonRecordStart(g)?[2]:[4,this.initializeNetworkObservers()];case 2:if(l.sent(),this.shouldAbandonRecordStart(g))return[2];m=null===(n=a.loggingConfig)||void 0===n?void 0:n.network,y=De(a.serverZone,a.trackServerUrl),b=[ge,fe,pe,y],null===(r=this.networkObservers)||void 0===r||r.start(function(e){b.some(function(t){return e.url.startsWith(t)})||T.addCustomRRWebEvent(ae.FETCH_REQUEST,e)},m),S=a.interactionConfig,I=a.loggingConfig,w=(null==S?void 0:S.enabled)?{mouseInteraction:this.eventsManager&&(null===(i=this.clickHandler)||void 0===i?void 0:i.createHook({eventsManager:this.eventsManager,sessionId:v,deviceIdFn:this.getDeviceId.bind(this),mirror:p.mirror,ugcFilterRules:null!==(s=S.ugcFilterRules)&&void 0!==s?s:[],performanceOptions:null===(c=a.performanceConfig)||void 0===c?void 0:c.interaction})),scroll:this.scrollHook}:{},C=(null==S?void 0:S.enabled)&&S.ugcFilterRules?S.ugcFilterRules:[],this.loggerProvider.log("Session Replay capture beginning for ".concat(v,".")),l.label=3;case 3:return l.trys.push([3,5,,6]),E=!!(null===(u=a.crossOriginIframes)||void 0===u?void 0:u.enabled),P=!1!==(null===(d=a.crossOriginIframes)||void 0===d?void 0:d.coordinateChildren),(k=E&&function(){try{var e=f();return!!e&&e.parent!==e}catch(e){return!0}}())&&P?(this.crossOriginParentSignalCleanup=function(e){var t=f();if(!t)return function(){};var n=t.parent;function r(t){if(t.source===n){var r=t.data;(null==r?void 0:r.type)===Ce&&("start"===r.action?e.onStart():"stop"===r.action&&e.onStop())}}return t.addEventListener("message",r),function(){return t.removeEventListener("message",r)}}({onStart:function(){T.recordingEnabled&&T._recordEventsInChildMode(p,v,a,w)},onStop:function(){try{T.recordCancelCallback&&T.recordCancelCallback(),T.recordCancelCallback=null}catch(t){var e=t;T.loggerProvider.warn("Error occurred while stopping child iframe replay capture: ".concat(e.toString()))}}}),this.startChildRecordingOnSetup&&(this.startChildRecordingOnSetup=!1,this._recordEventsInChildMode(p,v,a,w)),[2]):(this.startChildRecordingOnSetup=!1,[4,this.getRecordingPlugins(I)]);case 4:return x=l.sent(),this.shouldAbandonRecordStart(g)?[2]:(this.recordCancelCallback=p(o(o({},this.buildRRWebRecordOptions(a,w,function(e){if(T.shouldOptOut()||!T.recordingEnabled)return T.loggerProvider.log(T.shouldOptOut()?"Opting session ".concat(v," out of recording due to optOut config."):"Session Replay capture stopping for ".concat(v,".")),T.stopRecordingEvents(),void T.sendEvents();e.type===Qe.Meta&&(e.data.href=Ae(e.data.href,C)),T.eventCompressor?T.eventCompressor.enqueueEvent(e,v):T.pendingEmitEvents.push({event:e,sessionId:v})},"Error while capturing replay: ")),{plugins:x,recordCrossOriginIframes:E})),E&&!k&&P&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new Un),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(ae.DEBUG_INFO),e&&this.addCustomRRWebEvent(ae.METADATA,this.metadata),[3,6]);case 5:return M=l.sent(),this.loggerProvider.warn("Failed to initialize session replay:",M),[3,6];case 6:return[2]}})})},e.prototype.buildRRWebRecordOptions=function(e,t,n,r){var i=this,s=e.privacyConfig;return o(o(o(o({emit:n,inlineStylesheet:e.shouldInlineStylesheet,inlineImages:e.inlineImages,hooks:t},function(e,t){return void 0===t&&(t=function(){return""}),{maskAllInputs:!0,maskTextClass:"amp-mask",blockClass:"amp-block",blockSelector:Le(e),maskTextSelector:Fe(e,t()),maskInputFn:Re("input",e,t),maskTextFn:Re("text",e,t),maskAttributeFn:_e(e,t)}}(s,function(){return i.currentPageUrl})),{applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements}),void 0!==e.fullSnapshotIntervalMs&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler:function(e){var t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return i.loggerProvider.warn(r,t.toString()),!0}})},e.prototype._recordEventsInChildMode=function(e,t,n,r){try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,this.recordCancelCallback=e(o(o({},this.buildRRWebRecordOptions(n,r,function(){},"Error while capturing replay (child iframe): ")),{recordCrossOriginIframes:!0})),this.loggerProvider.log("Session Replay child iframe capture beginning for session ".concat(t,"."))}catch(e){this.loggerProvider.warn("Failed to initialize session replay in child iframe mode:",e)}},e.prototype.getDeviceId=function(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId},e.prototype.getSessionId=function(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId},e.prototype.start=function(){return k(this._start())},e.prototype._start=function(){return a(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return this.recordingEnabled=!0,this.startChildRecordingOnSetup=!0,[4,this.recordEvents()];case 1:return e.sent(),[2]}})})},e.prototype.stop=function(){this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,this.stopRecordingEvents(),this.sendEvents()},e.prototype.flush=function(e){var t;return void 0===e&&(e=!1),a(this,void 0,void 0,function(){return l(this,function(n){return[2,null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)]})})},e.prototype.shutdown=function(){var e,t;this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,null===(e=this.urlChangeCleanup)||void 0===e||e.call(this),null===(t=this.crossOriginParentSignalCleanup)||void 0===t||t.call(this),this.crossOriginParentSignalCleanup=null,this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()},e.prototype.mapSDKType=function(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null},e.prototype.setMetadata=function(e,t,n,r,i,o,s){var a=(null==e?void 0:e.toString())?W(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:r,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(s),replaySDKVersion:i,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:o}},e.prototype.initializeNetworkObservers=function(){var e,t,n;return a(this,void 0,void 0,function(){var r,i;return l(this,function(o){switch(o.label){case 0: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)return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,import("./observers-min.js")];case 2:return r=o.sent().NetworkObservers,this.networkObservers=new r,[3,4];case 3:return i=o.sent(),this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",i),[3,4];case 4:return[2]}})})},e}(),zn=function(e){return function(){var t=e.config||Ne();return{logger:t.loggerProvider,logLevel:t.logLevel}}},Kn=function(){var e=new Wn;return{init:F(e.init.bind(e),"init",zn(e)),evaluateTargetingAndCapture:F(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",zn(e)),setSessionId:F(e.setSessionId.bind(e),"setSessionId",zn(e)),getSessionId:F(e.getSessionId.bind(e),"getSessionId",zn(e)),getSessionReplayProperties:F(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",zn(e)),flush:F(e.flush.bind(e),"flush",zn(e)),start:F(e.start.bind(e),"start",zn(e)),stop:F(e.stop.bind(e),"stop",zn(e)),shutdown:F(e.shutdown.bind(e),"shutdown",zn(e))}}(),Hn=Kn.init,Gn=Kn.setSessionId,Qn=Kn.getSessionId,Jn=Kn.getSessionReplayProperties;Kn.flush,Kn.start,Kn.stop,Kn.shutdown,Kn.evaluateTargetingAndCapture;const $n="amp_session_id",Zn="Amplitude Session Replay Segment Plugin [Debug]:";function Vn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)"__proto__"!==r&&(e[r]=n[r])}return e}var Xn=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=Vn({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},i=0;i<n.length;i++){var o=n[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(a in r||(r[a]=t.read(s,a)),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",Vn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Vn({},this.attributes,t))},withConverter:function(t){return e(Vn({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const Yn=()=>{const e=Qn()||Xn.get($n);if(e){const t=parseInt(e.toString(),10);if(isNaN(t))return;return t}},er=(e,t)=>(Xn.set($n,e.toString()),Gn(e,t).promise),tr=(e,t)=>a(void 0,void 0,void 0,function*(){const n=Yn()||0;let r;e.event.integrations&&e.event.integrations["Actions Amplitude"]&&(r=e.event.integrations["Actions Amplitude"].session_id),r&&n<r&&(yield er(r,t));const i=Jn(),o=Object.assign(Object.assign({},i),e.event.properties);return e.updateEvent("properties",o),e}),nr="0.0.53",rr=({amplitudeApiKey:e,sessionReplayOptions:t,segmentInstance:n,enableWrapperDebug:r=!1})=>a(void 0,void 0,void 0,function*(){let i,o=!1,s=null==t?void 0:t.deviceId;const l={name:"Session Replay Events",type:"enrichment",version:nr,isLoaded:()=>o,load:(n,l)=>a(void 0,void 0,void 0,function*(){if(!s){const e=l.user();s=e.anonymousId()||void 0}const n=Yn();r&&console.log(`${Zn} initializing session replay with sessionId=${null!=n?n:"undefined"} and deviceId=${null!=s?s:"undefined"}`),i=Hn(e,Object.assign(Object.assign({},t),{sessionId:n,deviceId:s||void 0,version:{type:"segment",version:nr}})).promise,yield i,o=!0}),track:e=>a(void 0,void 0,void 0,function*(){return yield i,yield tr(e,s)}),page:e=>a(void 0,void 0,void 0,function*(){return yield i,yield tr(e,s)}),identify:e=>a(void 0,void 0,void 0,function*(){yield i;const t=Yn();return t&&(r&&console.log(`${Zn} calling setSessionId() with sessionId=${t} and deviceId=${null!=s?s:"undefined"}`),yield er(t,s)),e})};yield n.register(l)});export{c as _,d as a,u as b,a as c,l as d,o as e,rr as f,f as g,xt as o,rt as t};
2
2
  //# sourceMappingURL=index-min.js.map