@amplitude/segment-session-replay-plugin 0.0.21 → 0.0.23
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.
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/cjs/version.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/esm/version.js.map +1 -1
- package/lib/scripts/index-min.js +1 -1
- package/lib/scripts/index-min.js.gz +0 -0
- package/lib/scripts/index-min.js.map +1 -1
- package/lib/scripts/index-min2.js +1 -1
- package/lib/scripts/index-min2.js.gz +0 -0
- package/lib/scripts/index-min2.js.map +1 -1
- package/package.json +2 -2
package/lib/scripts/index-min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=function(t,n){return e=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])},e(t,n)};function t(t,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=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n,r,i=function(){return i=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},i.apply(this,arguments)};function o(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 s(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}c((r=r.apply(e,t||[])).next())})}function a(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(c){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,c])}}}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 l(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 u(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"}(n||(n={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(r||(r={}));var d,v="$default_instance",h="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"}(d||(d={}));var f,g=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},p=u([],l(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),m=function(e){var t,n=g();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,u([],l(r.entries()),!1).map(function(e){var t=l(e,2),n=t[0],r=t[1];return[4,6,8,10].includes(n)?"-".concat(p[r]):p[r]}).join("")},y=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"}(f||(f={}));var b="Amplitude Logger ",S=function(){function e(){this.logLevel=f.None}return e.prototype.disable=function(){this.logLevel=f.None},e.prototype.enable=function(e){void 0===e&&(e=f.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<f.Verbose||console.log("".concat(b,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<f.Warn||console.warn("".concat(b,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<f.Error||console.error("".concat(b,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<f.Debug||console.log("".concat(b,"[Debug]: ").concat(e.join(" ")))},e}(),I=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:v,logLevel:f.Warn,loggerProvider:new S,offline:!1,optOut:!1,serverUrl:h,serverZone:"US",useBatch:!1}},w=function(){function e(e){var t,n,r,i;this._optOut=!1;var o=I();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:o.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||o.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||o.flushQueueSize,this.instanceName=e.instanceName||o.instanceName,this.loggerProvider=e.loggerProvider||o.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:o.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:o.offline,this.optOut=null!==(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=k(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}(),C=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":h},k=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=I().serverZone),void 0===n&&(n=I().useBatch),e)return{serverUrl:e,serverZone:void 0};var r=["US","EU"].includes(t)?t:I().serverZone;return{serverZone:r,serverUrl:C(r,n)}};var P=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(),c=a.logger,l=a.logLevel;if(l&&l<f.Debug||!l||!c)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 v=e.apply(i,o);return v&&v.promise?v.promise.then(function(){r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),c.debug(JSON.stringify(d,null,2))}):(r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),c.debug(JSON.stringify(d,null,2))),v}},E=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:x(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),x=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},M=function(){function e(){this.queue=[]}return e.prototype.logEvent=function(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)},e.prototype.setEventReceiver=function(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(function(t){e(t)}),this.queue=[])},e}(),R=function(){return R=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},R.apply(this,arguments)};function O(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 T(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"==typeof SuppressedError&&SuppressedError;var L=function(e,t){var n,r,i=typeof e;if(i!==typeof t)return!1;try{for(var o=O(["string","number","boolean","undefined"]),s=o.next();!s.done;s=o.next()){if(s.value===i)return e===t}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),c=Array.isArray(t);if(a!==c)return!1;if(!a||!c){var l=Object.keys(e).sort(),u=Object.keys(t).sort();if(!L(l,u))return!1;var d=!0;return Object.keys(e).forEach(function(n){L(e[n],t[n])||(d=!1)}),d}for(var v=0;v<e.length;v++)if(!L(e[v],t[v]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,r=new Array(n);n--;)r[n]=[t[n],e[t[n]]];return r});var _,D=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=R({},this.identity.userProperties),n=R(R({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,r,i,o,s,a,c=n.userProperties||{};try{for(var l=O(Object.entries(e)),u=l.next();!u.done;u=l.next()){var d=T(u.value,2),v=d[0],h=d[1];switch(v){case"$set":try{for(var f=(i=void 0,O(Object.entries(h))),g=f.next();!g.done;g=f.next()){var p=T(g.value,2),m=p[0],y=p[1];c[m]=y}}catch(e){i={error:e}}finally{try{g&&!g.done&&(o=f.return)&&o.call(f)}finally{if(i)throw i.error}}break;case"$unset":try{for(var b=(s=void 0,O(Object.keys(h))),S=b.next();!S.done;S=b.next()){delete c[m=S.value]}}catch(e){s={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(s)throw s.error}}break;case"$clearAll":c={}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(t)throw t.error}}return n.userProperties=c,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return R({},this.identity)},e.prototype.setIdentity=function(e){var t=R({},this.identity);this.identity=R({},e),L(t,this.identity)||this.listeners.forEach(function(t){t(e)})},e.prototype.addIdentityListener=function(e){this.listeners.add(e)},e.prototype.removeIdentityListener=function(e){this.listeners.delete(e)},e}(),F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,A=function(){function e(){this.identityStore=new D,this.eventBridge=new M,this.applicationContextProvider=new E}return e.getInstance=function(t){return F.analyticsConnectorInstances||(F.analyticsConnectorInstances={}),F.analyticsConnectorInstances[t]||(F.analyticsConnectorInstances[t]=new e),F.analyticsConnectorInstances[t]},e}(),q=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},U=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,c,l,u,v,h,f,g,p,m,y,b,S,I,w,C;if("object"!=typeof e)return null;var k=e.code||0,P=this.buildStatus(k);switch(P){case d.Success:return{status:P,statusCode:k,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 d.Invalid:return{status:P,statusCode:k,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!==(c=e.events_with_invalid_id_lengths)&&void 0!==c?c:{},epsThreshold:null!==(l=e.eps_threshold)&&void 0!==l?l:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(v=e.silenced_devices)&&void 0!==v?v:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(f=e.throttled_devices)&&void 0!==f?f:{},throttledEvents:null!==(g=e.throttled_events)&&void 0!==g?g:[]}};case d.PayloadTooLarge:return{status:P,statusCode:k,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case d.RateLimit:return{status:P,statusCode:k,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 d.Timeout:default:return{status:P,statusCode:k}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?d.Success:429===e?d.RateLimit:413===e?d.PayloadTooLarge:408===e?d.Timeout:e>=400&&e<500?d.Invalid:e>=500?d.Failed:d.Unknown},e}(),j=function(e){function n(t){void 0===t&&(t={});var n=e.call(this)||this;return n.customHeaders=t,n}return t(n,e),n.prototype.send=function(e,t){return s(this,void 0,void 0,function(){var n,r,o;return a(this,function(s){switch(s.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:i({"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:o=s.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}})})},n}(U),N=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var n=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(JSON.stringify(n))),Promise.resolve({remoteConfig:n.remoteConfig,lastFetch:new Date(n.lastFetch)})}catch(e){return this.logger.debug("Remote config localstorage failed to parse: ",e),localStorage.removeItem(this.key),Promise.resolve(t)}},e.prototype.setConfig=function(e){try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}(),B=401,W=403,z=429,K=function(){function e(e,t,n,r){void 0===n&&(n="US"),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=e,this.serverUrl=r||("US"===n?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=t,this.storage=new N(e,t)}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 s(this,void 0,void 0,function(){var e,t=this;return a(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 s(this,void 0,void 0,function(){var t,n,r,i=this;return a(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 s(this,void 0,void 0,function(){var n,r;return a(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),s(this,void 0,void 0,function(){var n,r,i,o,s,c,l=this;return a(this,function(u){switch(u.label){case 0:n=t/e,r={remoteConfig:null,lastFetch:new Date},i=function(r){var i,s,c,u,d,v;return a(this,function(a){switch(a.label){case 0:i=!0,s=new AbortController,c=setTimeout(function(){return s.abort()},t),a.label=1;case 1:return a.trys.push([1,7,8,9]),[4,fetch(o.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:s.signal})];case 2:return(u=a.sent()).ok?[3,4]:[4,u.text()];case 3:return d=a.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(u.status,": ").concat(d)),u.status===B||u.status===W?(o.logger.error("Remote config client fetch failed with ".concat(u.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,i=!1):u.status>=400&&u.status<500&&u.status!==z&&(i=!1),[3,6];case 4:return[4,u.json()];case 5:return[2,{value:{remoteConfig:a.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(v=a.sent())instanceof Error&&"AbortError"===v.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: "),v),[3,9];case 8:return clearTimeout(c),[7];case 9:return i?r<e-1?[4,new Promise(function(e){return setTimeout(e,l.getJitterDelay(n))})]:[3,11]:[2,"break"];case 10:a.sent(),a.label=11;case 11:return[2]}})},o=this,s=0,u.label=1;case 1:return s<e?[5,i(s)]:[3,4];case 2:if("object"==typeof(c=u.sent()))return[2,c.value];if("break"===c)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 t=encodeURIComponent(this.apiKey),n=new URLSearchParams;return n.append("config_group",e.CONFIG_GROUP),"".concat(this.serverUrl,"/").concat(t,"?").concat(n.toString())},e.CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(_||(_={}));var H,Q="https://app.amplitude.com",J={US:Q,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var G="__AMPLITUDE_MESSENGER_INSTANCE__",$="__AMPLITUDE_MESSENGER__",Z=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?Q:t;this[H]=!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 s(this,void 0,void 0,function(){var t,n,r;return a(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===Q&&(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,c=null==a?void 0:a.action;if(c)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"===c)return void r.notify({action:"pong"});var l=r.actionHandlers.get(c);if(l)l(a.data);else{var u=null!==(s=r.pendingMessages.get(c))&&void 0!==s?s:[];u.push(a.data),r.pendingMessages.set(c,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=g();(null==e?void 0:e[$])===this&&delete e[$]},e}();function V(e){var t,n=g(),r=null==n?void 0:n[$];if("object"==typeof(t=r)&&null!==t&&G in t&&!0===t[G])return r;var i=new Z(e);return n&&(n[$]=i),i}H=G;var X="__AMPLITUDE_BACKGROUND_CAPTURE__";var Y,ee="[Amplitude]",te="".concat(ee," Session Replay ID"),ne=_.US,re={enabled:!0},ie=1e3,oe="".concat(ee," Session Replay Debug"),se="amp-mask",ae="amp-unmask",ce="https://api-sr.amplitude.com/sessions/v2/track",le="https://api-sr.eu.amplitude.com/sessions/v2/track",ue="https://api-sr.stag2.amplitude.com/sessions/v2/track",de=9e6,ve=/payload.*exceed/i,he=1024,fe="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"}(Y||(Y={}));var ge=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";function me(e,t){return t||("STAGING"===e?ue:"EU"===e?le:ce)}var ye=function(e,t,n){switch(t){case"light":if("input"!==e)return!0;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":case"conservative":return!0;default:return ye(e,pe,n)}},be=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(Pe(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},Se=function(e,t,n,r){var i,o;if(void 0===t&&(t={defaultMaskLevel:pe}),n){if(n.closest("."+se))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("."+ae))return!1;var a=(null!==(o=t.unmaskSelector)&&void 0!==o?o:[]).some(function(e){return n.closest(e)});if(a)return!1}return ye(e,be(r,t),n)},Ie=function(e,t,n){return function(r,i){return Se(e,t,i,null==n?void 0:n())?r.replace(/[^\s]/g,"*"):r}},we=function(e,t){return function(n,r,i){var o;return"style"===n?r:(null!==(o=null==e?void 0:e.maskAttributes)&&void 0!==o?o:[]).includes(n)&&Se("text",e,i,null==t?void 0:t())?r.replace(/[^\s]/g,"*"):r}},Ce=function(){var e=g();return(null==e?void 0:e.location)?e.location.href:""},ke=new Map,Pe=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 c=new RegExp("^".concat(a,"$"));return ke.set(e,c),c},Ee=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=Pe(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},xe=function(){return s(void 0,void 0,void 0,function(){var e,t,n,r,i,o,s;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),(e=g())?[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/he):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:""}]}})})},Me=function(e){var t=i({},e),n=t.apiKey;return t.apiKey="****".concat(n.substring(n.length-4)),t},Re=function(){return{flushMaxRetries:2,logLevel:f.Warn,loggerProvider:new S,transportProvider:new j}},Oe=function(e){function n(t,n){var r,o,s,a,c,d,v,h,f,g,p=this,m=Re();if((p=e.call(this,i(i({transportProvider:m.transportProvider,loggerProvider:new ge(n.loggerProvider||m.loggerProvider)},n),{apiKey:t}))||this).flushMaxRetries=void 0!==n.flushMaxRetries&&n.flushMaxRetries<=m.flushMaxRetries?n.flushMaxRetries:m.flushMaxRetries,p.apiKey=t,p.sampleRate=n.sampleRate||0,p.serverZone=n.serverZone||ne,p.configServerUrl=n.configServerUrl,p.trackServerUrl=n.trackServerUrl,p.shouldInlineStylesheet=n.shouldInlineStylesheet,p.version=n.version,p.performanceConfig=n.performanceConfig||re,p.storeType=null!==(r=n.storeType)&&void 0!==r?r:"memory",p.applyBackgroundColorToBlockedElements=null!==(o=n.applyBackgroundColorToBlockedElements)&&void 0!==o&&o,p.enableUrlChangePolling=null!==(s=n.enableUrlChangePolling)&&void 0!==s&&s,p.urlChangePollingInterval=null!==(a=n.urlChangePollingInterval)&&void 0!==a?a:ie,p.captureDocumentTitle=null!==(c=n.captureDocumentTitle)&&void 0!==c&&c,void 0!==n.fullSnapshotIntervalMs&&(p.fullSnapshotIntervalMs=n.fullSnapshotIntervalMs),p.privacyConfig=i(i({},null!==(d=n.privacyConfig)&&void 0!==d?d:{}),{unmaskSelector:Array.from(new Set(u([".".concat(ae)],l(null!==(h=null===(v=n.privacyConfig)||void 0===v?void 0:v.unmaskSelector)&&void 0!==h?h:[]),!1)))}),n.interactionConfig&&(p.interactionConfig=n.interactionConfig,p.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")}(p.interactionConfig.ugcFilterRules)),n.debugMode&&(p.debugMode=n.debugMode),void 0!==n.useWebWorker)p.useWebWorker=n.useWebWorker;else{var y=n;void 0!==(null===(f=y.experimental)||void 0===f?void 0:f.useWebWorker)&&(p.useWebWorker=y.experimental.useWebWorker)}return p.captureAdoptedStyleSheets=null===(g=n.captureAdoptedStyleSheets)||void 0===g||g,n.crossOriginIframes&&(p.crossOriginIframes=n.crossOriginIframes),p}return t(n,e),n}(w),Te=(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))(Te||{}),Le=(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))(Le||{}),_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||{}),De=function(){function e(e,t){this.localConfig=t,this.remoteConfigClient=e}return e.prototype.generateJoinedConfig=function(){var e,t,n,r,o,d,v;return s(this,void 0,void 0,function(){var s,h,f,g,p,m,y,b,S,I,w,C,k,P,E,x,M,R=this;return a(this,function(a){switch(a.label){case 0:(s=i({},this.localConfig)).optOut=this.localConfig.optOut,s.captureEnabled=!0,a.label=1;case 1:return a.trys.push([1,3,,4]),[4,new Promise(function(e,t){R.remoteConfigClient.subscribe("configs.sessionReplay","all",function(n,r){var i;if(R.localConfig.loggerProvider.debug("Session Replay remote configuration received from ".concat(r,":"),JSON.stringify(n,null,2)),n){var o=n,a=o.sr_sampling_config,c=o.sr_privacy_config,l=o.sr_targeting_config,u=null===(i=s.interactionConfig)||void 0===i?void 0:i.ugcFilterRules;s.interactionConfig=o.sr_interaction_config,s.interactionConfig&&u&&(s.interactionConfig.ugcFilterRules=u),s.loggingConfig=o.sr_logging_config,(a||c||l)&&(h={},a&&(h.sr_sampling_config=a),c&&(h.sr_privacy_config=c),l&&(h.sr_targeting_config=l)),e()}else t(new Error("No remote config received"))})})];case 2:return a.sent(),[3,4];case 3:return f=a.sent(),this.localConfig.loggerProvider.error("Failed to generate joined config: ",f),s.captureEnabled=!1,[2,{localConfig:this.localConfig,joinedConfig:s,remoteConfig:void 0}];case 4:if(!h)return[2,{localConfig:this.localConfig,joinedConfig:s,remoteConfig:h}];if(g=h.sr_sampling_config,p=h.sr_privacy_config,m=h.sr_targeting_config,g&&Object.keys(g).length>0?(Object.prototype.hasOwnProperty.call(g,"capture_enabled")?s.captureEnabled=g.capture_enabled:s.captureEnabled=!1,Object.prototype.hasOwnProperty.call(g,"sample_rate")&&(s.sampleRate=g.sample_rate)):(s.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),p){y=null!==(e=s.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:u([],l(new Set(u(u([],l(null!==(r=y.maskAttributes)&&void 0!==r?r:[]),!1),l(null!==(o=p.maskAttributes)&&void 0!==o?o:[]),!1))),!1),urlMaskLevels:u(u([],l(null!==(d=p.urlMaskLevels)&&void 0!==d?d:[]),!1),l(null!==(v=y.urlMaskLevels)&&void 0!==v?v:[]),!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 v=c(null!==(a=e.blockSelector)&&void 0!==a?a:[]),h=v.next();!h.done;h=v.next()){d[h.value]="block"}}catch(e){t={error:e}}finally{try{h&&!h.done&&(n=v.return)&&n.call(v)}finally{if(t)throw t.error}}try{for(var f=c(null!==(l=e.maskSelector)&&void 0!==l?l:[]),g=f.next();!g.done;g=f.next()){d[g.value]="mask"}}catch(e){r={error:e}}finally{try{g&&!g.done&&(i=f.return)&&i.call(f)}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=i(i({},S(y)),S(p));try{for(w=c(Object.entries(I)),C=w.next();!C.done;C=w.next())k=l(C.value,2),P=k[0],"mask"===(E=k[1])?b.maskSelector.push(P):"block"===E?b.blockSelector.push(P):"unmask"===E&&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}}s.privacyConfig=(O=b,T=this.localConfig.loggerProvider,L=document.createDocumentFragment(),_=function(e){if(void 0===e&&(e=[]),"string"==typeof e&&(e=[e]),e=e.filter(function(e){try{L.querySelector(e)}catch(t){return T.warn('[session-replay-browser] omitting selector "'.concat(e,'" because it is invalid')),!1}return!0}),0!==e.length)return e},O.blockSelector=_(O.blockSelector),O.maskSelector=_(O.maskSelector),O.unmaskSelector=_(O.unmaskSelector),O)}return m&&Object.keys(m).length>0&&(s.targetingConfig=m),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:Me(s)},null,2)),[2,{localConfig:this.localConfig,joinedConfig:s,remoteConfig:h}]}var O,T,L,_})})},e}(),Fe=function(e,t){return s(void 0,void 0,void 0,function(){var n,r;return a(this,function(i){return n=new Oe(e,t),r=new K(e,n.loggerProvider,n.serverZone,t.configServerUrl),[2,new De(r,n)]})})};function Ae(e){if(e.type!==Te.IncrementalSnapshot)return!1;var t=e.data;return t.source===Le.Mutation&&!t.isAttachIframe}function qe(e){var t,n,r,o,s=e[0],a=new Map,u=new Map,d=new Map,v=new Map,h=new Map;e.forEach(function(e,t){var n,r,i,o,s=e.data;try{for(var l=c(s.adds),f=l.next();!f.done;f=l.next()){var g=f.value;a.has(g.node.id)||a.set(g.node.id,t),u.set(g.node.id,t),h.set(g.node.id,g.parentId)}}catch(e){n={error:e}}finally{try{f&&!f.done&&(r=l.return)&&r.call(l)}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),v.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 f=new Set,g=new Set;try{for(var p=c(a),m=p.next();!m.done;m=p.next()){var y=l(m.value,2),b=y[0],S=y[1],I=d.get(b);if(void 0!==I)u.get(b)>=v.get(b)||(S<I?f.add(b):I<S&&g.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(f.size>0||g.size>0)for(var C=!0;C;){C=!1;try{for(var k=(r=void 0,c(h)),P=k.next();!P.done;P=k.next()){var E=l(P.value,2),x=E[0],M=E[1];if(!f.has(x)&&!g.has(x)&&!w.has(x)&&(f.has(M)||g.has(M)||w.has(M))){var R=d.get(x),O=a.get(x);void 0!==R&&void 0!==O&&R<O?g.add(x):void 0!==R&&void 0!==O&&R===O?w.add(x):f.add(x),C=!0}}}catch(e){r={error:e}}finally{try{P&&!P.done&&(o=k.return)&&o.call(k)}finally{if(r)throw r.error}}}var T=f.size>0||g.size>0||w.size>0,L=[];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;f.has(s.id)||(g.has(s.id)&&t>=a.get(s.id)||w.has(s.id)&&(f.has(s.parentId)||g.has(s.parentId)||w.has(s.parentId))||L.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 _=e.flatMap(function(e){return e.data.adds}),D=e.flatMap(function(e){return e.data.texts}),F=e.flatMap(function(e){return e.data.attributes}),A={source:Le.Mutation,removes:L,adds:T?_.filter(function(e){return!f.has(e.node.id)&&!g.has(e.node.id)&&!w.has(e.node.id)}):_,texts:T?D.filter(function(e){return!f.has(e.id)&&!g.has(e.id)&&!w.has(e.id)}):D,attributes:T?F.filter(function(e){return!f.has(e.id)&&!g.has(e.id)&&!w.has(e.id)}):F};return i(i({},s),{data:A})}function Ue(e){if(e.length<=1)return e;for(var t=[],n=0;n<e.length;)if(Ae(e[n])){for(var r=n+1;r<e.length&&Ae(e[r]);)r++;t.push(r>n+1?qe(e.slice(n,r)):e[n]),n=r}else t.push(e[n]),n++;return t}var je=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=new Blob([e]).size;n>de?s.config.loggerProvider.warn("Session replay event dropped: serialized size ".concat(Math.round(n/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.")):s.eventsManager&&s.deviceId&&s.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:s.deviceId})},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,u([],l(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=g();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 c=new Blob([r],{type:"application/javascript"}),d=URL.createObjectURL(c),v=new Worker(d);v.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,")")),v.terminate(),s.worker=void 0},v.onmessage=function(e){var t=e.data,n=t.compressedEvent,r=t.sessionId;s.addCompressedEventToManager(n,r)},this.worker=v}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===Te.FullSnapshot){if(this.config.loggerProvider.debug("Processing full snapshot immediately."),this.taskQueue.length>0||this.pendingQueue.length>0){var s=u(u([],l(this.taskQueue.splice(0)),!1),l(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1);try{for(var a=c(s),d=a.next();!d.done;d=a.next()){var v=d.value,h=this.compressEvent(v.event);this.addCompressedEventToManager(h,v.sessionId)}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this.isProcessing=!1}var f=this.compressEvent(e);return this.addCompressedEventToManager(f,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,u([],l(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(!(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=Ue(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 v=d.value;i.push({event:v,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}(),Ne="Session replay event batch rejected due to exceeded retry count",Be="Failed to store session replay events in IndexedDB",We="1.42.1";function ze(e,t){return s(this,void 0,void 0,function(){var n,r,i,o,l,u,d,v,h,f,g,p,m,y,b=this;return a(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(),l=[],u=s(b,void 0,void 0,function(){var e,t,n;return a(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];l.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=l.reduce(function(e,t){return e+t.length},0),v=new Uint8Array(d),h=0;try{for(f=c(l),g=f.next();!g.done;g=f.next())p=g.value,v.set(p,h),h+=p.length}catch(e){m={error:e}}finally{try{g&&!g.done&&(y=f.return)&&y.call(f)}finally{if(m)throw m.error}}return[2,v];case 4:return S.sent(),[2,null];case 5:return[2]}})})}var Ke=function(){function e(e){var t=e.trackServerUrl,n=e.loggerProvider,r=e.payloadBatcher,i=e.workerScript,o=this;if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.loggerProvider=n,this.payloadBatcher=r||function(e){return e},this.trackServerUrl=t,i)try{var s=new Blob([i],{type:"application/javascript"}),a=URL.createObjectURL(s),u=new Worker(a);u.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,")")),u.terminate(),o.worker=void 0;try{for(var i=c(o.pendingWorkerRequests),s=i.next();!s.done;s=i.next()){var a=l(s.value,2)[1];n.warn("Session replay event send failed due to worker crash: ".concat(e.message)),a.resolve()}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}o.pendingWorkerRequests.clear()},u.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=o.pendingWorkerRequests.get(t.id);r&&(o.handlePayloadTooLargeResponse(r.context,t.isWaf),r.resolve(),o.pendingWorkerRequests.delete(t.id))}else if("complete"===t.type){var i=o.pendingWorkerRequests.get(t.id);i&&(o.completeRequest({context:i.context}),i.resolve(),o.pendingWorkerRequests.delete(t.id))}},this.worker=u}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(i(i({},e),{attempts:0,timeout:0}))},e.prototype.sendBeacon=function(e){var t,n,r=e.events,i=e.sessionId,o=e.deviceId,s=e.apiKey,a=e.serverZone,c=function(e){return new Blob([e]).size},l=r,u=JSON.stringify({version:2,events:l});if(c(u)>65536){for(var d=0,v=l.length;d<v;){var h=Math.floor((d+v+1)/2);c(JSON.stringify({version:2,events:l.slice(0,h)}))<=65536?d=h:v=h-1}l=l.slice(0,d),u=JSON.stringify({version:2,events:l}),this.loggerProvider.warn("sendBeacon payload exceeded 64 KB limit, trimmed from ".concat(r.length," to ").concat(l.length," events"))}if(0!==l.length){var f=new URLSearchParams({device_id:o,session_id:String(i),type:"replay",api_key:s}),p="".concat(me(a,this.trackServerUrl),"?").concat(f.toString()),m=g();try{var y=new Blob([u],{type:"application/json"});!1===(null===(n=null===(t=null==m?void 0:m.navigator)||void 0===t?void 0:t.sendBeacon)||void 0===n?void 0:n.call(t,p,y))&&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 t.attempts<(t.flushMaxRetries||0)?(t.attempts+=1,!0):(e.completeRequest({context:t,err:Ne}),!1)}).forEach(function(t){e.queue=e.queue.concat(t),e.schedule(0)})},e.prototype.schedule=function(e){var t=this;this.scheduled||(this.scheduled=setTimeout(function(){t.flush(!0).then(function(){t.queue.length>0&&t.schedule(e)})},e))},e.prototype.flush=function(e){return void 0===e&&(e=!1),s(this,void 0,void 0,function(){var t,n,r,i,o,s,l;return a(this,function(a){switch(a.label){case 0:t=this.queue,this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),a.label=1;case 1:a.trys.push([1,6,7,8]),n=c(t),r=n.next(),a.label=2;case 2:return r.done?[3,5]:(i=r.value,[4,this.send(i,e)]);case 3:a.sent(),a.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=a.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(l=n.return)&&l.call(n)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},e.prototype.send=function(e,t){return void 0===t&&(t=!0),s(this,void 0,void 0,function(){var n,r,i,o;return a(this,function(s){return(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 s(this,void 0,void 0,function(){var i,o=this;return a(this,function(s){return i="".concat(++this.sendIdCounter),[2,new Promise(function(s){var a;o.pendingWorkerRequests.set(i,{context:t,resolve:s}),e.postMessage({type:"send",id:i,payload:n,useRetry:r,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:Ce(),sdkVersion:We}})})]})})},e.prototype.sendOnMainThread=function(e,t,n,r,o){var c,l,u,d;return s(this,void 0,void 0,function(){var s,v,h,f,p,m,y,b,S,I,w,C,k,P,E;return a(this,function(a){switch(a.label){case 0:s=Ce(),v=We,h=n.sampleRate,f=new URLSearchParams({device_id:t,session_id:"".concat(n.sessionId),type:"".concat(n.type)}),p="".concat(null!==(l=null===(c=n.version)||void 0===c?void 0:c.type)&&void 0!==l?l:"standalone","/").concat(null!==(d=null===(u=n.version)||void 0===u?void 0:u.version)&&void 0!==d?d:v),a.label=1;case 1:return a.trys.push([1,13,,14]),m=JSON.stringify(r),(y=g())&&"CompressionStream"in y?[4,ze(m,y)]:[3,3];case 2:return S=a.sent(),[3,4];case 3:S=null,a.label=4;case 4:return I=(b=S)?b.byteLength:new Blob([m]).size,w={headers:i({"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(e),"X-Client-Version":v,"X-Client-Library":p,"X-Client-Url":s.substring(0,1e3),"X-Client-Sample-Rate":"".concat(h),"X-Sampling-Hash-Alg":"xxhash32"},b?{"Content-Encoding":"gzip"}:{}),body:null!=b?b:m,method:"POST",keepalive:I<=65536},C="".concat(me(n.serverZone,this.trackServerUrl),"?").concat(f.toString()),[4,fetch(C,w)];case 5:if(null===(k=a.sent()))return this.completeRequest({context:n,err:"Unexpected error occurred"}),[2];if(o)return[3,6];P="";try{P=JSON.stringify(k.body,null,2)}catch(e){}return this.completeRequest({context:n,success:"".concat(k.status,": ").concat(P)}),[3,12];case 6:if(P="",413!==k.status)return[3,10];a.label=7;case 7:return a.trys.push([7,9,,10]),[4,k.text()];case 8:return P=a.sent(),[3,10];case 9:return a.sent(),[3,10];case 10:return[4,this.handleReponse(k.status,n,P)];case 11:a.sent(),a.label=12;case 12:return[3,14];case 13:return E=a.sent(),this.completeRequest({context:n,err:E}),[3,14];case 14:return[2]}})})},e.prototype.handleReponse=function(e,t,n){return void 0===n&&(n=""),s(this,void 0,void 0,function(){var r;return a(this,function(i){switch(i.label){case 0:switch(r=(new U).buildStatus(e),r){case d.Success:return[3,1];case d.Failed:case d.Timeout:case d.RateLimit:return[3,2];case d.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,ve.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)/he);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 o=function(){return Promise.resolve()},s=Math.floor(e.events.length/2);this.sendEventsList(i(i({},e),{events:e.events.slice(0,s),onComplete:o})),this.sendEventsList(i(i({},e),{events:e.events.slice(s),onComplete:o}))}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(new Blob(e.events).size/he);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 s(this,void 0,void 0,function(){var t;return a(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:Ne}),[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}();const He=(e,t)=>t.some(t=>e instanceof t);let Qe,Je;const Ge=new WeakMap,$e=new WeakMap,Ze=new WeakMap;let Ve={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Ge.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return tt(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Xe(e){Ve=e(Ve)}function Ye(e){return(Je||(Je=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(nt(this),t),tt(this.request)}:function(...t){return tt(e.apply(nt(this),t))}}function et(e){return"function"==typeof e?Ye(e):(e instanceof IDBTransaction&&function(e){if(Ge.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)});Ge.set(e,t)}(e),He(e,Qe||(Qe=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Ve):e)}function tt(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(tt(e.result)),r()},o=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",o)});return Ze.set(t,e),t}(e);if($e.has(e))return $e.get(e);const t=et(e);return t!==e&&($e.set(e,t),Ze.set(t,e)),t}const nt=e=>Ze.get(e);function rt(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=tt(s);return r&&s.addEventListener("upgradeneeded",e=>{r(tt(s.result),e.oldVersion,e.newVersion,tt(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 it=["get","getKey","getAll","getAllKeys","count"],ot=["put","add","delete","clear"],st=new Map;function at(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(st.get(t))return st.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=ot.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!it.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 st.set(t,o),o}Xe(e=>({...e,get:(t,n,r)=>at(t,n)||e.get(t,n,r),has:(t,n)=>!!at(t,n)||e.has(t,n)}));const ct=["continue","continuePrimaryKey","advance"],lt={},ut=new WeakMap,dt=new WeakMap,vt={get(e,t){if(!ct.includes(t))return e[t];let n=lt[t];return n||(n=lt[t]=function(...e){ut.set(this,dt.get(this)[t](...e))}),n}};async function*ht(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,vt);for(dt.set(n,t),Ze.set(n,nt(t));t;)yield n,t=await(ut.get(n)||t.continue()),ut.delete(n)}function ft(e,t){return t===Symbol.asyncIterator&&He(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&He(e,[IDBIndex,IDBObjectStore])}Xe(e=>({...e,get:(t,n,r)=>ft(t,n)?ht:e.get(t,n,r),has:(t,n)=>ft(t,n)||e.has(t,n)}));var gt=function(){function e(e){var t,n,r,i=this;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=7e5,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=function(e,t){var n=i.getStringSize(t);return i.getEventsArraySize(e)+n>=i.maxPersistedEventsSize||!!(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}return Object.defineProperty(e.prototype,"timeAtLastSplit",{get:function(){return this._timeAtLastSplit},enumerable:!1,configurable:!0}),e.prototype.getStringSize=function(e){for(var t=0,n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t++;else if(r<=2047)t+=2;else if(r>=55296&&r<=56319){var i=n+1<e.length?e.charCodeAt(n+1):NaN;i>=56320&&i<=57343?(t+=4,n++):t+=3}else t+=3}return t},e.prototype.getEventsArraySize=function(e){var t,n,r=0;try{for(var i=c(e),o=i.next();!o.done;o=i.next()){var s=o.value;r+=this.getStringSize(s)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return r+(2+Math.max(0,e.length-1)+2*e.length)},e}(),pt=function(e,t,n){var r;"object"==typeof(r=n)&&null!==r&&"AbortError"===r.name?e.debug(t):e.warn(t)};var mt="sessionCurrentSequence",yt="sequencesToSend",bt=5e3;function St(e,t,n){var r=setTimeout(n,t);return e.then(function(){return clearTimeout(r)},function(){return clearTimeout(r)}),function(){return clearTimeout(r)}}var It,wt,Ct,kt=function(e){var t,n;return e.objectStoreNames.contains(mt)||(n=e.createObjectStore(mt,{keyPath:"sessionId"})),e.objectStoreNames.contains(yt)||(t=e.createObjectStore(yt,{keyPath:"sequenceId",autoIncrement:!0})).createIndex("sessionId","sessionId"),{sequencesStore:t,currentSequenceStore:n}},Pt=function(e){return s(void 0,void 0,void 0,function(){return a(this,function(t){switch(t.label){case 0:return[4,(n=rt(e,1,{upgrade:kt}),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})})},Et=function(e){function n(t){var n,r=this;return(r=e.call(this,t)||this).consecutiveFailures=0,r.hasTriggeredFallback=!1,r.getSequencesToSend=function(){return s(r,void 0,void 0,function(){var e,t,n,r,i,o,s,c,l,u,d=this;return a(this,function(a){switch(a.label){case 0:e=!1,t=!1,a.label=1;case 1:return a.trys.push([1,6,,7]),n=[],(r=this.db.transaction("sequencesToSend")).done.catch(function(n){e||t||(pt(d.loggerProvider,"".concat(Be,": ").concat(n),n),d.recordFailure())}),i=St(r.done,bt,function(){e||t||(t=!0,pt(d.loggerProvider,"".concat(Be,": transaction timed out")),d.recordFailure())}),[4,r.store.openCursor()];case 2:o=a.sent(),a.label=3;case 3:return o?(s=o.value,c=s.sessionId,l=s.events,n.push({events:l,sequenceId:o.key,sessionId:c}),[4,o.continue()]):[3,5];case 4:return o=a.sent(),[3,3];case 5:return this.recordSuccess(),i(),[2,n];case 6:return u=a.sent(),t||(e=!0,pt(this.loggerProvider,"".concat(Be,": ").concat(u),u),this.recordFailure()),[3,7];case 7:return[2,void 0]}})})},r.storeCurrentSequence=function(e){return s(r,void 0,void 0,function(){var t,n,r,s,c,l,u,d,v=this;return a(this,function(a){switch(a.label){case 0:t=!1,n=!1,a.label=1;case 1:return a.trys.push([1,5,,6]),(r=this.db.transaction([mt,yt],"readwrite")).done.catch(function(e){t||n||(pt(v.loggerProvider,"".concat(Be,": ").concat(e),e),v.recordFailure())}),s=St(r.done,bt,function(){t||n||(n=!0,pt(v.loggerProvider,"".concat(Be,": transaction timed out")),v.recordFailure())}),[4,r.objectStore(mt).get(e)];case 2:return!(c=a.sent())||c.tabId&&c.tabId!==this.tabId||0===c.events.length?(s(),[2,void 0]):[4,r.objectStore(yt).put({sessionId:e,events:c.events,tabId:this.tabId})];case 3:return l=a.sent(),[4,r.objectStore(mt).put({sessionId:e,events:[],tabId:this.tabId})];case 4:return a.sent(),this.recordSuccess(),s(),c.tabId,u=o(c,["tabId"]),[2,i(i({},u),{sessionId:e,sequenceId:l})];case 5:return d=a.sent(),n||(t=!0,pt(this.loggerProvider,"".concat(Be,": ").concat(d),d),this.recordFailure()),[3,6];case 6:return[2,void 0]}})})},r.addEventToCurrentSequence=function(e,t){return s(r,void 0,void 0,function(){var n,r,i,o,s,c,l,u,d,v=this;return a(this,function(a){switch(a.label){case 0:n=!1,r=!1,a.label=1;case 1:return a.trys.push([1,13,,14]),(i=this.db.transaction([mt,yt],"readwrite")).done.catch(function(e){n||r||(pt(v.loggerProvider,"".concat(Be,": ").concat(e),e),v.recordFailure())}),o=St(i.done,bt,function(){n||r||(r=!0,pt(v.loggerProvider,"".concat(Be,": transaction timed out")),v.recordFailure())}),[4,i.objectStore(mt).get(e)];case 2:return(null==(s=a.sent())?void 0:s.tabId)&&s.tabId!==this.tabId?s.events.length>0?[4,i.objectStore(yt).put({sessionId:e,events:s.events,tabId:s.tabId})]:[3,4]:[3,6];case 3:a.sent(),a.label=4;case 4:return[4,i.objectStore(mt).put({sessionId:e,events:[t],tabId:this.tabId})];case 5:return a.sent(),this.recordSuccess(),o(),[2,void 0];case 6:return(c=s)?[3,8]:[4,i.objectStore(mt).put({sessionId:e,events:[t],tabId:this.tabId})];case 7:return a.sent(),this.recordSuccess(),o(),[2,void 0];case 8:return this.shouldSplitEventsList(c.events,t)?[3,10]:[4,i.objectStore(mt).put({sessionId:e,events:c.events.concat(t),tabId:this.tabId})];case 9:return a.sent(),this.recordSuccess(),o(),[2,void 0];case 10:return l=c.events,[4,i.objectStore(mt).put({sessionId:e,events:[t],tabId:this.tabId})];case 11:return a.sent(),[4,i.objectStore(yt).put({sessionId:e,events:l,tabId:this.tabId})];case 12:return u=a.sent(),this.recordSuccess(),o(),[2,{events:l,sessionId:e,sequenceId:u}];case 13:return d=a.sent(),r||(n=!0,pt(this.loggerProvider,"".concat(Be,": ").concat(d),d),this.recordFailure()),[3,14];case 14:return[2,void 0]}})})},r.storeSendingEvents=function(e,t){return s(r,void 0,void 0,function(){var n,r;return a(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.db.put(yt,{sessionId:e,events:t,tabId:this.tabId})];case 1:return n=i.sent(),this.recordSuccess(),[2,n];case 2:return r=i.sent(),pt(this.loggerProvider,"".concat(Be,": ").concat(r),r),this.recordFailure(),[3,3];case 3:return[2,void 0]}})})},r.cleanUpSessionEventsStore=function(e,t){return s(r,void 0,void 0,function(){var e;return a(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(yt,t)];case 2:return n.sent(),this.recordSuccess(),[3,4];case 3:return e=n.sent(),pt(this.loggerProvider,"".concat(Be,": ").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 t(n,e),n.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))},n.prototype.recordSuccess=function(){this.consecutiveFailures=0},n.new=function(e,t){var r;return s(this,void 0,void 0,function(){var o,s,c,l,u;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),o="replay"===e?"":"_".concat(e),s="".concat(t.apiKey.substring(0,10),"_amp_session_replay_events").concat(o),[4,Pt(s)];case 1:return c=a.sent(),l=null!==(r=t.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 n(i(i({},t),{db:c,tabId:l}))];case 2:return u=a.sent(),pt(t.loggerProvider,"".concat(Be,": ").concat(u),u),[3,3];case 3:return[2]}})})},n.prototype.getCurrentSequenceEvents=function(e){return s(this,void 0,void 0,function(){var t,n,r,i,s,l,u,d;return a(this,function(a){switch(a.label){case 0:return e?[4,this.db.get("sessionCurrentSequence",e)]:[3,2];case 1:return(i=a.sent())?i.tabId&&i.tabId!==this.tabId?[2,void 0]:(i.tabId,[2,[s=o(i,["tabId"])]]):[2,void 0];case 2:t=[],a.label=3;case 3:return a.trys.push([3,8,9,10]),[4,this.db.getAll("sessionCurrentSequence")];case 4:n=c.apply(void 0,[a.sent()]),r=n.next(),a.label=5;case 5:if(r.done)return[3,7];if((i=r.value).tabId&&i.tabId!==this.tabId)return[3,6];i.tabId,s=o(i,["tabId"]),t.push(s),a.label=6;case 6:return r=n.next(),[3,5];case 7:return[3,10];case 8:return l=a.sent(),u={error:l},[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]}})})},n}(gt),xt=function(e){function n(){var t=null!==e&&e.apply(this,arguments)||this;return t.finalizedSequences={},t.sequences={},t.sequenceId=0,t}return t(n,e),n.prototype.resetCurrentSequence=function(e){this.sequences[e]=[]},n.prototype.addSequence=function(e){var t=this.sequenceId++,n=u([],l(this.sequences[e]),!1);return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}},n.prototype.getSequencesToSend=function(){return s(this,void 0,void 0,function(){return a(this,function(e){return[2,Object.entries(this.finalizedSequences).map(function(e){var t=l(e,2),n=t[0],r=t[1],i=r.sessionId,o=r.events;return{sequenceId:Number(n),sessionId:i,events:o}})]})})},n.prototype.storeCurrentSequence=function(e){return s(this,void 0,void 0,function(){return a(this,function(t){return this.sequences[e]?[2,this.addSequence(e)]:[2,void 0]})})},n.prototype.addEventToCurrentSequence=function(e,t){return s(this,void 0,void 0,function(){var n;return a(this,function(r){return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(n=this.addSequence(e)),this.sequences[e].push(t),[2,n]})})},n.prototype.storeSendingEvents=function(e,t){return s(this,void 0,void 0,function(){return a(this,function(n){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},[2,this.sequenceId++]})})},n.prototype.cleanUpSessionEventsStore=function(e,t){return s(this,void 0,void 0,function(){return a(this,function(e){return void 0!==t&&delete this.finalizedSequences[t],[2]})})},n}(gt),Mt=function(e){var t=e.config,n=e.minInterval,r=e.maxInterval,o=e.type,c=e.payloadBatcher,d=e.storeType,v=e.trackDestinationWorkerScript;return s(void 0,void 0,void 0,function(){function e(e){return void 0===e&&(e=!1),s(this,void 0,void 0,function(){return a(this,function(t){return[2,h.flush(e)]})})}var h,f,g,p,m,y,b,S,I,w,C,k,P,E,x;return a(this,function(M){switch(M.label){case 0:return h=new Ke(i(i({},t),{loggerProvider:t.loggerProvider,payloadBatcher:c,workerScript:v})),f=function(){return new xt({loggerProvider:t.loggerProvider,maxInterval:r,minInterval:n})},p=!1,y=function(){return s(void 0,void 0,void 0,function(){var e,n,r;return a(this,function(i){switch(i.label){case 0:return p?(p=!1,t.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store."),g?[4,m.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,m=f(),e&&g&&(r=g,e.forEach(function(e){k({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r})})),[2]}})})},b=function(){return s(void 0,void 0,void 0,function(){var e;return a(this,function(i){switch(i.label){case 0:return[4,Et.new(o,{loggerProvider:t.loggerProvider,minInterval:n,maxInterval:r,apiKey:t.apiKey,onPersistentFailure:function(){y()}})];case 1:return(e=i.sent())?(p=!0,[2,e]):(t.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),[2,f()])}})})},"idb"!==d?[3,2]:[4,b()];case 1:return S=M.sent(),[3,3];case 2:S=f(),M.label=3;case 3:return m=S,I=[],w=0,C=function(e){if(!(e<=w)){var t=Math.min(e-w,I.length);t>0&&(I.splice(0,t),w=e)}},k=function(e){var n=e.events,r=e.sessionId,i=e.deviceId,c=e.sequenceId,l=n.map(function(e){return{event:e,bytes:new Blob([e]).size}}),u=l.filter(function(e){return e.bytes>de});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.bytes/1024)," KB")}).join(", "),". If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support."));var d=u.length>0?l.filter(function(e){return e.bytes<=de}).map(function(e){return e.event}):n;0!==d.length?(t.debugMode&&xe().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(){}),h.sendEventsList({events:d,sessionId:r,flushMaxRetries:t.flushMaxRetries,apiKey:t.apiKey,deviceId:i,sampleRate:t.sampleRate,serverZone:t.serverZone,version:t.version,type:o,onComplete:function(){return s(void 0,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:return[4,m.cleanUpSessionEventsStore(r,c)];case 1:return e.sent(),[2]}})})}})):m.cleanUpSessionEventsStore(r,c).catch(function(e){t.loggerProvider.warn("Failed to clean up session replay events store:",e)})},P=function(e){var n=e.sessionId,r=e.deviceId;g=r;var i=w+I.length;m.storeCurrentSequence(n).then(function(e){e&&(C(i),k({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)})},E=function(e){var n=e.deviceId;return s(void 0,void 0,void 0,function(){var e;return a(this,function(r){switch(r.label){case 0:return g=n,[4,m.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.forEach(function(e){k({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}),[2]):[2]}})})},x=function(e){var n=e.event,r=e.sessionId,i=e.deviceId;g=i;var o=w+I.length;I.push(n.data),m.addEventToCurrentSequence(r,n.data).then(function(e){e&&(C(o),k({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:P,addEvent:x,sendStoredEvents:E,flush:e,getBeaconEvents:function(){return u([],l(I),!1)},trackDestination:h}]}})})},Rt=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 s(this,void 0,void 0,function(){var t;return a(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 s(this,void 0,void 0,function(){var t;return a(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 Ot(e,t){if(Ct=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};It=i(i({},n),t),wt=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(It.root,n);var r=Tt(e,"all",function(){return Tt(e,"two",function(){return Tt(e,"one",function(){return Tt(e,"none")})})});if(r){var o=Bt(Wt(r,e));return o.length>0&&(r=o[0]),_t(r)}throw new Error("Selector was not found.")}function Tt(e,t,n){for(var r=null,i=[],o=e,s=0,a=function(){var e,a,d=(new Date).getTime()-Ct.getTime();if(void 0!==It.timeoutMs&&d>It.timeoutMs)throw new Error("Timeout: Can't find a unique selector after ".concat(d,"ms"));var v=Ut(function(e){var t=e.getAttribute("id");if(t&&It.idName(t))return{name:"#"+CSS.escape(t),penalty:0};return null}(o))||Ut.apply(void 0,u([],l(function(e){var t=Array.from(e.attributes).filter(function(e){return It.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))||Ut.apply(void 0,u([],l(function(e){var t=Array.from(e.classList).filter(It.className);return t.map(function(e){return{name:"."+CSS.escape(e),penalty:1}})}(o)),!1))||Ut(function(e){var t=e.tagName.toLowerCase();if(It.tagName(t))return{name:t,penalty:2};return null}(o))||[{name:"*",penalty:3}],h=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)h&&(v=v.concat(v.filter(qt).map(function(e){return At(e,h)})));else if("two"==t)v=v.slice(0,1),h&&(v=v.concat(v.filter(qt).map(function(e){return At(e,h)})));else if("one"==t){var f=l(v=v.slice(0,1),1)[0];h&&qt(f)&&(v=[At(f,h)])}else"none"==t&&(v=[{name:"*",penalty:3}],h&&(v=[At(v[0],h)]));try{for(var g=(e=void 0,c(v)),p=g.next();!p.done;p=g.next()){(f=p.value).level=s}}catch(t){e={error:t}}finally{try{p&&!p.done&&(a=g.return)&&a.call(g)}finally{if(e)throw e.error}}if(i.push(v),i.length>=It.seedMinLength&&(r=Lt(i,n)))return"break";o=o.parentElement,s++};o;){if("break"===a())break}return r||(r=Lt(i,n)),!r&&n?n():r}function Lt(e,t){var n,r,i=Bt(Nt(e));if(i.length>It.threshold)return t?t():null;try{for(var o=c(i),s=o.next();!s.done;s=o.next()){var a=s.value;if(Ft(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 _t(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 Dt(e){return e.map(function(e){return e.penalty}).reduce(function(e,t){return e+t},0)}function Ft(e){var t=_t(e);switch(wt.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 At(e,t){return{name:e.name+":nth-child(".concat(t,")"),penalty:e.penalty+1}}function qt(e){return"html"!==e.name&&!e.name.startsWith("#")}function Ut(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.filter(jt);return n.length>0?n:null}function jt(e){return null!=e}function Nt(e,t){var n,r,i,o,s,l;return void 0===t&&(t=[]),a(this,function(a){switch(a.label){case 0:if(!(e.length>0))return[3,9];a.label=1;case 1:a.trys.push([1,6,7,8]),n=c(e[0]),r=n.next(),a.label=2;case 2:return r.done?[3,5]:(i=r.value,[5,c(Nt(e.slice(1,e.length),t.concat(i)))]);case 3:a.sent(),a.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=a.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(l=n.return)&&l.call(n)}finally{if(s)throw s.error}return[7];case 8:return[3,11];case 9:return[4,t];case 10:a.sent(),a.label=11;case 11:return[2]}})}function Bt(e){return u([],l(e),!1).sort(function(e,t){return Dt(e)-Dt(t)})}function Wt(e,t,n){var r,i,o;return void 0===n&&(n={counter:0,visited:new Map}),a(this,function(s){switch(s.label){case 0:if(!(e.length>2&&e.length>It.optimizedMinLength))return[3,5];r=1,s.label=1;case 1:return r<e.length-1?n.counter>It.maxNumberOfTries?[2]:(n.counter+=1,(i=u([],l(e),!1)).splice(r,1),o=_t(i),n.visited.has(o)?[2]:Ft(i)&&function(e,t){return wt.querySelector(_t(e))===t}(i,t)?[4,i]:[3,4]):[3,5];case 2:return s.sent(),n.visited.set(o,!0),[5,c(Wt(i,t,n))];case 3:s.sent(),s.label=4;case 4:return r++,[3,1];case 5:return[2]}})}var zt=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}},Kt=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 o=r.reduce(function(e,t){var n=t.x,r=t.y,o=t.selector,s=t.timestamp,a=s-s%36e5,c="".concat(n,":").concat(r,":").concat(null!=o?o:"",":").concat(a);return e[c]?e[c].count+=1:e[c]=i(i({},t),{timestamp:a,count:1}),e},{});return{version:t,events:Object.values(o)}},Ht=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 c=g();if(c){var l=c.location,u=c.innerHeight,d=c.innerWidth;if(l){var v=e.x,h=e.y;if(void 0!==v&&void 0!==h){var f,p=o.getNode(e.id);if(p)try{f=Ot(p,a)}catch(e){n.logger.debug("error resolving selector from finder")}var m=Ee(l.href,s),y={x:v+n.scrollWatcher.currentScrollX,y:h+n.scrollWatcher.currentScrollY,selector:f,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 Qt(){var e=g();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function Jt(){var e=g();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}var Gt=function(){function e(e,t){var n=g();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=me(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}return e.prototype.send=function(e,t){var n=this.context,r=n.sessionId,i=n.type,o=new URLSearchParams({device_id:e,session_id:String(r),type:String(i),api_key:this.apiKey}),s="".concat(this.basePageUrl,"?").concat(o.toString());this.sendBeacon(s,t)||this.sendXhr(s,t)},e}(),$t=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(),c=g();if(c&&a){var l=null!==(r=c.scrollX)&&void 0!==r?r:0,u=null!==(i=c.scrollY)&&void 0!==i?i:0;(l>0||u>0)&&n.update({id:1,x:l,y:u}),n.transport.send(a,{version:1,events:[{maxScrollX:n._maxScrollX,maxScrollY:n._maxScrollY,maxScrollWidth:n._maxScrollWidth,maxScrollHeight:n._maxScrollHeight,viewportHeight:Qt(),viewportWidth:Jt(),pageUrl:Ee(c.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=Jt(),this._maxScrollHeight=Qt(),this.config=t,this.transport=e}return e.default=function(t,n){return new e(new Gt(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=Jt();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=Qt();this._maxScrollY=e.y;var o=e.y+i;o>this._maxScrollHeight&&(this._maxScrollHeight=o),this.timestamp=t}},e}(),Zt=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))},Vt=function(){var e=this;this.dbs={},this.createStore=function(t){return s(e,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:return[4,rt(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 s(e,void 0,void 0,function(){var e,n;return a(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 s(e,void 0,void 0,function(){var e,t,o,s;return a(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(),pt(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 s(e,void 0,void 0,function(){var e,t,s;return a(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(),pt(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 s(e,void 0,void 0,function(){var e,t,o,s,c,l,u,d;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,8,,9]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,(o=e.transaction("sessionTargetingMatch","readwrite")).store.getAll()];case 2:s=a.sent(),c=0,a.label=3;case 3:return c<s.length?(l=s[c],u=Date.now()-l.lastUpdated,l.sessionId!==t&&u>1728e5?[4,o.store.delete(l.sessionId)]:[3,5]):[3,6];case 4:a.sent(),a.label=5;case 5:return c++,[3,3];case 6:return[4,o.done];case 7:return a.sent(),[3,9];case 8:return d=a.sent(),pt(n,"Failed to clear old targeting matches for sessions: ".concat(d),d),[3,9];case 9:return[2]}})})}},Xt=new Vt,Yt=function(e){var t=e.sessionId,n=e.targetingConfig,r=e.loggerProvider,o=e.apiKey,c=e.targetingParams,l=e.urlChange,u=void 0!==l&&l;return s(void 0,void 0,void 0,function(){var e,s,l,d,v,h;return a(this,function(a){switch(a.label){case 0:return[4,Xt.clearStoreOfOldSessions({loggerProvider:r,apiKey:o,currentSessionId:t})];case 1:return a.sent(),[4,Xt.getTargetingMatchForSession({loggerProvider:r,apiKey:o,sessionId:t})];case 2:if(!0===a.sent()&&!u)return[2,!0];e=!0,a.label=3;case 3:return a.trys.push([3,6,,7]),[4,import("./index-min3.js")];case 4:return s=a.sent().evaluateTargeting,l=i(i({},c),{flag:n,sessionId:"string"==typeof t?parseInt(t,10):t,apiKey:o,loggerProvider:r}),[4,s(l)];case 5:return(d=a.sent())&&d.sr_targeting_config&&(e="on"===d.sr_targeting_config.key),Xt.storeTargetingMatchForSession({loggerProvider:r,apiKey:o,sessionId:t,targetingMatch:e}),[3,7];case 6:return v=a.sent(),h=v,r.warn(h.message),[3,7];case 7:return[2,e]}})})},en=2654435761,tn=2246822519,nn=3266489917,rn=374761393;function on(e,t){return(e<<t|e>>>32-t)>>>0}function sn(e,t){return e=on(e=e+Math.imul(t,tn)>>>0,13),e=Math.imul(e,en)>>>0}function an(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function cn(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+en+tn>>>0,a=t+tn>>>0,c=t>>>0,l=t-en>>>0;o<=i-16;)s=sn(s,an(r,o)),a=sn(a,an(r,o+=4)),c=sn(c,an(r,o+=4)),l=sn(l,an(r,o+=4)),o+=4;n=on(s,1)+on(a,7)+on(c,12)+on(l,18)>>>0}else n=t+rn>>>0;for(n=n+i>>>0;o<=i-4;)n=n+Math.imul(an(r,o),nn)>>>0,n=Math.imul(on(n,17),668265263)>>>0,o+=4;for(;o<i;)n=n+Math.imul(r[o],rn)>>>0,n=Math.imul(on(n,11),en)>>>0,o++;return n^=n>>>15,n=Math.imul(n,tn)>>>0,n^=n>>>13,n=Math.imul(n,nn)>>>0,(n^=n>>>16)>>>0}var ln="__amplitude_url_tracking_patched__",un=new WeakMap;function dn(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?ie:o;if(i){var a=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""},c=a(),l=e.setInterval(function(){var e=a();e!==c&&(c=e,t(e))},s);return function(){null!=l&&e.clearInterval(l)}}var u=un.get(e);if(!u){var d=void 0,v=new Set,h=function(){var t=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""}();void 0!==d&&t===d||(d=t,v.forEach(function(e){return e(t)}))},f=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 h(),r};return t[ln]=!0,t},g=e.history;if(null==g?void 0:g.pushState){var p=Reflect.get(g,"pushState");p[ln]||(g.pushState=f(p))}if(null==g?void 0:g.replaceState){var m=Reflect.get(g,"replaceState");m[ln]||(g.replaceState=f(m))}u={callbacks:v,notify:h,onPopStateOrHashChange:function(){return h()},listenersAttached:!1},un.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 vn(e){return void 0===e&&(e={}),{name:"amplitude/url-tracking@1",observer:function(t,n,r){var o,s,a,c=i(i({},e),r),l=c.ugcFilterRules||[],u=null!==(o=c.enablePolling)&&void 0!==o&&o,d=null!==(s=c.pollingInterval)&&void 0!==s?s:ie,v=null!==(a=c.captureDocumentTitle)&&void 0!==a&&a;if(!n)return function(){};var h=void 0,f=function(){return n.location&&n.location.href||""},g=function(){var e=f();if(void 0===h||e!==h){h=e;var r=function(){var e=n.innerHeight,t=n.innerWidth,r=n.document,i=f(),o="";return v&&(o=(null==r?void 0:r.title)||""),{href:l.length>0?Ee(i,l):i,title:o,viewportHeight:e,viewportWidth:t,type:"url-change-event"}}();t(r)}},p=dn(n,function(){return g()},u?{enablePolling:!0,pollingInterval:d}:{});return g(),function(){return p()}},options:e}}vn();var hn=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(),g()&&(this.sendToAllIframes({type:fe,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 v=(i=void 0,c(Array.from(d.addedNodes))),h=v.next();!h.done;h=v.next()){(p=h.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{h&&!h.done&&(o=v.return)&&o.call(v)}finally{if(i)throw i.error}}try{for(var f=(s=void 0,c(Array.from(d.removedNodes))),g=f.next();!g.done;g=f.next()){var p;if((p=g.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{g&&!g.done&&(a=f.return)&&a.call(f)}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:fe,action:"stop"})},e.prototype.sendToIframeAfterLoad=function(e){var t=this,n=function(){t.pendingLoadListeners.delete(e),t.sendToIframe(e,{type:fe,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 fn=function(){function e(){var e=this;this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.recordEventsInFlight=!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=g();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(){if(e.recordCancelCallback&&e.recordFunction)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,i,o){return void 0===n&&(n=!1),void 0===i&&(i=!1),void 0===o&&(o=!1),s(e,void 0,void 0,function(){var e,s,c,l,u,d,v,h,f,p,m,y;return a(this,function(a){switch(a.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,(c=t.event)&&Object.values(r).includes(c.event_type)&&(c=void 0),l=null!==(m=null!==(h=null===(v=t.page)||void 0===v?void 0:v.url)&&void 0!==h?h:null===(p=null===(f=g())||void 0===f?void 0:f.location)||void 0===p?void 0:p.href)&&void 0!==m?m:"",u=null!==(y=t.page)&&void 0!==y?y:""!==l?{url:l}:void 0,[4,Yt({sessionId:this.identifiers.sessionId,targetingConfig:e,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:t.userProperties,event:c,page:u},urlChange:o})]):[3,2];case 1:if(d=a.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:c,targetingParams:t},null,2)),a.label=2;case 2:return n?(this.initialize(!0),[3,5]):[3,3];case 3:return!i&&this.recordCancelCallback?[3,5]:(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),[4,this.recordEvents()]);case 4:a.sent(),a.label=5;case 5:return[2]}})})},this.addCustomRRWebEvent=function(t,n,r){return void 0===n&&(n={}),void 0===r&&(r=!0),s(e,void 0,void 0,function(){var e,o,s,c;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),e=void 0,(o=this.config)&&t!==Y.METADATA?(e={config:Me(o),version:We},r?[4,xe()]:[3,2]):[3,2];case 1:s=a.sent(),e=i(i({},s),e),a.label=2;case 2:return this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(t,i(i({},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 c=a.sent(),this.loggerProvider.debug("Error while adding custom replay capture event: ",c),[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 ge(new S)}return e.prototype.init=function(e,t){return y(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=g();if(null==r?void 0:r.location){var i=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),o=dn(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.getCurrentPageForTargeting=function(){var e,t,n=null===(t=null===(e=g())||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,o,d,v,h,f,p,m,y,b;return s(this,void 0,void 0,function(){var s,I,w,C,k,P,E,x,M,R,O,T,L,_,D,F,A,q,U,j,N,B,W,z,K,H,Q,G,$,Z=this;return a(this,function(a){switch(a.label){case 0:return null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),this.loggerProvider=new ge(t.loggerProvider||new S),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=Ce(),this.identifiers=new Zt({sessionId:t.sessionId,deviceId:t.deviceId}),s=this,[4,Fe(e,t)];case 1:return s.joinedConfigGenerator=a.sent(),[4,this.joinedConfigGenerator.generateJoinedConfig()];case 2:return I=a.sent(),w=I.joinedConfig,C=I.localConfig,k=I.remoteConfig,this.config=w,this.setMetadata(t.sessionId,w,C,k,null===(r=t.version)||void 0===r?void 0:r.version,We,null===(o=t.version)||void 0===o?void 0:o.type),this.pageLeaveFns=[],t.sessionId&&(null===(d=this.config.interactionConfig)||void 0===d?void 0:d.enabled)&&(P=$t.default({sessionId:t.sessionId,type:"interaction"},this.config),this.pageLeaveFns=[P.send(this.getDeviceId.bind(this)).bind(P)],this.scrollHook=P.hook.bind(P),this.clickHandler=new Ht(this.loggerProvider,P)),E=[],"idb"!==(x=this.config.storeType)||(null===(v=g())||void 0===v?void 0:v.indexedDB)||(x="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log("Using ".concat(x," for event storage.")),O=g(),this.config.useWebWorker&&O&&O.Worker?[4,import("./index-min2.js")]:[3,4];case 3:T=a.sent(),L=T.compressionScript,_=T.trackDestinationScript,M=L,R=_,a.label=4;case 4:return a.trys.push([4,6,,7]),[4,Mt({config:this.config,type:"replay",storeType:x,trackDestinationWorkerScript:R})];case 5:return D=a.sent(),E.push({name:"replay",manager:D}),[3,7];case 6:return F=a.sent(),j=F,this.loggerProvider.warn("Error occurred while creating replay events manager: ".concat(j.toString())),[3,7];case 7:if(!(null===(h=this.config.interactionConfig)||void 0===h?void 0:h.enabled))return[3,11];A=this.config.interactionConfig.batch?Kt:zt,a.label=8;case 8:return a.trys.push([8,10,,11]),[4,Mt({config:this.config,type:"interaction",minInterval:null!==(f=this.config.interactionConfig.trackEveryNms)&&void 0!==f?f:3e4,maxInterval:6e4,payloadBatcher:A,storeType:x,trackDestinationWorkerScript:R})];case 9:return q=a.sent(),E.push({name:"interaction",manager:q}),[3,11];case 10:return U=a.sent(),j=U,this.loggerProvider.warn("Error occurred while creating interaction events manager: ".concat(j.toString())),[3,11];case 11:if(this.eventsManager=new(Rt.bind.apply(Rt,u([void 0],l(E),!1))),this.eventCompressor&&this.eventCompressor.terminate(),this.eventCompressor=new je(this.eventsManager,this.config,this.getDeviceId(),M,function(){return Z.sendEvents()}),this.pendingEmitEvents.length>0){N=this.pendingEmitEvents.splice(0);try{for(B=c(N),W=B.next();!W.done;W=B.next())z=W.value,K=z.event,H=z.sessionId,this.eventCompressor.enqueueEvent(K,H)}catch(e){G={error:e}}finally{try{W&&!W.done&&($=B.return)&&$.call(B)}finally{if(G)throw G.error}}}return this.pageLeaveFns=u(u([],l(this.pageLeaveFns),!1),[function(){var e;if(Z.config&&(null===(e=Z.identifiers)||void 0===e?void 0:e.sessionId)&&D){var t=D.getBeaconEvents();if(t.length){var n=Z.getDeviceId();n&&D.trackDestination.sendBeacon({events:t,sessionId:Z.identifiers.sessionId,deviceId:n,apiKey:Z.config.apiKey,serverZone:Z.config.serverZone})}}}],!1),[4,this.initializeNetworkObservers()];case 12:return a.sent(),(null===(p=g())||void 0===p?void 0:p.opener)&&(function(e,t){var n,r=e;if(!0!==r[X]){r[X]=!0;var i=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.0.0-alpha.3.js.gz",o=null,s=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(){var t,n;null===(n=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Initializing background capture (external script)");var r=new URL(i,e.endpoint).toString();e.loadScriptOnce(r).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)"),o=null===(r=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===r?void 0:r.call(window,{messenger:e,onBackgroundCapture:s}),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==o?void 0:o.close)||void 0===e||e.call(o),o=null})}}(Q=V()),Q.setup(i({logger:this.loggerProvider},this.config.serverZone&&{endpoint:J[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 a.sent(),(this.config.targetingConfig||(null!==(b=null===(y=null===(m=this.config.privacyConfig)||void 0===m?void 0:m.urlMaskLevels)||void 0===y?void 0:y.length)&&void 0!==b?b:0)>0)&&this.setupUrlChangeListener(),[2]}})})},e.prototype.setSessionId=function(e,t){return y(this.asyncSetSessionId(e,t))},e.prototype.asyncSetSessionId=function(e,t,n){var r;return s(this,void 0,void 0,function(){var i,o,s;return a(this,function(a){switch(a.label){case 0:return this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,(i=this.identifiers&&this.identifiers.sessionId)&&this.sendEvents(i),o=t||this.getDeviceId(),this.identifiers=new Zt({sessionId:e,deviceId:o}),this.joinedConfigGenerator&&i?[4,this.joinedConfigGenerator.generateJoinedConfig()]:[3,2];case 1:s=a.sent().joinedConfig,this.config=s,a.label=2;case 2:return(null===(r=this.config)||void 0===r?void 0:r.targetingConfig)?[4,this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0)]:[3,4];case 3:return a.sent(),[3,6];case 4:return[4,this.recordEvents()];case 5:a.sent(),a.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={})[te]=n.sessionReplayId?n.sessionReplayId:null,i=e,t.debugMode&&(i[oe]=JSON.stringify({appHash:q(t.apiKey).toString()}))),this.addCustomRRWebEvent(Y.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=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),r=this.getDeviceId();this.eventsManager&&n&&r&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:r})},e.prototype.initialize=function(e){var t;return void 0===e&&(e=!1),s(this,void 0,void 0,function(){var n;return a(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,void 0===r&&(r=v),A.getInstance(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.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,cn(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(Y.TARGETING_DECISION,{message:r,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=n),n},e.prototype.getBlockSelectors=function(){var e,t,n,r=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==r.length)return r},e.prototype.getMaskTextSelectors=function(){var e,t,n=null===(e=this.config)||void 0===e?void 0:e.privacyConfig;if("conservative"===(n?be(this.currentPageUrl,n):void 0))return"*";if(null===(t=null==n?void 0:n.urlMaskLevels)||void 0===t?void 0:t.some(function(e){return"conservative"===e.maskLevel}))return"*";var r=null==n?void 0:n.urlMaskLevels;if("conservative"===(null==n?void 0:n.defaultMaskLevel)&&r&&r.length>0)return"*";var i=null==n?void 0:n.maskSelector;return i||void 0},e.prototype.getRecordingPlugins=function(e){var t,n,r,i,o,c;return s(this,void 0,void 0,function(){var s,l,u,d;return a(this,function(a){switch(a.label){case 0:s=[];try{l=vn({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}),s.push(l)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(!(null===(c=null==e?void 0:e.console)||void 0===c?void 0:c.enabled))return[3,4];a.label=1;case 1:return a.trys.push([1,3,,4]),[4,import("./rrweb-plugin-console-record-min.js")];case 2:return u=a.sent().getRecordConsolePlugin,s.push(u({level:e.console.levels})),[3,4];case 3:return d=a.sent(),this.loggerProvider.warn("Failed to load console plugin:",d),[3,4];case 4:return[2,s.length>0?s:void 0]}})})},e.prototype.getRecordFunction=function(){return s(this,void 0,void 0,function(){var e,t;return a(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),s(this,void 0,void 0,function(){var t;return a(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._recordEvents=function(e){var t,n,r,o,c,l,u,d;return void 0===e&&(e=!0),s(this,void 0,void 0,function(){var s,v,h,f,p,m,y,b,S,I,w,C,k,P,E,x,M,R,O,T=this;return a(this,function(a){switch(a.label){case 0:return s=this.config,v=this.getShouldRecord(),h=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId,v&&h&&s?(this.stopRecordingEvents(),[4,this.getRecordFunction()]):[2];case 1:return(f=a.sent())?[4,this.initializeNetworkObservers()]:[2];case 2:a.sent(),p=null===(n=s.loggingConfig)||void 0===n?void 0:n.network,m=me(s.serverZone,s.trackServerUrl),y=[ce,le,ue,m],null===(r=this.networkObservers)||void 0===r||r.start(function(e){y.some(function(t){return e.url.startsWith(t)})||T.addCustomRRWebEvent(Y.FETCH_REQUEST,e)},p),b=s.interactionConfig,S=s.loggingConfig,I=(null==b?void 0:b.enabled)?{mouseInteraction:this.eventsManager&&(null===(o=this.clickHandler)||void 0===o?void 0:o.createHook({eventsManager:this.eventsManager,sessionId:h,deviceIdFn:this.getDeviceId.bind(this),mirror:f.mirror,ugcFilterRules:null!==(c=b.ugcFilterRules)&&void 0!==c?c:[],performanceOptions:null===(l=s.performanceConfig)||void 0===l?void 0:l.interaction})),scroll:this.scrollHook}:{},w=(null==b?void 0:b.enabled)&&b.ugcFilterRules?b.ugcFilterRules:[],this.loggerProvider.log("Session Replay capture beginning for ".concat(h,".")),a.label=3;case 3:return a.trys.push([3,5,,6]),C=!!(null===(u=s.crossOriginIframes)||void 0===u?void 0:u.enabled),k=!1!==(null===(d=s.crossOriginIframes)||void 0===d?void 0:d.coordinateChildren),(P=C&&function(){try{var e=g();return!!e&&e.parent!==e}catch(e){return!0}}())&&k?(this.crossOriginParentSignalCleanup=function(e){var t=g();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)===fe&&("start"===r.action?e.onStart():"stop"===r.action&&e.onStop())}}return t.addEventListener("message",r),function(){return t.removeEventListener("message",r)}}({onStart:function(){return T._recordEventsInChildMode(f,h,s,I)},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()))}}}),[2]):(E=this,x=f,M=[i({},this.buildRRWebRecordOptions(s,I,function(e){if(T.shouldOptOut())return T.loggerProvider.log("Opting session ".concat(h," out of recording due to optOut config.")),T.stopRecordingEvents(),void T.sendEvents();e.type===Te.Meta&&(e.data.href=Ee(e.data.href,w)),T.eventCompressor?T.eventCompressor.enqueueEvent(e,h):T.pendingEmitEvents.push({event:e,sessionId:h})},"Error while capturing replay: "))],O={},[4,this.getRecordingPlugins(S)]);case 4:return E.recordCancelCallback=x.apply(void 0,[i.apply(void 0,M.concat([(O.plugins=a.sent(),O.recordCrossOriginIframes=C,O)]))]),C&&!P&&k&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new hn),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(Y.DEBUG_INFO),e&&this.addCustomRRWebEvent(Y.METADATA,this.metadata),[3,6];case 5:return R=a.sent(),this.loggerProvider.warn("Failed to initialize session replay:",R),[3,6];case 6:return[2]}})})},e.prototype.buildRRWebRecordOptions=function(e,t,n,r){var o=this,s=e.privacyConfig;return i(i({emit:n,inlineStylesheet:e.shouldInlineStylesheet,hooks:t,maskAllInputs:!0,maskTextClass:se,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements,maskInputFn:Ie("input",s,function(){return o.currentPageUrl}),maskTextFn:Ie("text",s,function(){return o.currentPageUrl}),maskAttributeFn:we(s,function(){return o.currentPageUrl}),maskTextSelector:this.getMaskTextSelectors()},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 o.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(i(i({},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.flush=function(e){var t;return void 0===e&&(e=!1),s(this,void 0,void 0,function(){return a(this,function(n){return[2,null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)]})})},e.prototype.shutdown=function(){var e,t;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())?q(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 s(this,void 0,void 0,function(){var r,i;return a(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}(),gn=function(e){return function(){var t=e.config||Re();return{logger:t.loggerProvider,logLevel:t.logLevel}}},pn=function(){var e=new fn;return{init:P(e.init.bind(e),"init",gn(e)),evaluateTargetingAndCapture:P(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",gn(e)),setSessionId:P(e.setSessionId.bind(e),"setSessionId",gn(e)),getSessionId:P(e.getSessionId.bind(e),"getSessionId",gn(e)),getSessionReplayProperties:P(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",gn(e)),flush:P(e.flush.bind(e),"flush",gn(e)),shutdown:P(e.shutdown.bind(e),"shutdown",gn(e))}}(),mn=pn.init,yn=pn.setSessionId,bn=pn.getSessionId,Sn=pn.getSessionReplayProperties;pn.flush,pn.shutdown,pn.evaluateTargetingAndCapture;const In="amp_session_id",wn="Amplitude Session Replay Segment Plugin [Debug]:";function Cn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}var kn=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=Cn({},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(r[a]=t.read(s,a),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",Cn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Cn({},this.attributes,t))},withConverter:function(t){return e(Cn({},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 Pn=()=>{const e=bn()||kn.get(In);if(e){const t=parseInt(e.toString(),10);if(isNaN(t))return;return t}},En=(e,t)=>(kn.set(In,e.toString()),yn(e,t).promise),xn=(e,t)=>s(void 0,void 0,void 0,function*(){const n=Pn()||0;let r;e.event.integrations&&e.event.integrations["Actions Amplitude"]&&(r=e.event.integrations["Actions Amplitude"].session_id),r&&n<r&&(yield En(r,t));const i=Sn(),o=Object.assign(Object.assign({},i),e.event.properties);return e.updateEvent("properties",o),e}),Mn="0.0.21",Rn=({amplitudeApiKey:e,sessionReplayOptions:t,segmentInstance:n,enableWrapperDebug:r=!1})=>s(void 0,void 0,void 0,function*(){let i,o=!1,a=null==t?void 0:t.deviceId;const c={name:"Session Replay Events",type:"enrichment",version:Mn,isLoaded:()=>o,load:(n,c)=>s(void 0,void 0,void 0,function*(){if(!a){const e=c.user();a=e.anonymousId()||void 0}const n=Pn();r&&console.log(`${wn} initializing session replay with sessionId=${null!=n?n:"undefined"} and deviceId=${null!=a?a:"undefined"}`),i=mn(e,Object.assign(Object.assign({},t),{sessionId:n,deviceId:a||void 0,version:{type:"segment",version:Mn}})).promise,yield i,o=!0}),track:e=>s(void 0,void 0,void 0,function*(){return yield i,yield xn(e,a)}),page:e=>s(void 0,void 0,void 0,function*(){return yield i,yield xn(e,a)}),identify:e=>s(void 0,void 0,void 0,function*(){yield i;const t=Pn();return t&&(r&&console.log(`${wn} calling setSessionId() with sessionId=${t} and deviceId=${null!=a?a:"undefined"}`),yield En(t,a)),e})};yield n.register(c)});export{s as _,a,i as b,Rn as c,g,rt as o};
|
|
1
|
+
var e=function(t,n){return e=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])},e(t,n)};function t(t,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=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n,r,i=function(){return i=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},i.apply(this,arguments)};function o(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 s(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}c((r=r.apply(e,t||[])).next())})}function a(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(c){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,c])}}}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 l(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 u(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"}(n||(n={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(r||(r={}));var d,v="$default_instance",h="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"}(d||(d={}));var f,g=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},p=u([],l(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),m=function(e){var t,n=g();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,u([],l(r.entries()),!1).map(function(e){var t=l(e,2),n=t[0],r=t[1];return[4,6,8,10].includes(n)?"-".concat(p[r]):p[r]}).join("")},y=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"}(f||(f={}));var b="Amplitude Logger ",S=function(){function e(){this.logLevel=f.None}return e.prototype.disable=function(){this.logLevel=f.None},e.prototype.enable=function(e){void 0===e&&(e=f.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<f.Verbose||console.log("".concat(b,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<f.Warn||console.warn("".concat(b,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<f.Error||console.error("".concat(b,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<f.Debug||console.log("".concat(b,"[Debug]: ").concat(e.join(" ")))},e}(),I=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:v,logLevel:f.Warn,loggerProvider:new S,offline:!1,optOut:!1,serverUrl:h,serverZone:"US",useBatch:!1}},w=function(){function e(e){var t,n,r,i;this._optOut=!1;var o=I();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:o.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||o.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||o.flushQueueSize,this.instanceName=e.instanceName||o.instanceName,this.loggerProvider=e.loggerProvider||o.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:o.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:o.offline,this.optOut=null!==(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=k(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}(),C=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":h},k=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=I().serverZone),void 0===n&&(n=I().useBatch),e)return{serverUrl:e,serverZone:void 0};var r=["US","EU"].includes(t)?t:I().serverZone;return{serverZone:r,serverUrl:C(r,n)}};var P=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(),c=a.logger,l=a.logLevel;if(l&&l<f.Debug||!l||!c)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 v=e.apply(i,o);return v&&v.promise?v.promise.then(function(){r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),c.debug(JSON.stringify(d,null,2))}):(r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),c.debug(JSON.stringify(d,null,2))),v}},E=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:x(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),x=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},M=function(){function e(){this.queue=[]}return e.prototype.logEvent=function(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)},e.prototype.setEventReceiver=function(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(function(t){e(t)}),this.queue=[])},e}(),R=function(){return R=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},R.apply(this,arguments)};function O(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 T(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"==typeof SuppressedError&&SuppressedError;var L=function(e,t){var n,r,i=typeof e;if(i!==typeof t)return!1;try{for(var o=O(["string","number","boolean","undefined"]),s=o.next();!s.done;s=o.next()){if(s.value===i)return e===t}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),c=Array.isArray(t);if(a!==c)return!1;if(!a||!c){var l=Object.keys(e).sort(),u=Object.keys(t).sort();if(!L(l,u))return!1;var d=!0;return Object.keys(e).forEach(function(n){L(e[n],t[n])||(d=!1)}),d}for(var v=0;v<e.length;v++)if(!L(e[v],t[v]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,r=new Array(n);n--;)r[n]=[t[n],e[t[n]]];return r});var _,D=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=R({},this.identity.userProperties),n=R(R({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,r,i,o,s,a,c=n.userProperties||{};try{for(var l=O(Object.entries(e)),u=l.next();!u.done;u=l.next()){var d=T(u.value,2),v=d[0],h=d[1];switch(v){case"$set":try{for(var f=(i=void 0,O(Object.entries(h))),g=f.next();!g.done;g=f.next()){var p=T(g.value,2),m=p[0],y=p[1];c[m]=y}}catch(e){i={error:e}}finally{try{g&&!g.done&&(o=f.return)&&o.call(f)}finally{if(i)throw i.error}}break;case"$unset":try{for(var b=(s=void 0,O(Object.keys(h))),S=b.next();!S.done;S=b.next()){delete c[m=S.value]}}catch(e){s={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(s)throw s.error}}break;case"$clearAll":c={}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(t)throw t.error}}return n.userProperties=c,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return R({},this.identity)},e.prototype.setIdentity=function(e){var t=R({},this.identity);this.identity=R({},e),L(t,this.identity)||this.listeners.forEach(function(t){t(e)})},e.prototype.addIdentityListener=function(e){this.listeners.add(e)},e.prototype.removeIdentityListener=function(e){this.listeners.delete(e)},e}(),F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,A=function(){function e(){this.identityStore=new D,this.eventBridge=new M,this.applicationContextProvider=new E}return e.getInstance=function(t){return F.analyticsConnectorInstances||(F.analyticsConnectorInstances={}),F.analyticsConnectorInstances[t]||(F.analyticsConnectorInstances[t]=new e),F.analyticsConnectorInstances[t]},e}(),q=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},U=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,c,l,u,v,h,f,g,p,m,y,b,S,I,w,C;if("object"!=typeof e)return null;var k=e.code||0,P=this.buildStatus(k);switch(P){case d.Success:return{status:P,statusCode:k,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 d.Invalid:return{status:P,statusCode:k,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!==(c=e.events_with_invalid_id_lengths)&&void 0!==c?c:{},epsThreshold:null!==(l=e.eps_threshold)&&void 0!==l?l:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(v=e.silenced_devices)&&void 0!==v?v:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(f=e.throttled_devices)&&void 0!==f?f:{},throttledEvents:null!==(g=e.throttled_events)&&void 0!==g?g:[]}};case d.PayloadTooLarge:return{status:P,statusCode:k,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case d.RateLimit:return{status:P,statusCode:k,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 d.Timeout:default:return{status:P,statusCode:k}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?d.Success:429===e?d.RateLimit:413===e?d.PayloadTooLarge:408===e?d.Timeout:e>=400&&e<500?d.Invalid:e>=500?d.Failed:d.Unknown},e}(),j=function(e){function n(t){void 0===t&&(t={});var n=e.call(this)||this;return n.customHeaders=t,n}return t(n,e),n.prototype.send=function(e,t){return s(this,void 0,void 0,function(){var n,r,o;return a(this,function(s){switch(s.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:i({"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:o=s.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}})})},n}(U),N=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var n=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(JSON.stringify(n))),Promise.resolve({remoteConfig:n.remoteConfig,lastFetch:new Date(n.lastFetch)})}catch(e){return this.logger.debug("Remote config localstorage failed to parse: ",e),localStorage.removeItem(this.key),Promise.resolve(t)}},e.prototype.setConfig=function(e){try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}(),B=401,W=403,z=429,K=function(){function e(e,t,n,r){void 0===n&&(n="US"),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=e,this.serverUrl=r||("US"===n?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=t,this.storage=new N(e,t)}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 s(this,void 0,void 0,function(){var e,t=this;return a(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 s(this,void 0,void 0,function(){var t,n,r,i=this;return a(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 s(this,void 0,void 0,function(){var n,r;return a(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),s(this,void 0,void 0,function(){var n,r,i,o,s,c,l=this;return a(this,function(u){switch(u.label){case 0:n=t/e,r={remoteConfig:null,lastFetch:new Date},i=function(r){var i,s,c,u,d,v;return a(this,function(a){switch(a.label){case 0:i=!0,s=new AbortController,c=setTimeout(function(){return s.abort()},t),a.label=1;case 1:return a.trys.push([1,7,8,9]),[4,fetch(o.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:s.signal})];case 2:return(u=a.sent()).ok?[3,4]:[4,u.text()];case 3:return d=a.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(u.status,": ").concat(d)),u.status===B||u.status===W?(o.logger.error("Remote config client fetch failed with ".concat(u.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,i=!1):u.status>=400&&u.status<500&&u.status!==z&&(i=!1),[3,6];case 4:return[4,u.json()];case 5:return[2,{value:{remoteConfig:a.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(v=a.sent())instanceof Error&&"AbortError"===v.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: "),v),[3,9];case 8:return clearTimeout(c),[7];case 9:return i?r<e-1?[4,new Promise(function(e){return setTimeout(e,l.getJitterDelay(n))})]:[3,11]:[2,"break"];case 10:a.sent(),a.label=11;case 11:return[2]}})},o=this,s=0,u.label=1;case 1:return s<e?[5,i(s)]:[3,4];case 2:if("object"==typeof(c=u.sent()))return[2,c.value];if("break"===c)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 t=encodeURIComponent(this.apiKey),n=new URLSearchParams;return n.append("config_group",e.CONFIG_GROUP),"".concat(this.serverUrl,"/").concat(t,"?").concat(n.toString())},e.CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(_||(_={}));var H,Q="https://app.amplitude.com",J={US:Q,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var G="__AMPLITUDE_MESSENGER_INSTANCE__",$="__AMPLITUDE_MESSENGER__",Z=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?Q:t;this[H]=!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 s(this,void 0,void 0,function(){var t,n,r;return a(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===Q&&(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,c=null==a?void 0:a.action;if(c)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"===c)return void r.notify({action:"pong"});var l=r.actionHandlers.get(c);if(l)l(a.data);else{var u=null!==(s=r.pendingMessages.get(c))&&void 0!==s?s:[];u.push(a.data),r.pendingMessages.set(c,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=g();(null==e?void 0:e[$])===this&&delete e[$]},e}();function V(e){var t,n=g(),r=null==n?void 0:n[$];if("object"==typeof(t=r)&&null!==t&&G in t&&!0===t[G])return r;var i=new Z(e);return n&&(n[$]=i),i}H=G;var X="__AMPLITUDE_BACKGROUND_CAPTURE__";var Y,ee="[Amplitude]",te="".concat(ee," Session Replay ID"),ne=_.US,re={enabled:!0},ie=1e3,oe="".concat(ee," Session Replay Debug"),se="amp-mask",ae="amp-unmask",ce="https://api-sr.amplitude.com/sessions/v2/track",le="https://api-sr.eu.amplitude.com/sessions/v2/track",ue="https://api-sr.stag2.amplitude.com/sessions/v2/track",de=9e6,ve=/payload.*exceed/i,he=1024,fe="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"}(Y||(Y={}));var ge=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";function me(e,t){return t||("STAGING"===e?ue:"EU"===e?le:ce)}var ye=function(e,t,n){switch(t){case"light":if("input"!==e)return!0;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":case"conservative":return!0;default:return ye(e,pe,n)}},be=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(Pe(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},Se=function(e,t,n,r){var i,o;if(void 0===t&&(t={defaultMaskLevel:pe}),n){if(n.closest("."+se))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("."+ae))return!1;var a=(null!==(o=t.unmaskSelector)&&void 0!==o?o:[]).some(function(e){return n.closest(e)});if(a)return!1}return ye(e,be(r,t),n)},Ie=function(e,t,n){return function(r,i){return Se(e,t,i,null==n?void 0:n())?r.replace(/[^\s]/g,"*"):r}},we=function(e,t){return function(n,r,i){var o;return"style"===n?r:(null!==(o=null==e?void 0:e.maskAttributes)&&void 0!==o?o:[]).includes(n)&&Se("text",e,i,null==t?void 0:t())?r.replace(/[^\s]/g,"*"):r}},Ce=function(){var e=g();return(null==e?void 0:e.location)?e.location.href:""},ke=new Map,Pe=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 c=new RegExp("^".concat(a,"$"));return ke.set(e,c),c},Ee=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=Pe(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},xe=function(){return s(void 0,void 0,void 0,function(){var e,t,n,r,i,o,s;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),(e=g())?[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/he):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:""}]}})})},Me=function(e){var t=i({},e),n=t.apiKey;return t.apiKey="****".concat(n.substring(n.length-4)),t},Re=function(){return{flushMaxRetries:2,logLevel:f.Warn,loggerProvider:new S,transportProvider:new j}},Oe=function(e){function n(t,n){var r,o,s,a,c,d,v,h,f,g,p=this,m=Re();if((p=e.call(this,i(i({transportProvider:m.transportProvider,loggerProvider:new ge(n.loggerProvider||m.loggerProvider)},n),{apiKey:t}))||this).flushMaxRetries=void 0!==n.flushMaxRetries&&n.flushMaxRetries<=m.flushMaxRetries?n.flushMaxRetries:m.flushMaxRetries,p.apiKey=t,p.sampleRate=n.sampleRate||0,p.serverZone=n.serverZone||ne,p.configServerUrl=n.configServerUrl,p.trackServerUrl=n.trackServerUrl,p.shouldInlineStylesheet=n.shouldInlineStylesheet,p.version=n.version,p.performanceConfig=n.performanceConfig||re,p.storeType=null!==(r=n.storeType)&&void 0!==r?r:"memory",p.applyBackgroundColorToBlockedElements=null!==(o=n.applyBackgroundColorToBlockedElements)&&void 0!==o&&o,p.enableUrlChangePolling=null!==(s=n.enableUrlChangePolling)&&void 0!==s&&s,p.urlChangePollingInterval=null!==(a=n.urlChangePollingInterval)&&void 0!==a?a:ie,p.captureDocumentTitle=null!==(c=n.captureDocumentTitle)&&void 0!==c&&c,void 0!==n.fullSnapshotIntervalMs&&(p.fullSnapshotIntervalMs=n.fullSnapshotIntervalMs),p.privacyConfig=i(i({},null!==(d=n.privacyConfig)&&void 0!==d?d:{}),{unmaskSelector:Array.from(new Set(u([".".concat(ae)],l(null!==(h=null===(v=n.privacyConfig)||void 0===v?void 0:v.unmaskSelector)&&void 0!==h?h:[]),!1)))}),n.interactionConfig&&(p.interactionConfig=n.interactionConfig,p.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")}(p.interactionConfig.ugcFilterRules)),n.debugMode&&(p.debugMode=n.debugMode),void 0!==n.useWebWorker)p.useWebWorker=n.useWebWorker;else{var y=n;void 0!==(null===(f=y.experimental)||void 0===f?void 0:f.useWebWorker)&&(p.useWebWorker=y.experimental.useWebWorker)}return p.captureAdoptedStyleSheets=null===(g=n.captureAdoptedStyleSheets)||void 0===g||g,n.crossOriginIframes&&(p.crossOriginIframes=n.crossOriginIframes),p}return t(n,e),n}(w),Te=(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))(Te||{}),Le=(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))(Le||{}),_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||{}),De=function(){function e(e,t){this.localConfig=t,this.remoteConfigClient=e}return e.prototype.generateJoinedConfig=function(){var e,t,n,r,o,d,v;return s(this,void 0,void 0,function(){var s,h,f,g,p,m,y,b,S,I,w,C,k,P,E,x,M,R=this;return a(this,function(a){switch(a.label){case 0:(s=i({},this.localConfig)).optOut=this.localConfig.optOut,s.captureEnabled=!0,a.label=1;case 1:return a.trys.push([1,3,,4]),[4,new Promise(function(e,t){R.remoteConfigClient.subscribe("configs.sessionReplay",{timeout:1500},function(n,r){var i;if(R.localConfig.loggerProvider.debug("Session Replay remote configuration received from ".concat(r,":"),JSON.stringify(n,null,2)),n){var o=n,a=o.sr_sampling_config,c=o.sr_privacy_config,l=o.sr_targeting_config,u=null===(i=s.interactionConfig)||void 0===i?void 0:i.ugcFilterRules;s.interactionConfig=o.sr_interaction_config,s.interactionConfig&&u&&(s.interactionConfig.ugcFilterRules=u),s.loggingConfig=o.sr_logging_config,(a||c||l)&&(h={},a&&(h.sr_sampling_config=a),c&&(h.sr_privacy_config=c),l&&(h.sr_targeting_config=l)),e()}else t(new Error("No remote config received"))})})];case 2:return a.sent(),[3,4];case 3:return f=a.sent(),this.localConfig.loggerProvider.error("Failed to generate joined config: ",f),s.captureEnabled=!1,[2,{localConfig:this.localConfig,joinedConfig:s,remoteConfig:void 0}];case 4:if(!h)return[2,{localConfig:this.localConfig,joinedConfig:s,remoteConfig:h}];if(g=h.sr_sampling_config,p=h.sr_privacy_config,m=h.sr_targeting_config,g&&Object.keys(g).length>0?(Object.prototype.hasOwnProperty.call(g,"capture_enabled")?s.captureEnabled=g.capture_enabled:s.captureEnabled=!1,Object.prototype.hasOwnProperty.call(g,"sample_rate")&&(s.sampleRate=g.sample_rate)):(s.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),p){y=null!==(e=s.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:u([],l(new Set(u(u([],l(null!==(r=y.maskAttributes)&&void 0!==r?r:[]),!1),l(null!==(o=p.maskAttributes)&&void 0!==o?o:[]),!1))),!1),urlMaskLevels:u(u([],l(null!==(d=p.urlMaskLevels)&&void 0!==d?d:[]),!1),l(null!==(v=y.urlMaskLevels)&&void 0!==v?v:[]),!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 v=c(null!==(a=e.blockSelector)&&void 0!==a?a:[]),h=v.next();!h.done;h=v.next()){d[h.value]="block"}}catch(e){t={error:e}}finally{try{h&&!h.done&&(n=v.return)&&n.call(v)}finally{if(t)throw t.error}}try{for(var f=c(null!==(l=e.maskSelector)&&void 0!==l?l:[]),g=f.next();!g.done;g=f.next()){d[g.value]="mask"}}catch(e){r={error:e}}finally{try{g&&!g.done&&(i=f.return)&&i.call(f)}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=i(i({},S(y)),S(p));try{for(w=c(Object.entries(I)),C=w.next();!C.done;C=w.next())k=l(C.value,2),P=k[0],"mask"===(E=k[1])?b.maskSelector.push(P):"block"===E?b.blockSelector.push(P):"unmask"===E&&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}}s.privacyConfig=(O=b,T=this.localConfig.loggerProvider,L=document.createDocumentFragment(),_=function(e){if(void 0===e&&(e=[]),"string"==typeof e&&(e=[e]),e=e.filter(function(e){try{L.querySelector(e)}catch(t){return T.warn('[session-replay-browser] omitting selector "'.concat(e,'" because it is invalid')),!1}return!0}),0!==e.length)return e},O.blockSelector=_(O.blockSelector),O.maskSelector=_(O.maskSelector),O.unmaskSelector=_(O.unmaskSelector),O)}return m&&Object.keys(m).length>0&&(s.targetingConfig=m),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:Me(s)},null,2)),[2,{localConfig:this.localConfig,joinedConfig:s,remoteConfig:h}]}var O,T,L,_})})},e}(),Fe=function(e,t){return s(void 0,void 0,void 0,function(){var n,r;return a(this,function(i){return n=new Oe(e,t),r=new K(e,n.loggerProvider,n.serverZone,t.configServerUrl),[2,new De(r,n)]})})};function Ae(e){if(e.type!==Te.IncrementalSnapshot)return!1;var t=e.data;return t.source===Le.Mutation&&!t.isAttachIframe}function qe(e){var t,n,r,o,s=e[0],a=new Map,u=new Map,d=new Map,v=new Map,h=new Map;e.forEach(function(e,t){var n,r,i,o,s=e.data;try{for(var l=c(s.adds),f=l.next();!f.done;f=l.next()){var g=f.value;a.has(g.node.id)||a.set(g.node.id,t),u.set(g.node.id,t),h.set(g.node.id,g.parentId)}}catch(e){n={error:e}}finally{try{f&&!f.done&&(r=l.return)&&r.call(l)}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),v.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 f=new Set,g=new Set;try{for(var p=c(a),m=p.next();!m.done;m=p.next()){var y=l(m.value,2),b=y[0],S=y[1],I=d.get(b);if(void 0!==I)u.get(b)>=v.get(b)||(S<I?f.add(b):I<S&&g.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(f.size>0||g.size>0)for(var C=!0;C;){C=!1;try{for(var k=(r=void 0,c(h)),P=k.next();!P.done;P=k.next()){var E=l(P.value,2),x=E[0],M=E[1];if(!f.has(x)&&!g.has(x)&&!w.has(x)&&(f.has(M)||g.has(M)||w.has(M))){var R=d.get(x),O=a.get(x);void 0!==R&&void 0!==O&&R<O?g.add(x):void 0!==R&&void 0!==O&&R===O?w.add(x):f.add(x),C=!0}}}catch(e){r={error:e}}finally{try{P&&!P.done&&(o=k.return)&&o.call(k)}finally{if(r)throw r.error}}}var T=f.size>0||g.size>0||w.size>0,L=[];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;f.has(s.id)||(g.has(s.id)&&t>=a.get(s.id)||w.has(s.id)&&(f.has(s.parentId)||g.has(s.parentId)||w.has(s.parentId))||L.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 _=e.flatMap(function(e){return e.data.adds}),D=e.flatMap(function(e){return e.data.texts}),F=e.flatMap(function(e){return e.data.attributes}),A={source:Le.Mutation,removes:L,adds:T?_.filter(function(e){return!f.has(e.node.id)&&!g.has(e.node.id)&&!w.has(e.node.id)}):_,texts:T?D.filter(function(e){return!f.has(e.id)&&!g.has(e.id)&&!w.has(e.id)}):D,attributes:T?F.filter(function(e){return!f.has(e.id)&&!g.has(e.id)&&!w.has(e.id)}):F};return i(i({},s),{data:A})}function Ue(e){if(e.length<=1)return e;for(var t=[],n=0;n<e.length;)if(Ae(e[n])){for(var r=n+1;r<e.length&&Ae(e[r]);)r++;t.push(r>n+1?qe(e.slice(n,r)):e[n]),n=r}else t.push(e[n]),n++;return t}var je=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=new Blob([e]).size;n>de?s.config.loggerProvider.warn("Session replay event dropped: serialized size ".concat(Math.round(n/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.")):s.eventsManager&&s.deviceId&&s.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:s.deviceId})},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,u([],l(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=g();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 c=new Blob([r],{type:"application/javascript"}),d=URL.createObjectURL(c),v=new Worker(d);v.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,")")),v.terminate(),s.worker=void 0},v.onmessage=function(e){var t=e.data,n=t.compressedEvent,r=t.sessionId;s.addCompressedEventToManager(n,r)},this.worker=v}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===Te.FullSnapshot){if(this.config.loggerProvider.debug("Processing full snapshot immediately."),this.taskQueue.length>0||this.pendingQueue.length>0){var s=u(u([],l(this.taskQueue.splice(0)),!1),l(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1);try{for(var a=c(s),d=a.next();!d.done;d=a.next()){var v=d.value,h=this.compressEvent(v.event);this.addCompressedEventToManager(h,v.sessionId)}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this.isProcessing=!1}var f=this.compressEvent(e);return this.addCompressedEventToManager(f,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,u([],l(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(!(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=Ue(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 v=d.value;i.push({event:v,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}(),Ne="Session replay event batch rejected due to exceeded retry count",Be="Failed to store session replay events in IndexedDB",We="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",ze="1.42.3";function Ke(e,t){return s(this,void 0,void 0,function(){var n,r,i,o,l,u,d,v,h,f,g,p,m,y,b=this;return a(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(),l=[],u=s(b,void 0,void 0,function(){var e,t,n;return a(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];l.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=l.reduce(function(e,t){return e+t.length},0),v=new Uint8Array(d),h=0;try{for(f=c(l),g=f.next();!g.done;g=f.next())p=g.value,v.set(p,h),h+=p.length}catch(e){m={error:e}}finally{try{g&&!g.done&&(y=f.return)&&y.call(f)}finally{if(m)throw m.error}}return[2,v];case 4:return S.sent(),[2,null];case 5:return[2]}})})}var He=function(){function e(e){var t=e.trackServerUrl,n=e.loggerProvider,r=e.payloadBatcher,i=e.workerScript,o=this;if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.flushPauseUntilMs=0,this.killedSessions=new Set,this.loggerProvider=n,this.payloadBatcher=r||function(e){return e},this.trackServerUrl=t,i)try{var s=new Blob([i],{type:"application/javascript"}),a=URL.createObjectURL(s),u=new Worker(a);u.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,")")),u.terminate(),o.worker=void 0;try{for(var i=c(o.pendingWorkerRequests),s=i.next();!s.done;s=i.next()){var a=l(s.value,2)[1];n.warn("Session replay event send failed due to worker crash: ".concat(e.message)),a.resolve()}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}o.pendingWorkerRequests.clear()},u.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=o.pendingWorkerRequests.get(t.id);r&&(o.handlePayloadTooLargeResponse(r.context,t.isWaf),r.resolve(),o.pendingWorkerRequests.delete(t.id))}else if("complete"===t.type){var i=o.pendingWorkerRequests.get(t.id);i&&(void 0!==t.skipCode&&o.applyServerDirective(i.context.sessionId,t.skipCode),o.completeRequest({context:i.context}),i.resolve(),o.pendingWorkerRequests.delete(t.id))}},this.worker=u}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(i(i({},e),{attempts:0,timeout:0}))},e.prototype.sendBeacon=function(e){var t,n,r=e.events,i=e.sessionId,o=e.deviceId,s=e.apiKey,a=e.serverZone,c=function(e){return new Blob([e]).size},l=r,u=JSON.stringify({version:2,events:l});if(c(u)>65536){for(var d=0,v=l.length;d<v;){var h=Math.floor((d+v+1)/2);c(JSON.stringify({version:2,events:l.slice(0,h)}))<=65536?d=h:v=h-1}l=l.slice(0,d),u=JSON.stringify({version:2,events:l}),this.loggerProvider.warn("sendBeacon payload exceeded 64 KB limit, trimmed from ".concat(r.length," to ").concat(l.length," events"))}if(0!==l.length){var f=new URLSearchParams({device_id:o,session_id:String(i),type:"replay",api_key:s}),p="".concat(me(a,this.trackServerUrl),"?").concat(f.toString()),m=g();try{var y=new Blob([u],{type:"application/json"});!1===(null===(n=null===(t=null==m?void 0:m.navigator)||void 0===t?void 0:t.sendBeacon)||void 0===n?void 0:n.call(t,p,y))&&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:We}),!1):t.attempts<(t.flushMaxRetries||0)?(t.attempts+=1,!0):(e.completeRequest({context:t,err:Ne}),!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;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),s(this,void 0,void 0,function(){var t,n,r,i,o,s,l;return a(this,function(a){switch(a.label){case 0:t=this.queue,this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),a.label=1;case 1:a.trys.push([1,6,7,8]),n=c(t),r=n.next(),a.label=2;case 2:return r.done?[3,5]:(i=r.value,[4,this.send(i,e)]);case 3:a.sent(),a.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=a.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(l=n.return)&&l.call(n)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},e.prototype.send=function(e,t){return void 0===t&&(t=!0),s(this,void 0,void 0,function(){var n,r,i,o;return a(this,function(s){return this.killedSessions.has(e.sessionId)?[2,this.completeRequest({context:e,err:We})]:(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 s(this,void 0,void 0,function(){var i,o=this;return a(this,function(s){return i="".concat(++this.sendIdCounter),[2,new Promise(function(s){var a;o.pendingWorkerRequests.set(i,{context:t,resolve:s}),e.postMessage({type:"send",id:i,payload:n,useRetry:r,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:Ce(),sdkVersion:ze}})})]})})},e.prototype.sendOnMainThread=function(e,t,n,r,o){var c,l,u,d,v,h,f;return s(this,void 0,void 0,function(){var s,p,m,y,b,S,I,w,C,k,P,E,x,M,R,O;return a(this,function(a){switch(a.label){case 0:s=Ce(),p=ze,m=n.sampleRate,y=new URLSearchParams({device_id:t,session_id:"".concat(n.sessionId),type:"".concat(n.type)}),b="".concat(null!==(l=null===(c=n.version)||void 0===c?void 0:c.type)&&void 0!==l?l:"standalone","/").concat(null!==(d=null===(u=n.version)||void 0===u?void 0:u.version)&&void 0!==d?d:p),a.label=1;case 1:return a.trys.push([1,13,,14]),S=JSON.stringify(r),(I=g())&&"CompressionStream"in I?[4,Ke(S,I)]:[3,3];case 2:return C=a.sent(),[3,4];case 3:C=null,a.label=4;case 4:return k=(w=C)?w.byteLength:new Blob([S]).size,P={headers:i({"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(e),"X-Client-Version":p,"X-Client-Library":b,"X-Client-Url":s.substring(0,1e3),"X-Client-Sample-Rate":"".concat(m),"X-Sampling-Hash-Alg":"xxhash32"},w?{"Content-Encoding":"gzip"}:{}),body:null!=w?w:S,method:"POST",keepalive:k<=65536},E="".concat(me(n.serverZone,this.trackServerUrl),"?").concat(y.toString()),[4,fetch(E,P)];case 5:if(null===(x=a.sent()))return this.completeRequest({context:n,err:"Unexpected error occurred"}),[2];if(x.status>=200&&x.status<300&&(M=null!==(f=null===(h=null===(v=x.headers)||void 0===v?void 0:v.get)||void 0===h?void 0:h.call(v,"X-Session-Replay-Event-Skipped"))&&void 0!==f?f:null,this.applyServerDirective(n.sessionId,M)),o)return[3,6];R="";try{R=JSON.stringify(x.body,null,2)}catch(e){}return this.completeRequest({context:n,success:"".concat(x.status,": ").concat(R)}),[3,12];case 6:if(R="",413!==x.status)return[3,10];a.label=7;case 7:return a.trys.push([7,9,,10]),[4,x.text()];case 8:return R=a.sent(),[3,10];case 9:return a.sent(),[3,10];case 10:return[4,this.handleReponse(x.status,n,R)];case 11:a.sent(),a.label=12;case 12:return[3,14];case 13:return O=a.sent(),this.completeRequest({context:n,err:O}),[3,14];case 14:return[2]}})})},e.prototype.handleReponse=function(e,t,n){return void 0===n&&(n=""),s(this,void 0,void 0,function(){var r;return a(this,function(i){switch(i.label){case 0:switch(r=(new U).buildStatus(e),r){case d.Success:return[3,1];case d.Failed:case d.Timeout:case d.RateLimit:return[3,2];case d.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,ve.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)/he);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 o=function(){return Promise.resolve()},s=Math.floor(e.events.length/2);this.sendEventsList(i(i({},e),{events:e.events.slice(0,s),onComplete:o})),this.sendEventsList(i(i({},e),{events:e.events.slice(s),onComplete:o}))}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(new Blob(e.events).size/he);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 s(this,void 0,void 0,function(){var t;return a(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:Ne}),[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){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)}else this.flushPauseUntilMs=0},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),v=d.next();!v.done;v=d.next()){var h=v.value;h.sessionId===e?this.completeRequest({context:h,err:We}):u.push(h)}}catch(e){i={error:e}}finally{try{v&&!v.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}this.queue=u}},e}();const Qe=(e,t)=>t.some(t=>e instanceof t);let Je,Ge;const $e=new WeakMap,Ze=new WeakMap,Ve=new WeakMap;let Xe={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return $e.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return nt(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Ye(e){Xe=e(Xe)}function et(e){return(Ge||(Ge=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(rt(this),t),nt(this.request)}:function(...t){return nt(e.apply(rt(this),t))}}function tt(e){return"function"==typeof e?et(e):(e instanceof IDBTransaction&&function(e){if($e.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)});$e.set(e,t)}(e),Qe(e,Je||(Je=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Xe):e)}function nt(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(nt(e.result)),r()},o=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",o)});return Ve.set(t,e),t}(e);if(Ze.has(e))return Ze.get(e);const t=tt(e);return t!==e&&(Ze.set(e,t),Ve.set(t,e)),t}const rt=e=>Ve.get(e);function it(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=nt(s);return r&&s.addEventListener("upgradeneeded",e=>{r(nt(s.result),e.oldVersion,e.newVersion,nt(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 ot=["get","getKey","getAll","getAllKeys","count"],st=["put","add","delete","clear"],at=new Map;function ct(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(at.get(t))return at.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=st.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!ot.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 at.set(t,o),o}Ye(e=>({...e,get:(t,n,r)=>ct(t,n)||e.get(t,n,r),has:(t,n)=>!!ct(t,n)||e.has(t,n)}));const lt=["continue","continuePrimaryKey","advance"],ut={},dt=new WeakMap,vt=new WeakMap,ht={get(e,t){if(!lt.includes(t))return e[t];let n=ut[t];return n||(n=ut[t]=function(...e){dt.set(this,vt.get(this)[t](...e))}),n}};async function*ft(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,ht);for(vt.set(n,t),Ve.set(n,rt(t));t;)yield n,t=await(dt.get(n)||t.continue()),dt.delete(n)}function gt(e,t){return t===Symbol.asyncIterator&&Qe(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&Qe(e,[IDBIndex,IDBObjectStore])}Ye(e=>({...e,get:(t,n,r)=>gt(t,n)?ft:e.get(t,n,r),has:(t,n)=>gt(t,n)||e.has(t,n)}));var pt=function(){function e(e){var t,n,r,i=this;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=7e5,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=function(e,t){var n=i.getStringSize(t);return i.getEventsArraySize(e)+n>=i.maxPersistedEventsSize||!!(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}return Object.defineProperty(e.prototype,"timeAtLastSplit",{get:function(){return this._timeAtLastSplit},enumerable:!1,configurable:!0}),e.prototype.getStringSize=function(e){for(var t=0,n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t++;else if(r<=2047)t+=2;else if(r>=55296&&r<=56319){var i=n+1<e.length?e.charCodeAt(n+1):NaN;i>=56320&&i<=57343?(t+=4,n++):t+=3}else t+=3}return t},e.prototype.getEventsArraySize=function(e){var t,n,r=0;try{for(var i=c(e),o=i.next();!o.done;o=i.next()){var s=o.value;r+=this.getStringSize(s)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return r+(2+Math.max(0,e.length-1)+2*e.length)},e}(),mt=function(e,t,n){var r;"object"==typeof(r=n)&&null!==r&&"AbortError"===r.name?e.debug(t):e.warn(t)};var yt="sessionCurrentSequence",bt="sequencesToSend",St=5e3;function It(e,t,n){var r=setTimeout(n,t);return e.then(function(){return clearTimeout(r)},function(){return clearTimeout(r)}),function(){return clearTimeout(r)}}var wt,Ct,kt,Pt=function(e){var t,n;return e.objectStoreNames.contains(yt)||(n=e.createObjectStore(yt,{keyPath:"sessionId"})),e.objectStoreNames.contains(bt)||(t=e.createObjectStore(bt,{keyPath:"sequenceId",autoIncrement:!0})).createIndex("sessionId","sessionId"),{sequencesStore:t,currentSequenceStore:n}},Et=function(e){return s(void 0,void 0,void 0,function(){return a(this,function(t){switch(t.label){case 0:return[4,(n=it(e,1,{upgrade:Pt}),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})})},xt=function(e){function n(t){var n,r=this;return(r=e.call(this,t)||this).consecutiveFailures=0,r.hasTriggeredFallback=!1,r.getSequencesToSend=function(){return s(r,void 0,void 0,function(){var e,t,n,r,i,o,s,c,l,u,d=this;return a(this,function(a){switch(a.label){case 0:e=!1,t=!1,a.label=1;case 1:return a.trys.push([1,6,,7]),n=[],(r=this.db.transaction("sequencesToSend")).done.catch(function(n){e||t||(mt(d.loggerProvider,"".concat(Be,": ").concat(n),n),d.recordFailure())}),i=It(r.done,St,function(){e||t||(t=!0,mt(d.loggerProvider,"".concat(Be,": transaction timed out")),d.recordFailure())}),[4,r.store.openCursor()];case 2:o=a.sent(),a.label=3;case 3:return o?(s=o.value,c=s.sessionId,l=s.events,n.push({events:l,sequenceId:o.key,sessionId:c}),[4,o.continue()]):[3,5];case 4:return o=a.sent(),[3,3];case 5:return this.recordSuccess(),i(),[2,n];case 6:return u=a.sent(),t||(e=!0,mt(this.loggerProvider,"".concat(Be,": ").concat(u),u),this.recordFailure()),[3,7];case 7:return[2,void 0]}})})},r.storeCurrentSequence=function(e){return s(r,void 0,void 0,function(){var t,n,r,s,c,l,u,d,v=this;return a(this,function(a){switch(a.label){case 0:t=!1,n=!1,a.label=1;case 1:return a.trys.push([1,5,,6]),(r=this.db.transaction([yt,bt],"readwrite")).done.catch(function(e){t||n||(mt(v.loggerProvider,"".concat(Be,": ").concat(e),e),v.recordFailure())}),s=It(r.done,St,function(){t||n||(n=!0,mt(v.loggerProvider,"".concat(Be,": transaction timed out")),v.recordFailure())}),[4,r.objectStore(yt).get(e)];case 2:return!(c=a.sent())||c.tabId&&c.tabId!==this.tabId||0===c.events.length?(s(),[2,void 0]):[4,r.objectStore(bt).put({sessionId:e,events:c.events,tabId:this.tabId})];case 3:return l=a.sent(),[4,r.objectStore(yt).put({sessionId:e,events:[],tabId:this.tabId})];case 4:return a.sent(),this.recordSuccess(),s(),c.tabId,u=o(c,["tabId"]),[2,i(i({},u),{sessionId:e,sequenceId:l})];case 5:return d=a.sent(),n||(t=!0,mt(this.loggerProvider,"".concat(Be,": ").concat(d),d),this.recordFailure()),[3,6];case 6:return[2,void 0]}})})},r.addEventToCurrentSequence=function(e,t){return s(r,void 0,void 0,function(){var n,r,i,o,s,c,l,u,d,v=this;return a(this,function(a){switch(a.label){case 0:n=!1,r=!1,a.label=1;case 1:return a.trys.push([1,13,,14]),(i=this.db.transaction([yt,bt],"readwrite")).done.catch(function(e){n||r||(mt(v.loggerProvider,"".concat(Be,": ").concat(e),e),v.recordFailure())}),o=It(i.done,St,function(){n||r||(r=!0,mt(v.loggerProvider,"".concat(Be,": transaction timed out")),v.recordFailure())}),[4,i.objectStore(yt).get(e)];case 2:return(null==(s=a.sent())?void 0:s.tabId)&&s.tabId!==this.tabId?s.events.length>0?[4,i.objectStore(bt).put({sessionId:e,events:s.events,tabId:s.tabId})]:[3,4]:[3,6];case 3:a.sent(),a.label=4;case 4:return[4,i.objectStore(yt).put({sessionId:e,events:[t],tabId:this.tabId})];case 5:return a.sent(),this.recordSuccess(),o(),[2,void 0];case 6:return(c=s)?[3,8]:[4,i.objectStore(yt).put({sessionId:e,events:[t],tabId:this.tabId})];case 7:return a.sent(),this.recordSuccess(),o(),[2,void 0];case 8:return this.shouldSplitEventsList(c.events,t)?[3,10]:[4,i.objectStore(yt).put({sessionId:e,events:c.events.concat(t),tabId:this.tabId})];case 9:return a.sent(),this.recordSuccess(),o(),[2,void 0];case 10:return l=c.events,[4,i.objectStore(yt).put({sessionId:e,events:[t],tabId:this.tabId})];case 11:return a.sent(),[4,i.objectStore(bt).put({sessionId:e,events:l,tabId:this.tabId})];case 12:return u=a.sent(),this.recordSuccess(),o(),[2,{events:l,sessionId:e,sequenceId:u}];case 13:return d=a.sent(),r||(n=!0,mt(this.loggerProvider,"".concat(Be,": ").concat(d),d),this.recordFailure()),[3,14];case 14:return[2,void 0]}})})},r.storeSendingEvents=function(e,t){return s(r,void 0,void 0,function(){var n,r;return a(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.db.put(bt,{sessionId:e,events:t,tabId:this.tabId})];case 1:return n=i.sent(),this.recordSuccess(),[2,n];case 2:return r=i.sent(),mt(this.loggerProvider,"".concat(Be,": ").concat(r),r),this.recordFailure(),[3,3];case 3:return[2,void 0]}})})},r.cleanUpSessionEventsStore=function(e,t){return s(r,void 0,void 0,function(){var e;return a(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(bt,t)];case 2:return n.sent(),this.recordSuccess(),[3,4];case 3:return e=n.sent(),mt(this.loggerProvider,"".concat(Be,": ").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 t(n,e),n.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))},n.prototype.recordSuccess=function(){this.consecutiveFailures=0},n.new=function(e,t){var r;return s(this,void 0,void 0,function(){var o,s,c,l,u;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),o="replay"===e?"":"_".concat(e),s="".concat(t.apiKey.substring(0,10),"_amp_session_replay_events").concat(o),[4,Et(s)];case 1:return c=a.sent(),l=null!==(r=t.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 n(i(i({},t),{db:c,tabId:l}))];case 2:return u=a.sent(),mt(t.loggerProvider,"".concat(Be,": ").concat(u),u),[3,3];case 3:return[2]}})})},n.prototype.getCurrentSequenceEvents=function(e){return s(this,void 0,void 0,function(){var t,n,r,i,s,l,u,d;return a(this,function(a){switch(a.label){case 0:return e?[4,this.db.get("sessionCurrentSequence",e)]:[3,2];case 1:return(i=a.sent())?i.tabId&&i.tabId!==this.tabId?[2,void 0]:(i.tabId,[2,[s=o(i,["tabId"])]]):[2,void 0];case 2:t=[],a.label=3;case 3:return a.trys.push([3,8,9,10]),[4,this.db.getAll("sessionCurrentSequence")];case 4:n=c.apply(void 0,[a.sent()]),r=n.next(),a.label=5;case 5:if(r.done)return[3,7];if((i=r.value).tabId&&i.tabId!==this.tabId)return[3,6];i.tabId,s=o(i,["tabId"]),t.push(s),a.label=6;case 6:return r=n.next(),[3,5];case 7:return[3,10];case 8:return l=a.sent(),u={error:l},[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]}})})},n}(pt),Mt=function(e){function n(){var t=null!==e&&e.apply(this,arguments)||this;return t.finalizedSequences={},t.sequences={},t.sequenceId=0,t}return t(n,e),n.prototype.resetCurrentSequence=function(e){this.sequences[e]=[]},n.prototype.addSequence=function(e){var t=this.sequenceId++,n=u([],l(this.sequences[e]),!1);return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}},n.prototype.getSequencesToSend=function(){return s(this,void 0,void 0,function(){return a(this,function(e){return[2,Object.entries(this.finalizedSequences).map(function(e){var t=l(e,2),n=t[0],r=t[1],i=r.sessionId,o=r.events;return{sequenceId:Number(n),sessionId:i,events:o}})]})})},n.prototype.storeCurrentSequence=function(e){return s(this,void 0,void 0,function(){return a(this,function(t){return this.sequences[e]?[2,this.addSequence(e)]:[2,void 0]})})},n.prototype.addEventToCurrentSequence=function(e,t){return s(this,void 0,void 0,function(){var n;return a(this,function(r){return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(n=this.addSequence(e)),this.sequences[e].push(t),[2,n]})})},n.prototype.storeSendingEvents=function(e,t){return s(this,void 0,void 0,function(){return a(this,function(n){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},[2,this.sequenceId++]})})},n.prototype.cleanUpSessionEventsStore=function(e,t){return s(this,void 0,void 0,function(){return a(this,function(e){return void 0!==t&&delete this.finalizedSequences[t],[2]})})},n}(pt),Rt=function(e){var t=e.config,n=e.minInterval,r=e.maxInterval,o=e.type,c=e.payloadBatcher,d=e.storeType,v=e.trackDestinationWorkerScript;return s(void 0,void 0,void 0,function(){function e(e){return void 0===e&&(e=!1),s(this,void 0,void 0,function(){return a(this,function(t){return[2,h.flush(e)]})})}var h,f,g,p,m,y,b,S,I,w,C,k,P,E,x;return a(this,function(M){switch(M.label){case 0:return h=new He(i(i({},t),{loggerProvider:t.loggerProvider,payloadBatcher:c,workerScript:v})),f=function(){return new Mt({loggerProvider:t.loggerProvider,maxInterval:r,minInterval:n})},p=!1,y=function(){return s(void 0,void 0,void 0,function(){var e,n,r;return a(this,function(i){switch(i.label){case 0:return p?(p=!1,t.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store."),g?[4,m.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,m=f(),e&&g&&(r=g,e.forEach(function(e){k({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r})})),[2]}})})},b=function(){return s(void 0,void 0,void 0,function(){var e;return a(this,function(i){switch(i.label){case 0:return[4,xt.new(o,{loggerProvider:t.loggerProvider,minInterval:n,maxInterval:r,apiKey:t.apiKey,onPersistentFailure:function(){y()}})];case 1:return(e=i.sent())?(p=!0,[2,e]):(t.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),[2,f()])}})})},"idb"!==d?[3,2]:[4,b()];case 1:return S=M.sent(),[3,3];case 2:S=f(),M.label=3;case 3:return m=S,I=[],w=0,C=function(e){if(!(e<=w)){var t=Math.min(e-w,I.length);t>0&&(I.splice(0,t),w=e)}},k=function(e){var n=e.events,r=e.sessionId,i=e.deviceId,c=e.sequenceId,l=n.map(function(e){return{event:e,bytes:new Blob([e]).size}}),u=l.filter(function(e){return e.bytes>de});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.bytes/1024)," KB")}).join(", "),". If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support."));var d=u.length>0?l.filter(function(e){return e.bytes<=de}).map(function(e){return e.event}):n;0!==d.length?(t.debugMode&&xe().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(){}),h.sendEventsList({events:d,sessionId:r,flushMaxRetries:t.flushMaxRetries,apiKey:t.apiKey,deviceId:i,sampleRate:t.sampleRate,serverZone:t.serverZone,version:t.version,type:o,onComplete:function(){return s(void 0,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:return[4,m.cleanUpSessionEventsStore(r,c)];case 1:return e.sent(),[2]}})})}})):m.cleanUpSessionEventsStore(r,c).catch(function(e){t.loggerProvider.warn("Failed to clean up session replay events store:",e)})},P=function(e){var n=e.sessionId,r=e.deviceId;g=r;var i=w+I.length;m.storeCurrentSequence(n).then(function(e){e&&(C(i),k({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)})},E=function(e){var n=e.deviceId;return s(void 0,void 0,void 0,function(){var e;return a(this,function(r){switch(r.label){case 0:return g=n,[4,m.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.forEach(function(e){k({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}),[2]):[2]}})})},x=function(e){var n=e.event,r=e.sessionId,i=e.deviceId;g=i;var o=w+I.length;I.push(n.data),m.addEventToCurrentSequence(r,n.data).then(function(e){e&&(C(o),k({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:P,addEvent:x,sendStoredEvents:E,flush:e,getBeaconEvents:function(){return u([],l(I),!1)},trackDestination:h}]}})})},Ot=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 s(this,void 0,void 0,function(){var t;return a(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 s(this,void 0,void 0,function(){var t;return a(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 Tt(e,t){if(kt=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};wt=i(i({},n),t),Ct=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(wt.root,n);var r=Lt(e,"all",function(){return Lt(e,"two",function(){return Lt(e,"one",function(){return Lt(e,"none")})})});if(r){var o=Wt(zt(r,e));return o.length>0&&(r=o[0]),Dt(r)}throw new Error("Selector was not found.")}function Lt(e,t,n){for(var r=null,i=[],o=e,s=0,a=function(){var e,a,d=(new Date).getTime()-kt.getTime();if(void 0!==wt.timeoutMs&&d>wt.timeoutMs)throw new Error("Timeout: Can't find a unique selector after ".concat(d,"ms"));var v=jt(function(e){var t=e.getAttribute("id");if(t&&wt.idName(t))return{name:"#"+CSS.escape(t),penalty:0};return null}(o))||jt.apply(void 0,u([],l(function(e){var t=Array.from(e.attributes).filter(function(e){return wt.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))||jt.apply(void 0,u([],l(function(e){var t=Array.from(e.classList).filter(wt.className);return t.map(function(e){return{name:"."+CSS.escape(e),penalty:1}})}(o)),!1))||jt(function(e){var t=e.tagName.toLowerCase();if(wt.tagName(t))return{name:t,penalty:2};return null}(o))||[{name:"*",penalty:3}],h=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)h&&(v=v.concat(v.filter(Ut).map(function(e){return qt(e,h)})));else if("two"==t)v=v.slice(0,1),h&&(v=v.concat(v.filter(Ut).map(function(e){return qt(e,h)})));else if("one"==t){var f=l(v=v.slice(0,1),1)[0];h&&Ut(f)&&(v=[qt(f,h)])}else"none"==t&&(v=[{name:"*",penalty:3}],h&&(v=[qt(v[0],h)]));try{for(var g=(e=void 0,c(v)),p=g.next();!p.done;p=g.next()){(f=p.value).level=s}}catch(t){e={error:t}}finally{try{p&&!p.done&&(a=g.return)&&a.call(g)}finally{if(e)throw e.error}}if(i.push(v),i.length>=wt.seedMinLength&&(r=_t(i,n)))return"break";o=o.parentElement,s++};o;){if("break"===a())break}return r||(r=_t(i,n)),!r&&n?n():r}function _t(e,t){var n,r,i=Wt(Bt(e));if(i.length>wt.threshold)return t?t():null;try{for(var o=c(i),s=o.next();!s.done;s=o.next()){var a=s.value;if(At(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 Dt(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 Ft(e){return e.map(function(e){return e.penalty}).reduce(function(e,t){return e+t},0)}function At(e){var t=Dt(e);switch(Ct.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 qt(e,t){return{name:e.name+":nth-child(".concat(t,")"),penalty:e.penalty+1}}function Ut(e){return"html"!==e.name&&!e.name.startsWith("#")}function jt(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.filter(Nt);return n.length>0?n:null}function Nt(e){return null!=e}function Bt(e,t){var n,r,i,o,s,l;return void 0===t&&(t=[]),a(this,function(a){switch(a.label){case 0:if(!(e.length>0))return[3,9];a.label=1;case 1:a.trys.push([1,6,7,8]),n=c(e[0]),r=n.next(),a.label=2;case 2:return r.done?[3,5]:(i=r.value,[5,c(Bt(e.slice(1,e.length),t.concat(i)))]);case 3:a.sent(),a.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=a.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(l=n.return)&&l.call(n)}finally{if(s)throw s.error}return[7];case 8:return[3,11];case 9:return[4,t];case 10:a.sent(),a.label=11;case 11:return[2]}})}function Wt(e){return u([],l(e),!1).sort(function(e,t){return Ft(e)-Ft(t)})}function zt(e,t,n){var r,i,o;return void 0===n&&(n={counter:0,visited:new Map}),a(this,function(s){switch(s.label){case 0:if(!(e.length>2&&e.length>wt.optimizedMinLength))return[3,5];r=1,s.label=1;case 1:return r<e.length-1?n.counter>wt.maxNumberOfTries?[2]:(n.counter+=1,(i=u([],l(e),!1)).splice(r,1),o=Dt(i),n.visited.has(o)?[2]:At(i)&&function(e,t){return Ct.querySelector(Dt(e))===t}(i,t)?[4,i]:[3,4]):[3,5];case 2:return s.sent(),n.visited.set(o,!0),[5,c(zt(i,t,n))];case 3:s.sent(),s.label=4;case 4:return r++,[3,1];case 5:return[2]}})}var Kt=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}},Ht=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 o=r.reduce(function(e,t){var n=t.x,r=t.y,o=t.selector,s=t.timestamp,a=s-s%36e5,c="".concat(n,":").concat(r,":").concat(null!=o?o:"",":").concat(a);return e[c]?e[c].count+=1:e[c]=i(i({},t),{timestamp:a,count:1}),e},{});return{version:t,events:Object.values(o)}},Qt=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 c=g();if(c){var l=c.location,u=c.innerHeight,d=c.innerWidth;if(l){var v=e.x,h=e.y;if(void 0!==v&&void 0!==h){var f,p=o.getNode(e.id);if(p)try{f=Tt(p,a)}catch(e){n.logger.debug("error resolving selector from finder")}var m=Ee(l.href,s),y={x:v+n.scrollWatcher.currentScrollX,y:h+n.scrollWatcher.currentScrollY,selector:f,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 Jt(){var e=g();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function Gt(){var e=g();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}var $t=function(){function e(e,t){var n=g();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=me(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}return e.prototype.send=function(e,t){var n=this.context,r=n.sessionId,i=n.type,o=new URLSearchParams({device_id:e,session_id:String(r),type:String(i),api_key:this.apiKey}),s="".concat(this.basePageUrl,"?").concat(o.toString());this.sendBeacon(s,t)||this.sendXhr(s,t)},e}(),Zt=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(),c=g();if(c&&a){var l=null!==(r=c.scrollX)&&void 0!==r?r:0,u=null!==(i=c.scrollY)&&void 0!==i?i:0;(l>0||u>0)&&n.update({id:1,x:l,y:u}),n.transport.send(a,{version:1,events:[{maxScrollX:n._maxScrollX,maxScrollY:n._maxScrollY,maxScrollWidth:n._maxScrollWidth,maxScrollHeight:n._maxScrollHeight,viewportHeight:Jt(),viewportWidth:Gt(),pageUrl:Ee(c.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=Gt(),this._maxScrollHeight=Jt(),this.config=t,this.transport=e}return e.default=function(t,n){return new e(new $t(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=Gt();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=Jt();this._maxScrollY=e.y;var o=e.y+i;o>this._maxScrollHeight&&(this._maxScrollHeight=o),this.timestamp=t}},e}(),Vt=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))},Xt=function(){var e=this;this.dbs={},this.createStore=function(t){return s(e,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:return[4,it(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 s(e,void 0,void 0,function(){var e,n;return a(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 s(e,void 0,void 0,function(){var e,t,o,s;return a(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(),mt(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 s(e,void 0,void 0,function(){var e,t,s;return a(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(),mt(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 s(e,void 0,void 0,function(){var e,t,o,s,c,l,u,d;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,8,,9]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,(o=e.transaction("sessionTargetingMatch","readwrite")).store.getAll()];case 2:s=a.sent(),c=0,a.label=3;case 3:return c<s.length?(l=s[c],u=Date.now()-l.lastUpdated,l.sessionId!==t&&u>1728e5?[4,o.store.delete(l.sessionId)]:[3,5]):[3,6];case 4:a.sent(),a.label=5;case 5:return c++,[3,3];case 6:return[4,o.done];case 7:return a.sent(),[3,9];case 8:return d=a.sent(),mt(n,"Failed to clear old targeting matches for sessions: ".concat(d),d),[3,9];case 9:return[2]}})})}},Yt=new Xt,en=function(e){var t=e.sessionId,n=e.targetingConfig,r=e.loggerProvider,o=e.apiKey,c=e.targetingParams,l=e.urlChange,u=void 0!==l&&l;return s(void 0,void 0,void 0,function(){var e,s,l,d,v,h;return a(this,function(a){switch(a.label){case 0:return[4,Yt.clearStoreOfOldSessions({loggerProvider:r,apiKey:o,currentSessionId:t})];case 1:return a.sent(),[4,Yt.getTargetingMatchForSession({loggerProvider:r,apiKey:o,sessionId:t})];case 2:if(!0===a.sent()&&!u)return[2,!0];e=!0,a.label=3;case 3:return a.trys.push([3,6,,7]),[4,import("./index-min3.js")];case 4:return s=a.sent().evaluateTargeting,l=i(i({},c),{flag:n,sessionId:"string"==typeof t?parseInt(t,10):t,apiKey:o,loggerProvider:r}),[4,s(l)];case 5:return(d=a.sent())&&d.sr_targeting_config&&(e="on"===d.sr_targeting_config.key),Yt.storeTargetingMatchForSession({loggerProvider:r,apiKey:o,sessionId:t,targetingMatch:e}),[3,7];case 6:return v=a.sent(),h=v,r.warn(h.message),[3,7];case 7:return[2,e]}})})},tn=2654435761,nn=2246822519,rn=3266489917,on=374761393;function sn(e,t){return(e<<t|e>>>32-t)>>>0}function an(e,t){return e=sn(e=e+Math.imul(t,nn)>>>0,13),e=Math.imul(e,tn)>>>0}function cn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function ln(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+nn>>>0,a=t+nn>>>0,c=t>>>0,l=t-tn>>>0;o<=i-16;)s=an(s,cn(r,o)),a=an(a,cn(r,o+=4)),c=an(c,cn(r,o+=4)),l=an(l,cn(r,o+=4)),o+=4;n=sn(s,1)+sn(a,7)+sn(c,12)+sn(l,18)>>>0}else n=t+on>>>0;for(n=n+i>>>0;o<=i-4;)n=n+Math.imul(cn(r,o),rn)>>>0,n=Math.imul(sn(n,17),668265263)>>>0,o+=4;for(;o<i;)n=n+Math.imul(r[o],on)>>>0,n=Math.imul(sn(n,11),tn)>>>0,o++;return n^=n>>>15,n=Math.imul(n,nn)>>>0,n^=n>>>13,n=Math.imul(n,rn)>>>0,(n^=n>>>16)>>>0}var un="__amplitude_url_tracking_patched__",dn=new WeakMap;function vn(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?ie:o;if(i){var a=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""},c=a(),l=e.setInterval(function(){var e=a();e!==c&&(c=e,t(e))},s);return function(){null!=l&&e.clearInterval(l)}}var u=dn.get(e);if(!u){var d=void 0,v=new Set,h=function(){var t=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""}();void 0!==d&&t===d||(d=t,v.forEach(function(e){return e(t)}))},f=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 h(),r};return t[un]=!0,t},g=e.history;if(null==g?void 0:g.pushState){var p=Reflect.get(g,"pushState");p[un]||(g.pushState=f(p))}if(null==g?void 0:g.replaceState){var m=Reflect.get(g,"replaceState");m[un]||(g.replaceState=f(m))}u={callbacks:v,notify:h,onPopStateOrHashChange:function(){return h()},listenersAttached:!1},dn.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 hn(e){return void 0===e&&(e={}),{name:"amplitude/url-tracking@1",observer:function(t,n,r){var o,s,a,c=i(i({},e),r),l=c.ugcFilterRules||[],u=null!==(o=c.enablePolling)&&void 0!==o&&o,d=null!==(s=c.pollingInterval)&&void 0!==s?s:ie,v=null!==(a=c.captureDocumentTitle)&&void 0!==a&&a;if(!n)return function(){};var h=void 0,f=function(){return n.location&&n.location.href||""},g=function(){var e=f();if(void 0===h||e!==h){h=e;var r=function(){var e=n.innerHeight,t=n.innerWidth,r=n.document,i=f(),o="";return v&&(o=(null==r?void 0:r.title)||""),{href:l.length>0?Ee(i,l):i,title:o,viewportHeight:e,viewportWidth:t,type:"url-change-event"}}();t(r)}},p=vn(n,function(){return g()},u?{enablePolling:!0,pollingInterval:d}:{});return g(),function(){return p()}},options:e}}hn();var fn=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(),g()&&(this.sendToAllIframes({type:fe,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 v=(i=void 0,c(Array.from(d.addedNodes))),h=v.next();!h.done;h=v.next()){(p=h.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{h&&!h.done&&(o=v.return)&&o.call(v)}finally{if(i)throw i.error}}try{for(var f=(s=void 0,c(Array.from(d.removedNodes))),g=f.next();!g.done;g=f.next()){var p;if((p=g.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{g&&!g.done&&(a=f.return)&&a.call(f)}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:fe,action:"stop"})},e.prototype.sendToIframeAfterLoad=function(e){var t=this,n=function(){t.pendingLoadListeners.delete(e),t.sendToIframe(e,{type:fe,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 gn=function(){function e(){var e=this;this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.recordEventsInFlight=!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=g();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(){if(e.recordCancelCallback&&e.recordFunction)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,i,o){return void 0===n&&(n=!1),void 0===i&&(i=!1),void 0===o&&(o=!1),s(e,void 0,void 0,function(){var e,s,c,l,u,d,v,h,f,p,m,y;return a(this,function(a){switch(a.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,(c=t.event)&&Object.values(r).includes(c.event_type)&&(c=void 0),l=null!==(m=null!==(h=null===(v=t.page)||void 0===v?void 0:v.url)&&void 0!==h?h:null===(p=null===(f=g())||void 0===f?void 0:f.location)||void 0===p?void 0:p.href)&&void 0!==m?m:"",u=null!==(y=t.page)&&void 0!==y?y:""!==l?{url:l}:void 0,[4,en({sessionId:this.identifiers.sessionId,targetingConfig:e,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:t.userProperties,event:c,page:u},urlChange:o})]):[3,2];case 1:if(d=a.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:c,targetingParams:t},null,2)),a.label=2;case 2:return n?(this.initialize(!0),[3,5]):[3,3];case 3:return!i&&this.recordCancelCallback?[3,5]:(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),[4,this.recordEvents()]);case 4:a.sent(),a.label=5;case 5:return[2]}})})},this.addCustomRRWebEvent=function(t,n,r){return void 0===n&&(n={}),void 0===r&&(r=!0),s(e,void 0,void 0,function(){var e,o,s,c;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),e=void 0,(o=this.config)&&t!==Y.METADATA?(e={config:Me(o),version:ze},r?[4,xe()]:[3,2]):[3,2];case 1:s=a.sent(),e=i(i({},s),e),a.label=2;case 2:return this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(t,i(i({},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 c=a.sent(),this.loggerProvider.debug("Error while adding custom replay capture event: ",c),[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 ge(new S)}return e.prototype.init=function(e,t){return y(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=g();if(null==r?void 0:r.location){var i=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),o=vn(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.getCurrentPageForTargeting=function(){var e,t,n=null===(t=null===(e=g())||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,o,d,v,h,f,p,m,y,b;return s(this,void 0,void 0,function(){var s,I,w,C,k,P,E,x,M,R,O,T,L,_,D,F,A,q,U,j,N,B,W,z,K,H,Q,G,$,Z=this;return a(this,function(a){switch(a.label){case 0:return null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),this.loggerProvider=new ge(t.loggerProvider||new S),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=Ce(),this.identifiers=new Vt({sessionId:t.sessionId,deviceId:t.deviceId}),s=this,[4,Fe(e,t)];case 1:return s.joinedConfigGenerator=a.sent(),[4,this.joinedConfigGenerator.generateJoinedConfig()];case 2:return I=a.sent(),w=I.joinedConfig,C=I.localConfig,k=I.remoteConfig,this.config=w,this.setMetadata(t.sessionId,w,C,k,null===(r=t.version)||void 0===r?void 0:r.version,ze,null===(o=t.version)||void 0===o?void 0:o.type),this.pageLeaveFns=[],t.sessionId&&(null===(d=this.config.interactionConfig)||void 0===d?void 0:d.enabled)&&(P=Zt.default({sessionId:t.sessionId,type:"interaction"},this.config),this.pageLeaveFns=[P.send(this.getDeviceId.bind(this)).bind(P)],this.scrollHook=P.hook.bind(P),this.clickHandler=new Qt(this.loggerProvider,P)),E=[],"idb"!==(x=this.config.storeType)||(null===(v=g())||void 0===v?void 0:v.indexedDB)||(x="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log("Using ".concat(x," for event storage.")),O=g(),this.config.useWebWorker&&O&&O.Worker?[4,import("./index-min2.js")]:[3,4];case 3:T=a.sent(),L=T.compressionScript,_=T.trackDestinationScript,M=L,R=_,a.label=4;case 4:return a.trys.push([4,6,,7]),[4,Rt({config:this.config,type:"replay",storeType:x,trackDestinationWorkerScript:R})];case 5:return D=a.sent(),E.push({name:"replay",manager:D}),[3,7];case 6:return F=a.sent(),j=F,this.loggerProvider.warn("Error occurred while creating replay events manager: ".concat(j.toString())),[3,7];case 7:if(!(null===(h=this.config.interactionConfig)||void 0===h?void 0:h.enabled))return[3,11];A=this.config.interactionConfig.batch?Ht:Kt,a.label=8;case 8:return a.trys.push([8,10,,11]),[4,Rt({config:this.config,type:"interaction",minInterval:null!==(f=this.config.interactionConfig.trackEveryNms)&&void 0!==f?f:3e4,maxInterval:6e4,payloadBatcher:A,storeType:x,trackDestinationWorkerScript:R})];case 9:return q=a.sent(),E.push({name:"interaction",manager:q}),[3,11];case 10:return U=a.sent(),j=U,this.loggerProvider.warn("Error occurred while creating interaction events manager: ".concat(j.toString())),[3,11];case 11:if(this.eventsManager=new(Ot.bind.apply(Ot,u([void 0],l(E),!1))),this.eventCompressor&&this.eventCompressor.terminate(),this.eventCompressor=new je(this.eventsManager,this.config,this.getDeviceId(),M,function(){return Z.sendEvents()}),this.pendingEmitEvents.length>0){N=this.pendingEmitEvents.splice(0);try{for(B=c(N),W=B.next();!W.done;W=B.next())z=W.value,K=z.event,H=z.sessionId,this.eventCompressor.enqueueEvent(K,H)}catch(e){G={error:e}}finally{try{W&&!W.done&&($=B.return)&&$.call(B)}finally{if(G)throw G.error}}}return this.pageLeaveFns=u(u([],l(this.pageLeaveFns),!1),[function(){var e;if(Z.config&&(null===(e=Z.identifiers)||void 0===e?void 0:e.sessionId)&&D){var t=D.getBeaconEvents();if(t.length){var n=Z.getDeviceId();n&&D.trackDestination.sendBeacon({events:t,sessionId:Z.identifiers.sessionId,deviceId:n,apiKey:Z.config.apiKey,serverZone:Z.config.serverZone})}}}],!1),[4,this.initializeNetworkObservers()];case 12:return a.sent(),(null===(p=g())||void 0===p?void 0:p.opener)&&(function(e,t){var n,r=e;if(!0!==r[X]){r[X]=!0;var i=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.0.0-alpha.3.js.gz",o=null,s=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(){var t,n;null===(n=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Initializing background capture (external script)");var r=new URL(i,e.endpoint).toString();e.loadScriptOnce(r).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)"),o=null===(r=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===r?void 0:r.call(window,{messenger:e,onBackgroundCapture:s}),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==o?void 0:o.close)||void 0===e||e.call(o),o=null})}}(Q=V()),Q.setup(i({logger:this.loggerProvider},this.config.serverZone&&{endpoint:J[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 a.sent(),(this.config.targetingConfig||(null!==(b=null===(y=null===(m=this.config.privacyConfig)||void 0===m?void 0:m.urlMaskLevels)||void 0===y?void 0:y.length)&&void 0!==b?b:0)>0)&&this.setupUrlChangeListener(),[2]}})})},e.prototype.setSessionId=function(e,t){return y(this.asyncSetSessionId(e,t))},e.prototype.asyncSetSessionId=function(e,t,n){var r;return s(this,void 0,void 0,function(){var i,o,s;return a(this,function(a){switch(a.label){case 0:return this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,(i=this.identifiers&&this.identifiers.sessionId)&&this.sendEvents(i),o=t||this.getDeviceId(),this.identifiers=new Vt({sessionId:e,deviceId:o}),this.joinedConfigGenerator&&i?[4,this.joinedConfigGenerator.generateJoinedConfig()]:[3,2];case 1:s=a.sent().joinedConfig,this.config=s,a.label=2;case 2:return(null===(r=this.config)||void 0===r?void 0:r.targetingConfig)?[4,this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0)]:[3,4];case 3:return a.sent(),[3,6];case 4:return[4,this.recordEvents()];case 5:a.sent(),a.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={})[te]=n.sessionReplayId?n.sessionReplayId:null,i=e,t.debugMode&&(i[oe]=JSON.stringify({appHash:q(t.apiKey).toString()}))),this.addCustomRRWebEvent(Y.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=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),r=this.getDeviceId();this.eventsManager&&n&&r&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:r})},e.prototype.initialize=function(e){var t;return void 0===e&&(e=!1),s(this,void 0,void 0,function(){var n;return a(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,void 0===r&&(r=v),A.getInstance(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.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,ln(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(Y.TARGETING_DECISION,{message:r,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=n),n},e.prototype.getBlockSelectors=function(){var e,t,n,r=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==r.length)return r},e.prototype.getMaskTextSelectors=function(){var e,t,n=null===(e=this.config)||void 0===e?void 0:e.privacyConfig;if("conservative"===(n?be(this.currentPageUrl,n):void 0))return"*";if(null===(t=null==n?void 0:n.urlMaskLevels)||void 0===t?void 0:t.some(function(e){return"conservative"===e.maskLevel}))return"*";var r=null==n?void 0:n.urlMaskLevels;if("conservative"===(null==n?void 0:n.defaultMaskLevel)&&r&&r.length>0)return"*";var i=null==n?void 0:n.maskSelector;return i||void 0},e.prototype.getRecordingPlugins=function(e){var t,n,r,i,o,c;return s(this,void 0,void 0,function(){var s,l,u,d;return a(this,function(a){switch(a.label){case 0:s=[];try{l=hn({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}),s.push(l)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(!(null===(c=null==e?void 0:e.console)||void 0===c?void 0:c.enabled))return[3,4];a.label=1;case 1:return a.trys.push([1,3,,4]),[4,import("./rrweb-plugin-console-record-min.js")];case 2:return u=a.sent().getRecordConsolePlugin,s.push(u({level:e.console.levels})),[3,4];case 3:return d=a.sent(),this.loggerProvider.warn("Failed to load console plugin:",d),[3,4];case 4:return[2,s.length>0?s:void 0]}})})},e.prototype.getRecordFunction=function(){return s(this,void 0,void 0,function(){var e,t;return a(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),s(this,void 0,void 0,function(){var t;return a(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._recordEvents=function(e){var t,n,r,o,c,l,u,d;return void 0===e&&(e=!0),s(this,void 0,void 0,function(){var s,v,h,f,p,m,y,b,S,I,w,C,k,P,E,x,M,R,O,T=this;return a(this,function(a){switch(a.label){case 0:return s=this.config,v=this.getShouldRecord(),h=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId,v&&h&&s?(this.stopRecordingEvents(),[4,this.getRecordFunction()]):[2];case 1:return(f=a.sent())?[4,this.initializeNetworkObservers()]:[2];case 2:a.sent(),p=null===(n=s.loggingConfig)||void 0===n?void 0:n.network,m=me(s.serverZone,s.trackServerUrl),y=[ce,le,ue,m],null===(r=this.networkObservers)||void 0===r||r.start(function(e){y.some(function(t){return e.url.startsWith(t)})||T.addCustomRRWebEvent(Y.FETCH_REQUEST,e)},p),b=s.interactionConfig,S=s.loggingConfig,I=(null==b?void 0:b.enabled)?{mouseInteraction:this.eventsManager&&(null===(o=this.clickHandler)||void 0===o?void 0:o.createHook({eventsManager:this.eventsManager,sessionId:h,deviceIdFn:this.getDeviceId.bind(this),mirror:f.mirror,ugcFilterRules:null!==(c=b.ugcFilterRules)&&void 0!==c?c:[],performanceOptions:null===(l=s.performanceConfig)||void 0===l?void 0:l.interaction})),scroll:this.scrollHook}:{},w=(null==b?void 0:b.enabled)&&b.ugcFilterRules?b.ugcFilterRules:[],this.loggerProvider.log("Session Replay capture beginning for ".concat(h,".")),a.label=3;case 3:return a.trys.push([3,5,,6]),C=!!(null===(u=s.crossOriginIframes)||void 0===u?void 0:u.enabled),k=!1!==(null===(d=s.crossOriginIframes)||void 0===d?void 0:d.coordinateChildren),(P=C&&function(){try{var e=g();return!!e&&e.parent!==e}catch(e){return!0}}())&&k?(this.crossOriginParentSignalCleanup=function(e){var t=g();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)===fe&&("start"===r.action?e.onStart():"stop"===r.action&&e.onStop())}}return t.addEventListener("message",r),function(){return t.removeEventListener("message",r)}}({onStart:function(){return T._recordEventsInChildMode(f,h,s,I)},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()))}}}),[2]):(E=this,x=f,M=[i({},this.buildRRWebRecordOptions(s,I,function(e){if(T.shouldOptOut())return T.loggerProvider.log("Opting session ".concat(h," out of recording due to optOut config.")),T.stopRecordingEvents(),void T.sendEvents();e.type===Te.Meta&&(e.data.href=Ee(e.data.href,w)),T.eventCompressor?T.eventCompressor.enqueueEvent(e,h):T.pendingEmitEvents.push({event:e,sessionId:h})},"Error while capturing replay: "))],O={},[4,this.getRecordingPlugins(S)]);case 4:return E.recordCancelCallback=x.apply(void 0,[i.apply(void 0,M.concat([(O.plugins=a.sent(),O.recordCrossOriginIframes=C,O)]))]),C&&!P&&k&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new fn),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(Y.DEBUG_INFO),e&&this.addCustomRRWebEvent(Y.METADATA,this.metadata),[3,6];case 5:return R=a.sent(),this.loggerProvider.warn("Failed to initialize session replay:",R),[3,6];case 6:return[2]}})})},e.prototype.buildRRWebRecordOptions=function(e,t,n,r){var o=this,s=e.privacyConfig;return i(i({emit:n,inlineStylesheet:e.shouldInlineStylesheet,hooks:t,maskAllInputs:!0,maskTextClass:se,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements,maskInputFn:Ie("input",s,function(){return o.currentPageUrl}),maskTextFn:Ie("text",s,function(){return o.currentPageUrl}),maskAttributeFn:we(s,function(){return o.currentPageUrl}),maskTextSelector:this.getMaskTextSelectors()},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 o.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(i(i({},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.flush=function(e){var t;return void 0===e&&(e=!1),s(this,void 0,void 0,function(){return a(this,function(n){return[2,null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)]})})},e.prototype.shutdown=function(){var e,t;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())?q(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 s(this,void 0,void 0,function(){var r,i;return a(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}(),pn=function(e){return function(){var t=e.config||Re();return{logger:t.loggerProvider,logLevel:t.logLevel}}},mn=function(){var e=new gn;return{init:P(e.init.bind(e),"init",pn(e)),evaluateTargetingAndCapture:P(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",pn(e)),setSessionId:P(e.setSessionId.bind(e),"setSessionId",pn(e)),getSessionId:P(e.getSessionId.bind(e),"getSessionId",pn(e)),getSessionReplayProperties:P(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",pn(e)),flush:P(e.flush.bind(e),"flush",pn(e)),shutdown:P(e.shutdown.bind(e),"shutdown",pn(e))}}(),yn=mn.init,bn=mn.setSessionId,Sn=mn.getSessionId,In=mn.getSessionReplayProperties;mn.flush,mn.shutdown,mn.evaluateTargetingAndCapture;const wn="amp_session_id",Cn="Amplitude Session Replay Segment Plugin [Debug]:";function kn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}var Pn=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=kn({},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(r[a]=t.read(s,a),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",kn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,kn({},this.attributes,t))},withConverter:function(t){return e(kn({},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 En=()=>{const e=Sn()||Pn.get(wn);if(e){const t=parseInt(e.toString(),10);if(isNaN(t))return;return t}},xn=(e,t)=>(Pn.set(wn,e.toString()),bn(e,t).promise),Mn=(e,t)=>s(void 0,void 0,void 0,function*(){const n=En()||0;let r;e.event.integrations&&e.event.integrations["Actions Amplitude"]&&(r=e.event.integrations["Actions Amplitude"].session_id),r&&n<r&&(yield xn(r,t));const i=In(),o=Object.assign(Object.assign({},i),e.event.properties);return e.updateEvent("properties",o),e}),Rn="0.0.23",On=({amplitudeApiKey:e,sessionReplayOptions:t,segmentInstance:n,enableWrapperDebug:r=!1})=>s(void 0,void 0,void 0,function*(){let i,o=!1,a=null==t?void 0:t.deviceId;const c={name:"Session Replay Events",type:"enrichment",version:Rn,isLoaded:()=>o,load:(n,c)=>s(void 0,void 0,void 0,function*(){if(!a){const e=c.user();a=e.anonymousId()||void 0}const n=En();r&&console.log(`${Cn} initializing session replay with sessionId=${null!=n?n:"undefined"} and deviceId=${null!=a?a:"undefined"}`),i=yn(e,Object.assign(Object.assign({},t),{sessionId:n,deviceId:a||void 0,version:{type:"segment",version:Rn}})).promise,yield i,o=!0}),track:e=>s(void 0,void 0,void 0,function*(){return yield i,yield Mn(e,a)}),page:e=>s(void 0,void 0,void 0,function*(){return yield i,yield Mn(e,a)}),identify:e=>s(void 0,void 0,void 0,function*(){yield i;const t=En();return t&&(r&&console.log(`${Cn} calling setSessionId() with sessionId=${t} and deviceId=${null!=a?a:"undefined"}`),yield xn(t,a)),e})};yield n.register(c)});export{s as _,a,i as b,On as c,g,it as o};
|
|
2
2
|
//# sourceMappingURL=index-min.js.map
|