@amplitude/session-replay-browser 1.52.0-codexsemantic-review-integration.0 → 1.52.0
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/config/joined-config.d.ts +1 -0
- package/lib/cjs/config/joined-config.d.ts.map +1 -1
- package/lib/cjs/config/joined-config.js +10 -1
- package/lib/cjs/config/joined-config.js.map +1 -1
- package/lib/cjs/config/local-config.d.ts +3 -3
- package/lib/cjs/config/local-config.d.ts.map +1 -1
- package/lib/cjs/config/local-config.js +5 -3
- package/lib/cjs/config/local-config.js.map +1 -1
- package/lib/cjs/config/types.d.ts +17 -9
- package/lib/cjs/config/types.d.ts.map +1 -1
- package/lib/cjs/config/types.js.map +1 -1
- package/lib/cjs/helpers.d.ts.map +1 -1
- package/lib/cjs/helpers.js +7 -4
- package/lib/cjs/helpers.js.map +1 -1
- package/lib/cjs/hooks/click.d.ts +2 -8
- package/lib/cjs/hooks/click.d.ts.map +1 -1
- package/lib/cjs/hooks/click.js +3 -42
- package/lib/cjs/hooks/click.js.map +1 -1
- package/lib/cjs/index.d.ts +1 -0
- package/lib/cjs/index.d.ts.map +1 -1
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/plugins/url-tracking-plugin.d.ts +0 -3
- package/lib/cjs/plugins/url-tracking-plugin.d.ts.map +1 -1
- package/lib/cjs/plugins/url-tracking-plugin.js +9 -16
- package/lib/cjs/plugins/url-tracking-plugin.js.map +1 -1
- package/lib/cjs/semantic-identity.d.ts +1 -1
- package/lib/cjs/semantic-identity.d.ts.map +1 -1
- package/lib/cjs/semantic-identity.js +4 -3
- package/lib/cjs/semantic-identity.js.map +1 -1
- package/lib/cjs/semantic-types.d.ts +45 -0
- package/lib/cjs/semantic-types.d.ts.map +1 -0
- package/lib/cjs/semantic-types.js +3 -0
- package/lib/cjs/semantic-types.js.map +1 -0
- package/lib/cjs/semantic.d.ts +9 -12
- package/lib/cjs/semantic.d.ts.map +1 -1
- package/lib/cjs/semantic.js +17 -90
- package/lib/cjs/semantic.js.map +1 -1
- package/lib/cjs/session-replay.d.ts +39 -2
- package/lib/cjs/session-replay.d.ts.map +1 -1
- package/lib/cjs/session-replay.js +267 -132
- package/lib/cjs/session-replay.js.map +1 -1
- package/lib/cjs/utils/rrweb.d.ts +0 -3
- package/lib/cjs/utils/rrweb.d.ts.map +1 -1
- package/lib/cjs/utils/rrweb.js.map +1 -1
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.d.ts.map +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/cjs/version.js.map +1 -1
- package/lib/cjs/window-focus.d.ts +40 -0
- package/lib/cjs/window-focus.d.ts.map +1 -0
- package/lib/cjs/window-focus.js +182 -0
- package/lib/cjs/window-focus.js.map +1 -0
- package/lib/esm/config/joined-config.d.ts +1 -0
- package/lib/esm/config/joined-config.d.ts.map +1 -1
- package/lib/esm/config/joined-config.js +10 -1
- package/lib/esm/config/joined-config.js.map +1 -1
- package/lib/esm/config/local-config.d.ts +3 -3
- package/lib/esm/config/local-config.d.ts.map +1 -1
- package/lib/esm/config/local-config.js +5 -3
- package/lib/esm/config/local-config.js.map +1 -1
- package/lib/esm/config/types.d.ts +17 -9
- package/lib/esm/config/types.d.ts.map +1 -1
- package/lib/esm/config/types.js.map +1 -1
- package/lib/esm/helpers.d.ts.map +1 -1
- package/lib/esm/helpers.js +8 -5
- package/lib/esm/helpers.js.map +1 -1
- package/lib/esm/hooks/click.d.ts +2 -8
- package/lib/esm/hooks/click.d.ts.map +1 -1
- package/lib/esm/hooks/click.js +3 -42
- package/lib/esm/hooks/click.js.map +1 -1
- package/lib/esm/index.d.ts +1 -0
- package/lib/esm/index.d.ts.map +1 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/plugins/url-tracking-plugin.d.ts +0 -3
- package/lib/esm/plugins/url-tracking-plugin.d.ts.map +1 -1
- package/lib/esm/plugins/url-tracking-plugin.js +9 -16
- package/lib/esm/plugins/url-tracking-plugin.js.map +1 -1
- package/lib/esm/semantic-identity.d.ts +1 -1
- package/lib/esm/semantic-identity.d.ts.map +1 -1
- package/lib/esm/semantic-identity.js +4 -3
- package/lib/esm/semantic-identity.js.map +1 -1
- package/lib/esm/semantic-types.d.ts +45 -0
- package/lib/esm/semantic-types.d.ts.map +1 -0
- package/lib/esm/semantic-types.js +2 -0
- package/lib/esm/semantic-types.js.map +1 -0
- package/lib/esm/semantic.d.ts +9 -12
- package/lib/esm/semantic.d.ts.map +1 -1
- package/lib/esm/semantic.js +17 -90
- package/lib/esm/semantic.js.map +1 -1
- package/lib/esm/session-replay.d.ts +39 -2
- package/lib/esm/session-replay.d.ts.map +1 -1
- package/lib/esm/session-replay.js +267 -132
- package/lib/esm/session-replay.js.map +1 -1
- package/lib/esm/utils/rrweb.d.ts +0 -3
- package/lib/esm/utils/rrweb.d.ts.map +1 -1
- package/lib/esm/utils/rrweb.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.d.ts.map +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/esm/version.js.map +1 -1
- package/lib/esm/window-focus.d.ts +40 -0
- package/lib/esm/window-focus.d.ts.map +1 -0
- package/lib/esm/window-focus.js +179 -0
- package/lib/esm/window-focus.js.map +1 -0
- 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/session-replay-browser-min.js +1 -1
- package/lib/scripts/session-replay-browser-min.js.gz +0 -0
- package/lib/scripts/session-replay-browser-min.js.map +1 -1
- package/package.json +4 -4
package/lib/scripts/index-min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{_ as e,a as t,b as n,c as i,d as r,e as s,f as o,g as a,o as l}from"./targeting-min.js";function c(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var d,u;!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"}(d||(d={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(u||(u={}));var h,g="$default_instance",v="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(h||(h={}));var f=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},p=e([],t(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),m=function(n){var i,r=f();if(!(null===(i=null==r?void 0:r.crypto)||void 0===i?void 0:i.getRandomValues))return function(e){return e?(e^16*Math.random()>>e/4).toString(16):(String(1e7)+String(-1e3)+String(-4e3)+String(-8e3)+String(-1e11)).replace(/[018]/g,m)}(n);var s=r.crypto.getRandomValues(new Uint8Array(16));return s[6]=15&s[6]|64,s[8]=63&s[8]|128,e([],t(s.entries()),!1).map(function(e){var n=t(e,2),i=n[0],r=n[1];return[4,6,8,10].includes(i)?"-".concat(p[r]):p[r]}).join("")},y={},b={get exports(){return y},set exports(e){y=e}},S=Object.prototype.hasOwnProperty;function I(e){return"[Throws: "+(e?e.message:"?")+"]"}function C(e){var t=[];return function e(n){if(null===n||"object"!=typeof n)return n;if(-1!==t.indexOf(n))return"[Circular]";if(t.push(n),"function"==typeof n.toJSON)try{var i=e(n.toJSON());return t.pop(),i}catch(e){return I(e)}if(Array.isArray(n)){var r=n.map(e);return t.pop(),r}var s=Object.keys(n).reduce(function(t,i){return t[i]=e(function(e,t){if(S.call(e,t))try{return e[t]}catch(e){return I(e)}return e[t]}(n,i)),t},{});return t.pop(),s}(e)}b.exports=function(e,t,n){return JSON.stringify(C(e),t,n)};var k,w=y.ensureProperties=C,E=y||c({__proto__:null,ensureProperties:w,get default(){return y}},[y]),x=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"}(k||(k={}));var P="Amplitude Logger ",M=function(){function e(){this.logLevel=k.None}return e.prototype.disable=function(){this.logLevel=k.None},e.prototype.enable=function(e){void 0===e&&(e=k.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<k.Verbose||console.log("".concat(P,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<k.Warn||console.warn("".concat(P,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<k.Error||console.error("".concat(P,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<k.Debug||console.log("".concat(P,"[Debug]: ").concat(e.join(" ")))},e}(),O=function(e){return void 0===e||""===e?g:e},T=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:g,logLevel:k.Warn,loggerProvider:new M,offline:!1,optOut:!1,serverUrl:v,serverZone:"US",useBatch:!1}},R=function(){function e(e){var t,n,i,r;this._optOut=!1;var s=T();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:s.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||s.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||s.flushQueueSize,this.instanceName=O(e.instanceName),this.loggerProvider=e.loggerProvider||s.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:s.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:s.offline,this.optOut=null!==(i=e.optOut)&&void 0!==i?i:s.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||s.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(r=e.useBatch)&&void 0!==r?r:s.useBatch,this.loggerProvider.enable(this.logLevel);var o=A(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=o.serverZone,this.serverUrl=o.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),_=function(e,t){return"EU"===e?t?"https://api.eu.amplitude.com/batch":"https://api.eu.amplitude.com/2/httpapi":t?"https://api2.amplitude.com/batch":v},A=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=T().serverZone),void 0===n&&(n=T().useBatch),e)return{serverUrl:e,serverZone:void 0};var i=["US","EU"].includes(t)?t:T().serverZone;return{serverZone:i,serverUrl:_(i,n)}};var L=function(e,t,n,i,r){return void 0===r&&(r=null),function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<k.Debug||!c||!l)return e.apply(r,s);var d,u={type:"invoke public method",name:t,args:s,stacktrace:(d=1,void 0===d&&(d=0),((new Error).stack||"").split("\n").slice(2+d).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};i&&u.states&&(u.states.before=i());var h=e.apply(r,s);return h&&h.promise?h.promise.then(function(){i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))}):(i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))),h}};class F{getApplicationContext(){return{versionName:this.versionName,language:N(),platform:"Web",os:void 0,deviceModel:void 0}}}const N=()=>"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||"";class q{constructor(){this.queue=[]}logEvent(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)}setEventReceiver(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(t=>{e(t)}),this.queue=[])}}const $=(e,t)=>{const n=["string","number","boolean","undefined"],i=typeof e;if(i!==typeof t)return!1;for(const r of n)if(r===i)return e===t;if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;const r=Array.isArray(e),s=Array.isArray(t);if(r!==s)return!1;if(!r||!s){const n=Object.keys(e).sort(),i=Object.keys(t).sort();if(!$(n,i))return!1;let r=!0;return Object.keys(e).forEach(n=>{$(e[n],t[n])||(r=!1)}),r}for(let n=0;n<e.length;n++)if(!$(e[n],t[n]))return!1;return!0};Object.entries||(Object.entries=function(e){const t=Object.keys(e);let n=t.length;const i=new Array(n);for(;n--;)i[n]=[t[n],e[t[n]]];return i});class j{constructor(){this.identity={userProperties:{}},this.listeners=new Set}editIdentity(){const e=this,t=Object.assign({},this.identity.userProperties),n=Object.assign(Object.assign({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut(e){return n.optOut=e,this},updateUserProperties:function(e){let t=n.userProperties||{};for(const[n,i]of Object.entries(e))switch(n){case"$set":for(const[e,n]of Object.entries(i))t[e]=n;break;case"$unset":for(const e of Object.keys(i))delete t[e];break;case"$clearAll":t={}}return n.userProperties=t,this},commit:function(){return e.setIdentity(n),this}}}getIdentity(){return Object.assign({},this.identity)}setIdentity(e){const t=Object.assign({},this.identity);this.identity=Object.assign({},e),$(t,this.identity)||this.listeners.forEach(t=>{t(e)})}addIdentityListener(e){this.listeners.add(e)}removeIdentityListener(e){this.listeners.delete(e)}}const D="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self;class U{constructor(){this.identityStore=new j,this.eventBridge=new q,this.applicationContextProvider=new F}static getInstance(e){return D.analyticsConnectorInstances||(D.analyticsConnectorInstances={}),D.analyticsConnectorInstances[e]||(D.analyticsConnectorInstances[e]=new U),D.analyticsConnectorInstances[e]}}var B=function(e){var t=0;if(0===e.length)return t;for(var n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},z=function(){function e(){}return e.prototype.send=function(e,t,n){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,s,o,a,l,c,d,u,g,v,f,p,m,y,b,S,I,C,k;if("object"!=typeof e)return null;var w=e.code||0,E=this.buildStatus(w);switch(E){case h.Success:return{status:E,statusCode:w,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case h.Invalid:return{status:E,statusCode:w,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(d=e.exceeded_daily_quota_devices)&&void 0!==d?d:{},silencedDevices:null!==(u=e.silenced_devices)&&void 0!==u?u:[],silencedEvents:null!==(g=e.silenced_events)&&void 0!==g?g:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case h.PayloadTooLarge:return{status:E,statusCode:w,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case h.RateLimit:return{status:E,statusCode:w,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!==(C=e.exceeded_daily_quota_users)&&void 0!==C?C:{},throttledEvents:null!==(k=e.throttled_events)&&void 0!==k?k:[]}};case h.Timeout:default:return{status:E,statusCode:w}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?h.Success:429===e?h.RateLimit:413===e?h.PayloadTooLarge:408===e?h.Timeout:e>=400&&e<500?h.Invalid:e>=500?h.Failed:h.Unknown},e}(),W=function(e){function t(t){void 0===t&&(t={});var n=e.call(this)||this;return n.customHeaders=t,n}return n(t,e),t.prototype.send=function(e,t){return i(this,void 0,void 0,function(){var n,i,o;return r(this,function(r){switch(r.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:s({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(i=r.sent()).text()];case 2:o=r.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:i.status})]}return[2]}})})},t}(z),K=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t;try{this.isSupported="undefined"!=typeof localStorage}catch(e){this.logger.debug("Remote config localstorage failed to access: ",e),this.isSupported=!1}}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};if(!this.isSupported)return Promise.resolve(t);try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var n=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(E(n))),Promise.resolve({remoteConfig:n.remoteConfig,lastFetch:new Date(n.lastFetch)})}catch(e){return this.logger.debug("Remote config localstorage failed to parse: ",e),localStorage.removeItem(this.key),Promise.resolve(t)}},e.prototype.setConfig=function(e){if(!this.isSupported)return Promise.resolve(!1);try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}();var H,G=401,J=403,Q=429,Z=function(){function e(t,n,i,r,s,o,a){void 0===i&&(i="US"),void 0===o&&(o=e.DEFAULT_CONFIG_GROUP),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=t,this.configGroup=o,this.serverUrl=r||("US"===i?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=n,this.storage=a||new K(t,n),this.customFetch=s}return e.prototype.subscribe=function(e,t,n){var i=m(),r={id:i,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(r),"all"===t?this.subscribeAll(r):this.subscribeWaitForRemote(r,t.timeout),i},e.prototype.unsubscribe=function(e){var t=this.callbackInfos.findIndex(function(t){return t.id===e});return-1===t?(this.logger.debug("Remote config client unsubscribe failed because callback with id ".concat(e," doesn't exist.")),!1):(this.callbackInfos.splice(t,1),this.logger.debug("Remote config client unsubscribe succeeded removing callback with id ".concat(e,".")),!0)},e.prototype.updateConfigs=function(){return i(this,void 0,void 0,function(){var e,t=this;return r(this,function(n){switch(n.label){case 0:return 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 i(this,void 0,void 0,function(){var t,n,i,s=this;return r(this,function(r){switch(r.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){s.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),s.sendCallback(e,t,"remote"),s.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(i=r.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(i))),null!==i.remoteConfig?this.sendCallback(e,i,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return r.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return i(this,void 0,void 0,function(){var n,i;return r(this,function(r){switch(r.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),r.label=1;case 1:return r.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),n])];case 2:return i=r.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,i,"remote"),this.storage.setConfig(i),[3,5];case 3:return r.sent(),this.logger.debug("Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache."),[4,this.storage.fetchConfig()];case 4:return null!==(i=r.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,i,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,i,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var i;e.lastCallback=new Date,i=e.key?e.key.split(".").reduce(function(e,t){return null===e?e:t in e?e[t]:null},t.remoteConfig):t.remoteConfig,e.callback(i,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),i(this,void 0,void 0,function(){var n,i,s,o,a,l,c=this;return r(this,function(d){switch(d.label){case 0:n=t/e,i={remoteConfig:null,lastFetch:new Date},s=function(i){var s,a,l,d,u,h,g,v,f;return r(this,function(r){switch(r.label){case 0:s=!0,a=new AbortController,l=setTimeout(function(){return a.abort()},t),r.label=1;case 1:return r.trys.push([1,10,11,12]),d=o.getUrlParams(),u={Accept:"*/*"},o.customFetch?[4,(p=o.customFetch({url:d,method:"GET",headers:u,signal:a.signal}),m=a.signal,new Promise(function(e,t){var n=function(){var e=new Error("Remote config custom fetch aborted by timeout");e.name="AbortError",t(e)};m.addEventListener("abort",n,{once:!0}),p.then(function(t){m.removeEventListener("abort",n),e(t)},function(e){m.removeEventListener("abort",n),t(e)})}))]:[3,3];case 2:return g=r.sent(),[3,5];case 3:return[4,fetch(d,{method:"GET",headers:u,signal:a.signal})];case 4:g=r.sent(),r.label=5;case 5:return(h=g).ok||h.status>=200&&h.status<300?[3,7]:[4,h.text()];case 6:return v=r.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(h.status,": ").concat(v)),h.status===G||h.status===J?(o.logger.error("Remote config client fetch failed with ".concat(h.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,s=!1):h.status>=400&&h.status<500&&h.status!==Q&&(s=!1),[3,9];case 7:return[4,h.json()];case 8:return[2,{value:{remoteConfig:r.sent(),lastFetch:new Date}}];case 9:return[3,12];case 10:return(f=r.sent())instanceof Error&&"AbortError"===f.name?o.logger.debug("Remote config client fetch with retry time ".concat(e," timed out after ").concat(t,"ms")):o.logger.debug("Remote config client fetch with retry time ".concat(e," is rejected because: "),f),[3,12];case 11:return clearTimeout(l),[7];case 12:return s?i<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,14]:[2,"break"];case 13:r.sent(),r.label=14;case 14:return[2]}var p,m})},o=this,a=0,d.label=1;case 1:return a<e?[5,s(a)]:[3,4];case 2:if("object"==typeof(l=d.sent()))return[2,l.value];if("break"===l)return[3,4];d.label=3;case 3:return a++,[3,1];case 4:return[2,i]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var e=encodeURIComponent(this.apiKey),t=new URLSearchParams;return t.append("config_group",this.configGroup),"".concat(this.serverUrl,"/").concat(e,"?").concat(t.toString())},e.DEFAULT_CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(H||(H={}));var X,V="https://app.amplitude.com",Y={US:V,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var ee="__AMPLITUDE_MESSENGER_INSTANCE__",te="__AMPLITUDE_MESSENGER__",ne=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?V:t;this[X]=!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,i,r;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===(r=null===(i=window.opener)||void 0===i?void 0:i.postMessage)||void 0===r||r.call(i,e,this.endpoint)},e.prototype.sendRequest=function(e,t,n){var i=this;void 0===n&&(n={timeout:15e3});var r="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),s={id:r,action:e,args:t};return new Promise(function(t,o){i.requestCallbacks[r]={resolve:t,reject:o},i.notify(s),n.timeout>0&&setTimeout(function(){o(new Error("".concat(e," timed out (id: ").concat(r,")"))),delete i.requestCallbacks[r]},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,i,r,s;this.actionHandlers.has(e)&&(null===(s=null===(r=this.logger)||void 0===r?void 0:r.warn)||void 0===s||s.call(r,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var a=this.pendingMessages.get(e);if(a){this.pendingMessages.delete(e);try{for(var l=o(a),c=l.next();!c.done;c=l.next()){t(c.value)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}},e.prototype.loadScriptOnce=function(e){return i(this,void 0,void 0,function(){var t,n,i;return r(this,function(r){switch(r.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 i;try{var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.addEventListener("load",function(){t({status:!0})},{once:!0}),r.addEventListener("error",function(){n({status:!1,message:"Failed to load the script ".concat(e)})}),null===(i=document.head)||void 0===i||i.appendChild(r)}catch(e){n(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,n),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,n];case 2:return r.sent(),[3,4];case 3:throw i=r.sent(),this.scriptLoadPromises.delete(e),i;case 4:return[2]}})})},e.prototype.setup=function(e){var t,n,i=this,r=void 0===e?{}:e,s=r.logger,o=r.endpoint;s&&(this.logger=s),o&&this.endpoint===V&&(this.endpoint=o),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,r,s,o;if(null===(n=null===(t=i.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message received: ",JSON.stringify(e)),i.endpoint===e.origin){var a=e.data,l=null==a?void 0:a.action;if(l)if("id"in a&&a.id)null===(s=null===(r=i.logger)||void 0===r?void 0:r.debug)||void 0===s||s.call(r,"Received Response to previous request: ",JSON.stringify(e)),i.handleResponse(a);else{if("ping"===l)return void i.notify({action:"pong"});var c=i.actionHandlers.get(l);if(c)c(a.data);else{var d=null!==(o=i.pendingMessages.get(l))&&void 0!==o?o:[];d.push(a.data),i.pendingMessages.set(l,d)}}}},window.addEventListener("message",this.messageHandler),this.notify({action:"page-loaded"}))},e.prototype.destroy=function(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.isSetup=!1,this.actionHandlers.clear(),this.pendingMessages.clear(),this.requestCallbacks={},this.scriptLoadPromises.clear();var e=f();(null==e?void 0:e[te])===this&&delete e[te]},e}();function ie(e){var t,n=f(),i=null==n?void 0:n[te];if("object"==typeof(t=i)&&null!==t&&ee in t&&!0===t[ee])return i;var r=new ne(e);return n&&(n[te]=r),r}X=ee;var re=["desktop","tablet","mobile"],se="__AMPLITUDE_BACKGROUND_CAPTURE__";function oe(e,t){var n,i=e;if(!0!==i[se]){i[se]=!0;var r=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.1.0.js.gz",o=null,a=function(t,n){var i,r;"background-capture-complete"===t&&(null===(r=null===(i=e.logger)||void 0===i?void 0:i.debug)||void 0===r||r.call(i,"Background capture complete"),e.notify({action:"background-capture-complete",data:n}))};e.registerActionHandler("initialize-background-capture",function(t){var n,i;null===(i=null===(n=e.logger)||void 0===n?void 0:n.debug)||void 0===i||i.call(n,"Initializing background capture (external script)");var l=new URL(r,e.endpoint).toString(),c=t&&"object"==typeof t?function(e){if("string"==typeof e)return re.includes(e)?e:void 0}(t.deviceMode):void 0;e.loadScriptOnce(l).then(function(){var t,n,i;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===(i=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===i?void 0:i.call(window,s({messenger:e,onBackgroundCapture:a},void 0!==c?{initialDeviceMode:c}:{})),e.notify({action:"background-capture-loaded"})}).catch(function(){var t;null===(t=e.logger)||void 0===t||t.warn("Failed to initialize background capture")})}),e.registerActionHandler("close-background-capture",function(){var e;null===(e=null==o?void 0:o.close)||void 0===e||e.call(o),o=null})}}const ae="[Amplitude]",le=`${ae} Session Replay ID`,ce=H.US,de={enabled:!0},ue=1e3,he=`${ae} Session Replay Debug`,ge="https://api-sr.amplitude.com/sessions/v2/track",ve="https://api-sr.eu.amplitude.com/sessions/v2/track",fe="https://api-sr.stag2.amplitude.com/sessions/v2/track",pe=9e6,me=/payload.*exceed/i,ye=500,be=1e4,Se=1024,Ie="X-Session-Replay-Event-Skipped",Ce="amplitude-sr-iframe";var ke;!function(e){e.GET_SR_PROPS="get-sr-props",e.DEBUG_INFO="debug-info",e.FETCH_REQUEST="fetch-request",e.METADATA="metadata",e.TARGETING_DECISION="targeting-decision",e.REPLAY_GATE_DECISION="replay-gate-decision"}(ke||(ke={}));class we{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}var Ee="medium";function xe(e){var t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}var Pe=new Map,Me=function(e){var t=Pe.get(e);if(t)return t;var n="\0TRAIL\0",i="\0MID\0",r="\0DS\0",s="\0ST\0",o="\0QU\0",a=e;a=(a=(a=(a=(a=(a=(a=(a=(a=(a=(a=a.replace(/\/\*\*$/,n)).replace(/\/\*\*\//g,i)).replace(/\*\*/g,r)).replace(/\*/g,s)).replace(/\?/g,o)).replace(/[.+^${}()|[\]\\]/g,"\\$&")).split(n).join("(/.*)?")).split(i).join("/(.*\\/)?")).split(r).join(".*")).split(s).join(".*")).split(o).join(".");var l=new RegExp("^".concat(a,"$"));return Pe.set(e,l),l},Oe=function(e,t,n){var i;switch(t){case"light":if("input"!==e)return!1;var r=n?xe(n):"";return!!r&&(!!["password","hidden","email","tel"].includes(r)||!!(null===(i=n.autocomplete)||void 0===i?void 0:i.startsWith("cc-")));case"medium":return"input"===e;case"conservative":return!0;default:return Oe(e,Ee,n)}},Te=function(e,t){var n,i,r;if(e&&t.urlMaskLevels)try{for(var s=o(t.urlMaskLevels),a=s.next();!a.done;a=s.next()){var l=a.value;if(Me(l.match).test(e))return l.maskLevel}}catch(e){n={error:e}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return null!==(r=t.defaultMaskLevel)&&void 0!==r?r:Ee},Re=function(e,t,n,i){var r,s;if(void 0===t&&(t={defaultMaskLevel:Ee}),n){if(n.closest(".amp-mask, [data-amp-mask]"))return!0;var o=(null!==(r=t.maskSelector)&&void 0!==r?r:[]).some(function(e){return n.closest(e)});if(o)return!0;if(n.closest(".amp-unmask, [data-amp-unmask]"))return!1;var a=(null!==(s=t.unmaskSelector)&&void 0!==s?s:[]).some(function(e){return n.closest(e)});if(a)return!1}return Oe(e,Te(i,t),n)},_e=function(e,t,n){return function(i,r){return Re(e,t,r,null==n?void 0:n())?i.replace(/[^\s]/g,"*"):i}},Ae=function(e,t){return function(n,i,r){var s;if("style"===n)return i;if(!(null!==(s=null==e?void 0:e.maskAttributes)&&void 0!==s?s:[]).includes(n))return i;var o=["INPUT","SELECT","TEXTAREA"].includes(r.tagName)?"input":"text";return Re(o,e,r,null==t?void 0:t())?i.replace(/[^\s]/g,"*"):i}},Le=function(n){var i=null==n?void 0:n.blockSelector;return e(e([],t("string"==typeof i?i?[i]:[]:null!=i?i:[]),!1),["[data-amp-block]"],!1).join(",")},Fe=function(n,i){var r,s;return n&&("conservative"===Te(i,n)||"conservative"===n.defaultMaskLevel||(null===(r=n.urlMaskLevels)||void 0===r?void 0:r.some(function(e){return"conservative"===e.maskLevel})))?"*":e(e([],t(null!==(s=null==n?void 0:n.maskSelector)&&void 0!==s?s:[]),!1),["[data-amp-mask]"],!1).join(",")};function Ne(e,t){return t||("STAGING"===e?fe:"EU"===e?ve:ge)}const qe=()=>{const e=f();return(null==e?void 0:e.location)?e.location.href:""},$e=(e,t)=>{for(const n of t){const t=Me(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},je=()=>i(void 0,void 0,void 0,function*(){try{const e=f();if(e){const{usage:t,quota:n,usageDetails:i}=yield e.navigator.storage.estimate(),r=t?Math.round(t/Se):0;return{totalStorageSize:r,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(i)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}}),De=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t},Ue=()=>({flushMaxRetries:2,logLevel:k.Warn,loggerProvider:new M,transportProvider:new W});class Be extends R{constructor(e,t){var n,i,r,s,o,a,l,c,d,u,h,g,v,f;const p=Ue();super(Object.assign(Object.assign({transportProvider:p.transportProvider,loggerProvider:new we(t.loggerProvider||p.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=p.flushMaxRetries?t.flushMaxRetries:p.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.semanticCapture=t.semanticCapture,this.semanticAnalyticsContext=t.semanticAnalyticsContext,this.serverZone=t.serverZone||ce,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.inlineImages=t.inlineImages,this.version=t.version,this.performanceConfig=t.performanceConfig||de,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"memory",this.applyBackgroundColorToBlockedElements=null!==(i=t.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,this.enableUrlChangePolling=null!==(r=t.enableUrlChangePolling)&&void 0!==r&&r,this.urlChangePollingInterval=null!==(s=t.urlChangePollingInterval)&&void 0!==s?s:ue,this.captureDocumentTitle=null!==(o=t.captureDocumentTitle)&&void 0!==o&&o,void 0!==t.fullSnapshotIntervalMs&&(this.fullSnapshotIntervalMs=t.fullSnapshotIntervalMs),void 0!==t.eagerFullSnapshotSend&&(this.eagerFullSnapshotSend=t.eagerFullSnapshotSend),this.captureFullSnapshotOnFocus=null!==(a=t.captureFullSnapshotOnFocus)&&void 0!==a&&a,void 0!==t.maxPersistedEventsSizeBytes&&(this.maxPersistedEventsSizeBytes=Ge(t.maxPersistedEventsSizeBytes,We,Ke,"maxPersistedEventsSizeBytes",this.loggerProvider)),void 0!==t.maxSingleEventSizeBytes&&(this.maxSingleEventSizeBytes=Ge(t.maxSingleEventSizeBytes,We,He,"maxSingleEventSizeBytes",this.loggerProvider)),this.privacyConfig=Object.assign(Object.assign({},null!==(l=t.privacyConfig)&&void 0!==l?l:{}),{unmaskSelector:Array.from(new Set([".amp-unmask",...null!==(d=null===(c=t.privacyConfig)||void 0===c?void 0:c.unmaskSelector)&&void 0!==d?d:[]]))}),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every(e=>"string"==typeof e.selector&&"string"==typeof e.replacement))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every(e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t}))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode);const m=t;this.useWebWorker=null===(g=null!==(u=t.useWebWorker)&&void 0!==u?u:null===(h=m.experimental)||void 0===h?void 0:h.useWebWorker)||void 0===g||g,this.enableTransportCompression=null===(v=t.enableTransportCompression)||void 0===v||v,this.sendTimeoutMs=t.sendTimeoutMs,this.captureAdoptedStyleSheets=null===(f=t.captureAdoptedStyleSheets)||void 0===f||f,t.crossOriginIframes&&(this.crossOriginIframes=t.crossOriginIframes),t.flushIntervalConfig?this.flushIntervalConfig=function(e,t){var n,i;const r={};void 0!==e.minIntervalMs&&(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<ze?(t.warn(`flushIntervalConfig.minIntervalMs ${e.minIntervalMs} is below floor ${ze}ms; clamping.`),r.minIntervalMs=ze):r.minIntervalMs=e.minIntervalMs);void 0!==e.maxIntervalMs&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<ze?(t.warn(`flushIntervalConfig.maxIntervalMs ${e.maxIntervalMs} is below floor ${ze}ms; clamping.`),r.maxIntervalMs=ze):r.maxIntervalMs=e.maxIntervalMs);if(void 0!==r.minIntervalMs||void 0!==r.maxIntervalMs){const e=null!==(n=r.minIntervalMs)&&void 0!==n?n:ye,s=null!==(i=r.maxIntervalMs)&&void 0!==i?i:be;s<e&&(void 0===r.maxIntervalMs?(t.warn(`flushIntervalConfig.minIntervalMs (${e}) exceeds the default maxIntervalMs (10000); raising max to match min.`),r.maxIntervalMs=e):void 0===r.minIntervalMs?(t.warn(`flushIntervalConfig.maxIntervalMs (${s}) is below the default minIntervalMs (500); lowering min to match max.`),r.minIntervalMs=s):(t.warn(`flushIntervalConfig.maxIntervalMs (${r.maxIntervalMs}) is less than minIntervalMs (${r.minIntervalMs}); raising max to match min.`),r.maxIntervalMs=r.minIntervalMs))}return r}(t.flushIntervalConfig,this.loggerProvider):this.flushIntervalConfig={minIntervalMs:1e3,maxIntervalMs:1e4},this.handleSendEvents=t.handleSendEvents,this.handleFetchConfig=t.handleFetchConfig}}const ze=100,We=1e3,Ke=8e6,He=1e7;function Ge(e,t,n,i,r){if(Number.isFinite(e))return e<t?(r.warn(`${i} ${e} is below floor ${t}; clamping.`),t):e>n?(r.warn(`${i} ${e} exceeds ceiling ${n}; clamping.`),n):e;r.warn(`${i} value is not a finite number (got ${String(e)}); ignoring.`)}var Je=new Set(["button","checkbox","combobox","link","listbox","menuitem","menuitemcheckbox","menuitemradio","option","radio","searchbox","slider","spinbutton","switch","tab","textbox","treeitem","gridcell"]),Qe=new Set(["banner","navigation","main","complementary","contentinfo","search","form","region","dialog","alertdialog","list","table","row","group"]),Ze=new Set(["button","cell","checkbox","columnheader","gridcell","heading","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","rowheader","switch","tab","tooltip","treeitem","alert","status","listitem"]),Xe=new Set(["INPUT","SELECT","TEXTAREA"]),Ve=["type","name","href","target","aria-controls","aria-haspopup","data-testid"];function Ye(e,t){var n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"…":n}function et(e,t){void 0===t&&(t="https://semantic.invalid/");try{var n=new URL(e,t);if("http:"!==n.protocol&&"https:"!==n.protocol)return"/";var i=/^#!?\//.test(n.hash)?"#"+n.hash.slice(1).split(/[?#]/)[0]:"",r=function(e){return e.split("/").map(function(e){var t;try{t=decodeURIComponent(e)}catch(e){return":id"}return/^\d+$/.test(t)||/^[\da-f]{8,}$/i.test(t)||/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(t)||t.length>=16&&/^[a-z\d]+$/i.test(t)&&/[a-z]/i.test(t)&&/\d/.test(t)?":id":e}).join("/")};return r(n.pathname)+r(i)}catch(e){return"/"}}function tt(e){var t,n,i,r,s=null===(t=e.getAttribute("role"))||void 0===t?void 0:t.trim().split(/\s+/)[0].toLowerCase();if(s)return"none"===s||"presentation"===s?"generic":s;var o=e.tagName.toLowerCase();if("a"===o||"area"===o)return e.hasAttribute("href")?"link":"generic";if("input"===o){return null!==(i={button:"button",image:"button",reset:"button",submit:"button",file:"button",checkbox:"checkbox",radio:"radio",range:"slider",number:"spinbutton",search:"searchbox",hidden:"generic"}[(null!==(n=e.getAttribute("type"))&&void 0!==n?n:"text").toLowerCase()])&&void 0!==i?i:e.hasAttribute("list")?"combobox":"textbox"}if("select"===o)return e.multiple||e.size>1?"listbox":"combobox";return/^h[1-6]$/.test(o)?"heading":"section"===o?e.hasAttribute("aria-label")||e.hasAttribute("aria-labelledby")?"region":"generic":null!==(r={button:"button",summary:"button",textarea:"textbox",nav:"navigation",main:"main",form:"form",header:"banner",footer:"contentinfo",aside:"complementary",dialog:"dialog",ul:"list",ol:"list",menu:"list",li:"listitem",table:"table",tr:"row",td:"cell",th:"columnheader",img:"img",option:"option",progress:"progressbar",output:"status",fieldset:"group",details:"group",optgroup:"group"}[o])&&void 0!==r?r:"generic"}function nt(e){var t,n=null===(t=e.getAttribute("aria-invalid"))||void 0===t?void 0:t.trim().toLowerCase();return!!n&&"false"!==n}function it(n){var i=function(i){try{var r=n.getPrivacy().blockSelector;return!!i.closest(e([".amp-block","[data-amp-block]"],t("string"==typeof r?[r]:null!=r?r:[]),!1).join(","))}catch(e){return!0}},r=function(e){try{return i(e)||Re(Xe.has(e.tagName)?"input":"text",n.getPrivacy(),e,n.getUrl())}catch(e){return!0}},s=function(e){return!!e.closest('[contenteditable]:not([contenteditable="false"])')},a=function(e,t,i){var o;if(void 0===i&&(i=80),r(e)||s(e)||void 0===t&&Xe.has(e.tagName))return null;if(void 0!==t)return null===t?null:Ye(t,i);for(var a,l=n.document.createTreeWalker(e,5),c=0,d="";a=l.nextNode();){if(++c>256)return null;if(1===a.nodeType){var u=a;if(r(u)||s(u)||Xe.has(u.tagName))return null}else d+=null!==(o=a.nodeValue)&&void 0!==o?o:"";if(d.length>2*i)break}return Ye(d,i)},l=function(e){var t,l,c,d,u,h=function(e,t){return{name:e||null,source:null===e?"masked":e?t:"unnamed"}};if(i(e))return h(null,"masked");var g=e.getAttribute("aria-labelledby");if(g){var v=g.trim().split(/\s+/).slice(0,20).map(function(e){return n.document.getElementById(e)}).filter(function(e){return!!e}).map(function(e){return a(e)});if(v.some(function(e){return null===e}))return h(null,"masked");var f=Ye(v.join(" "),80);if(f)return h(f,"aria-labelledby")}var p=e.getAttribute("aria-label");if(null==p?void 0:p.trim())return h(a(e,p),"aria-label");var m=e.labels;if(null==m?void 0:m.length){var y=m[0],b="";if(r(y))return h(null,"masked");for(var S=!1,I=n.document.createTreeWalker(y,5),C=void 0,k=0;C=I.nextNode();){if(++k>256){S=!0;break}if(1===C.nodeType&&C!==e&&(r(C)||s(C))){S=!0;break}3!==C.nodeType||(null===(c=C.parentElement)||void 0===c?void 0:c.closest('input, select, textarea, [contenteditable]:not([contenteditable="false"])'))||(b+=null!==(d=C.nodeValue)&&void 0!==d?d:"")}return h(S?null:a(y,b),y.htmlFor?"label-for":"label-wrap")}if("IMG"===e.tagName&&e.hasAttribute("alt"))return h(a(e,e.getAttribute("alt")),"alt");if("INPUT"===e.tagName&&/^(button|submit|reset)$/i.test(null!==(u=e.getAttribute("type"))&&void 0!==u?u:"")&&e.hasAttribute("value"))return h(a(e,e.getAttribute("value")),"value");if(Ze.has(tt(e))){var w=a(e);if(null===w||w)return h(w,"text")}try{for(var E=o(["title","placeholder"]),x=E.next();!x.done;x=E.next()){var P=x.value,M=e.getAttribute(P);if(M)return h(a(e,M),P)}}catch(e){t={error:e}}finally{try{x&&!x.done&&(l=E.return)&&l.call(E)}finally{if(t)throw t.error}}return h("","unnamed")},c=function(e){if(i(e))return null;var t=n.getNodeId(e);return t<0?null:t},d=function(e){var t=l(e);return{id:c(e),role:tt(e),name:t.name,name_source:t.source}},u=function(e){var t=e;try{return t.checkVisibility?t.checkVisibility({opacityProperty:!0,visibilityProperty:!0}):e.getClientRects().length>0&&"hidden"!==n.window.getComputedStyle(e).visibility}catch(e){return!1}},h=null,g=0,v="";return{id:c,blocked:i,masked:r,text:a,name:l,describe:d,visible:u,role:tt,url:function(e){return void 0===e&&(e=n.getUrl()),et(e,n.getUrl())},actionable:function(e){for(var t=e,n=e,i=0;t&&i<12;i++,t=t.parentElement){var r=tt(t);if(Je.has(r))return t;n===e&&"generic"!==r&&(n=t)}return n},container:function(e){for(var t=e.parentElement,n=0;t&&n<20;n++,t=t.parentElement)if(Qe.has(tt(t))||t.hasAttribute("aria-label")){var i=d(t);return{id:i.id,role:i.role,name:i.name}}return null},states:function(e){var n,i,r=[],s=e,a="INPUT"===e.tagName&&"checkbox"===s.type&&s.indeterminate||"mixed"===e.getAttribute("aria-checked")||"mixed"===e.getAttribute("aria-pressed");try{for(var l=o(Object.entries({disabled:e.matches(":disabled")||"true"===e.getAttribute("aria-disabled"),required:s.required||"true"===e.getAttribute("aria-required"),invalid:nt(e)||s.willValidate&&!s.validity.valid,checked:!a&&(s.checked||"true"===e.getAttribute("aria-checked")),mixed:a,busy:"true"===e.getAttribute("aria-busy"),open:("DETAILS"===e.tagName||"DIALOG"===e.tagName)&&e.hasAttribute("open"),expanded:"true"===e.getAttribute("aria-expanded"),collapsed:"false"===e.getAttribute("aria-expanded"),selected:s.selected||"true"===e.getAttribute("aria-selected"),current:e.hasAttribute("aria-current")&&"false"!==e.getAttribute("aria-current"),pressed:"true"===e.getAttribute("aria-pressed"),readonly:s.readOnly||"true"===e.getAttribute("aria-readonly")})),c=l.next();!c.done;c=l.next()){var d=t(c.value,2),u=d[0];d[1]&&r.push(u)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}return r},heading:function(){var e=n.window.performance.now(),t=n.getUrl();if(e<g&&t===v&&(!h||h.isConnected&&u(h)))return h?a(h):null;h=null,g=e+250,v=t;var i=n.document.body;if(!i)return null;for(var r=n.document.createTreeWalker(i,1),s=r.nextNode(),o=0;s&&o++<2e3&&n.window.performance.now()-e<2;){var l="H1"===s.tagName;if((l||s.matches('[role="heading"][aria-level="1"]'))&&u(s)){if(s.closest('main,[role="main"]')){h=s;break}l&&!h&&(h=s)}s=r.nextNode()}return h?a(h):null},invalidateHeading:function(){g=0,h=null},attributes:function(e){var t,s,a,l={};if(i(e))return l;try{for(var c=o(Ve),d=c.next();!d.done;d=c.next()){var u=d.value,h=e.getAttribute(u);null===h||(null===(a=n.getPrivacy().maskAttributes)||void 0===a?void 0:a.includes(u))&&r(e)||(l[u]=Ye("href"===u?et(h,n.getUrl()):h,60))}}catch(e){t={error:e}}finally{try{d&&!d.done&&(s=c.return)&&s.call(c)}finally{if(t)throw t.error}}return l}}}var rt=new WeakMap;function st(e){try{return e.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)})}}function ot(e,t){var n=rt.get(e);return n||(n=Object.freeze({tab_id:st(t),document_id:st(t)}),rt.set(e,n)),n}var at={click:2e3,keys:1e3,"resource-error":200,field:1e3,submit:300,notice:300,dialog:300,"amp-event":500,context:200,recording:200,navigation:200,visibility:200,lifecycle:200};function lt(e){return s(s({},e),{families:e.families?s({},e.families):void 0})}var ct=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function dt(e){var t,n=e.target;return 1===(null==n?void 0:n.nodeType)?n:null!==(t=null==n?void 0:n.parentElement)&&void 0!==t?t:null}function ut(e){return["INPUT","SELECT","TEXTAREA"].includes(e.tagName)}function ht(e){var t;return"INPUT"===e.tagName&&["password","hidden"].includes(null!==(t=xe(e))&&void 0!==t?t:"")}function gt(e){var t,n,i=[];if(ut(e))try{for(var r=o(ct),s=r.next();!s.done;s=r.next()){var a=s.value;e.validity[a]&&i.push(a)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}return nt(e)&&i.push("ariaInvalid"),{valid:(!ut(e)||e.validity.valid)&&!i.includes("ariaInvalid"),validity:i}}function vt(e,t){var n=e.helpers.name(t),i=n.name,r=n.source;return{id:e.helpers.id(t),role:e.helpers.role(t),name:"text"===r||"value"===r?null:i,name_source:"text"===r||"value"===r?"masked":r}}function ft(e,t,n){if(n)return null;if("SELECT"===t.tagName){var i=t.selectedOptions[0];return!i||e.helpers.blocked(i)?null:i.hasAttribute("label")?e.helpers.text(i,i.label):e.helpers.text(i)}return"INPUT"===t.tagName&&["radio","checkbox"].includes(t.type)&&t.checked?vt(e,t).name:null}var pt={families:["click","field","submit"],setup:function(n){var i,r,a=n.host,l=n.helpers,c=[],d=new Set,u=!0,h=new WeakMap,g=new Map,v=function(e){var t=a.window.setTimeout(function(){d.delete(t),u&&e()},0);return d.add(t),t},f=function(e,t){a.document.addEventListener(e,t,!0),c.push(function(){return a.document.removeEventListener(e,t,!0)})},p=function(e){var t=n.now();if(u&&n.enabled("click")&&("auxclick"!==e.type||1===e.button)){var i=dt(e);if(i&&!l.blocked(i)){var r=l.actionable(i);if(!l.blocked(r)&&n.canEmit("click")){var c=function(e,t){var n,i,r,s=null!==(r=e.host.getPrivacy().maskAttributes)&&void 0!==r?r:[];try{for(var a=o(["data-amp-key","data-testid","data-test","data-cy","id"]),l=a.next();!l.done;l=a.next()){var c=l.value,d=t.getAttribute(c);if(!(!d||s.includes(c)&&e.helpers.masked(t)||"id"===c&&(/^\d+$/.test(d)||/[a-f\d]{8,}/i.test(d)||/:r/.test(d)||/\d{3,}/.test(d))))return d.length>80?"".concat(d.slice(0,79),"…"):d}}catch(e){n={error:e}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}return null}(n,r),d=null;if(!c&&a.getSelector)try{d=a.getSelector(r)}catch(e){}n.emit("click",s(s(s(s({},l.describe(r)),{container:l.container(r),states:l.states(r),visible:l.visible(r),key:c}),c?{}:{selector:d}),{attrs:l.attributes(r),url:l.url(),heading:l.heading(),keyboard:0===e.detail,modifiers:[e.altKey?"alt":"",e.ctrlKey?"ctrl":"",e.metaKey?"meta":"",e.shiftKey?"shift":""].filter(Boolean),trusted:e.isTrusted}),t)}}}},m=function(e){var t,i;if(n.enabled("field")){var r=dt(e),o=null==r?void 0:r.closest('input, select, textarea, [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]');if(o&&("change"!==e.type||ut(o))&&!ht(o)&&!l.blocked(o)&&n.canEmit("field")){var c=Re("input",a.getPrivacy(),o,a.getUrl()),d=s(s(s(s(s(s({},vt(n,o)),{states:l.states(o),kind:"INPUT"===o.tagName?o.type:ut(o)?o.tagName.toLowerCase():"contenteditable",value_state:(ut(o)?o.value.length>0:(null!==(i=null===(t=o.textContent)||void 0===t?void 0:t.length)&&void 0!==i?i:0)>0)?"filled":"empty"}),"INPUT"===o.tagName&&["checkbox","radio"].includes(o.type)?{checked:o.checked}:{}),function(e,t){if(t)return{};if("TEXTAREA"===e.tagName)return{value:e.value};if("INPUT"!==e.tagName)return{};var n=e;return["checkbox","radio","file","button","submit","reset","image"].includes(n.type)?{}:{value:n.value}}(o,c)),gt(o)),{masked:c,option_label:ft(n,o,c)}),u=JSON.stringify(d),g=h.get(o),v=n.now();(null==g?void 0:g.payload)===u&&("focusout"===e.type||v-g.timestamp<500)||n.emit("field",d)&&h.set(o,{payload:u,timestamp:v})}}},y=function(e,t){var n=l.describe(e);if(null===n.name&&"masked"!==n.name_source){var i=null!=t?t:e.querySelector('button:not([type]), button[type="submit"], input[type="submit"], input[type="image"]');i&&!l.blocked(i)&&(n.name=l.name(i).name)}return{id:n.id,role:n.role,name:n.name}};return n.enabled("click")&&(a.externalClicks?c.push(n.on("click",p)):f("click",function(e){return p(e)}),(null!==(i=a.externalAuxClicks)&&void 0!==i?i:a.externalClicks)||f("auxclick",function(e){return p(e)})),n.enabled("field")&&(f("change",m),f("focusout",m)),n.enabled("submit")&&(f("submit",function(e){if(n.enabled("submit")){var t=dt(e);if("FORM"===(null==t?void 0:t.tagName)&&!l.blocked(t)){var i=e.submitter,r=i&&!l.blocked(i)?i:null;v(function(){n.enabled("submit")&&!l.blocked(t)&&n.canEmit("submit")&&n.emit("submit",{form:y(t,r&&!l.blocked(r)?r:null),submitter:r&&!l.blocked(r)?{id:l.id(r),role:l.role(r),name:l.name(r).name}:null,valid:!0,invalid_fields:[],prevented:e.defaultPrevented})})}}}),f("invalid",function(i){if(n.enabled("submit")){var s=dt(i);if(s&&ut(s)){var a=s.form;if(a&&!l.blocked(a)){var c=g.get(a);c||(c=new Set,g.set(a,c)),!ht(s)&&!l.blocked(s)&&c.size<10&&c.add(s),void 0===r&&(r=v(function(){var i,s;r=void 0;var a=e([],t(g),!1);if(g.clear(),n.enabled("submit"))try{for(var c=o(a),d=c.next();!d.done;d=c.next()){var u=t(d.value,2),h=u[0],v=u[1];l.blocked(h)||n.canEmit("submit")&&n.emit("submit",{form:y(h,null),submitter:null,valid:!1,prevented:!0,invalid_fields:e([],t(v),!1).filter(function(e){return!l.blocked(e)&&!ht(e)}).map(function(e){var t=vt(n,e);return{id:t.id,name:t.name,validity:gt(e).validity}})})}}catch(e){i={error:e}}finally{try{d&&!d.done&&(s=c.return)&&s.call(c)}finally{if(i)throw i.error}}}))}}}})),function(){u=!1,c.forEach(function(e){return e()}),d.forEach(function(e){return a.window.clearTimeout(e)}),d.clear(),g.clear()}}},mt='dialog,[role="dialog"],[role="alertdialog"],[aria-modal="true"]';function yt(e,t){var n,i,s,o,a,l;return r(this,function(r){switch(r.label){case 0:n=[{children:[e],index:0,hidden:!1}],r.label=1;case 1:return n.length?(i=n[n.length-1]).index===i.children.length?(n.pop(),[3,1]):(s=i.children[i.index++],o=s.attributes,a=i.hidden||void 0!==(null==o?void 0:o.hidden)||"true"===(null==o?void 0:o["aria-hidden"]),[4,{node:s,baseline:t,hidden:a}]):[3,3];case 2:return r.sent(),(null===(l=s.childNodes)||void 0===l?void 0:l.length)&&n.push({children:s.childNodes,index:0,hidden:a}),[3,1];case 3:return[2]}})}function bt(e){var t,n,i,s,a,l,c,d,u,h,g,v,f,p,m,y,b,S,I,C,k,w,E,x,P,M;return r(this,function(O){switch(O.label){case 0:return"snapshot"!==e.type?[3,2]:[5,o(yt(e.node,!0))];case 1:return O.sent(),[3,33];case 2:O.trys.push([2,7,8,9]),t=o(e.texts),n=t.next(),O.label=3;case 3:return n.done?[3,6]:[4,{id:n.value.id,text:!0}];case 4:O.sent(),O.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return i=O.sent(),I={error:i},[3,9];case 8:try{n&&!n.done&&(C=t.return)&&C.call(t)}finally{if(I)throw I.error}return[7];case 9:s=function(e){return r(this,function(t){switch(t.label){case 0:return[4,{id:e.id,dialogs:["open","hidden","aria-hidden","role","aria-modal"].some(function(t){return t in e.attributes})}];case 1:return t.sent(),[2]}})},O.label=10;case 10:O.trys.push([10,15,16,17]),a=o(e.attributes),l=a.next(),O.label=11;case 11:return l.done?[3,14]:(c=l.value,[5,s(c)]);case 12:O.sent(),O.label=13;case 13:return l=a.next(),[3,11];case 14:return[3,17];case 15:return d=O.sent(),k={error:d},[3,17];case 16:try{l&&!l.done&&(w=a.return)&&w.call(a)}finally{if(k)throw k.error}return[7];case 17:u=new Set,h=function(e){var t=!u.has(e);return u.size<1e3&&u.add(e),{id:e,text:t}},O.label=18;case 18:O.trys.push([18,23,24,25]),g=o(e.removes),v=g.next(),O.label=19;case 19:return v.done?[3,22]:(f=v.value,[4,h(f.parentId)]);case 20:O.sent(),O.label=21;case 21:return v=g.next(),[3,19];case 22:return[3,25];case 23:return p=O.sent(),E={error:p},[3,25];case 24:try{v&&!v.done&&(x=g.return)&&x.call(g)}finally{if(E)throw E.error}return[7];case 25:O.trys.push([25,31,32,33]),m=o(e.adds),y=m.next(),O.label=26;case 26:return y.done?[3,30]:(b=y.value,[4,h(b.parentId)]);case 27:return O.sent(),[5,o(yt(b.node,!1))];case 28:O.sent(),O.label=29;case 29:return y=m.next(),[3,26];case 30:return[3,33];case 31:return S=O.sent(),P={error:S},[3,33];case 32:try{y&&!y.done&&(M=m.return)&&M.call(m)}finally{if(P)throw P.error}return[7];case 33:return[2]}})}var St={families:["notice","dialog"],setup:function(e){var n=e.hasCapacity("notice"),i=e.hasCapacity("dialog"),r=e.host,s=e.helpers,a=r.window;if(!n&&!i||!r.getNode)return function(){};var l,c=!0,d=null,u=!1,h=0,g=[],v=new Set,f=new Set,p=new Set,m=new WeakMap,y=new WeakMap,b=new Map,S=new WeakMap,I=new Set,C=new Set,k=!1,w=!1,E=function(e){var t;if(!C.has(e)){C.add(e);try{null===(t=r.onError)||void 0===t||t.call(r,new Error("Semantic feedback ".concat(e," limit reached; some changes may be omitted.")))}catch(e){}}},x=function(e,t){var i;if(n&&e.isConnected&&!(void 0!==t&&(null!==(i=y.get(e))&&void 0!==i?i:-1)>=t)){if(!f.has(e)&&!b.has(e)){if(f.size+b.size>=256)return void E("notice queue");f.add(e)}void 0!==t&&y.set(e,t)}},P=function(e){i&&!p.has(e)&&p.add(e)},M=e.subscribe(function(e){"click"===e.name&&(d=e.timestamp)}),O=function(){return null!==d&&e.now()-d>=0&&e.now()-d<=3e3?d:null},T=function(){f.clear(),b.forEach(function(e){return a.clearTimeout(e)}),b.clear()},R=function(){c=!1,j(),M(),void 0!==l&&(u?a.clearTimeout(l):a.cancelAnimationFrame(l),l=void 0),T(),g.length=0,v.clear(),p.clear(),I.clear()},_=function(){return n&&!e.hasCapacity("notice")&&(n=!1,T()),i&&!e.hasCapacity("dialog")&&(i=!1,p.clear(),I.clear(),v.clear()),n||i||R(),c},A=function(t){if(f.delete(t),t.isConnected&&!b.has(t)){var i=m.get(t),r=void 0===i?0:500-(e.now()-i);r<=0?function(t){if(c&&t.isConnected&&!s.blocked(t)&&e.canEmit("notice")){var n=s.text(t,void 0,200);if(null===n||n.trim()){var i=t.getAttribute("role"),r=s.container(t);e.emit("notice",{id:s.id(t),role:"alert"===i||"status"===i||"log"===i?i:"live",text:n,visible:s.visible(t),region:r?{role:r.role,name:r.name}:null,cause_click_ts:O()}),m.set(t,e.now())}}}(t):b.set(t,a.setTimeout(function(){b.delete(t),c&&n&&(x(t),f.size&&N())},r))}},L=function(t){if(p.delete(t),s.blocked(t))return I.delete(t),void v.delete(t);var n=S.get(t),i=function(e){return e.isConnected&&e.matches(mt)&&!e.closest('[hidden],[aria-hidden="true"]')&&("DIALOG"!==e.tagName||e.hasAttribute("open"))}(t);if((null==n?void 0:n.open)!==i&&(n||i)){var r=function(e){var t=S.get(e),n=e.isConnected&&e.matches(mt)&&!e.closest('[hidden],[aria-hidden="true"]')&&("DIALOG"!==e.tagName||e.hasAttribute("open")),i="true"===e.getAttribute("aria-modal");try{i=i||e.matches(":modal")}catch(e){}var r=!e.isConnected&&t?t.payload:s.describe(e);return{open:n,payload:{id:r.id,role:"alertdialog"===e.getAttribute("role")?"alertdialog":"dialog",name:e.isConnected?r.name:null,name_source:e.isConnected?r.name_source:"masked",state:n?"open":"closed",modal:!e.isConnected&&t?t.payload.modal:i,visible:n&&s.visible(e),cause_click_ts:O()}}}(t);S.set(t,r),i?I.add(t):I.delete(t),e.emit("dialog",r.payload),t.isConnected||v.delete(t)}},F=function(){var e,n,i,r,s,d,u,h;if(l=void 0,c&&_()){var m=a.performance.now();if(k){k=!1;try{for(var y=o(v),S=y.next();!S.done;S=y.next()){var C=S.value;P(C)}}catch(t){e={error:t}}finally{try{S&&!S.done&&(n=y.return)&&n.call(y)}finally{if(e)throw e.error}}try{for(var E=o(f),x=E.next();!x.done;x=E.next()){(C=x.value).isConnected||f.delete(C)}}catch(e){i={error:e}}finally{try{x&&!x.done&&(r=E.return)&&r.call(E)}finally{if(i)throw i.error}}try{for(var M=o(b),O=M.next();!O.done;O=M.next()){var T=t(O.value,2),R=(C=T[0],T[1]);C.isConnected||(a.clearTimeout(R),b.delete(C))}}catch(e){s={error:e}}finally{try{O&&!O.done&&(d=M.return)&&d.call(M)}finally{if(s)throw s.error}}try{for(var F=o(v),q=F.next();!q.done;q=F.next()){(C=q.value).isConnected||I.has(C)||(v.delete(C),p.delete(C))}}catch(e){u={error:e}}finally{try{q&&!q.done&&(h=F.return)&&h.call(F)}finally{if(u)throw u.error}}}var j=0,D=function(e){for(;c&&(f.size||p.size)&&j<50&&a.performance.now()<e;){var t=p.size>0&&(w||!f.size);w=!t,j++,t?L(p.values().next().value):A(f.values().next().value),_()}};D(m+2);for(var U=0;c&&g.length&&U++<1e3&&a.performance.now()-m<4;){var B=g[0],z=B.work.next();z.done?g.shift():$(z.value,B.generation)}D(m+4),c&&(k||g.length||f.size||p.size)&&N()}},N=function(){c&&void 0===l&&(u="function"!=typeof a.requestAnimationFrame,l=u?a.setTimeout(F,16):a.requestAnimationFrame(F))},q=function(e){return!!v.has(e)||(v.size>=256?(E("dialog tracking"),!1):(v.add(e),!0))},$=function(e,t){var a,l,c;if("node"in e){var d=e.node,u=e.baseline,h=e.hidden;if(2!==d.type)return;var g=null!==(c=d.attributes)&&void 0!==c?c:{},f="dialog"===d.tagName||"dialog"===g.role||"alertdialog"===g.role||"true"===g["aria-modal"],p=["alert","status","log"].includes(g.role)||["polite","assertive"].includes(g["aria-live"]);if((!i||!f)&&(!n||!p||u))return;var m=r.getNode(d.id);if(!m||1!==m.nodeType||s.blocked(m))return;var y=m;if(i&&f&&q(y))if(u&&!S.has(y)){var b=!h&&("dialog"!==d.tagName||void 0!==g.open);S.set(y,{open:b,payload:{id:d.id,role:"alertdialog"===g.role?"alertdialog":"dialog",name:null,name_source:"unnamed",state:b?"open":"closed",modal:"true"===g["aria-modal"]||"modal"===g.rr_open_mode,visible:!1,cause_click_ts:null}}),b&&I.add(y)}else{var C=S.get(y);C&&u&&(C.payload.id=d.id),P(y)}n&&p&&!u&&x(y,t)}else if(n&&e.text||i&&e.dialogs){var k=r.getNode(e.id),w=1===(null==k?void 0:k.nodeType)?k:null==k?void 0:k.parentElement;if(w&&w.isConnected&&!s.blocked(w)){if(n&&e.text){var E=w.closest('[role="alert"],[role="status"],[role="log"],[aria-live="polite"],[aria-live="assertive"]');E&&x(E,t)}if(i&&e.dialogs){w.matches(mt)&&q(w)&&P(w);try{for(var M=o(v),O=M.next();!O.done;O=M.next()){f=O.value;w.contains(f)&&P(f)}}catch(e){a={error:e}}finally{try{O&&!O.done&&(l=M.return)&&l.call(M)}finally{if(a)throw a.error}}}}}},j=e.on("dom",function(e){c&&_()&&(h++,("snapshot"===e.type||e.removes.length)&&(k=!0),g.length>=128?E("replay batch queue"):g.push({work:bt(e),generation:h}),N())});return R}};var It={families:["context","recording","visibility","lifecycle"],setup:function(e){var t=[],n=e.host,i=n.document,r=n.window;if(e.enabled("context")&&t.push(e.on("snapshot",function(){return function(e){var t,n,i,r,a;if(e.canEmit("context")){var l=e.host,c=l.document,d=l.window,u={total:0,inlined:0,unreadable:0};try{for(var h=o(Array.from(c.styleSheets)),g=h.next();!g.done;g=h.next()){var v=g.value;u.total++;try{v.cssRules,!1!==l.inlineStylesheet&&u.inlined++}catch(e){u.unreadable++}}}catch(e){t={error:e}}finally{try{g&&!g.done&&(n=h.return)&&n.call(h)}finally{if(t)throw t.error}}var f="function"==typeof d.matchMedia&&d.matchMedia("(pointer:coarse)").matches,p=f&&d.innerWidth<768?"mobile":f&&d.innerWidth<1024?"tablet":"desktop",m=e.dropped();e.emit("context",s({sdk:l.sdk,mask:null!==(i=l.getPrivacy().defaultMaskLevel)&&void 0!==i?i:"medium",css:u,viewport:{w:d.innerWidth,h:d.innerHeight},device:p,language:d.navigator.language,visibility_state:"hidden"===c.visibilityState?"hidden":"visible",focused:c.hasFocus(),user_agent:d.navigator.userAgent,analytics_sdk:null!==(a=null===(r=l.getAnalyticsContext)||void 0===r?void 0:r.call(l))&&void 0!==a?a:{present:!1,autocapture:[]}},Object.keys(m).length?{caps_hit:m}:{}))}}(e)})),e.enabled("recording")&&t.push(e.on("recording",function(t){return e.emit("recording",t)})),e.enabled("visibility")){var a=function(){return"hidden"===i.visibilityState?"hidden":"visible"},l=a(),c=function(){var t=a();t!==l&&(l=t,e.emit("visibility",{state:t}))};i.addEventListener("visibilitychange",c,!0),t.push(function(){return i.removeEventListener("visibilitychange",c,!0)})}if(e.enabled("lifecycle")){var d=function(n,i,r){var s=function(t){e.emit("lifecycle",{type:"pageshow"===i&&t.persisted?"pageshow_bfcache":r})};n.addEventListener(i,s,!0),t.push(function(){return n.removeEventListener(i,s,!0)})};d(r,"pagehide","pagehide"),d(r,"pageshow","pageshow"),d(i,"freeze","freeze"),d(i,"resume","resume")}return function(){return t.forEach(function(e){return e()})}}},Ct=/^(Escape|Enter|Tab|ArrowUp|ArrowDown|ArrowLeft|ArrowRight|Home|End|PageUp|PageDown|F[1-9]|F1[0-2])$/,kt=/^[kpf]$/i,wt={families:["keys"],setup:function(e){var t=e.host.document,n=e.helpers,i=function(t){if(e.enabled("keys")&&!t.repeat&&!t.isComposing&&229!==t.keyCode&&!t.getModifierState("AltGraph")){var i=t.key;if(!Ct.test(i)){if(t.altKey||t.ctrlKey===t.metaKey||!kt.test(i))return;i=i.toUpperCase()}var r=t.composedPath().filter(function(e){return 1===e.nodeType}),s=r[0];if(s&&!r.some(function(e){return n.blocked(e)})&&!s.matches('input[type="password"], input[type="hidden"]')&&e.canEmit("keys")){var o=n.name(s),a="value"===o.source||"text"===o.source&&!!s.closest("input,textarea,select,[contenteditable]");e.emit("keys",{key:[t.ctrlKey?"Ctrl":"",t.metaKey?"Meta":"",t.altKey?"Alt":"",t.shiftKey?"Shift":"",i].filter(Boolean).join("+"),target:{id:n.id(s),role:n.role(s),name:a?null:o.name,name_source:a?"masked":o.source,states:n.states(s)}})}}},r=function(){return t.removeEventListener("keydown",i,!0)};return e.onCleanup(r),t.addEventListener("keydown",i,!0),r}},Et=65535,xt={families:["resource-error"],setup:function(e){var t,n=e.host,i=n.document,r=n.window,a=e.helpers,l=!0,c=[],d=0,u=i.fonts,h=function(){void 0!==t&&r.clearTimeout(t),t=void 0},g=function(){var t,n,i,r;h();var u=c,g=d;if(c=[],d=0,l&&e.enabled("resource-error")){var v=new Map;try{for(var f=o(u),p=f.next();!p.done;p=f.next()){var m=p.value;if(m.element.isConnected&&!a.blocked(m.element)){var y=a.container(m.element),b=s(s({rt:m.rt,count:m.count},m.path?{path:m.path}:{}),y?{container:y}:{}),S=JSON.stringify([b.rt,b.path,b.container]),I=v.get(S);I?I.count=Math.min(Et,I.count+b.count):v.set(S,b)}}}catch(e){t={error:e}}finally{try{p&&!p.done&&(n=f.return)&&n.call(f)}finally{if(t)throw t.error}}g&&e.emit("resource-error",{rt:"font",count:g});try{for(var C=o(v.values()),k=C.next();!k.done;k=C.next()){b=k.value;e.emit("resource-error",b)}}catch(e){i={error:e}}finally{try{k&&!k.done&&(r=C.return)&&r.call(C)}finally{if(i)throw i.error}}}},v=function(){"hidden"===i.visibilityState?g():void 0===t&&(t=r.setTimeout(g,500))},f=function(t){if(l&&e.enabled("resource-error")){var n=t.target;if(n&&1===n.nodeType&&!a.blocked(n)){var r,s;if("IMG"===n.tagName)r="img",s=n.currentSrc||n.getAttribute("src")||"";else if("SCRIPT"===n.tagName&&n.hasAttribute("src"))r="script",s=n.getAttribute("src")||"";else{if("LINK"!==n.tagName||!n.relList.contains("stylesheet"))return;r="css",s=n.getAttribute("href")||""}var o=function(e){if(e)try{var t=new URL(e,i.baseURI);if("http:"!==t.protocol&&"https:"!==t.protocol)return;var n=a.url(t.origin+t.pathname);return n.length<=200?n:void 0}catch(e){return}}(s),d=c.find(function(e){return e.element===n&&e.rt===r&&e.path===o});d?d.count=Math.min(Et,d.count+1):(c.length>=100&&g(),c.push({element:n,rt:r,path:o,count:1})),v()}}},p=function(t){if(l&&e.enabled("resource-error")){var n=t.fontfaces;(null==n?void 0:n.length)&&(d=Math.min(Et,d+n.length),v())}},m=function(){"hidden"===i.visibilityState&&g()},y=function(){l=!1,h(),c=[],d=0,i.removeEventListener("error",f,!0),i.removeEventListener("visibilitychange",m,!0),r.removeEventListener("pagehide",g,!0),null==u||u.removeEventListener("loadingerror",p)};return e.onCleanup(y),i.addEventListener("error",f,!0),i.addEventListener("visibilitychange",m,!0),r.addEventListener("pagehide",g,!0),null==u||u.addEventListener("loadingerror",p),y}},Pt=new Set(["[Amplitude] Dead Click","[Amplitude] Rage Click","[Amplitude] Error Click","[Amplitude] Thrashed Cursor"]),Mt=["[Amplitude] Clicks","[Amplitude] Begin Time","[Amplitude] End Time"],Ot="[Amplitude] Element Text",Tt="[Amplitude] Element Tag",Rt="[Amplitude] Page Path",_t={families:["amp-event"],setup:function(e){if(!e.enabled("amp-event"))return function(){};var t,n=e.subscribe(function(e){"click"===e.name&&(t={timestamp:e.timestamp,id:e.payload.id,name:e.payload.name})}),i=e.on("analytics",function(n){var i,r;if(e.enabled("amp-event")&&Pt.has(n.eventType)){var s=e.helpers,a=n.element;if((!a||!s.blocked(a))&&e.canEmit("amp-event")){var l=n.properties,c={},d=null,u=l[Ot];if("string"==typeof u){if(a){var h=s.text(a),g=s.text(a,u);null!==h&&h===g&&(d=g)}c[Ot]=d}var v=l[Tt];a?c[Tt]=a.tagName.toLowerCase():"string"==typeof v&&/^[a-z][a-z0-9-]{0,59}$/i.test(v)&&(c[Tt]=v.toLowerCase());try{for(var f=o(Mt),p=f.next();!p.done;p=f.next()){var m=p.value,y=l[m];"number"==typeof y&&Number.isFinite(y)&&(c[m]=y)}}catch(e){i={error:e}}finally{try{p&&!p.done&&(r=f.return)&&r.call(f)}finally{if(i)throw i.error}}var b=l[Rt];"string"==typeof b&&(c[Rt]=s.url(b));var S=t?e.now()-t.timestamp:1/0,I=null!==d&&t&&S>=0&&S<=3e3&&t.name===d?t.id:null;e.emit("amp-event",{event_type:n.eventType,insert_id:"string"==typeof n.insertId?n.insertId:null,id:I,props:c})}}});return function(){i(),n(),t=void 0}}},At=[pt,St,It,{families:["navigation"],setup:function(e){return e.on("url",function(t){var n=t.url,i=t.timestamp;n.trim()&&e.canEmit("navigation")&&e.emit("navigation",{url:e.helpers.url(n)},i)})}},_t,wt,xt];function Lt(e,t,n){return void 0===n&&(n=At),function(e,t,n){var i,r,a=lt(e),l=!1,c=!1,d=!1,u=[],h={},g={},v=new Map,f=new Set,p=null!==(i=t.now)&&void 0!==i?i:Date.now,m=function(e){var n;try{null===(n=t.onError)||void 0===n||n.call(t,e)}catch(e){}},y=function(e){try{e()}catch(e){m(e)}},b=function(e){var t;return l&&!1!==(null===(t=a.families)||void 0===t?void 0:t[e])},S=function(e){var t;return b(e)&&(null!==(t=h[e])&&void 0!==t?t:0)<at[e]},I=function(e){var t;return!(!b(e)||!S(e)&&(g[e]=(null!==(t=g[e])&&void 0!==t?t:0)+1,1))},C={host:t,helpers:it(t),now:p,enabled:b,canEmit:I,hasCapacity:S,dropped:function(){return s({},g)},hasSnapshot:function(){return d},emit:function(e,n,i){var r,o,a;if(void 0===i&&(i=p()),!I(e))return!1;try{a=null===(r=t.getIdentity)||void 0===r?void 0:r.call(t)}catch(e){m(e)}null!=a||(a=ot(t.document,t.window));var l={name:e,payload:s(s({},n),{v:1,tab_id:a.tab_id,document_id:a.document_id}),timestamp:i};h[e]=(null!==(o=h[e])&&void 0!==o?o:0)+1;try{t.emit(l)}catch(e){return m(e),!1}return"context"===e&&(g={}),f.forEach(function(e){return y(function(){return e(l)})}),!0},on:function(e,t){var n=v.get(e);n||(n=new Set,v.set(e,n));var i=function(e){return y(function(){return t(e)})};n.add(i);var r=n;return function(){r.delete(i)}},subscribe:function(e){return f.add(e),function(){f.delete(e)}}},k=function(){l=!1;var e=u;u=[],e.reverse().forEach(function(e){return y(e)}),v.clear(),f.clear()},w=function(){var e,i,d,h;if(!l&&c&&a.enabled){var g=null!==(d=a.sampleRate)&&void 0!==d?d:1;if(!(!Number.isFinite(g)||g<=0||g>1||(void 0===r&&(r=(null!==(h=t.random)&&void 0!==h?h:Math.random)()),r>=g))){l=!0;var v=function(e){if(e.families.some(b)){var t=[],n=s(s({},C),{onCleanup:function(e){t.push(e)},on:function(e,n){var i=C.on(e,n);return t.push(i),i},subscribe:function(e){var n=C.subscribe(e);return t.push(n),n}}),i=function(){t.splice(0).reverse().forEach(function(e){return y(e)})};try{t.push(e.setup(n)),u.push(i)}catch(e){i(),m(e)}}};try{for(var f=o(n),p=f.next();!p.done;p=f.next())v(p.value)}catch(t){e={error:t}}finally{try{p&&!p.done&&(i=f.return)&&i.call(f)}finally{if(e)throw e.error}}}}};return{isActive:function(){return l},start:function(){c=!0,w()},stop:function(){c=!1,d=!1,k()},updateConfig:function(e){k(),a=lt(e),w()},resetSession:function(){k(),r=void 0,d=!1,h={},g={},w()},notify:function(e,t){var n,i,r;"snapshot"===e&&(d=!0),"snapshot"!==e&&"navigation"!==e&&"url"!==e||null===(i=(n=C.helpers).invalidateHeading)||void 0===i||i.call(n),l&&(null===(r=v.get(e))||void 0===r||r.forEach(function(e){return e(t)}))}}}(e,t,n)}var Ft=(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))(Ft||{}),Nt=(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))(Nt||{}),qt=(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))(qt||{});class $t{constructor(e){this.ready=!1,this.firstSnapshot=!1,this.pendingSnapshots=0,this.pendingEvents=[],this.startSignal={state:"start",reason:"init"},this.resumeReason="focus",this.config={enabled:!1},this.capture=Lt(this.config,e)}prepare(e,t){const n=this.sessionId!==t,i=void 0===this.sessionId;this.config=e,this.capture.updateConfig(e),n&&this.capture.resetSession(),this.startSignal={state:n?"start":"resume",reason:i?"init":n?"new_session":this.resumeReason},this.sessionId=t,this.ready=!1,this.firstSnapshot=!1,this.pendingSnapshots=0,this.pendingEvents=[]}recordingReady(){if(!this.config.enabled||this.ready)return;this.ready=!0,this.capture.start();const e=this.pendingEvents;this.pendingEvents=[];for(const t of e)this.event(t);const t=this.pendingSnapshots;this.pendingSnapshots=0;for(let e=0;e<t;e++)this.snapshot()}event(e){if(!this.config.enabled)return;const t=e.type===Ft.FullSnapshot,n=e.type===Ft.IncrementalSnapshot&&e.data.source===Nt.Mutation,i=e.type===Ft.Plugin&&"amplitude/url-tracking@1"===e.data.plugin?e.data.payload:void 0,r=i&&"object"==typeof i&&"url-change-event"===i.type&&"string"==typeof i.href?i.href:void 0;(t||n||void 0!==r)&&(this.ready?this.capture.isActive()&&(void 0!==r?this.capture.notify("url",{url:r,timestamp:e.timestamp}):e.type===Ft.FullSnapshot?(this.capture.notify("dom",{type:"snapshot",node:e.data.node}),this.snapshot()):e.type===Ft.IncrementalSnapshot&&e.data.source===Nt.Mutation&&this.capture.notify("dom",Object.assign(Object.assign({},e.data),{type:"mutation"}))):this.pendingEvents.length<128&&this.pendingEvents.push(e))}click(e){this.ready&&this.capture.notify("click",e)}snapshot(){this.config.enabled&&(this.ready?(this.firstSnapshot||(this.firstSnapshot=!0,this.capture.notify("recording",this.startSignal)),this.capture.notify("snapshot",void 0)):this.pendingSnapshots++)}stop(e="targeting",t="stop"){const n=this.ready&&this.firstSnapshot;this.ready=!1,this.firstSnapshot=!1,n&&(this.resumeReason=e,this.capture.notify("recording",{state:t,reason:e})),this.capture.stop(),this.pendingEvents=[],this.ready=!1,this.pendingSnapshots=0}}const jt="AMP_semantic_tab_v1",Dt=new WeakMap,Ut=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;let Bt,zt,Wt;function Kt(e,t){if(Wt=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};Bt=Object.assign(Object.assign({},n),t),zt=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Bt.root,n);let i=Ht(e,"all",()=>Ht(e,"two",()=>Ht(e,"one",()=>Ht(e,"none"))));if(i){const t=cn(dn(i,e));return t.length>0&&(i=t[0]),Jt(i)}throw new Error("Selector was not found.")}function Ht(e,t,n){let i=null,r=[],s=e,o=0;for(;s;){const e=(new Date).getTime()-Wt.getTime();if(void 0!==Bt.timeoutMs&&e>Bt.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=on(Xt(s))||on(...Vt(s))||on(...Yt(s))||on(en(s))||[tn()];const l=nn(s);if("all"==t)l&&(a=a.concat(a.filter(sn).map(e=>rn(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(sn).map(e=>rn(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&sn(e)&&(a=[rn(e,l)])}else"none"==t&&(a=[tn()],l&&(a=[rn(a[0],l)]));for(let e of a)e.level=o;if(r.push(a),r.length>=Bt.seedMinLength&&(i=Gt(r,n),i))break;s=s.parentElement,o++}return i||(i=Gt(r,n)),!i&&n?n():i}function Gt(e,t){const n=cn(ln(e));if(n.length>Bt.threshold)return t?t():null;for(let e of n)if(Zt(e))return e;return null}function Jt(e){let t=e[0],n=t.name;for(let i=1;i<e.length;i++){const r=e[i].level||0;n=t.level===r-1?`${e[i].name} > ${n}`:`${e[i].name} ${n}`,t=e[i]}return n}function Qt(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function Zt(e){const t=Jt(e);switch(zt.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function Xt(e){const t=e.getAttribute("id");return t&&Bt.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function Vt(e){const t=Array.from(e.attributes).filter(e=>Bt.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function Yt(e){return Array.from(e.classList).filter(Bt.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function en(e){const t=e.tagName.toLowerCase();return Bt.tagName(t)?{name:t,penalty:2}:null}function tn(){return{name:"*",penalty:3}}function nn(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==e);)n=n.nextSibling;return i}function rn(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function sn(e){return"html"!==e.name&&!e.name.startsWith("#")}function on(...e){const t=e.filter(an);return t.length>0?t:null}function an(e){return null!=e}function*ln(e,t=[]){if(e.length>0)for(let n of e[0])yield*ln(e.slice(1,e.length),t.concat(n));else yield t}function cn(e){return[...e].sort((e,t)=>Qt(e)-Qt(t))}function*dn(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>Bt.optimizedMinLength)for(let i=1;i<e.length-1;i++){if(n.counter>Bt.maxNumberOfTries)return;n.counter+=1;const r=[...e];r.splice(i,1);const s=Jt(r);if(n.visited.has(s))return;Zt(r)&&un(r,t)&&(yield r,n.visited.set(s,!0),yield*dn(r,t,n))}}function un(e,t){return zt.querySelector(Jt(e))===t}const hn=(e,t)=>{const n=document.createDocumentFragment();return function(e,t,n){var i,r,a=s({},e);try{for(var l=o(["blockSelector","maskSelector","unmaskSelector"]),c=l.next();!c.done;c=l.next()){var d=c.value,u=e[d],h=("string"==typeof u?[u]:null!=u?u:[]).filter(function(e){try{return t(e),!0}catch(t){if(!n)throw new Error("Invalid privacy selector: ".concat(e));return n(e),!1}});a[d]=h.length?h:void 0}}catch(e){i={error:e}}finally{try{c&&!c.done&&(r=l.return)&&r.call(l)}finally{if(i)throw i.error}}return a}(e,e=>{n.querySelector(e)},e=>{t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`)})};class gn{constructor(e,t){this.localConfig=t,this.remoteConfigClient=e}generateJoinedConfig(){var e,t,n,r,s,o,a,l;return i(this,void 0,void 0,function*(){const i=Object.assign({},this.localConfig);let c;i.optOut=this.localConfig.optOut,i.captureEnabled=!0;try{yield new Promise((e,t)=>{this.remoteConfigClient.subscribe("configs.sessionReplay",{timeout:1500},(n,r)=>{var s;if(this.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${r}:`,JSON.stringify(n,null,2)),!n)return void t(new Error("No remote config received"));const o=n,a=o.sr_sampling_config,l=o.sr_privacy_config,d=o.sr_targeting_config,u=o.sr_semantic_config,h=null===(s=i.interactionConfig)||void 0===s?void 0:s.ugcFilterRules;i.interactionConfig=o.sr_interaction_config,i.interactionConfig&&h&&(i.interactionConfig.ugcFilterRules=h),i.loggingConfig=o.sr_logging_config,(a||l||d||u)&&(c={},u&&(c.sr_semantic_config=u),a&&(c.sr_sampling_config=a),l&&(c.sr_privacy_config=l),d&&(c.sr_targeting_config=d)),e()})})}catch(e){return this.localConfig.loggerProvider.error("Failed to generate joined config: ",e),i.captureEnabled=!1,{localConfig:this.localConfig,joinedConfig:i,remoteConfig:void 0}}if(!c)return{localConfig:this.localConfig,joinedConfig:i,remoteConfig:c};const{sr_sampling_config:d,sr_privacy_config:u,sr_targeting_config:h,sr_semantic_config:g}=c;if(g&&(i.semanticCapture=Object.assign(Object.assign(Object.assign({enabled:!1},i.semanticCapture),g),{families:Object.assign(Object.assign({},null===(e=i.semanticCapture)||void 0===e?void 0:e.families),g.families)})),d&&Object.keys(d).length>0?(Object.prototype.hasOwnProperty.call(d,"capture_enabled")?i.captureEnabled=d.capture_enabled:i.captureEnabled=!1,Object.prototype.hasOwnProperty.call(d,"sample_rate")&&(i.sampleRate=d.sample_rate),Object.prototype.hasOwnProperty.call(d,"min_session_duration_ms")&&(i.minSessionDurationMs=this.sanitizeMinSessionDurationMs(d.min_session_duration_ms))):(i.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),u){const e=null!==(t=i.privacyConfig)&&void 0!==t?t:{},c={defaultMaskLevel:null!==(r=null!==(n=u.defaultMaskLevel)&&void 0!==n?n:e.defaultMaskLevel)&&void 0!==r?r:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:[...new Set([...null!==(s=e.maskAttributes)&&void 0!==s?s:[],...null!==(o=u.maskAttributes)&&void 0!==o?o:[]])],urlMaskLevels:[...null!==(a=u.urlMaskLevels)&&void 0!==a?a:[],...null!==(l=e.urlMaskLevels)&&void 0!==l?l:[]]},d=e=>{var t,n,i;const r={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])r[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])r[t]="mask";for(const t of null!==(i=e.unmaskSelector)&&void 0!==i?i:[])r[t]="unmask";return r},h=Object.assign(Object.assign({},d(e)),d(u));for(const[e,t]of Object.entries(h))"mask"===t?c.maskSelector.push(e):"block"===t?c.blockSelector.push(e):"unmask"===t&&c.unmaskSelector.push(e);i.privacyConfig=hn(c,this.localConfig.loggerProvider)}return h&&Object.keys(h).length>0&&(i.targetingConfig=h),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:De(i)},null,2)),{localConfig:this.localConfig,joinedConfig:i,remoteConfig:c}})}sanitizeMinSessionDurationMs(e){if("number"==typeof e&&Number.isFinite(e)){if(!(e<0))return e>vn?(this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value ${e} exceeds ${vn}ms ceiling; clamping.`),vn):e;this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value is negative (${e}); ignoring.`)}else this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value is not a finite number (got ${String(e)}); ignoring.`)}}const vn=6e4;function fn(e){const t=e.length;let n=0;for(;n<t&&!(e.charCodeAt(n)>127);n++);if(n===t)return t;let i=n;for(;n<t;n++){const r=e.charCodeAt(n);if(r<=127)i++;else if(r<=2047)i+=2;else if(r>=55296&&r<=56319){const r=n+1<t?e.charCodeAt(n+1):NaN;r>=56320&&r<=57343?(i+=4,n++):i+=3}else i+=3}return i}function pn(e){let t=0;for(let n=0;n<e.length;n++)t+=fn(e[n]);return t}function mn(e,t){if(3*e.length<=t)return;const n=fn(e);return n>t?n:void 0}function yn(e,t){t<0&&(t=0);const n=e.length;let i=0,r=0;for(;r<n;r++){const s=e.charCodeAt(r);let o=1,a=1;if(s<=127)o=1;else if(s<=2047)o=2;else if(s>=55296&&s<=56319){const t=r+1<n?e.charCodeAt(r+1):NaN;t>=56320&&t<=57343?(o=4,a=2):o=3}else o=3;if(i+o>t)break;i+=o,2===a&&r++}return r>=n?{value:e,truncated:!1}:{value:e.slice(0,r),truncated:!0}}function bn(e){if(e.type!==Ft.IncrementalSnapshot)return!1;const t=e.data;return t.source===Nt.Mutation&&!t.isAttachIframe}function Sn(e){const t={};for(const n of e)for(const e of Object.keys(n))t[e]=n[e];return t}function In(e){const t=new Map;if(e.forEach((e,n)=>{if(e.attributes&&"style"in e.attributes){const i=t.get(e.id);i?i.push(n):t.set(e.id,[n])}}),0===t.size)return e;const n=t=>e[t].attributes.style,i=new Set,r=new Map;for(const e of t.values()){if(1===e.length)continue;let t=-1;e.forEach((e,i)=>{var r;("object"!=typeof(r=n(e))||null===r)&&(t=i)});const s=[];if(e.forEach((e,n)=>{n!==t&&(i.add(e),n>t&&s.push(e))}),s.length>0){const e=s[s.length-1],t=Sn(s.map(e=>n(e)));i.delete(e),r.set(e,t)}}if(0===i.size&&0===r.size)return e;const s=[];return e.forEach((e,t)=>{const n=r.get(t);if(void 0!==n)return void s.push(Object.assign(Object.assign({},e),{attributes:Object.assign(Object.assign({},e.attributes),{style:n})}));if(!i.has(t))return void s.push(e);const o=Object.assign({},e.attributes);delete o.style,Object.keys(o).length>0&&s.push(Object.assign(Object.assign({},e),{attributes:o}))}),s}function Cn(e){const t=e[0],n=new Map,i=new Map,r=new Map,s=new Map,o=new Map;e.forEach((e,t)=>{const a=e.data;for(const e of a.adds)n.has(e.node.id)||n.set(e.node.id,t),i.set(e.node.id,t),o.set(e.node.id,e.parentId);for(const e of a.removes)r.has(e.id)||r.set(e.id,t),s.set(e.id,t)});const a=new Set,l=new Set;for(const[e,t]of n){const n=r.get(e);if(void 0===n)continue;i.get(e)>=s.get(e)||(t<n?a.add(e):n<t&&l.add(e))}const c=new Set;if(a.size>0||l.size>0){let e=!0;for(;e;){e=!1;for(const[t,i]of o)if(!a.has(t)&&!l.has(t)&&!c.has(t)&&(a.has(i)||l.has(i)||c.has(i))){const i=r.get(t),s=n.get(t);void 0!==i&&void 0!==s&&i<s?l.add(t):void 0!==i&&void 0!==s&&i===s?c.add(t):a.add(t),e=!0}}}const d=a.size>0||l.size>0||c.size>0,u=[];e.forEach((e,t)=>{for(const i of e.data.removes)a.has(i.id)||l.has(i.id)&&t>=n.get(i.id)||c.has(i.id)&&(a.has(i.parentId)||l.has(i.parentId)||c.has(i.parentId))||u.push(i)});const h=e.flatMap(e=>e.data.adds),g=e.flatMap(e=>e.data.texts),v=e.flatMap(e=>e.data.attributes),f=d?v.filter(e=>!a.has(e.id)&&!l.has(e.id)&&!c.has(e.id)):v,p={source:Nt.Mutation,removes:u,adds:d?h.filter(e=>!a.has(e.node.id)&&!l.has(e.node.id)&&!c.has(e.node.id)):h,texts:d?g.filter(e=>!a.has(e.id)&&!l.has(e.id)&&!c.has(e.id)):g,attributes:In(f)};return Object.assign(Object.assign({},t),{data:p})}function kn(e){if(e.length<=1)return e;const t=[];let n=0;for(;n<e.length;){if(!bn(e[n])){t.push(e[n]),n++;continue}let i=n+1;for(;i<e.length&&bn(e[i]);)i++;t.push(i>n+1?Cn(e.slice(n,i)):e[n]),n=i}return t}class wn{constructor(e,t,n,i,r){var s;this.taskQueue=[],this.pendingQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const{type:t,timestamp:n,delay:i,data:r}=e;return null!=i?JSON.stringify({type:t,timestamp:n,delay:i,data:r}):JSON.stringify({type:t,timestamp:n,data:r})},this.addCompressedEventToManager=(e,t)=>{var n;const i=mn(e,null!==(n=this.config.maxSingleEventSizeBytes)&&void 0!==n?n:pe);void 0===i?this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId}):this.config.loggerProvider.warn(`Session replay event dropped: serialized size ${Math.round(i/1024)} KB exceeds maximum allowed event size. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.`)},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?this.worker.postMessage(JSON.stringify({event:e,sessionId:t})):this.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.flushQueue=()=>{for(this.pendingQueue.length>0&&this.taskQueue.push(...this.mergeMutationTasks(this.pendingQueue.splice(0)));this.taskQueue.length>0;){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e,i=this.compressEvent(t);this.addCompressedEventToManager(i,n)}}this.isProcessing=!1},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const o=f();if(this.canUseIdleCallback=o&&"requestIdleCallback"in o,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(s=t.performanceConfig)||void 0===s?void 0:s.timeout)||2e3,this.onFullSnapshotProcessed=r,i){t.loggerProvider.log("Enabling web worker for compression");try{const e=new Blob([i],{type:"application/javascript"}),n=URL.createObjectURL(e),r=new Worker(n);r.onerror=e=>{e.preventDefault(),t.loggerProvider.error(`Worker failed, falling back to non-worker compression: ${e.message} (${e.filename}:${e.lineno})`),r.terminate(),this.worker=void 0},r.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=r}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}))}enqueueEvent(e,t){var n,i;if(e.type===Ft.FullSnapshot){if(this.config.loggerProvider.debug("Processing full snapshot immediately."),this.taskQueue.length>0||this.pendingQueue.length>0){const e=[...this.taskQueue.splice(0),...this.mergeMutationTasks(this.pendingQueue.splice(0))];for(const t of e){const e=this.compressEvent(t.event);this.addCompressedEventToManager(e,t.sessionId)}this.isProcessing=!1}const i=this.compressEvent(e);return this.addCompressedEventToManager(i,t),void(null===(n=this.onFullSnapshotProcessed)||void 0===n||n.call(this))}this.canUseIdleCallback&&(null===(i=this.config.performanceConfig)||void 0===i?void 0:i.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))}processQueue(e){for(this.pendingQueue.length>0&&this.taskQueue.push(...this.mergeMutationTasks(this.pendingQueue.splice(0)));this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0||this.pendingQueue.length>0?requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1}mergeMutationTasks(e){var t;if(!1===(null===(t=this.config.performanceConfig)||void 0===t?void 0:t.mergeMutations))return e;if(e.length<=1)return e;const n=[];let i=0;for(;i<e.length;){const t=e[i].sessionId;let r=i+1;for(;r<e.length&&e[r].sessionId===t;)r++;const s=kn(e.slice(i,r).map(e=>e.event));for(const e of s)n.push({event:e,sessionId:t});i=r}return n}}const En="Session replay event batch rejected due to exceeded retry count",xn="Failed to store session replay events in IndexedDB",Pn="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",Mn="1.52.0-codexsemantic-review-integration.0";class On{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n,workerScript:i,enableTransportCompression:r,sendTimeoutMs:s,handleSendEvents:o}){if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.timedOutWorkerRequests=new Map,this.flushPauseUntilMs=0,this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,this.mergeLogFiredThisPause=!1,this.killedSessions=new Set,this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e,this.enableTransportCompression=null==r||r,this.sendTimeoutMs=null!=s?s:1e4,this.handleSendEvents=o,i)try{const e=new Blob([i],{type:"application/javascript"}),n=URL.createObjectURL(e),r=new Worker(n);r.onerror=e=>{e.preventDefault(),t.error(`Track destination worker failed, falling back to main-thread sending: ${e.message} (${e.filename}:${e.lineno})`),r.terminate(),this.worker=void 0;for(const[,n]of this.pendingWorkerRequests)n.timeout&&clearTimeout(n.timeout),t.warn(`Session replay event send failed due to worker crash: ${e.message}`),n.resolve();this.pendingWorkerRequests.clear(),this.timedOutWorkerRequests.clear()},r.onmessage=e=>{const n=e.data;if("log"===n.type)t.log(n.message);else if("warn"===n.type)t.warn(n.message);else if("payload_too_large"===n.type){const e=this.pendingWorkerRequests.get(n.id);if(e)e.timeout&&clearTimeout(e.timeout),this.handlePayloadTooLargeResponse(e.context,n.isWaf),e.resolve(),this.pendingWorkerRequests.delete(n.id);else{const e=this.timedOutWorkerRequests.get(n.id);e&&(this.timedOutWorkerRequests.delete(n.id),this.handlePayloadTooLargeResponse(e,n.isWaf))}}else if("complete"===n.type){const e=this.pendingWorkerRequests.get(n.id);if(e)e.timeout&&clearTimeout(e.timeout),void 0!==n.skipCode&&this.applyServerDirective(e.context.sessionId,n.skipCode),this.completeRequest({context:e.context}),e.resolve(),this.pendingWorkerRequests.delete(n.id);else{const e=this.timedOutWorkerRequests.get(n.id);e&&(this.timedOutWorkerRequests.delete(n.id),void 0!==n.skipCode&&this.applyServerDirective(e.sessionId,n.skipCode),this.completeRequest({context:e}))}}else"fetch-request"===n.type&&this.handleDelegatedFetch(r,n).catch(e=>{t.warn("Failed to handle delegated session replay fetch:",e)})},this.worker=r}catch(e){t.error("Failed to create track destination worker, falling back to main-thread sending:",e)}}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}markCoalesceNextFlush(){this.coalesceNextFlush=!0,this.schedule(0)}sendBeacon({events:e,sessionId:t,deviceId:n,apiKey:i,serverZone:r}){var s,o;const a=e=>fn(e);let l=e,c=JSON.stringify({version:2,events:l});if(a(c)>65536){let t=0,n=l.length;for(;t<n;){const e=Math.floor((t+n+1)/2);a(JSON.stringify({version:2,events:l.slice(0,e)}))<=65536?t=e:n=e-1}l=l.slice(0,t),c=JSON.stringify({version:2,events:l}),this.loggerProvider.warn(`sendBeacon payload exceeded 64 KB limit, trimmed from ${e.length} to ${l.length} events`)}if(0===l.length)return;if(this.handleSendEvents){const e=new URLSearchParams({device_id:n,session_id:String(t),type:"replay"}),s=`${Ne(r,this.trackServerUrl)}?${e.toString()}`,o={"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${i}`};this.loggerProvider.debug(`Routing session replay exit batch (${l.length} events) through custom transport for session id ${t}.`);try{this.handleSendEvents({url:s,method:"POST",headers:o,body:c,keepalive:!0}).catch(e=>{this.loggerProvider.warn("Custom transport failed to send session replay exit batch:",e)})}catch(e){this.loggerProvider.warn("Custom transport threw while sending session replay exit batch:",e)}return}const d=new URLSearchParams({device_id:n,session_id:String(t),type:"replay",api_key:i}),u=`${Ne(r,this.trackServerUrl)}?${d.toString()}`,h=f();try{const e=new Blob([c],{type:"application/json"});!1===(null===(o=null===(s=null==h?void 0:h.navigator)||void 0===s?void 0:s.sendBeacon)||void 0===o?void 0:o.call(s,u,e))&&this.loggerProvider.warn("sendBeacon failed to queue session replay payload")}catch(e){}}addToQueue(...e){e.filter(e=>this.killedSessions.has(e.sessionId)?(this.completeRequest({context:e,err:Pn}),!1):e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:En}),!1)).forEach(e=>{this.queue=this.queue.concat(e),this.schedule(0)})}schedule(e){if(this.scheduled)return;const t=this.flushPauseUntilMs-Date.now(),n=t>e?t:e;t>0&&(this.mergeOnNextFlush=!0),this.scheduled=setTimeout(()=>{this.flush(!0).then(()=>{this.queue.length>0&&this.schedule(e)})},n)}flush(e=!1){return i(this,void 0,void 0,function*(){let t=this.queue;this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),this.mergeOnNextFlush?(this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,t=this.mergeQueueAfterThrottle(t)):this.coalesceNextFlush&&(this.coalesceNextFlush=!1,t=this.mergeDrainBacklog(t));for(const n of t)yield this.send(n,e)})}mergeQueueAfterThrottle(e){const t=this.coalesceByIdentity(e);return t.length<e.length&&!this.mergeLogFiredThisPause&&(this.mergeLogFiredThisPause=!0,this.loggerProvider.log(`Session replay throttle pause ended; merged ${e.length} queued batches into ${t.length} request(s)`)),t}mergeDrainBacklog(e){const t=this.coalesceByIdentity(e);return t.length<e.length&&this.loggerProvider.log(`Session replay coalesced ${e.length} persisted page-load backlog batches into ${t.length} request(s)`),t}coalesceByIdentity(e){var t,n,r,s,o,a,l;if(e.length<=1)return e;const c=new Map;for(const i of e){const e=[i.sessionId,null!==(t=i.deviceId)&&void 0!==t?t:"",null!==(n=i.apiKey)&&void 0!==n?n:"",i.type,null!==(r=i.serverZone)&&void 0!==r?r:"",i.sampleRate,null!==(o=null===(s=i.version)||void 0===s?void 0:s.type)&&void 0!==o?o:"",null!==(l=null===(a=i.version)||void 0===a?void 0:a.version)&&void 0!==l?l:""].join("|"),d=c.get(e);d?d.push(i):c.set(e,[i])}const d=[];for(const e of c.values()){if(1===e.length){d.push(e[0]);continue}let t=null,n=0;const r=()=>{t&&d.push(t),t=null,n=0};for(const s of e){const e=pn(s.events);if(null===t){t=Object.assign(Object.assign({},s),{events:[...s.events],attempts:0}),n=e;continue}if(n+e>4e6){r(),t=Object.assign(Object.assign({},s),{events:[...s.events],attempts:0}),n=e;continue}const o=t.onComplete,a=s.onComplete;t.events=t.events.concat(s.events),n+=e,t.onComplete=()=>i(this,void 0,void 0,function*(){yield Promise.allSettled([o(),a()])})}r()}return d}send(e,t=!0){return i(this,void 0,void 0,function*(){if(this.killedSessions.has(e.sessionId))return this.completeRequest({context:e,err:Pn});const n=e.apiKey;if(!n)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const i=e.deviceId;if(!i)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const r=this.payloadBatcher({version:1,events:e.events});if(0===r.events.length)return void this.completeRequest({context:e});const{worker:s}=this;return s?this.sendViaWorker(s,e,r,t):this.sendOnMainThread(n,i,e,r,t)})}sendViaWorker(e,t,n,r){return i(this,void 0,void 0,function*(){const i=""+ ++this.sendIdCounter;return new Promise(s=>{var o;const a=this.sendTimeoutMs>0?setTimeout(()=>{const e=this.pendingWorkerRequests.get(i);e&&(this.pendingWorkerRequests.delete(i),this.rememberTimedOutRequest(i,e.context),this.loggerProvider.warn(`Session replay worker send timed out after ${this.sendTimeoutMs}ms; leaving events for retry`),e.resolve())},this.sendTimeoutMs):void 0;this.pendingWorkerRequests.set(i,{context:t,resolve:s,timeout:a}),e.postMessage({type:"send",id:i,payload:n,useRetry:r,useCustomTransport:!!this.handleSendEvents,context:{apiKey:t.apiKey,deviceId:t.deviceId,sessionId:t.sessionId,events:t.events,eventType:t.type,flushMaxRetries:null!==(o=t.flushMaxRetries)&&void 0!==o?o:0,sampleRate:t.sampleRate,serverZone:t.serverZone,trackServerUrl:this.trackServerUrl,version:t.version,currentUrl:qe(),sdkVersion:Mn,enableTransportCompression:this.enableTransportCompression,sendTimeoutMs:this.sendTimeoutMs}})})})}rememberTimedOutRequest(e,t){if(this.timedOutWorkerRequests.set(e,t),this.timedOutWorkerRequests.size>256)for(const e of this.timedOutWorkerRequests.keys()){this.timedOutWorkerRequests.delete(e);break}}handleDelegatedFetch(e,t){var n,r,s;return i(this,void 0,void 0,function*(){const{requestId:i,url:o,method:a,headers:l,body:c,keepalive:d}=t;try{let t;this.handleSendEvents?t=yield this.handleSendEvents({url:o,method:a,headers:l,body:c,keepalive:d}):(this.loggerProvider.warn("Delegated session replay fetch received without a custom transport configured; falling back to built-in fetch."),t=yield fetch(o,{method:a,headers:l,body:c,keepalive:d}));const u=t.status;let h=null,g="";if(u>=200&&u<300&&(h=null!==(s=null===(r=null===(n=t.headers)||void 0===n?void 0:n.get)||void 0===r?void 0:r.call(n,Ie))&&void 0!==s?s:null),413===u)try{g=yield t.text()}catch(e){}this.loggerProvider.debug(`Delegated session replay fetch (request ${i}) returned status ${u}.`),e.postMessage({type:"fetch-response",requestId:i,status:u,skipHeader:h,body:g})}catch(t){this.loggerProvider.debug(`Delegated session replay fetch (request ${i}) failed:`,t),e.postMessage({type:"fetch-response",requestId:i,status:0,skipHeader:null,body:String(t),error:!0})}})}sendOnMainThread(e,t,n,r,s){var o,a,l,c,d,u,h;return i(this,void 0,void 0,function*(){const g=qe(),v=Mn,p=n.sampleRate,m=new URLSearchParams({device_id:t,session_id:`${n.sessionId}`,type:`${n.type}`}),y=`${null!==(a=null===(o=n.version)||void 0===o?void 0:o.type)&&void 0!==a?a:"standalone"}/${null!==(c=null===(l=n.version)||void 0===l?void 0:l.version)&&void 0!==c?c:v}`;try{const t=JSON.stringify(r),o=f(),a=this.enableTransportCompression&&o&&"CompressionStream"in o?yield function(e,t){return i(this,void 0,void 0,function*(){try{const n=new(0,t.CompressionStream)("gzip"),r=n.writable.getWriter(),s=n.readable.getReader(),o=[],a=(()=>i(this,void 0,void 0,function*(){for(;;){const{done:e,value:t}=yield s.read();if(e)break;o.push(t)}}))();yield r.write((new TextEncoder).encode(e)),yield r.close(),yield a;const l=o.reduce((e,t)=>e+t.length,0),c=new Uint8Array(l);let d=0;for(const e of o)c.set(e,d),d+=e.length;return c}catch(e){return null}})}(t,o):null,l=a?a.byteLength:fn(t),c=new AbortController,I=Object.assign({"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${e}`,"X-Client-Version":v,"X-Client-Library":y,"X-Client-Url":g.substring(0,1e3),"X-Client-Sample-Rate":`${p}`,"X-Sampling-Hash-Alg":"xxhash32"},a?{"Content-Encoding":"gzip"}:{}),C=null!=a?a:t,k=l<=65536,w={headers:I,body:C,method:"POST",keepalive:k,signal:c.signal},E=`${Ne(n.serverZone,this.trackServerUrl)}?${m.toString()}`;if(0===r.events.length)return void this.completeRequest({context:n});const x=this.sendTimeoutMs>0?setTimeout(()=>{c.abort()},this.sendTimeoutMs):void 0;let P;try{P=this.handleSendEvents?yield(b=this.handleSendEvents({url:E,method:"POST",headers:I,body:C,keepalive:k}),S=c.signal,new Promise((e,t)=>{const n=()=>{const e=new Error("Custom session replay transport aborted by send timeout");e.name="AbortError",t(e)};S.addEventListener("abort",n,{once:!0}),b.then(t=>{S.removeEventListener("abort",n),e(t)},e=>{S.removeEventListener("abort",n),t(e)})})):yield fetch(E,w)}finally{x&&clearTimeout(x)}if(null===P)return void this.completeRequest({context:n,err:"Unexpected error occurred"});if(P.status>=200&&P.status<300){const e=null!==(h=null===(u=null===(d=P.headers)||void 0===d?void 0:d.get)||void 0===u?void 0:u.call(d,Ie))&&void 0!==h?h:null;this.applyServerDirective(n.sessionId,e)}if(s){let e="";if(413===P.status)try{e=yield P.text()}catch(e){}yield this.handleReponse(P.status,n,e)}else{let e="";try{e=JSON.stringify(P.body,null,2)}catch(e){}this.completeRequest({context:n,success:`${P.status}: ${e}`})}}catch(e){!!e&&"object"==typeof e&&"AbortError"===e.name&&s?yield this.handleOtherResponse(n):this.completeRequest({context:n,err:e})}var b,S})}handleReponse(e,t,n=""){return i(this,void 0,void 0,function*(){switch((new z).buildStatus(e)){case h.Success:this.handleSuccessResponse(t);break;case h.Failed:case h.Timeout:case h.RateLimit:yield this.handleOtherResponse(t);break;case h.PayloadTooLarge:this.handlePayloadTooLargeResponse(t,me.test(n));break;default:if(499===e){yield this.handleOtherResponse(t);break}this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}})}handlePayloadTooLargeResponse(e,t){const n=t?"WAF (compressed payload too large)":"server (event too large)",i=Math.round(e.events.reduce((e,t)=>e+t.length,0)/Se);if(!t)return void this.completeRequest({context:e,err:`Session replay event batch dropped: ${n} rejected payload (${e.events.length} events, ${i} KB) — not retrying non-WAF 413`});if(1===e.events.length)return void this.completeRequest({context:e,err:`Session replay event dropped: single event (${i} KB, 1 event) rejected by ${n} — cannot split further`});this.loggerProvider.warn(`Session replay event batch rejected by ${n} (${e.events.length} events, ${i} KB total) — splitting and retrying`),e.onComplete();const r=()=>Promise.resolve(),s=Math.floor(e.events.length/2);this.sendEventsList(Object.assign(Object.assign({},e),{events:e.events.slice(0,s),onComplete:r})),this.sendEventsList(Object.assign(Object.assign({},e),{events:e.events.slice(s),onComplete:r}))}handleSuccessResponse(e){const t=Math.round(pn(e.events)/Se);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){return i(this,void 0,void 0,function*(){const t=Math.random()*e.attempts*this.retryTimeout;e.attempts++,e.attempts>(e.flushMaxRetries||0)?this.completeRequest({context:e,err:En}):(yield new Promise(e=>setTimeout(e,t)),yield this.send(e,!0))})}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}applyServerDirective(e,t){if(null===t)return this.flushPauseUntilMs=0,void(this.mergeLogFiredThisPause=!1);if("429"===t){const e=this.flushPauseUntilMs>Date.now();return this.flushPauseUntilMs=Date.now()+6e4,void(e||this.loggerProvider.log("Session replay throttled by server; pausing flush schedule for 60s"))}"4005"!==t&&"4004"!==t||this.killSession(e,t)}killSession(e,t){if(this.killedSessions.has(e))return;if(this.killedSessions.add(e),this.killedSessions.size>256)for(const e of this.killedSessions){this.killedSessions.delete(e);break}this.loggerProvider.log(`Session replay capture stopped for session ${e} by server directive ${t}; remaining events will be dropped`);const n=[];for(const t of this.queue)t.sessionId===e?this.completeRequest({context:t,err:Pn}):n.push(t);this.queue=n}}class Tn{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,i;this.minInterval=ye,this.maxInterval=be,this.maxPersistedEventsSize=6e6,this._timeAtLastSplit=Date.now(),this.eventsContentBytes=new WeakMap,this.sequenceContentBytes=new Map,this.shouldSplitEventsList=(e,t)=>{const n=this.getEventsArraySize(e),i=this.maxPersistedEventsSize-n;let r=t.length>=i;return!r&&3*t.length>=i&&(r=fn(t)>=i),!!r||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(i=e.maxPersistedEventsSize)&&void 0!==i?i:this.maxPersistedEventsSize,this.interval=this.minInterval}isPrefixOf(e,t){return!(t.length<e.length)&&(0===e.length||t[e.length-1]===e.tail)}measureContentBytes(e,t){if(e&&e.length===t.length&&this.isPrefixOf(e,t))return e;let n=0,i=0;e&&this.isPrefixOf(e,t)&&(n=e.contentBytes,i=e.length);for(let e=i;e<t.length;e++)n+=fn(t[e]);return{length:t.length,contentBytes:n,tail:t.length>0?t[t.length-1]:void 0}}getEventsContentBytes(e){const t=this.measureContentBytes(this.eventsContentBytes.get(e),e);return this.eventsContentBytes.set(e,t),t.contentBytes}getEventsArraySize(e){return this.getEventsContentBytes(e)+(2+Math.max(0,e.length-1)+2*e.length)}recallSequenceContentBytes(e,t){const n=this.sequenceContentBytes.get(e);n&&n.length===t.length&&this.isPrefixOf(n,t)&&this.eventsContentBytes.set(t,n)}rememberSequenceContentBytes(e,t){const n=this.measureContentBytes(this.sequenceContentBytes.get(e),t);this.sequenceContentBytes.set(e,n),this.eventsContentBytes.set(t,n)}forgetSequenceContentBytes(e){this.sequenceContentBytes.delete(e)}}const Rn=(e,t,n)=>{var i;"object"==typeof(i=n)&&null!==i&&"AbortError"===i.name?e.debug(t):e.warn(t)};const _n="sessionCurrentSequence",An="sequencesToSend",Ln=5e3;function Fn(e,t,n){const i=setTimeout(n,t);return e.then(()=>clearTimeout(i),()=>clearTimeout(i)),()=>clearTimeout(i)}const Nn=e=>{let t,n;return e.objectStoreNames.contains(_n)||(n=e.createObjectStore(_n,{keyPath:"sessionId"})),e.objectStoreNames.contains(An)||(t=e.createObjectStore(An,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}},qn=e=>i(void 0,void 0,void 0,function*(){return yield function(e,t,n="IDB operation timed out"){return new Promise((i,r)=>{const s=setTimeout(()=>r(new Error(`${n} after ${t}ms`)),t);e.then(e=>{clearTimeout(s),i(e)},e=>{clearTimeout(s),r(e)})})}(l(e,1,{upgrade:Nn}),2e3,"IDB openDB timed out")});class $n extends Tn{maybeLogEmptyFiltered(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug(`Filtered empty session replay sequence at ${e} (idb store)`)}constructor(e){var t;super(e),this.consecutiveFailures=0,this.hasTriggeredFallback=!1,this.emptyFilteredCount=0,this.getSequencesToSend=()=>i(this,void 0,void 0,function*(){let e=!1,t=!1;try{const n=[],i=this.db.transaction("sequencesToSend","readwrite");i.done.catch(n=>{e||t||(Rn(this.loggerProvider,`${xn}: ${n}`,n),this.recordFailure())});const r=Fn(i.done,Ln,()=>{e||t||(t=!0,Rn(this.loggerProvider,`${xn}: transaction timed out`),this.recordFailure())});let s=yield i.store.openCursor();for(;s;){const{sessionId:e,events:t}=s.value;0===t.length?(this.maybeLogEmptyFiltered("getSequencesToSend"),yield s.delete()):n.push({events:t,sequenceId:s.key,sessionId:e}),s=yield s.continue()}return this.recordSuccess(),r(),n}catch(n){t||(e=!0,Rn(this.loggerProvider,`${xn}: ${n}`,n),this.recordFailure())}}),this.storeCurrentSequence=e=>i(this,void 0,void 0,function*(){let t=!1,n=!1;try{const i=this.db.transaction([_n,An],"readwrite");i.done.catch(e=>{t||n||(Rn(this.loggerProvider,`${xn}: ${e}`,e),this.recordFailure())});const r=Fn(i.done,Ln,()=>{t||n||(n=!0,Rn(this.loggerProvider,`${xn}: transaction timed out`),this.recordFailure())}),s=yield i.objectStore(_n).get(e);if(!s||s.tabId&&s.tabId!==this.tabId)return void r();if(0===s.events.length)return this.maybeLogEmptyFiltered("storeCurrentSequence"),void r();const o=yield i.objectStore(An).put({sessionId:e,events:s.events,tabId:this.tabId});yield i.objectStore(_n).put({sessionId:e,events:[],tabId:this.tabId}),this.rememberSequenceContentBytes(e,[]),this.recordSuccess(),r();const{tabId:l}=s,c=a(s,["tabId"]);return Object.assign(Object.assign({},c),{sessionId:e,sequenceId:o})}catch(i){this.forgetSequenceContentBytes(e),n||(t=!0,Rn(this.loggerProvider,`${xn}: ${i}`,i),this.recordFailure())}}),this.addEventToCurrentSequence=(e,t)=>i(this,void 0,void 0,function*(){let n=!1,i=!1;try{const r=this.db.transaction([_n,An],"readwrite");r.done.catch(e=>{n||i||(Rn(this.loggerProvider,`${xn}: ${e}`,e),this.recordFailure())});const s=Fn(r.done,Ln,()=>{n||i||(i=!0,Rn(this.loggerProvider,`${xn}: transaction timed out`),this.recordFailure())}),o=yield r.objectStore(_n).get(e);if((null==o?void 0:o.tabId)&&o.tabId!==this.tabId){o.events.length>0&&(yield r.objectStore(An).put({sessionId:e,events:o.events,tabId:o.tabId}));const n=[t];return yield r.objectStore(_n).put({sessionId:e,events:n,tabId:this.tabId}),this.rememberSequenceContentBytes(e,n),this.recordSuccess(),void s()}const a=o;if(!a){const n=[t];return yield r.objectStore(_n).put({sessionId:e,events:n,tabId:this.tabId}),this.rememberSequenceContentBytes(e,n),this.recordSuccess(),void s()}if(this.recallSequenceContentBytes(e,a.events),!this.shouldSplitEventsList(a.events,t)){const n=a.events.concat(t);return yield r.objectStore(_n).put({sessionId:e,events:n,tabId:this.tabId}),this.rememberSequenceContentBytes(e,n),this.recordSuccess(),void s()}const l=a.events;if(0===l.length){this.maybeLogEmptyFiltered("addEventToCurrentSequence");const n=[t];return yield r.objectStore(_n).put({sessionId:e,events:n,tabId:this.tabId}),this.rememberSequenceContentBytes(e,n),this.recordSuccess(),void s()}const c=[t];yield r.objectStore(_n).put({sessionId:e,events:c,tabId:this.tabId}),this.rememberSequenceContentBytes(e,c);const d=yield r.objectStore(An).put({sessionId:e,events:l,tabId:this.tabId});return this.recordSuccess(),s(),{events:l,sessionId:e,sequenceId:d}}catch(t){this.forgetSequenceContentBytes(e),i||(n=!0,Rn(this.loggerProvider,`${xn}: ${t}`,t),this.recordFailure())}}),this.storeSendingEvents=(e,t)=>i(this,void 0,void 0,function*(){try{const n=yield this.db.put(An,{sessionId:e,events:t,tabId:this.tabId});return this.recordSuccess(),n}catch(e){Rn(this.loggerProvider,`${xn}: ${e}`,e),this.recordFailure()}}),this.cleanUpSessionEventsStore=(e,t)=>i(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(An,t),this.recordSuccess()}catch(e){Rn(this.loggerProvider,`${xn}: ${e}`,e),this.recordFailure()}}),this.db=e.db,this.tabId=e.tabId,this.onPersistentFailure=e.onPersistentFailure,this.consecutiveFailureThreshold=null!==(t=e.consecutiveFailureThreshold)&&void 0!==t?t:1}recordFailure(){var e;this.consecutiveFailures++,!this.hasTriggeredFallback&&this.consecutiveFailures>=this.consecutiveFailureThreshold&&(this.hasTriggeredFallback=!0,null===(e=this.onPersistentFailure)||void 0===e||e.call(this))}recordSuccess(){this.consecutiveFailures=0}static new(e,t){var n;return i(this,void 0,void 0,function*(){try{const i="replay"===e?"":`_${e}`,r=`${t.apiKey.substring(0,10)}_amp_session_replay_events${i}`,s=yield qn(r),o=null!==(n=t.tabId)&&void 0!==n?n:function(){try{return crypto.randomUUID()}catch(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}();return new $n(Object.assign(Object.assign({},t),{db:s,tabId:o}))}catch(e){Rn(t.loggerProvider,`${xn}: ${e}`,e)}})}getCurrentSequenceEvents(e){return i(this,void 0,void 0,function*(){if(e){const t=yield this.db.get("sessionCurrentSequence",e);if(!t)return;if(t.tabId&&t.tabId!==this.tabId)return;return[a(t,["tabId"])]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence")){if(e.tabId&&e.tabId!==this.tabId)continue;const n=a(e,["tabId"]);t.push(n)}return t})}}class jn extends Tn{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0,this.emptyFilteredCount=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}maybeLogEmptyFiltered(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug(`Filtered empty session replay sequence at ${e} (in-memory store)`)}getSequencesToSend(){return i(this,void 0,void 0,function*(){const e=[];for(const[t,{sessionId:n,events:i}]of Object.entries(this.finalizedSequences))0!==i.length?e.push({sequenceId:Number(t),sessionId:n,events:i}):(this.maybeLogEmptyFiltered("getSequencesToSend"),delete this.finalizedSequences[Number(t)]);return e})}storeCurrentSequence(e){return i(this,void 0,void 0,function*(){const t=this.sequences[e];if(t){if(0!==t.length)return this.addSequence(e);this.maybeLogEmptyFiltered("storeCurrentSequence")}})}addEventToCurrentSequence(e,t){return i(this,void 0,void 0,function*(){let n;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(0===this.sequences[e].length?this.maybeLogEmptyFiltered("addEventToCurrentSequence"):n=this.addSequence(e)),this.sequences[e].push(t),n})}storeSendingEvents(e,t){return i(this,void 0,void 0,function*(){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},this.sequenceId++})}cleanUpSessionEventsStore(e,t){return i(this,void 0,void 0,function*(){void 0!==t&&delete this.finalizedSequences[t]})}}const Dn=({config:e,minInterval:t,maxInterval:n,maxPersistedEventsSize:r,type:s,payloadBatcher:o,storeType:a,trackDestinationWorkerScript:l,shouldSend:c})=>i(void 0,void 0,void 0,function*(){var d;const u=null!==(d=e.maxSingleEventSizeBytes)&&void 0!==d?d:pe,h=new On(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:o,workerScript:l})),g=()=>new jn({loggerProvider:e.loggerProvider,maxInterval:n,minInterval:t,maxPersistedEventsSize:r});let v,f,p=!1;f="idb"===a?yield i(void 0,void 0,void 0,function*(){const o=yield $n.new(s,{loggerProvider:e.loggerProvider,minInterval:t,maxInterval:n,maxPersistedEventsSize:r,apiKey:e.apiKey,onPersistentFailure:()=>{i(void 0,void 0,void 0,function*(){if(!p)return;p=!1,e.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store.");const t=v?yield f.getSequencesToSend():void 0;if(f=g(),t&&v){const e=v;t.forEach(t=>{S({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}})}});return o?(p=!0,o):(e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),g())}):g();const m=[];let y=0;const b=e=>{if(e<=y)return;const t=Math.min(e-y,m.length);t>0&&(m.splice(0,t),y=e)},S=({events:t,sessionId:n,deviceId:r,sequenceId:o})=>{let a=t;const l=[];for(let e=0;e<t.length;e++){const n=mn(t[e],u);void 0!==n?(0===l.length&&(a=t.slice(0,e)),l.push(n)):a!==t&&a.push(t[e])}l.length>0&&e.loggerProvider.warn(`Dropping ${l.length} oversized event(s) from session replay sequence before send. Sizes: ${l.map(e=>`${Math.round(e/1024)} KB`).join(", ")}. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.`),0!==a.length?(e.debugMode&&je().then(({totalStorageSize:t,percentOfQuota:n,usageDetails:i})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${i}`)}).catch(()=>{}),h.sendEventsList({events:a,sessionId:n,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:r,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:s,onComplete:()=>i(void 0,void 0,void 0,function*(){yield f.cleanUpSessionEventsStore(n,o)})})):f.cleanUpSessionEventsStore(n,o).catch(t=>{e.loggerProvider.warn("Failed to clean up session replay events store:",t)})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{if(v=n,c&&!c())return;const i=y+m.length;f.storeCurrentSequence(t).then(e=>{e&&(b(i),S({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n}))}).catch(t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)})},addEvent:({event:t,sessionId:n,deviceId:i})=>{v=i;const r=!c||c(),s=y+m.length;m.push(t.data),f.addEventToCurrentSequence(n,t.data).then(t=>{if(t){if(!r)return f.cleanUpSessionEventsStore(t.sessionId,t.sequenceId).catch(t=>{e.loggerProvider.warn("Failed to clean up dropped session replay sequence:",t)}),void b(s);b(s),S({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:i})}}).catch(t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)})},sendStoredEvents:({deviceId:t})=>i(void 0,void 0,void 0,function*(){v=t;const n=yield f.getSequencesToSend();(null==n?void 0:n.length)&&(e.loggerProvider.log(`Draining ${n.length} stored sequence(s) from previous session.`),n.length>1&&h.markCoalesceNextFlush(),n.forEach(e=>{S({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:t})}))}),flush:function(e=!1){return i(this,void 0,void 0,function*(){return h.flush(e)})},getBeaconEvents:()=>[...m],dropPendingBeaconEvents:()=>{b(y+m.length)},trackDestination:h}});class Un{constructor(...e){const t=new Map;e.forEach(e=>{t.set(e.name,e.manager)}),this.managers=t}sendStoredEvents(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.sendStoredEvents(e))}),yield Promise.all(t)})}addEvent({sessionId:e,event:t,deviceId:n}){var i;null===(i=this.managers.get(t.type))||void 0===i||i.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach(n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})})}flush(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.flush(e))}),yield Promise.all(t)})}}const Bn=({version:e,events:t})=>{const n=[];return t.forEach(e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)}),{version:e,events:n}},zn=({version:e,events:t})=>{const n=[];t.forEach(e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)});const i=n.reduce((e,t)=>{const{x:n,y:i,selector:r,timestamp:s}=t,o=s-s%36e5,a=`${n}:${i}:${null!=r?r:""}:${o}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:o,count:1}),e},{});return{version:e,events:Object.values(i)}};class Wn{constructor(e,t){this.createHook=({eventsManager:e,sessionId:t,deviceIdFn:n,mirror:i,ugcFilterRules:r,performanceOptions:s})=>o=>{var a,l,c,d,u;if(o.type!==qt.Click)return;const h=f();if(!h)return;const{location:g,innerHeight:v,innerWidth:p}=h;if(!g)return;const{x:m,y:y}=o;if(void 0===m||void 0===y)return;const b=i.getNode(o.id);let S;if(b)try{S=null!==(a=this.getSelector(b,s))&&void 0!==a?a:void 0}catch(e){this.logger.debug("error resolving selector from finder")}const I=$e(g.href,r),C={x:m+(null!==(c=null===(l=this.scrollWatcher)||void 0===l?void 0:l.currentScrollX)&&void 0!==c?c:0),y:y+(null!==(u=null===(d=this.scrollWatcher)||void 0===d?void 0:d.currentScrollY)&&void 0!==u?u:0),selector:S,viewportHeight:v,viewportWidth:p,pageUrl:I,timestamp:Date.now(),type:"click"},k=n();k&&e.addEvent({sessionId:t,event:{type:"interaction",data:JSON.stringify(C)},deviceId:k})},this.logger=e,this.scrollWatcher=t}getSelector(e,t){var n,i,r;if(null===(n=this.clickSelectors)||void 0===n?void 0:n.has(e))return null!==(i=this.clickSelectors.get(e))&&void 0!==i?i:null;const s=Kt(e,t);return null===(r=this.clickSelectors)||void 0===r||r.set(e,s),s}createSharedHook(e,t){return(n,i)=>{if(n.type!==qt.Click)return;const r=this.clickSelectors;this.clickSelectors=new Map;try{try{null==e||e(n)}catch(e){this.logger.debug("Heatmap click hook failed",e)}if("click"===(null==i?void 0:i.type))try{null==t||t(i)}catch(e){this.logger.debug("Semantic click hook failed",e)}}finally{this.clickSelectors=r}}}}function Kn(){const e=f();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function Hn(){const e=f();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}class Gn{constructor(e,t){const n=f();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=Ne(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e,this.handleSendEvents=t.handleSendEvents,this.loggerProvider=t.loggerProvider}send(e,t){var n;const{sessionId:i,type:r}=this.context;if(this.handleSendEvents){const s=new URLSearchParams({device_id:e,session_id:String(i),type:String(r)}),o=`${this.basePageUrl}?${s.toString()}`,a={"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${this.apiKey}`};try{this.handleSendEvents({url:o,method:"POST",headers:a,body:JSON.stringify(t),keepalive:!0}).catch(e=>{var t;null===(t=this.loggerProvider)||void 0===t||t.warn("Custom transport failed to send session replay interaction beacon:",e)})}catch(e){null===(n=this.loggerProvider)||void 0===n||n.warn("Custom transport threw while sending session replay interaction beacon:",e)}return}const s=new URLSearchParams({device_id:e,session_id:String(i),type:String(r),api_key:this.apiKey}),o=`${this.basePageUrl}?${s.toString()}`;this.sendBeacon(o,t)||this.sendXhr(o,t)}}class Jn{static default(e,t){return new Jn(new Gn(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,i,r,s;const o=e(),a=f();if(a&&o){const e=null!==(n=a.scrollX)&&void 0!==n?n:0,t=null!==(i=a.scrollY)&&void 0!==i?i:0;(e>0||t>0)&&this.update({id:1,x:e,y:t}),this.transport.send(o,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:Kn(),viewportWidth:Hn(),pageUrl:$e(a.location.href,null!==(s=null===(r=this.config.interactionConfig)||void 0===r?void 0:r.ugcFilterRules)&&void 0!==s?s:[]),timestamp:this.timestamp,type:"scroll"}]})}},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=Hn(),this._maxScrollHeight=Kn(),this.config=t,this.transport=e}get maxScrollX(){return this._maxScrollX}get maxScrollY(){return this._maxScrollY}get maxScrollWidth(){return this._maxScrollWidth}get maxScrollHeight(){return this._maxScrollHeight}get currentScrollX(){return this._currentScrollX}get currentScrollY(){return this._currentScrollY}update(e){const t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){const n=Hn();this._maxScrollX=e.x;const i=e.x+n;i>this._maxScrollWidth&&(this._maxScrollWidth=i),this.timestamp=t}if(e.y>this._maxScrollY){const n=Kn();this._maxScrollY=e.y;const i=e.y+n;i>this._maxScrollHeight&&(this._maxScrollHeight=i),this.timestamp=t}}}class Qn{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Zn=864e5,Xn=e=>`AMP_SR_START_${e.substring(0,10)}_`,Vn=(e,t)=>`${Xn(e)}${t}`,Yn=()=>{try{const e=f();return null==e?void 0:e.localStorage}catch(e){return}};const ei=new class{constructor(){this.dbs={},this.createStore=e=>i(this,void 0,void 0,function*(){return yield l(e,1,{upgrade:e=>{e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})}),this.openOrCreateDB=e=>i(this,void 0,void 0,function*(){if(this.dbs&&this.dbs[e])return this.dbs[e];const t=`${e.substring(0,10)}_amp_session_replay_targeting`,n=yield this.createStore(t);return this.dbs[e]=n,n}),this.getTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:n})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n),r=yield e.get("sessionTargetingMatch",i);return null==r?void 0:r.targetingMatch}catch(t){Rn(e,`Failed to get targeting match for session id ${n}: ${t}`,t)}}),this.storeTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:n,targetingMatch:r})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n);return yield e.put("sessionTargetingMatch",{targetingMatch:r,sessionId:i,lastUpdated:Date.now()})}catch(t){Rn(e,`Failed to store targeting match for session id ${n}: ${t}`,t)}}),this.clearStoreOfOldSessions=({loggerProvider:e,apiKey:t,currentSessionId:n})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n),r=e.transaction("sessionTargetingMatch","readwrite"),s=yield r.store.getAll();for(let e=0;e<s.length;e++){const t=s[e],n=Date.now()-t.lastUpdated;t.sessionId!==i&&n>1728e5&&(yield r.store.delete(t.sessionId))}yield r.done}catch(t){Rn(e,`Failed to clear old targeting matches for sessions: ${t}`,t)}})}},ti=2654435761,ni=2246822519,ii=3266489917,ri=374761393;function si(e,t){return(e<<t|e>>>32-t)>>>0}function oi(e,t){return e=si(e=e+Math.imul(t,ni)>>>0,13),e=Math.imul(e,ti)>>>0}function ai(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function li(e,t=0){const n=function(e){const t=[];for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);if(i>=55296&&i<=56319&&n+1<e.length){const t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(i=t-56320+(i-55296<<10)+65536,n++)}i<128?t.push(i):i<2048?t.push(192|i>>6,128|63&i):i<65536?t.push(224|i>>12,128|i>>6&63,128|63&i):t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}return new Uint8Array(t)}(e),i=n.length;let r,s=0;if(i>=16){let e=t+ti+ni>>>0,o=t+ni>>>0,a=t>>>0,l=t-ti>>>0;for(;s<=i-16;)e=oi(e,ai(n,s)),s+=4,o=oi(o,ai(n,s)),s+=4,a=oi(a,ai(n,s)),s+=4,l=oi(l,ai(n,s)),s+=4;r=si(e,1)+si(o,7)+si(a,12)+si(l,18)>>>0}else r=t+ri>>>0;for(r=r+i>>>0;s<=i-4;)r=r+Math.imul(ai(n,s),ii)>>>0,r=Math.imul(si(r,17),668265263)>>>0,s+=4;for(;s<i;)r=r+Math.imul(n[s],ri)>>>0,r=Math.imul(si(r,11),ti)>>>0,s++;return r^=r>>>15,r=Math.imul(r,ni)>>>0,r^=r>>>13,r=Math.imul(r,ii)>>>0,r^=r>>>16,r>>>0}const ci="__amplitude_url_tracking_patched__",di=new WeakMap;function ui(e,t,n={}){if(!(null==e?void 0:e.location))return()=>{};const{enablePolling:i=!1,pollingInterval:r=ue}=n;if(i){const i=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""};let s=i();const o=e.setInterval(()=>{var e;const r=i();r!==s&&(s=r,t(r),null===(e=n.onNavigation)||void 0===e||e.call(n,"replace"))},r);return()=>{null!=o&&e.clearInterval(o)}}let s=di.get(e);if(!s){let t;const n=new Set,i=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""},r=e=>{const r=i();void 0!==t&&r===t||(t=r,n.forEach(t=>t(r,e)))},o=(e,t)=>{const n=function(...n){const i=e.apply(this,n);return r(t),i};return n[ci]=!0,n},a=e.history;if(null==a?void 0:a.pushState){const e=Reflect.get(a,"pushState");e[ci]||(a.pushState=o(e,"push"))}if(null==a?void 0:a.replaceState){const e=Reflect.get(a,"replaceState");e[ci]||(a.replaceState=o(e,"replace"))}s={callbacks:n,notify:r,onPopStateOrHashChange:e=>r("hashchange"===(null==e?void 0:e.type)?"hash":"pop"),listenersAttached:!1},di.set(e,s)}const o=s;o.listenersAttached||(e.addEventListener("popstate",o.onPopStateOrHashChange),e.addEventListener("hashchange",o.onPopStateOrHashChange),o.listenersAttached=!0);const a=(e,i)=>{var r;t(e),null===(r=n.onNavigation)||void 0===r||r.call(n,i)};return o.callbacks.add(a),()=>{o.callbacks.delete(a),0===o.callbacks.size&&o.listenersAttached&&(e.removeEventListener("popstate",o.onPopStateOrHashChange),e.removeEventListener("hashchange",o.onPopStateOrHashChange),o.listenersAttached=!1)}}function hi(e={}){return{name:"amplitude/url-tracking@1",observer(t,n,i){var r,s,o;const a=Object.assign(Object.assign({},e),i),l=a.ugcFilterRules||[],c=null!==(r=a.enablePolling)&&void 0!==r&&r,d=null!==(s=a.pollingInterval)&&void 0!==s?s:ue,u=null!==(o=a.captureDocumentTitle)&&void 0!==o&&o;if(!n)return()=>{};let h;const g=()=>n.location&&n.location.href||"",v=()=>{const e=g();if(void 0===h||e!==h){h=e;const i=(()=>{const{innerHeight:e,innerWidth:t,document:i}=n,r=g();let s="";return u&&(s=(null==i?void 0:i.title)||""),{href:l.length>0?$e(r,l):r,title:s,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(i)}},f=ui(n,()=>v(),c?{enablePolling:!0,pollingInterval:d}:{});return v(),()=>f()},options:e}}class gi{constructor(){this.pendingLoadListeners=new Map}start(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect();f()&&(this.sendToAllIframes({type:Ce,action:"start"}),this.mutationObserver=new MutationObserver(e=>{for(const t of e){for(const e of Array.from(t.addedNodes))e instanceof HTMLIFrameElement?this.sendToIframeAfterLoad(e):e instanceof Element&&e.querySelectorAll("iframe").forEach(e=>{this.sendToIframeAfterLoad(e)});for(const e of Array.from(t.removedNodes))if(e instanceof HTMLIFrameElement){const t=this.pendingLoadListeners.get(e);t&&(e.removeEventListener("load",t),this.pendingLoadListeners.delete(e))}}}),this.mutationObserver.observe(document.documentElement,{childList:!0,subtree:!0}))}stop(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),this.mutationObserver=void 0,this.pendingLoadListeners.forEach((e,t)=>{t.removeEventListener("load",e)}),this.pendingLoadListeners.clear(),this.sendToAllIframes({type:Ce,action:"stop"})}sendToIframeAfterLoad(e){const t=()=>{this.pendingLoadListeners.delete(e),this.sendToIframe(e,{type:Ce,action:"start"})};this.pendingLoadListeners.set(e,t),e.addEventListener("load",t,{once:!0})}sendToAllIframes(e){document.querySelectorAll("iframe").forEach(t=>this.sendToIframe(t,e))}sendToIframe(e,t){var n;try{null===(n=e.contentWindow)||void 0===n||n.postMessage(t,"*")}catch(e){}}}class vi{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.recordFunction=null,this.recordEventsInFlight=!1,this.recordingEnabled=!0,this.recordingGeneration=0,this.startChildRecordingOnSetup=!1,this.pendingEmitEvents=[],this.currentPageUrl="",this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.crossOriginIframeCoordinator=null,this.crossOriginParentSignalCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=e=>{const t=f();t&&(t.removeEventListener("blur",this.blurListener),t.removeEventListener("focus",this.focusListener),!e&&t.addEventListener("blur",this.blurListener),!e&&t.addEventListener("focus",this.focusListener),t.self&&"onpagehide"in t.self?(t.removeEventListener("pagehide",this.pageLeaveListener),!e&&t.addEventListener("pagehide",this.pageLeaveListener)):(t.removeEventListener("beforeunload",this.pageLeaveListener),!e&&t.addEventListener("beforeunload",this.pageLeaveListener)))},this.blurListener=()=>{this.sendEvents()},this.focusListener=()=>{var e;if(this.recordingEnabled)if(this.recordCancelCallback&&this.recordFunction){if(!1===(null===(e=this.config)||void 0===e?void 0:e.captureFullSnapshotOnFocus))return;try{this.recordFunction.takeFullSnapshot(!0)}catch(e){this.loggerProvider.warn("Failed to take full snapshot on focus:",e)}}else this.recordEventsInFlight||this.recordEvents(!1)},this.pageLeaveListener=e=>{var t;null===(t=this.eventCompressor)||void 0===t||t.flushQueue(),this.sendEvents(),this.pageLeaveFns.forEach(t=>{t(e)})},this.evaluateTargetingAndCapture=(e,t=!1,n=!1,r=!1)=>i(this,void 0,void 0,function*(){var s,o,a,l,c,d;if(!this.identifiers||!this.identifiers.sessionId||!this.config)return void(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."));if(!this.config.targetingConfig){if(!t)return void this.loggerProvider.log("No targeting config set, skipping initialization/recording for event.");this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}this.lastTargetingParams=e;const h=this.config.targetingConfig;if(h&&!this.sessionTargetingMatch){const t=r?this.latestUrlChangeTargetingEvaluationId:void 0;let n=e.event;n&&Object.values(u).includes(n.event_type)&&(n=void 0);const g=null!==(c=null!==(o=null===(s=e.page)||void 0===s?void 0:s.url)&&void 0!==o?o:null===(l=null===(a=f())||void 0===a?void 0:a.location)||void 0===l?void 0:l.href)&&void 0!==c?c:"",v=null!==(d=e.page)&&void 0!==d?d:""!==g?{url:g}:void 0,p=yield(({sessionId:e,targetingConfig:t,loggerProvider:n,apiKey:r,targetingParams:s,urlChange:o=!1})=>i(void 0,void 0,void 0,function*(){if(yield ei.clearStoreOfOldSessions({loggerProvider:n,apiKey:r,currentSessionId:e}),!0===(yield ei.getTargetingMatchForSession({loggerProvider:n,apiKey:r,sessionId:e}))&&!o)return!0;let i=!0;try{const{evaluateTargeting:o}=yield import("./targeting-min.js").then(function(e){return e.i}),a=Object.assign(Object.assign({},s),{flag:t,sessionId:"string"==typeof e?parseInt(e,10):e,apiKey:r,loggerProvider:n}),l=yield o(a);l&&l.sr_targeting_config&&(i="on"===l.sr_targeting_config.key),ei.storeTargetingMatchForSession({loggerProvider:n,apiKey:r,sessionId:e,targetingMatch:i})}catch(e){const t=e;n.warn(t.message)}return i}))({sessionId:this.identifiers.sessionId,targetingConfig:h,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:n,page:v},urlChange:r});if(r&&void 0!==t&&t!==this.latestUrlChangeTargetingEvaluationId)return void this.loggerProvider.debug(`Ignoring stale URL-change targeting result #${t}; latest is #${this.latestUrlChangeTargetingEvaluationId}.`);this.sessionTargetingMatch=this.sessionTargetingMatch||p,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:n,targetingParams:e},null,2))}t?this.initialize(!0):!n&&this.recordCancelCallback||(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),yield this.recordEvents())}),this.addCustomRRWebEvent=(e,t={},n=!0)=>i(this,void 0,void 0,function*(){try{let i;const r=this.config;if(r&&e!==ke.METADATA&&(i={config:De(r),version:Mn},n)){const e=yield je();i=Object.assign(Object.assign({},e),i)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},t),i)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}}),this.stopRecordingEvents=(e="targeting",t="stop")=>{var n,i,r,s;try{null===(n=this.semanticAdapter)||void 0===n||n.stop(e,t),this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(i=this.networkObservers)||void 0===i||i.stop(),null===(r=this.crossOriginIframeCoordinator)||void 0===r||r.stop(),this.crossOriginIframeCoordinator=null,null===(s=this.crossOriginParentSignalCleanup)||void 0===s||s.call(this),this.crossOriginParentSignalCleanup=null}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new we(new M)}init(e,t){return x(this._init(e,t))}setupUrlChangeListener(){var e,t;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);const n=f();if(!(null==n?void 0:n.location))return;const i=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),r=ui(n,e=>{if(this.currentPageUrl=e,i){const t=++this.latestUrlChangeTargetingEvaluationId;this.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:e}},!1,!1,!0),this.loggerProvider.debug(`Queued URL-change targeting re-evaluation #${t} for ${e}.`)}});this.urlChangeCleanup=()=>{r(),this.urlChangeCleanup=null}}isBelowMinSessionDuration(){var e;const t=null===(e=this.config)||void 0===e?void 0:e.minSessionDurationMs;return void 0!==t&&void 0!==this.sessionStartTime&&Date.now()-this.sessionStartTime<t}getCurrentPageForTargeting(){var e,t;const n=null===(t=null===(e=f())||void 0===e?void 0:e.location)||void 0===t?void 0:t.href;return null!=n?{url:n}:void 0}_init(e,t){var n,r,s,o,a,l,c,d,u,h,g,v,p,m,y;return i(this,void 0,void 0,function*(){null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),null===(r=this.semanticAdapter)||void 0===r||r.stop("customer_stop"),this.semanticAdapter=void 0,this.recordingEnabled=!0,this.startChildRecordingOnSetup=!1,this.loggerProvider=new we(t.loggerProvider||new M),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=qe(),this.identifiers=new Qn({sessionId:t.sessionId,deviceId:t.deviceId});const b=Date.now();((e,t,n)=>{const i=Yn();if(!i)return;const r=Xn(e);try{const e=[];for(let n=0;n<i.length;n++){const s=i.key(n);if(!s||!s.startsWith(r))continue;const o=i.getItem(s);if(null===o)continue;const a=Number(o);(!Number.isFinite(a)||a<=0||t-a>=Zn)&&e.push(s)}for(const t of e)i.removeItem(t)}catch(e){null==n||n.debug(`Failed to prune stale replay start times: ${String(e)}`)}})(e,b,this.loggerProvider),this.sessionStartTime=void 0!==t.sessionId&&null!==(s=((e,t,n,i)=>{const r=Yn();if(!r)return;const s=Vn(e,t);try{const e=r.getItem(s);if(null!==e){const t=Number(e);if(Number.isFinite(t)&&t>0&&t<=n&&n-t<Zn)return t}return r.setItem(s,String(n)),n}catch(e){return void(null==i||i.debug(`Failed to read/write replay start time from storage: ${String(e)}`))}})(e,t.sessionId,b,this.loggerProvider))&&void 0!==s?s:b,this.joinedConfigGenerator=yield((e,t)=>i(void 0,void 0,void 0,function*(){const n=new Be(e,t),i=new Z(e,n.loggerProvider,n.serverZone,t.configServerUrl,t.handleFetchConfig);return new gn(i,n)}))(e,t);const{joinedConfig:S,localConfig:I,remoteConfig:C}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=S,this.setMetadata(t.sessionId,S,I,C,null===(o=t.version)||void 0===o?void 0:o.version,Mn,null===(a=t.version)||void 0===a?void 0:a.type),this.pageLeaveFns=[],t.sessionId&&(null===(l=this.config.interactionConfig)||void 0===l?void 0:l.enabled)){const e=Jn.default({sessionId:t.sessionId,type:"interaction"},this.config);this.pageLeaveFns=[e.send(this.getDeviceId.bind(this)).bind(e)],this.scrollHook=e.hook.bind(e),this.clickHandler=new Wn(this.loggerProvider,e)}const k=[];let w,E,{storeType:x}=this.config;"idb"!==x||(null===(c=f())||void 0===c?void 0:c.indexedDB)||(x="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${x} for event storage.`);const P=f();if(this.config.useWebWorker&&P&&P.Worker){const{compressionScript:e,trackDestinationScript:t}=yield import("./worker-min.js");w=e,E=t}let O;try{O=yield Dn({config:this.config,type:"replay",minInterval:null===(d=this.config.flushIntervalConfig)||void 0===d?void 0:d.minIntervalMs,maxInterval:null===(u=this.config.flushIntervalConfig)||void 0===u?void 0:u.maxIntervalMs,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,storeType:x,trackDestinationWorkerScript:E,shouldSend:()=>!this.isBelowMinSessionDuration()}),this.rrwebEventManager=O,k.push({name:"replay",manager:O})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(h=this.config.interactionConfig)||void 0===h?void 0:h.enabled){const e=this.config.interactionConfig.batch?zn:Bn;try{const t=yield Dn({config:this.config,type:"interaction",minInterval:null!==(g=this.config.interactionConfig.trackEveryNms)&&void 0!==g?g:3e4,maxInterval:6e4,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,payloadBatcher:e,storeType:x,trackDestinationWorkerScript:E});k.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new Un(...k),this.eventCompressor&&this.eventCompressor.terminate();const T=!0===this.config.eagerFullSnapshotSend?()=>this.sendEvents():void 0;if(this.eventCompressor=new wn(this.eventsManager,this.config,this.getDeviceId(),w,T),this.pendingEmitEvents.length>0){const e=this.pendingEmitEvents.splice(0);for(const{event:t,sessionId:n}of e)this.eventCompressor.enqueueEvent(t,n)}if(this.pageLeaveFns=[...this.pageLeaveFns,()=>{var e;if(!this.config||!(null===(e=this.identifiers)||void 0===e?void 0:e.sessionId)||!O)return;const t=O.getBeaconEvents();if(!t.length)return;const n=this.getDeviceId();n&&(this.isBelowMinSessionDuration()||O.trackDestination.sendBeacon({events:t,sessionId:this.identifiers.sessionId,deviceId:n,apiKey:this.config.apiKey,serverZone:this.config.serverZone}))}],yield this.initializeNetworkObservers(),null===(v=f())||void 0===v?void 0:v.opener){const e=ie();oe(e),e.setup(Object.assign({logger:this.loggerProvider},this.config.serverZone&&{endpoint:Y[this.config.serverZone]}))}this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),yield this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0);(this.config.targetingConfig||(null!==(y=null===(m=null===(p=this.config.privacyConfig)||void 0===p?void 0:p.urlMaskLevels)||void 0===m?void 0:m.length)&&void 0!==y?y:0)>0)&&this.setupUrlChangeListener()})}setSessionId(e,t){return x(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,n){var r,s,o,a,l,c;return i(this,void 0,void 0,function*(){const i=null===(r=this.identifiers)||void 0===r?void 0:r.sessionId,d=this.getDeviceId();if(!(void 0===i||i!==e||void 0!==t&&t!==d||void 0!==(null==n?void 0:n.userProperties)&&0!==Object.keys(n.userProperties).length))return;this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,i&&this.sendEvents(i);const u=i!==e;u&&(null===(o=null===(s=this.config)||void 0===s?void 0:s.semanticCapture)||void 0===o?void 0:o.enabled)&&this.semanticAdapter&&this.stopRecordingEvents("new_session"),u&&(null===(a=this.rrwebEventManager)||void 0===a||a.dropPendingBeaconEvents());const h=t||this.getDeviceId();if(this.identifiers=new Qn({sessionId:e,deviceId:h}),u&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,(null===(l=this.config)||void 0===l?void 0:l.apiKey)&&(((e,t,n,i)=>{const r=Yn();if(r)try{r.setItem(Vn(e,t),String(n))}catch(e){null==i||i.debug(`Failed to write replay start time to storage: ${String(e)}`)}})(this.config.apiKey,e,this.sessionStartTime,this.loggerProvider),void 0!==i&&((e,t,n)=>{const i=Yn();if(i)try{i.removeItem(Vn(e,t))}catch(e){null==n||n.debug(`Failed to remove replay start time from storage: ${String(e)}`)}})(this.config.apiKey,i,this.loggerProvider))),this.joinedConfigGenerator&&i){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig();this.config=e}(null===(c=this.config)||void 0===c?void 0:c.targetingConfig)?yield this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0):yield this.recordEvents()})}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let i={};return n&&(i={[le]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(i[he]=JSON.stringify({appHash:B(e.apiKey).toString()}))),this.addCustomRRWebEvent(ke.GET_SR_PROPS,{shouldRecord:n,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i}sendEvents(e){var t,n;const i=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),r=this.getDeviceId();if(this.eventsManager&&i&&r){if(this.isBelowMinSessionDuration()){const e=this.sessionStartTime,t=this.config.minSessionDurationMs;return this.loggerProvider.log(`Session ${i} not sent: duration ${Date.now()-e}ms is below minimum ${t}ms.`),void this.suppressedSendCount++}if(!this.hasEmittedGateDecision&&void 0!==(null===(n=this.config)||void 0===n?void 0:n.minSessionDurationMs)&&this.recordCancelCallback&&this.recordFunction){this.hasEmittedGateDecision=!0;const e=void 0!==this.sessionStartTime?Date.now()-this.sessionStartTime:void 0;this.addCustomRRWebEvent(ke.REPLAY_GATE_DECISION,{sessionId:i,suppressedSendCount:this.suppressedSendCount,elapsedMs:e,minSessionDurationMs:this.config.minSessionDurationMs},!1)}this.eventsManager.sendCurrentSequenceEvents({sessionId:i,deviceId:r})}}initialize(e=!1){var t;return i(this,void 0,void 0,function*(){if(!(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId))return this.loggerProvider.log("Session is not being recorded due to lack of session id."),Promise.resolve();const n=this.getDeviceId();return n?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())})}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(i=this.config.instanceName,U.getInstance(O(i))).identityStore.getIdentity().optOut}var i;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.recordingEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured because recording was stopped.`),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;let e=!1,t="",n=!1;if(this.config.targetingConfig)this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,n=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,n=!1);else{(i=this.identifiers.sessionId,r=this.config.sampleRate,li(i.toString())%1e6/1e6<r)?(e=!0,n=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,n=!1)}var i,r;return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(ke.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:n,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e;return Le(null===(e=this.config)||void 0===e?void 0:e.privacyConfig)}getMaskTextSelectors(){var e;return Fe(null===(e=this.config)||void 0===e?void 0:e.privacyConfig,this.currentPageUrl)}getRecordingPlugins(e){var t,n,r,s,o,a;return i(this,void 0,void 0,function*(){const i=[];try{const e=hi({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===(s=this.config)||void 0===s?void 0:s.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle});i.push(e)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(null===(a=null==e?void 0:e.console)||void 0===a?void 0:a.enabled)try{const{getRecordConsolePlugin:t}=yield import("./console-plugin-min.js");i.push(t({level:e.console.levels}))}catch(e){this.loggerProvider.warn("Failed to load console plugin:",e)}return i.length>0?i:void 0})}getRecordFunction(){return i(this,void 0,void 0,function*(){if(this.recordFunction)return this.recordFunction;try{const{record:e}=yield import("./rrweb-record-min.js");return this.recordFunction=e,e}catch(e){return this.loggerProvider.warn("Failed to load rrweb-record module:",e),null}})}recordEvents(e=!0){return i(this,void 0,void 0,function*(){if(this.recordEventsInFlight)this.recordEventsPendingShouldLogMetadata=e;else{this.recordEventsInFlight=!0;try{for(yield this._recordEvents(e);null!==this.recordEventsPendingShouldLogMetadata;){const e=this.recordEventsPendingShouldLogMetadata;this.recordEventsPendingShouldLogMetadata=null,yield this._recordEvents(e)}}finally{this.recordEventsInFlight=!1,this.recordEventsPendingShouldLogMetadata=null}}})}shouldAbandonRecordStart(e){return!this.recordingEnabled||e!==this.recordingGeneration}_recordEvents(e=!0){var t,n,r,s,o,a,l,c,d,u,h,g,v;return i(this,void 0,void 0,function*(){const i=this.config,p=this.getShouldRecord(),m=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!p||!m||!i)return void((null===(n=null==i?void 0:i.semanticCapture)||void 0===n?void 0:n.enabled)&&this.semanticAdapter&&this.recordCancelCallback&&this.stopRecordingEvents(this.shouldOptOut()?"opt_out":i.targetingConfig?"targeting":"sampled_out"));this.stopRecordingEvents("focus","pause");const y=this.recordingGeneration,b=yield this.getRecordFunction();if(!b||this.shouldAbandonRecordStart(y))return;if(yield this.initializeNetworkObservers(),this.shouldAbandonRecordStart(y))return;const S=null===(r=i.loggingConfig)||void 0===r?void 0:r.network,I=Ne(i.serverZone,i.trackServerUrl),C=[ge,ve,fe,I];null===(s=this.networkObservers)||void 0===s||s.start(e=>{C.some(t=>e.url.startsWith(t))||this.addCustomRRWebEvent(ke.FETCH_REQUEST,e)},S);const{interactionConfig:k,loggingConfig:w}=i,E=(null==k?void 0:k.enabled)&&this.eventsManager?null===(o=this.clickHandler)||void 0===o?void 0:o.createHook({eventsManager:this.eventsManager,sessionId:m,deviceIdFn:this.getDeviceId.bind(this),mirror:b.mirror,ugcFilterRules:null!==(a=k.ugcFilterRules)&&void 0!==a?a:[],performanceOptions:null===(l=i.performanceConfig)||void 0===l?void 0:l.interaction}):void 0;let x=E;if((null===(c=i.semanticCapture)||void 0===c?void 0:c.enabled)&&b.supportsNativeMouseInteraction){x=(null!==(d=this.clickHandler)&&void 0!==d?d:this.clickHandler=new Wn(this.loggerProvider)).createSharedHook(E,e=>{var t;return null===(t=this.semanticAdapter)||void 0===t?void 0:t.click(e)})}const P=Object.assign(Object.assign({},x?{mouseInteraction:x}:{}),(null==k?void 0:k.enabled)?{scroll:this.scrollHook}:{}),M=(null==k?void 0:k.enabled)&&k.ugcFilterRules?k.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${m}.`);try{const t=!!(null===(u=i.crossOriginIframes)||void 0===u?void 0:u.enabled),n=!1!==(null===(h=i.crossOriginIframes)||void 0===h?void 0:h.coordinateChildren),r=t&&function(){try{const e=f();return!!e&&e.parent!==e}catch(e){return!0}}();if(r&&n)return this.crossOriginParentSignalCleanup=function(e){const t=f();if(!t)return()=>{};const n=t.parent;function i(t){if(t.source!==n)return;const i=t.data;(null==i?void 0:i.type)===Ce&&("start"===i.action?e.onStart():"stop"===i.action&&e.onStop())}return t.addEventListener("message",i),()=>t.removeEventListener("message",i)}({onStart:()=>{this.recordingEnabled&&this._recordEventsInChildMode(b,m,i,P)},onStop:()=>{try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping child iframe replay capture: ${t.toString()}`)}}}),void(this.startChildRecordingOnSetup&&(this.startChildRecordingOnSetup=!1,this._recordEventsInChildMode(b,m,i,P)));this.startChildRecordingOnSetup=!1;const s=yield this.getRecordingPlugins(w);if(this.shouldAbandonRecordStart(y))return;this.prepareSemanticCapture(i,m),this.recordCancelCallback=b(Object.assign(Object.assign({},this.buildRRWebRecordOptions(i,P,e=>{var t,n,i,r;const s=(null===(n=null===(t=this.config)||void 0===t?void 0:t.semanticCapture)||void 0===n?void 0:n.enabled)&&this.semanticAdapter&&e.type===Ft.Custom&&"amp-semantic/recording"===e.data.tag&&"stop"===(null===(i=e.data.payload)||void 0===i?void 0:i.state);if((this.shouldOptOut()||!this.recordingEnabled)&&!s)return this.loggerProvider.log(this.shouldOptOut()?`Opting session ${m} out of recording due to optOut config.`:`Session Replay capture stopping for ${m}.`),this.stopRecordingEvents(this.shouldOptOut()?"opt_out":"customer_stop"),void this.sendEvents();e.type===Ft.Meta&&(e.data.href=$e(e.data.href,M)),this.eventCompressor?this.eventCompressor.enqueueEvent(e,m):this.pendingEmitEvents.push({event:e,sessionId:m}),null===(r=this.semanticAdapter)||void 0===r||r.event(e)},"Error while capturing replay: ")),{plugins:s,recordCrossOriginIframes:t})),this.recordCancelCallback&&(null===(g=this.semanticAdapter)||void 0===g||g.recordingReady()),t&&!r&&n&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new gi),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(ke.DEBUG_INFO),e&&this.addCustomRRWebEvent(ke.METADATA,this.metadata)}catch(e){null===(v=this.semanticAdapter)||void 0===v||v.stop("error"),this.loggerProvider.warn("Failed to initialize session replay:",e)}})}prepareSemanticCapture(e,t){var n,i,r,s;const o=f();if(null==o?void 0:o.document){if(!(null===(n=e.semanticCapture)||void 0===n?void 0:n.enabled))return null===(i=this.semanticAdapter)||void 0===i||i.stop("targeting"),void(null===(r=this.semanticAdapter)||void 0===r||r.prepare({enabled:!1},t));this.semanticAdapter||(this.semanticAdapter=new $t({document:o.document,window:o,sdk:`@amplitude/session-replay-browser@${Mn}`,externalClicks:!0===(null===(s=this.recordFunction)||void 0===s?void 0:s.supportsNativeMouseInteraction),externalAuxClicks:!1,getNodeId:e=>{var t,n,i,r;return null!==(r=null===(i=null===(t=this.recordFunction)||void 0===t?void 0:(n=t.mirror).getId)||void 0===i?void 0:i.call(n,e))&&void 0!==r?r:-1},getNode:e=>{var t,n;return null!==(n=null===(t=this.recordFunction)||void 0===t?void 0:t.mirror.getNode(e))&&void 0!==n?n:null},getPrivacy:()=>{var e,t;return null!==(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)&&void 0!==t?t:{}},getUrl:()=>o.location.href,getIdentity:()=>function(e){const t=e.document,n=Dt.get(t);if(n)return n;let i=ot(t,e);if(e.top===e)try{const t=e.sessionStorage,n=()=>{var e;try{const n=JSON.parse(null!==(e=t.getItem(jt))&&void 0!==e?e:"null");if(n&&Ut.test(n.tab_id)&&(null===n.owner||"string"==typeof n.owner))return n}catch(e){}},r=n();null===(null==r?void 0:r.owner)&&(i=Object.freeze(Object.assign(Object.assign({},i),{tab_id:r.tab_id})));const s=e=>{try{t.setItem(jt,JSON.stringify({tab_id:i.tab_id,owner:e}))}catch(e){}};t.setItem(jt,JSON.stringify({tab_id:i.tab_id,owner:i.document_id})),e.addEventListener("pagehide",()=>{var e;(null===(e=n())||void 0===e?void 0:e.owner)===i.document_id&&s(null)}),e.addEventListener("pageshow",e=>{e.persisted&&s(i.document_id)})}catch(n){i=ot(t,e)}return Dt.set(t,i),i}(o),getAnalyticsContext:()=>{var e,t;return null!==(t=null===(e=this.config)||void 0===e?void 0:e.semanticAnalyticsContext)&&void 0!==t?t:{present:!1,autocapture:[]}},inlineStylesheet:e.shouldInlineStylesheet,getSelector:e=>{var t,n;try{const i=Object.assign(Object.assign({},null===(n=null===(t=this.config)||void 0===t?void 0:t.performanceConfig)||void 0===n?void 0:n.interaction),{timeoutMs:1});return this.clickHandler?this.clickHandler.getSelector(e,i):Kt(e,i)}catch(e){return null}},emit:e=>{this.recordCancelCallback&&this.recordFunction&&this.recordFunction.addCustomEvent(`amp-semantic/${e.name}`,e.payload)},onError:e=>this.loggerProvider.debug("Semantic capture error:",e)})),this.semanticAdapter.prepare(e.semanticCapture,t)}}buildRRWebRecordOptions(e,t,n,i){const{privacyConfig:r}=e;return Object.assign(Object.assign(Object.assign(Object.assign({emit:n,inlineStylesheet:e.shouldInlineStylesheet,inlineImages:e.inlineImages,hooks:t},function(e,t){return void 0===t&&(t=function(){return""}),{maskAllInputs:!0,maskTextClass:"amp-mask",blockClass:"amp-block",blockSelector:Le(e),maskTextSelector:Fe(e,t()),maskInputFn:_e("input",e,t),maskTextFn:_e("text",e,t),maskAttributeFn:Ae(e,t)}}(r,()=>this.currentPageUrl)),{applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements}),void 0!==e.fullSnapshotIntervalMs&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn(i,t.toString()),!0}})}_recordEventsInChildMode(e,t,n,i){try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,this.recordCancelCallback=e(Object.assign(Object.assign({},this.buildRRWebRecordOptions(n,i,()=>{},"Error while capturing replay (child iframe): ")),{recordCrossOriginIframes:!0})),this.loggerProvider.log(`Session Replay child iframe capture beginning for session ${t}.`)}catch(e){this.loggerProvider.warn("Failed to initialize session replay in child iframe mode:",e)}}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}start(){return x(this._start())}_start(){return i(this,void 0,void 0,function*(){this.recordingEnabled=!0,this.startChildRecordingOnSetup=!0,yield this.recordEvents()})}stop(){this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,this.stopRecordingEvents("customer_stop"),this.sendEvents()}flush(e=!1){var t;return i(this,void 0,void 0,function*(){return null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)})}shutdown(){var e,t;this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,null===(e=this.urlChangeCleanup)||void 0===e||e.call(this),null===(t=this.crossOriginParentSignalCleanup)||void 0===t||t.call(this),this.crossOriginParentSignalCleanup=null,this.teardownEventListeners(!0),this.stopRecordingEvents(this.semanticAdapter&&this.shouldOptOut()?"opt_out":"customer_stop"),this.sendEvents()}mapSDKType(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null}setMetadata(e,t,n,i,r,s,o){const a=(null==e?void 0:e.toString())?B(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:i,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(o),replaySDKVersion:r,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:s}}initializeNetworkObservers(){var e,t,n;return i(this,void 0,void 0,function*(){if((null===(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===t?void 0:t.network)||void 0===n?void 0:n.enabled)&&!this.networkObservers)try{const{NetworkObservers:e}=yield import("./observers-min.js");this.networkObservers=new e}catch(e){this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",e)}})}}const fi=e=>()=>{const{config:t}=e,{loggerProvider:n,logLevel:i}=t||Ue();return{logger:n,logLevel:i}};var pi=(()=>{const e=new vi;return{init:L(e.init.bind(e),"init",fi(e)),evaluateTargetingAndCapture:L(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",fi(e)),setSessionId:L(e.setSessionId.bind(e),"setSessionId",fi(e)),getSessionId:L(e.getSessionId.bind(e),"getSessionId",fi(e)),getSessionReplayProperties:L(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",fi(e)),flush:L(e.flush.bind(e),"flush",fi(e)),start:L(e.start.bind(e),"start",fi(e)),stop:L(e.stop.bind(e),"stop",fi(e)),shutdown:L(e.shutdown.bind(e),"shutdown",fi(e))}})();const{init:mi,setSessionId:yi,getSessionId:bi,getSessionReplayProperties:Si,flush:Ii,start:Ci,stop:ki,shutdown:wi,evaluateTargetingAndCapture:Ei}=pi;export{we as S,bi as a,Si as b,Ci as c,ki as d,wi as e,Ii as f,f as g,Ei as h,mi as i,yi as s,yn as t};
|
|
1
|
+
import{_ as e,a as t,b as i,c as n,d as s,e as r,f as o,g as a,o as l}from"./targeting-min.js";function c(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}var d,u;!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"}(d||(d={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(u||(u={}));var h,g="$default_instance",v="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(h||(h={}));var f=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},p=e([],t(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),m=function(i){var n,s=f();if(!(null===(n=null==s?void 0:s.crypto)||void 0===n?void 0:n.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)}(i);var r=s.crypto.getRandomValues(new Uint8Array(16));return r[6]=15&r[6]|64,r[8]=63&r[8]|128,e([],t(r.entries()),!1).map(function(e){var i=t(e,2),n=i[0],s=i[1];return[4,6,8,10].includes(n)?"-".concat(p[s]):p[s]}).join("")},y={},b={get exports(){return y},set exports(e){y=e}},S=Object.prototype.hasOwnProperty;function I(e){return"[Throws: "+(e?e.message:"?")+"]"}function C(e){var t=[];return function e(i){if(null===i||"object"!=typeof i)return i;if(-1!==t.indexOf(i))return"[Circular]";if(t.push(i),"function"==typeof i.toJSON)try{var n=e(i.toJSON());return t.pop(),n}catch(e){return I(e)}if(Array.isArray(i)){var s=i.map(e);return t.pop(),s}var r=Object.keys(i).reduce(function(t,n){return t[n]=e(function(e,t){if(S.call(e,t))try{return e[t]}catch(e){return I(e)}return e[t]}(i,n)),t},{});return t.pop(),r}(e)}b.exports=function(e,t,i){return JSON.stringify(C(e),t,i)};var w,E=y.ensureProperties=C,P=y||c({__proto__:null,ensureProperties:E,get default(){return y}},[y]),k=function(e){return{promise:e||Promise.resolve()}};!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Verbose=3]="Verbose",e[e.Debug=4]="Debug"}(w||(w={}));var M="Amplitude Logger ",O=function(){function e(){this.logLevel=w.None}return e.prototype.disable=function(){this.logLevel=w.None},e.prototype.enable=function(e){void 0===e&&(e=w.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<w.Verbose||console.log("".concat(M,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<w.Warn||console.warn("".concat(M,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<w.Error||console.error("".concat(M,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<w.Debug||console.log("".concat(M,"[Debug]: ").concat(e.join(" ")))},e}(),T=function(e){return void 0===e||""===e?g:e},F=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:g,logLevel:w.Warn,loggerProvider:new O,offline:!1,optOut:!1,serverUrl:v,serverZone:"US",useBatch:!1}},R=function(){function e(e){var t,i,n,s;this._optOut=!1;var r=F();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:r.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||r.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||r.flushQueueSize,this.instanceName=T(e.instanceName),this.loggerProvider=e.loggerProvider||r.loggerProvider,this.logLevel=null!==(i=e.logLevel)&&void 0!==i?i:r.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:r.offline,this.optOut=null!==(n=e.optOut)&&void 0!==n?n:r.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||r.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(s=e.useBatch)&&void 0!==s?s:r.useBatch,this.loggerProvider.enable(this.logLevel);var o=_(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=o.serverZone,this.serverUrl=o.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),x=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":v},_=function(e,t,i){if(void 0===e&&(e=""),void 0===t&&(t=F().serverZone),void 0===i&&(i=F().useBatch),e)return{serverUrl:e,serverZone:void 0};var n=["US","EU"].includes(t)?t:F().serverZone;return{serverZone:n,serverUrl:x(n,i)}};var L=function(e,t,i,n,s){return void 0===s&&(s=null),function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var a=i(),l=a.logger,c=a.logLevel;if(c&&c<w.Debug||!c||!l)return e.apply(s,r);var d,u={type:"invoke public method",name:t,args:r,stacktrace:(d=1,void 0===d&&(d=0),((new Error).stack||"").split("\n").slice(2+d).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};n&&u.states&&(u.states.before=n());var h=e.apply(s,r);return h&&h.promise?h.promise.then(function(){n&&u.states&&(u.states.after=n()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))}):(n&&u.states&&(u.states.after=n()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))),h}};class q{getApplicationContext(){return{versionName:this.versionName,language:A(),platform:"Web",os:void 0,deviceModel:void 0}}}const A=()=>"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||"";class D{constructor(){this.queue=[]}logEvent(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)}setEventReceiver(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(t=>{e(t)}),this.queue=[])}}const $=(e,t)=>{const i=["string","number","boolean","undefined"],n=typeof e;if(n!==typeof t)return!1;for(const s of i)if(s===n)return e===t;if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;const s=Array.isArray(e),r=Array.isArray(t);if(s!==r)return!1;if(!s||!r){const i=Object.keys(e).sort(),n=Object.keys(t).sort();if(!$(i,n))return!1;let s=!0;return Object.keys(e).forEach(i=>{$(e[i],t[i])||(s=!1)}),s}for(let i=0;i<e.length;i++)if(!$(e[i],t[i]))return!1;return!0};Object.entries||(Object.entries=function(e){const t=Object.keys(e);let i=t.length;const n=new Array(i);for(;i--;)n[i]=[t[i],e[t[i]]];return n});class j{constructor(){this.identity={userProperties:{}},this.listeners=new Set}editIdentity(){const e=this,t=Object.assign({},this.identity.userProperties),i=Object.assign(Object.assign({},this.identity),{userProperties:t});return{setUserId:function(e){return i.userId=e,this},setDeviceId:function(e){return i.deviceId=e,this},setUserProperties:function(e){return i.userProperties=e,this},setOptOut(e){return i.optOut=e,this},updateUserProperties:function(e){let t=i.userProperties||{};for(const[i,n]of Object.entries(e))switch(i){case"$set":for(const[e,i]of Object.entries(n))t[e]=i;break;case"$unset":for(const e of Object.keys(n))delete t[e];break;case"$clearAll":t={}}return i.userProperties=t,this},commit:function(){return e.setIdentity(i),this}}}getIdentity(){return Object.assign({},this.identity)}setIdentity(e){const t=Object.assign({},this.identity);this.identity=Object.assign({},e),$(t,this.identity)||this.listeners.forEach(t=>{t(e)})}addIdentityListener(e){this.listeners.add(e)}removeIdentityListener(e){this.listeners.delete(e)}}const N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self;class U{constructor(){this.identityStore=new j,this.eventBridge=new D,this.applicationContextProvider=new q}static getInstance(e){return N.analyticsConnectorInstances||(N.analyticsConnectorInstances={}),N.analyticsConnectorInstances[e]||(N.analyticsConnectorInstances[e]=new U),N.analyticsConnectorInstances[e]}}var B=function(e){var t=0;if(0===e.length)return t;for(var i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t|=0}return t},W=function(){function e(){}return e.prototype.send=function(e,t,i){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,i,n,s,r,o,a,l,c,d,u,g,v,f,p,m,y,b,S,I,C,w;if("object"!=typeof e)return null;var E=e.code||0,P=this.buildStatus(E);switch(P){case h.Success:return{status:P,statusCode:E,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(i=e.payload_size_bytes)&&void 0!==i?i:0,serverUploadTime:null!==(n=e.server_upload_time)&&void 0!==n?n:0}};case h.Invalid:return{status:P,statusCode:E,body:{error:null!==(s=e.error)&&void 0!==s?s:"",missingField:null!==(r=e.missing_field)&&void 0!==r?r:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(d=e.exceeded_daily_quota_devices)&&void 0!==d?d:{},silencedDevices:null!==(u=e.silenced_devices)&&void 0!==u?u:[],silencedEvents:null!==(g=e.silenced_events)&&void 0!==g?g:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case h.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case h.RateLimit:return{status:P,statusCode:E,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(b=e.throttled_devices)&&void 0!==b?b:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},exceededDailyQuotaDevices:null!==(I=e.exceeded_daily_quota_devices)&&void 0!==I?I:{},exceededDailyQuotaUsers:null!==(C=e.exceeded_daily_quota_users)&&void 0!==C?C:{},throttledEvents:null!==(w=e.throttled_events)&&void 0!==w?w:[]}};case h.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?h.Success:429===e?h.RateLimit:413===e?h.PayloadTooLarge:408===e?h.Timeout:e>=400&&e<500?h.Invalid:e>=500?h.Failed:h.Unknown},e}(),z=function(e){function t(t){void 0===t&&(t={});var i=e.call(this)||this;return i.customHeaders=t,i}return i(t,e),t.prototype.send=function(e,t){return n(this,void 0,void 0,function(){var i,n,o;return s(this,function(s){switch(s.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return i={headers:r({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,i)];case 1:return[4,(n=s.sent()).text()];case 2:o=s.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:n.status})]}return[2]}})})},t}(W),H=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t;try{this.isSupported="undefined"!=typeof localStorage}catch(e){this.logger.debug("Remote config localstorage failed to access: ",e),this.isSupported=!1}}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};if(!this.isSupported)return Promise.resolve(t);try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var i=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(P(i))),Promise.resolve({remoteConfig:i.remoteConfig,lastFetch:new Date(i.lastFetch)})}catch(e){return this.logger.debug("Remote config localstorage failed to parse: ",e),localStorage.removeItem(this.key),Promise.resolve(t)}},e.prototype.setConfig=function(e){if(!this.isSupported)return Promise.resolve(!1);try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}();var K,G=401,Q=403,J=429,Z=function(){function e(t,i,n,s,r,o,a){void 0===n&&(n="US"),void 0===o&&(o=e.DEFAULT_CONFIG_GROUP),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=t,this.configGroup=o,this.serverUrl=s||("US"===n?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=i,this.storage=a||new H(t,i),this.customFetch=r}return e.prototype.subscribe=function(e,t,i){var n=m(),s={id:n,key:e,deliveryMode:t,callback:i};return this.callbackInfos.push(s),"all"===t?this.subscribeAll(s):this.subscribeWaitForRemote(s,t.timeout),n},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 n(this,void 0,void 0,function(){var e,t=this;return s(this,function(i){switch(i.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=i.sent(),this.storage.setConfig(e),this.callbackInfos.forEach(function(i){t.sendCallback(i,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 n(this,void 0,void 0,function(){var t,i,n,r=this;return s(this,function(s){switch(s.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){r.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),r.sendCallback(e,t,"remote"),r.storage.setConfig(t)}),i=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,i])];case 1:return void 0!==(n=s.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(n))),null!==n.remoteConfig?this.sendCallback(e,n,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return s.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return n(this,void 0,void 0,function(){var i,n;return s(this,function(s){switch(s.label){case 0:i=new Promise(function(e,i){setTimeout(function(){i("Timeout exceeded")},t)}),s.label=1;case 1:return s.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),i])];case 2:return n=s.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,n,"remote"),this.storage.setConfig(n),[3,5];case 3:return s.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!==(n=s.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,n,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,n,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,i){var n;e.lastCallback=new Date,n=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(n,i,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),n(this,void 0,void 0,function(){var i,n,r,o,a,l,c=this;return s(this,function(d){switch(d.label){case 0:i=t/e,n={remoteConfig:null,lastFetch:new Date},r=function(n){var r,a,l,d,u,h,g,v,f;return s(this,function(s){switch(s.label){case 0:r=!0,a=new AbortController,l=setTimeout(function(){return a.abort()},t),s.label=1;case 1:return s.trys.push([1,10,11,12]),d=o.getUrlParams(),u={Accept:"*/*"},o.customFetch?[4,(p=o.customFetch({url:d,method:"GET",headers:u,signal:a.signal}),m=a.signal,new Promise(function(e,t){var i=function(){var e=new Error("Remote config custom fetch aborted by timeout");e.name="AbortError",t(e)};m.addEventListener("abort",i,{once:!0}),p.then(function(t){m.removeEventListener("abort",i),e(t)},function(e){m.removeEventListener("abort",i),t(e)})}))]:[3,3];case 2:return g=s.sent(),[3,5];case 3:return[4,fetch(d,{method:"GET",headers:u,signal:a.signal})];case 4:g=s.sent(),s.label=5;case 5:return(h=g).ok||h.status>=200&&h.status<300?[3,7]:[4,h.text()];case 6:return v=s.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(h.status,": ").concat(v)),h.status===G||h.status===Q?(o.logger.error("Remote config client fetch failed with ".concat(h.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,r=!1):h.status>=400&&h.status<500&&h.status!==J&&(r=!1),[3,9];case 7:return[4,h.json()];case 8:return[2,{value:{remoteConfig:s.sent(),lastFetch:new Date}}];case 9:return[3,12];case 10:return(f=s.sent())instanceof Error&&"AbortError"===f.name?o.logger.debug("Remote config client fetch with retry time ".concat(e," timed out after ").concat(t,"ms")):o.logger.debug("Remote config client fetch with retry time ".concat(e," is rejected because: "),f),[3,12];case 11:return clearTimeout(l),[7];case 12:return r?n<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(i))})]:[3,14]:[2,"break"];case 13:s.sent(),s.label=14;case 14:return[2]}var p,m})},o=this,a=0,d.label=1;case 1:return a<e?[5,r(a)]:[3,4];case 2:if("object"==typeof(l=d.sent()))return[2,l.value];if("break"===l)return[3,4];d.label=3;case 3:return a++,[3,1];case 4:return[2,n]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var e=encodeURIComponent(this.apiKey),t=new URLSearchParams;return t.append("config_group",this.configGroup),"".concat(this.serverUrl,"/").concat(e,"?").concat(t.toString())},e.DEFAULT_CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(K||(K={}));var X,V="https://app.amplitude.com",Y={US:V,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var ee="__AMPLITUDE_MESSENGER_INSTANCE__",te="__AMPLITUDE_MESSENGER__",ie=function(){function e(e){var t=(void 0===e?{}:e).origin,i=void 0===t?V:t;this[X]=!0,this.isSetup=!1,this.messageHandler=null,this.requestCallbacks={},this.actionHandlers=new Map,this.pendingMessages=new Map,this.scriptLoadPromises=new Map,this.endpoint=i}return e.prototype.notify=function(e){var t,i,n,s;null===(i=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===i||i.call(t,"Message sent: ",JSON.stringify(e)),null===(s=null===(n=window.opener)||void 0===n?void 0:n.postMessage)||void 0===s||s.call(n,e,this.endpoint)},e.prototype.sendRequest=function(e,t,i){var n=this;void 0===i&&(i={timeout:15e3});var s="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),r={id:s,action:e,args:t};return new Promise(function(t,o){n.requestCallbacks[s]={resolve:t,reject:o},n.notify(r),i.timeout>0&&setTimeout(function(){o(new Error("".concat(e," timed out (id: ").concat(s,")"))),delete n.requestCallbacks[s]},i.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 i,n,s,r;this.actionHandlers.has(e)&&(null===(r=null===(s=this.logger)||void 0===s?void 0:s.warn)||void 0===r||r.call(s,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var a=this.pendingMessages.get(e);if(a){this.pendingMessages.delete(e);try{for(var l=o(a),c=l.next();!c.done;c=l.next()){t(c.value)}}catch(e){i={error:e}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}},e.prototype.loadScriptOnce=function(e){return n(this,void 0,void 0,function(){var t,i,n;return s(this,function(s){switch(s.label){case 0:if(t=this.scriptLoadPromises.get(e))return[2,t];i=function(e){return document.querySelector('script[src="'.concat(CSS.escape(e),'"]'))?Promise.resolve({status:!0}):new Promise(function(t,i){var n;try{var s=document.createElement("script");s.type="text/javascript",s.async=!0,s.src=e,s.addEventListener("load",function(){t({status:!0})},{once:!0}),s.addEventListener("error",function(){i({status:!1,message:"Failed to load the script ".concat(e)})}),null===(n=document.head)||void 0===n||n.appendChild(s)}catch(e){i(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,i),s.label=1;case 1:return s.trys.push([1,3,,4]),[4,i];case 2:return s.sent(),[3,4];case 3:throw n=s.sent(),this.scriptLoadPromises.delete(e),n;case 4:return[2]}})})},e.prototype.setup=function(e){var t,i,n=this,s=void 0===e?{}:e,r=s.logger,o=s.endpoint;r&&(this.logger=r),o&&this.endpoint===V&&(this.endpoint=o),this.isSetup||(this.isSetup=!0,null===(i=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===i||i.call(t,"Setting up messenger"),this.messageHandler=function(e){var t,i,s,r,o;if(null===(i=null===(t=n.logger)||void 0===t?void 0:t.debug)||void 0===i||i.call(t,"Message received: ",JSON.stringify(e)),n.endpoint===e.origin){var a=e.data,l=null==a?void 0:a.action;if(l)if("id"in a&&a.id)null===(r=null===(s=n.logger)||void 0===s?void 0:s.debug)||void 0===r||r.call(s,"Received Response to previous request: ",JSON.stringify(e)),n.handleResponse(a);else{if("ping"===l)return void n.notify({action:"pong"});var c=n.actionHandlers.get(l);if(c)c(a.data);else{var d=null!==(o=n.pendingMessages.get(l))&&void 0!==o?o:[];d.push(a.data),n.pendingMessages.set(l,d)}}}},window.addEventListener("message",this.messageHandler),this.notify({action:"page-loaded"}))},e.prototype.destroy=function(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.isSetup=!1,this.actionHandlers.clear(),this.pendingMessages.clear(),this.requestCallbacks={},this.scriptLoadPromises.clear();var e=f();(null==e?void 0:e[te])===this&&delete e[te]},e}();function ne(e){var t,i=f(),n=null==i?void 0:i[te];if("object"==typeof(t=n)&&null!==t&&ee in t&&!0===t[ee])return n;var s=new ie(e);return i&&(i[te]=s),s}X=ee;var se=["desktop","tablet","mobile"],re="__AMPLITUDE_BACKGROUND_CAPTURE__";function oe(e,t){var i,n=e;if(!0!==n[re]){n[re]=!0;var s=null!==(i=null==t?void 0:t.scriptUrl)&&void 0!==i?i:"https://cdn.amplitude.com/libs/background-capture-1.1.0.js.gz",o=null,a=function(t,i){var n,s;"background-capture-complete"===t&&(null===(s=null===(n=e.logger)||void 0===n?void 0:n.debug)||void 0===s||s.call(n,"Background capture complete"),e.notify({action:"background-capture-complete",data:i}))};e.registerActionHandler("initialize-background-capture",function(t){var i,n;null===(n=null===(i=e.logger)||void 0===i?void 0:i.debug)||void 0===n||n.call(i,"Initializing background capture (external script)");var l=new URL(s,e.endpoint).toString(),c=t&&"object"==typeof t?function(e){if("string"==typeof e)return se.includes(e)?e:void 0}(t.deviceMode):void 0;e.loadScriptOnce(l).then(function(){var t,i,n;null===(i=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===i||i.call(t,"Background capture script loaded (external)"),o=null===(n=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===n?void 0:n.call(window,r({messenger:e,onBackgroundCapture:a},void 0!==c?{initialDeviceMode:c}:{})),e.notify({action:"background-capture-loaded"})}).catch(function(){var t;null===(t=e.logger)||void 0===t||t.warn("Failed to initialize background capture")})}),e.registerActionHandler("close-background-capture",function(){var e;null===(e=null==o?void 0:o.close)||void 0===e||e.call(o),o=null})}}const ae="[Amplitude]",le=`${ae} Session Replay ID`,ce=K.US,de={enabled:!0},ue=1e3,he=`${ae} Session Replay Debug`,ge="https://api-sr.amplitude.com/sessions/v2/track",ve="https://api-sr.eu.amplitude.com/sessions/v2/track",fe="https://api-sr.stag2.amplitude.com/sessions/v2/track",pe=9e6,me=/payload.*exceed/i,ye=500,be=1e4,Se=1024,Ie="X-Session-Replay-Event-Skipped",Ce="amplitude-sr-iframe";var we;!function(e){e.GET_SR_PROPS="get-sr-props",e.DEBUG_INFO="debug-info",e.FETCH_REQUEST="fetch-request",e.METADATA="metadata",e.TARGETING_DECISION="targeting-decision",e.REPLAY_GATE_DECISION="replay-gate-decision"}(we||(we={}));class Ee{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const i=this.logger[e];if("function"==typeof i){return(null!==(t=i.__rrweb_original__)&&void 0!==t?t:i).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}var Pe="medium";var ke=new Map,Me=function(e){var t=ke.get(e);if(t)return t;var i="\0TRAIL\0",n="\0MID\0",s="\0DS\0",r="\0ST\0",o="\0QU\0",a=e;a=(a=(a=(a=(a=(a=(a=(a=(a=(a=(a=a.replace(/\/\*\*$/,i)).replace(/\/\*\*\//g,n)).replace(/\*\*/g,s)).replace(/\*/g,r)).replace(/\?/g,o)).replace(/[.+^${}()|[\]\\]/g,"\\$&")).split(i).join("(/.*)?")).split(n).join("/(.*\\/)?")).split(s).join(".*")).split(r).join(".*")).split(o).join(".");var l=new RegExp("^".concat(a,"$"));return ke.set(e,l),l},Oe=function(e,t,i){switch(t){case"light":if("input"!==e)return!1;var n=i?function(e){var t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(i):"";return!!n&&(!!["password","hidden","email","tel"].includes(n)||!!i.autocomplete.startsWith("cc-"));case"medium":return"input"===e;case"conservative":return!0;default:return Oe(e,Pe,i)}},Te=function(e,t){var i,n,s;if(e&&t.urlMaskLevels)try{for(var r=o(t.urlMaskLevels),a=r.next();!a.done;a=r.next()){var l=a.value;if(Me(l.match).test(e))return l.maskLevel}}catch(e){i={error:e}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return null!==(s=t.defaultMaskLevel)&&void 0!==s?s:Pe},Fe=function(e,t,i,n){var s,r;if(void 0===t&&(t={defaultMaskLevel:Pe}),i){if(i.closest(".amp-mask, [data-amp-mask]"))return!0;var o=(null!==(s=t.maskSelector)&&void 0!==s?s:[]).some(function(e){return i.closest(e)});if(o)return!0;if(i.closest(".amp-unmask, [data-amp-unmask]"))return!1;var a=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some(function(e){return i.closest(e)});if(a)return!1}return Oe(e,Te(n,t),i)},Re=function(e,t,i){return function(n,s){return Fe(e,t,s,null==i?void 0:i())?n.replace(/[^\s]/g,"*"):n}},xe=function(e,t){return function(i,n,s){var r;if("style"===i)return n;if(!(null!==(r=null==e?void 0:e.maskAttributes)&&void 0!==r?r:[]).includes(i))return n;var o=["INPUT","SELECT","TEXTAREA"].includes(s.tagName)?"input":"text";return Fe(o,e,s,null==t?void 0:t())?n.replace(/[^\s]/g,"*"):n}},_e=function(i){var n=null==i?void 0:i.blockSelector;return e(e([],t("string"==typeof n?n?[n]:[]:null!=n?n:[]),!1),["[data-amp-block]"],!1).join(",")},Le=function(i,n){var s,r;return i&&("conservative"===Te(n,i)||"conservative"===i.defaultMaskLevel||(null===(s=i.urlMaskLevels)||void 0===s?void 0:s.some(function(e){return"conservative"===e.maskLevel})))?"*":e(e([],t(null!==(r=null==i?void 0:i.maskSelector)&&void 0!==r?r:[]),!1),["[data-amp-mask]"],!1).join(",")};function qe(e,t){return t||("STAGING"===e?fe:"EU"===e?ve:ge)}const Ae=()=>{const e=f();return(null==e?void 0:e.location)?e.location.href:""},De=(e,t)=>{for(const i of t){const t=Me(i.selector);if(t.test(e))return e.replace(t,i.replacement)}return e},$e=()=>n(void 0,void 0,void 0,function*(){try{const e=f();if(e){const{usage:t,quota:i,usageDetails:n}=yield e.navigator.storage.estimate(),s=t?Math.round(t/Se):0;return{totalStorageSize:s,percentOfQuota:t&&i?Math.round(1e3*(t/i+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(n)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}}),je=e=>{const t=a(e,["loggerProvider"]),i=Object.assign(Object.assign({},t),{apiKey:`****${e.apiKey.substring(e.apiKey.length-4)}`});return JSON.parse(JSON.stringify(i))},Ne=()=>({flushMaxRetries:2,logLevel:w.Warn,loggerProvider:new O,transportProvider:new z});class Ue extends R{constructor(e,t){var i,n,s,r,o,a,l,c,d,u,h,g,v,f;const p=Ne();super(Object.assign(Object.assign({transportProvider:p.transportProvider,loggerProvider:new Ee(t.loggerProvider||p.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=p.flushMaxRetries?t.flushMaxRetries:p.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.semanticCapture=t.semanticCapture,this.semanticAnalyticsContext=t.semanticAnalyticsContext,this.serverZone=t.serverZone||ce,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.inlineImages=t.inlineImages,this.version=t.version,this.performanceConfig=t.performanceConfig||de,this.storeType=null!==(i=t.storeType)&&void 0!==i?i:"memory",this.applyBackgroundColorToBlockedElements=null!==(n=t.applyBackgroundColorToBlockedElements)&&void 0!==n&&n,this.enableUrlChangePolling=null!==(s=t.enableUrlChangePolling)&&void 0!==s&&s,this.urlChangePollingInterval=null!==(r=t.urlChangePollingInterval)&&void 0!==r?r:ue,this.captureDocumentTitle=null!==(o=t.captureDocumentTitle)&&void 0!==o&&o,void 0!==t.fullSnapshotIntervalMs&&(this.fullSnapshotIntervalMs=t.fullSnapshotIntervalMs),void 0!==t.eagerFullSnapshotSend&&(this.eagerFullSnapshotSend=t.eagerFullSnapshotSend),this.captureFullSnapshotOnFocus=null!==(a=t.captureFullSnapshotOnFocus)&&void 0!==a&&a,void 0!==t.maxPersistedEventsSizeBytes&&(this.maxPersistedEventsSizeBytes=Ke(t.maxPersistedEventsSizeBytes,We,ze,"maxPersistedEventsSizeBytes",this.loggerProvider)),void 0!==t.maxSingleEventSizeBytes&&(this.maxSingleEventSizeBytes=Ke(t.maxSingleEventSizeBytes,We,He,"maxSingleEventSizeBytes",this.loggerProvider)),this.privacyConfig=Object.assign(Object.assign({},null!==(l=t.privacyConfig)&&void 0!==l?l:{}),{unmaskSelector:Array.from(new Set([".amp-unmask",...null!==(d=null===(c=t.privacyConfig)||void 0===c?void 0:c.unmaskSelector)&&void 0!==d?d:[]]))}),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every(e=>"string"==typeof e.selector&&"string"==typeof e.replacement))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every(e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t}))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode);const m=t;this.useWebWorker=null===(g=null!==(u=t.useWebWorker)&&void 0!==u?u:null===(h=m.experimental)||void 0===h?void 0:h.useWebWorker)||void 0===g||g,this.enableTransportCompression=null===(v=t.enableTransportCompression)||void 0===v||v,this.sendTimeoutMs=t.sendTimeoutMs,this.captureAdoptedStyleSheets=null===(f=t.captureAdoptedStyleSheets)||void 0===f||f,t.crossOriginIframes&&(this.crossOriginIframes=t.crossOriginIframes),t.flushIntervalConfig?this.flushIntervalConfig=function(e,t){var i,n;const s={};void 0!==e.minIntervalMs&&(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<Be?(t.warn(`flushIntervalConfig.minIntervalMs ${e.minIntervalMs} is below floor ${Be}ms; clamping.`),s.minIntervalMs=Be):s.minIntervalMs=e.minIntervalMs);void 0!==e.maxIntervalMs&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<Be?(t.warn(`flushIntervalConfig.maxIntervalMs ${e.maxIntervalMs} is below floor ${Be}ms; clamping.`),s.maxIntervalMs=Be):s.maxIntervalMs=e.maxIntervalMs);if(void 0!==s.minIntervalMs||void 0!==s.maxIntervalMs){const e=null!==(i=s.minIntervalMs)&&void 0!==i?i:ye,r=null!==(n=s.maxIntervalMs)&&void 0!==n?n:be;r<e&&(void 0===s.maxIntervalMs?(t.warn(`flushIntervalConfig.minIntervalMs (${e}) exceeds the default maxIntervalMs (10000); raising max to match min.`),s.maxIntervalMs=e):void 0===s.minIntervalMs?(t.warn(`flushIntervalConfig.maxIntervalMs (${r}) is below the default minIntervalMs (500); lowering min to match max.`),s.minIntervalMs=r):(t.warn(`flushIntervalConfig.maxIntervalMs (${s.maxIntervalMs}) is less than minIntervalMs (${s.minIntervalMs}); raising max to match min.`),s.maxIntervalMs=s.minIntervalMs))}return s}(t.flushIntervalConfig,this.loggerProvider):this.flushIntervalConfig={minIntervalMs:1e3,maxIntervalMs:1e4},this.handleSendEvents=t.handleSendEvents,this.handleFetchConfig=t.handleFetchConfig}}const Be=100,We=1e3,ze=8e6,He=1e7;function Ke(e,t,i,n,s){if(Number.isFinite(e))return e<t?(s.warn(`${n} ${e} is below floor ${t}; clamping.`),t):e>i?(s.warn(`${n} ${e} exceeds ceiling ${i}; clamping.`),i):e;s.warn(`${n} value is not a finite number (got ${String(e)}); ignoring.`)}var Ge=(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))(Ge||{}),Qe=(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))(Qe||{}),Je=(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))(Je||{});class Ze{constructor(e,t){this.createCapture=e,this.ready=!1,this.pendingSnapshots=0,this.config={enabled:!1},this.capture=e(this.config,t)}prepare(e,t){this.stop(),this.config=e,this.capture.updateConfig(e),this.sessionId!==t&&this.capture.resetSession(),this.sessionId=t}recordingReady(){if(!this.config.enabled||this.ready)return;this.ready=!0,this.capture.start();const e=this.pendingSnapshots;this.pendingSnapshots=0;for(let t=0;t<e;t++)this.snapshot()}event(e){e.type===Ge.FullSnapshot&&this.snapshot()}snapshot(){this.config.enabled&&(this.ready?this.capture.isActive()&&this.capture.notify("snapshot",void 0):this.pendingSnapshots=Math.min(this.pendingSnapshots+1,200))}stop(){this.ready=!1,this.pendingSnapshots=0,this.capture.stop()}}const Xe="AMP_semantic_tab_v1",Ve=new WeakMap,Ye=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;const et=(e,t)=>{const i=document.createDocumentFragment();return function(e,t,i){var n,s,a=r({},e);try{for(var l=o(["blockSelector","maskSelector","unmaskSelector"]),c=l.next();!c.done;c=l.next()){var d=c.value,u=e[d],h=("string"==typeof u?[u]:null!=u?u:[]).filter(function(e){try{return t(e),!0}catch(t){if(!i)throw new Error("Invalid privacy selector: ".concat(e));return i(e),!1}});a[d]=h.length?h:void 0}}catch(e){n={error:e}}finally{try{c&&!c.done&&(s=l.return)&&s.call(l)}finally{if(n)throw n.error}}return a}(e,e=>{i.querySelector(e)},e=>{t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`)})};class tt{constructor(e,t){this.localConfig=t,this.remoteConfigClient=e}generateJoinedConfig(){var e,t,i,s,r,o,a,l;return n(this,void 0,void 0,function*(){const n=Object.assign({},this.localConfig);let c;n.optOut=this.localConfig.optOut,n.captureEnabled=!0;try{yield new Promise((e,t)=>{this.remoteConfigClient.subscribe("configs.sessionReplay",{timeout:1500},(i,s)=>{var r;if(this.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${s}:`,JSON.stringify(i,null,2)),!i)return void t(new Error("No remote config received"));const o=i,a=o.sr_sampling_config,l=o.sr_privacy_config,d=o.sr_targeting_config,u=o.sr_semantic_config,h=null===(r=n.interactionConfig)||void 0===r?void 0:r.ugcFilterRules;n.interactionConfig=o.sr_interaction_config,n.interactionConfig&&h&&(n.interactionConfig.ugcFilterRules=h),n.loggingConfig=o.sr_logging_config,(a||l||d||u)&&(c={},u&&(c.sr_semantic_config=u),a&&(c.sr_sampling_config=a),l&&(c.sr_privacy_config=l),d&&(c.sr_targeting_config=d)),e()})})}catch(e){return this.localConfig.loggerProvider.error("Failed to generate joined config: ",e),n.captureEnabled=!1,{localConfig:this.localConfig,joinedConfig:n,remoteConfig:void 0}}if(!c)return{localConfig:this.localConfig,joinedConfig:n,remoteConfig:c};const{sr_sampling_config:d,sr_privacy_config:u,sr_targeting_config:h,sr_semantic_config:g}=c;if(g&&(n.semanticCapture=Object.assign(Object.assign(Object.assign(Object.assign({enabled:!1},n.semanticCapture),void 0!==g.enabled?{enabled:g.enabled}:{}),void 0!==g.sampleRate?{sampleRate:this.sanitizeSemanticSampleRate(g.sampleRate)}:{}),{families:Object.assign(Object.assign({},null===(e=n.semanticCapture)||void 0===e?void 0:e.families),g.families)})),d&&Object.keys(d).length>0?(Object.prototype.hasOwnProperty.call(d,"capture_enabled")?n.captureEnabled=d.capture_enabled:n.captureEnabled=!1,Object.prototype.hasOwnProperty.call(d,"sample_rate")&&(n.sampleRate=d.sample_rate),Object.prototype.hasOwnProperty.call(d,"min_session_duration_ms")&&(n.minSessionDurationMs=this.sanitizeMinSessionDurationMs(d.min_session_duration_ms))):(n.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),u){const e=null!==(t=n.privacyConfig)&&void 0!==t?t:{},c={defaultMaskLevel:null!==(s=null!==(i=u.defaultMaskLevel)&&void 0!==i?i:e.defaultMaskLevel)&&void 0!==s?s:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:[...new Set([...null!==(r=e.maskAttributes)&&void 0!==r?r:[],...null!==(o=u.maskAttributes)&&void 0!==o?o:[]])],urlMaskLevels:[...null!==(a=u.urlMaskLevels)&&void 0!==a?a:[],...null!==(l=e.urlMaskLevels)&&void 0!==l?l:[]]},d=e=>{var t,i,n;const s={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const i of null!==(t=e.blockSelector)&&void 0!==t?t:[])s[i]="block";for(const t of null!==(i=e.maskSelector)&&void 0!==i?i:[])s[t]="mask";for(const t of null!==(n=e.unmaskSelector)&&void 0!==n?n:[])s[t]="unmask";return s},h=Object.assign(Object.assign({},d(e)),d(u));for(const[e,t]of Object.entries(h))"mask"===t?c.maskSelector.push(e):"block"===t?c.blockSelector.push(e):"unmask"===t&&c.unmaskSelector.push(e);n.privacyConfig=et(c,this.localConfig.loggerProvider)}return h&&Object.keys(h).length>0&&(n.targetingConfig=h),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:je(n)},null,2)),{localConfig:this.localConfig,joinedConfig:n,remoteConfig:c}})}sanitizeSemanticSampleRate(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1?e:(this.localConfig.loggerProvider.warn(`Invalid semantic sampleRate remote value (${String(e)}); disabling capture.`),0)}sanitizeMinSessionDurationMs(e){if("number"==typeof e&&Number.isFinite(e)){if(!(e<0))return e>it?(this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value ${e} exceeds ${it}ms ceiling; clamping.`),it):e;this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value is negative (${e}); ignoring.`)}else this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value is not a finite number (got ${String(e)}); ignoring.`)}}const it=6e4;function nt(e){const t=e.length;let i=0;for(;i<t&&!(e.charCodeAt(i)>127);i++);if(i===t)return t;let n=i;for(;i<t;i++){const s=e.charCodeAt(i);if(s<=127)n++;else if(s<=2047)n+=2;else if(s>=55296&&s<=56319){const s=i+1<t?e.charCodeAt(i+1):NaN;s>=56320&&s<=57343?(n+=4,i++):n+=3}else n+=3}return n}function st(e){let t=0;for(let i=0;i<e.length;i++)t+=nt(e[i]);return t}function rt(e,t){if(3*e.length<=t)return;const i=nt(e);return i>t?i:void 0}function ot(e,t){t<0&&(t=0);const i=e.length;let n=0,s=0;for(;s<i;s++){const r=e.charCodeAt(s);let o=1,a=1;if(r<=127)o=1;else if(r<=2047)o=2;else if(r>=55296&&r<=56319){const t=s+1<i?e.charCodeAt(s+1):NaN;t>=56320&&t<=57343?(o=4,a=2):o=3}else o=3;if(n+o>t)break;n+=o,2===a&&s++}return s>=i?{value:e,truncated:!1}:{value:e.slice(0,s),truncated:!0}}function at(e){if(e.type!==Ge.IncrementalSnapshot)return!1;const t=e.data;return t.source===Qe.Mutation&&!t.isAttachIframe}function lt(e){const t={};for(const i of e)for(const e of Object.keys(i))t[e]=i[e];return t}function ct(e){const t=new Map;if(e.forEach((e,i)=>{if(e.attributes&&"style"in e.attributes){const n=t.get(e.id);n?n.push(i):t.set(e.id,[i])}}),0===t.size)return e;const i=t=>e[t].attributes.style,n=new Set,s=new Map;for(const e of t.values()){if(1===e.length)continue;let t=-1;e.forEach((e,n)=>{var s;("object"!=typeof(s=i(e))||null===s)&&(t=n)});const r=[];if(e.forEach((e,i)=>{i!==t&&(n.add(e),i>t&&r.push(e))}),r.length>0){const e=r[r.length-1],t=lt(r.map(e=>i(e)));n.delete(e),s.set(e,t)}}if(0===n.size&&0===s.size)return e;const r=[];return e.forEach((e,t)=>{const i=s.get(t);if(void 0!==i)return void r.push(Object.assign(Object.assign({},e),{attributes:Object.assign(Object.assign({},e.attributes),{style:i})}));if(!n.has(t))return void r.push(e);const o=Object.assign({},e.attributes);delete o.style,Object.keys(o).length>0&&r.push(Object.assign(Object.assign({},e),{attributes:o}))}),r}function dt(e){const t=e[0],i=new Map,n=new Map,s=new Map,r=new Map,o=new Map;e.forEach((e,t)=>{const a=e.data;for(const e of a.adds)i.has(e.node.id)||i.set(e.node.id,t),n.set(e.node.id,t),o.set(e.node.id,e.parentId);for(const e of a.removes)s.has(e.id)||s.set(e.id,t),r.set(e.id,t)});const a=new Set,l=new Set;for(const[e,t]of i){const i=s.get(e);if(void 0===i)continue;n.get(e)>=r.get(e)||(t<i?a.add(e):i<t&&l.add(e))}const c=new Set;if(a.size>0||l.size>0){let e=!0;for(;e;){e=!1;for(const[t,n]of o)if(!a.has(t)&&!l.has(t)&&!c.has(t)&&(a.has(n)||l.has(n)||c.has(n))){const n=s.get(t),r=i.get(t);void 0!==n&&void 0!==r&&n<r?l.add(t):void 0!==n&&void 0!==r&&n===r?c.add(t):a.add(t),e=!0}}}const d=a.size>0||l.size>0||c.size>0,u=[];e.forEach((e,t)=>{for(const n of e.data.removes)a.has(n.id)||l.has(n.id)&&t>=i.get(n.id)||c.has(n.id)&&(a.has(n.parentId)||l.has(n.parentId)||c.has(n.parentId))||u.push(n)});const h=e.flatMap(e=>e.data.adds),g=e.flatMap(e=>e.data.texts),v=e.flatMap(e=>e.data.attributes),f=d?v.filter(e=>!a.has(e.id)&&!l.has(e.id)&&!c.has(e.id)):v,p={source:Qe.Mutation,removes:u,adds:d?h.filter(e=>!a.has(e.node.id)&&!l.has(e.node.id)&&!c.has(e.node.id)):h,texts:d?g.filter(e=>!a.has(e.id)&&!l.has(e.id)&&!c.has(e.id)):g,attributes:ct(f)};return Object.assign(Object.assign({},t),{data:p})}function ut(e){if(e.length<=1)return e;const t=[];let i=0;for(;i<e.length;){if(!at(e[i])){t.push(e[i]),i++;continue}let n=i+1;for(;n<e.length&&at(e[n]);)n++;t.push(n>i+1?dt(e.slice(i,n)):e[i]),i=n}return t}class ht{constructor(e,t,i,n,s){var r;this.taskQueue=[],this.pendingQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const{type:t,timestamp:i,delay:n,data:s}=e;return null!=n?JSON.stringify({type:t,timestamp:i,delay:n,data:s}):JSON.stringify({type:t,timestamp:i,data:s})},this.addCompressedEventToManager=(e,t)=>{var i;const n=rt(e,null!==(i=this.config.maxSingleEventSizeBytes)&&void 0!==i?i:pe);void 0===n?this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId}):this.config.loggerProvider.warn(`Session replay event dropped: serialized size ${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.`)},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(i){"DataCloneError"===i.name?this.worker.postMessage(JSON.stringify({event:e,sessionId:t})):this.config.loggerProvider.warn("Unexpected error while posting message to worker:",i)}else{const i=this.compressEvent(e);this.addCompressedEventToManager(i,t)}},this.flushQueue=()=>{for(this.pendingQueue.length>0&&this.taskQueue.push(...this.mergeMutationTasks(this.pendingQueue.splice(0)));this.taskQueue.length>0;){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:i}=e,n=this.compressEvent(t);this.addCompressedEventToManager(n,i)}}this.isProcessing=!1},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const o=f();if(this.canUseIdleCallback=o&&"requestIdleCallback"in o,this.eventsManager=e,this.config=t,this.deviceId=i,this.timeout=(null===(r=t.performanceConfig)||void 0===r?void 0:r.timeout)||2e3,this.onFullSnapshotProcessed=s,n){t.loggerProvider.log("Enabling web worker for compression");try{const e=new Blob([n],{type:"application/javascript"}),i=URL.createObjectURL(e),s=new Worker(i);s.onerror=e=>{e.preventDefault(),t.loggerProvider.error(`Worker failed, falling back to non-worker compression: ${e.message} (${e.filename}:${e.lineno})`),s.terminate(),this.worker=void 0},s.onmessage=e=>{const{compressedEvent:t,sessionId:i}=e.data;this.addCompressedEventToManager(t,i)},this.worker=s}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}))}enqueueEvent(e,t){var i,n;if(e.type===Ge.FullSnapshot){if(this.config.loggerProvider.debug("Processing full snapshot immediately."),this.taskQueue.length>0||this.pendingQueue.length>0){const e=[...this.taskQueue.splice(0),...this.mergeMutationTasks(this.pendingQueue.splice(0))];for(const t of e){const e=this.compressEvent(t.event);this.addCompressedEventToManager(e,t.sessionId)}this.isProcessing=!1}const n=this.compressEvent(e);return this.addCompressedEventToManager(n,t),void(null===(i=this.onFullSnapshotProcessed)||void 0===i||i.call(this))}this.canUseIdleCallback&&(null===(n=this.config.performanceConfig)||void 0===n?void 0:n.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.pendingQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(this.pendingQueue.length>0&&this.taskQueue.push(...this.mergeMutationTasks(this.pendingQueue.splice(0)));this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:i}=e;this.addCompressedEvent(t,i)}}this.taskQueue.length>0||this.pendingQueue.length>0?requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1}mergeMutationTasks(e){var t;if(!1===(null===(t=this.config.performanceConfig)||void 0===t?void 0:t.mergeMutations))return e;if(e.length<=1)return e;const i=[];let n=0;for(;n<e.length;){const t=e[n].sessionId;let s=n+1;for(;s<e.length&&e[s].sessionId===t;)s++;const r=ut(e.slice(n,s).map(e=>e.event));for(const e of r)i.push({event:e,sessionId:t});n=s}return i}}const gt="Session replay event batch rejected due to exceeded retry count",vt="Failed to store session replay events in IndexedDB",ft="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",pt="1.52.0";class mt{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:i,workerScript:n,enableTransportCompression:s,sendTimeoutMs:r,handleSendEvents:o}){if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.timedOutWorkerRequests=new Map,this.flushPauseUntilMs=0,this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,this.mergeLogFiredThisPause=!1,this.killedSessions=new Set,this.loggerProvider=t,this.payloadBatcher=i||(e=>e),this.trackServerUrl=e,this.enableTransportCompression=null==s||s,this.sendTimeoutMs=null!=r?r:1e4,this.handleSendEvents=o,n)try{const e=new Blob([n],{type:"application/javascript"}),i=URL.createObjectURL(e),s=new Worker(i);s.onerror=e=>{e.preventDefault(),t.error(`Track destination worker failed, falling back to main-thread sending: ${e.message} (${e.filename}:${e.lineno})`),s.terminate(),this.worker=void 0;for(const[,i]of this.pendingWorkerRequests)i.timeout&&clearTimeout(i.timeout),t.warn(`Session replay event send failed due to worker crash: ${e.message}`),i.resolve();this.pendingWorkerRequests.clear(),this.timedOutWorkerRequests.clear()},s.onmessage=e=>{const i=e.data;if("log"===i.type)t.log(i.message);else if("warn"===i.type)t.warn(i.message);else if("payload_too_large"===i.type){const e=this.pendingWorkerRequests.get(i.id);if(e)e.timeout&&clearTimeout(e.timeout),this.handlePayloadTooLargeResponse(e.context,i.isWaf),e.resolve(),this.pendingWorkerRequests.delete(i.id);else{const e=this.timedOutWorkerRequests.get(i.id);e&&(this.timedOutWorkerRequests.delete(i.id),this.handlePayloadTooLargeResponse(e,i.isWaf))}}else if("complete"===i.type){const e=this.pendingWorkerRequests.get(i.id);if(e)e.timeout&&clearTimeout(e.timeout),void 0!==i.skipCode&&this.applyServerDirective(e.context.sessionId,i.skipCode),this.completeRequest({context:e.context}),e.resolve(),this.pendingWorkerRequests.delete(i.id);else{const e=this.timedOutWorkerRequests.get(i.id);e&&(this.timedOutWorkerRequests.delete(i.id),void 0!==i.skipCode&&this.applyServerDirective(e.sessionId,i.skipCode),this.completeRequest({context:e}))}}else"fetch-request"===i.type&&this.handleDelegatedFetch(s,i).catch(e=>{t.warn("Failed to handle delegated session replay fetch:",e)})},this.worker=s}catch(e){t.error("Failed to create track destination worker, falling back to main-thread sending:",e)}}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}markCoalesceNextFlush(){this.coalesceNextFlush=!0,this.schedule(0)}sendBeacon({events:e,sessionId:t,deviceId:i,apiKey:n,serverZone:s}){var r,o;const a=e=>nt(e);let l=e,c=JSON.stringify({version:2,events:l});if(a(c)>65536){let t=0,i=l.length;for(;t<i;){const e=Math.floor((t+i+1)/2);a(JSON.stringify({version:2,events:l.slice(0,e)}))<=65536?t=e:i=e-1}l=l.slice(0,t),c=JSON.stringify({version:2,events:l}),this.loggerProvider.warn(`sendBeacon payload exceeded 64 KB limit, trimmed from ${e.length} to ${l.length} events`)}if(0===l.length)return;if(this.handleSendEvents){const e=new URLSearchParams({device_id:i,session_id:String(t),type:"replay"}),r=`${qe(s,this.trackServerUrl)}?${e.toString()}`,o={"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${n}`};this.loggerProvider.debug(`Routing session replay exit batch (${l.length} events) through custom transport for session id ${t}.`);try{this.handleSendEvents({url:r,method:"POST",headers:o,body:c,keepalive:!0}).catch(e=>{this.loggerProvider.warn("Custom transport failed to send session replay exit batch:",e)})}catch(e){this.loggerProvider.warn("Custom transport threw while sending session replay exit batch:",e)}return}const d=new URLSearchParams({device_id:i,session_id:String(t),type:"replay",api_key:n}),u=`${qe(s,this.trackServerUrl)}?${d.toString()}`,h=f();try{const e=new Blob([c],{type:"application/json"});!1===(null===(o=null===(r=null==h?void 0:h.navigator)||void 0===r?void 0:r.sendBeacon)||void 0===o?void 0:o.call(r,u,e))&&this.loggerProvider.warn("sendBeacon failed to queue session replay payload")}catch(e){}}addToQueue(...e){e.filter(e=>this.killedSessions.has(e.sessionId)?(this.completeRequest({context:e,err:ft}),!1):e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:gt}),!1)).forEach(e=>{this.queue=this.queue.concat(e),this.schedule(0)})}schedule(e){if(this.scheduled)return;const t=this.flushPauseUntilMs-Date.now(),i=t>e?t:e;t>0&&(this.mergeOnNextFlush=!0),this.scheduled=setTimeout(()=>{this.flush(!0).then(()=>{this.queue.length>0&&this.schedule(e)})},i)}flush(e=!1){return n(this,void 0,void 0,function*(){let t=this.queue;this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),this.mergeOnNextFlush?(this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,t=this.mergeQueueAfterThrottle(t)):this.coalesceNextFlush&&(this.coalesceNextFlush=!1,t=this.mergeDrainBacklog(t));for(const i of t)yield this.send(i,e)})}mergeQueueAfterThrottle(e){const t=this.coalesceByIdentity(e);return t.length<e.length&&!this.mergeLogFiredThisPause&&(this.mergeLogFiredThisPause=!0,this.loggerProvider.log(`Session replay throttle pause ended; merged ${e.length} queued batches into ${t.length} request(s)`)),t}mergeDrainBacklog(e){const t=this.coalesceByIdentity(e);return t.length<e.length&&this.loggerProvider.log(`Session replay coalesced ${e.length} persisted page-load backlog batches into ${t.length} request(s)`),t}coalesceByIdentity(e){var t,i,s,r,o,a,l;if(e.length<=1)return e;const c=new Map;for(const n of e){const e=[n.sessionId,null!==(t=n.deviceId)&&void 0!==t?t:"",null!==(i=n.apiKey)&&void 0!==i?i:"",n.type,null!==(s=n.serverZone)&&void 0!==s?s:"",n.sampleRate,null!==(o=null===(r=n.version)||void 0===r?void 0:r.type)&&void 0!==o?o:"",null!==(l=null===(a=n.version)||void 0===a?void 0:a.version)&&void 0!==l?l:""].join("|"),d=c.get(e);d?d.push(n):c.set(e,[n])}const d=[];for(const e of c.values()){if(1===e.length){d.push(e[0]);continue}let t=null,i=0;const s=()=>{t&&d.push(t),t=null,i=0};for(const r of e){const e=st(r.events);if(null===t){t=Object.assign(Object.assign({},r),{events:[...r.events],attempts:0}),i=e;continue}if(i+e>4e6){s(),t=Object.assign(Object.assign({},r),{events:[...r.events],attempts:0}),i=e;continue}const o=t.onComplete,a=r.onComplete;t.events=t.events.concat(r.events),i+=e,t.onComplete=()=>n(this,void 0,void 0,function*(){yield Promise.allSettled([o(),a()])})}s()}return d}send(e,t=!0){return n(this,void 0,void 0,function*(){if(this.killedSessions.has(e.sessionId))return this.completeRequest({context:e,err:ft});const i=e.apiKey;if(!i)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const n=e.deviceId;if(!n)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const s=this.payloadBatcher({version:1,events:e.events});if(0===s.events.length)return void this.completeRequest({context:e});const{worker:r}=this;return r?this.sendViaWorker(r,e,s,t):this.sendOnMainThread(i,n,e,s,t)})}sendViaWorker(e,t,i,s){return n(this,void 0,void 0,function*(){const n=""+ ++this.sendIdCounter;return new Promise(r=>{var o;const a=this.sendTimeoutMs>0?setTimeout(()=>{const e=this.pendingWorkerRequests.get(n);e&&(this.pendingWorkerRequests.delete(n),this.rememberTimedOutRequest(n,e.context),this.loggerProvider.warn(`Session replay worker send timed out after ${this.sendTimeoutMs}ms; leaving events for retry`),e.resolve())},this.sendTimeoutMs):void 0;this.pendingWorkerRequests.set(n,{context:t,resolve:r,timeout:a}),e.postMessage({type:"send",id:n,payload:i,useRetry:s,useCustomTransport:!!this.handleSendEvents,context:{apiKey:t.apiKey,deviceId:t.deviceId,sessionId:t.sessionId,events:t.events,eventType:t.type,flushMaxRetries:null!==(o=t.flushMaxRetries)&&void 0!==o?o:0,sampleRate:t.sampleRate,serverZone:t.serverZone,trackServerUrl:this.trackServerUrl,version:t.version,currentUrl:Ae(),sdkVersion:pt,enableTransportCompression:this.enableTransportCompression,sendTimeoutMs:this.sendTimeoutMs}})})})}rememberTimedOutRequest(e,t){if(this.timedOutWorkerRequests.set(e,t),this.timedOutWorkerRequests.size>256)for(const e of this.timedOutWorkerRequests.keys()){this.timedOutWorkerRequests.delete(e);break}}handleDelegatedFetch(e,t){var i,s,r;return n(this,void 0,void 0,function*(){const{requestId:n,url:o,method:a,headers:l,body:c,keepalive:d}=t;try{let t;this.handleSendEvents?t=yield this.handleSendEvents({url:o,method:a,headers:l,body:c,keepalive:d}):(this.loggerProvider.warn("Delegated session replay fetch received without a custom transport configured; falling back to built-in fetch."),t=yield fetch(o,{method:a,headers:l,body:c,keepalive:d}));const u=t.status;let h=null,g="";if(u>=200&&u<300&&(h=null!==(r=null===(s=null===(i=t.headers)||void 0===i?void 0:i.get)||void 0===s?void 0:s.call(i,Ie))&&void 0!==r?r:null),413===u)try{g=yield t.text()}catch(e){}this.loggerProvider.debug(`Delegated session replay fetch (request ${n}) returned status ${u}.`),e.postMessage({type:"fetch-response",requestId:n,status:u,skipHeader:h,body:g})}catch(t){this.loggerProvider.debug(`Delegated session replay fetch (request ${n}) failed:`,t),e.postMessage({type:"fetch-response",requestId:n,status:0,skipHeader:null,body:String(t),error:!0})}})}sendOnMainThread(e,t,i,s,r){var o,a,l,c,d,u,h;return n(this,void 0,void 0,function*(){const g=Ae(),v=pt,p=i.sampleRate,m=new URLSearchParams({device_id:t,session_id:`${i.sessionId}`,type:`${i.type}`}),y=`${null!==(a=null===(o=i.version)||void 0===o?void 0:o.type)&&void 0!==a?a:"standalone"}/${null!==(c=null===(l=i.version)||void 0===l?void 0:l.version)&&void 0!==c?c:v}`;try{const t=JSON.stringify(s),o=f(),a=this.enableTransportCompression&&o&&"CompressionStream"in o?yield function(e,t){return n(this,void 0,void 0,function*(){try{const i=new(0,t.CompressionStream)("gzip"),s=i.writable.getWriter(),r=i.readable.getReader(),o=[],a=(()=>n(this,void 0,void 0,function*(){for(;;){const{done:e,value:t}=yield r.read();if(e)break;o.push(t)}}))();yield s.write((new TextEncoder).encode(e)),yield s.close(),yield a;const l=o.reduce((e,t)=>e+t.length,0),c=new Uint8Array(l);let d=0;for(const e of o)c.set(e,d),d+=e.length;return c}catch(e){return null}})}(t,o):null,l=a?a.byteLength:nt(t),c=new AbortController,I=Object.assign({"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${e}`,"X-Client-Version":v,"X-Client-Library":y,"X-Client-Url":g.substring(0,1e3),"X-Client-Sample-Rate":`${p}`,"X-Sampling-Hash-Alg":"xxhash32"},a?{"Content-Encoding":"gzip"}:{}),C=null!=a?a:t,w=l<=65536,E={headers:I,body:C,method:"POST",keepalive:w,signal:c.signal},P=`${qe(i.serverZone,this.trackServerUrl)}?${m.toString()}`;if(0===s.events.length)return void this.completeRequest({context:i});const k=this.sendTimeoutMs>0?setTimeout(()=>{c.abort()},this.sendTimeoutMs):void 0;let M;try{M=this.handleSendEvents?yield(b=this.handleSendEvents({url:P,method:"POST",headers:I,body:C,keepalive:w}),S=c.signal,new Promise((e,t)=>{const i=()=>{const e=new Error("Custom session replay transport aborted by send timeout");e.name="AbortError",t(e)};S.addEventListener("abort",i,{once:!0}),b.then(t=>{S.removeEventListener("abort",i),e(t)},e=>{S.removeEventListener("abort",i),t(e)})})):yield fetch(P,E)}finally{k&&clearTimeout(k)}if(null===M)return void this.completeRequest({context:i,err:"Unexpected error occurred"});if(M.status>=200&&M.status<300){const e=null!==(h=null===(u=null===(d=M.headers)||void 0===d?void 0:d.get)||void 0===u?void 0:u.call(d,Ie))&&void 0!==h?h:null;this.applyServerDirective(i.sessionId,e)}if(r){let e="";if(413===M.status)try{e=yield M.text()}catch(e){}yield this.handleReponse(M.status,i,e)}else{let e="";try{e=JSON.stringify(M.body,null,2)}catch(e){}this.completeRequest({context:i,success:`${M.status}: ${e}`})}}catch(e){!!e&&"object"==typeof e&&"AbortError"===e.name&&r?yield this.handleOtherResponse(i):this.completeRequest({context:i,err:e})}var b,S})}handleReponse(e,t,i=""){return n(this,void 0,void 0,function*(){switch((new W).buildStatus(e)){case h.Success:this.handleSuccessResponse(t);break;case h.Failed:case h.Timeout:case h.RateLimit:yield this.handleOtherResponse(t);break;case h.PayloadTooLarge:this.handlePayloadTooLargeResponse(t,me.test(i));break;default:if(499===e){yield this.handleOtherResponse(t);break}this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}})}handlePayloadTooLargeResponse(e,t){const i=t?"WAF (compressed payload too large)":"server (event too large)",n=Math.round(e.events.reduce((e,t)=>e+t.length,0)/Se);if(!t)return void this.completeRequest({context:e,err:`Session replay event batch dropped: ${i} rejected payload (${e.events.length} events, ${n} KB) — not retrying non-WAF 413`});if(1===e.events.length)return void this.completeRequest({context:e,err:`Session replay event dropped: single event (${n} KB, 1 event) rejected by ${i} — cannot split further`});this.loggerProvider.warn(`Session replay event batch rejected by ${i} (${e.events.length} events, ${n} KB total) — splitting and retrying`),e.onComplete();const s=()=>Promise.resolve(),r=Math.floor(e.events.length/2);this.sendEventsList(Object.assign(Object.assign({},e),{events:e.events.slice(0,r),onComplete:s})),this.sendEventsList(Object.assign(Object.assign({},e),{events:e.events.slice(r),onComplete:s}))}handleSuccessResponse(e){const t=Math.round(st(e.events)/Se);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){return n(this,void 0,void 0,function*(){const t=Math.random()*e.attempts*this.retryTimeout;e.attempts++,e.attempts>(e.flushMaxRetries||0)?this.completeRequest({context:e,err:gt}):(yield new Promise(e=>setTimeout(e,t)),yield this.send(e,!0))})}completeRequest({context:e,err:t,success:i}){e.onComplete(),t?this.loggerProvider.warn(t):i&&this.loggerProvider.log(i)}applyServerDirective(e,t){if(null===t)return this.flushPauseUntilMs=0,void(this.mergeLogFiredThisPause=!1);if("429"===t){const e=this.flushPauseUntilMs>Date.now();return this.flushPauseUntilMs=Date.now()+6e4,void(e||this.loggerProvider.log("Session replay throttled by server; pausing flush schedule for 60s"))}"4005"!==t&&"4004"!==t||this.killSession(e,t)}killSession(e,t){if(this.killedSessions.has(e))return;if(this.killedSessions.add(e),this.killedSessions.size>256)for(const e of this.killedSessions){this.killedSessions.delete(e);break}this.loggerProvider.log(`Session replay capture stopped for session ${e} by server directive ${t}; remaining events will be dropped`);const i=[];for(const t of this.queue)t.sessionId===e?this.completeRequest({context:t,err:ft}):i.push(t);this.queue=i}}class yt{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,i,n;this.minInterval=ye,this.maxInterval=be,this.maxPersistedEventsSize=6e6,this._timeAtLastSplit=Date.now(),this.eventsContentBytes=new WeakMap,this.sequenceContentBytes=new Map,this.shouldSplitEventsList=(e,t)=>{const i=this.getEventsArraySize(e),n=this.maxPersistedEventsSize-i;let s=t.length>=n;return!s&&3*t.length>=n&&(s=nt(t)>=n),!!s||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(i=e.maxInterval)&&void 0!==i?i:this.maxInterval,this.maxPersistedEventsSize=null!==(n=e.maxPersistedEventsSize)&&void 0!==n?n:this.maxPersistedEventsSize,this.interval=this.minInterval}isPrefixOf(e,t){return!(t.length<e.length)&&(0===e.length||t[e.length-1]===e.tail)}measureContentBytes(e,t){if(e&&e.length===t.length&&this.isPrefixOf(e,t))return e;let i=0,n=0;e&&this.isPrefixOf(e,t)&&(i=e.contentBytes,n=e.length);for(let e=n;e<t.length;e++)i+=nt(t[e]);return{length:t.length,contentBytes:i,tail:t.length>0?t[t.length-1]:void 0}}getEventsContentBytes(e){const t=this.measureContentBytes(this.eventsContentBytes.get(e),e);return this.eventsContentBytes.set(e,t),t.contentBytes}getEventsArraySize(e){return this.getEventsContentBytes(e)+(2+Math.max(0,e.length-1)+2*e.length)}recallSequenceContentBytes(e,t){const i=this.sequenceContentBytes.get(e);i&&i.length===t.length&&this.isPrefixOf(i,t)&&this.eventsContentBytes.set(t,i)}rememberSequenceContentBytes(e,t){const i=this.measureContentBytes(this.sequenceContentBytes.get(e),t);this.sequenceContentBytes.set(e,i),this.eventsContentBytes.set(t,i)}forgetSequenceContentBytes(e){this.sequenceContentBytes.delete(e)}}const bt=(e,t,i)=>{var n;"object"==typeof(n=i)&&null!==n&&"AbortError"===n.name?e.debug(t):e.warn(t)};const St="sessionCurrentSequence",It="sequencesToSend",Ct=5e3;function wt(e,t,i){const n=setTimeout(i,t);return e.then(()=>clearTimeout(n),()=>clearTimeout(n)),()=>clearTimeout(n)}const Et=e=>{let t,i;return e.objectStoreNames.contains(St)||(i=e.createObjectStore(St,{keyPath:"sessionId"})),e.objectStoreNames.contains(It)||(t=e.createObjectStore(It,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:i}},Pt=e=>n(void 0,void 0,void 0,function*(){return yield function(e,t,i="IDB operation timed out"){return new Promise((n,s)=>{const r=setTimeout(()=>s(new Error(`${i} after ${t}ms`)),t);e.then(e=>{clearTimeout(r),n(e)},e=>{clearTimeout(r),s(e)})})}(l(e,1,{upgrade:Et}),2e3,"IDB openDB timed out")});class kt extends yt{maybeLogEmptyFiltered(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug(`Filtered empty session replay sequence at ${e} (idb store)`)}constructor(e){var t;super(e),this.consecutiveFailures=0,this.hasTriggeredFallback=!1,this.emptyFilteredCount=0,this.getSequencesToSend=()=>n(this,void 0,void 0,function*(){let e=!1,t=!1;try{const i=[],n=this.db.transaction("sequencesToSend","readwrite");n.done.catch(i=>{e||t||(bt(this.loggerProvider,`${vt}: ${i}`,i),this.recordFailure())});const s=wt(n.done,Ct,()=>{e||t||(t=!0,bt(this.loggerProvider,`${vt}: transaction timed out`),this.recordFailure())});let r=yield n.store.openCursor();for(;r;){const{sessionId:e,events:t}=r.value;0===t.length?(this.maybeLogEmptyFiltered("getSequencesToSend"),yield r.delete()):i.push({events:t,sequenceId:r.key,sessionId:e}),r=yield r.continue()}return this.recordSuccess(),s(),i}catch(i){t||(e=!0,bt(this.loggerProvider,`${vt}: ${i}`,i),this.recordFailure())}}),this.storeCurrentSequence=e=>n(this,void 0,void 0,function*(){let t=!1,i=!1;try{const n=this.db.transaction([St,It],"readwrite");n.done.catch(e=>{t||i||(bt(this.loggerProvider,`${vt}: ${e}`,e),this.recordFailure())});const s=wt(n.done,Ct,()=>{t||i||(i=!0,bt(this.loggerProvider,`${vt}: transaction timed out`),this.recordFailure())}),r=yield n.objectStore(St).get(e);if(!r||r.tabId&&r.tabId!==this.tabId)return void s();if(0===r.events.length)return this.maybeLogEmptyFiltered("storeCurrentSequence"),void s();const o=yield n.objectStore(It).put({sessionId:e,events:r.events,tabId:this.tabId});yield n.objectStore(St).put({sessionId:e,events:[],tabId:this.tabId}),this.rememberSequenceContentBytes(e,[]),this.recordSuccess(),s();const{tabId:l}=r,c=a(r,["tabId"]);return Object.assign(Object.assign({},c),{sessionId:e,sequenceId:o})}catch(n){this.forgetSequenceContentBytes(e),i||(t=!0,bt(this.loggerProvider,`${vt}: ${n}`,n),this.recordFailure())}}),this.addEventToCurrentSequence=(e,t)=>n(this,void 0,void 0,function*(){let i=!1,n=!1;try{const s=this.db.transaction([St,It],"readwrite");s.done.catch(e=>{i||n||(bt(this.loggerProvider,`${vt}: ${e}`,e),this.recordFailure())});const r=wt(s.done,Ct,()=>{i||n||(n=!0,bt(this.loggerProvider,`${vt}: transaction timed out`),this.recordFailure())}),o=yield s.objectStore(St).get(e);if((null==o?void 0:o.tabId)&&o.tabId!==this.tabId){o.events.length>0&&(yield s.objectStore(It).put({sessionId:e,events:o.events,tabId:o.tabId}));const i=[t];return yield s.objectStore(St).put({sessionId:e,events:i,tabId:this.tabId}),this.rememberSequenceContentBytes(e,i),this.recordSuccess(),void r()}const a=o;if(!a){const i=[t];return yield s.objectStore(St).put({sessionId:e,events:i,tabId:this.tabId}),this.rememberSequenceContentBytes(e,i),this.recordSuccess(),void r()}if(this.recallSequenceContentBytes(e,a.events),!this.shouldSplitEventsList(a.events,t)){const i=a.events.concat(t);return yield s.objectStore(St).put({sessionId:e,events:i,tabId:this.tabId}),this.rememberSequenceContentBytes(e,i),this.recordSuccess(),void r()}const l=a.events;if(0===l.length){this.maybeLogEmptyFiltered("addEventToCurrentSequence");const i=[t];return yield s.objectStore(St).put({sessionId:e,events:i,tabId:this.tabId}),this.rememberSequenceContentBytes(e,i),this.recordSuccess(),void r()}const c=[t];yield s.objectStore(St).put({sessionId:e,events:c,tabId:this.tabId}),this.rememberSequenceContentBytes(e,c);const d=yield s.objectStore(It).put({sessionId:e,events:l,tabId:this.tabId});return this.recordSuccess(),r(),{events:l,sessionId:e,sequenceId:d}}catch(t){this.forgetSequenceContentBytes(e),n||(i=!0,bt(this.loggerProvider,`${vt}: ${t}`,t),this.recordFailure())}}),this.storeSendingEvents=(e,t)=>n(this,void 0,void 0,function*(){try{const i=yield this.db.put(It,{sessionId:e,events:t,tabId:this.tabId});return this.recordSuccess(),i}catch(e){bt(this.loggerProvider,`${vt}: ${e}`,e),this.recordFailure()}}),this.cleanUpSessionEventsStore=(e,t)=>n(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(It,t),this.recordSuccess()}catch(e){bt(this.loggerProvider,`${vt}: ${e}`,e),this.recordFailure()}}),this.db=e.db,this.tabId=e.tabId,this.onPersistentFailure=e.onPersistentFailure,this.consecutiveFailureThreshold=null!==(t=e.consecutiveFailureThreshold)&&void 0!==t?t:1}recordFailure(){var e;this.consecutiveFailures++,!this.hasTriggeredFallback&&this.consecutiveFailures>=this.consecutiveFailureThreshold&&(this.hasTriggeredFallback=!0,null===(e=this.onPersistentFailure)||void 0===e||e.call(this))}recordSuccess(){this.consecutiveFailures=0}static new(e,t){var i;return n(this,void 0,void 0,function*(){try{const n="replay"===e?"":`_${e}`,s=`${t.apiKey.substring(0,10)}_amp_session_replay_events${n}`,r=yield Pt(s),o=null!==(i=t.tabId)&&void 0!==i?i:function(){try{return crypto.randomUUID()}catch(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}();return new kt(Object.assign(Object.assign({},t),{db:r,tabId:o}))}catch(e){bt(t.loggerProvider,`${vt}: ${e}`,e)}})}getCurrentSequenceEvents(e){return n(this,void 0,void 0,function*(){if(e){const t=yield this.db.get("sessionCurrentSequence",e);if(!t)return;if(t.tabId&&t.tabId!==this.tabId)return;return[a(t,["tabId"])]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence")){if(e.tabId&&e.tabId!==this.tabId)continue;const i=a(e,["tabId"]);t.push(i)}return t})}}class Mt extends yt{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0,this.emptyFilteredCount=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,i=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:i},this.resetCurrentSequence(e),{sequenceId:t,events:i,sessionId:e}}maybeLogEmptyFiltered(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug(`Filtered empty session replay sequence at ${e} (in-memory store)`)}getSequencesToSend(){return n(this,void 0,void 0,function*(){const e=[];for(const[t,{sessionId:i,events:n}]of Object.entries(this.finalizedSequences))0!==n.length?e.push({sequenceId:Number(t),sessionId:i,events:n}):(this.maybeLogEmptyFiltered("getSequencesToSend"),delete this.finalizedSequences[Number(t)]);return e})}storeCurrentSequence(e){return n(this,void 0,void 0,function*(){const t=this.sequences[e];if(t){if(0!==t.length)return this.addSequence(e);this.maybeLogEmptyFiltered("storeCurrentSequence")}})}addEventToCurrentSequence(e,t){return n(this,void 0,void 0,function*(){let i;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(0===this.sequences[e].length?this.maybeLogEmptyFiltered("addEventToCurrentSequence"):i=this.addSequence(e)),this.sequences[e].push(t),i})}storeSendingEvents(e,t){return n(this,void 0,void 0,function*(){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},this.sequenceId++})}cleanUpSessionEventsStore(e,t){return n(this,void 0,void 0,function*(){void 0!==t&&delete this.finalizedSequences[t]})}}const Ot=({config:e,minInterval:t,maxInterval:i,maxPersistedEventsSize:s,type:r,payloadBatcher:o,storeType:a,trackDestinationWorkerScript:l,shouldSend:c})=>n(void 0,void 0,void 0,function*(){var d;const u=null!==(d=e.maxSingleEventSizeBytes)&&void 0!==d?d:pe,h=new mt(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:o,workerScript:l})),g=()=>new Mt({loggerProvider:e.loggerProvider,maxInterval:i,minInterval:t,maxPersistedEventsSize:s});let v,f,p=!1;f="idb"===a?yield n(void 0,void 0,void 0,function*(){const o=yield kt.new(r,{loggerProvider:e.loggerProvider,minInterval:t,maxInterval:i,maxPersistedEventsSize:s,apiKey:e.apiKey,onPersistentFailure:()=>{n(void 0,void 0,void 0,function*(){if(!p)return;p=!1,e.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store.");const t=v?yield f.getSequencesToSend():void 0;if(f=g(),t&&v){const e=v;t.forEach(t=>{S({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}})}});return o?(p=!0,o):(e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),g())}):g();const m=[];let y=0;const b=e=>{if(e<=y)return;const t=Math.min(e-y,m.length);t>0&&(m.splice(0,t),y=e)},S=({events:t,sessionId:i,deviceId:s,sequenceId:o})=>{let a=t;const l=[];for(let e=0;e<t.length;e++){const i=rt(t[e],u);void 0!==i?(0===l.length&&(a=t.slice(0,e)),l.push(i)):a!==t&&a.push(t[e])}l.length>0&&e.loggerProvider.warn(`Dropping ${l.length} oversized event(s) from session replay sequence before send. Sizes: ${l.map(e=>`${Math.round(e/1024)} KB`).join(", ")}. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.`),0!==a.length?(e.debugMode&&$e().then(({totalStorageSize:t,percentOfQuota:i,usageDetails:n})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${i}%, usage details: ${n}`)}).catch(()=>{}),h.sendEventsList({events:a,sessionId:i,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:s,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:r,onComplete:()=>n(void 0,void 0,void 0,function*(){yield f.cleanUpSessionEventsStore(i,o)})})):f.cleanUpSessionEventsStore(i,o).catch(t=>{e.loggerProvider.warn("Failed to clean up session replay events store:",t)})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:i})=>{if(v=i,c&&!c())return;const n=y+m.length;f.storeCurrentSequence(t).then(e=>{e&&(b(n),S({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i}))}).catch(t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)})},addEvent:({event:t,sessionId:i,deviceId:n})=>{v=n;const s=!c||c(),r=y+m.length;m.push(t.data),f.addEventToCurrentSequence(i,t.data).then(t=>{if(t){if(!s)return f.cleanUpSessionEventsStore(t.sessionId,t.sequenceId).catch(t=>{e.loggerProvider.warn("Failed to clean up dropped session replay sequence:",t)}),void b(r);b(r),S({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:n})}}).catch(t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)})},sendStoredEvents:({deviceId:t})=>n(void 0,void 0,void 0,function*(){v=t;const i=yield f.getSequencesToSend();(null==i?void 0:i.length)&&(e.loggerProvider.log(`Draining ${i.length} stored sequence(s) from previous session.`),i.length>1&&h.markCoalesceNextFlush(),i.forEach(e=>{S({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:t})}))}),flush:function(e=!1){return n(this,void 0,void 0,function*(){return h.flush(e)})},getBeaconEvents:()=>[...m],dropPendingBeaconEvents:()=>{b(y+m.length)},trackDestination:h}});class Tt{constructor(...e){const t=new Map;e.forEach(e=>{t.set(e.name,e.manager)}),this.managers=t}sendStoredEvents(e){return n(this,void 0,void 0,function*(){const t=[];this.managers.forEach(i=>{t.push(i.sendStoredEvents(e))}),yield Promise.all(t)})}addEvent({sessionId:e,event:t,deviceId:i}){var n;null===(n=this.managers.get(t.type))||void 0===n||n.addEvent({sessionId:e,event:t,deviceId:i})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach(i=>{i.sendCurrentSequenceEvents({sessionId:e,deviceId:t})})}flush(e){return n(this,void 0,void 0,function*(){const t=[];this.managers.forEach(i=>{t.push(i.flush(e))}),yield Promise.all(t)})}}let Ft,Rt,xt;function _t(e,t){if(xt=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const i={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};Ft=Object.assign(Object.assign({},i),t),Rt=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Ft.root,i);let n=Lt(e,"all",()=>Lt(e,"two",()=>Lt(e,"one",()=>Lt(e,"none"))));if(n){const t=Zt(Xt(n,e));return t.length>0&&(n=t[0]),At(n)}throw new Error("Selector was not found.")}function Lt(e,t,i){let n=null,s=[],r=e,o=0;for(;r;){const e=(new Date).getTime()-xt.getTime();if(void 0!==Ft.timeoutMs&&e>Ft.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Gt(jt(r))||Gt(...Nt(r))||Gt(...Ut(r))||Gt(Bt(r))||[Wt()];const l=zt(r);if("all"==t)l&&(a=a.concat(a.filter(Kt).map(e=>Ht(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(Kt).map(e=>Ht(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&Kt(e)&&(a=[Ht(e,l)])}else"none"==t&&(a=[Wt()],l&&(a=[Ht(a[0],l)]));for(let e of a)e.level=o;if(s.push(a),s.length>=Ft.seedMinLength&&(n=qt(s,i),n))break;r=r.parentElement,o++}return n||(n=qt(s,i)),!n&&i?i():n}function qt(e,t){const i=Zt(Jt(e));if(i.length>Ft.threshold)return t?t():null;for(let e of i)if($t(e))return e;return null}function At(e){let t=e[0],i=t.name;for(let n=1;n<e.length;n++){const s=e[n].level||0;i=t.level===s-1?`${e[n].name} > ${i}`:`${e[n].name} ${i}`,t=e[n]}return i}function Dt(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function $t(e){const t=At(e);switch(Rt.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function jt(e){const t=e.getAttribute("id");return t&&Ft.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function Nt(e){const t=Array.from(e.attributes).filter(e=>Ft.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function Ut(e){return Array.from(e.classList).filter(Ft.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function Bt(e){const t=e.tagName.toLowerCase();return Ft.tagName(t)?{name:t,penalty:2}:null}function Wt(){return{name:"*",penalty:3}}function zt(e){const t=e.parentNode;if(!t)return null;let i=t.firstChild;if(!i)return null;let n=0;for(;i&&(i.nodeType===Node.ELEMENT_NODE&&n++,i!==e);)i=i.nextSibling;return n}function Ht(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function Kt(e){return"html"!==e.name&&!e.name.startsWith("#")}function Gt(...e){const t=e.filter(Qt);return t.length>0?t:null}function Qt(e){return null!=e}function*Jt(e,t=[]){if(e.length>0)for(let i of e[0])yield*Jt(e.slice(1,e.length),t.concat(i));else yield t}function Zt(e){return[...e].sort((e,t)=>Dt(e)-Dt(t))}function*Xt(e,t,i={counter:0,visited:new Map}){if(e.length>2&&e.length>Ft.optimizedMinLength)for(let n=1;n<e.length-1;n++){if(i.counter>Ft.maxNumberOfTries)return;i.counter+=1;const s=[...e];s.splice(n,1);const r=At(s);if(i.visited.has(r))return;$t(s)&&Vt(s,t)&&(yield s,i.visited.set(r,!0),yield*Xt(s,t,i))}}function Vt(e,t){return Rt.querySelector(At(e))===t}const Yt=({version:e,events:t})=>{const i=[];return t.forEach(e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&i.push(t)}),{version:e,events:i}},ei=({version:e,events:t})=>{const i=[];t.forEach(e=>{const t=JSON.parse(e);"click"===t.type&&i.push(t)});const n=i.reduce((e,t)=>{const{x:i,y:n,selector:s,timestamp:r}=t,o=r-r%36e5,a=`${i}:${n}:${null!=s?s:""}:${o}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:o,count:1}),e},{});return{version:e,events:Object.values(n)}};class ti{constructor(e,t){this.createHook=({eventsManager:e,sessionId:t,deviceIdFn:i,mirror:n,ugcFilterRules:s,performanceOptions:r})=>o=>{if(o.type!==Je.Click)return;const a=f();if(!a)return;const{location:l,innerHeight:c,innerWidth:d}=a;if(!l)return;const{x:u,y:h}=o;if(void 0===u||void 0===h)return;const g=n.getNode(o.id);let v;if(g)try{v=_t(g,r)}catch(e){this.logger.debug("error resolving selector from finder")}const p=De(l.href,s),m={x:u+this.scrollWatcher.currentScrollX,y:h+this.scrollWatcher.currentScrollY,selector:v,viewportHeight:c,viewportWidth:d,pageUrl:p,timestamp:Date.now(),type:"click"},y=i();y&&e.addEvent({sessionId:t,event:{type:"interaction",data:JSON.stringify(m)},deviceId:y})},this.logger=e,this.scrollWatcher=t}}function ii(){const e=f();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function ni(){const e=f();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}class si{constructor(e,t){const i=f();i&&i.navigator&&"function"==typeof i.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(i.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const i=new XMLHttpRequest;return i.open("POST",e,!0),i.setRequestHeader("Accept","*/*"),i.send(JSON.stringify(t)),!0},this.basePageUrl=qe(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e,this.handleSendEvents=t.handleSendEvents,this.loggerProvider=t.loggerProvider}send(e,t){var i;const{sessionId:n,type:s}=this.context;if(this.handleSendEvents){const r=new URLSearchParams({device_id:e,session_id:String(n),type:String(s)}),o=`${this.basePageUrl}?${r.toString()}`,a={"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${this.apiKey}`};try{this.handleSendEvents({url:o,method:"POST",headers:a,body:JSON.stringify(t),keepalive:!0}).catch(e=>{var t;null===(t=this.loggerProvider)||void 0===t||t.warn("Custom transport failed to send session replay interaction beacon:",e)})}catch(e){null===(i=this.loggerProvider)||void 0===i||i.warn("Custom transport threw while sending session replay interaction beacon:",e)}return}const r=new URLSearchParams({device_id:e,session_id:String(n),type:String(s),api_key:this.apiKey}),o=`${this.basePageUrl}?${r.toString()}`;this.sendBeacon(o,t)||this.sendXhr(o,t)}}class ri{static default(e,t){return new ri(new si(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var i,n,s,r;const o=e(),a=f();if(a&&o){const e=null!==(i=a.scrollX)&&void 0!==i?i:0,t=null!==(n=a.scrollY)&&void 0!==n?n:0;(e>0||t>0)&&this.update({id:1,x:e,y:t}),this.transport.send(o,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:ii(),viewportWidth:ni(),pageUrl:De(a.location.href,null!==(r=null===(s=this.config.interactionConfig)||void 0===s?void 0:s.ugcFilterRules)&&void 0!==r?r:[]),timestamp:this.timestamp,type:"scroll"}]})}},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=ni(),this._maxScrollHeight=ii(),this.config=t,this.transport=e}get maxScrollX(){return this._maxScrollX}get maxScrollY(){return this._maxScrollY}get maxScrollWidth(){return this._maxScrollWidth}get maxScrollHeight(){return this._maxScrollHeight}get currentScrollX(){return this._currentScrollX}get currentScrollY(){return this._currentScrollY}update(e){const t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){const i=ni();this._maxScrollX=e.x;const n=e.x+i;n>this._maxScrollWidth&&(this._maxScrollWidth=n),this.timestamp=t}if(e.y>this._maxScrollY){const i=ii();this._maxScrollY=e.y;const n=e.y+i;n>this._maxScrollHeight&&(this._maxScrollHeight=n),this.timestamp=t}}}class oi{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const ai=864e5,li=e=>`AMP_SR_START_${e.substring(0,10)}_`,ci=(e,t)=>`${li(e)}${t}`,di=()=>{try{const e=f();return null==e?void 0:e.localStorage}catch(e){return}};const ui=new class{constructor(){this.dbs={},this.createStore=e=>n(this,void 0,void 0,function*(){return yield l(e,1,{upgrade:e=>{e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})}),this.openOrCreateDB=e=>n(this,void 0,void 0,function*(){if(this.dbs&&this.dbs[e])return this.dbs[e];const t=`${e.substring(0,10)}_amp_session_replay_targeting`,i=yield this.createStore(t);return this.dbs[e]=i,i}),this.getTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:i})=>n(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),n=String(i),s=yield e.get("sessionTargetingMatch",n);return null==s?void 0:s.targetingMatch}catch(t){bt(e,`Failed to get targeting match for session id ${i}: ${t}`,t)}}),this.storeTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:i,targetingMatch:s})=>n(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),n=String(i);return yield e.put("sessionTargetingMatch",{targetingMatch:s,sessionId:n,lastUpdated:Date.now()})}catch(t){bt(e,`Failed to store targeting match for session id ${i}: ${t}`,t)}}),this.clearStoreOfOldSessions=({loggerProvider:e,apiKey:t,currentSessionId:i})=>n(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),n=String(i),s=e.transaction("sessionTargetingMatch","readwrite"),r=yield s.store.getAll();for(let e=0;e<r.length;e++){const t=r[e],i=Date.now()-t.lastUpdated;t.sessionId!==n&&i>1728e5&&(yield s.store.delete(t.sessionId))}yield s.done}catch(t){bt(e,`Failed to clear old targeting matches for sessions: ${t}`,t)}})}},hi=2654435761,gi=2246822519,vi=3266489917,fi=374761393;function pi(e,t){return(e<<t|e>>>32-t)>>>0}function mi(e,t){return e=pi(e=e+Math.imul(t,gi)>>>0,13),e=Math.imul(e,hi)>>>0}function yi(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function bi(e,t=0){const i=function(e){const t=[];for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);if(n>=55296&&n<=56319&&i+1<e.length){const t=e.charCodeAt(i+1);t>=56320&&t<=57343&&(n=t-56320+(n-55296<<10)+65536,i++)}n<128?t.push(n):n<2048?t.push(192|n>>6,128|63&n):n<65536?t.push(224|n>>12,128|n>>6&63,128|63&n):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return new Uint8Array(t)}(e),n=i.length;let s,r=0;if(n>=16){let e=t+hi+gi>>>0,o=t+gi>>>0,a=t>>>0,l=t-hi>>>0;for(;r<=n-16;)e=mi(e,yi(i,r)),r+=4,o=mi(o,yi(i,r)),r+=4,a=mi(a,yi(i,r)),r+=4,l=mi(l,yi(i,r)),r+=4;s=pi(e,1)+pi(o,7)+pi(a,12)+pi(l,18)>>>0}else s=t+fi>>>0;for(s=s+n>>>0;r<=n-4;)s=s+Math.imul(yi(i,r),vi)>>>0,s=Math.imul(pi(s,17),668265263)>>>0,r+=4;for(;r<n;)s=s+Math.imul(i[r],fi)>>>0,s=Math.imul(pi(s,11),hi)>>>0,r++;return s^=s>>>15,s=Math.imul(s,gi)>>>0,s^=s>>>13,s=Math.imul(s,vi)>>>0,s^=s>>>16,s>>>0}const Si="__amplitude_url_tracking_patched__",Ii=new WeakMap;function Ci(e,t,i={}){if(!(null==e?void 0:e.location))return()=>{};const{enablePolling:n=!1,pollingInterval:s=ue}=i;if(n){const i=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""};let n=i();const r=e.setInterval(()=>{const e=i();e!==n&&(n=e,t(e))},s);return()=>{null!=r&&e.clearInterval(r)}}let r=Ii.get(e);if(!r){let t;const i=new Set,n=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""},s=()=>{const e=n();void 0!==t&&e===t||(t=e,i.forEach(t=>t(e)))},o=e=>{const t=function(...t){const i=e.apply(this,t);return s(),i};return t[Si]=!0,t},a=e.history;if(null==a?void 0:a.pushState){const e=Reflect.get(a,"pushState");e[Si]||(a.pushState=o(e))}if(null==a?void 0:a.replaceState){const e=Reflect.get(a,"replaceState");e[Si]||(a.replaceState=o(e))}r={callbacks:i,notify:s,onPopStateOrHashChange:()=>s(),listenersAttached:!1},Ii.set(e,r)}const o=r;return o.listenersAttached||(e.addEventListener("popstate",o.onPopStateOrHashChange),e.addEventListener("hashchange",o.onPopStateOrHashChange),o.listenersAttached=!0),o.callbacks.add(t),()=>{o.callbacks.delete(t),0===o.callbacks.size&&o.listenersAttached&&(e.removeEventListener("popstate",o.onPopStateOrHashChange),e.removeEventListener("hashchange",o.onPopStateOrHashChange),o.listenersAttached=!1)}}function wi(e={}){return{name:"amplitude/url-tracking@1",observer(t,i,n){var s,r,o;const a=Object.assign(Object.assign({},e),n),l=a.ugcFilterRules||[],c=null!==(s=a.enablePolling)&&void 0!==s&&s,d=null!==(r=a.pollingInterval)&&void 0!==r?r:ue,u=null!==(o=a.captureDocumentTitle)&&void 0!==o&&o;if(!i)return()=>{};let h;const g=()=>i.location&&i.location.href||"",v=()=>{const e=g();if(void 0===h||e!==h){h=e;const n=(()=>{const{innerHeight:e,innerWidth:t,document:n}=i,s=g();let r="";return u&&(r=(null==n?void 0:n.title)||""),{href:l.length>0?De(s,l):s,title:r,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(n)}},f=Ci(i,()=>v(),c?{enablePolling:!0,pollingInterval:d}:{});return v(),()=>f()},options:e}}class Ei{constructor(){this.pendingLoadListeners=new Map}start(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect();f()&&(this.sendToAllIframes({type:Ce,action:"start"}),this.mutationObserver=new MutationObserver(e=>{for(const t of e){for(const e of Array.from(t.addedNodes))e instanceof HTMLIFrameElement?this.sendToIframeAfterLoad(e):e instanceof Element&&e.querySelectorAll("iframe").forEach(e=>{this.sendToIframeAfterLoad(e)});for(const e of Array.from(t.removedNodes))if(e instanceof HTMLIFrameElement){const t=this.pendingLoadListeners.get(e);t&&(e.removeEventListener("load",t),this.pendingLoadListeners.delete(e))}}}),this.mutationObserver.observe(document.documentElement,{childList:!0,subtree:!0}))}stop(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),this.mutationObserver=void 0,this.pendingLoadListeners.forEach((e,t)=>{t.removeEventListener("load",e)}),this.pendingLoadListeners.clear(),this.sendToAllIframes({type:Ce,action:"stop"})}sendToIframeAfterLoad(e){const t=()=>{this.pendingLoadListeners.delete(e),this.sendToIframe(e,{type:Ce,action:"start"})};this.pendingLoadListeners.set(e,t),e.addEventListener("load",t,{once:!0})}sendToAllIframes(e){document.querySelectorAll("iframe").forEach(t=>this.sendToIframe(t,e))}sendToIframe(e,t){var i;try{null===(i=e.contentWindow)||void 0===i||i.postMessage(t,"*")}catch(e){}}}class Pi{constructor(){this.focusLeftWindow=!1}noteBlur(){this.focusLeftWindow=!1,this.cancelFocusDestinationCheck();const e=f();this.scheduleFocusInspect(e,()=>{var t;const i=null===(t=null==e?void 0:e.document)||void 0===t?void 0:t.activeElement;"IFRAME"!==(null==i?void 0:i.tagName)?(this.releaseFocusedFrame(),this.focusLeftWindow=!0):this.watchFocusedFrame(i)})}onDocumentHidden(){this.releaseFocusedFrame()}onDocumentVisible(){this.focusLeftWindow=!1,this.cancelFocusDestinationCheck(),this.releaseFocusedFrame()}consumeArrivedFromOutside(){var e,t;const i=this.focusLeftWindow&&"visible"===(null===(t=null===(e=f())||void 0===e?void 0:e.document)||void 0===t?void 0:t.visibilityState);return this.focusLeftWindow=!1,this.releaseFocusedFrame(),i}stop(){this.focusLeftWindow=!1,this.cancelFocusDestinationCheck(),this.releaseFocusedFrame()}noteFrameBlur(){this.cancelFocusDestinationCheck();const e=f();this.scheduleFocusInspect(e,()=>{var t;const i=null===(t=null==e?void 0:e.document)||void 0===t?void 0:t.activeElement,n=null==e?void 0:e.document;if("function"==typeof(null==n?void 0:n.hasFocus)&&n.hasFocus()||"IFRAME"!==(null==i?void 0:i.tagName))return void this.releaseFocusedFrame();const s=this.focusHolder(i);s?this.watchFocusedFrame(s):this.focusLeftWindow=!0})}focusHolder(e,t){if(null==t?void 0:t.has(e))return e;const i=null!=t?t:new Set;let n;i.add(e);try{n=e.contentDocument}catch(t){return e}if(null==n)return e;if("function"==typeof n.hasFocus&&n.hasFocus())return e;const s=n.activeElement;return"IFRAME"===(null==s?void 0:s.tagName)?this.focusHolder(s,i):void 0}watchFocusedFrame(e){let t;this.releaseFocusedFrame();const i=()=>{this.noteFrameBlur()};try{if(t=e.contentWindow,null==t||"function"!=typeof t.addEventListener)return;t.addEventListener("blur",i)}catch(e){return}this.focusedFrameWindow=t,this.focusedFrameBlur=i}releaseFocusedFrame(){const e=this.focusedFrameWindow,t=this.focusedFrameBlur;if(this.focusedFrameWindow=void 0,this.focusedFrameBlur=void 0,void 0!==e)try{e.removeEventListener("blur",t)}catch(e){}}scheduleFocusInspect(e,t){const i=()=>{this.focusDestinationFrame=void 0;try{t()}catch(e){this.releaseFocusedFrame()}};"function"!=typeof(null==e?void 0:e.requestAnimationFrame)?i():this.focusDestinationFrame=e.requestAnimationFrame(i)}cancelFocusDestinationCheck(){if(void 0===this.focusDestinationFrame)return;const e=f();"function"==typeof(null==e?void 0:e.cancelAnimationFrame)&&e.cancelAnimationFrame(this.focusDestinationFrame),this.focusDestinationFrame=void 0}}class ki{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.recordFunction=null,this.recordEventsInFlight=!1,this.recordingEnabled=!0,this.recordingGeneration=0,this.startChildRecordingOnSetup=!1,this.pendingEmitEvents=[],this.windowFocus=new Pi,this.currentPageUrl="",this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.crossOriginIframeCoordinator=null,this.crossOriginParentSignalCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=e=>{const t=f();if(t){t.removeEventListener("blur",this.blurListener),t.removeEventListener("focus",this.focusListener),!e&&t.addEventListener("blur",this.blurListener),!e&&t.addEventListener("focus",this.focusListener),t.self&&"onpagehide"in t.self?(t.removeEventListener("pagehide",this.pageLeaveListener),!e&&t.addEventListener("pagehide",this.pageLeaveListener)):(t.removeEventListener("beforeunload",this.pageLeaveListener),!e&&t.addEventListener("beforeunload",this.pageLeaveListener));const i=t.document;(null==i?void 0:i.addEventListener)&&i.removeEventListener&&(i.removeEventListener("visibilitychange",this.visibilityListener),!e&&i.addEventListener("visibilitychange",this.visibilityListener))}},this.blurListener=()=>{this.scheduleHiddenSend(),this.windowFocus.noteBlur()},this.visibilityListener=()=>{var e,t;const i=null===(t=null===(e=f())||void 0===e?void 0:e.document)||void 0===t?void 0:t.visibilityState;if("hidden"===i)return this.windowFocus.onDocumentHidden(),void this.scheduleHiddenSend();"visible"===i&&(this.windowFocus.onDocumentVisible(),this.cancelHiddenSend(),this.captureVisibleTab())},this.focusListener=()=>{var e;if(!this.recordingEnabled)return;if(this.windowFocus.consumeArrivedFromOutside())this.captureVisibleTab();else if(this.recordCancelCallback&&this.recordFunction){if(!1===(null===(e=this.config)||void 0===e?void 0:e.captureFullSnapshotOnFocus))return;try{this.recordFunction.takeFullSnapshot(!0)}catch(e){this.loggerProvider.warn("Failed to take full snapshot on focus:",e)}}else this.recordEventsInFlight||this.recordEvents(!1)},this.pageLeaveListener=e=>{this.cancelHiddenSend(),this.flushPendingReplayEvents(),this.pageLeaveFns.forEach(t=>{t(e)})},this.evaluateTargetingAndCapture=(e,t=!1,i=!1,s=!1)=>n(this,void 0,void 0,function*(){var r,o,a,l,c,d;if(!this.identifiers||!this.identifiers.sessionId||!this.config)return void(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."));if(!this.config.targetingConfig){if(!t)return void this.loggerProvider.log("No targeting config set, skipping initialization/recording for event.");this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}this.lastTargetingParams=e;const h=this.config.targetingConfig;if(h&&!this.sessionTargetingMatch){const t=s?this.latestUrlChangeTargetingEvaluationId:void 0;let i=e.event;i&&Object.values(u).includes(i.event_type)&&(i=void 0);const g=null!==(c=null!==(o=null===(r=e.page)||void 0===r?void 0:r.url)&&void 0!==o?o:null===(l=null===(a=f())||void 0===a?void 0:a.location)||void 0===l?void 0:l.href)&&void 0!==c?c:"",v=null!==(d=e.page)&&void 0!==d?d:""!==g?{url:g}:void 0,p=yield(({sessionId:e,targetingConfig:t,loggerProvider:i,apiKey:s,targetingParams:r,urlChange:o=!1})=>n(void 0,void 0,void 0,function*(){if(yield ui.clearStoreOfOldSessions({loggerProvider:i,apiKey:s,currentSessionId:e}),!0===(yield ui.getTargetingMatchForSession({loggerProvider:i,apiKey:s,sessionId:e}))&&!o)return!0;let n=!0;try{const{evaluateTargeting:o}=yield import("./targeting-min.js").then(function(e){return e.i}),a=Object.assign(Object.assign({},r),{flag:t,sessionId:"string"==typeof e?parseInt(e,10):e,apiKey:s,loggerProvider:i}),l=yield o(a);l&&l.sr_targeting_config&&(n="on"===l.sr_targeting_config.key),ui.storeTargetingMatchForSession({loggerProvider:i,apiKey:s,sessionId:e,targetingMatch:n})}catch(e){const t=e;i.warn(t.message)}return n}))({sessionId:this.identifiers.sessionId,targetingConfig:h,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:i,page:v},urlChange:s});if(s&&void 0!==t&&t!==this.latestUrlChangeTargetingEvaluationId)return void this.loggerProvider.debug(`Ignoring stale URL-change targeting result #${t}; latest is #${this.latestUrlChangeTargetingEvaluationId}.`);this.sessionTargetingMatch=this.sessionTargetingMatch||p,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:i,targetingParams:e},null,2))}t?this.initialize(!0):!i&&this.recordCancelCallback||(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),yield this.recordEvents())}),this.addCustomRRWebEvent=(e,t={},i=!0)=>n(this,void 0,void 0,function*(){try{let n;const s=this.config;if(s&&e!==we.METADATA&&(n={config:je(s),version:pt},i)){const e=yield $e();n=Object.assign(Object.assign({},e),n)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},t),n)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}}),this.stopRecordingEvents=()=>{var e,t,i;try{this.useSemanticAdapter(e=>e.stop()),this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(e=this.networkObservers)||void 0===e||e.stop(),null===(t=this.crossOriginIframeCoordinator)||void 0===t||t.stop(),this.crossOriginIframeCoordinator=null,null===(i=this.crossOriginParentSignalCleanup)||void 0===i||i.call(this),this.crossOriginParentSignalCleanup=null}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new Ee(new O)}init(e,t){return k(this._init(e,t))}setupUrlChangeListener(){var e,t;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);const i=f();if(!(null==i?void 0:i.location))return;const n=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),s=Ci(i,e=>{if(this.currentPageUrl=e,n){const t=++this.latestUrlChangeTargetingEvaluationId;this.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:e}},!1,!1,!0),this.loggerProvider.debug(`Queued URL-change targeting re-evaluation #${t} for ${e}.`)}});this.urlChangeCleanup=()=>{s(),this.urlChangeCleanup=null}}isBelowMinSessionDuration(){var e;const t=null===(e=this.config)||void 0===e?void 0:e.minSessionDurationMs;return void 0!==t&&void 0!==this.sessionStartTime&&Date.now()-this.sessionStartTime<t}getCurrentPageForTargeting(){var e,t;const i=null===(t=null===(e=f())||void 0===e?void 0:e.location)||void 0===t?void 0:t.href;return null!=i?{url:i}:void 0}_init(e,t){var i,s,r,o,a,l,c,d,u,h,g,v,p,m;return n(this,void 0,void 0,function*(){null===(i=this.urlChangeCleanup)||void 0===i||i.call(this),this.useSemanticAdapter(e=>e.stop()),this.semanticAdapter=void 0,this.recordingEnabled=!0,this.startChildRecordingOnSetup=!1,this.loggerProvider=new Ee(t.loggerProvider||new O),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=Ae(),this.identifiers=new oi({sessionId:t.sessionId,deviceId:t.deviceId});const y=Date.now();((e,t,i)=>{const n=di();if(!n)return;const s=li(e);try{const e=[];for(let i=0;i<n.length;i++){const r=n.key(i);if(!r||!r.startsWith(s))continue;const o=n.getItem(r);if(null===o)continue;const a=Number(o);(!Number.isFinite(a)||a<=0||t-a>=ai)&&e.push(r)}for(const t of e)n.removeItem(t)}catch(e){null==i||i.debug(`Failed to prune stale replay start times: ${String(e)}`)}})(e,y,this.loggerProvider),this.sessionStartTime=void 0!==t.sessionId&&null!==(s=((e,t,i,n)=>{const s=di();if(!s)return;const r=ci(e,t);try{const e=s.getItem(r);if(null!==e){const t=Number(e);if(Number.isFinite(t)&&t>0&&t<=i&&i-t<ai)return t}return s.setItem(r,String(i)),i}catch(e){return void(null==n||n.debug(`Failed to read/write replay start time from storage: ${String(e)}`))}})(e,t.sessionId,y,this.loggerProvider))&&void 0!==s?s:y,this.joinedConfigGenerator=yield((e,t)=>n(void 0,void 0,void 0,function*(){const i=new Ue(e,t),n=new Z(e,i.loggerProvider,i.serverZone,t.configServerUrl,t.handleFetchConfig);return new tt(n,i)}))(e,t);const{joinedConfig:b,localConfig:S,remoteConfig:I}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=b,this.setMetadata(t.sessionId,b,S,I,null===(r=t.version)||void 0===r?void 0:r.version,pt,null===(o=t.version)||void 0===o?void 0:o.type),this.pageLeaveFns=[],t.sessionId&&(null===(a=this.config.interactionConfig)||void 0===a?void 0:a.enabled)){const e=ri.default({sessionId:t.sessionId,type:"interaction"},this.config);this.pageLeaveFns=[e.send(this.getDeviceId.bind(this)).bind(e)],this.scrollHook=e.hook.bind(e),this.clickHandler=new ti(this.loggerProvider,e)}const C=[];let w,E,{storeType:P}=this.config;"idb"!==P||(null===(l=f())||void 0===l?void 0:l.indexedDB)||(P="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${P} for event storage.`);const k=f();if(this.config.useWebWorker&&k&&k.Worker){const{compressionScript:e,trackDestinationScript:t}=yield import("./worker-min.js");w=e,E=t}let M;try{M=yield Ot({config:this.config,type:"replay",minInterval:null===(c=this.config.flushIntervalConfig)||void 0===c?void 0:c.minIntervalMs,maxInterval:null===(d=this.config.flushIntervalConfig)||void 0===d?void 0:d.maxIntervalMs,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,storeType:P,trackDestinationWorkerScript:E,shouldSend:()=>!this.isBelowMinSessionDuration()}),this.rrwebEventManager=M,C.push({name:"replay",manager:M})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(u=this.config.interactionConfig)||void 0===u?void 0:u.enabled){const e=this.config.interactionConfig.batch?ei:Yt;try{const t=yield Ot({config:this.config,type:"interaction",minInterval:null!==(h=this.config.interactionConfig.trackEveryNms)&&void 0!==h?h:3e4,maxInterval:6e4,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,payloadBatcher:e,storeType:P,trackDestinationWorkerScript:E});C.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new Tt(...C),this.eventCompressor&&this.eventCompressor.terminate();const T=!0===this.config.eagerFullSnapshotSend?()=>this.sendEvents():void 0;if(this.eventCompressor=new ht(this.eventsManager,this.config,this.getDeviceId(),w,T),this.pendingEmitEvents.length>0){const e=this.pendingEmitEvents.splice(0);for(const{event:t,sessionId:i}of e)this.eventCompressor.enqueueEvent(t,i)}if(this.pageLeaveFns=[...this.pageLeaveFns,()=>{var e;if(!this.config||!(null===(e=this.identifiers)||void 0===e?void 0:e.sessionId)||!M)return;const t=M.getBeaconEvents();if(!t.length)return;const i=this.getDeviceId();i&&(this.isBelowMinSessionDuration()||M.trackDestination.sendBeacon({events:t,sessionId:this.identifiers.sessionId,deviceId:i,apiKey:this.config.apiKey,serverZone:this.config.serverZone}))}],yield this.initializeNetworkObservers(),null===(g=f())||void 0===g?void 0:g.opener){const e=ne();oe(e),e.setup(Object.assign({logger:this.loggerProvider},this.config.serverZone&&{endpoint:Y[this.config.serverZone]}))}this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),yield this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0);(this.config.targetingConfig||(null!==(m=null===(p=null===(v=this.config.privacyConfig)||void 0===v?void 0:v.urlMaskLevels)||void 0===p?void 0:p.length)&&void 0!==m?m:0)>0)&&this.setupUrlChangeListener()})}setSessionId(e,t){return k(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,i){var s,r,o,a,l,c;return n(this,void 0,void 0,function*(){const n=null===(s=this.identifiers)||void 0===s?void 0:s.sessionId,d=this.getDeviceId();if(!(void 0===n||n!==e||void 0!==t&&t!==d||void 0!==(null==i?void 0:i.userProperties)&&0!==Object.keys(i.userProperties).length))return;this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,n&&this.sendEvents(n);const u=n!==e;u&&(null===(o=null===(r=this.config)||void 0===r?void 0:r.semanticCapture)||void 0===o?void 0:o.enabled)&&this.semanticAdapter&&this.useSemanticAdapter(e=>e.stop()),u&&(null===(a=this.rrwebEventManager)||void 0===a||a.dropPendingBeaconEvents());const h=t||this.getDeviceId();if(this.identifiers=new oi({sessionId:e,deviceId:h}),u&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,(null===(l=this.config)||void 0===l?void 0:l.apiKey)&&(((e,t,i,n)=>{const s=di();if(s)try{s.setItem(ci(e,t),String(i))}catch(e){null==n||n.debug(`Failed to write replay start time to storage: ${String(e)}`)}})(this.config.apiKey,e,this.sessionStartTime,this.loggerProvider),void 0!==n&&((e,t,i)=>{const n=di();if(n)try{n.removeItem(ci(e,t))}catch(e){null==i||i.debug(`Failed to remove replay start time from storage: ${String(e)}`)}})(this.config.apiKey,n,this.loggerProvider))),this.joinedConfigGenerator&&n){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig();this.config=e}(null===(c=this.config)||void 0===c?void 0:c.targetingConfig)?yield this.evaluateTargetingAndCapture({userProperties:null==i?void 0:i.userProperties,page:this.getCurrentPageForTargeting()},!1,!0):yield this.recordEvents()})}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const i=this.getShouldRecord();let n={};return i&&(n={[le]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(n[he]=JSON.stringify({appHash:B(e.apiKey).toString()}))),this.addCustomRRWebEvent(we.GET_SR_PROPS,{shouldRecord:i,eventProperties:n},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,n}flushPendingReplayEvents(){var e;null===(e=this.eventCompressor)||void 0===e||e.flushQueue(),this.sendEvents()}scheduleHiddenSend(){var e;if(null===(e=this.eventCompressor)||void 0===e||e.flushQueue(),void 0!==this.hiddenFlushTimer)return;const t=this.hostSetTimeout();this.hiddenFlushTimer=t(()=>{this.hiddenFlushTimer=void 0,this.sendEvents()},0)}cancelHiddenSend(){void 0!==this.hiddenFlushTimer&&(this.hostClearTimeout()(this.hiddenFlushTimer),this.hiddenFlushTimer=void 0)}hostSetTimeout(){const e=f();return"function"==typeof(null==e?void 0:e.setTimeout)?e.setTimeout.bind(e):setTimeout}hostClearTimeout(){const e=f();return"function"==typeof(null==e?void 0:e.clearTimeout)?e.clearTimeout.bind(e):clearTimeout}captureVisibleTab(){var e;if(this.recordingEnabled)if(null===(e=this.eventCompressor)||void 0===e||e.flushQueue(),this.recordCancelCallback&&this.recordFunction){try{this.recordFunction.takeFullSnapshot(!0)}catch(e){this.loggerProvider.warn("Failed to take full snapshot when the tab became visible:",e)}this.sendEvents()}else this.recordEventsInFlight||this.recordEvents(!1)}sendEvents(e){var t,i;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),s=this.getDeviceId();if(this.eventsManager&&n&&s){if(this.isBelowMinSessionDuration()){const e=this.sessionStartTime,t=this.config.minSessionDurationMs;return this.loggerProvider.log(`Session ${n} not sent: duration ${Date.now()-e}ms is below minimum ${t}ms.`),void this.suppressedSendCount++}if(!this.hasEmittedGateDecision&&void 0!==(null===(i=this.config)||void 0===i?void 0:i.minSessionDurationMs)&&this.recordCancelCallback&&this.recordFunction){this.hasEmittedGateDecision=!0;const e=void 0!==this.sessionStartTime?Date.now()-this.sessionStartTime:void 0;this.addCustomRRWebEvent(we.REPLAY_GATE_DECISION,{sessionId:n,suppressedSendCount:this.suppressedSendCount,elapsedMs:e,minSessionDurationMs:this.config.minSessionDurationMs},!1)}this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:s})}}initialize(e=!1){var t;return n(this,void 0,void 0,function*(){if(!(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId))return this.loggerProvider.log("Session is not being recorded due to lack of session id."),Promise.resolve();const i=this.getDeviceId();return i?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:i}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())})}shouldOptOut(){var e,t;let i;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){i=(n=this.config.instanceName,U.getInstance(T(n))).identityStore.getIdentity().optOut}var n;return void 0!==i?i:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.recordingEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured because recording was stopped.`),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;let e=!1,t="",i=!1;if(this.config.targetingConfig)this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,i=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,i=!1);else{(n=this.identifiers.sessionId,s=this.config.sampleRate,bi(n.toString())%1e6/1e6<s)?(e=!0,i=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,i=!1)}var n,s;return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(we.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e;return _e(null===(e=this.config)||void 0===e?void 0:e.privacyConfig)}getMaskTextSelectors(){var e;return Le(null===(e=this.config)||void 0===e?void 0:e.privacyConfig,this.currentPageUrl)}getRecordingPlugins(e){var t,i,s,r,o,a;return n(this,void 0,void 0,function*(){const n=[];try{const e=wi({ugcFilterRules:(null===(i=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===i?void 0:i.ugcFilterRules)||[],enablePolling:(null===(s=this.config)||void 0===s?void 0:s.enableUrlChangePolling)||!1,pollingInterval:null===(r=this.config)||void 0===r?void 0:r.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle});n.push(e)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(null===(a=null==e?void 0:e.console)||void 0===a?void 0:a.enabled)try{const{getRecordConsolePlugin:t}=yield import("./console-plugin-min.js");n.push(t({level:e.console.levels}))}catch(e){this.loggerProvider.warn("Failed to load console plugin:",e)}return n.length>0?n:void 0})}getRecordFunction(){return n(this,void 0,void 0,function*(){if(this.recordFunction)return this.recordFunction;try{const{record:e}=yield import("./rrweb-record-min.js");return this.recordFunction=e,e}catch(e){return this.loggerProvider.warn("Failed to load rrweb-record module:",e),null}})}recordEvents(e=!0){return n(this,void 0,void 0,function*(){if(this.recordEventsInFlight)this.recordEventsPendingShouldLogMetadata=e;else{this.recordEventsInFlight=!0;try{for(yield this._recordEvents(e);null!==this.recordEventsPendingShouldLogMetadata;){const e=this.recordEventsPendingShouldLogMetadata;this.recordEventsPendingShouldLogMetadata=null,yield this._recordEvents(e)}}finally{this.recordEventsInFlight=!1,this.recordEventsPendingShouldLogMetadata=null}}})}shouldAbandonRecordStart(e){return!this.recordingEnabled||e!==this.recordingGeneration}_recordEvents(e=!0){var t,i,s,r,o,a,l,c;return n(this,void 0,void 0,function*(){const n=this.config,d=this.getShouldRecord(),u=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!d||!u||!n)return void(this.semanticAdapter&&this.recordCancelCallback&&this.stopRecordingEvents());this.stopRecordingEvents();const h=this.recordingGeneration,g=yield this.getRecordFunction();if(!g||this.shouldAbandonRecordStart(h))return;if(yield this.initializeNetworkObservers(),this.shouldAbandonRecordStart(h))return;const v=null===(i=n.loggingConfig)||void 0===i?void 0:i.network,p=qe(n.serverZone,n.trackServerUrl),m=[ge,ve,fe,p];null===(s=this.networkObservers)||void 0===s||s.start(e=>{m.some(t=>e.url.startsWith(t))||this.addCustomRRWebEvent(we.FETCH_REQUEST,e)},v);const{interactionConfig:y,loggingConfig:b}=n,S=(null==y?void 0:y.enabled)?{mouseInteraction:this.eventsManager&&(null===(r=this.clickHandler)||void 0===r?void 0:r.createHook({eventsManager:this.eventsManager,sessionId:u,deviceIdFn:this.getDeviceId.bind(this),mirror:g.mirror,ugcFilterRules:null!==(o=y.ugcFilterRules)&&void 0!==o?o:[],performanceOptions:null===(a=n.performanceConfig)||void 0===a?void 0:a.interaction})),scroll:this.scrollHook}:{},I=(null==y?void 0:y.enabled)&&y.ugcFilterRules?y.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${u}.`);try{const t=!!(null===(l=n.crossOriginIframes)||void 0===l?void 0:l.enabled),i=!1!==(null===(c=n.crossOriginIframes)||void 0===c?void 0:c.coordinateChildren),s=t&&function(){try{const e=f();return!!e&&e.parent!==e}catch(e){return!0}}();if(s&&i)return this.crossOriginParentSignalCleanup=function(e){const t=f();if(!t)return()=>{};const i=t.parent;function n(t){if(t.source!==i)return;const n=t.data;(null==n?void 0:n.type)===Ce&&("start"===n.action?e.onStart():"stop"===n.action&&e.onStop())}return t.addEventListener("message",n),()=>t.removeEventListener("message",n)}({onStart:()=>{this.recordingEnabled&&this._recordEventsInChildMode(g,u,n,S)},onStop:()=>{try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping child iframe replay capture: ${t.toString()}`)}}}),void(this.startChildRecordingOnSetup&&(this.startChildRecordingOnSetup=!1,this._recordEventsInChildMode(g,u,n,S)));this.startChildRecordingOnSetup=!1;const r=yield this.getRecordingPlugins(b);if(this.shouldAbandonRecordStart(h))return;this.prepareSemanticCapture(n,u),this.recordCancelCallback=g(Object.assign(Object.assign({},this.buildRRWebRecordOptions(n,S,e=>{if(this.shouldOptOut()||!this.recordingEnabled)return this.loggerProvider.log(this.shouldOptOut()?`Opting session ${u} out of recording due to optOut config.`:`Session Replay capture stopping for ${u}.`),this.stopRecordingEvents(),void this.sendEvents();e.type===Ge.Meta&&(e.data.href=De(e.data.href,I)),this.eventCompressor?this.eventCompressor.enqueueEvent(e,u):this.pendingEmitEvents.push({event:e,sessionId:u}),this.useSemanticAdapter(t=>t.event(e))},"Error while capturing replay: ")),{plugins:r,recordCrossOriginIframes:t})),this.recordCancelCallback&&this.useSemanticAdapter(e=>e.recordingReady()),t&&!s&&i&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new Ei),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(we.DEBUG_INFO),e&&this.addCustomRRWebEvent(we.METADATA,this.metadata)}catch(e){this.useSemanticAdapter(e=>e.stop()),this.loggerProvider.warn("Failed to initialize session replay:",e)}})}useSemanticAdapter(e){const t=this.semanticAdapter;if(t)try{e(t)}catch(e){this.semanticAdapter=void 0,this.loggerProvider.debug("Semantic capture failed:",e);try{t.stop()}catch(e){this.loggerProvider.debug("Semantic capture stop failed:",e)}}}prepareSemanticCapture(e,t){var i;const n=f();if(!(null==n?void 0:n.document))return;const s=e.semanticCapture,r=null==s?void 0:s.createCapture;if(!(null==s?void 0:s.enabled)||"function"!=typeof r)return this.useSemanticAdapter(e=>e.stop()),void this.useSemanticAdapter(e=>e.prepare({enabled:!1},t));if((null===(i=this.semanticAdapter)||void 0===i?void 0:i.createCapture)!==r){this.useSemanticAdapter(e=>e.stop()),this.semanticAdapter=void 0;try{this.semanticAdapter=new Ze(r,{document:n.document,window:n,sdk:`@amplitude/session-replay-browser@${pt}`,getPrivacy:()=>{var e,t;return null!==(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)&&void 0!==t?t:{}},getIdentity:()=>function(e){const t=e.document,i=Ve.get(t);if(i)return i;const n=Object.freeze({tab_id:m(),document_id:m()});let s=n;if(e.top===e)try{const t=e.sessionStorage,i=()=>{var e;try{const i=JSON.parse(null!==(e=t.getItem(Xe))&&void 0!==e?e:"null");if(i&&Ye.test(i.tab_id)&&(null===i.owner||"string"==typeof i.owner))return i}catch(e){}},n=i();null===(null==n?void 0:n.owner)&&(s=Object.freeze(Object.assign(Object.assign({},s),{tab_id:n.tab_id})));const r=e=>{try{t.setItem(Xe,JSON.stringify({tab_id:s.tab_id,owner:e}))}catch(e){}};t.setItem(Xe,JSON.stringify({tab_id:s.tab_id,owner:s.document_id})),e.addEventListener("pagehide",()=>{var e;(null===(e=i())||void 0===e?void 0:e.owner)===s.document_id&&r(null)}),e.addEventListener("pageshow",e=>{e.persisted&&r(s.document_id)})}catch(e){s=n}return Ve.set(t,s),s}(n),getAnalyticsContext:()=>{var e,t;return null!==(t=null===(e=this.config)||void 0===e?void 0:e.semanticAnalyticsContext)&&void 0!==t?t:{present:!1,autocapture:[]}},inlineStylesheet:e.shouldInlineStylesheet,emit:e=>{if(this.recordCancelCallback&&this.recordFunction)try{this.recordFunction.addCustomEvent(`amp-semantic/${e.name}`,e.payload)}catch(e){this.loggerProvider.debug("Error while adding semantic replay capture event:",e)}},onError:e=>this.loggerProvider.debug("Semantic capture error:",e)})}catch(e){return void this.loggerProvider.debug("Semantic capture initialization failed:",e)}}this.useSemanticAdapter(e=>e.prepare(s,t))}buildRRWebRecordOptions(e,t,i,n){const{privacyConfig:s}=e;return Object.assign(Object.assign(Object.assign(Object.assign({emit:i,inlineStylesheet:e.shouldInlineStylesheet,inlineImages:e.inlineImages,hooks:t},function(e,t){return void 0===t&&(t=function(){return""}),{maskAllInputs:!0,maskTextClass:"amp-mask",blockClass:"amp-block",blockSelector:_e(e),maskTextSelector:Le(e,t()),maskInputFn:Re("input",e,t),maskTextFn:Re("text",e,t),maskAttributeFn:xe(e,t)}}(s,()=>this.currentPageUrl)),{applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements}),void 0!==e.fullSnapshotIntervalMs&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn(n,t.toString()),!0}})}_recordEventsInChildMode(e,t,i,n){try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,this.recordCancelCallback=e(Object.assign(Object.assign({},this.buildRRWebRecordOptions(i,n,()=>{},"Error while capturing replay (child iframe): ")),{recordCrossOriginIframes:!0})),this.loggerProvider.log(`Session Replay child iframe capture beginning for session ${t}.`)}catch(e){this.loggerProvider.warn("Failed to initialize session replay in child iframe mode:",e)}}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}start(){return k(this._start())}_start(){return n(this,void 0,void 0,function*(){this.recordingEnabled=!0,this.startChildRecordingOnSetup=!0,yield this.recordEvents()})}stop(){this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,this.cancelHiddenSend(),this.windowFocus.stop(),this.stopRecordingEvents(),this.sendEvents()}flush(e=!1){var t;return n(this,void 0,void 0,function*(){return null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)})}shutdown(){var e,t;this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,this.cancelHiddenSend(),this.windowFocus.stop(),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()}mapSDKType(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null}setMetadata(e,t,i,n,s,r,o){const a=(null==e?void 0:e.toString())?B(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:i,remoteConfig:n,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(o),replaySDKVersion:s,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:r}}initializeNetworkObservers(){var e,t,i;return n(this,void 0,void 0,function*(){if((null===(i=null===(t=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===t?void 0:t.network)||void 0===i?void 0:i.enabled)&&!this.networkObservers)try{const{NetworkObservers:e}=yield import("./observers-min.js");this.networkObservers=new e}catch(e){this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",e)}})}}const Mi=e=>()=>{const{config:t}=e,{loggerProvider:i,logLevel:n}=t||Ne();return{logger:i,logLevel:n}};var Oi=(()=>{const e=new ki;return{init:L(e.init.bind(e),"init",Mi(e)),evaluateTargetingAndCapture:L(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Mi(e)),setSessionId:L(e.setSessionId.bind(e),"setSessionId",Mi(e)),getSessionId:L(e.getSessionId.bind(e),"getSessionId",Mi(e)),getSessionReplayProperties:L(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Mi(e)),flush:L(e.flush.bind(e),"flush",Mi(e)),start:L(e.start.bind(e),"start",Mi(e)),stop:L(e.stop.bind(e),"stop",Mi(e)),shutdown:L(e.shutdown.bind(e),"shutdown",Mi(e))}})();const{init:Ti,setSessionId:Fi,getSessionId:Ri,getSessionReplayProperties:xi,flush:_i,start:Li,stop:qi,shutdown:Ai,evaluateTargetingAndCapture:Di}=Oi;export{Ee as S,Ri as a,xi as b,Li as c,qi as d,Ai as e,_i as f,f as g,Di as h,Ti as i,Fi as s,ot as t};
|
|
2
2
|
//# sourceMappingURL=index-min.js.map
|